DataModule.pm 13 KB

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