Mastodon-Client-0.017/ 0000775 0001750 0001750 00000000000 13646430665 014372 5 ustar jjatria jjatria Mastodon-Client-0.017/cpanfile 0000644 0001750 0001750 00000002177 13646430665 016103 0 ustar jjatria jjatria requires 'Class::Load', '0.25';
requires 'DateTime', '1.51';
requires 'DateTime::Format::Strptime', '1.73';
requires 'Future', '0.35';
requires 'HTTP::Request::Common', '6.18';
requires 'HTTP::Thin', '0.006';
requires 'IO::Async', '0.66';
requires 'Image::Info', '1.41';
requires 'JSON::MaybeXS', '1.003009';
requires 'List::Util', '1.47';
requires 'Log::Any', '1.049';
requires 'Moo', '2.003002';
requires 'Net::Async::HTTP', '0.41';
requires 'Role::EventEmitter', '0.002';
requires 'Try::Tiny', '0.28';
requires 'Type::Params', '1.000006';
requires 'Types::Common::String', '1.000006';
requires 'Types::Path::Tiny', '0.005';
requires 'Types::Standard', '1.003003';
requires 'URI', '1.71';
on test => sub {
requires 'Plack', '1.0043';
requires 'Test::Pod', '1.51';
requires 'Test::TCP', '2.17';
requires 'Test2::V0', '0.000126';
};
Mastodon-Client-0.017/t/ 0000775 0001750 0001750 00000000000 13646430665 014635 5 ustar jjatria jjatria Mastodon-Client-0.017/t/01_entities.t 0000644 0001750 0001750 00000003063 13646430665 017146 0 ustar jjatria jjatria use Test2::V0;
# Test data uses only minimum arguments for entity constructors
# These were set as required only to aid in automatic detection,
# which makes blind coercion possible
#
my $samples = {
Account => {
acct => 'username',
avatar => 'https://example.tld/image.png',
},
Application => {
website => 'https://website.xyz',
},
Attachment => {
preview_url => 'https://example.tld/image.png',
},
Card => {
description => 'A card',
url => 'https://website.xyz',
},
Context => {
ancestors => [],
descendants => [],
},
Error => {
error => 'An error',
},
Instance => {
uri => 'botsin.space',
},
Mention => {
acct => 'username@instance.xyz',
username => 'tester',
},
Relationship => {
muting => 0,
},
Report => {
action_taken => 0,
},
Results => {
hashtags => [ 'tag '],
},
Tag => {
url => 'https://website.xyz',
}
};
my ($account, $status);
test($_) foreach qw(
Account Instance Application Attachment Card Context
Mention Relationship Report Results Error Tag
);
$samples->{Status} = {
account => $account,
visibility => 'public',
favourites_count => 123,
};
test('Status');
$samples->{Notification} = {
status => $status,
};
test('Notification');
sub test {
my $name = shift;
eval "use Mastodon::Entity::$name";
ok my $e = "Mastodon::Entity::$name"->new($samples->{$name}),
"$name constructor succeeds";
$account = $e if $name eq 'Account';
$status = $e if $name eq 'Status';
isa_ok $e, "Mastodon::Entity::$name";
}
done_testing();
Mastodon-Client-0.017/t/02_entity_coercion.t 0000644 0001750 0001750 00000003257 13646430665 020525 0 ustar jjatria jjatria use Test2::V0;
use Mastodon::Types qw( to_Entity to_Instance );
# Test data uses only minimum arguments for entity constructors
# These were set as required only to aid in automatic detection,
# which makes blind coercion possible
#
my $samples = {
Account => {
acct => 'username',
avatar => 'https://example.tld/image.png',
},
Application => {
website => 'https://website.xyz',
},
Attachment => {
preview_url => 'https://example.tld/image.png',
},
Card => {
description => 'A card',
url => 'https://website.xyz',
},
Context => {
ancestors => [],
descendants => [],
},
Error => {
error => 'An error',
},
Instance => {
uri => 'mastodon.social',
},
Mention => {
acct => 'username@instance.xyz',
username => 'tester',
},
Relationship => {
muting => 0,
},
Report => {
action_taken => 0,
},
Results => {
hashtags => [ 'tag '],
},
Tag => {
url => 'https://website.xyz',
}
};
$samples->{Status} = {
account => $samples->{Account},
visibility => 'public',
favourites_count => 123,
application => $samples->{Application},
media_attachments => [
$samples->{Attachment},
$samples->{Attachment},
],
mentions => [
$samples->{Mention},
$samples->{Mention},
],
};
$samples->{Notification} = {
status => $samples->{Status},
};
foreach my $name (keys %{$samples}) {
ok my $e = to_Entity($samples->{$name}), 'Coercion succeeds';
isa_ok $e, "Mastodon::Entity::$name";
}
ok my $e = to_Instance('mastodon.social'),
'Coercion of instance from string succeeds';
isa_ok $e, 'Mastodon::Entity::Instance';
like $e->uri, qr/https/, 'Instance defaults to HTTPS';
done_testing();
Mastodon-Client-0.017/t/lib/ 0000775 0001750 0001750 00000000000 13646430665 015403 5 ustar jjatria jjatria Mastodon-Client-0.017/t/lib/Plack/ 0000775 0001750 0001750 00000000000 13646430665 016435 5 ustar jjatria jjatria Mastodon-Client-0.017/t/lib/Plack/App/ 0000775 0001750 0001750 00000000000 13646430665 017155 5 ustar jjatria jjatria Mastodon-Client-0.017/t/lib/Plack/App/Mastodon/ 0000775 0001750 0001750 00000000000 13646430665 020741 5 ustar jjatria jjatria Mastodon-Client-0.017/t/lib/Plack/App/Mastodon/MockServer/ 0000775 0001750 0001750 00000000000 13646430665 023021 5 ustar jjatria jjatria Mastodon-Client-0.017/t/lib/Plack/App/Mastodon/MockServer/v1.pm 0000644 0001750 0001750 00000017117 13646430665 023712 0 ustar jjatria jjatria package Plack::App::Mastodon::MockServer::v1;
use strict;
use warnings;
use parent qw( Plack::Component );
use Plack::Util;
use JSON::MaybeXS qw( encode_json );
my $samples = {
Account => {
a => {
acct => 'a',
avatar => 'https://perl.test/path/to/image.png',
avatar_static => 'https://perl.test/path/to/image.png',
created_at => '2017-04-12T11:24:56.416Z',
display_name => 'Ada',
followers_count => 2,
following_count => 1,
header => '/headers/original/missing.png',
header_static => '/headers/original/missing.png',
id => 1,
locked => 0,
note => '',
statuses_count => 2,
url => 'https://perl.test/@a',
username => 'a'
},
b => {
acct => 'b',
avatar => 'https://perl.test/path/to/image.png',
avatar_static => 'https://perl.test/path/to/image.png',
created_at => '2015-04-12T11:24:56.416Z',
display_name => 'Bob',
followers_count => 0,
following_count => 1,
header => '/headers/original/missing.png',
header_static => '/headers/original/missing.png',
id => 2,
locked => 0,
note => '',
statuses_count => 0,
url => 'https://perl.test/@b',
username => 'b'
},
c => {
acct => 'c',
avatar => 'https://perl.test/path/to/image.png',
avatar_static => 'https://perl.test/path/to/image.png',
created_at => '2016-04-12T11:24:56.416Z',
display_name => 'Cid',
followers_count => 1,
following_count => 1,
header => '/headers/original/missing.png',
header_static => '/headers/original/missing.png',
id => 2,
locked => 0,
note => '',
statuses_count => 0,
url => 'https://perl.test/@c',
username => 'c'
},
},
Relationship => {
a => {
b => {
id => 2,
blocking => 0,
followed_by => 1,
following => 0,
muting => 0,
requested => 0
},
c => {
id => 3,
blocking => 0,
followed_by => 1,
following => 1,
muting => 0,
requested => 0
},
},
b => {
a => {
id => 1,
blocking => 0,
followed_by => 0,
following => 1,
muting => 0,
requested => 0
},
c => {
id => 3,
blocking => 0,
followed_by => 0,
following => 0,
muting => 0,
requested => 0
},
},
c => {
a => {
id => 1,
blocking => 0,
followed_by => 1,
following => 1,
muting => 0,
requested => 0
},
b => {
id => 2,
blocking => 0,
followed_by => 0,
following => 0,
muting => 0,
requested => 0
},
},
},
Instance => {
description => 'This is not a real instance',
email => 'admin@perl.test',
title => 'perl.test',
uri => 'https://perl.test'
},
Status => {
a => [
{
id => 100,
uri => 'tag:perl.test,2017-04-17:objectId=100:objectType=Status',
url => 'https://perl.test/@a/100',
reblog => undef,
account => undef, # {Account}{a}
content => '
A #tag
',
mentions => [],
reblogged => undef,
sensitive => 0,
visibility => 'public',
created_at => '2017-04-17T17:32:29.772Z',
favourited => undef,
application => undef,
spoiler_text => '',
reblogs_count => 0,
in_reply_to_id => undef,
favourites_count => 0,
media_attachments => [],
in_reply_to_account_id => undef,
tags => [{
url => 'https://perl.test/tags/tag',
name => 'tag'
}],
},
{
id => 101,
uri => 'tag:perl.test,2017-04-17:objectId=101:objectType=Status',
url => 'https://perl.test/@a/101',
tags => [],
reblog => undef,
content => 'Hello, @c!
',
account => undef, # {Account}{a}
reblogged => undef,
sensitive => 0,
visibility => 'public',
created_at => '2017-04-17T18:23:59.781Z',
favourited => undef,
application => undef,
spoiler_text => '',
reblogs_count => 0,
in_reply_to_id => undef,
favourites_count => 0,
media_attachments => [],
in_reply_to_account_id => undef,
mentions => [{
username => 'c',
acct => 'c',
id => 3,
url => 'https://perl.test/@c'
}],
},
],
},
};
$samples->{Status}{a}[0]{account} = $samples->{Account}{a};
$samples->{Status}{a}[1]{account} = $samples->{Account}{a};
my $routes = {
GET => {
'instance' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json $samples->{Instance} ],
],
'accounts/2' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json $samples->{Account}{b} ],
],
'accounts/verify_credentials' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json $samples->{Account}{a} ],
],
'accounts/1/followers' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [ $samples->{Account}{b}, $samples->{Account}{c} ] ],
],
'accounts/2/followers' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [] ],
],
'accounts/1/following' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [ $samples->{Account}{c} ] ],
],
'accounts/2/following' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [ $samples->{Account}{a} ] ],
],
'accounts/1/statuses' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json $samples->{Status}{a} ],
],
'accounts/2/statuses' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [] ],
],
'accounts/relationships?id[]=2' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [ $samples->{Relationship}{a}{b} ] ],
],
'accounts/relationships?id[]=2&id[]=3' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [
$samples->{Relationship}{a}{b}, $samples->{Relationship}{a}{c}
] ],
],
'accounts/search?q=a' => [
200,
[ 'Content-Type' => 'application/json' ],
[ encode_json [ $samples->{Account}{a} ] ],
],
},
};
sub call {
my ($self, $env) = @_;
my $uri = $env->{REQUEST_URI};
my $endpoint = $uri;
$endpoint =~ s%^/api/v1/%%;
$endpoint =~ s|%5B%5D|[]|g;
my $return = $routes->{$env->{REQUEST_METHOD}}{$endpoint} //
[
404,
[ 'Content-Type' => 'text/plain' ],
[ '' ],
];
return $return;
}
1;
Mastodon-Client-0.017/t/05_authorize.t 0000644 0001750 0001750 00000000657 13646430665 017346 0 ustar jjatria jjatria use Test2::V0;
use Mastodon::Client;
my $client = Mastodon::Client->new();
like dies { $client->authorize; },
qr/cannot authorize client without/i,
'Cannot authorize a client without ID and secret';
$client = Mastodon::Client->new(
client_id => 'id',
client_secret => 'secret',
access_token => 'token',
);
# ok warning { $client->authorize; }, 'Warns if access_token already exists';
done_testing();
Mastodon-Client-0.017/t/10_tcp.t 0000644 0001750 0001750 00000015750 13646430665 016116 0 ustar jjatria jjatria use Test2::V0;
use Test::TCP;
use Mastodon::Client;
use Try::Tiny;
use lib 't/lib';
use Plack::Runner;
use Plack::App::Mastodon::MockServer::v1;
# use Log::Any::Adapter;
# Log::Any::Adapter->set( 'Stderr',
# category => 'Mastodon',
# log_level => 'debug',
# );
my $host = '127.0.0.1';
my $server = try {
Test::TCP->new(
host => $host,
max_wait => 3, # seconds
code => sub {
my $port = shift;
my $runner = Plack::Runner->new;
$runner->parse_options(
'--host' => $host,
'--port' => $port,
'--env' => 'test',
'--server' => 'HTTP::Server::PSGI'
);
$runner->run(Plack::App::Mastodon::MockServer::v1->new->to_app);
}
);
}
catch {
plan skip_all => $_;
};
my $url = "http://$host:" . $server->port;
my $client = Mastodon::Client->new(
instance => $url,
coerce_entities => 1,
);
ok my $instance = $client->fetch_instance, 'fetch_instance succeeds';
isa_ok $instance, 'Mastodon::Entity::Instance';
isa_ok $client->instance, 'Mastodon::Entity::Instance';
# Override internal base URL
$client->instance->{uri} = $url;
# get_account
{
my $response;
ok $response = $client->get_account();
isa_ok $response, 'Mastodon::Entity::Account';
like $response->username, qr/a/i, 'Fetches self';
isa_ok $client->latest_response, 'HTTP::Response';
like $client->account, { acct => $response->acct }, 'Cache self account';
ok $response = $client->get_account(2);
isa_ok $response, 'Mastodon::Entity::Account';
like $response->username, qr/b/i, 'Fetches other';
ok $response = $client->get_account({});
isa_ok $response, 'Mastodon::Entity::Account';
like $response->username, qr/a/i, 'Fetches self';
ok $response = $client->get_account(2, {});
isa_ok $response, 'Mastodon::Entity::Account';
like $response->username, qr/b/i, 'Fetches other';
}
# followers
{
use Mastodon::Types qw( is_Account );
use List::Util qw( all );
my $response;
ok $response = $client->followers(), 'followers()';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 2, 'a has two followers';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/b/i, 'Followed by b';
like $response->[1]->username, qr/c/i, 'Followed by c';
ok $response = $client->followers(2), 'followers(Int)';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 0, 'b has no followers';
ok $response = $client->followers({}), 'followers(HashRef)';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 2, 'a has two followers';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/b/i, 'a followed by b';
like $response->[1]->username, qr/c/i, 'a followed by c';
ok $response = $client->followers(2, {}), 'followers(Int, HashRef)';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 0, 'b has no followers';
}
# following
{
use Mastodon::Types qw( is_Account );
use List::Util qw( all );
my $response;
ok $response = $client->following(), 'following()';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/c/i, 'a follows c';
ok $response = $client->following(2), 'following(Int)';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/a/i, 'b follows a';
ok $response = $client->following({}), 'following(HashRef)';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/c/i, 'a follows c';
ok $response = $client->following(2, {}), 'following(Int, HashRef)';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
like $response->[0]->username, qr/a/i, 'b follows a';
}
# statuses
{
use Mastodon::Types qw( is_Status );
use List::Util qw( all );
my $response;
ok $response = $client->statuses(), 'statuses()';
ref_ok $response, 'ARRAY';
ok( (all { is_Status($_) } @{$response}), 'List of Status');
like $response->[0]->content, qr/#/i, 'Recent status has tag';
like $response->[1]->content, qr/@/i, 'Recent status has mention';
ok $response = $client->statuses(2), 'statuses(Int)';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 0, 'b has no statuses';
ok $response = $client->statuses({}), 'statuses(HashRef)';
ref_ok $response, 'ARRAY';
ok( (all { is_Status($_) } @{$response}), 'List of Status');
like $response->[0]->content, qr/#/i, 'Recent status has tag';
like $response->[1]->content, qr/@/i, 'Recent status has mention';
ok $response = $client->statuses(2, {}), 'statuses(Int, HashRef)';
ref_ok $response, 'ARRAY';
is scalar(@{$response}), 0, 'b has no statuses';
}
# relationships
{
use Mastodon::Types qw( is_Relationship );
use List::Util qw( all );
my $response;
like dies { $client->relationships() },
qr/at least one id number needed/i, 'relationships() dies';
like dies { $client->relationships({}) },
qr/at least one id number needed/i, 'relationships(HashRef) dies';
ok $response = $client->relationships(2), 'relationships(Int)';
ref_ok $response, 'ARRAY';
ok( (all { is_Relationship($_) } @{$response}), 'List of Relationship');
is scalar(@{$response}), 1, 'Requested one relationship';
ok !$response->[0]->following, 'Not followed by b';
ok $response = $client->relationships(2, 3), 'relationships(Int, Int)';
ref_ok $response, 'ARRAY';
ok( (all { is_Relationship($_) } @{$response}), 'List of Relationship');
is scalar(@{$response}), 2, 'Requested two relationships';
ok !$response->[0]->following, 'Not followed by b';
ok $response->[1]->following, 'Followed by c';
ok $response = $client->relationships(2, {}), 'relationships(Int, HashRef)';
ref_ok $response, 'ARRAY';
ok( (all { is_Relationship($_) } @{$response}), 'List of Relationship');
is scalar(@{$response}), 1, 'Requested one relationship';
ok !$response->[0]->following, 'Not followed by b';
}
# search_accounts
{
use Mastodon::Types qw( is_Account );
use List::Util qw( all );
my $response;
like dies { $client->search_accounts() },
qr/wrong number of parameters/i, 'search_accounts() dies';
like dies { $client->search_accounts({}) },
qr/did not pass type constraint/i, 'search_accounts(HashRef) dies';
like dies { $client->search_accounts('a', 'b') },
qr/did not pass type constraint/i, 'search_accounts(Str, Str) dies';
ok $response = $client->search_accounts('a'), 'search_accounts(Str)';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
is scalar(@{$response}), 1, 'Requested one relationship';
like $response->[0]->username, qr/a/, 'Found self';
ok $response = $client->search_accounts('a', {}), 'search_accounts(Str, HashRef)';
ref_ok $response, 'ARRAY';
ok( (all { is_Account($_) } @{$response}), 'List of Account');
is scalar(@{$response}), 1, 'Requested one relationship';
like $response->[0]->username, qr/a/, 'Found self';
}
undef $server;
done_testing();
Mastodon-Client-0.017/t/data_leak.t 0000644 0001750 0001750 00000003201 13646430665 016721 0 ustar jjatria jjatria use Test2::V0;
use Test2::Tools::Spec;
use Mastodon::Client;
# Incorrect use of Type::Params coercions for setting defaults caused
# some methods to leak data across instances. This regression test is
# here to make sure that is never again the case.
describe 'Data leaks' => sub {
tests 'authorization_url' => sub {
my $alpha = Mastodon::Client->new(
instance => 'alpha.botsin.space',
client_id => 'alpha_id',
client_secret => 'alpha_secret',
);
my $beta = Mastodon::Client->new(
instance => 'beta.botsin.space',
client_id => 'beta_id',
client_secret => 'beta_secret',
);
is $alpha->authorization_url->host, $alpha->instance->uri->host;
is $beta->authorization_url->host, $beta->instance->uri->host;
};
tests 'authorization_url' => sub {
my $data;
my $alpha = Mastodon::Client->new(
name => 'alpha',
instance => 'alpha.botsin.space',
);
my $beta = Mastodon::Client->new(
name => 'beta',
instance => 'beta.botsin.space',
);
my $mock = mock 'Mastodon::Client', override => [
post => sub {
( undef, undef, $data ) = @_;
return { client_id => 'id', client_secret => 'secret' };
},
];
$alpha->register;
is $data, {
client_name => $alpha->name,
redirect_uris => $alpha->redirect_uri,
scopes => join( ' ', sort @{ $alpha->scopes } ),
};
$beta->register;
is $data, {
client_name => $beta->name,
redirect_uris => $beta->redirect_uri,
scopes => join( ' ', sort @{ $beta->scopes } ),
};
};
};
done_testing();
Mastodon-Client-0.017/t/Dockerfile 0000644 0001750 0001750 00000000310 13646430665 016617 0 ustar jjatria jjatria FROM perl:5.30-slim
RUN apt-get update && apt-get install --yes \
build-essential openssl zlib1g-dev libssl-dev
COPY cpanfile cpanfile.snapshot ./
RUN cpanm -nq --installdeps .
CMD prove -lvr
Mastodon-Client-0.017/t/00_basic.t 0000644 0001750 0001750 00000001237 13646430665 016403 0 ustar jjatria jjatria use Test2::V0;
use Mastodon::Client;
my $client = Mastodon::Client->new(
instance => 'mastodon.cloud',
name => 'JJ',
client_id => 'id',
client_secret => 'secret',
access_token => 'token',
scopes => [qw( read write )],
);
isa_ok( $client, 'Mastodon::Client' );
is $client->name, 'JJ', 'Correct name';
is $client->scopes, [qw( read write )], 'Correct scopes';
$client = Mastodon::Client->new;
is $client->name, undef, 'Name has no default';
is $client->scopes, ['read'],
'Scopes default to read only';
like $client->instance->uri, qr/mastodon\.social/,
'Instance defaults to mastodon.social';
done_testing();
Mastodon-Client-0.017/t/authorize.t 0000644 0001750 0001750 00000011325 13646430665 017034 0 ustar jjatria jjatria use Test2::V0;
use Test2::Tools::Spec;
use Log::Any::Test;
use Log::Any qw( $log );
use Mastodon::Client;
describe 'authorize' => sub {
before_each 'Clear log' => sub {
$log->clear;
};
describe 'Needs a client_id and client_secret' => sub {
my %params;
case 'No client_id' => sub {
%params = ( client_secret => 'secret' );
};
case 'No client_secret' => sub {
%params = ( client_id => 'id' );
};
case 'Neither' => sub {
%params = ();
};
it 'Dies' => sub {
my $client = Mastodon::Client->new(
%params,
instance => 'botsin.space',
);
ok dies { $client->authorize }, 'It dies';
is $log->msgs, [
{
level => 'critical',
message => match(qr/without client_id and client_secret/),
category => 'Mastodon',
},
], 'Logged dying message';
};
};
describe 'Warnings' => sub {
my ( %client_params, $post_response, $warning );
after_each 'Reset' => sub {
%client_params = ();
undef $post_response;
};
case 'Already authorized' => sub {
%client_params = ( access_token => 'foo' );
$warning = match qr/already authorized/;
};
case 'It receives an error' => sub {
$post_response = {
error => 1,
error_description => 'this is a test'
};
$warning = 'this is a test';
};
it 'Warns' => sub {
my $mock = mock 'Mastodon::Client', override => [
post => sub { return $post_response },
];
my $client = Mastodon::Client->new(
instance => 'botsin.space',
client_id => 'id',
client_secret => 'secret',
%client_params,
);
is $client->authorize, $client, 'Method returns $self';
is $log->msgs, [
{
message => $warning,
level => 'warning',
category => 'Mastodon',
},
], 'Raises expected warning';
};
};
it q{Dies if granted scopes don't match} => sub {
my $client = Mastodon::Client->new(
instance => 'botsin.space',
client_id => 'id',
client_secret => 'secret',
);
my $mock = mock 'Mastodon::Client', override => [
post => sub {
return { scope => $_[2]->{scope} . ' extra' };
},
];
ok dies { $client->authorize }, 'It dies';
is $log->msgs, [
{
message => match(qr/scopes do not match/),
level => 'critical',
category => 'Mastodon',
},
];
};
it 'Sets access token and authorization time' => sub {
my $client = Mastodon::Client->new(
instance => 'botsin.space',
client_id => 'id',
client_secret => 'secret',
);
my $mock = mock 'Mastodon::Client', override => [
post => sub {
return {
scope => $_[2]->{scope},
created_at => '2018-12-16T12:20:40.123Z',
access_token => 'a token',
};
},
];
is $client->authorize, object {
call access_token => 'a token';
call authorized => '2018-12-16T12:20:40';
etc;
}, 'Method sets attributes';
is $log->msgs, [], 'Nothing logged';
};
describe 'Accepts different credentials' => sub {
my ( %check, %params, $data );
before_each 'Clear data' => sub { undef $data };
case 'No params' => sub {
note 'This is legacy behaviour, we should probably die instead';
%params = ();
%check = ( username => '', password => '', grant_type => 'password' );
};
case 'Access code' => sub {
%params = ( access_code => 'access_code' );
%check = ( grant_type => 'authorization_code', code => 'access_code' );
};
case 'Username and password' => sub {
%check = %params = ( username => 'username', password => 'password' );
$check{grant_type} = 'password';
};
it 'Works' => sub {
my $mock = mock 'Mastodon::Client', override => [
post => sub {
( undef, undef, $data ) = @_;
return {
created_at => 1,
scope => $data->{scope} // '',
access_token => 'mocked_token',
};
},
];
my $client = Mastodon::Client->new(
instance => 'botsin.space',
client_id => 'id',
client_secret => 'secret',
);
$client->authorize( %params );
is $data, hash {
field $_ => $check{$_} for keys %check;
field client_id => $client->client_id;
field client_secret => $client->client_secret;
field redirect_uri => T;
field scope => T;
end;
}, 'Posted correct data payload';
is $log->msgs, [], 'Nothing logged';
};
};
};
done_testing();
Mastodon-Client-0.017/t/examples/ 0000775 0001750 0001750 00000000000 13646430665 016453 5 ustar jjatria jjatria Mastodon-Client-0.017/t/examples/public_stream.pl 0000644 0001750 0001750 00000004056 13646430665 021644 0 ustar jjatria jjatria #!/usr/bin/env perl
binmode STDOUT, ':utf8';
use warnings;
use strict;
use diagnostics;
use Term::ANSIColor qw(:constants);
use Mastodon::Client;
use Config::Tiny;
# use Log::Any::Adapter;
# my $log = Log::Any::Adapter->set( 'Stderr',
# category => 'Mastodon',
# log_level => 'debug',
# );
unless (scalar @ARGV) {
print " Missing arguments
USAGE: $0
should be an INI file with a valid 'client_secret', 'client_id', and
'access_token', and an 'instance' key with the URL to a Mastodon instance.\n";
exit(1);
}
my ($configfile, $stream) = @ARGV;
my $config = (defined $configfile)
? Config::Tiny->read( $configfile )->{_} : {};
my $app = Mastodon::Client->new({
%{$config},
coerce_entities => 1,
});
my $listener = $app->stream( $stream // 'public' );
# Counter for statuses
my $n = 0;
$listener->on( update => sub {
my ($listener, $data) = @_;
# Only print 10 first statuses
$listener->stop if ++$n >= 10;
use HTML::FormatText::WithLinks;
my $f = HTML::FormatText::WithLinks->new;
local $Term::ANSIColor::AUTORESET = 1;
my $name = $data->account->display_name;
$name = $data->account->acct if !defined $name or $name eq q{};
if ($data->reblog) {
print BLUE sprintf("%s reblogged a status:\n", $name);
$listener->emit( update => $data->reblog )
}
else {
print BOLD BLUE sprintf("%s:\n", $name);
print $f->parse($data->content);
}
});
$listener->on( delete => sub {
my ($listener, $data) = @_;
print BOLD RED sprintf("Status %s was deleted!\n\n", $data);
});
$listener->on( heartbeat => sub {
my ($listener) = @_;
print BOLD RED " -- THUMP -- \n\n";
});
$listener->on( notification => sub {
my ($listener, $data) = @_;
use Lingua::EN::Inflexion;
my $line = $data->account->acct . ' ' . verb($data->type)->past . ' you';
if ($data->type =~ /(blog|fav)/) {
$line .= 'r status';
}
print BOLD GREEN "$line!\n";
});
$listener->on( error => sub {
my ($listener, $fatal, $message, $data) = @_;
$fatal //= 0;
print BOLD YELLOW "ERROR: $message\n\n";
});
$listener->start;
Mastodon-Client-0.017/t/examples/getter.pl 0000644 0001750 0001750 00000001316 13646430665 020301 0 ustar jjatria jjatria #!/usr/bin/env perl
binmode STDOUT, ':utf8';
use warnings;
use strict;
use diagnostics;
use Mastodon::Client;
use Config::Tiny;
use Log::Any::Adapter;
my $log = Log::Any::Adapter->set( 'Stderr',
category => 'Mastodon',
log_level => 'warn',
);
unless (scalar @ARGV) {
print " Missing arguments
USAGE: $0
should be an INI file with a valid 'client_secret', 'client_id', and
'access_token', and an 'instance' key with the URL to a Mastodon instance.\n";
exit(1);
}
my $config = (scalar @ARGV) ? Config::Tiny->read( $ARGV[0] )->{_} : {};
my $client = Mastodon::Client->new({
%{$config},
coerce_entities => 0,
});
use Data::Dumper;
print Dumper($client->get( $ARGV[1] )), "\n";
Mastodon-Client-0.017/t/author-pod-syntax.t 0000644 0001750 0001750 00000000454 13646430665 020431 0 ustar jjatria jjatria #!perl
BEGIN {
unless ($ENV{AUTHOR_TESTING}) {
print qq{1..0 # SKIP these tests are for testing by the author\n};
exit
}
}
# This file was automatically generated by Dist::Zilla::Plugin::PodSyntaxTests.
use strict; use warnings;
use Test::More;
use Test::Pod 1.41;
all_pod_files_ok();
Mastodon-Client-0.017/META.yml 0000644 0001750 0001750 00000006200 13646430665 015637 0 ustar jjatria jjatria ---
abstract: 'Talk to a Mastodon server'
author:
- 'José Joaquín Atria '
build_requires:
Plack: '1.0043'
Test2::V0: '0.000126'
Test::Pod: '1.51'
Test::TCP: '2.17'
perl: '5.010'
configure_requires:
ExtUtils::MakeMaker: '0'
perl: v5.10.0
dynamic_config: 0
generated_by: 'Dist::Zilla version 6.012, CPAN::Meta::Converter version 2.150010'
license: perl
meta-spec:
url: http://module-build.sourceforge.net/META-spec-v1.4.html
version: '1.4'
name: Mastodon-Client
provides:
Mastodon::Client:
file: lib/Mastodon/Client.pm
version: '0.017'
Mastodon::Entity::Account:
file: lib/Mastodon/Entity/Account.pm
version: '0.017'
Mastodon::Entity::Application:
file: lib/Mastodon/Entity/Application.pm
version: '0.017'
Mastodon::Entity::Attachment:
file: lib/Mastodon/Entity/Attachment.pm
version: '0.017'
Mastodon::Entity::Card:
file: lib/Mastodon/Entity/Card.pm
version: '0.017'
Mastodon::Entity::Context:
file: lib/Mastodon/Entity/Context.pm
version: '0.017'
Mastodon::Entity::Error:
file: lib/Mastodon/Entity/Error.pm
version: '0.017'
Mastodon::Entity::Instance:
file: lib/Mastodon/Entity/Instance.pm
version: '0.017'
Mastodon::Entity::Mention:
file: lib/Mastodon/Entity/Mention.pm
version: '0.017'
Mastodon::Entity::Notification:
file: lib/Mastodon/Entity/Notification.pm
version: '0.017'
Mastodon::Entity::Relationship:
file: lib/Mastodon/Entity/Relationship.pm
version: '0.017'
Mastodon::Entity::Report:
file: lib/Mastodon/Entity/Report.pm
version: '0.017'
Mastodon::Entity::Results:
file: lib/Mastodon/Entity/Results.pm
version: '0.017'
Mastodon::Entity::Status:
file: lib/Mastodon/Entity/Status.pm
version: '0.017'
Mastodon::Entity::Tag:
file: lib/Mastodon/Entity/Tag.pm
version: '0.017'
Mastodon::Listener:
file: lib/Mastodon/Listener.pm
version: '0.017'
Mastodon::Role::Entity:
file: lib/Mastodon/Role/Entity.pm
version: '0.017'
Mastodon::Role::UserAgent:
file: lib/Mastodon/Role/UserAgent.pm
version: '0.017'
Mastodon::Types:
file: lib/Mastodon/Types.pm
version: '0.017'
requires:
Class::Load: '0.25'
DateTime: '1.51'
DateTime::Format::Strptime: '1.73'
Future: '0.35'
HTTP::Request::Common: '6.18'
HTTP::Thin: '0.006'
IO::Async: '0.66'
Image::Info: '1.41'
JSON::MaybeXS: '1.003009'
List::Util: '1.47'
Log::Any: '1.049'
Moo: '2.003002'
Net::Async::HTTP: '0.41'
Role::EventEmitter: '0.002'
Try::Tiny: '0.28'
Type::Params: '1.000006'
Types::Common::String: '1.000006'
Types::Path::Tiny: '0.005'
Types::Standard: '1.003003'
URI: '1.71'
perl: '5.010'
resources:
bugtracker: https://gitlab.com/jjatria/Mastodon-Client/issues
repository: git://gitlab.com/jjatria/Mastodon-Client.git
version: '0.017'
x_contributors:
- 'Al Beano '
- 'Alexander Zaitsev '
- 'Eric Prestemon '
- 'Florian Obser '
- 'Lance Wicks '
- 'Luc Didry '
x_generated_by_perl: v5.30.0
x_serialization_backend: 'YAML::Tiny version 1.73'
Mastodon-Client-0.017/Makefile.PL 0000644 0001750 0001750 00000004532 13646430665 016346 0 ustar jjatria jjatria # This file was automatically generated by Dist::Zilla::Plugin::MakeMaker v6.012.
use strict;
use warnings;
use 5.010;
use ExtUtils::MakeMaker;
my %WriteMakefileArgs = (
"ABSTRACT" => "Talk to a Mastodon server",
"AUTHOR" => "Jos\x{e9} Joaqu\x{ed}n Atria ",
"CONFIGURE_REQUIRES" => {
"ExtUtils::MakeMaker" => 0
},
"DISTNAME" => "Mastodon-Client",
"LICENSE" => "perl",
"MIN_PERL_VERSION" => "5.010",
"NAME" => "Mastodon::Client",
"PREREQ_PM" => {
"Class::Load" => "0.25",
"DateTime" => "1.51",
"DateTime::Format::Strptime" => "1.73",
"Future" => "0.35",
"HTTP::Request::Common" => "6.18",
"HTTP::Thin" => "0.006",
"IO::Async" => "0.66",
"Image::Info" => "1.41",
"JSON::MaybeXS" => "1.003009",
"List::Util" => "1.47",
"Log::Any" => "1.049",
"Moo" => "2.003002",
"Net::Async::HTTP" => "0.41",
"Role::EventEmitter" => "0.002",
"Try::Tiny" => "0.28",
"Type::Params" => "1.000006",
"Types::Common::String" => "1.000006",
"Types::Path::Tiny" => "0.005",
"Types::Standard" => "1.003003",
"URI" => "1.71"
},
"TEST_REQUIRES" => {
"Plack" => "1.0043",
"Test2::V0" => "0.000126",
"Test::Pod" => "1.51",
"Test::TCP" => "2.17"
},
"VERSION" => "0.017",
"test" => {
"TESTS" => "t/*.t"
}
);
my %FallbackPrereqs = (
"Class::Load" => "0.25",
"DateTime" => "1.51",
"DateTime::Format::Strptime" => "1.73",
"Future" => "0.35",
"HTTP::Request::Common" => "6.18",
"HTTP::Thin" => "0.006",
"IO::Async" => "0.66",
"Image::Info" => "1.41",
"JSON::MaybeXS" => "1.003009",
"List::Util" => "1.47",
"Log::Any" => "1.049",
"Moo" => "2.003002",
"Net::Async::HTTP" => "0.41",
"Plack" => "1.0043",
"Role::EventEmitter" => "0.002",
"Test2::V0" => "0.000126",
"Test::Pod" => "1.51",
"Test::TCP" => "2.17",
"Try::Tiny" => "0.28",
"Type::Params" => "1.000006",
"Types::Common::String" => "1.000006",
"Types::Path::Tiny" => "0.005",
"Types::Standard" => "1.003003",
"URI" => "1.71"
);
unless ( eval { ExtUtils::MakeMaker->VERSION(6.63_03) } ) {
delete $WriteMakefileArgs{TEST_REQUIRES};
delete $WriteMakefileArgs{BUILD_REQUIRES};
$WriteMakefileArgs{PREREQ_PM} = \%FallbackPrereqs;
}
delete $WriteMakefileArgs{CONFIGURE_REQUIRES}
unless eval { ExtUtils::MakeMaker->VERSION(6.52) };
WriteMakefile(%WriteMakefileArgs);
Mastodon-Client-0.017/Changes 0000644 0001750 0001750 00000013655 13646430665 015675 0 ustar jjatria jjatria Revision history for Mastodon::Client
0.017 2020-04-17 23:46:11+01:00 Europe/London
* New:
* Added an example script to illustrate the use of Mastodon::Listener.
* Fixes:
* Stream parser in Mastodon::Listener can now handle long messages
that did not fit in a single chunk (thanks Alexander Zaitsev!)
* Corrected the minimum required version of Types::Standard
0.016 2019-10-13 12:23:24+01:00 Europe/London
* New:
* A new 'latest_response' accessor makes it possible to retrieve the
most recent response obtained from the server, to assist in error
handling.
* Add caption and focus settings support to upload_media
(thanks Eric Prestemon!).
* We now ship a cpanfile specifying the distribution's dependencies and
a Dockerfile (in 't') that can be used to run tests in an isolated
environment.
* Changes:
* The default user agent is now an instance of HTTP::Thin instead of
LWP::UserAgent.
* When coercing the Image type from a filename, we now use Path::Tiny's
'slurp_raw' instead of the plain 'slurp'.
* Fixes:
* Fixed an issue with parameter validation closures that meant
having multiple clients would leak data across them.
* Fixed an issue that caused a failure when trying to update the 'scopes'
attribute, which is now read-write (thanks Luc Didry!)
* Fixed an issue caused by a missing coercion for Bool types.
0.015 2018-04-22 02:36:42+01:00 Europe/London
* New:
* Status entities now have a placeholder `emojis` attribute.
This will likely need to be populated with a new entity.
* Changes:
* A successful call to `register` will overwrite the value
of the client's `scopes` attribute to that passed as an
argument (since those are the scopes that were requested
from the server; thanks Shura0!).
* Fixes:
* Fixed an issue with authorisation of clients that used
scopes other than `read` (thanks Shura0!)
* Corrected an error in the documentation that stated that
`register` accepted a hash reference instead of a hash.
* Coercing attachment entities without `remote_url`s no longer
results in an error.
0.014 2018-01-23 19:27:43+00:00 Europe/London
* Changes:
* Allowed warnings in tests because of an open issue with
Net::Async::HTTP
0.013 2018-01-21 22:29:25+00:00 Europe/London
* Changes:
* [internal] Switched from AnyEvent to IO::Async.
* Fixes:
* Fixed a typo in the synopsis that could cause a server error
when run (++Florian Obser).
0.012 2017-06-09 12:58:08+01:00 Europe/London
* Changes:
* Improved documentation, including a section with details about
the OAuth2 process for obtaining IDs, secrets, and tokens
0.011 2017-05-10 15:59:57+01:00 Europe/London
* Fixes:
* Fix an issue with data preparation, which made authentication
impossible (thanks @whiteisthenewblack!)
0.010 2017-05-08 00:15:59+01:00 Europe/London
* Fixes:
* Added AutoPrereq plugin for automatic dependency detection
0.009 2017-05-06 23:50:20+01:00 Europe/London
* New:
* Added tidyall tests
* Changes:
* Switch to JSON::MaybeXS
* Use Class::Load to programmatically load classes
* Improved robustness of stream parsing
* Simplified method to perform requests
* Fixes:
* Fixed syntax errors in POD
* Fixed a missing import in Application entities
* Reblog status method no longer calls DELETE
0.008 2017-04-22 02:45:33+01:00 Europe/London
* New:
* Added documentation for entity and listener objects
* Status and Account objects have some convenience methods
* Changes:
* Re-wrote Mastodon::Listener to use AnyEvent::HTTP
* Added more attributes to Mastodon::Listener, making it more
usable as a standalone class
* Fixes:
* Fixed an issue with entity coercions, that could cause some
tests to fail
* TCP tests are skipped if unable to establish a connection
* Added more missing dependencies
* Never coerce server responses for app registration
0.007 2017-04-18 16:12:15+01:00 Europe/London
* Fixes:
* Corrected list of provided packages (fixed broken release)
* Add readme to distribution
0.006 2017-04-18 02:28:45+01:00 Europe/London
* New:
* Added tests for more methods
* Entity objects have experimental method shortcuts
* Fixes:
* Some of the GET methods did not correctly parse arguments
* Changes:
* The `uri` attribute for Status entities is not of type URI
0.005 2017-04-17 15:20:15+01:00 Europe/London
* Fixes:
* Fixed wrong links in POD
0.004 2017-04-17 15:14:15+01:00 Europe/London
* New:
* Added some tests for GET requests, using Test::TCP
* Added an example script to dump responses to GET requests,
mainly for debug
* Fixes:
* Corrected some inconsistencies in the method signatures
with what was documented
* Do not try to coerce non-entity responses (ie. from OAuth2 flow)
* Respect the value of coerce_entities in more methods
* Changes:
* The `authorized` attribute is now never undefined
0.003 2017-04-17 00:12:15+01:00 Europe/London
* New:
* Added Travis CI configuration
* Fixes:
* Added some missing dependencies to dist.ini
0.002 2017-04-16 23:06:52+01:00 Europe/London
* New:
* Added convenience methods for all API endpoints
* Added a `coerce_entities` option to turn JSON responses from
Mastodon into Perl objects
* Added more tests (suite is still far from complete!)
* Added methods for sending DELETE and PATCH requests
* Added this change log. :)
* Several changes to dist.ini add repository data, META.json, etc.
* Added documentation
* Changes:
* Interface of `timeline()` and `stream()` methods now more
closely mirrors that of the rest of the distribution
* Fixes:
* Fixed several issues with passing arguments to requst functions
0.001
* Initial release
Mastodon-Client-0.017/README.md 0000644 0001750 0001750 00000060015 13646430665 015651 0 ustar jjatria jjatria # NAME
Mastodon::Client - Talk to a Mastodon server
# SYNOPSIS
use Mastodon::Client;
my $client = Mastodon::Client->new(
instance => 'mastodon.social',
name => 'PerlBot',
client_id => $client_id,
client_secret => $client_secret,
access_token => $access_token,
coerce_entities => 1,
);
$client->post_status('Posted to a Mastodon server!');
$client->post_status('And now in secret...',
{ visibility => 'unlisted' }
)
# Streaming interface might change!
my $listener = $client->stream( 'public' );
$listener->on( update => sub {
my ($listener, $status) = @_;
printf "%s said: %s\n",
$status->account->display_name,
$status->content;
});
$listener->start;
# DESCRIPTION
Mastodon::Client lets you talk to a Mastodon server to obtain authentication
credentials, read posts from timelines in both static or streaming mode, and
perform all the other operations exposed by the Mastodon API.
Most of these are available through the convenience methods listed below, which
validate input parameters and are likely to provide more meaningful feedback in
case of errors.
Alternatively, this distribution can be used via the low-level request methods
(**post**, **get**, etc), which allow direct access to the API endpoints. All
other methods call one of these at some point.
# VERSION NOTICE
This distribution currently **only supports version 1 of the Mastodon API**.
Help implementing support for any missing features in version 1, and for the
new features in version 2, would be greatfully appreciated.
# ATTRIBUTES
- **instance**
A Mastodon::Entity::Instance object representing the instance to which this
client will speak. Defaults to `mastodon.social`.
- **api\_version**
An integer specifying the version of the API endpoints to use. Defaults to `1`.
- **redirect\_uri**
The URI to which authorization codes should be forwarded as part of the OAuth2
flow. Defaults to `urn:ietf:wg:oauth:2.0:oob` (meaning no redirection).
- **user\_agent**
The user agent to use for the requests. Defaults to an instance of
[HTTP::Thin](https://metacpan.org/pod/HTTP::Thin). It is expected to have a `request` method that
accepts [HTTP::Request](https://metacpan.org/pod/HTTP::Request) objects.
- **coerce\_entities**
A boolean value. Set to true if you want Mastodon::Client to internally coerce
all response entities to objects. This adds a level of validation, and can
make the objects easier to use.
Although this does require some additional processing, the coercion is done by
[Type::Tiny](https://metacpan.org/pod/Type::Tiny), so the impact is negligible.
For now, it defaults to **false** (but this will likely change, so I recommend
you use it).
- **access\_token**
The access token of your client. This is provided by the Mastodon API and is
used for the OAuth2 authentication required for most API calls.
You can get this by calling **authorize** with either an access code or your
account's username and password.
- **authorized**
Boolean. False is the client has no defined access\_token. When an access token
is set, this is set to true or to a [DateTime](https://metacpan.org/pod/DateTime) object representing the time of
authorization if possible (as received from the server).
- **client\_id**
- **client\_secret**
The client ID and secret are provided by the Mastodon API when you register
your client using the **register** method. They are used to identify where your
calls are coming from, and are required before you can use the **authorize**
method to get the access token.
- **name**
Your client's name. This is required when registering, but is otherwise seldom
used. If you are using the **authorization\_url** to get an access code from your
users, then they will see this name when they go to that page.
- **account**
Holds the authenticated account. It is set internally by the **get\_account**
method.
- **scopes**
This array reference holds the scopes set by you for the client. These are
required when registering your client with the Mastodon instance. Defaults to
`read`.
Mastodon::Client will internally make sure that the scopes you were provided
when calling **authorize** match those that you requested. If this is not the
case, it will helpfully die.
- **website**
The URL of a human-readable website for the client. If made available, it
appears as a link in the "authorized applications" tab of the user preferences
in the default Mastodon web GUI. Defaults to the empty string.
# METHODS
## Authorizing an application
Although not all of the API methods require authentication to be used, most of
them do. The authentication process involves a) registering an application with
a Mastodon server to obtain a client secret and ID; b) authorizing the
application by either providing a user's credentials, or by using an
authentication URL.
The methods facilitating this process are detailed below:
- **register()**
- **register(%data)**
Obtain a client secret and ID from a given mastodon instance. Takes a single
hash as an argument, with the following possible keys:
- **redirect\_uris**
The URL to which authorization codes should be forwarded after authorized by
the user. Defaults to the value of the **redirect\_uri** attribute.
- **scopes**
The scopes requested by this client. Defaults to the value of the **scopes**
attribute.
- **website**
The client's website. Defaults to the value of the `website` attribute.
When successful, sets the `client_secret`, `scopes`, and `client_id`
attributes of the Mastodon::Client object and returns the modified object.
This should be called **once** per client and its contents cached locally.
- **authorization\_url()**
Generate an authorization URL for the given application. Accessing this URL
via a browser by a logged in user will allow that user to grant this
application access to the requested scopes. The scopes used are the ones in the
**scopes** attribute at the time this method is called.
- **authorize()**
- **authorize( %data )**
Grant the application access to the requested scopes for a given user. This
method takes a hash with either an access code or a user's login credentials to
grant authorization. Valid keys are:
- **access\_code**
The access code obtained by visiting the URL generated by **authorization\_url**.
- **username**
- **password**
The user's login credentials.
When successful, the method automatically sets the client's **authorized**
attribute to a true value and caches the **access\_token** for all future calls.
## Error handling
Methods that make requests to the server will `die` whenever an error is
encountered, or the data that was received from the server is not what is
expected. The error string will, when possible, come from the response's
status line, but this will likely not be enough to fully diagnose what
went wrong.
- **latest\_response**
To make this easier, the client will cache the server's response after each
request has been made, and expose it through the `latest_response` accessor.
Note that, as its name implies, _this will only store the most recent
response_.
If called before any request has been made, it will return an undefined
value.
The remaining methods listed here follow the order of those in the official API
documentation.
## Accounts
- **get\_account()**
- **get\_account($id)**
- **get\_account($params)**
- **get\_account($id, $params)**
Fetches an account by ID. If no ID is provided, this defaults to the current
authenticated account. Global GET parameters are available for this method.
Depending on the value of `coerce_entities`, it returns a
Mastodon::Entity::Account object, or a plain hash reference.
- **update\_account($params)**
Make changes to the authenticated account. Takes a hash reference with the
following possible keys:
- **display\_name**
- **note**
Strings
- **avatar**
- **header**
A base64 encoded image, or the name of a file to be encoded.
Depending on the value of `coerce_entities`, returns the modified
Mastodon::Entity::Account object, or a plain hash reference.
- **followers()**
- **followers($id)**
- **followers($params)**
- **followers($id, $params)**
Get the list of followers of an account by ID. If no ID is provided, the one
for the current authenticated account is used. Global GET parameters are
available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
- **following()**
- **following($id)**
- **following($params)**
- **following($id, $params)**
Get the list of accounts followed by the account specified by ID. If no ID is
provided, the one for the current authenticated account is used. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
- **statuses()**
- **statuses($id)**
- **statuses($params)**
- **statuses($id, $params)**
Get a list of statuses from the account specified by ID. If no ID is
provided, the one for the current authenticated account is used.
In addition to the global GET parameters, this method accepts the following
parameters:
- **only\_media**
- **exclude\_replies**
Both boolean.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
- **follow($id)**
- **unfollow($id)**
Follow or unfollow an account specified by ID. The ID argument is mandatory.
Depending on the value of `coerce_entities`, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
- **block($id)**
- **unblock($id)**
Block or unblock an account specified by ID. The ID argument is mandatory.
Depending on the value of `coerce_entities`, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
- **mute($id)**
- **unmute($id)**
Mute or unmute an account specified by ID. The ID argument is mandatory.
Depending on the value of `coerce_entities`, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
- **relationships(@ids)**
- **relationships(@ids, $params)**
Get the list of relationships of the current authenticated user with the
accounts specified by ID. At least one ID is required, but more can be passed
at once. Global GET parameters are available for this method, and can be passed
as an additional hash reference as a final argument.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Relationship objects, or a plain array reference.
- **search\_accounts($query)**
- **search\_accounts($query, $params)**
Search for accounts. Takes a mandatory string argument to use as the search
query. If the search query is of the form `username@domain`, the accounts
will be searched remotely.
In addition to the global GET parameters, this method accepts the following
parameters:
- **limit**
The maximum number of matches. Defaults to 40.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
This method does not require authentication.
## Blocks
- **blocks()**
- **blocks($params)**
Get the list of accounts blocked by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
## Favourites
- **favourites()**
- **favourites($params)**
Get the list of statuses favourited by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
## Follow requests
- **follow\_requests()**
- **follow\_requests($params)**
Get the list of accounts requesting to follow the the authenticated user.
Global GET parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
- **authorize\_follow($id)**
- **reject\_follow($id)**
Accept or reject the follow request by the account of the specified ID. The ID
argument is mandatory.
Returns an empty object.
## Follows
- **remote\_follow($acct)**
Follow a remote user by account string (ie. `username@domain`). The argument
is mandatory.
Depending on the value of `coerce_entities`, returns an
Mastodon::Entity::Account object, or a plain hash reference with the local
representation of the specified account.
## Instances
- **fetch\_instance()**
Fetches the latest information for the current instance the client is talking
to. When successful, this method updates the value of the `instance`
attribute.
Depending on the value of `coerce_entities`, returns an
Mastodon::Entity::Instance object, or a plain hash reference.
This method does not require authentication.
## Media
- **upload\_media($file)**
- **upload\_media($file, $params)**
Upload a file as an attachment. Takes a mandatory argument with the name of a
local file to encode and upload, and an optional hash reference with the
following additional parameters:
- **description**
A plain-text description of the media, for accessibility, as a string.
- **focus**
An array reference of two floating point values, to be used as
the x and y focus values. These inform clients which point in
the image is the most important one to show in a cropped view.
The value of a coordinate is a real number between -1 and +1,
where 0 is the center. x:-1 indicates the left edge of the
image, x:1 the right edge. For the y axis, y:1 is the top edge
and y:-1 is the bottom.
Depending on the value of `coerce_entities`, returns an
Mastodon::Entity::Attachment object, or a plain hash reference.
The returned object's ID can be passed to the **post\_status** to post it to a
timeline.
## Mutes
- **mutes()**
- **mutes($params)**
Get the list of accounts muted by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
## Notifications
- **notifications()**
- **notifications($params)**
Get the list of notifications for the authenticated user. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Notification objects, or a plain array reference.
- **get\_notification($id)**
Get a notification by ID. The argument is mandatory.
Depending on the value of `coerce_entities`, returns an
Mastodon::Entity::Notification object, or a plain hash reference.
- **clear\_notifications()**
Clears all notifications for the authenticated user.
This method takes no arguments and returns an empty object.
## Reports
- **reports()**
- **reports($params)**
Get a list of reports made by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of `coerce_entities`, returns an array reference of
Mastodon::Entity::Report objects, or a plain array reference.
- **report($params)**
Report a user or status. Takes a mandatory hash with the following keys:
- **account\_id**
The ID of a single account to report.
- **status\_ids**
The ID of a single status to report, or an array reference of statuses to
report.
- **comment**
An optional string.
While the comment is always optional, either the **account\_id** or the list of
**status\_ids** must be present.
Depending on the value of `coerce_entities`, returns the new
Mastodon::Entity::Report object, or a plain hash reference.
## Search
- **search($query)**
- **search($query, $params)**
Search for content. Takes a mandatory string argument to use as the search
query. If the search query is a URL, Mastodon will attempt to fetch the
provided account or status. Otherwise, it will do a local account and hashtag
search.
In addition to the global GET parameters, this method accepts the following
parameters:
- **resolve**
Whether to resolve non-local accounts.
## Statuses
- **get\_status($id)**
- **get\_status($id, $params)**
Fetches a status by ID. The ID argument is mandatory. Global GET parameters are available for this method as an additional hash reference.
Depending on the value of `coerce_entities`, it returns a
Mastodon::Entity::Status object, or a plain hash reference.
This method does not require authentication.
- **get\_status\_context($id)**
- **get\_status\_context($id, $params)**
Fetches the context of a status by ID. The ID argument is mandatory. Global GET parameters are available for this method as an additional hash reference.
Depending on the value of `coerce_entities`, it returns a
Mastodon::Entity::Context object, or a plain hash reference.
This method does not require authentication.
- **get\_status\_card($id)**
- **get\_status\_card($id, $params)**
Fetches a card associated to a status by ID. The ID argument is mandatory.
Global GET parameters are available for this method as an additional hash
reference.
Depending on the value of `coerce_entities`, it returns a
Mastodon::Entity::Card object, or a plain hash reference.
This method does not require authentication.
- **get\_status\_reblogs($id)**
- **get\_status\_reblogs($id, $params)**
- **get\_status\_favourites($id)**
- **get\_status\_favourites($id, $params)**
Fetches a list of accounts who have reblogged or favourited a status by ID.
The ID argument is mandatory. Global GET parameters are available for this
method as an additional hash reference.
Depending on the value of `coerce_entities`, it returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
This method does not require authentication.
- **post\_status($text)**
- **post\_status($text, $params)**
Posts a new status. Takes a mandatory string as the content of the status
(which can be the empty string), and an optional hash reference with the
following additional parameters:
- **status**
The content of the status, as a string. Since this is already provided as the
first argument of the method, this is not necessary. But if provided, this
value will overwrite that of the first argument.
- **in\_reply\_to\_id**
The optional ID of a status to reply to.
- **media\_ids**
An array reference of up to four media IDs. These can be obtained as the result
of a call to **upload\_media()**.
- **sensitive**
Boolean, to mark status content as NSFW.
- **spoiler\_text**
A string, to be shown as a warning before the actual content.
- **visibility**
A string; one of `direct`, `private`, `unlisted`, or `public`.
Depending on the value of `coerce_entities`, it returns the new
Mastodon::Entity::Status object, or a plain hash reference.
- **delete\_status($id)**
Delete a status by ID. The ID is mandatory. Returns an empty object.
- **reblog($id)**
- **unreblog($id)**
- **favourite($id)**
- **unfavourite($id)**
Reblog or favourite a status by ID, or revert this action. The ID argument is
mandatory.
Depending on the value of `coerce_entities`, it returns the specified
Mastodon::Entity::Status object, or a plain hash reference.
## Timelines
- **timeline($query)**
- **timeline($query, $params)**
Retrieves a timeline. The first argument defines either the name of a timeline
(which can be one of `home` or `public`), or a hashtag (if it begins with the
`#` character). This argument is mandatory.
In addition to the global GET parameters, this method accepts the following
parameters:
Accessing the public and tag timelines does not require authentication.
- **local**
Boolean. If true, limits results only to those originating from the current
instance. Only applies to public and tag timelines.
Depending on the value of `coerce_entities`, it returns an array of
Mastodon::Entity::Status objects, or a plain array reference. The more recent
statuses come first.
# STREAMING RESULTS
Alternatively, it is possible to use the streaming API to get a constant stream
of updates. To do this, there is the **stream()** method.
- **stream($query)**
Creates a Mastodon::Listener object which will fetch a stream for the
specified query. Possible values for the query are either `user`, for events
that are relevant to the authorized user; `public`, for all public statuses;
or a tag (if it begins with the `#` character), for all public statuses for
the particular tag.
For more details on how to use this object, see the documentation for
[Mastodon::Listener](https://metacpan.org/pod/Mastodon::Listener).
Accessing streaming public timeline does not require authentication.
# REQUEST METHODS
Mastodon::Client uses four lower-level request methods to contact the API
with GET, POST, PATCH, and DELETE requests. These are left available in case
one of the higher-level convenience methods are unsuitable or undesirable, but
you use them at your own risk.
They all take a URL as their first parameter, which can be a string with the
API endpoint to contact, or a [URI](https://metacpan.org/pod/URI) object, which will be used as-is.
If passed as a string, the methods expect one that contains only the variable
parts of the endpoint (ie. not including the `HOST/api/v1` part). The
remaining parts will be filled-in appropriately internally.
- **delete($url)**
- **get($url)**
- **get($url, $params)**
Query parameters can be passed as part of the [URI](https://metacpan.org/pod/URI) object, but it is not
recommended you do so, since Mastodon has expectations for array parameters
that do not meet those of eg. [URI::QueryParam](https://metacpan.org/pod/URI::QueryParam). It will be easier and safer
if any additional parameters are passed as a hash reference, which will be
added to the URL before the request is sent.
- **post($url)**
- **post($url, $data)**
- **patch($url)**
- **patch($url, $data)**
the `post` and `patch` methods work similarly to `get` and `delete`, but
the optional hash reference is sent in as form data, instead of processed as
query parameters. The Mastodon API does not use query parameters on POST or
PATCH endpoints.
# CONTRIBUTIONS AND BUG REPORTS
Contributions of any kind are most welcome!
The main repository for this distribution is on
[GitLab](https://gitlab.com/jjatria/Mastodon-Client), which is where patches
and bug reports are mainly tracked. The repository is also mirrored on
[Github](https://github.com/jjatria/Mastodon-Client), in case that platform
makes it easier to post contributions.
If none of the above is acceptable, bug reports can also be sent through the
CPAN RT system, or by mail directly to the developers at the address below,
although these will not be as closely tracked.
# AUTHOR
- José Joaquín Atria
# CONTRIBUTORS
- Lance Wicks
# COPYRIGHT AND LICENSE
This software is copyright (c) 2017 by José Joaquín Atria.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
Mastodon-Client-0.017/lib/ 0000775 0001750 0001750 00000000000 13646430665 015140 5 ustar jjatria jjatria Mastodon-Client-0.017/lib/Mastodon/ 0000775 0001750 0001750 00000000000 13646430665 016724 5 ustar jjatria jjatria Mastodon-Client-0.017/lib/Mastodon/Client.pm 0000644 0001750 0001750 00000107521 13646430665 020504 0 ustar jjatria jjatria # ABSTRACT: Talk to a Mastodon server
package Mastodon::Client;
use strict;
use warnings;
use v5.10.0;
our $VERSION = '0.017';
use Carp;
use Mastodon::Types qw( Acct Account DateTime Image URI Instance );
use Moo;
use Types::Common::String qw( NonEmptyStr );
use Types::Standard qw(
Any Int Str Bool Undef HashRef ArrayRef Dict Tuple StrictNum
slurpy Maybe Optional
);
use Types::Path::Tiny qw( File );
use Type::Params qw( compile validate );
use Log::Any;
my $log = Log::Any->get_logger(category => 'Mastodon');
with 'Mastodon::Role::UserAgent';
has coerce_entities => (
is => 'rw',
isa => Bool,
lazy => 1,
default => 0,
);
has access_token => (
is => 'rw',
isa => NonEmptyStr,
lazy => 1,
predicate => '_has_access_token',
);
has authorized => (
is => 'rw',
isa => DateTime|Bool,
lazy => 1,
default => sub { $_[0]->_has_access_token },
coerce => 1,
);
has client_id => (
is => 'rw',
isa => NonEmptyStr,
lazy => 1,
);
has client_secret => (
is => 'rw',
isa => NonEmptyStr,
lazy => 1,
);
has name => (
is => 'ro',
isa => NonEmptyStr,
);
has website => (
is => 'ro',
isa => Str,
lazy => 1,
default => q{},
);
has account => (
is => 'rw',
isa => HashRef|Account,
init_arg => undef,
lazy => 1,
default => sub {
$_[0]->get_account;
},
);
has scopes => (
is => 'rw',
isa => ArrayRef->plus_coercions( Str, sub { [ split / /, $_ ] } ),
lazy => 1,
default => sub { [ 'read' ] },
coerce => 1,
);
after access_token => sub {
$_[0]->authorized(1) unless $_[0]->authorized;
};
sub authorize {
my $self = shift;
unless ( $self->client_id and $self->client_secret ) {
croak $log->fatal(
'Cannot authorize client without client_id and client_secret');
}
if ( $self->access_token ) {
$log->warn('Client is already authorized');
return $self;
}
state $check = compile(
slurpy Dict [
access_code => Optional [Str],
username => Optional [Str],
password => Optional [Str],
],
);
my ($params) = $check->(@_);
my $data = {
client_id => $self->client_id,
client_secret => $self->client_secret,
redirect_uri => $self->redirect_uri,
};
if ( $params->{access_code} ) {
$data->{grant_type} = 'authorization_code';
$data->{code} = $params->{access_code};
}
else {
$data->{grant_type} = 'password';
$data->{username} = $params->{username} // '';
$data->{password} = $params->{password} // '';
}
$data->{scope} = join q{ }, sort @{ $self->scopes };
my $response = $self->post( 'oauth/token' => $data );
if ( defined $response->{error} ) {
$log->warn( $response->{error_description} );
}
else {
my $granted_scopes = join q{ }, sort split( / /, $response->{scope} );
my $requested_scopes = join q{ }, sort @{ $self->scopes };
croak $log->fatal('Granted and requested scopes do not match')
if $granted_scopes ne $requested_scopes;
$self->access_token( $response->{access_token} );
$self->authorized( $response->{created_at} );
}
return $self;
}
# Authorize follow requests by account ID
sub authorize_follow {
my $self = shift;
state $check = compile( Int );
my ($id) = $check->(@_);
return $self->post( 'follow_requests/authorize' => { id => $id } );
}
# Clears notifications
sub clear_notifications {
my $self = shift;
state $check = compile();
$check->(@_);
return $self->post( 'notifications/clear' );
}
# Delete a status by ID
sub delete_status {
my $self = shift;
state $check = compile( Int );
my ($id) = $check->(@_);
return $self->delete( "statuses/$id" );
}
sub fetch_instance {
my $self = shift;
# Do not return from the instance attribute, since the user might have
# disabled coercions, and the attribute is always coerced
my $instance = $self->get( 'instance' );
$self->instance($instance);
return $instance;
}
sub get_account {
my $self = shift;
my $own = 'verify_credentials';
state $check = compile( Optional [Int|HashRef], Optional [HashRef] );
my ($id, $params) = $check->(@_);
if (ref $id eq 'HASH') {
$params = $id;
$id = undef;
}
$id //= $own;
$params //= {};
my $data = $self->get( "accounts/$id", $params );
# We fetched authenticated user account's data
# Update local reference
$self->account($data) if ($id eq $own);
return $data;
}
# Get a single notification by ID
sub get_notification {
my $self = shift;
state $check = compile( Int, Optional [HashRef] );
my ($id, $params) = $check->(@_);
return $self->get( "notifications/$id", $params );
}
# Get a single status by ID
sub get_status {
my $self = shift;
state $check = compile( Int, Optional [HashRef] );
my ($id, $params) = $check->(@_);
return $self->get( "statuses/$id", $params );
}
# Post a status
sub post_status {
my $self = shift;
state $check = compile( Str|HashRef, Optional[HashRef]);
my ($text, $params) = $check->(@_);
$params //= {};
my $payload;
if (ref $text eq 'HASH') {
$params = $text;
croak $log->fatal('Post must contain a (possibly empty) status text')
unless defined $params->{status};
$payload = $params;
}
else {
$payload = { status => $text, %{$params} };
}
return $self->post( 'statuses', $payload);
}
# Reblog a status by ID
sub reblog_status {
my $self = shift;
state $check = compile( Int );
my ($id) = $check->(@_);
return $self->post( "statuses/$id/reblog" );
}
sub register {
my $self = shift;
if ( $self->client_id && $self->client_secret ) {
$log->warn('Client is already registered');
return $self;
}
state $check = compile(
slurpy Dict [
redirect_uris => Optional [ Str ],
scopes => Optional [ ArrayRef [ Str ] ],
website => Optional [ Str ],
instance => Optional [ Any ],
]
);
my ($params) = $check->(@_);
# We used to accept instance by mistake, we want to turn it off
warn 'Deprecation notice: do not pass an instance parameter to register'
if $params->{instance};
my $website = $params->{website} // $self->website;
my $scopes = $params->{scopes} // $self->scopes;
my $response = $self->post(
'apps' => {
client_name => $self->name,
redirect_uris => $params->{redirect_uris} // $self->redirect_uri,
scopes => join( ' ', sort @{$scopes} ),
$website ? ( website => $website ) : (),
},
);
$self->client_id( $response->{client_id} );
$self->client_secret( $response->{client_secret} );
$self->scopes($scopes);
return $self;
}
sub statuses {
my $self = shift;
state $check = compile( Optional [HashRef|Int], Optional [HashRef]);
my ($id, $params) = $check->(@_);
if (ref $id) {
$params = $id;
$id = undef;
}
$id //= $self->account->{id};
$params //= {};
return $self->get( "accounts/$id/statuses", $params );
}
# Reject follow requests by account ID
sub reject_follow {
my $self = shift;
state $check = compile( Int );
my ($id) = $check->(@_);
return $self->post( 'follow_requests/reject' => { id => $id } );
}
# Follow a remote user by acct (username@instance)
sub remote_follow {
my $self = shift;
state $check = compile( Acct );
my ($acct) = $check->(@_);
return $self->post( 'follows' => { uri => $acct } );
}
# Report a user account or list of statuses
sub report {
my $self = shift;
state $check = compile( slurpy Dict[
account_id => Optional[Int],
status_ids => Optional[ArrayRef->plus_coercions( Int, sub { [ $_ ] } ) ],
comment => Optional[Str],
]);
my ($data) = $check->(@_);
croak $log->fatal('Either account_id or status_ids are required for report')
unless join(q{ }, keys(%{$data})) =~ /\b(account_id|status_ids)\b/;
return $self->post( 'reports' => $data );
}
sub relationships {
my $self = shift;
state $check = compile( slurpy ArrayRef [Int|HashRef] );
my ($ids) = $check->(@_);
my $params = (ref $ids->[-1] eq 'HASH') ? pop(@{$ids}) : {};
croak $log->fatal('At least one ID number needed in relationships')
unless scalar @{$ids};
$params = {
id => $ids,
%{$params},
};
return $self->get( 'accounts/relationships', $params );
}
sub search {
my $self = shift;
state $check = compile( Str, Optional [HashRef] );
my ($query, $params) = $check->(@_);
$params //= {};
$params = {
'q' => $query,
%{$params},
};
return $self->get( 'search', $params );
}
sub search_accounts {
my $self = shift;
state $check = compile( Str, Optional [HashRef] );
my ($query, $params) = $check->(@_);
$params //= {};
$params = {
'q' => $query,
%{$params},
};
return $self->get( 'accounts/search', $params );
}
sub stream {
my $self = shift;
state $check = compile( NonEmptyStr );
my ($query) = $check->(@_);
my $endpoint
= $self->instance->uri
. '/api/v'
. $self->api_version
. '/streaming/'
. (( $query =~ /^#/ )
? ( 'hashtag?' . $query )
: $query
);
use Mastodon::Listener;
return Mastodon::Listener->new(
url => $endpoint,
access_token => $self->access_token,
coerce_entities => $self->coerce_entities,
);
}
sub timeline {
my $self = shift;
state $check = compile( NonEmptyStr, Optional [HashRef] );
my ($query, $params) = $check->(@_);
my $endpoint
= ( $query =~ /^#/ )
? 'timelines/tag/' . $query
: 'timelines/' . $query;
return $self->get($endpoint, $params);
}
sub update_account {
my $self = shift;
state $check = compile(
slurpy Dict [
display_name => Optional [Str],
note => Optional [Str],
avatar => Optional [Image],
header => Optional [Image],
]
);
my ($data) = $check->(@_);
return $self->patch( 'accounts/update_credentials' => $data );
}
sub upload_media {
my $self = shift;
state $check = compile(
File->plus_coercions( Str, sub { Path::Tiny::path($_) } ),
Optional [ Dict[
description => Optional[Str],
focus => Optional[Tuple[StrictNum, StrictNum]],
]]
);
my ($file, $params) = $check->(@_);
$params //= {};
if (exists $params->{focus}) {
my ($x,$y) = @{$params->{focus}};
if ($x >= -1 && $x <= 1 && $y >= -1 && $y <= 1) {
$params->{focus} = "$x,$y";
} else {
delete $params->{focus};
}
}
return $self->post( 'media' =>
{ file => [ $file, undef ], %$params },
headers => { Content_Type => 'form-data' },
);
}
# POST requests with no data and a mandatory ID number
foreach my $pair ([
[ statuses => [qw( reblog unreblog favourite unfavourite )] ],
[ accounts => [qw( mute unmute block unblock follow unfollow )] ],
]) {
my ($base, $endpoints) = @{$pair};
foreach my $endpoint (@{$endpoints}) {
my $method = ($base eq 'statuses') ? $endpoint . '_status' : $endpoint;
no strict 'refs';
*{ __PACKAGE__ . '::' . $method } = sub {
my $self = shift;
state $check = compile( Int );
my ($id) = $check->(@_);
return $self->post( "$base/$id/$endpoint" );
};
}
}
# GET requests with no parameters but optional parameter hashref
for my $action (qw(
blocks favourites follow_requests mutes notifications reports
)) {
no strict 'refs';
*{ __PACKAGE__ . '::' . $action } = sub {
my $self = shift;
state $check = compile(Optional [HashRef]);
my ($params) = $check->(@_);
$params //= {};
return $self->get( $action, $params );
};
}
# GET requests with optional ID and parameter hashref
# ID number defaults to authenticated account's ID
for my $action (qw( following followers )) {
no strict 'refs';
*{ __PACKAGE__ . '::' . $action } = sub {
my $self = shift;
state $check = compile( Optional [Int|HashRef], Optional [HashRef] );
my ($id, $params) = $check->(@_);
if (ref $id eq 'HASH') {
$params = $id;
$id = undef;
}
$id //= $self->account->{id};
$params //= {};
return $self->get( "accounts/$id/$action", $params );
};
}
# GET requests for status details
foreach my $pair ([
[ get_status_context => 'context' ],
[ get_status_card => 'card' ],
[ get_status_reblogs => 'reblogged_by' ],
[ get_status_favourites => 'favourited_by' ],
]) {
my ($method, $endpoint) = @{$pair};
no strict 'refs';
*{ __PACKAGE__ . '::' . $method } = sub {
my $self = shift;
state $check = compile( Int, Optional [HashRef] );
my ($id, $params) = $check->(@_);
return $self->get( "statuses/$id/$endpoint", $params );
};
}
1;
__END__
=encoding utf8
=head1 NAME
Mastodon::Client - Talk to a Mastodon server
=head1 SYNOPSIS
use Mastodon::Client;
my $client = Mastodon::Client->new(
instance => 'mastodon.social',
name => 'PerlBot',
client_id => $client_id,
client_secret => $client_secret,
access_token => $access_token,
coerce_entities => 1,
);
$client->post_status('Posted to a Mastodon server!');
$client->post_status('And now in secret...',
{ visibility => 'unlisted' }
)
# Streaming interface might change!
my $listener = $client->stream( 'public' );
$listener->on( update => sub {
my ($listener, $status) = @_;
printf "%s said: %s\n",
$status->account->display_name,
$status->content;
});
$listener->start;
=head1 DESCRIPTION
Mastodon::Client lets you talk to a Mastodon server to obtain authentication
credentials, read posts from timelines in both static or streaming mode, and
perform all the other operations exposed by the Mastodon API.
Most of these are available through the convenience methods listed below, which
validate input parameters and are likely to provide more meaningful feedback in
case of errors.
Alternatively, this distribution can be used via the low-level request methods
(B, B, etc), which allow direct access to the API endpoints. All
other methods call one of these at some point.
=head1 VERSION NOTICE
This distribution currently B.
Help implementing support for any missing features in version 1, and for the
new features in version 2, would be greatfully appreciated.
=head1 ATTRIBUTES
=over 4
=item B
A Mastodon::Entity::Instance object representing the instance to which this
client will speak. Defaults to C.
=item B
An integer specifying the version of the API endpoints to use. Defaults to C<1>.
=item B
The URI to which authorization codes should be forwarded as part of the OAuth2
flow. Defaults to C (meaning no redirection).
=item B
The user agent to use for the requests. Defaults to an instance of
L. It is expected to have a C method that
accepts L objects.
=item B
A boolean value. Set to true if you want Mastodon::Client to internally coerce
all response entities to objects. This adds a level of validation, and can
make the objects easier to use.
Although this does require some additional processing, the coercion is done by
L, so the impact is negligible.
For now, it defaults to B (but this will likely change, so I recommend
you use it).
=item B
The access token of your client. This is provided by the Mastodon API and is
used for the OAuth2 authentication required for most API calls.
You can get this by calling B with either an access code or your
account's username and password.
=item B
Boolean. False is the client has no defined access_token. When an access token
is set, this is set to true or to a L object representing the time of
authorization if possible (as received from the server).
=item B
=item B
The client ID and secret are provided by the Mastodon API when you register
your client using the B method. They are used to identify where your
calls are coming from, and are required before you can use the B
method to get the access token.
=item B
Your client's name. This is required when registering, but is otherwise seldom
used. If you are using the B to get an access code from your
users, then they will see this name when they go to that page.
=item B
Holds the authenticated account. It is set internally by the B
method.
=item B
This array reference holds the scopes set by you for the client. These are
required when registering your client with the Mastodon instance. Defaults to
C.
Mastodon::Client will internally make sure that the scopes you were provided
when calling B match those that you requested. If this is not the
case, it will helpfully die.
=item B
The URL of a human-readable website for the client. If made available, it
appears as a link in the "authorized applications" tab of the user preferences
in the default Mastodon web GUI. Defaults to the empty string.
=back
=head1 METHODS
=head2 Authorizing an application
Although not all of the API methods require authentication to be used, most of
them do. The authentication process involves a) registering an application with
a Mastodon server to obtain a client secret and ID; b) authorizing the
application by either providing a user's credentials, or by using an
authentication URL.
The methods facilitating this process are detailed below:
=over 4
=item B
=item B
Obtain a client secret and ID from a given mastodon instance. Takes a single
hash as an argument, with the following possible keys:
=over 4
=item B
The URL to which authorization codes should be forwarded after authorized by
the user. Defaults to the value of the B attribute.
=item B
The scopes requested by this client. Defaults to the value of the B
attribute.
=item B
The client's website. Defaults to the value of the C attribute.
=back
When successful, sets the C, C, and C
attributes of the Mastodon::Client object and returns the modified object.
This should be called B per client and its contents cached locally.
=item B
Generate an authorization URL for the given application. Accessing this URL
via a browser by a logged in user will allow that user to grant this
application access to the requested scopes. The scopes used are the ones in the
B attribute at the time this method is called.
=item B
=item B
Grant the application access to the requested scopes for a given user. This
method takes a hash with either an access code or a user's login credentials to
grant authorization. Valid keys are:
=over 4
=item B
The access code obtained by visiting the URL generated by B.
=item B
=item B
The user's login credentials.
=back
When successful, the method automatically sets the client's B
attribute to a true value and caches the B for all future calls.
=back
=head2 Error handling
Methods that make requests to the server will C whenever an error is
encountered, or the data that was received from the server is not what is
expected. The error string will, when possible, come from the response's
status line, but this will likely not be enough to fully diagnose what
went wrong.
=over 4
=item B
To make this easier, the client will cache the server's response after each
request has been made, and expose it through the C accessor.
Note that, as its name implies, I.
If called before any request has been made, it will return an undefined
value.
=back
The remaining methods listed here follow the order of those in the official API
documentation.
=head2 Accounts
=over 4
=item B
=item B
=item B
=item B
Fetches an account by ID. If no ID is provided, this defaults to the current
authenticated account. Global GET parameters are available for this method.
Depending on the value of C, it returns a
Mastodon::Entity::Account object, or a plain hash reference.
=item B
Make changes to the authenticated account. Takes a hash reference with the
following possible keys:
=over 4
=item B
=item B
Strings
=item B
=item B
A base64 encoded image, or the name of a file to be encoded.
=back
Depending on the value of C, returns the modified
Mastodon::Entity::Account object, or a plain hash reference.
=item B
=item B
=item B
=item B
Get the list of followers of an account by ID. If no ID is provided, the one
for the current authenticated account is used. Global GET parameters are
available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B
=item B
=item B
=item B
Get the list of accounts followed by the account specified by ID. If no ID is
provided, the one for the current authenticated account is used. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B
=item B
=item B
=item B
Get a list of statuses from the account specified by ID. If no ID is
provided, the one for the current authenticated account is used.
In addition to the global GET parameters, this method accepts the following
parameters:
=over 4
=item B
=item B
Both boolean.
=back
Depending on the value of C, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
=item B
=item B
Follow or unfollow an account specified by ID. The ID argument is mandatory.
Depending on the value of C, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B
=item B
Block or unblock an account specified by ID. The ID argument is mandatory.
Depending on the value of C, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B
=item B
Mute or unmute an account specified by ID. The ID argument is mandatory.
Depending on the value of C, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B
=item B
Get the list of relationships of the current authenticated user with the
accounts specified by ID. At least one ID is required, but more can be passed
at once. Global GET parameters are available for this method, and can be passed
as an additional hash reference as a final argument.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Relationship objects, or a plain array reference.
=item B
=item B
Search for accounts. Takes a mandatory string argument to use as the search
query. If the search query is of the form C, the accounts
will be searched remotely.
In addition to the global GET parameters, this method accepts the following
parameters:
=over 4
=item B
The maximum number of matches. Defaults to 40.
=back
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
This method does not require authentication.
=back
=head2 Blocks
=over 4
=item B
=item B
Get the list of accounts blocked by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=back
=head2 Favourites
=over 4
=item B
=item B
Get the list of statuses favourited by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
=back
=head2 Follow requests
=over 4
=item B
=item B
Get the list of accounts requesting to follow the the authenticated user.
Global GET parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B
=item B
Accept or reject the follow request by the account of the specified ID. The ID
argument is mandatory.
Returns an empty object.
=back
=head2 Follows
=over 4
=item B
Follow a remote user by account string (ie. C). The argument
is mandatory.
Depending on the value of C, returns an
Mastodon::Entity::Account object, or a plain hash reference with the local
representation of the specified account.
=back
=head2 Instances
=over 4
=item B
Fetches the latest information for the current instance the client is talking
to. When successful, this method updates the value of the C
attribute.
Depending on the value of C, returns an
Mastodon::Entity::Instance object, or a plain hash reference.
This method does not require authentication.
=back
=head2 Media
=over 4
=item B
=item B
Upload a file as an attachment. Takes a mandatory argument with the name of a
local file to encode and upload, and an optional hash reference with the
following additional parameters:
=over 4
=item B
A plain-text description of the media, for accessibility, as a string.
=item B
An array reference of two floating point values, to be used as
the x and y focus values. These inform clients which point in
the image is the most important one to show in a cropped view.
The value of a coordinate is a real number between -1 and +1,
where 0 is the center. x:-1 indicates the left edge of the
image, x:1 the right edge. For the y axis, y:1 is the top edge
and y:-1 is the bottom.
=back
Depending on the value of C, returns an
Mastodon::Entity::Attachment object, or a plain hash reference.
The returned object's ID can be passed to the B to post it to a
timeline.
=back
=head2 Mutes
=over 4
=item B
=item B
Get the list of accounts muted by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=back
=head2 Notifications
=over 4
=item B
=item B
Get the list of notifications for the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Notification objects, or a plain array reference.
=item B
Get a notification by ID. The argument is mandatory.
Depending on the value of C, returns an
Mastodon::Entity::Notification object, or a plain hash reference.
=item B
Clears all notifications for the authenticated user.
This method takes no arguments and returns an empty object.
=back
=head2 Reports
=over 4
=item B
=item B
Get a list of reports made by the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C, returns an array reference of
Mastodon::Entity::Report objects, or a plain array reference.
=item B
Report a user or status. Takes a mandatory hash with the following keys:
=over 4
=item B
The ID of a single account to report.
=item B
The ID of a single status to report, or an array reference of statuses to
report.
=item B
An optional string.
=back
While the comment is always optional, either the B or the list of
B must be present.
Depending on the value of C, returns the new
Mastodon::Entity::Report object, or a plain hash reference.
=back
=head2 Search
=over 4
=item B
=item B
Search for content. Takes a mandatory string argument to use as the search
query. If the search query is a URL, Mastodon will attempt to fetch the
provided account or status. Otherwise, it will do a local account and hashtag
search.
In addition to the global GET parameters, this method accepts the following
parameters:
=over 4
=item B
Whether to resolve non-local accounts.
=back
=back
=head2 Statuses
=over 4
=item B
=item B
Fetches a status by ID. The ID argument is mandatory. Global GET parameters are available for this method as an additional hash reference.
Depending on the value of C, it returns a
Mastodon::Entity::Status object, or a plain hash reference.
This method does not require authentication.
=item B
=item B
Fetches the context of a status by ID. The ID argument is mandatory. Global GET parameters are available for this method as an additional hash reference.
Depending on the value of C, it returns a
Mastodon::Entity::Context object, or a plain hash reference.
This method does not require authentication.
=item B
=item B
Fetches a card associated to a status by ID. The ID argument is mandatory.
Global GET parameters are available for this method as an additional hash
reference.
Depending on the value of C, it returns a
Mastodon::Entity::Card object, or a plain hash reference.
This method does not require authentication.
=item B
=item B
=item B
=item B
Fetches a list of accounts who have reblogged or favourited a status by ID.
The ID argument is mandatory. Global GET parameters are available for this
method as an additional hash reference.
Depending on the value of C, it returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
This method does not require authentication.
=item B
=item B
Posts a new status. Takes a mandatory string as the content of the status
(which can be the empty string), and an optional hash reference with the
following additional parameters:
=over 4
=item B
The content of the status, as a string. Since this is already provided as the
first argument of the method, this is not necessary. But if provided, this
value will overwrite that of the first argument.
=item B
The optional ID of a status to reply to.
=item B
An array reference of up to four media IDs. These can be obtained as the result
of a call to B.
=item B
Boolean, to mark status content as NSFW.
=item B
A string, to be shown as a warning before the actual content.
=item B
A string; one of C, C, C, or C.
=back
Depending on the value of C, it returns the new
Mastodon::Entity::Status object, or a plain hash reference.
=item B
Delete a status by ID. The ID is mandatory. Returns an empty object.
=item B
=item B
=item B
=item B
Reblog or favourite a status by ID, or revert this action. The ID argument is
mandatory.
Depending on the value of C, it returns the specified
Mastodon::Entity::Status object, or a plain hash reference.
=back
=head2 Timelines
=over 4
=item B
=item B
Retrieves a timeline. The first argument defines either the name of a timeline
(which can be one of C or C), or a hashtag (if it begins with the
C<#> character). This argument is mandatory.
In addition to the global GET parameters, this method accepts the following
parameters:
Accessing the public and tag timelines does not require authentication.
=over 4
=item B
Boolean. If true, limits results only to those originating from the current
instance. Only applies to public and tag timelines.
=back
Depending on the value of C, it returns an array of
Mastodon::Entity::Status objects, or a plain array reference. The more recent
statuses come first.
=back
=head1 STREAMING RESULTS
Alternatively, it is possible to use the streaming API to get a constant stream
of updates. To do this, there is the B method.
=over 4
=item B
Creates a Mastodon::Listener object which will fetch a stream for the
specified query. Possible values for the query are either C, for events
that are relevant to the authorized user; C, for all public statuses;
or a tag (if it begins with the C<#> character), for all public statuses for
the particular tag.
For more details on how to use this object, see the documentation for
L.
Accessing streaming public timeline does not require authentication.
=back
=head1 REQUEST METHODS
Mastodon::Client uses four lower-level request methods to contact the API
with GET, POST, PATCH, and DELETE requests. These are left available in case
one of the higher-level convenience methods are unsuitable or undesirable, but
you use them at your own risk.
They all take a URL as their first parameter, which can be a string with the
API endpoint to contact, or a L object, which will be used as-is.
If passed as a string, the methods expect one that contains only the variable
parts of the endpoint (ie. not including the C part). The
remaining parts will be filled-in appropriately internally.
=over 4
=item B
=item B
=item B
Query parameters can be passed as part of the L object, but it is not
recommended you do so, since Mastodon has expectations for array parameters
that do not meet those of eg. L. It will be easier and safer
if any additional parameters are passed as a hash reference, which will be
added to the URL before the request is sent.
=item B
=item B
=item B
=item B
the C and C methods work similarly to C and C, but
the optional hash reference is sent in as form data, instead of processed as
query parameters. The Mastodon API does not use query parameters on POST or
PATCH endpoints.
=back
=head1 CONTRIBUTIONS AND BUG REPORTS
Contributions of any kind are most welcome!
The main repository for this distribution is on
L, which is where patches
and bug reports are mainly tracked. The repository is also mirrored on
L, in case that platform
makes it easier to post contributions.
If none of the above is acceptable, bug reports can also be sent through the
CPAN RT system, or by mail directly to the developers at the address below,
although these will not be as closely tracked.
=head1 AUTHOR
=over 4
=item *
José Joaquín Atria
=back
=head1 CONTRIBUTORS
=over 4
=item *
Lance Wicks
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2017 by José Joaquín Atria.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
Mastodon-Client-0.017/lib/Mastodon/Role/ 0000775 0001750 0001750 00000000000 13646430665 017625 5 ustar jjatria jjatria Mastodon-Client-0.017/lib/Mastodon/Role/Entity.pm 0000644 0001750 0001750 00000000224 13646430665 021433 0 ustar jjatria jjatria package Mastodon::Role::Entity;
use strict;
use warnings;
our $VERSION = '0.017';
use Moo::Role;
has _client => ( is => 'rw', weaken => 1);
1;
Mastodon-Client-0.017/lib/Mastodon/Role/UserAgent.pm 0000644 0001750 0001750 00000012220 13646430665 022053 0 ustar jjatria jjatria package Mastodon::Role::UserAgent;
use strict;
use warnings;
our $VERSION = '0.017';
use v5.10.0;
use Moo::Role;
use Log::Any;
my $log = Log::Any->get_logger( category => 'Mastodon' );
use URI::QueryParam;
use List::Util qw( any );
use Types::Standard qw(
ArrayRef
Dict
HashRef
Maybe
Num
Optional
Str
Undef
slurpy
);
use Mastodon::Types qw(
HTTPResponse
Instance
URI
UserAgent
to_Entity
);
use Type::Params qw( compile );
use Carp;
has instance => (
is => 'rw',
isa => Instance,
default => 'https://mastodon.social',
coerce => 1,
);
has api_version => (
is => 'ro',
isa => Num,
default => 1,
);
has redirect_uri => (
is => 'ro',
isa => Str,
lazy => 1,
default => 'urn:ietf:wg:oauth:2.0:oob',
);
has user_agent => (
is => 'ro',
isa => UserAgent,
default => sub {
require HTTP::Thin;
HTTP::Thin->new;
},
);
has latest_response => (
is => 'ro',
isa => Maybe[HTTPResponse],
init_args => undef,
);
sub authorization_url {
my $self = shift;
unless ($self->client_id and $self->client_secret) {
croak $log->fatal(
'Cannot get authorization URL without client_id and client_secret'
);
}
state $check = compile( slurpy Dict [ access_code => Optional [Instance] ] );
my ($params) = $check->(@_);
$params->{instance} //= $self->instance;
my $uri = URI->new('/oauth/authorize')->abs($params->{instance}->uri);
$uri->query_param(redirect_uri => $self->redirect_uri);
$uri->query_param(response_type => 'code');
$uri->query_param(client_id => $self->client_id);
$uri->query_param(scope => join q{ }, sort(@{$self->scopes}));
return $uri;
}
sub post { shift->_request( post => shift, data => shift, @_ ) }
sub patch { shift->_request( patch => shift, data => shift, @_ ) }
sub get { shift->_request( get => shift, params => shift, @_ ) }
sub delete { shift->_request( delete => shift, params => shift, @_ ) }
sub _request {
my $self = shift;
my $method = shift;
my $url = shift;
my $args = { @_ };
my $headers = $args->{headers} // {};
my $data = $self->_prepare_data($args->{data});
$url = $self->_prepare_params($url, $args->{params});
$method = uc($method);
if ($self->can('access_token') and $self->access_token) {
$headers = {
Authorization => 'Bearer ' . $self->access_token,
%{$headers},
};
}
if ($log->is_trace) {
require Data::Dumper;
$log->debugf('Method: %s', $method);
$log->debugf('URL: %s', $url);
$log->debugf('Headers: %s', Data::Dumper::Dumper( $headers ));
$log->debugf('Data: %s', Data::Dumper::Dumper( $data ));
}
use Try::Tiny;
return try {
my @args = $url;
push @args, [%{$data}] unless $method eq 'GET';
@args = (@args, %{$headers});
require HTTP::Request::Common;
my $type = ($method eq 'PATCH') ? 'POST' : $method;
my $request = HTTP::Request::Common->can($type)->( @args );
$request->method($method);
my $response = $self->user_agent->request( $request );
use JSON::MaybeXS qw( decode_json );
use Encode qw( encode );
# We want to be able to set it, but do not want the user to do so
$self->{latest_response} = $response;
die $response->status_line unless $response->is_success;
my $payload = decode_json encode('utf8', $response->decoded_content);
# Some API calls return empty objects, which cannot be coerced
if ($response->decoded_content ne '{}') {
if ($url !~ /(?:apps|oauth)/ and $self->coerce_entities) {
$payload = (ref $payload eq 'ARRAY')
? [ map { to_Entity({ %{$_}, _client => $self }) } @{$payload} ]
: to_Entity({ %{$payload}, _client => $self });
}
}
if (ref $payload eq 'ARRAY') {
die $payload->{error} if any { defined $_->{error} } @{$payload};
}
elsif (ref $payload eq 'HASH') {
die $payload->{error} if defined $payload->{error};
}
return $payload;
}
catch {
my $msg = sprintf 'Could not complete request: %s', $_;
$log->fatal($msg);
croak $msg;
};
}
sub _prepare_data {
my ($self, $data) = @_;
$data //= {};
foreach my $key (keys %{$data}) {
# Array parameters to the API need keys that are marked with []
# However, HTTP::Request::Common expects an arrayref to encode files
# for transfer, even though the API does not expect that to be an array
# So we need to manually skip it, unless we come up with another solution.
next if $key eq 'file';
my $val = $data->{$key};
$data->{$key . '[]'} = delete($data->{$key}) if ref $val eq 'ARRAY';
}
return $data;
}
sub _prepare_params {
my ($self, $url, $params) = @_;
$params //= {};
croak 'Cannot make a request without a URL' unless $url;
unless (ref $url eq 'URI') {
my $base = $url =~ m{^/oauth/} ? '/' : '/api/v' . $self->api_version . '/';
$url = URI->new( $self->instance->uri . $base . $url );
}
# Adjust query param format to be Ruby-compliant
foreach my $key (keys %{$params}) {
my $val = $params->{$key};
if (ref $val eq 'ARRAY') { $url->query_param($key . '[]' => @{$val}) }
else { $url->query_param($key => $val) }
}
return $url;
}
1;
Mastodon-Client-0.017/lib/Mastodon/Listener.pm 0000644 0001750 0001750 00000015345 13646430665 021055 0 ustar jjatria jjatria package Mastodon::Listener;
use strict;
use warnings;
our $VERSION = '0.017';
use Moo;
with 'Role::EventEmitter';
use Types::Standard qw( Int Str Bool );
use Mastodon::Types qw( Instance to_Status to_Notification );
use IO::Async::Loop;
use Net::Async::HTTP;
use Try::Tiny;
use JSON::MaybeXS qw( decode_json );
use Log::Any;
my $log = Log::Any->get_logger(category => 'Mastodon');
has instance => (
is => 'ro',
isa => Instance,
coerce => 1,
default => 'mastodon.cloud',
);
has api_version => (
is => 'ro',
isa => Int,
default => 1,
);
has url => (
is => 'ro',
lazy => 1,
default => sub {
$_[0]->instance
. '/api/v' . $_[0]->api_version
. '/streaming/' . $_[0]->stream;
},
);
has stream => (
is => 'ro',
lazy => 1,
default => 'public',
);
has access_token => (
is => 'ro',
required => 1,
);
has _ua => (
is => 'rw',
init_arg => undef,
default => sub { Net::Async::HTTP->new },
);
has _future => (
is => 'rw',
init_arg => undef,
lazy => 1,
default => sub { Future->new },
);
has coerce_entities => (
is => 'rw',
isa => Bool,
lazy => 1,
default => 0,
);
sub BUILD {
my ($self, $arg) = @_;
IO::Async::Loop->new->add($self->_ua);
}
sub start {
my $self = shift;
my $on_error = sub { $self->emit( error => shift, shift, \@_ ) };
$self->_future(
$self->_ua->do_request(
uri => $self->url,
headers => {
Authorization => 'Bearer ' . $self->access_token,
},
on_error => sub { $on_error->( 1, shift, \@_ ) },
on_header => sub {
my $response = shift;
$on_error->( 1, $response->message, $response )
unless $response->is_success;
my $current_event;
my $buffer = '';
return sub {
my $chunk = shift;
# We do not have enough data yet, add it to the buffer
unless ( $chunk =~ /\n$/m ) {
$buffer .= $chunk;
return;
}
$chunk = $buffer . $chunk;
if ( $chunk =~ /^(:thump|event: (\w+))$/m ) {
my $line = $1;
my $event = $2;
unless ( defined $event ) {
# Heartbeats have no data
$self->emit( 'heartbeat' );
return;
}
$current_event = $event;
$chunk =~ s/$line\n//;
}
if ( $chunk =~ /^data:/ ) {
$chunk =~ s/^data:\s+//;
if ( $current_event eq 'delete' ) {
# The payload for delete is a single integer
$self->emit( delete => $chunk );
}
else {
try {
my $payload = decode_json $chunk;
$self->emit( $current_event => $payload );
}
catch {
$self->emit( error => 0,
"Error decoding JSON payload: $_", $chunk
);
};
}
undef $current_event;
}
$buffer = '';
return;
}
},
)
);
$self->_future->get;
}
sub stop {
my $self = shift;
$self->_future->done(@_) unless $self->_future->is_ready;
return $self;
}
sub reset {
my $self = shift;
$self->stop->start;
}
around emit => sub {
my $orig = shift;
my $self = shift;
my ($event, $data, @rest) = @_;
if ($event =~ /(update|notification)/ and $self->coerce_entities) {
$data = to_Notification($data) if $event eq 'notification';
$data = to_Status($data) if $event eq 'update';
}
$self->$orig($event, $data, @rest);
};
1;
__END__
=encoding utf8
=head1 NAME
Mastodon::Listener - Access the streaming API of a Mastodon server
=head1 SYNOPSIS
# From Mastodon::Client
my $listener = $client->stream( 'public' );
# Or use it directly
my $listener = Mastodon::Listener->new(
url => 'https://mastodon.cloud/api/v1/streaming/public',
access_token => $token,
coerce_entities => 1,
)
$listener->on( update => sub {
my ($listener, $status) = @_;
printf "%s said: %s\n",
$status->account->display_name,
$status->content;
});
$listener->start;
=head1 DESCRIPTION
A Mastodon::Listener object is created by calling the B method from a
L, and it exists for the sole purpose of parsing a stream of
events from a Mastodon server.
Mastodon::Listener objects inherit from L. Please refer to
its documentation for details on how to register callbacks for the different
events.
Once callbacks have been registered, the listener can be set in motion by
calling its B method, which takes no arguments and never returns.
The B method can be called from within callbacks to disconnect from the
stream.
=head1 ATTRIBUTES
=over 4
=item B
The OAuth2 access token of your application, if authorization is needed. This
is not needed for streaming from public timelines.
=item B
The API version to use. Defaults to C<1>.
=item B
Whether JSON responses should be coerced into Mastodon::Entity objects.
Currently defaults to false (but this will likely change in v0.01).
=item B
The instance to use, as a L object. Will be coerced
from a URL, and defaults to C.
=item B
The stream to use. Current valid streams are C, C, and tag
timelines. To access a tag timeline, the argument to this value should begin
with a hash character (C<#>).
=item B
The full streaming URL to use. By default, it is constructed from the values in
the B, B, and B attributes.
=back
=head1 EVENTS
=over 4
=item B
A new status has appeared. Callback will be called with the listener and
the new status.
=item B
A new notification has appeared. Callback will be called with the listener
and the new notification.
=item B
A status has been deleted. Callback will be called with the listener and the
ID of the deleted status.
=item B
A new C<:thump> has been received from the server. This is mostly for
debugging purposes.
=item B
Inherited from L, will be emitted when an error was found.
The callback will be called with a fatal flag, an error message, and any
relevant data as a single third arghument.
If the error event is triggered in response to a 4xx or 5xx error, the data
payload will be an array reference with the response and request objects
as received from L.
=back
=head1 AUTHOR
=over 4
=item *
José Joaquín Atria
=back
=head1 COPYRIGHT AND LICENSE
This software is copyright (c) 2017 by José Joaquín Atria.
This is free software; you can redistribute it and/or modify it under
the same terms as the Perl 5 programming language system itself.
=cut
Mastodon-Client-0.017/lib/Mastodon/Types.pm 0000644 0001750 0001750 00000005153 13646430665 020370 0 ustar jjatria jjatria package Mastodon::Types;
use strict;
use warnings;
our $VERSION = '0.017';
use Type::Library -base;
use Type::Utils -all;
use Types::Standard qw( Str HashRef Num );
use Types::Path::Tiny qw( File to_File);
use URI;
use DateTime;
use MIME::Base64;
use Class::Load qw( load_class );
duck_type 'UserAgent', [qw( get post delete )];
class_type 'URI', { class => 'URI' };
coerce 'URI', from Str, via {
s{^/+}{}g;
my $uri = URI->new((m{^https?://} ? q{} : 'https://') . $_);
$uri->scheme('https') unless $uri->scheme;
return $uri;
};
# We provide our own DateTime type because the Types::DateTime distribution
# is currently undermaintained
class_type 'DateTime', { class => 'DateTime' };
class_type 'HTTPResponse', { class => 'HTTP::Response' };
coerce 'DateTime',
from Num,
via { 'DateTime'->from_epoch( epoch => $_ ) }
from Str,
via {
require DateTime::Format::Strptime;
DateTime::Format::Strptime->new(
pattern => '%FT%T.%3N%Z',
on_error => 'croak',
)->parse_datetime($_);
};
# Validation here could be improved
# It is either a username if a local account, or a username@instance.tld
# but what characters are valid?
declare 'Acct', as Str;
declare 'Image',
as Str, where { m{^data:image/(?:png|jpeg);base64,[a-zA-Z0-9/+=\n]+$} };
coerce File, from Str, via {
require Path::Tiny;
return Path::Tiny::path( $_ );
};
coerce 'Image',
from File->coercibles,
via {
my $file = to_File($_);
require Image::Info;
require MIME::Base64;
my $type = lc Image::Info::image_type( $file->stringify )->{file_type};
my $img = "data:image/$type;base64,"
. MIME::Base64::encode_base64( $file->slurp_raw );
return $img;
};
# Entity types
my @entities = qw(
Status Account Instance Attachment Card Context Mention
Notification Relationship Report Results Error Tag Application
);
foreach my $name (@entities) {
class_type $name, { class => "Mastodon::Entity::$name" };
coerce $name, from HashRef, via {
load_class "Mastodon::Entity::$name";
"Mastodon::Entity::$name"->new($_);
};
}
role_type 'Entity', { role => 'Mastodon::Role::Entity' };
coerce 'Instance',
from Str,
via {
require Mastodon::Entity::Instance;
Mastodon::Entity::Instance->new({
uri => $_,
});
};
coerce 'Entity',
from HashRef,
via {
my $hash = $_;
my $entity;
use Try::Tiny;
foreach my $name (@entities) {
$entity = try {
load_class "Mastodon::Entity::$name";
"Mastodon::Entity::$name"->new($hash);
};
last if defined $entity;
}
return $entity;
};
1;
Mastodon-Client-0.017/lib/Mastodon/Entity/ 0000775 0001750 0001750 00000000000 13646430665 020200 5 ustar jjatria jjatria Mastodon-Client-0.017/lib/Mastodon/Entity/Notification.pm 0000644 0001750 0001750 00000003257 13646430665 023171 0 ustar jjatria jjatria package Mastodon::Entity::Notification;
use strict;
use warnings;
our $VERSION = '0.017';
use Moo;
with 'Mastodon::Role::Entity';
use Types::Standard qw( Int Enum );
use Mastodon::Types qw( Status DateTime Account );
has account => ( is => 'ro', isa => Account, );
has created_at => ( is => 'ro', isa => DateTime, );
has id => ( is => 'ro', isa => Int, );
has status => ( is => 'ro', isa => Status, required => 1, coerce => 1, );
has type => ( is => 'ro', isa => Enum[qw(
mention reblog favourite follow
)], );
1;
=encoding utf8
=head1 NAME
Mastodon::Entity::Notification - A Mastodon notification
=head1 DESCRIPTION
This object should not be manually created. It is intended to be generated
from the data received from a Mastodon server using the coercions in
L.
For current information, see the
L
=head1 ATTRIBUTES
=over 4
=item B