blib/lib/WWW/Spotify.pm

filter: Statementstmt 84.8% 268 / 316 Branchbran 68.9% 109 / 158 Conditioncond 64.7% 46 / 71 MC/DCmcdc 52.2% 23 / 44 Subroutinesub 77.7% 42 / 54 Podpod 81.5% 31 / 38 totaltotal 76.2% 519 / 681 CC 105 SCAR 18.4
CC
105
Cov
78%
previous_result_set
20.0
send_get_request
16.3
get_audiobook
12.0
CRAP 6.3
↑ Summary
1 package WWW::Spotify;
2  
3 6 ▶use Moo 2.002004;
Subroutine BEGIN: called CC=1 SCAR=0.0
4  
5 6 our $VERSION = '1.000';
6  
7 6 ▶use JSON::Path ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 6 ▶use JSON::MaybeXS qw( decode_json encode_json );
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use MIME::Base64 qw( encode_base64 );
Subroutine BEGIN: called CC=1 SCAR=0.0
10 6 ▶use Types::Standard qw( Bool InstanceOf Int Str CodeRef );
Subroutine BEGIN: called CC=1 SCAR=0.0
11 6 ▶use HTTP::Status qw( HTTP_OK is_success );
Subroutine BEGIN: called CC=1 SCAR=0.0
12 6 ▶use URI::Escape qw( uri_escape uri_escape_utf8 );
Subroutine BEGIN: called CC=1 SCAR=0.0
13 6 ▶use LWP::UserAgent ();
Subroutine BEGIN: called CC=1 SCAR=0.0
14  
15 6 has 'oauth_authorize_url' => (
16 is => 'rw',
17 isa => Str,
18 default => 'https://accounts.spotify.com/authorize'
19 );
20  
21 6 has 'oauth_token_url' => (
22 is => 'rw',
23 isa => Str,
24 default => 'https://accounts.spotify.com/api/token'
25 );
26  
27 6 has 'oauth_redirect_uri' => (
28 is => 'rw',
29 isa => Str,
30 default => 'http://www.spotify.com'
31 );
32  
33 has 'oauth_client_id' => (
34 is => 'rw',
35 isa => Str,
36 6 ▶ default => $ENV{SPOTIFY_CLIENT_ID} || q{}
Condition50%1/2
$ENV{'SPOTIFY_CLIENT_ID'} || ''
l!l
06
MC/DC0%0/1
$ENV{'SPOTIFY_CLIENT_ID'} || ''
$ENV{'SPOTIFY_CLIENT_ID'}
Truth table50%1/2
A
A= $ENV{'SPOTIFY_CLIENT_ID'}
Aresult
11
00
37 );
38  
39 has 'oauth_client_secret' => (
40 is => 'rw',
41 isa => Str,
42 6 ▶ default => $ENV{SPOTIFY_CLIENT_SECRET} || q{}
Condition50%1/2
$ENV{'SPOTIFY_CLIENT_SECRET'} || ''
l!l
06
MC/DC0%0/1
$ENV{'SPOTIFY_CLIENT_SECRET'} || ''
$ENV{'SPOTIFY_CLIENT_SECRET'}
Truth table50%1/2
A
A= $ENV{'SPOTIFY_CLIENT_SECRET'}
Aresult
11
00
43 );
44  
45 6 has 'current_access_token' => (
46 is => 'rw',
47 isa => Str,
48 default => q{}
49 );
50  
51 6 has 'refresh_token' => (
52 is => 'rw',
53 isa => Str,
54 default => q{}
55 );
56  
57 6 has 'grab_response_header' => (
58 is => 'rw',
59 isa => Bool,
60 default => 0
61 );
62  
63 6 has 'results' => (
64 is => 'rw',
65 isa => Int,
66 default => '15'
67 );
68  
69 6 has 'debug' => (
70 is => 'rw',
71 isa => Bool,
72 default => 0
73 );
74  
75 6 has 'uri_scheme' => (
76 is => 'ro',
77 isa => Str,
78 default => 'https'
79 );
80  
81 6 has 'current_client_credentials' => (
82 is => 'rw',
83 isa => Str,
84 default => q{}
85 );
86  
87 6 has 'uri_hostname' => (
88 is => 'ro',
89 isa => Str,
90 default => 'api.spotify.com'
91 );
92  
93 6 has 'auto_json_decode' => (
94 is => 'rw',
95 isa => Bool,
96 default => 0
97 );
98  
99 6 has 'last_result' => (
100 is => 'rw',
101 isa => Str,
102 default => q{}
103 );
104  
105 6 has 'last_error' => (
106 is => 'rw',
107 isa => Str,
108 default => q{}
109 );
110  
111 6 has 'response_headers' => (
112 is => 'rw',
113 isa => Str,
114 default => q{}
115 );
116  
117 has 'ua' => (
118 is => 'ro',
119 isa => InstanceOf ['LWP::UserAgent'],
120 lazy => 1,
121 0 ▶ default => sub { LWP::UserAgent->new },
Subroutine __ANON__: not called CC=1 SCAR=6.9
122 6 );
123  
124 6 has 'response_status' => (
125 is => 'rw',
126 isa => Int,
127 default => 0
128 );
129  
130 6 has 'response_content_type' => (
131 is => 'rw',
132 isa => Str,
133 default => q{}
134 );
135  
136 6 has 'custom_request_handler' => (
137 is => 'rw',
138 isa => CodeRef,
139 predicate => '_has_custom_request_handler',
140 );
141  
142 6 has 'custom_request_handler_result' => (
143 is => 'ro',
144 writer => '_set_custom_request_handler_result'
145 );
146  
147 6 has 'die_on_response_error' => (
148 is => 'rw',
149 isa => Bool,
150 default => 0
151 );
152  
153 6 has 'token_expires_at' => (
154 is => 'rw',
155 isa => Int,
156 default => 0
157 );
158  
159 6 my @api_call_options = (
160 {
161 path => '/v1/albums/{id}',
162 info => 'Get an album',
163 type => 'GET',
164 method => 'album'
165 },
166  
167 {
168 path => '/v1/audiobooks/{id}',
169 info => 'Get an audiobook',
170 type => 'GET',
171 method => 'get_audiobook',
172 params => ['market']
173 },
174  
175 {
176 path => '/v1/audiobooks/{id}/chapters',
177 info => 'Get Audiobook Chapters',
178 type => 'GET',
179 method => 'get_audiobook_chapters',
180 params => [ 'id', 'market', 'limit', 'offset' ]
181 },
182  
183 {
184 path => '/v1/me/audiobooks',
185 info => 'Get User\'s Saved Audiobooks',
186 type => 'GET',
187 method => 'get_users_saved_audiobooks',
188 params => [ 'limit', 'offset' ]
189 },
190  
191 {
192 path => '/v1/me/shows',
193 info => 'Get User\'s Saved Shows',
194 type => 'GET',
195 method => 'get_users_saved_shows',
196 params => [ 'limit', 'offset' ]
197 },
198  
199 {
200 path => '/v1/chapters/{id}',
201 info => 'Get a Chapter',
202 type => 'GET',
203 method => 'get_chapter',
204 params => [ 'id', 'market' ]
205 },
206  
207 {
208 path => '/v1/markets',
209 info => 'Get Available Markets',
210 type => 'GET',
211 method => 'get_available_markets'
212 },
213  
214 {
215 path => '/v1/shows/{id}',
216 info => 'Get a Show',
217 type => 'GET',
218 method => 'get_show',
219 params => ['market']
220 },
221  
222 {
223 path => '/v1/shows/{id}/episodes',
224 info => 'Get Show Episodes',
225 type => 'GET',
226 method => 'get_show_episodes',
227 params => [ 'id', 'market', 'limit', 'offset' ]
228 },
229  
230 {
231 path => '/v1/playlists/{playlist_id}',
232 info => 'Get a playlist',
233 type => 'GET',
234 method => 'get_playlist'
235 },
236  
237 {
238 path => '/v1/playlists/{playlist_id}/items',
239 info => 'Get playlist items',
240 type => 'GET',
241 method => 'get_playlist_items',
242 params => [ 'limit', 'offset', 'market', 'fields' ]
243 },
244  
245 {
246 path => '/v1/me/playlists',
247 info => 'Create a playlist for the current user',
248 type => 'POST',
249 method => 'create_playlist'
250 },
251  
252 {
253 path => '/v1/me/playlists',
254 info => 'Get current user\'s playlists',
255 type => 'GET',
256 method => 'get_current_user_playlists',
257 params => [ 'limit', 'offset' ]
258 },
259  
260 {
261 path => '/v1/playlists/{playlist_id}/items',
262 info => 'Add items to a playlist',
263 type => 'POST',
264 method => 'add_items_to_playlist'
265 },
266  
267 {
268 path => '/v1/playlists/{playlist_id}/followers',
269 info => 'Unfollow (remove) a playlist',
270 type => 'DELETE',
271 method => 'unfollow_playlist'
272 },
273  
274 {
275 path => '/v1/me/following',
276 info => 'Get Followed Artists',
277 type => 'GET',
278 method => 'get_followed_artists',
279 params => [ 'type', 'after', 'limit' ]
280 },
281  
282 {
283 path => '/v1/albums/{id}/tracks',
284 info => q{Get an album's tracks},
285 type => 'GET',
286 method => 'albums_tracks'
287 },
288  
289 {
290 path => '/v1/artists/{id}',
291 info => 'Get an artist',
292 type => 'GET',
293 method => 'artist'
294 },
295  
296 {
297 path => '/v1/artists/{id}/albums',
298 info => q{Get an artist's albums},
299 type => 'GET',
300 method => 'artist_albums',
301 params => [ 'limit', 'offset', 'country', 'album_type' ]
302 },
303  
304 # adding q and type to url unlike example since they are both required
305 {
306 path => '/v1/search?q={q}&type={type}',
307 info => 'Search for an item',
308 type => 'GET',
309 method => 'search',
310 params => [ 'limit', 'offset', 'q', 'type' ]
311 },
312  
313 {
314 path => '/v1/tracks/{id}',
315 info => 'Get a track',
316 type => 'GET',
317 method => 'track'
318 },
319  
320 {
321 path => '/v1/me',
322 info => q{Get current user's profile},
323 type => 'GET',
324 method => 'me'
325 },
326  
327 # February 2026 consolidated library endpoints. These take Spotify
328 # URIs (spotify:track:{id}, spotify:show:{id}, ...) rather than bare
329 # ids, passed as a "uris" query parameter on every verb.
330 {
331 path => '/v1/me/library?uris={uris}',
332 info => 'Save Items to Library',
333 type => 'PUT',
334 method => 'save_library_items',
335 params => ['uris']
336 },
337  
338 {
339 path => '/v1/me/library?uris={uris}',
340 info => 'Remove Items from Library',
341 type => 'DELETE',
342 method => 'remove_library_items',
343 params => ['uris']
344 },
345  
346 {
347 path => '/v1/me/library/contains?uris={uris}',
348 info => 'Check Items in Library',
349 type => 'GET',
350 method => 'check_library_items',
351 params => ['uris']
352 },
353 );
354  
355 6 my %method_to_uri = map { $_->{method} => $_->{path} } @api_call_options;
356  
357 # _build_url: construct the request URL from an attributes hashref.
358 #
359 # For send_get_request the URL-building logic is richer (query_full_url
360 # passthrough, search substitution, extras appended as query params). That
361 # full logic stays in send_get_request. _build_url handles the simpler
362 # pattern shared by POST / PUT / DELETE.
363 13 ▶sub _build_url {
Subroutine _build_url: called CC=8 SCAR=21.3
364 13 my ( $self, $attributes ) = @_;
365  
366 13 my $url = $self->uri_scheme() . '://' . $self->uri_hostname();
367 13 my $path = $method_to_uri{ $attributes->{method} };
368  
369 # Params consumed by a {placeholder} in the path are removed from
370 # %unused so the request body only carries what the URL did not.
371 13 ▶ my %unused = %{ $attributes->{params} || {} };
Condition50%1/2
$attributes->{'params'} || {}
l!l
130
MC/DC0%0/1
$attributes->{'params'} || {}
$attributes->{'params'}
Truth table50%1/2
A
A= $attributes->{'params'}
Aresult
11
00
372  
373 13 ▶ if ($path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path) 13 0 13
374 13 my ( $path_part, $query_part ) = split /\?/, $path, 2;
375  
376 # Path-segment placeholders: fully escape the value.
377 13 $path_part =~ s/\{([^}]+)\}/
378 6 my $v = delete $unused{$1};
379 6 ▶ defined $v ? uri_escape($v) : q{}
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 6 0 6
380 /ge;
381  
382 13 ▶ if ( defined $query_part ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_part) { } 4 9 13
383  
384 # Query-string placeholders: substitute raw. Callers are
385 # responsible for any encoding needed (e.g. _uris_param pre-escapes
386 # Spotify URIs; search() pre-escapes q and type).
387 4 $query_part =~ s/\{([^}]+)\}/
388 4 my $v = delete $unused{$1};
389 4 ▶ defined $v ? $v : q{}
Branch: 1 branch
BranchTrueFalseTotal
defined $v ? : 4 0 4
390 /ge;
391 4 $path = $path_part . '?' . $query_part;
392 }
393 else {
394 9 $path = $path_part;
395 }
396  
397 13 $url .= $path;
398 }
399  
400 13 ▶ warn "$url\n" if $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 13 13
401 13 ▶ return wantarray ? ( $url, \%unused ) : $url;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 13 0 13
402 }
403  
404 # _send_request: shared machinery for every HTTP verb.
405 #
406 # Parameters:
407 # $verb - 'get' | 'post' | 'put' | 'delete'
408 # $url - fully-formed request URL
409 # $attributes - original attributes hashref
410 # $body - optional request body (undef for GET)
411 #
412 # Returns the HTTP::Response.
413 36 ▶sub _send_request {
Subroutine _send_request: called CC=7 SCAR=19.9
414 36 my ( $self, $verb, $url, $attributes, $body ) = @_;
415  
416 36 ▶ if ( $self->current_access_token() eq q{}
Branch: 1 branch
BranchTrueFalseTotal
if ($self->current_access_token eq "" or time >= $self->token_expires_at) 1 35 36
Condition66%2/3
$self->current_access_token eq "" or time >= $self->token_expires_at
l!l&&r!l&&!r
0135
MC/DC50%1/2
$self->current_access_token eq "" or time >= $self->token_expires_at
$self->current_access_token eq "" time >= $self->token_expires_at
Truth table66%2/3
A or B
A= $self->current_access_token eq ""B= time >= $self->token_expires_at
ABresult
1X1
011
000
417 || time() >= $self->token_expires_at() ) {
418 1 ▶ warn "Needed to get access token\n" if $self->debug();
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 1 1
419 1 $self->current_access_token(q{});
420 1 $self->get_client_credentials();
421 }
422  
423 my @headers
424 36 = ( Authorization => 'Bearer ' . $self->current_access_token() );
425 36 ▶ push @headers, 'Content-Type' => 'application/json', Content => $body
Branch: 1 branch
BranchTrueFalseTotal
if defined $body 7 29 36
426 if defined $body;
427  
428 36 my $res = $self->ua->$verb( $url, @headers );
429  
430 36 ▶ $self->response_headers( $res->headers->as_string )
Branch: 1 branch
BranchTrueFalseTotal
if $self->grab_response_header 0 36 36
431 if $self->grab_response_header();
432 36 $self->response_status( $res->code );
433 36 $self->response_content_type( scalar $res->content_type );
434  
435 36 ▶ if ( $self->_has_custom_request_handler() ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_has_custom_request_handler) 0 36 36
436 0 $self->_set_custom_request_handler_result(
437 $self->custom_request_handler()->($res) );
438 }
439  
440 36 return $res;
441 }
442  
443 36 ▶sub _finish_request {
Subroutine _finish_request: called CC=3 SCAR=11.0
444 36 my ( $self, $res ) = @_;
445  
446 36 ▶ if ( $self->die_on_response_error() && $self->last_error ne '' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->die_on_response_error and $self->last_error ne "") 2 34 36
Condition66%2/3
$self->die_on_response_error and $self->last_error ne ""
!ll&&!rl&&r
3402
MC/DC50%1/2
$self->die_on_response_error and $self->last_error ne ""
$self->die_on_response_error $self->last_error ne ""
Truth table66%2/3
A and B
A= $self->die_on_response_errorB= $self->last_error ne ""
ABresult
0X0
100
111
447 2 die $self->last_error();
448 }
449  
450 34 return $self->format_results(
451 $res->decoded_content( charset => 'none' ) );
452 }
453  
454 # POST / PUT / DELETE: params not consumed by the URL path go in a JSON body.
455 13 ▶sub _send_body_request {
Subroutine _send_body_request: called CC=4 SCAR=13.9
456 13 my ( $self, $verb, $attributes ) = @_;
457  
458 13 $self->last_error(q{});
459  
460 13 my ( $url, $body_params ) = $self->_build_url($attributes);
461 13 ▶ my $body = %{$body_params} ? encode_json($body_params) : undef;
Branch: 1 branch
BranchTrueFalseTotal
%{$body_params;} ? : 7 6 13
462 13 my $res = $self->_send_request( $verb, $url, $attributes, $body );
463  
464 13 ▶ if ( !is_success( $self->response_status() ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless (&is_success(scalar $self->response_status)) 1 12 13
465 1 ▶ warn "\u$verb request failed with status ",
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 1 1
466 $self->response_status(), "\n"
467 if $self->debug();
468 1 $self->last_error( "\u$verb request failed, status("
469 . $self->response_status()
470 . ") examine last_result for details" );
471 }
472  
473 13 return $self->_finish_request($res);
474 }
475  
476 7 ▶sub send_post_request { $_[0]->_send_body_request( post => $_[1] ) }
Subroutine send_post_request: called CC=1 SCAR=0.0
Pod undocumented
477 2 ▶sub send_put_request { $_[0]->_send_body_request( put => $_[1] ) }
Subroutine send_put_request: called CC=1 SCAR=0.0
Pod documented
478 4 ▶sub send_delete_request { $_[0]->_send_body_request( delete => $_[1] ) }
Subroutine send_delete_request: called CC=1 SCAR=0.0
Pod documented
479  
480 23 ▶sub send_get_request {
Subroutine send_get_request: called CC=16 SCAR=27.9
Pod undocumented
481  
482 # need to build the URL here
483 23 my ( $self, $attributes ) = @_;
484  
485 23 my $uri_params = q{};
486  
487 # reset last error
488 23 $self->last_error(q{});
489  
490 23 ▶ if ( defined $attributes->{extras}
Branch: 1 branch
BranchTrueFalseTotal
if (defined $attributes->{"extras"} and ref $attributes->{"extras"} eq "HASH") 4 19 23
Condition66%2/3
defined $attributes->{"extras"} and ref $attributes->{"extras"} eq "HASH"
!ll&&!rl&&r
1904
MC/DC50%1/2
defined $attributes->{"extras"} and ref $attributes->{"extras"} eq "HASH"
defined $attributes->{"extras"} ref $attributes->{"extras"} eq "HASH"
Truth table66%2/3
A and B
A= defined $attributes->{"extras"}B= ref $attributes->{"extras"} eq "HASH"
ABresult
0X0
100
111
491 and ref $attributes->{extras} eq 'HASH' ) {
492 4 my @tmp = ();
493  
494 4 foreach my $key ( keys %{ $attributes->{extras} } ) {
495 push @tmp,
496 8 "$key=" . uri_escape_utf8( $attributes->{extras}{$key} );
497 }
498 4 $uri_params = join( '&', @tmp );
499 }
500  
501 23 my $url;
502 23 ▶ if ( $attributes->{method} eq 'query_full_url' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attributes->{'method'} eq 'query_full_url') { } 2 21 23
503 2 $url = $attributes->{url};
504 }
505 else {
506 21 $url = $self->uri_scheme() . '://' . $self->uri_hostname();
507  
508 21 my $path = $method_to_uri{ $attributes->{method} };
509 21 ▶ if ($path) {
Branch: 1 branch
BranchTrueFalseTotal
if ($path) 21 0 21
510  
511 21 ▶ warn "raw: $path" if $self->debug();
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 21 21
512  
513 21 ▶ if ( $attributes->{params} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($attributes->{"params"}) 20 1 21
514  
515 # Split on '?' so we only uri_escape values that appear in the
516 # path segment. Query-string placeholder values (comma-lists,
517 # pre-escaped URIs, etc.) must be left as-is.
518 20 my ( $path_part, $query_part ) = split /\?/, $path, 2;
519  
520 20 $path_part
521 14 =~ s/\{([^}]+)\}/uri_escape( $attributes->{params}{$1} )/ge;
522  
523 20 ▶ if ( defined $query_part ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $query_part) { } 3 17 20
524  
525 # Substitute raw - callers pre-escape what needs escaping.
526 3 $query_part =~ s/\{([^}]+)\}/$attributes->{params}{$1}/ge;
527 3 $path = $path_part . '?' . $query_part;
528 }
529 else {
530 17 $path = $path_part;
531 }
532 }
533  
534 21 ▶ warn "modified: $path\n" if $self->debug();
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 21 21
535 }
536  
537 21 $url .= $path;
538 }
539  
540 # append "extras" as query params if present
541 23 ▶ if ($uri_params) {
Branch: 1 branch
BranchTrueFalseTotal
if ($uri_params) 4 19 23
542 4 ▶ my $start_with = $url =~ /\?/ ? '&' : '?';
Branch: 1 branch
BranchTrueFalseTotal
$url =~ /\?/ ? : 1 3 4
543 4 $url .= $start_with . $uri_params;
544 }
545  
546 23 ▶ warn "$url\n" if $self->debug;
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 23 23
547  
548 23 my $res = $self->_send_request( 'get', $url, $attributes, undef );
549  
550 # the original code did not provide adequate built in validation
551 # of the response for an API call.
552 # Adding a new method (die_on_response_error) with a default of 0 to avoid
553 # breaking/changing existing code using older versions of this module.
554 23 ▶ if ( $self->response_content_type() =~ /application\/json/i
Branch: 1 branch
BranchTrueFalseTotal
if ($self->response_content_type =~ m[application/json]i and $self->response_status != 200) 1 22 23
Condition66%2/3
$self->response_content_type =~ m[application/json]i and $self->response_status != 200
!ll&&!rl&&r
0221
MC/DC50%1/2
$self->response_content_type =~ m[application/json]i and $self->response_status != 200
$self->response_content_type =~ m[application/json]i $self->response_status != 200
Truth table66%2/3
A and B
A= $self->response_content_type =~ m[application/json]iB= $self->response_status != 200
ABresult
0X0
100
111
555 && $self->response_status() != HTTP_OK ) {
556 1 ▶ warn "content type is ", $self->response_content_type(), "\n"
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 1 1
557 if $self->debug();
558 1 $self->last_error( "request failed, status("
559 . $self->response_status()
560 . ") examine last_result for details" );
561 }
562  
563 23 return $self->_finish_request($res);
564 }
565  
566 34 ▶sub format_results {
Subroutine format_results: called CC=3 SCAR=11.0
Pod undocumented
567 34 my $self = shift;
568 34 my $content = shift;
569  
570 # want to store the result in case
571 # we want to interact with it via a helper method
572 34 $self->last_result($content);
573  
574 34 ▶ if ( $self->auto_json_decode ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->auto_json_decode) 2 32 34
575 2 my $decoded = eval { decode_json($content) };
576 2 ▶ die "format_results: last_result is not valid JSON: $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 1 2
577 1 return $decoded;
578 }
579  
580 # results are not altered in this case and would be
581 # json instead of a perl data structure
582  
583 32 return $content;
584 }
585  
586 5 ▶sub get_client_credentials {
Subroutine get_client_credentials: called CC=6 SCAR=19.2
Pod undocumented
587 5 my $self = shift;
588 5 my $scope = shift;
589  
590 5 ▶ if ( $self->current_access_token() ne q{} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->current_access_token ne "") 0 5 5
591 0 return $self->current_access_token();
592 }
593 5 ▶ if ( $self->oauth_client_id() eq q{} ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->oauth_client_id eq "") 0 5 5
594 0 die "need to set the client oauth parameters\n";
595 }
596  
597 5 my $form = { grant_type => 'client_credentials' };
598 5 ▶ $form->{scope} = $scope if $scope;
Branch: 1 branch
BranchTrueFalseTotal
if $scope 0 5 5
599  
600 5 ▶ $self->_request_token($form)
Branch: 1 branch
BranchTrueFalseTotal
$self->_request_token($form) or die "get_client_credentials: failed to obtain access token\n" 3 1 4
601 or die "get_client_credentials: failed to obtain access token\n";
602 3 ▶ warn "setting access token\n" if $self->debug();
Branch: 1 branch
BranchTrueFalseTotal
if $self->debug 0 3 3
603 3 return $self->current_access_token();
604 }
605  
606 2 ▶sub authorize_url {
Subroutine authorize_url: called CC=4 SCAR=13.9
Pod documented
607 2 my ( $self, $args ) = @_;
608 2 ▶ $args ||= {};
Condition100%2/2
$args ||= {}
l!l
11
MC/DC100%1/1
$args ||= {}
$args
Truth table100%2/2
A
A= $args
Aresult
11
00
609  
610 2 my @parts = (
611 'client_id=' . uri_escape( $self->oauth_client_id() ),
612 'response_type=code',
613 'redirect_uri=' . uri_escape( $self->oauth_redirect_uri() ),
614 );
615 2 ▶ push @parts, 'scope=' . uri_escape( $args->{scope} ) if $args->{scope};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"scope"} 1 1 2
616 2 ▶ push @parts, 'state=' . uri_escape( $args->{state} ) if $args->{state};
Branch: 1 branch
BranchTrueFalseTotal
if $args->{"state"} 1 1 2
617  
618 2 return $self->oauth_authorize_url() . '?' . join '&', @parts;
619 }
620  
621 10 ▶sub _assert_token_url {
Subroutine _assert_token_url: called CC=2 SCAR=6.9
622 10 my ($self) = @_;
623 10 ▶ die "oauth_token_url '${\$self->oauth_token_url}' is not allowed - "
Branch: 1 branch
BranchTrueFalseTotal
unless $self->oauth_token_url =~ m[\Ahttps://accounts\.spotify\.com/]i 2 8 10
624 . "only https://accounts.spotify.com/ URLs are permitted\n"
625 unless $self->oauth_token_url
626 =~ m{\Ahttps://accounts\.spotify\.com/}i;
627 }
628  
629 10 ▶sub _request_token {
Subroutine _request_token: called CC=5 SCAR=16.1
630 10 my ( $self, $form ) = @_;
631  
632 10 $self->_assert_token_url();
633  
634 8 my $encoded = encode_base64(
635 $self->oauth_client_id() . ':' . $self->oauth_client_secret(), q{} );
636  
637 8 my $res = $self->ua->post(
638 $self->oauth_token_url(), $form,
639 Authorization => 'Basic ' . $encoded
640 );
641  
642 8 my $result = eval { decode_json( $res->content ) };
643  
644 8 ▶ return 0 unless $result && $result->{access_token};
Branch: 1 branch
BranchTrueFalseTotal
unless $result and $result->{"access_token"} 2 6 8
Condition66%2/3
$result and $result->{"access_token"}
!ll&&!rl&&r
026
MC/DC50%1/2
$result and $result->{"access_token"}
$result $result->{"access_token"}
Truth table66%2/3
A and B
A= $resultB= $result->{"access_token"}
ABresult
0X0
100
111
645  
646 6 $self->current_access_token( $result->{access_token} );
647 $self->token_expires_at( time() + $result->{expires_in} )
648 6 ▶ if $result->{expires_in};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"expires_in"} 6 0 6
649 $self->refresh_token( $result->{refresh_token} )
650 6 ▶ if $result->{refresh_token};
Branch: 1 branch
BranchTrueFalseTotal
if $result->{"refresh_token"} 2 4 6
651  
652 6 return 1;
653 }
654  
655 3 ▶sub get_access_token {
Subroutine get_access_token: called CC=3 SCAR=12.5
Pod documented
656 3 my ( $self, $code ) = @_;
657  
658 3 ▶ die "get_access_token requires an authorization code\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $code and length $code 0 3 3
Condition33%1/3
defined $code and length $code
!ll&&!rl&&r
003
MC/DC0%0/2
defined $code and length $code
defined $code length $code
Truth table33%1/3
A and B
A= defined $codeB= length $code
ABresult
0X0
100
111
659 unless defined $code && length $code;
660  
661 3 return $self->_request_token(
662 {
663 grant_type => 'authorization_code',
664 code => $code,
665 redirect_uri => $self->oauth_redirect_uri(),
666 }
667 );
668 }
669  
670 3 ▶sub refresh_access_token {
Subroutine refresh_access_token: called CC=2 SCAR=6.9
Pod documented
671 3 my $self = shift;
672  
673 3 ▶ die "refresh_access_token requires a stored refresh token\n"
Branch: 1 branch
BranchTrueFalseTotal
unless $self->refresh_token 1 2 3
674 unless $self->refresh_token();
675  
676 2 return $self->_request_token(
677 {
678 grant_type => 'refresh_token',
679 refresh_token => $self->refresh_token(),
680 }
681 );
682 }
683  
684 4 ▶sub get {
Subroutine get: called CC=7 SCAR=20.1
Pod documented
685  
686 # This seemed like a simple enough method
687 # but everything I tried resulted in unacceptable
688 # trade offs and explict defining of the structures
689 # The new method, which I hope I remember when I
690 # revisit it, was to use JSON::Path
691 # It is an awesome module, but a little heavy
692 # on dependencies. However I would not have been
693 # able to do this in so few lines without it
694  
695 # Making a generalization here
696 # if you use a * you are looking for an array
697 # if you don't have an * you want the first 1 (or should I say you get the first 1)
698  
699 4 my ( $self, @return ) = @_;
700  
701 4 my @out;
702  
703 4 ▶ die "get(): no result available - make an API call first\n"
Branch: 1 branch
BranchTrueFalseTotal
unless length $self->last_result 1 3 4
704 unless length $self->last_result();
705  
706 3 my $result = eval { decode_json( $self->last_result() ) };
707 3 ▶ die "get(): last_result is not valid JSON: $@\n" if $@;
Branch: 1 branch
BranchTrueFalseTotal
if $@ 1 2 3
708  
709 2 my $search_ref = $result;
710  
711 2 foreach my $key (@return) {
712 2 my $type = 'value';
713 2 ▶ if ( $key =~ /\*\]/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($key =~ /\*\]/) 0 2 2
714 0 $type = 'values';
715 }
716  
717 2 my $jpath = JSON::Path->new("\$.$key");
718  
719 2 my @t_arr = $jpath->$type($result);
720  
721 2 ▶ if ( $type eq 'value' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq 'value') { } 2 0 2
722 2 push @out, $t_arr[0];
723 }
724 else {
725 0 push @out, \@t_arr;
726 }
727 }
728 2 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 2 2
729 0 return @out;
730 }
731 else {
732 2 return $out[0];
733 }
734  
735 }
736  
737 3 ▶sub query_full_url {
Subroutine query_full_url: called CC=2 SCAR=6.9
Pod documented
738 3 my ( $self, $url ) = @_;
739  
740 # Prevent bearer-token leakage to off-origin hosts. All Spotify API
741 # responses that contain URLs (next/previous paging, href fields) point to
742 # api.spotify.com; anything else is unexpected and potentially malicious.
743 3 ▶ die "query_full_url: URL '$url' is not allowed - "
Branch: 1 branch
BranchTrueFalseTotal
unless $url =~ m[\Ahttps://api\.spotify\.com/]i 2 1 3
744 . "only https://api.spotify.com/ URLs may be called with credentials\n"
745 unless $url =~ m{\Ahttps://api\.spotify\.com/}i;
746  
747 1 return $self->send_get_request(
748 { method => 'query_full_url', url => $url } );
749 }
750  
751 #-- spotify specific methods
752  
753 4 ▶sub album {
Subroutine album: called CC=3 SCAR=11.0
Pod documented
754 4 my $self = shift;
755 4 my $id = shift;
756  
757 4 ▶ die "album id is required\n" unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 2 2 4
Condition100%3/3
defined $id and length $id
!ll&&!rl&&r
112
MC/DC100%2/2
defined $id and length $id
defined $id length $id
Truth table100%3/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
758  
759 2 return $self->send_get_request(
760 {
761 method => 'album',
762 params => { 'id' => $id },
763 }
764 );
765 }
766  
767 3 ▶sub albums_tracks {
Subroutine albums_tracks: called CC=3 SCAR=11.0
Pod documented
768 3 my $self = shift;
769 3 my $album_id = shift;
770 3 my $extras = shift;
771  
772 3 ▶ die "album_id is required\n" unless defined $album_id && length $album_id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $album_id and length $album_id 2 1 3
Condition100%3/3
defined $album_id and length $album_id
!ll&&!rl&&r
111
MC/DC100%2/2
defined $album_id and length $album_id
defined $album_id length $album_id
Truth table100%3/3
A and B
A= defined $album_idB= length $album_id
ABresult
0X0
100
111
773  
774 1 return $self->send_get_request(
775 {
776 method => 'albums_tracks',
777 params => { 'id' => $album_id },
778 extras => $extras,
779 }
780 );
781  
782 }
783  
784 3 ▶sub artist {
Subroutine artist: called CC=3 SCAR=11.0
Pod documented
785 3 my $self = shift;
786 3 my $id = shift;
787  
788 3 ▶ die "artist id is required\n" unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 2 1 3
Condition100%3/3
defined $id and length $id
!ll&&!rl&&r
111
MC/DC100%2/2
defined $id and length $id
defined $id length $id
Truth table100%3/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
789  
790 1 return $self->send_get_request(
791 {
792 method => 'artist',
793 params => { 'id' => $id },
794 }
795 );
796  
797 }
798  
799 2 ▶sub artist_albums {
Subroutine artist_albums: called CC=3 SCAR=11.0
Pod documented
800 2 my $self = shift;
801 2 my $artist_id = shift;
802 2 my $extras = shift;
803  
804 2 ▶ die "artist_id is required\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $artist_id and length $artist_id 1 1 2
Condition66%2/3
defined $artist_id and length $artist_id
!ll&&!rl&&r
101
MC/DC50%1/2
defined $artist_id and length $artist_id
defined $artist_id length $artist_id
Truth table66%2/3
A and B
A= defined $artist_idB= length $artist_id
ABresult
0X0
100
111
805 unless defined $artist_id && length $artist_id;
806  
807 1 return $self->send_get_request(
808 {
809 method => 'artist_albums',
810 params => { 'id' => $artist_id },
811 extras => $extras,
812 }
813 );
814  
815 }
816  
817 0 ▶sub me {
Subroutine me: not called CC=1 SCAR=6.9
Pod undocumented
818 0 my $self = shift;
819 0 return $self->send_get_request(
820 {
821 method => 'me',
822 }
823 );
824 }
825  
826 1 ▶sub next_result_set {
Subroutine next_result_set: called CC=4 SCAR=16.4
Pod undocumented
827 1 my $self = shift;
828 1 my $url = $self->get('next');
829 1 ▶ return unless defined $url && $url ne 'null' && $url ne q{};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and $url ne "null" and $url ne "" 0 1 1
Condition33%2/6
defined $url and $url ne "null" and $url ne ""
!ll&&!rl&&r
001
defined $url and $url ne "null"
!ll&&!rl&&r
001
MC/DC0%0/3
defined $url and $url ne "null" and $url ne ""
defined $url $url ne "null" $url ne ""
Truth table25%1/4
A and B and C
A= defined $urlB= $url ne "null"C= $url ne ""
ABCresult
0XX0
10X0
1100
1111
830 1 return $self->query_full_url($url);
831 }
832  
833 0 ▶sub previous_result_set {
Subroutine previous_result_set: not called CC=4 SCAR=30.0
Pod undocumented
834 0 my $self = shift;
835 0 my $url = $self->get('previous');
836 0 ▶ return unless defined $url && $url ne 'null' && $url ne q{};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $url and $url ne "null" and $url ne "" 0 0 0
Condition0%0/6
defined $url and $url ne "null" and $url ne ""
!ll&&!rl&&r
000
defined $url and $url ne "null"
!ll&&!rl&&r
000
MC/DC0%0/3
defined $url and $url ne "null" and $url ne ""
defined $url $url ne "null" $url ne ""
Truth table0%0/4
A and B and C
A= defined $urlB= $url ne "null"C= $url ne ""
ABCresult
0XX0
10X0
1100
1111
837 0 return $self->query_full_url($url);
838 }
839  
840 6 ▶sub search {
Subroutine search: called CC=5 SCAR=16.1
Pod documented
841 6 my $self = shift;
842 6 my $q = shift;
843 6 my $type = shift;
844 6 my $extras = shift;
845  
846 6 ▶ die "search query (q) is required\n" unless defined $q && length $q;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $q and length $q 2 4 6
Condition100%3/3
defined $q and length $q
!ll&&!rl&&r
114
MC/DC100%2/2
defined $q and length $q
defined $q length $q
Truth table100%3/3
A and B
A= defined $qB= length $q
ABresult
0X0
100
111
847 4 ▶ die "search type is required\n" unless defined $type && length $type;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $type and length $type 2 2 4
Condition100%3/3
defined $type and length $type
!ll&&!rl&&r
112
MC/DC100%2/2
defined $type and length $type
defined $type length $type
Truth table100%3/3
A and B
A= defined $typeB= length $type
ABresult
0X0
100
111
848  
849 2 my $response = $self->send_get_request(
850 {
851 method => 'search',
852 params => {
853 q => uri_escape_utf8($q),
854 type => uri_escape_utf8($type),
855 },
856 extras => $extras,
857 }
858 );
859  
860 2 return $response;
861 }
862  
863 2 ▶sub track {
Subroutine track: called CC=3 SCAR=11.0
Pod documented
864 2 my $self = shift;
865 2 my $id = shift;
866  
867 2 ▶ die "track id is required\n" unless defined $id && length $id;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $id and length $id 1 1 2
Condition66%2/3
defined $id and length $id
!ll&&!rl&&r
101
MC/DC50%1/2
defined $id and length $id
defined $id length $id
Truth table66%2/3
A and B
A= defined $idB= length $id
ABresult
0X0
100
111
868  
869 1 return $self->send_get_request(
870 {
871 method => 'track',
872 params => { 'id' => $id }
873 }
874 );
875 }
876  
877 1 ▶sub get_playlist {
Subroutine get_playlist: called CC=3 SCAR=14.2
Pod documented
878 1 my ( $self, $playlist_id ) = @_;
879  
880 1 ▶ die "playlist_id is required\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $playlist_id and length $playlist_id 1 0 1
Condition33%1/3
defined $playlist_id and length $playlist_id
!ll&&!rl&&r
100
MC/DC0%0/2
defined $playlist_id and length $playlist_id
defined $playlist_id length $playlist_id
Truth table33%1/3
A and B
A= defined $playlist_idB= length $playlist_id
ABresult
0X0
100
111
881 unless defined $playlist_id && length $playlist_id;
882  
883 0 return $self->send_get_request(
884 {
885 method => 'get_playlist',
886 params => { 'playlist_id' => $playlist_id },
887 }
888 );
889 }
890  
891 2 ▶sub get_playlist_items {
Subroutine get_playlist_items: called CC=3 SCAR=11.0
Pod documented
892 2 my ( $self, $playlist_id, $extras ) = @_;
893  
894 2 ▶ die "playlist_id is required\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $playlist_id and length $playlist_id 1 1 2
Condition66%2/3
defined $playlist_id and length $playlist_id
!ll&&!rl&&r
101
MC/DC50%1/2
defined $playlist_id and length $playlist_id
defined $playlist_id length $playlist_id
Truth table66%2/3
A and B
A= defined $playlist_idB= length $playlist_id
ABresult
0X0
100
111
895 unless defined $playlist_id && length $playlist_id;
896  
897 1 return $self->send_get_request(
898 {
899 method => 'get_playlist_items',
900 params => { 'playlist_id' => $playlist_id },
901 extras => $extras
902 }
903 );
904 }
905  
906 2 ▶sub create_playlist {
Subroutine create_playlist: called CC=4 SCAR=13.9
Pod documented
907 2 my ( $self, $name, $public, $description ) = @_;
908  
909 2 my %params = ( 'name' => $name );
910 2 ▶ $params{public} = $public ? \1 : \0 if defined $public;
Branch: 2 branches
BranchTrueFalseTotal
if defined $public 2 0 2
$public ? : 1 1 2
911 2 ▶ $params{description} = $description if defined $description;
Branch: 1 branch
BranchTrueFalseTotal
if defined $description 1 1 2
912  
913 2 return $self->send_post_request(
914 {
915 method => 'create_playlist',
916 params => \%params
917 }
918 );
919 }
920  
921 1 ▶sub get_current_user_playlists {
Subroutine get_current_user_playlists: called CC=1 SCAR=0.0
Pod documented
922 1 my ( $self, $extras ) = @_;
923 1 return $self->send_get_request(
924 {
925 method => 'get_current_user_playlists',
926 extras => $extras
927 }
928 );
929 }
930  
931 5 ▶sub add_items_to_playlist {
Subroutine add_items_to_playlist: called CC=5 SCAR=16.1
Pod documented
932 5 my ( $self, $playlist_id, $uris, $position ) = @_;
933  
934 5 ▶ die "playlist_id is required\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $playlist_id and length $playlist_id 2 3 5
Condition100%3/3
defined $playlist_id and length $playlist_id
!ll&&!rl&&r
113
MC/DC100%2/2
defined $playlist_id and length $playlist_id
defined $playlist_id length $playlist_id
Truth table100%3/3
A and B
A= defined $playlist_idB= length $playlist_id
ABresult
0X0
100
111
935 unless defined $playlist_id && length $playlist_id;
936  
937 3 ▶ my %params = (
Branch: 1 branch
BranchTrueFalseTotal
ref $uris eq 'ARRAY' ? : 1 2 3
938 'playlist_id' => $playlist_id,
939 'uris' => ref $uris eq 'ARRAY' ? $uris : [$uris],
940 );
941 3 ▶ $params{position} = $position if defined $position;
Branch: 1 branch
BranchTrueFalseTotal
if defined $position 1 2 3
942  
943 3 return $self->send_post_request(
944 {
945 method => 'add_items_to_playlist',
946 params => \%params
947 }
948 );
949 }
950  
951 4 ▶sub unfollow_playlist {
Subroutine unfollow_playlist: called CC=3 SCAR=11.0
Pod documented
952 4 my ( $self, $playlist_id ) = @_;
953  
954 4 ▶ die "playlist_id is required\n"
Branch: 1 branch
BranchTrueFalseTotal
unless defined $playlist_id and length $playlist_id 2 2 4
Condition100%3/3
defined $playlist_id and length $playlist_id
!ll&&!rl&&r
112
MC/DC100%2/2
defined $playlist_id and length $playlist_id
defined $playlist_id length $playlist_id
Truth table100%3/3
A and B
A= defined $playlist_idB= length $playlist_id
ABresult
0X0
100
111
955 unless defined $playlist_id && length $playlist_id;
956  
957 2 return $self->send_delete_request(
958 {
959 method => 'unfollow_playlist',
960 params => { 'playlist_id' => $playlist_id }
961 }
962 );
963 }
964  
965 0 ▶sub get_followed_artists {
Subroutine get_followed_artists: not called CC=1 SCAR=6.9
Pod documented
966 0 my ( $self, %params ) = @_;
967  
968 # Ensure 'type' is set to 'artist' as it's the only supported value
969 0 $params{type} = 'artist';
970  
971 0 return $self->send_get_request(
972 {
973 method => 'get_followed_artists',
974 params => \%params,
975 }
976 );
977 }
978  
979 # Spotify URIs contain ':' and commas separate multiple items; both must be
980 # percent-encoded before being spliced into a query string by _build_url /
981 # send_get_request (which perform a raw substitution on the query part).
982 3 ▶sub _uris_param {
Subroutine _uris_param: called CC=2 SCAR=6.9
983 3 my $uris = shift;
984 3 ▶ $uris = join( ',', @{$uris} ) if ref $uris eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
if ref $uris eq "ARRAY" 2 1 3
985 3 return uri_escape($uris);
986 }
987  
988 1 ▶sub save_library_items {
Subroutine save_library_items: called CC=2 SCAR=7.1
Pod documented
989 1 my ( $self, $uris ) = @_;
990  
991 1 ▶ die "Spotify URIs are required" unless $uris;
Branch: 1 branch
BranchTrueFalseTotal
unless $uris 0 1 1
992  
993 1 return $self->send_put_request(
994 {
995 method => 'save_library_items',
996 params => { uris => _uris_param($uris) },
997 }
998 );
999 }
1000  
1001 1 ▶sub remove_library_items {
Subroutine remove_library_items: called CC=2 SCAR=7.1
Pod documented
1002 1 my ( $self, $uris ) = @_;
1003  
1004 1 ▶ die "Spotify URIs are required" unless $uris;
Branch: 1 branch
BranchTrueFalseTotal
unless $uris 0 1 1
1005  
1006 1 return $self->send_delete_request(
1007 {
1008 method => 'remove_library_items',
1009 params => { uris => _uris_param($uris) },
1010 }
1011 );
1012 }
1013  
1014 1 ▶sub check_library_items {
Subroutine check_library_items: called CC=2 SCAR=7.1
Pod documented
1015 1 my ( $self, $uris ) = @_;
1016  
1017 1 ▶ die "Spotify URIs are required" unless $uris;
Branch: 1 branch
BranchTrueFalseTotal
unless $uris 0 1 1
1018  
1019 1 return $self->send_get_request(
1020 {
1021 method => 'check_library_items',
1022 params => { uris => _uris_param($uris) },
1023 }
1024 );
1025 }
1026  
1027 0 ▶sub get_audiobook {
Subroutine get_audiobook: not called CC=3 SCAR=24.8
Pod documented
1028 0 my ( $self, $id, $market ) = @_;
1029  
1030 0 ▶ die "Audiobook ID is required" unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 0 0
1031  
1032 0 my $params = { id => $id };
1033 0 ▶ $params->{market} = $market if $market;
Branch: 1 branch
BranchTrueFalseTotal
if $market 0 0 0
1034  
1035 0 return $self->send_get_request(
1036 {
1037 method => 'get_audiobook',
1038 params => $params,
1039 }
1040 );
1041 }
1042  
1043 0 ▶sub get_audiobook_chapters {
Subroutine get_audiobook_chapters: not called CC=2 SCAR=17.9
Pod documented
1044 0 my ( $self, $id, %params ) = @_;
1045  
1046 0 ▶ die "Audiobook ID is required" unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 0 0
1047  
1048 0 $params{id} = $id;
1049  
1050 0 return $self->send_get_request(
1051 {
1052 method => 'get_audiobook_chapters',
1053 params => \%params,
1054 }
1055 );
1056 }
1057  
1058 0 ▶sub get_users_saved_audiobooks {
Subroutine get_users_saved_audiobooks: not called CC=3 SCAR=24.8
Pod documented
1059 0 my ( $self, $limit, $offset ) = @_;
1060  
1061 0 my $params = {};
1062 0 ▶ $params->{limit} = $limit if $limit;
Branch: 1 branch
BranchTrueFalseTotal
if $limit 0 0 0
1063 0 ▶ $params->{offset} = $offset if defined $offset;
Branch: 1 branch
BranchTrueFalseTotal
if defined $offset 0 0 0
1064  
1065 0 return $self->send_get_request(
1066 {
1067 method => 'get_users_saved_audiobooks',
1068 params => $params,
1069 }
1070 );
1071 }
1072  
1073 0 ▶sub get_users_saved_shows {
Subroutine get_users_saved_shows: not called CC=1 SCAR=6.9
Pod documented
1074 0 my ( $self, %params ) = @_;
1075  
1076 0 return $self->send_get_request(
1077 {
1078 method => 'get_users_saved_shows',
1079 params => \%params,
1080 }
1081 );
1082 }
1083  
1084 0 ▶sub get_chapter {
Subroutine get_chapter: not called CC=2 SCAR=17.9
Pod documented
1085 0 my ( $self, $id, %params ) = @_;
1086  
1087 0 ▶ die "Chapter ID is required" unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 0 0
1088  
1089 0 $params{id} = $id;
1090  
1091 0 return $self->send_get_request(
1092 {
1093 method => 'get_chapter',
1094 params => \%params,
1095 }
1096 );
1097 }
1098  
1099 0 ▶sub get_available_markets {
Subroutine get_available_markets: not called CC=1 SCAR=6.9
Pod documented
1100 0 my ($self) = @_;
1101  
1102 0 return $self->send_get_request(
1103 {
1104 method => 'get_available_markets',
1105 }
1106 );
1107 }
1108  
1109 0 ▶sub get_show {
Subroutine get_show: not called CC=3 SCAR=24.8
Pod documented
1110 0 my ( $self, $id, $market ) = @_;
1111  
1112 0 ▶ die "Show ID is required" unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 0 0
1113  
1114 0 my $params = { id => $id };
1115 0 ▶ $params->{market} = $market if $market;
Branch: 1 branch
BranchTrueFalseTotal
if $market 0 0 0
1116  
1117 0 return $self->send_get_request(
1118 {
1119 method => 'get_show',
1120 params => $params,
1121 }
1122 );
1123 }
1124  
1125 0 ▶sub get_show_episodes {
Subroutine get_show_episodes: not called CC=2 SCAR=17.9
Pod documented
1126 0 my ( $self, $id, %params ) = @_;
1127  
1128 0 ▶ die "Show ID is required" unless $id;
Branch: 1 branch
BranchTrueFalseTotal
unless $id 0 0 0
1129  
1130 0 $params{id} = $id;
1131  
1132 0 return $self->send_get_request(
1133 {
1134 method => 'get_show_episodes',
1135 params => \%params,
1136 }
1137 );
1138 }
1139  
1140 6 1;
1141  
1142 =pod
1143  
1144 =encoding UTF-8
1145  
1146 =head1 NAME
1147  
1148 WWW::Spotify - Spotify Web API Wrapper
1149  
1150 =head1 VERSION
1151  
1152 version 1.000
1153  
1154 =head1 SYNOPSIS
1155  
1156 use WWW::Spotify ();
1157  
1158 # client id and secret default to $ENV{SPOTIFY_CLIENT_ID} and
1159 # $ENV{SPOTIFY_CLIENT_SECRET}; every request sends a bearer token
1160 my $spotify = WWW::Spotify->new();
1161  
1162 my $result;
1163  
1164 $result = $spotify->album('0sNOF9WDwhWunNAHPD3Baj');
1165  
1166 # $result is a json structure, you can operate on it directly
1167 # or you can use the "get" method see below
1168  
1169 $result = $spotify->albums_tracks( '6akEvsycLGftJxYudPjmqK',
1170 {
1171 limit => 1,
1172 offset => 1
1173  
1174 }
1175 );
1176  
1177 $result = $spotify->artist( '0LcJLqbBmaGUft1e9Mm8HV' );
1178  
1179 $result = $spotify->artist_albums( '1vCWHaC5f2uS3yhpwWbIA6' ,
1180 { album_type => 'single',
1181 # country => 'US',
1182 limit => 2,
1183 offset => 0
1184 } );
1185  
1186 $result = $spotify->track( '0eGsygTp906u18L0Oimnem' );
1187  
1188 $result = $spotify->search(
1189 'tania bowra' ,
1190 'artist' ,
1191 { limit => 15 , offset => 0 }
1192 );
1193  
1194 my $names = $spotify->get('artists.items[*].name');
1195  
1196 # $names is an arrayref of every artist name in the search result
1197  
1198 # user-authorized (OAuth authorization code) flow: send the user to
1199 # authorize_url, exchange the returned code, then call /v1/me endpoints
1200  
1201 my $url = $spotify->authorize_url( { scope => 'playlist-read-private' } );
1202 my $code = 'CODE'; # the ?code= value Spotify appends to the redirect
1203 $spotify->get_access_token($code);
1204  
1205 $result = $spotify->get_current_user_playlists();
1206  
1207 my $link = $spotify->get('items[*].href');
1208  
1209 foreach my $playlist (@{$link}) {
1210 $spotify->query_full_url($playlist);
1211 my $pl_name = $spotify->get('name');
1212 print "$pl_name\n";
1213 }
1214  
1215 =head1 DESCRIPTION
1216  
1217 Wrapper for the Spotify Web API.
1218  
1219 https://developer.spotify.com/web-api/
1220  
1221 Have access to a JSON viewer to help develop and debug. The Chrome JSON viewer is
1222 very good and provides the exact path of the item within the JSON in the lower left
1223 of the screen as you mouse over an element.
1224  
1225 =head1 UPGRADING FROM 0.017 OR EARLIER
1226  
1227 Version 1.000 is a breaking release. Besides removing the methods for
1228 endpoints Spotify deleted in November 2024 and February 2026 (the full
1229 list with replacements is in the Changes file), three things changed
1230 that affect code calling the endpoints that survived:
1231  
1232 =over 4
1233  
1234 =item * force_client_auth, result_format, get_oauth_authorize
1235  
1236 Removed. Every request now sends a bearer token, so there is nothing
1237 to force. Passing C<force_client_auth> to C<new()> is silently ignored
1238 by Moo; calling it as a method dies. Use L</authorize_url> instead of
1239 C<get_oauth_authorize>.
1240  
1241 =item * custom_request_handler receives an HTTP::Response
1242  
1243 The callback used to get the WWW::Mechanize object. It now gets the
1244 L<HTTP::Response>, so C<< $m->status() >> becomes C<< $res->code >>
1245 and C<< $m->content() >> becomes C<< $res->decoded_content >>.
1246  
1247 =item * last_result holds UTF-8 bytes
1248  
1249 It was previously a character string. Decode it with
1250 L<JSON::MaybeXS/decode_json> (or set L</auto_json_decode>) rather than
1251 printing it to a C<:utf8> handle.
1252  
1253 =back
1254  
1255 =head1 CONSTRUCTOR ARGS
1256  
1257 =head2 ua
1258  
1259 You may provide your own user agent object to the constructor. This should be
1260 a L<LWP::UserAgent> or a subclass of it. To get extra debugging
1261 information, you can do something like this:
1262  
1263 use LWP::ConsoleLogger::Easy qw( debug_ua );
1264 use LWP::UserAgent ();
1265 use WWW::Spotify ();
1266  
1267 my $ua = LWP::UserAgent->new;
1268 debug_ua( $ua );
1269 my $spotify = WWW::Spotify->new( ua => $ua )
1270  
1271 =head1 METHODS
1272  
1273 =head2 auto_json_decode
1274  
1275 When true results will be returned as JSON instead of a perl data structure
1276  
1277 $spotify->auto_json_decode(1);
1278  
1279 =head2 get
1280  
1281 Returns a specific item or array of items from the JSON result of the
1282 last action.
1283  
1284 $result = $spotify->search(
1285 'tania bowra' ,
1286 'artist' ,
1287 { limit => 15 , offset => 0 }
1288 );
1289  
1290 my $image_url = $spotify->get( 'artists.items[0].images[0].url' );
1291  
1292 JSON::Path is the underlying library that actually parses the JSON.
1293  
1294 =head2 query_full_url( $url , [needs o_auth] )
1295  
1296 Results from some calls (playlist for example) return full urls that can be in their entirety. This method allows you
1297 make a call to that url and use all of the o_auth and other features provided.
1298  
1299 $spotify->query_full_url( "https://api.spotify.com/v1/users/spotify/playlists/06U6mm6KPtPIg9D4YGNEnu" , 1 );
1300  
1301 =head2 album
1302  
1303 equivalent to /v1/albums/{id}
1304  
1305 $spotify->album('0sNOF9WDwhWunNAHPD3Baj');
1306  
1307 used album vs albums since it is a singular request
1308  
1309 =head2 albums_tracks
1310  
1311 equivalent to /v1/albums/{id}/tracks
1312  
1313 $spotify->albums_tracks('6akEvsycLGftJxYudPjmqK',
1314 {
1315 limit => 1,
1316 offset => 1
1317  
1318 }
1319 );
1320  
1321 =head2 artist
1322  
1323 equivalent to /v1/artists/{id}
1324  
1325 $spotify->artist( '0LcJLqbBmaGUft1e9Mm8HV' );
1326  
1327 used artist vs artists since it is a singular request and avoids collision with "artists" method
1328  
1329 =head2 artist_albums
1330  
1331 equivalent to /v1/artists/{id}/albums
1332  
1333 $spotify->artist_albums( '1vCWHaC5f2uS3yhpwWbIA6' ,
1334 { album_type => 'single',
1335 # country => 'US',
1336 limit => 2,
1337 offset => 0
1338 } );
1339  
1340 =head2 search
1341  
1342 equivalent to /v1/search?type=album (etc)
1343  
1344 The query and any extras are UTF-8 encoded before escaping, so pass
1345 character strings (decoded text), not UTF-8 bytes.
1346  
1347 $spotify->search(
1348 'tania bowra' ,
1349 'artist' ,
1350 { limit => 10 , offset => 0 }
1351 );
1352  
1353 Note: as of the February 2026 API changes the maximum C<limit> is 10
1354 (previously 50); use C<offset> to paginate.
1355  
1356 =head2 track
1357  
1358 equivalent to /v1/tracks/{id}
1359  
1360 $spotify->track( '0eGsygTp906u18L0Oimnem' );
1361  
1362 =head2 get_playlist
1363  
1364 equivalent to GET /v1/playlists/{playlist_id}
1365  
1366 $spotify->get_playlist('37i9dQZF1DXcBWIGoYBM5M');
1367  
1368 This method retrieves a playlist owned by a Spotify user. The playlist must be public or owned by the authenticated user.
1369  
1370 =head2 get_playlist_items
1371  
1372 equivalent to /v1/playlists/{playlist_id}/items (renamed from /tracks in the
1373 February 2026 API changes)
1374  
1375 $spotify->get_playlist_items('37i9dQZF1DXcBWIGoYBM5M', { limit => 10, offset => 0 });
1376  
1377 =head2 create_playlist
1378  
1379 equivalent to POST /v1/me/playlists (replaced /v1/users/{user_id}/playlists
1380 in the February 2026 API changes) - creates a playlist for the
1381 authenticated user
1382  
1383 $spotify->create_playlist('My New Playlist', 1, 'A description of my playlist');
1384  
1385 =head2 get_current_user_playlists
1386  
1387 equivalent to /v1/me/playlists
1388  
1389 $spotify->get_current_user_playlists({ limit => 20, offset => 0 });
1390  
1391 =head2 add_items_to_playlist
1392  
1393 equivalent to /v1/playlists/{playlist_id}/items (renamed from /tracks in the
1394 February 2026 API changes)
1395  
1396 $spotify->add_items_to_playlist('playlist_id', ['spotify:track:4iV5W9uYEdYUVa79Axb7Rh', 'spotify:track:1301WleyT98MSxVHPZCA6M'], 0);
1397  
1398 =head2 unfollow_playlist
1399  
1400 equivalent to DELETE /v1/playlists/{playlist_id}/followers - removes the
1401 playlist from the authenticated user's library (Spotify has no hard
1402 playlist delete)
1403  
1404 $spotify->unfollow_playlist('playlist_id');
1405  
1406 =head2 get_followed_artists
1407  
1408 equivalent to /v1/me/following
1409  
1410 $spotify->get_followed_artists(
1411 limit => 20,
1412 after => '0I2XqVXqHScXjHhk6AYYRe'
1413 );
1414  
1415 Note: This method always sets the 'type' parameter to 'artist' as it's the only supported value.
1416  
1417 =head2 save_library_items
1418  
1419 equivalent to PUT /v1/me/library (February 2026 consolidated library
1420 endpoint; replaces the removed PUT /v1/me/tracks, /v1/me/albums,
1421 /v1/me/episodes, /v1/me/shows, /v1/me/audiobooks, /v1/me/following and
1422 /v1/playlists/{id}/followers endpoints)
1423  
1424 Takes Spotify URIs (not bare ids), as a comma-separated string or an
1425 array reference. Maximum 40 URIs.
1426  
1427 $spotify->save_library_items( [ 'spotify:track:7a3LWj5xSFhFRYmztS8wgK',
1428 'spotify:album:4aawyAB9vmqN3uQ7FjRGTy' ] );
1429  
1430 =head2 remove_library_items
1431  
1432 equivalent to DELETE /v1/me/library (February 2026 consolidated library
1433 endpoint; replaces the removed per-type DELETE endpoints)
1434  
1435 $spotify->remove_library_items( 'spotify:track:7a3LWj5xSFhFRYmztS8wgK' );
1436  
1437 =head2 check_library_items
1438  
1439 equivalent to GET /v1/me/library/contains (February 2026 consolidated
1440 library endpoint; replaces the removed per-type */contains endpoints)
1441  
1442 $spotify->check_library_items( [ 'spotify:track:7a3LWj5xSFhFRYmztS8wgK' ] );
1443  
1444 =head2 get_audiobook
1445  
1446 equivalent to GET /v1/audiobooks/{id}
1447  
1448 $spotify->get_audiobook('7iHfbu1YPACw6oZPAFJtqe');
1449  
1450 or with market parameter:
1451  
1452 $spotify->get_audiobook('7iHfbu1YPACw6oZPAFJtqe', 'US');
1453  
1454 =head2 get_users_saved_audiobooks
1455  
1456 equivalent to GET /v1/me/audiobooks
1457  
1458 $spotify->get_users_saved_audiobooks(20, 0);
1459  
1460 =head2 get_available_markets
1461  
1462 equivalent to GET /v1/markets
1463  
1464 $spotify->get_available_markets();
1465  
1466 This method retrieves the list of markets where Spotify is available.
1467  
1468 =head2 get_show
1469  
1470 equivalent to GET /v1/shows/{id}
1471  
1472 $spotify->get_show('38bS44xjbVVZ3No3ByF1dJ', 'US');
1473  
1474 This method retrieves Spotify catalog information for a single show identified by its unique Spotify ID.
1475  
1476 =head2 get_show_episodes
1477  
1478 equivalent to GET /v1/shows/{id}/episodes
1479  
1480 $spotify->get_show_episodes('38bS44xjbVVZ3No3ByF1dJ', market => 'US', limit => 10, offset => 5);
1481  
1482 This method retrieves Spotify catalog information about a show's episodes. Optional parameters can be used to limit the number of episodes returned.
1483  
1484 =head2 get_audiobook_chapters
1485  
1486 equivalent to GET /v1/audiobooks/{id}/chapters
1487  
1488 $spotify->get_audiobook_chapters('3ZXb8FKZGU0EHALYX6uCzU', market => 'US', limit => 50, offset => 0);
1489  
1490 This method retrieves the chapters of an audiobook.
1491  
1492 =head2 send_delete_request
1493  
1494 Internal method used to send DELETE requests to the Spotify API.
1495  
1496 =head2 send_put_request
1497  
1498 Internal method used to send PUT requests to the Spotify API.
1499  
1500 =head2 get_users_saved_shows
1501  
1502 equivalent to GET /v1/me/shows
1503  
1504 $spotify->get_users_saved_shows(limit => 20, offset => 0);
1505  
1506 This method retrieves a list of shows saved in the current Spotify user's library. Optional parameters can be used to limit the number of shows returned.
1507  
1508 =head2 get_chapter
1509  
1510 equivalent to GET /v1/chapters/{id}
1511  
1512 $spotify->get_chapter('0D5wENdkdwbqlrHoaJ9g29', market => 'US');
1513  
1514 =head2 oauth_client_id
1515  
1516 needed for requests that require OAuth, see Spotify API documentation for more information
1517  
1518 $spotify->oauth_client_id('2xfjijkcjidjkfdi');
1519  
1520 Can also be set via environment variable, SPOTIFY_CLIENT_ID
1521  
1522 =head2 oauth_client_secret
1523  
1524 needed for requests that require OAuth, see Spotify API documentation for more information
1525  
1526 $spotify->oauth_client_secret('2xfjijkcjidjkfdi');
1527  
1528 Can also be set via environment variable, SPOTIFY_CLIENT_SECRET
1529  
1530 =head2 authorize_url
1531  
1532 builds the URL to send a user to for the OAuth authorization-code flow.
1533 Uses C<oauth_client_id> and C<oauth_redirect_uri>; C<scope> and C<state>
1534 are optional
1535  
1536 my $url = $spotify->authorize_url({
1537 scope => 'user-read-private playlist-modify-private',
1538 state => $random_string,
1539 });
1540  
1541 Open the URL in a browser; after login Spotify redirects to
1542 C<oauth_redirect_uri> with a C<code> query parameter.
1543  
1544 =head2 get_access_token
1545  
1546 exchanges an authorization code (from the C<authorize_url> redirect) for
1547 a user access token. On success stores C<current_access_token>,
1548 C<refresh_token>, and C<token_expires_at>, and returns true
1549  
1550 $spotify->get_access_token($code);
1551  
1552 =head2 refresh_access_token
1553  
1554 fetches a new access token using the stored C<refresh_token> (set by
1555 C<get_access_token>). Dies if no refresh token is stored; returns true
1556 on success
1557  
1558 $spotify->refresh_access_token();
1559  
1560 =head2 refresh_token
1561  
1562 the OAuth refresh token, set automatically by C<get_access_token>. Can
1563 be set manually to restore a persisted session
1564  
1565 $spotify->refresh_token($saved_refresh_token);
1566  
1567 =head2 response_status
1568  
1569 returns the response code for the last request made
1570  
1571 my $status = $spotify->response_status();
1572  
1573 =head2 response_content_type
1574  
1575 returns the response type for the last request made, helpful to verify JSON
1576  
1577 my $content_type = $spotify->response_content_type();
1578  
1579 =head2 custom_request_handler
1580  
1581 pass a callback subroutine to this method that will be run at the end of the
1582 request prior to die_on_response_error, if enabled
1583  
1584 # $res is the HTTP::Response object
1585 $spotify->custom_request_handler(
1586 sub { my $res = shift;
1587 if ($res->code == 401) {
1588 return 1;
1589 }
1590 }
1591 );
1592  
1593 =head2 custom_request_handler_result
1594  
1595 returns the result of the most recent execution of the custom_request_handler callback
1596 this allows you to determine the success/failure criteria of your callback
1597  
1598 my $callback_result = $spotify->custom_request_handler_result();
1599  
1600 =head2 die_on_response_error
1601  
1602 Boolean - default 0
1603  
1604 added to provide minimal automated checking of responses
1605  
1606 $spotify->die_on_response_error(1);
1607  
1608 eval {
1609 # run assuming you do NOT have proper authentication setup
1610 $result = $spotify->album('0sNOF9WDwhWunNAHPD3Baj');
1611 };
1612  
1613 if ($@) {
1614 warn $spotify->last_error();
1615 }
1616  
1617 =head2 last_error
1618  
1619 returns last_error (if applicable) from the most recent request.
1620 reset to empty string on each request
1621  
1622 print $spotify->last_error() , "\n";
1623  
1624 =head1 THANKS
1625  
1626 Paul Lamere at The Echo Nest / Spotify
1627  
1628 All the great Perl community members that keep Perl fun
1629  
1630 Olaf Alders for all his help and support in maintaining this module
1631  
1632 =head1 AUTHOR
1633  
1634 Aaron Johnson <aaronjjohnson@gmail.com>
1635  
1636 =head1 COPYRIGHT AND LICENSE
1637  
1638 This software is copyright (c) 2024 by Aaron Johnson.
1639  
1640 This is free software; you can redistribute it and/or modify it under
1641 the same terms as the Perl 5 programming language system itself.
1642  
1643 =cut
1644  
1645 __END__
↑ Summary