1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
|
# 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<post>, B<get>, 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<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.
=head1 ATTRIBUTES
=over 4
=item B<instance>
A Mastodon::Entity::Instance object representing the instance to which this
client will speak. Defaults to C<mastodon.social>.
=item B<api_version>
An integer specifying the version of the API endpoints to use. Defaults to C<1>.
=item B<redirect_uri>
The URI to which authorization codes should be forwarded as part of the OAuth2
flow. Defaults to C<urn:ietf:wg:oauth:2.0:oob> (meaning no redirection).
=item B<user_agent>
The user agent to use for the requests. Defaults to an instance of
L<HTTP::Thin>. It is expected to have a C<request> method that
accepts L<HTTP::Request> objects.
=item B<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
L<Type::Tiny>, so the impact is negligible.
For now, it defaults to B<false> (but this will likely change, so I recommend
you use it).
=item B<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 B<authorize> with either an access code or your
account's username and password.
=item B<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 L<DateTime> object representing the time of
authorization if possible (as received from the server).
=item B<client_id>
=item B<client_secret>
The client ID and secret are provided by the Mastodon API when you register
your client using the B<register> method. They are used to identify where your
calls are coming from, and are required before you can use the B<authorize>
method to get the access token.
=item B<name>
Your client's name. This is required when registering, but is otherwise seldom
used. If you are using the B<authorization_url> to get an access code from your
users, then they will see this name when they go to that page.
=item B<account>
Holds the authenticated account. It is set internally by the B<get_account>
method.
=item B<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
C<read>.
Mastodon::Client will internally make sure that the scopes you were provided
when calling B<authorize> match those that you requested. If this is not the
case, it will helpfully die.
=item B<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.
=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<register()>
=item B<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:
=over 4
=item B<redirect_uris>
The URL to which authorization codes should be forwarded after authorized by
the user. Defaults to the value of the B<redirect_uri> attribute.
=item B<scopes>
The scopes requested by this client. Defaults to the value of the B<scopes>
attribute.
=item B<website>
The client's website. Defaults to the value of the C<website> attribute.
=back
When successful, sets the C<client_secret>, C<scopes>, and C<client_id>
attributes of the Mastodon::Client object and returns the modified object.
This should be called B<once> per client and its contents cached locally.
=item B<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
B<scopes> attribute at the time this method is called.
=item B<authorize()>
=item B<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:
=over 4
=item B<access_code>
The access code obtained by visiting the URL generated by B<authorization_url>.
=item B<username>
=item B<password>
The user's login credentials.
=back
When successful, the method automatically sets the client's B<authorized>
attribute to a true value and caches the B<access_token> for all future calls.
=back
=head2 Error handling
Methods that make requests to the server will C<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.
=over 4
=item B<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 C<latest_response> accessor.
Note that, as its name implies, I<this will only store the most recent
response>.
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<get_account()>
=item B<get_account($id)>
=item B<get_account($params)>
=item B<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 C<coerce_entities>, it returns a
Mastodon::Entity::Account object, or a plain hash reference.
=item B<update_account($params)>
Make changes to the authenticated account. Takes a hash reference with the
following possible keys:
=over 4
=item B<display_name>
=item B<note>
Strings
=item B<avatar>
=item B<header>
A base64 encoded image, or the name of a file to be encoded.
=back
Depending on the value of C<coerce_entities>, returns the modified
Mastodon::Entity::Account object, or a plain hash reference.
=item B<followers()>
=item B<followers($id)>
=item B<followers($params)>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B<following()>
=item B<following($id)>
=item B<following($params)>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B<statuses()>
=item B<statuses($id)>
=item B<statuses($params)>
=item B<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:
=over 4
=item B<only_media>
=item B<exclude_replies>
Both boolean.
=back
Depending on the value of C<coerce_entities>, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
=item B<follow($id)>
=item B<unfollow($id)>
Follow or unfollow an account specified by ID. The ID argument is mandatory.
Depending on the value of C<coerce_entities>, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B<block($id)>
=item B<unblock($id)>
Block or unblock an account specified by ID. The ID argument is mandatory.
Depending on the value of C<coerce_entities>, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B<mute($id)>
=item B<unmute($id)>
Mute or unmute an account specified by ID. The ID argument is mandatory.
Depending on the value of C<coerce_entities>, returns the new
Mastodon::Entity::Relationship object, or a plain hash reference.
=item B<relationships(@ids)>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Relationship objects, or a plain array reference.
=item B<search_accounts($query)>
=item B<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 C<username@domain>, the accounts
will be searched remotely.
In addition to the global GET parameters, this method accepts the following
parameters:
=over 4
=item B<limit>
The maximum number of matches. Defaults to 40.
=back
Depending on the value of C<coerce_entities>, 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<blocks()>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=back
=head2 Favourites
=over 4
=item B<favourites()>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Status objects, or a plain array reference.
=back
=head2 Follow requests
=over 4
=item B<follow_requests()>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=item B<authorize_follow($id)>
=item B<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.
=back
=head2 Follows
=over 4
=item B<remote_follow($acct)>
Follow a remote user by account string (ie. C<username@domain>). The argument
is mandatory.
Depending on the value of C<coerce_entities>, 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<fetch_instance()>
Fetches the latest information for the current instance the client is talking
to. When successful, this method updates the value of the C<instance>
attribute.
Depending on the value of C<coerce_entities>, returns an
Mastodon::Entity::Instance object, or a plain hash reference.
This method does not require authentication.
=back
=head2 Media
=over 4
=item B<upload_media($file)>
=item B<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:
=over 4
=item B<description>
A plain-text description of the media, for accessibility, as a string.
=item B<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.
=back
Depending on the value of C<coerce_entities>, returns an
Mastodon::Entity::Attachment object, or a plain hash reference.
The returned object's ID can be passed to the B<post_status> to post it to a
timeline.
=back
=head2 Mutes
=over 4
=item B<mutes()>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
=back
=head2 Notifications
=over 4
=item B<notifications()>
=item B<notifications($params)>
Get the list of notifications for the authenticated user. Global GET
parameters are available for this method.
Depending on the value of C<coerce_entities>, returns an array reference of
Mastodon::Entity::Notification objects, or a plain array reference.
=item B<get_notification($id)>
Get a notification by ID. The argument is mandatory.
Depending on the value of C<coerce_entities>, returns an
Mastodon::Entity::Notification object, or a plain hash reference.
=item B<clear_notifications()>
Clears all notifications for the authenticated user.
This method takes no arguments and returns an empty object.
=back
=head2 Reports
=over 4
=item B<reports()>
=item B<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 C<coerce_entities>, returns an array reference of
Mastodon::Entity::Report objects, or a plain array reference.
=item B<report($params)>
Report a user or status. Takes a mandatory hash with the following keys:
=over 4
=item B<account_id>
The ID of a single account to report.
=item B<status_ids>
The ID of a single status to report, or an array reference of statuses to
report.
=item B<comment>
An optional string.
=back
While the comment is always optional, either the B<account_id> or the list of
B<status_ids> must be present.
Depending on the value of C<coerce_entities>, returns the new
Mastodon::Entity::Report object, or a plain hash reference.
=back
=head2 Search
=over 4
=item B<search($query)>
=item B<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:
=over 4
=item B<resolve>
Whether to resolve non-local accounts.
=back
=back
=head2 Statuses
=over 4
=item B<get_status($id)>
=item B<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 C<coerce_entities>, it returns a
Mastodon::Entity::Status object, or a plain hash reference.
This method does not require authentication.
=item B<get_status_context($id)>
=item B<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 C<coerce_entities>, it returns a
Mastodon::Entity::Context object, or a plain hash reference.
This method does not require authentication.
=item B<get_status_card($id)>
=item B<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 C<coerce_entities>, it returns a
Mastodon::Entity::Card object, or a plain hash reference.
This method does not require authentication.
=item B<get_status_reblogs($id)>
=item B<get_status_reblogs($id, $params)>
=item B<get_status_favourites($id)>
=item B<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 C<coerce_entities>, it returns an array reference of
Mastodon::Entity::Account objects, or a plain array reference.
This method does not require authentication.
=item B<post_status($text)>
=item B<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:
=over 4
=item B<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.
=item B<in_reply_to_id>
The optional ID of a status to reply to.
=item B<media_ids>
An array reference of up to four media IDs. These can be obtained as the result
of a call to B<upload_media()>.
=item B<sensitive>
Boolean, to mark status content as NSFW.
=item B<spoiler_text>
A string, to be shown as a warning before the actual content.
=item B<visibility>
A string; one of C<direct>, C<private>, C<unlisted>, or C<public>.
=back
Depending on the value of C<coerce_entities>, it returns the new
Mastodon::Entity::Status object, or a plain hash reference.
=item B<delete_status($id)>
Delete a status by ID. The ID is mandatory. Returns an empty object.
=item B<reblog($id)>
=item B<unreblog($id)>
=item B<favourite($id)>
=item B<unfavourite($id)>
Reblog or favourite a status by ID, or revert this action. The ID argument is
mandatory.
Depending on the value of C<coerce_entities>, it returns the specified
Mastodon::Entity::Status object, or a plain hash reference.
=back
=head2 Timelines
=over 4
=item B<timeline($query)>
=item B<timeline($query, $params)>
Retrieves a timeline. The first argument defines either the name of a timeline
(which can be one of C<home> or C<public>), 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<local>
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<coerce_entities>, 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<stream()> method.
=over 4
=item B<stream($query)>
Creates a Mastodon::Listener object which will fetch a stream for the
specified query. Possible values for the query are either C<user>, for events
that are relevant to the authorized user; C<public>, 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<Mastodon::Listener>.
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<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 C<HOST/api/v1> part). The
remaining parts will be filled-in appropriately internally.
=over 4
=item B<delete($url)>
=item B<get($url)>
=item B<get($url, $params)>
Query parameters can be passed as part of the L<URI> object, but it is not
recommended you do so, since Mastodon has expectations for array parameters
that do not meet those of eg. L<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.
=item B<post($url)>
=item B<post($url, $data)>
=item B<patch($url)>
=item B<patch($url, $data)>
the C<post> and C<patch> methods work similarly to C<get> and C<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.
=back
=head1 CONTRIBUTIONS AND BUG REPORTS
Contributions of any kind are most welcome!
The main repository for this distribution is on
L<GitLab|https://gitlab.com/jjatria/Mastodon-Client>, which is where patches
and bug reports are mainly tracked. The repository is also mirrored on
L<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.
=head1 AUTHOR
=over 4
=item *
José Joaquín Atria <jjatria@cpan.org>
=back
=head1 CONTRIBUTORS
=over 4
=item *
Lance Wicks <lancew@cpan.org>
=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
|