From 0c4ab535867f4d6955354dcca5bd96a7c51dfa3f Mon Sep 17 00:00:00 2001 From: Lucas Date: Sun, 5 Mar 2023 17:23:13 +0000 Subject: [PATCH] api: add /media and /media/:media_id --- lib/PoorBooru/API/V0.pm | 3 ++ lib/PoorBooru/API/V0/Controller/Media.pm | 62 ++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 lib/PoorBooru/API/V0/Controller/Media.pm diff --git a/lib/PoorBooru/API/V0.pm b/lib/PoorBooru/API/V0.pm index 656a3db..69f22bd 100644 --- a/lib/PoorBooru/API/V0.pm +++ b/lib/PoorBooru/API/V0.pm @@ -25,6 +25,9 @@ sub startup ($self) $r->get("/tags")->to("tags#list"); $r->get("/tag/:tag_id_or_name")->to("tags#show"); + $r->get("/media")->to("media#list"); + $r->get("/media/:media_id")->to("media#show"); + $r->get("/random/tag")->to("random#tag"); } diff --git a/lib/PoorBooru/API/V0/Controller/Media.pm b/lib/PoorBooru/API/V0/Controller/Media.pm new file mode 100644 index 0000000..05dcaa1 --- /dev/null +++ b/lib/PoorBooru/API/V0/Controller/Media.pm @@ -0,0 +1,62 @@ +package PoorBooru::API::V0::Controller::Media; +use v5.36; +use strict; +use warnings; + +use Mojo::Base "Mojolicious::Controller"; + +my $MEDIA_SEARCH_OPTS = { + order_by => { -desc => "media_id" }, + rows => 5, +}; + +sub _pager_links ($c, $pager) +{ + +{ map +( $_ => ($pager->$_ and + $c->url_with->query({page => $pager->$_})) ), + qw(first_page previous_page current_page next_page last_page) } +} + +sub list ($self) +{ + my $v = $self->validation; + my $page = $v->optional("page")->num(1, undef)->param // 1; + + return $self->render( + json => {error => "Invalid page number"}, + status => 400, + ) if $v->has_error; + + my $paged_media = $self->schema->resultset("Media") + ->search({}, $MEDIA_SEARCH_OPTS)->page($page); + my @media = map +{ + media_id => $_->media_id, + seaweedfs_fid => $_->seaweedfs_fid, + }, $paged_media->all; + + return $self->render(json => { + pager => _pager_links($self, $paged_media->pager), + media => \@media, + }); +}; + +sub show ($self) +{ + my $media_id = $self->stash("media_id"); + my $media = $self->schema->resultset("Media") + ->single({ media_id => $media_id }); + + return $self->render( + json => {error => "Media not found"}, + status => 404, + ) if !defined($media); + + return $self->render(json => { + id => $media->media_id, + name => $media->filename, + download => $media->seaweedfs_fid, + content_type => $media->content_type, + }); +}; + +1;