DataModule.pm 15 KB

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