forked from michaelherger/Spotty-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
API.pm
1544 lines (1218 loc) · 35 KB
/
API.pm
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
package Plugins::Spotty::API;
use strict;
use Exporter::Lite;
BEGIN {
use constant LIBRARY_LIMIT => 500;
use constant RECOMMENDATION_LIMIT => 100; # for whatever reason this call does support a maximum chunk size of 100
use constant DEFAULT_LIMIT => 200;
use constant MAX_LIMIT => 10_000;
use constant SPOTIFY_LIMIT => 50;
use Exporter::Lite;
our @EXPORT_OK = qw( SPOTIFY_LIMIT DEFAULT_LIMIT uri2url );
}
use base qw(Slim::Utils::Accessor);
use Digest::MD5 qw(md5_hex);
use JSON::XS::VersionOneAndTwo;
use List::Util qw(min max);
use POSIX qw(strftime);
use Scalar::Util qw(blessed);
use URI::Escape qw(uri_escape_utf8);
use Plugins::Spotty::Plugin;
use Plugins::Spotty::AccountHelper;
use Plugins::Spotty::Helper;
use Plugins::Spotty::API::Pipeline;
use Plugins::Spotty::API::AsyncRequest;
use Plugins::Spotty::API::Token;
use Plugins::Spotty::API::Web;
use Slim::Utils::Cache;
use Slim::Utils::Log;
use Slim::Utils::Prefs;
use Slim::Utils::Strings qw(cstring string);
my $log = logger('plugin.spotty');
my $cache = Slim::Utils::Cache->new();
use Plugins::Spotty::API::Cache;
my $libraryCache = Plugins::Spotty::API::Cache->new();
my $prefs = preferences('plugin.spotty');
my $error429;
my %tokenHandlers;
{
__PACKAGE__->mk_accessor( rw => qw(
client
cache
_username
_country
_canPodcast
) );
}
sub new {
my ($class, $args) = @_;
my $self = $class->SUPER::new();
$self->client($args->{client});
$self->cache($args->{cache});
$self->_username($args->{username});
$self->_country($prefs->get('country'));
# update our profile ASAP
$self->me();
return $self;
}
sub getToken {
my ( $self, $cb ) = @_;
if ($cache->get('spotty_rate_limit_exceeded')) {
return $cb->(-429) ;
}
Plugins::Spotty::API::Token->get($self, $cb);
}
sub me {
my ( $self, $cb ) = @_;
$self->_call('me',
sub {
my $result = shift;
if ( $result && ref $result ) {
$self->country($result->{country});
$self->_username($result->{username}) if $result->{username};
Plugins::Spotty::AccountHelper->setName($self->username, $result);
$cb->($result) if $cb;
}
}
);
}
sub home {
Plugins::Spotty::API::Web->home(@_);
}
sub browseWebUrl {
Plugins::Spotty::API::Web->browseWebUrl(@_);
}
# get the username - keep it simple. Shouldn't change, don't want nested async calls...
sub username {
my ($self, $username) = @_;
$self->_username($username) if $username;
return $self->_username if $self->_username;
# fall back to default account if no username was given
my $credentials = Plugins::Spotty::AccountHelper->getCredentials($self->client);
if ( $credentials && ref $credentials && $credentials->{username} ) {
$self->_username($credentials->{username})
}
return $self->_username;
}
# get the user's country - keep it simple. Shouldn't change, don't want nested async calls...
sub country {
my ($self, $country) = @_;
if ($country) {
$self->_country($country);
$prefs->set('country', $country);
}
return $self->_country || 'US';
}
sub locale {
cstring($_[0]->client, 'LOCALE');
}
sub user {
my ( $self, $cb, $username ) = @_;
if (!$username) {
$cb->([]);
return;
}
# usernames must be lower case, and space not URI encoded
$username = lc($username);
$username =~ s/ /\+/g;
$self->_call('users/' . uri_escape_utf8($username),
sub {
my ($result) = @_;
if ( $result && ref $result ) {
$result->{image} = $libraryCache->getLargestArtwork(delete $result->{images});
}
$cb->($result || {});
}
);
}
sub player {
my ( $self, $cb ) = @_;
$self->_call('me/player',
sub {
my ($result) = @_;
if ($result && ref $result) {
$result->{progress} = $result->{progress_ms} ? $result->{progress_ms} / 1000 : 0;
if ($result->{item} && $result->{item}->{type} eq 'track') {
$result->{track} = $libraryCache->normalize($result->{item});
}
# keep track of MAC -> ID mapping
if ( Plugins::Spotty::Connect->canSpotifyConnect() ) {
Plugins::Spotty::Connect::DaemonManager->checkAPIConnectPlayer($self, $result);
}
$cb->($result);
return;
}
$cb->();
},
GET => {
_nocache => 1,
market => 'from_token',
}
)
}
sub playerTransfer {
my ( $self, $cb, $device ) = @_;
$self->withIdFromMac(sub {
my $deviceId = shift;
if (!$deviceId) {
$cb->() if $cb;
return;
}
$self->_call('me/player',
sub {
$cb->() if $cb;
},
PUT => {
body => encode_json({
device_ids => [ $deviceId ],
play => 1
})
}
);
}, $device);
}
=pod
sub playerPlay {
my ( $self, $cb, $device, $args ) = @_;
$self->withIdFromMac(sub {
$args ||= {};
$args->{device_id} = $_[0] if $_[0];
$self->_call('me/player/play',
sub {
$cb->() if $cb;
},
PUT => $args
);
}, $device);
}
=cut
sub playerPause {
my ( $self, $cb, $device ) = @_;
$self->withIdFromMac(sub {
my $args = {};
$args->{device_id} = $_[0] if $_[0];
$self->_call('me/player/pause',
sub {
$cb->() if $cb;
},
PUT => $args
);
}, $device);
}
sub playerNext {
my ( $self, $cb, $device ) = @_;
$self->withIdFromMac(sub {
my $args = {};
$args->{device_id} = $_[0] if $_[0];
$self->_call('me/player/next',
sub {
$cb->() if $cb;
},
POST => $args
);
}, $device);
}
sub playerSeek {
my ( $self, $cb, $device, $songtime ) = @_;
$self->withIdFromMac(sub {
my $args = {
position_ms => int($songtime * 1000),
};
$args->{device_id} = $_[0] if $_[0];
$self->_call('me/player/seek',
sub {
$cb->() if $cb;
},
PUT => $args
);
}, $device);
}
sub playerVolume {
my ( $self, $cb, $device, $volume ) = @_;
$self->withIdFromMac(sub {
my $args = {
volume_percent => int($volume),
};
$args->{device_id} = $_[0] if $_[0];
$self->_call('me/player/volume',
sub {
$cb->() if $cb;
},
PUT => $args
);
}, $device);
}
sub idFromMac {
my ( $class, $mac ) = @_;
return Plugins::Spotty::Connect->canSpotifyConnect()
&& Plugins::Spotty::Connect::DaemonManager->idFromMac($mac);
}
sub withIdFromMac {
my ( $self, $cb, $mac ) = @_;
my $id = $self->idFromMac($mac);
if ( $id || $mac !~ /((?:[a-f0-9]{2}:){5}[a-f0-9]{2})/i ) {
$cb->($id || $mac);
}
else {
# ID wasn't in the cache yet, let's get the playerlist
$self->devices(sub {
$cb->($self->idFromMac($mac));
});
}
}
sub devices {
my ( $self, $cb ) = @_;
$self->_call('me/player/devices',
sub {
my ($result) = @_;
if ( Plugins::Spotty::Connect->canSpotifyConnect() ) {
Plugins::Spotty::Connect::DaemonManager->checkAPIConnectPlayers($self, $result);
}
$cb->() if $cb;
},
GET => {
_nocache => 1,
}
);
}
sub search {
my ( $self, $cb, $args ) = @_;
return $cb->([]) unless $args->{query} || $args->{series};
my $type = $args->{type} || 'track';
my $params = $args->{series}
? { chunks => $args->{series} }
: {
q => $args->{query},
type => $type,
market => 'from_token',
limit => $args->{limit} || DEFAULT_LIMIT
};
if ( $type =~ /album|artist|track|playlist|show_audio|episode_audio/ ) {
Plugins::Spotty::API::Pipeline->new($self, 'search', sub {
my $type = $type . 's';
$type =~ s/_audio//;
my $items = [];
for my $item ( @{ $_[0]->{$type}->{items} } ) {
# sometimes we'd get empty list items...
next unless $item && $self->_isPlayable($item);
if (main::INFOLOG) {
# if (main::INFOLOG && $log->is_info) {
if ( $item->{is_externally_hosted} || ($item->{media_type} || 'audio') ne 'audio' ) {
$log->warn("This item might need inspection: " . Data::Dump::dump($item));
}
}
$item = $libraryCache->normalize($item);
push @$items, $item;
}
return $items, $_[0]->{$type}->{total}, $_[0]->{$type}->{'next'};
}, $cb, $params)->get();
}
else {
$log->error("Unknown search type: $type");
$cb->([])
}
}
sub album {
my ( $self, $cb, $args ) = @_;
my ($id) = $args->{uri} =~ /album:(.*)/;
$self->_call('albums/' . $id,
sub {
my ($album) = @_;
my $total = $album->{tracks}->{total} if $album->{tracks} && ref $album->{tracks};
$album = $libraryCache->normalize($album);
# we might need to grab more tracks: audio books can have hundreds of "tracks"
if ( $total && $total > SPOTIFY_LIMIT ) {
Plugins::Spotty::API::Pipeline->new($self, 'albums/' . $id . '/tracks', sub {
my $items = [];
my $minAlbum = {
name => $album->{name},
image => $album->{image},
};
for my $track ( @{ $_[0]->{items} } ) {
# Add missing album data to track
$track->{album} = $minAlbum;
push @$items, $libraryCache->normalize($track);
}
return $items, $_[0]->{total}, $_[0]->{'next'};
}, sub {
$album->{tracks} = $_[0];
$cb->($album);
},{
market => 'from_token',
limit => $args->{limit} || max(LIBRARY_LIMIT, _DEFAULT_LIMIT())
})->get();
return;
}
$cb->($album);
},
GET => {
market => 'from_token',
limit => min($args->{limit} || SPOTIFY_LIMIT, SPOTIFY_LIMIT),
offset => $args->{offset} || 0,
}
);
}
sub addAlbumToLibrary {
my ( $self, $cb, $albumIds ) = @_;
$albumIds = join(',', @$albumIds) if ref $albumIds;
$self->_call("me/albums",
$cb,
PUT => {
ids => $albumIds,
}
);
}
sub artist {
my ( $self, $cb, $args ) = @_;
my ($id) = $args->{uri} =~ /artist:(.*)/;
$self->_call('artists/' . $id,
sub {
my $artist = $libraryCache->normalize($_[0]);
$cb->($artist);
},
GET => {
market => 'from_token',
limit => min($args->{limit} || SPOTIFY_LIMIT, SPOTIFY_LIMIT),
offset => $args->{offset} || 0,
}
);
}
sub artists {
my ( $self, $cb, $ids ) = @_;
if (!ref $ids) {
$ids = [ $ids ];
}
$ids = [ map { /artist:(.*)/ ? $1 : $_ } @$ids ];
if (!scalar @$ids) {
$cb->([]);
return;
}
my $chunks = {};
# build list of chunks we can query in one go
while ( my @ids = splice @$ids, 0, SPOTIFY_LIMIT) {
my $idList = join(',', @ids) || next;
$chunks->{md5_hex($idList)} = {
ids => $idList
};
}
Plugins::Spotty::API::Pipeline->new($self, 'artists', sub {
my ($artists) = @_;
my @artists;
foreach (@{$artists->{artists}}) {
# null album info for invalid IDs is returned
next unless $_ && ref $_;
my $artist = $libraryCache->normalize($_);
push @artists, $artist;
}
return \@artists;
}, $cb, {
chunks => $chunks,
})->get();
}
sub relatedArtists {
my ( $self, $cb, $uri ) = @_;
my ($id) = $uri =~ /artist:(.*)/;
Plugins::Spotty::API::Pipeline->new($self, 'artists/' . $id . '/related-artists', sub {
my $artists = $_[0] || {};
my $items = [ sort _artistSort map {
$libraryCache->normalize($_)
} @{$artists->{artists} || []} ];
return $items, $artists->{total}, $artists->{'next'};
}, $cb)->get();
}
sub artistTracks {
my ( $self, $cb, $args ) = @_;
my ($id) = $args->{uri} =~ /artist:(.*)/;
$self->_call('artists/' . $id . '/top-tracks',
sub {
my $tracks = $_[0] || {};
$cb->([ map { $libraryCache->normalize($_) } @{$tracks->{tracks} || []} ]);
},
GET => {
# Why the heck would this call need country rather than market?!? And no "from_token"?!?
country => $self->country(),
}
);
}
sub artistAlbums {
my ( $self, $cb, $args ) = @_;
my ($id) = $args->{uri} =~ /artist:(.*)/;
Plugins::Spotty::API::Pipeline->new($self, 'artists/' . $id . '/albums', sub {
my $albums = $_[0] || {};
my $items = [ map { $libraryCache->normalize($_)} @{$albums->{items} || []} ];
return $items, $albums->{total}, $albums->{'next'};
}, $cb, {
# "from_token" not allowed here?!?!
market => $self->country,
limit => min($args->{limit} || _DEFAULT_LIMIT(), _DEFAULT_LIMIT()),
offset => $args->{offset} || 0,
include_groups => $args->{include} || 'album,single,appears_on,compilation',
})->get();
}
sub followArtist {
my ( $self, $cb, $artistIds ) = @_;
$artistIds = join(',', @$artistIds) if ref $artistIds;
$self->_call("me/following", $cb,
PUT => {
ids => $artistIds,
type => 'artist'
}
);
}
sub playlist {
my ( $self, $cb, $args ) = @_;
my ($user, $id) = $self->getPlaylistUserAndId($args->{uri});
my $limit = $args->{limit};
# set the limit higher if it's the user's self curated playlist
$limit ||= lc($user) eq lc($self->username) ? max(LIBRARY_LIMIT, _DEFAULT_LIMIT()) : _DEFAULT_LIMIT();
Plugins::Spotty::API::Pipeline->new($self, 'playlists/' . $id . '/tracks', sub {
my $items = [];
my $rawItems = $_[0]->{items};
if ($prefs->get('sortPlaylisttracksByAddition')) {
$rawItems = [ sort {
$b->{added_at} cmp $a->{added_at}
} @$rawItems ];
}
my $cc = $self->country;
for my $item ( @$rawItems ) {
my $track = $item->{track} || next;
# if we set market => 'from_token', then we don't get available_markets back, but only a is_playable flag
next unless $self->_isPlayable($track, $cc);
push @$items, $libraryCache->normalize($track);
}
return $items, $_[0]->{total}, $_[0]->{'next'};
}, $cb, {
market => 'from_token',
limit => $limit
})->get();
}
sub getPlaylistUserAndId {
my ($self, $uri) = @_;
my ($user, $id) = $uri =~ /^spotify:user:([^:]+):playlist:(.+)/;
if ( !($user && $id) ) {
($id) = $uri =~ /^spotify:.*?\bplaylist:(.+)/;
$id ||= '';
$user = $cache->get('playlist_owner_' . $id) || '';
}
return ($user, $id);
}
# USE CAREFULLY! Calling this too often might get us banned
sub track {
my ( $self, $cb, $uri ) = @_;
if ($self->canPodcast() && $uri =~ /episode:/) {
$self->episode($cb, $uri);
}
else {
$self->_track($cb, $uri);
}
}
sub _track {
my ( $self, $cb, $uri ) = @_;
my $id = $uri;
$id =~ s/(?:spotify|track)://g;
$self->_call('tracks/' . $id, sub {
my $track = $libraryCache->normalize(shift);
$cb->($track, @_) if $cb;
},
GET => {
market => 'from_token'
});
}
sub episode {
my ( $self, $cb, $uri ) = @_;
my $id = $uri;
$id =~ s/(?:spotify|episode)://g;
$self->_call('episodes/' . $id, sub {
my $episode = $libraryCache->normalize(shift);
$cb->($episode, @_) if $cb;
},
GET => {
market => 'from_token'
});
}
sub trackCached {
my ( $self, $cb, $uri, $args ) = @_;
if ( $uri !~ /^spotify:(?:episode|track)/ ) {
$cb->() if $cb;
return;
}
if ( my $cached = $uri =~ /:episode:/ ? $cache->get($uri) : $libraryCache->get($uri) ) {
$cb->($cached) if $cb;
return $cached;
}
# look up track information unless told not to do so
$self->track($cb, $uri) if blessed $self && !$args->{noLookup};
return;
}
sub tracks {
my ( $self, $cb, $ids ) = @_;
if (!scalar @$ids) {
$cb->([]);
return;
}
$self->getToken(sub {
my ($token) = @_;
if ($token && $token =~ /^-\d+$/) {
$cb->([ map {
my $t = {
title => 'Failed to get access token',
duration => 1,
uri => $_,
};
$cache->set($_, $t, 60);
$t;
} @$ids ]);
}
else {
# TODO - this is potentially dangerous, as we're calling our callback twice.
# In this particular case it's ok, but we have to fix this should there be more callers.
$self->_tracks($cb, $ids);
$self->_episodes($cb, $ids) if $self->canPodcast();
}
});
}
sub _tracks {
my ($self, $cb, undef, $type ) = @_;
$type ||= 'track';
my $chunks = {};
my $ids = [ sort @{Storable::dclone($_[2])} ];
# build list of chunks we can query in one go
while ( my @ids = splice @$ids, 0, SPOTIFY_LIMIT) {
my $idList = join(',', map { s/(?:spotify|$type)://g; $_ } grep { $_ && /^(?:spotify:$type|$type):/ } @ids) || next;
$chunks->{md5_hex($idList)} = {
market => 'from_token',
ids => $idList
};
}
if (!keys %$chunks) {
return $cb->([]);
}
$type .= 's';
Plugins::Spotty::API::Pipeline->new($self, $type, sub {
my ($tracks) = @_;
my @tracks;
foreach (@{$tracks->{$type}}) {
# track info for invalid IDs is returned
next unless $_ && ref $_;
my $track = $libraryCache->normalize($_);
push @tracks, $track if $self->_isPlayable($_);
}
return \@tracks;
}, $cb, {
chunks => $chunks,
})->get();
}
sub _episodes {
my ($self, $cb, $ids ) = @_;
$self->_tracks($cb, $ids, 'episode');
}
# try to get a list of track URI
sub trackURIsFromURI {
my ( $self, $cb, $uri ) = @_;
my $cb2 = sub {
$cb->([ map {
$_->{uri}
} @{$_[0]} ])
};
my $params = {
uri => $uri
};
if ($uri =~ /:playlist:.*:recommended/) {
main::INFOLOG && $log->is_info && $log->info("Not looking up playlist, as it's the :recommended continuation");
$cb->([]);
}
elsif ($uri =~ /:playlist:/) {
$self->playlist($cb2, $params);
}
elsif ( $uri =~ /:artist:/ ) {
$self->artistTracks($cb2, $params);
}
elsif ( $uri =~ /:show:/ ) {
$self->show(sub {
$cb2->(($_[0] || {})->{episodes});
}, $params);
}
elsif ( $uri =~ /:album:/ ) {
$self->album(sub {
$cb2->(($_[0] || {})->{tracks});
}, $params);
}
elsif ( $uri =~ m{:/*(?:track|episode):} ) {
$cb->([ $uri ]);
}
else {
$log->warn("No tracks found for URI $uri");
$cb->([]);
}
}
sub mySongs {
my ( $self, $cb, $fast ) = @_;
Plugins::Spotty::API::Pipeline->new($self, 'me/tracks', sub {
if ( $_[0] && $_[0]->{items} && ref $_[0]->{items} ) {
return [ map { $libraryCache->normalize($_->{track}, $fast) } @{ $_[0]->{items} } ], $_[0]->{total}, $_[0]->{'next'};
}
}, sub {
my $items = shift;
$items = [ sort {
Slim::Utils::Text::ignoreCaseArticles($a->{name}) cmp Slim::Utils::Text::ignoreCaseArticles($b->{name})
} @{$items || []} ] if $prefs->get('sortSongsAlphabetically');
$cb->($items);
}, {
limit => max(LIBRARY_LIMIT, _DEFAULT_LIMIT()),
})->get();
}
sub myAlbums {
my ( $self, $cb, $fast ) = @_;
Plugins::Spotty::API::Pipeline->new($self, 'me/albums', sub {
if ( $_[0] && $_[0]->{items} && ref $_[0]->{items} ) {
return [ map { $libraryCache->normalize($_->{album}, $fast) } @{ $_[0]->{items} } ], $_[0]->{total}, $_[0]->{'next'};
}
}, sub {
my $items = shift;
$items = [ sort {
Slim::Utils::Text::ignoreCaseArticles($a->{name}) cmp Slim::Utils::Text::ignoreCaseArticles($b->{name})
} @{$items || []} ] if $prefs->get('sortAlbumsAlphabetically');
$cb->($items);
}, {
limit => max(LIBRARY_LIMIT, _DEFAULT_LIMIT()),
})->get();
}
sub myAlbumsMeta {
my ( $self, $cb ) = @_;
$self->_call('me/albums', sub {
my ($response) = @_;
my $libraryMeta = {};
if ( $response && $response->{items} && ref $response->{items} ) {
# keep track of some meta-information about the
$libraryMeta = {
total => $response->{total} || 0,
lastAdded => $response->{items}->[0]->{added_at} || ''
};
}
$cb->($libraryMeta);
},
GET => {
limit => 1
});
}
sub isInMyAlbums {
my ( $self, $cb, $ids ) = @_;
if (!$ids) {
$cb->([]);
return;
}
$ids = [split /,/, $ids] unless ref $ids;
my $chunks = {};
# build list of chunks we can query in one go
while ( my @ids = splice @$ids, 0, SPOTIFY_LIMIT) {
my $idList = join(',', map { s/.*://g; $_ } @ids) || next;
$chunks->{$idList} = { ids => $idList };
}
Plugins::Spotty::API::Pipeline->new($self, 'me/albums/contains', sub {
my ($tracks, $idList) = @_;
my @ids = split(',', $idList);
my @results;
for ( my $x = 0; $x < min((scalar @ids), (scalar @{$tracks || []})) ; $x++ ) {
push @results, {
$ids[$x] => 1
} if $tracks->[$x];
}
return \@results;
}, sub {
my ($tracks) = @_;
$cb->({ map {
my ($k, $v) = each %$_;
$k => $v;
} @$tracks });
}, {
chunks => $chunks,
})->get();
}
sub myArtists {
my ( $self, $cb, $noAlbumArtists ) = @_;
# Getting the artists list is such a pain. Even when fetching every single request from cache,
# this would be slow on some systems. Let's just cache the full result...
my $cacheKey = 'spotify_my_artists' . Slim::Utils::Unicode::utf8toLatin1Transliterate($self->username || '');
if ( my $cached = $cache->get($cacheKey) ) {
$cb->($cached);
return;
}
Plugins::Spotty::API::Pipeline->new($self, 'me/following', sub {
if ( $_[0] && $_[0]->{artists} && $_[0]->{artists} && (my $artists = $_[0]->{artists}) ) {
return [ map { $libraryCache->normalize($_, 'fast') } @{ $artists->{items} } ], $artists->{total}, $artists->{'next'};
}
}, sub {
my $results = shift;
# sometimes we get invalid list items back?!?
my $items = [ grep { $_->{id} } @{$results || []} ];
if ($noAlbumArtists) {
$cb->($items);
return;
}
my %knownArtists = map {
my $id = $_->{id};
$id => 1
} @$items;
# Spotify does include artists from saved albums in their apps, but doesn't provide an API call to do this.
# Let's do it the hard way: get the list of artists for which we have a stored album.
$self->myAlbums(sub {
my $albums = shift || [];
# the album object comes without the artist image - let's collect IDs and grab them later
my $missingArtwork = [];
foreach ( @$albums ) {
next unless $_->{artists};
if ( my $artist = $_->{artists}->[0] ) {
if ( !$knownArtists{$artist->{id}}++ ) {
$artist = $libraryCache->normalize($artist, 'fast');
push @$items, $artist;
if (!$artist->{image}) {
push @$missingArtwork, $artist->{id};
}
}
}
}
$items = [ sort _artistSort @$items ] if $prefs->get('sortArtistsAlphabetically');
# do one more lookup if the albums list returned artists we don't have artwork for, yet...
if (scalar @$missingArtwork) {
$self->artists(sub {
# now let's merge these new results with what we had already...
my %artists = map {
$_->{id} => $libraryCache->normalize($_, 'fast')
} @{shift || []};
map {
if (my $artist = $artists{$_->{id}}) {
$_->{image} = $artist->{image};