DataModule.pm 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. package Trog::DataModule;
  2. use strict;
  3. use warnings;
  4. use UUID::Tiny;
  5. use List::Util;
  6. use File::Copy;
  7. use Mojo::File;
  8. no warnings 'experimental';
  9. use feature qw{signatures};
  10. =head1 QUERY FORMAT
  11. The $query_language and $query_help variables are presented to the user as to how to use the search box in the tCMS header.
  12. =head1 POST STRUCTURE
  13. Posts generally need to have the following:
  14. data: Brief description of content, or the content itself.
  15. content_type: What this content actually is. Used to filter into the appropriate pages.
  16. href: Primary link. This is the subject of a news post, or a link to the item itself. Can be local or remote.
  17. local_href: Backup link. Automatically created link to a static cache of the content.
  18. title: Title of the content. Used as link name for the 'href' attribute.
  19. user: User was banned for this post
  20. id: Internal identifier in datastore for the post.
  21. tags: array ref of appropriate tags.
  22. created: timestamp of creation of this version of the post
  23. version: revision # of this post.
  24. =head1 CONSTRUCTOR
  25. =head2 new(Config::Simple $config)
  26. Try not to do expensive things here.
  27. =cut
  28. sub new ($class, $config) {
  29. $config = $config->vars();
  30. return bless($config, $class);
  31. }
  32. #It is required that subclasses implement this
  33. sub lang ($self) { ... }
  34. sub help ($self) { ... }
  35. sub read ($self,$query={}) { ... }
  36. sub write ($self) { ... }
  37. sub count ($self) { ... }
  38. =head1 METHODS
  39. =head2 get(%request)
  40. Queries the data model. Should return the following:
  41. id => Filter down to just the post by ID. May be subsequently filtered by ACL, resulting in a 404 (which is good, as it does not disclose info).
  42. version => if id is passed, return the provided post version rather than the most recent one
  43. tags => ARRAYREF of tags, any one of which is required to give a result. If none are passed, no filtering is performed.
  44. acls => ARRAYREF of acl tags, any one of which is required to give result. Filter applies after tags. 'admin' ACL being present skips this filter.
  45. page => Offset multiplier for pagination.
  46. limit => Offset for pagination.
  47. like => Search query, as might be passed in the search bar.
  48. author => filter by post author
  49. If it is more efficient to filter within your data storage engine, you probably should override this method.
  50. As implemented, this takes the data as a given and filters in post.
  51. =cut
  52. sub get ($self, %request) {
  53. my $posts = $self->read(\%request);
  54. my @filtered = $self->filter(\%request, @$posts);
  55. @filtered = $self->_fixup(@filtered);
  56. @filtered = $self->paginate(\%request,@filtered);
  57. return @filtered;
  58. }
  59. sub _fixup ($self, @filtered) {
  60. @filtered = _add_media_type(@filtered);
  61. # urlencode spaces in filenames
  62. @filtered = map {
  63. my $subj = $_;
  64. foreach my $param (qw{href preview video_href audio_href local_href wallpaper}) {
  65. next unless exists $subj->{$param};
  66. $subj->{$param} =~ s/ /%20/g;
  67. }
  68. #XXX Add dynamic routing data for posts which don't have them (/posts/$id) and (/users/$user)
  69. my $is_user_page = grep { $_ eq 'about' } @{$subj->{tags}};
  70. if (!exists $subj->{local_href}) {
  71. $subj->{local_href} = "/posts/$subj->{id}";
  72. $subj->{local_href} = "/users/$subj->{title}" if $is_user_page;
  73. }
  74. if (!exists $subj->{callback}) {
  75. $subj->{callback} = "Trog::Routes::HTML::posts";
  76. $subj->{callback} = "Trog::Routes::HTML::users" if $is_user_page;
  77. }
  78. $subj->{method} = 'GET' unless exists($subj->{method});
  79. $subj
  80. } @filtered;
  81. return @filtered;
  82. }
  83. sub filter ($self, $query, @filtered) {
  84. $query->{acls} //= [];
  85. $query->{tags} //=[];
  86. $query->{exclude_tags} //= [];
  87. # If an ID is passed, just get that (and all it's prior versions)
  88. if ($query->{id}) {
  89. @filtered = grep { $_->{id} eq $query->{id} } @filtered;
  90. @filtered = _dedup_versions($query->{version}, @filtered);
  91. return @filtered;
  92. }
  93. # XXX aclname and id are essentially serving the same purpose, should unify
  94. if ($query->{aclname}) {
  95. @filtered = grep { ($_->{aclname} || '') eq $query->{aclname} } @filtered;
  96. @filtered = _dedup_versions($query->{version}, @filtered);
  97. return @filtered;
  98. }
  99. @filtered = _dedup_versions(undef, @filtered);
  100. #Filter out posts which are too old
  101. #Coerce older into numeric
  102. $query->{older} =~ s/[^0-9]//g if $query->{older};
  103. @filtered = grep { $_->{created} < $query->{older} } @filtered if $query->{older};
  104. # Filter posts not matching the passed tag(s), if any
  105. @filtered = grep {
  106. my $tags = $_->{tags};
  107. grep { my $t = $_; grep { $t eq $_ } @{$query->{tags}} } @$tags
  108. } @filtered if @{$query->{tags}};
  109. # Filter posts *matching* the passed exclude_tag(s), if any
  110. @filtered = grep {
  111. my $tags = $_->{tags};
  112. !grep { my $t = $_; grep { $t eq $_ } @{$query->{exclude_tags}} } @$tags
  113. } @filtered if @{$query->{exclude_tags}};
  114. # Filter posts without the proper ACLs
  115. @filtered = grep {
  116. my $tags = $_->{tags};
  117. grep { my $t = $_; grep { $t eq $_ } @{$query->{acls}} } @$tags
  118. } @filtered unless grep { $_ eq 'admin' } @{$query->{acls}};
  119. @filtered = grep { $_->{title} =~ m/\Q$query->{like}\E/i || $_->{data} =~ m/\Q$query->{like}\E/i } @filtered if $query->{like};
  120. @filtered = grep { $_->{user} eq $query->{author} } @filtered if $query->{author};
  121. return @filtered;
  122. }
  123. sub paginate ($self, $query, @filtered) {
  124. my $offset = int($query->{limit} // 25);
  125. $offset = @filtered < $offset ? @filtered : $offset;
  126. @filtered = splice(@filtered, ( int($query->{page}) -1) * $offset, $offset) if $query->{page} && $query->{limit};
  127. return @filtered;
  128. }
  129. sub _dedup_versions ($version=-1, @posts) {
  130. #ASSUMPTION made here - if we pass version this is direct ID query
  131. if (defined $version) {
  132. my $version_max = List::Util::max(map { $_->{version} } @posts);
  133. return map {
  134. $_->{version_max} //= $version_max;
  135. $_
  136. } grep { $_->{version} eq $version } @posts;
  137. }
  138. my @uniqids = List::Util::uniq(map { $_->{id} } @posts);
  139. my %posts_deduped;
  140. for my $id (@uniqids) {
  141. my @ofid = sort { $b->{version} <=> $a->{version} } grep { $_->{id} eq $id } @posts;
  142. my $version_max = List::Util::max(map { $_->{version } } @ofid);
  143. $posts_deduped{$id} = $ofid[0];
  144. $posts_deduped{$id}{version_max} = $version_max;
  145. }
  146. my @deduped = @posts_deduped{@uniqids};
  147. return @deduped;
  148. }
  149. sub _add_media_type (@posts) {
  150. return map {
  151. my $post = $_;
  152. $post->{content_type} //= '';
  153. $post->{is_video} = 1 if $post->{content_type} =~ m/^video\//;
  154. $post->{is_audio} = 1 if $post->{content_type} =~ m/^audio\//;
  155. $post->{is_image} = 1 if $post->{content_type} =~ m/^image\//;
  156. $post->{is_profile} = 1 if grep {$_ eq 'about' } @{$post->{tags}};
  157. $post
  158. } @posts;
  159. }
  160. =head2 count() = INT $num
  161. Returns the total number of posts.
  162. Used to determine paginator parameters.
  163. =cut
  164. =head2 add(@posts) = BOOL $failed_or_not
  165. Add the provided posts to the datastore.
  166. If any post already exists with the same id, a new post with a version higher than it will be added.
  167. Passes an array of new posts to add to the data store module's write() function.
  168. You probably won't want to override this.
  169. =cut
  170. sub add ($self, @posts) {
  171. my @to_write;
  172. foreach my $post (@posts) {
  173. $post->{id} //= UUID::Tiny::create_uuid_as_string(UUID::Tiny::UUID_V1, UUID::Tiny::UUID_NS_DNS);
  174. $post->{local_href} //= "/posts/$post->{id}";
  175. $post->{method} //= 'GET';
  176. $post->{created} = time();
  177. my @existing_posts = $self->get( id => $post->{id} );
  178. if (@existing_posts) {
  179. my $existing_post = $existing_posts[0];
  180. $post->{version} = $existing_post->{version};
  181. $post->{version}++;
  182. }
  183. $post->{version} //= 0;
  184. $post = _process($post);
  185. push @to_write, $post;
  186. }
  187. $self->write(\@to_write);
  188. #hup the parent to refresh the routing table
  189. my $parent = getppid;
  190. kill 'HUP', $parent;
  191. return 0;
  192. }
  193. #XXX this level of post-processing seems gross, but may be unavoidable
  194. # Not actually a subprocess, kek
  195. sub _process ($post) {
  196. $post->{href} = _handle_upload($post->{file}, $post->{id}) if $post->{file};
  197. $post->{preview} = _handle_upload($post->{preview_file}, $post->{id}) if $post->{preview_file};
  198. $post->{wallpaper} = _handle_upload($post->{wallpaper_file}, $post->{id}) if $post->{wallpaper_file};
  199. $post->{preview} = $post->{href} if $post->{app} && $post->{app} eq 'image';
  200. delete $post->{app};
  201. delete $post->{file};
  202. delete $post->{preview_file};
  203. delete $post->{wallpaper_file};
  204. delete $post->{scheme};
  205. delete $post->{route};
  206. delete $post->{domain};
  207. # Handle acls/tags
  208. $post->{tags} //= [];
  209. @{$post->{tags}} = grep { my $subj = $_; !grep { $_ eq $subj} qw{public private unlisted} } @{$post->{tags}};
  210. push(@{$post->{tags}}, @{$post->{acls}}) if $post->{visibility} eq 'private';
  211. delete $post->{acls};
  212. push(@{$post->{tags}}, $post->{visibility});
  213. # Add the 'series' tag if we are in a series, restrict to relevant acl
  214. if ($post->{series}) {
  215. push(@{$post->{tags}}, 'series');
  216. push(@{$post->{tags}}, $post->{series});
  217. }
  218. #Filter adding the same acl twice
  219. @{$post->{tags}} = List::Util::uniq(@{$post->{tags}});
  220. # Handle multimedia content types
  221. if ($post->{href}) {
  222. my $mf = Mojo::File->new("www/$post->{href}");
  223. my $ext = '.'.$mf->extname();
  224. $post->{content_type} = Plack::MIME->mime_type($ext) if $ext;
  225. }
  226. if ($post->{video_href}) {
  227. my $mf = Mojo::File->new("www/$post->{video_href}");
  228. my $ext = '.'.$mf->extname();
  229. $post->{video_content_type} = Plack::MIME->mime_type($ext) if $ext;
  230. }
  231. if ($post->{audio_href}) {
  232. my $mf = Mojo::File->new("www/$post->{audio_href}");
  233. my $ext = '.'.$mf->extname();
  234. $post->{audio_content_type} = Plack::MIME->mime_type($ext) if $ext;
  235. }
  236. $post->{content_type} ||= 'text/html';
  237. return $post;
  238. }
  239. sub _handle_upload ($file, $uuid) {
  240. my $f = $file->{tempname};
  241. my $newname = "$uuid.$file->{filename}";
  242. File::Copy::move($f, "www/assets/$newname");
  243. return "/assets/$newname";
  244. }
  245. =head2 delete(@posts)
  246. Delete the following posts.
  247. Will remove all versions of said post.
  248. You should override this, it is a stub here.
  249. =cut
  250. sub delete ($self) { die 'stub' }
  251. =head2 routes()
  252. Returns the routes to each post.
  253. You should override this for performance reasons, as it's just a wrapper around get() by defualt.
  254. =cut
  255. sub routes($self) {
  256. my %routes = map { $_->{local_href} => { method => $_->{method}, callback => \&{$_->{callback}} } } ($self->get( limit => 0, acls => ['admin'] ));
  257. return %routes;
  258. }
  259. 1;