DataModule.pm 16 KB

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