api: add /media and /media/:media_id

This commit is contained in:
Lucas 2023-03-05 17:23:13 +00:00
parent 8655e5fa04
commit 0c4ab53586
2 changed files with 65 additions and 0 deletions

View File

@ -25,6 +25,9 @@ sub startup ($self)
$r->get("/tags")->to("tags#list"); $r->get("/tags")->to("tags#list");
$r->get("/tag/:tag_id_or_name")->to("tags#show"); $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"); $r->get("/random/tag")->to("random#tag");
} }

View File

@ -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;