This repository has been archived by the owner on Jan 22, 2022. It is now read-only.
/
mobileclient.py
2248 lines (1870 loc) · 91.3 KB
/
mobileclient.py
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
# -*- coding: utf-8 -*-
from __future__ import print_function, division, absolute_import, unicode_literals
from past.builtins import basestring
from builtins import * # noqa
from collections import defaultdict
import datetime
from operator import itemgetter
import re
from uuid import getnode as getmac
from gmusicapi import session
from gmusicapi.clients.shared import _Base
from gmusicapi.exceptions import CallFailure, NotSubscribed, InvalidDeviceId
from gmusicapi.protocol import mobileclient
from gmusicapi.utils import utils
class Mobileclient(_Base):
"""Allows library management and streaming by posing as the
googleapis.com mobile clients.
Uploading is not supported by this client (use the :class:`Musicmanager`
to upload).
"""
_session_class = session.Mobileclient
FROM_MAC_ADDRESS = object()
def __init__(self, debug_logging=True, validate=True, verify_ssl=True):
super(Mobileclient, self).__init__(self.__class__.__name__,
debug_logging,
validate,
verify_ssl)
def _ensure_device_id(self, device_id=None):
if device_id is None:
device_id = self.android_id
if len(device_id) == 16 and re.match('^[a-z0-9]*$', device_id):
# android device ids are now sent in base 10
device_id = str(int(device_id, 16))
return device_id
def _validate_device_id(self, device_id, is_mac=False):
"""Ensure that a given device_id belongs to the user supplying it."""
if is_mac: # Always allow logins with MAC address.
return device_id
device_ids = []
for d in self.get_registered_devices():
if d['id'].startswith('ios:'):
device_ids.append(d['id'])
elif d['id'].startswith('0x'):
# old android format
device_ids.append(d['id'][2:])
else:
# mac address format
device_ids.append(d['id'].replace(':', ''))
if device_id in device_ids:
return device_id
else:
self.logout()
raise InvalidDeviceId('Invalid device_id %s.' % device_id, device_ids)
@property
def locale(self):
"""The locale of the Mobileclient session used to localize some responses.
Should be an `ICU <http://www.localeplanet.com/icu/>`__ locale supported by Android.
Set on authentication with :func:`login` but can be changed at any time.
"""
return self.session._locale
@locale.setter
def locale(self, locale):
self.session._locale = locale
@utils.cached_property(ttl=600)
def is_subscribed(self):
"""Returns the subscription status of the Google Music account.
Result is cached with a TTL of 10 minutes. To get live status before the TTL
is up, delete the ``is_subscribed`` property of the Mobileclient instance.
>>> mc = Mobileclient()
>>> mc.is_subscribed # Live status.
>>> mc.is_subscribed # Cached status.
>>> del mc.is_subscribed # Delete is_subscribed property.
>>> mc.is_subscribed # Live status.
"""
res = self._make_call(mobileclient.Config)
for item in res['data']['entries']:
if item['key'] == 'isNautilusUser' and item['value'] == 'true':
self.session._is_subscribed = True
break
else:
self.session._is_subscribed = False
return self.session._is_subscribed
def login(self, email, password, android_id, locale='en_US'):
"""Authenticates the Mobileclient.
Returns ``True`` on success, ``False`` on failure.
:param email: eg ``'test@gmail.com'`` or just ``'test'``.
:param password: password or app-specific password for 2-factor users.
This is not stored locally, and is sent securely over SSL.
:param android_id: 16 hex digits, eg ``'1234567890abcdef'``.
Pass Mobileclient.FROM_MAC_ADDRESS instead to attempt to use
this machine's MAC address as an android id.
**Use this at your own risk**:
the id will be a non-standard 12 characters,
but appears to work fine in testing.
If a valid MAC address cannot be determined on this machine
(which is often the case when running on a VPS), raise OSError.
:param locale: `ICU <http://www.localeplanet.com/icu/>`__ locale
used to localize certain responses. This must be a locale supported
by Android. Defaults to ``'en_US'``.
"""
# TODO 2fa
if android_id is None:
raise ValueError("android_id cannot be None.")
is_mac = android_id is self.FROM_MAC_ADDRESS
if is_mac:
mac_int = getmac()
if (mac_int >> 40) % 2:
raise OSError("a valid MAC could not be determined."
" Provide an android_id (and be"
" sure to provide the same one on future runs).")
device_id = utils.create_mac_string(mac_int)
device_id = device_id.replace(':', '')
else:
device_id = android_id
if not self.session.login(email, password, device_id):
self.logger.info("failed to authenticate")
return False
self.android_id = self._validate_device_id(device_id, is_mac=is_mac)
self.logger.info("authenticated")
self.locale = locale
if self.is_subscribed:
self.logger.info("subscribed")
return True
# TODO expose max/page-results, etc for list operations
def get_all_songs(self, incremental=False, include_deleted=None, updated_after=None):
"""Returns a list of dictionaries that each represent a song.
:param incremental: if True, return a generator that yields lists
of at most 1000 tracks
as they are retrieved from the server. This can be useful for
presenting a loading bar to a user.
:param include_deleted: ignored. Will be removed in a future release.
:param updated_after: a datetime.datetime; defaults to unix epoch.
If provided, deleted songs may be returned.
Here is an example song dictionary::
{
'comment':'',
'rating':'0',
'albumArtRef':[
{
'url': 'http://lh6.ggpht.com/...'
}
],
'artistId':[
'Aod62yyj3u3xsjtooghh2glwsdi'
],
'composer':'',
'year':2011,
'creationTimestamp':'1330879409467830',
'id':'5924d75a-931c-30ed-8790-f7fce8943c85',
'album':'Heritage ',
'totalDiscCount':0,
'title':'Haxprocess',
'recentTimestamp':'1372040508935000',
'albumArtist':'',
'trackNumber':6,
'discNumber':0,
'deleted':False,
'storeId':'Txsffypukmmeg3iwl3w5a5s3vzy',
'nid':'Txsffypukmmeg3iwl3w5a5s3vzy',
'totalTrackCount':10,
'estimatedSize':'17229205',
'albumId':'Bdkf6ywxmrhflvtasnayxlkgpcm',
'beatsPerMinute':0,
'genre':'Progressive Metal',
'playCount':7,
'artistArtRef':[
{
'url': 'http://lh3.ggpht.com/...'
}
],
'kind':'sj#track',
'artist':'Opeth',
'lastModifiedTimestamp':'1330881158830924',
'clientId':'+eGFGTbiyMktbPuvB5MfsA',
'durationMillis':'418000'
}
"""
tracks = self._get_all_items(mobileclient.ListTracks, incremental,
updated_after=updated_after)
return tracks
@utils.accept_singleton(dict)
@utils.empty_arg_shortcircuit
def rate_songs(self, songs, rating):
"""Rate library or store songs.
Returns rated song ids.
:param songs: a list of song dictionaries
or a single song dictionary.
required keys: 'id' for library songs or 'nid' and 'trackType' for store songs.
:param rating: set to ``'0'`` (no thumb), ``'1'`` (down thumb), or ``'5'`` (up thumb).
"""
mutate_call = mobileclient.BatchMutateTracks
mutations = []
for song in songs:
song['rating'] = rating
mutations.append({'update': song})
self._make_call(mutate_call, mutations)
# TODO
# store tracks don't send back their id, so we're
# forced to spoof this
return [utils.id_or_nid(song) for song in songs]
@utils.accept_singleton(dict)
@utils.empty_arg_shortcircuit
@utils.deprecated('prefer Mobileclient.rate_songs')
def change_song_metadata(self, songs):
"""Changes the metadata of tracks.
Returns a list of the song ids changed.
:param songs: a list of song dictionaries
or a single song dictionary.
Currently, only the ``rating`` key can be changed.
Set it to ``'0'`` (no thumb), ``'1'`` (down thumb), or ``'5'`` (up thumb).
You can also use this to rate store tracks
that aren't in your library, eg::
song = mc.get_track_info('<some store track id>')
song['rating'] = '5'
mc.change_song_metadata(song)
"""
mutate_call = mobileclient.BatchMutateTracks
mutations = [{'update': s} for s in songs]
self._make_call(mutate_call, mutations)
# TODO
# store tracks don't send back their id, so we're
# forced to spoof this
return [utils.id_or_nid(d) for d in songs]
def increment_song_playcount(self, song_id, plays=1, playtime=None):
"""Increments a song's playcount and returns its song id.
:params song_id: a song id. Providing the id of a store track
that has been added to the library will *not* increment the
corresponding library song's playcount. To do this, use the
'id' field (which looks like a uuid and doesn't begin with 'T'),
not the 'nid' field.
:params plays: (optional) positive number of plays to increment by.
The default is 1.
:params playtime: (optional) a datetime.datetime of the
time the song was played.
It will default to the time of the call.
"""
if playtime is None:
playtime = datetime.datetime.now()
self._make_call(mobileclient.IncrementPlayCount, song_id, plays, playtime)
return song_id
@utils.require_subscription
@utils.enforce_id_param
@utils.deprecated('prefer Mobileclient.add_store_tracks')
def add_store_track(self, store_song_id):
"""Adds a store track to the library
Returns the library track id of added store track.
:param store_song_id: store song id
"""
return self.add_store_tracks(store_song_id)[0]
@utils.require_subscription
@utils.accept_singleton(basestring)
@utils.enforce_ids_param
def add_store_tracks(self, store_song_ids):
"""Add store tracks to the library
Returns a list of the library track ids of added store tracks.
:param store_song_ids: a list of store song ids or a single store song id
"""
mutate_call = mobileclient.BatchMutateTracks
add_mutations = [mutate_call.build_track_add(self.get_track_info(store_song_id))
for store_song_id in store_song_ids]
res = self._make_call(mutate_call, add_mutations)
return [r['id'] for r in res['mutate_response']]
@utils.accept_singleton(basestring)
@utils.enforce_ids_param
@utils.empty_arg_shortcircuit
def delete_songs(self, library_song_ids):
"""Deletes songs from the library.
Returns a list of deleted song ids.
:param song_ids: a list of song ids, or a single song id.
"""
mutate_call = mobileclient.BatchMutateTracks
del_mutations = mutate_call.build_track_deletes(library_song_ids)
res = self._make_call(mutate_call, del_mutations)
return [d['id'] for d in res['mutate_response']]
@utils.enforce_id_param
def get_stream_url(self, song_id, device_id=None, quality='hi'):
"""Returns a url that will point to an mp3 file.
:param song_id: A single song id.
This can be ``'storeId'`` from a store song, ``'id'`` from an uploaded song, or
``'trackId'`` from a playlist entry.
:param device_id: (optional) defaults to ``android_id`` from login.
Otherwise, provide a mobile device id as a string.
Android device ids are 16 characters, while iOS ids
are uuids with 'ios:' prepended.
If you have already used Google Music on a mobile device,
:func:`Mobileclient.get_registered_devices
<gmusicapi.clients.Mobileclient.get_registered_devices>` will provide
at least one working id. Omit ``'0x'`` from the start of the string if present.
Registered computer ids (a MAC address) will not be accepted and will 403.
Providing an unregistered mobile device id will register it to your account,
subject to Google's `device limits
<http://support.google.com/googleplay/bin/answer.py?hl=en&answer=1230356>`__.
**Registering a device id that you do not own is likely a violation of the TOS.**
:param quality: (optional) stream bits per second quality
One of three possible values, hi: 320kbps, med: 160kbps, low: 128kbps.
The default is hi
When handling the resulting url, keep in mind that:
* you will likely need to handle redirects
* the url expires after a minute
* only one IP can be streaming music at once.
This can result in an http 403 with
``X-Rejected-Reason: ANOTHER_STREAM_BEING_PLAYED``.
The file will not contain metadata.
Use :func:`Webclient.get_song_download_info
<gmusicapi.clients.Webclient.get_song_download_info>`
or :func:`Musicmanager.download_song
<gmusicapi.clients.Musicmanager.download_song>`
to download files with metadata.
"""
if song_id.startswith('T') and not self.is_subscribed:
raise NotSubscribed("Store tracks require a subscription to stream.")
device_id = self._ensure_device_id(device_id)
return self._make_call(mobileclient.GetStreamUrl, song_id, device_id, quality)
def get_station_track_stream_url(self, song_id, wentry_id, session_token, quality='hi'):
"""Returns a url that will point to an mp3 file.
This is only for use by free accounts, and requires a call to
:func:`get_station_info` first to provide `wentry_id` and `session_token`.
Subscribers should instead use :func:`get_stream_url`.
:param song_id: a single song id
:param wentry_id: a free radio station track entry id (`wentryid` from
:func:`get_station_info`)
:param session_token: a free radio station session token (`sessionToken` from
:func:`get_station_info`)
:param quality: (optional) stream bits per second quality
One of three possible values, hi: 320kbps, med: 160kbps, low: 128kbps.
The default is hi
"""
return self._make_call(mobileclient.GetStationTrackStreamUrl, song_id, wentry_id,
session_token, quality)
def get_all_playlists(self, incremental=False, include_deleted=None, updated_after=None):
"""Returns a list of dictionaries that each represent a playlist.
:param incremental: if True, return a generator that yields lists
of at most 1000 playlists
as they are retrieved from the server. This can be useful for
presenting a loading bar to a user.
:param include_deleted: ignored. Will be removed in a future release.
:param updated_after: a datetime.datetime; defaults to unix epoch
If provided, deleted playlists may be returned.
Here is an example playlist dictionary::
{
# can also be SHARED (public/subscribed to), MAGIC or omitted
'type': 'USER_GENERATED',
'kind': 'sj#playlist',
'name': 'Something Mix',
'deleted': False,
'lastModifiedTimestamp': '1325458766483033',
'recentTimestamp': '1325458766479000',
'shareToken': '<long string>',
'ownerProfilePhotoUrl': 'http://lh3.googleusercontent.com/...',
'ownerName': 'Simon Weber',
'accessControlled': False, # has to do with shared playlists
'creationTimestamp': '1325285553626172',
'id': '3d72c9b5-baad-4ff7-815d-cdef717e5d61'
}
"""
playlists = self._get_all_items(mobileclient.ListPlaylists, incremental,
updated_after=updated_after)
return playlists
# these could trivially support multiple creation/edits/deletion, but
# I chose to match the old webclient interface (at least for now).
def create_playlist(self, name, description=None, public=False):
"""Creates a new empty playlist and returns its id.
:param name: the desired title.
Creating multiple playlists with the same name is allowed.
:param description: (optional) the desired description
:param public: (optional) if True and the user has a subscription, share playlist.
"""
share_state = 'PUBLIC' if public else 'PRIVATE'
mutate_call = mobileclient.BatchMutatePlaylists
add_mutations = mutate_call.build_playlist_adds([{'name': name,
'description': description,
'public': share_state}])
res = self._make_call(mutate_call, add_mutations)
return res['mutate_response'][0]['id']
@utils.enforce_id_param
def edit_playlist(self, playlist_id, new_name=None, new_description=None, public=None):
"""Changes the name of a playlist and returns its id.
:param playlist_id: the id of the playlist
:param new_name: (optional) desired title
:param new_description: (optional) desired description
:param public: (optional) if True and the user has a subscription, share playlist.
"""
if all(value is None for value in (new_name, new_description, public)):
raise ValueError('new_name, new_description, or public must be provided')
if public is None:
share_state = public
else:
share_state = 'PUBLIC' if public else 'PRIVATE'
mutate_call = mobileclient.BatchMutatePlaylists
update_mutations = mutate_call.build_playlist_updates([
{'id': playlist_id, 'name': new_name,
'description': new_description, 'public': share_state}
])
res = self._make_call(mutate_call, update_mutations)
return res['mutate_response'][0]['id']
@utils.enforce_id_param
def delete_playlist(self, playlist_id):
"""Deletes a playlist and returns its id.
:param playlist_id: the id to delete.
"""
# TODO accept multiple?
mutate_call = mobileclient.BatchMutatePlaylists
del_mutations = mutate_call.build_playlist_deletes([playlist_id])
res = self._make_call(mutate_call, del_mutations)
return res['mutate_response'][0]['id']
def get_all_user_playlist_contents(self):
"""
Retrieves the contents of *all* user-created playlists
-- the Mobileclient does not support retrieving
only the contents of one
playlist.
This will not return results for public playlists
that the user is subscribed to; use :func:`get_shared_playlist_contents`
instead.
The same structure as :func:`get_all_playlists`
will be returned, but
with the addition of a ``'tracks'`` key in each dict
set to a list of properly-ordered playlist entry dicts.
Here is an example playlist entry for an individual track::
{
'kind': 'sj#playlistEntry',
'deleted': False,
'trackId': '2bb0ab1c-ce1a-3c0f-9217-a06da207b7a7',
'lastModifiedTimestamp': '1325285553655027',
'playlistId': '3d72c9b5-baad-4ff7-815d-cdef717e5d61',
'absolutePosition': '01729382256910287871', # denotes playlist ordering
'source': '1', # '2' if hosted on Google Music, '1' otherwise (see below)
'creationTimestamp': '1325285553655027',
'id': 'c9f1aff5-f93d-4b98-b13a-429cc7972fea' ## see below
}
If a user uploads local music to Google Music using the Music Manager,
Google will attempt to match each uploaded track to a track already
hosted on its servers. If a match is found for a track, the playlist
entry key ``'source'`` has the value ``'2'``, and the entry will have a
key ``'track'`` with a value that is a dict of track metadata (title,
artist, etc).
If a track is not hosted on Google Music, then the playlist entry key
``'source'`` has the value ``'1'``, and may not have a ``'track'``
key (e.g., for an MP3 without ID3 tags). In this case, the key ``'trackId'``
corresponds to the column ``ServerId`` in the table ``XFILES`` in Music
Manager's local SQLite database (stored, e.g., at
~/Library/Application\ Support/Google/MusicManager/ServerDatabase.db
on OS X). Among other things, the SQLite database exposes the track's
local file path, and Music Manager's imputed metadata.
(Note that the above behavior is documented for the Music Manager set to
sync from local Folders, and may differ if it instead syncs from iTunes.)
"""
user_playlists = [p for p in self.get_all_playlists()
if (p.get('type') == 'USER_GENERATED' or
p.get('type') != 'SHARED' or
'type' not in p)]
all_entries = self._get_all_items(mobileclient.ListPlaylistEntries,
incremental=False,
updated_after=None)
for playlist in user_playlists:
# TODO could use a dict to make this faster
entries = [e for e in all_entries
if e['playlistId'] == playlist['id']]
entries.sort(key=itemgetter('absolutePosition'))
playlist['tracks'] = entries
return user_playlists
def get_shared_playlist_contents(self, share_token):
"""
Retrieves the contents of a public playlist.
:param share_token: from ``playlist['shareToken']``, or a playlist share
url (``https://play.google.com/music/playlist/<token>``).
Note that tokens from urls will need to be url-decoded,
eg ``AM...%3D%3D`` becomes ``AM...==``.
For example, to retrieve the contents of a playlist that the user is
subscribed to::
subscribed_to = [p for p in mc.get_all_playlists() if p.get('type') == 'SHARED']
share_tok = subscribed_to[0]['shareToken']
tracks = mc.get_shared_playlist_contents(share_tok)
The user need not be subscribed to a playlist to list its tracks.
Returns a list of playlist entries
with structure the same as those
returned by :func:`get_all_user_playlist_contents`,
but without the ``'clientId'`` or ``'playlistId'`` keys.
"""
res = self._make_call(mobileclient.ListSharedPlaylistEntries,
updated_after=None, share_token=share_token)
entries = res['entries'][0]['playlistEntry']
entries.sort(key=itemgetter('absolutePosition'))
return entries
@utils.accept_singleton(basestring, 2)
@utils.enforce_id_param
@utils.enforce_ids_param(position=2)
@utils.empty_arg_shortcircuit(position=2)
def add_songs_to_playlist(self, playlist_id, song_ids):
"""Appends songs to the end of a playlist.
Returns a list of playlist entry ids that were added.
:param playlist_id: the id of the playlist to add to.
:param song_ids: a list of song ids, or a single song id.
These can be ``'storeId'`` from a store song, ``'id'`` from an uploaded song, or
``'trackId'`` from a playlist entry.
Playlists have a maximum size of 1000 songs.
Calls may fail before that point (presumably) due to
an error on Google's end (see `#239
<https://github.com/simon-weber/gmusicapi/issues/239>`__).
"""
mutate_call = mobileclient.BatchMutatePlaylistEntries
add_mutations = mutate_call.build_plentry_adds(playlist_id, song_ids)
res = self._make_call(mutate_call, add_mutations)
return [e['id'] for e in res['mutate_response']]
@utils.accept_singleton(basestring, 1)
@utils.enforce_ids_param(position=1)
@utils.empty_arg_shortcircuit(position=1)
def remove_entries_from_playlist(self, entry_ids):
"""Removes specific entries from a playlist.
Returns a list of entry ids that were removed.
:param entry_ids: a list of entry ids, or a single entry id.
"""
mutate_call = mobileclient.BatchMutatePlaylistEntries
del_mutations = mutate_call.build_plentry_deletes(entry_ids)
res = self._make_call(mutate_call, del_mutations)
return [e['id'] for e in res['mutate_response']]
def reorder_playlist_entry(self, entry, to_follow_entry=None, to_precede_entry=None):
"""Reorders a single entry in a playlist and returns its id.
Read ``reorder_playlist_entry(foo, bar, gaz)`` as
"reorder playlist entry *foo* to follow entry *bar*
and precede entry *gaz*."
:param entry: the playlist entry to move.
:param to_follow_entry: the playlist entry
that will come before *entry* in the resulting playlist,
or None if *entry* is to be the first entry in the playlist.
:param to_precede_entry: the playlist entry
that will come after *entry* in the resulting playlist
or None if *entry* is to be the last entry in the playlist.
``reorder_playlist_entry(foo)`` is invalid and will raise ValueError;
provide at least one of *to_follow_entry* or *to_precede_entry*.
Leaving *to_follow_entry* or *to_precede_entry* as None when
*entry* is not to be the first or last entry in the playlist
is undefined.
All params are dicts returned by
:func:`get_all_user_playlist_contents` or
:func:`get_shared_playlist_contents`.
"""
if to_follow_entry is None and to_precede_entry is None:
raise ValueError('either to_follow_entry or to_precede_entry must be provided')
mutate_call = mobileclient.BatchMutatePlaylistEntries
before = to_follow_entry['clientId'] if to_follow_entry else None
after = to_precede_entry['clientId'] if to_precede_entry else None
reorder_mutation = mutate_call.build_plentry_reorder(entry, before, after)
res = self._make_call(mutate_call, [reorder_mutation])
return [e['id'] for e in res['mutate_response']]
# WIP, see issue #179
# def reorder_playlist(self, reordered_playlist, orig_playlist=None):
# """TODO"""
# if not reordered_playlist['tracks']:
# #TODO what to return?
# return
# if orig_playlist is None:
# #TODO get pl from server
# pass
# if len(reordered_playlist['tracks']) != len(orig_playlist['tracks']):
# raise ValueError('the original playlist does not have the same number of'
# ' tracks as the reordered playlist')
# # find the minimum number of mutations to match the orig playlist
# orig_tracks = orig_playlist['tracks']
# orig_tracks_id_to_idx = dict([(t['id'], i) for (i, t) in enumerate(orig_tracks)])
# re_tracks = reordered_playlist['tracks']
# re_tracks_id_to_idx = dict([(t['id'], i) for (i, t) in enumerate(re_tracks)])
# translated_re_tracks = [orig_tracks_id_to_idx[t['id']] for t in re_tracks]
# lis = utils.longest_increasing_subseq(translated_re_tracks)
# idx_to_move = set(range(len(orig_tracks))) - set(lis)
# idx_pos_pairs = [(i, re_tracks_id_to_idx[orig_tracks[i]['id']])
# for i in idx_to_move]
# #TODO build out mutations
# return idx_pos_pairs
# @staticmethod
# def _create_ple_reorder_mutations(tracks, from_to_idx_pairs):
# """
# Return a list of mutations.
# :param tracks: orig_playlist['tracks']
# :param from_to_idx_pairs: [(from_index, to_index)]
# """
# for from_idx, to_idx in sorted(key=itemgetter(1)
# playlist_len = len(self.plentry_ids)
# for from_pos, to_pos in [pair for pair in
# itertools.product(range(playlist_len), repeat=2)
# if pair[0] < pair[1]]:
# pl = self.mc_get_playlist_songs(self.playlist_id)
# from_e = pl[from_pos]
# e_before_new_pos, e_after_new_pos = None, None
# if to_pos - 1 >= 0:
# e_before_new_pos = pl[to_pos]
# if to_pos + 1 < playlist_len:
# e_after_new_pos = pl[to_pos + 1]
# self.mc.reorder_playlist_entry(from_e,
# to_follow_entry=e_before_new_pos,
# to_precede_entry=e_after_new_pos)
# self._mc_assert_ple_position(from_e, to_pos)
# if e_before_new_pos:
# self._mc_assert_ple_position(e_before_new_pos, to_pos - 1)
# if e_after_new_pos:
# self._mc_assert_ple_position(e_after_new_pos, to_pos + 1)
def get_registered_devices(self):
"""
Returns a list of dictionaries representing devices associated with the account.
Performing the :class:`Musicmanager` OAuth flow will register a device
of type ``'DESKTOP_APP'``.
Installing the Android or iOS Google Music app and logging into it will
register a device of type ``'ANDROID'`` or ``'IOS'`` respectively, which is
required for streaming with the :class:`Mobileclient`.
Here is an example response::
[
{
u'kind': u'sj#devicemanagementinfo',
u'friendlyName': u'my-hostname',
u'id': u'AA:BB:CC:11:22:33',
u'lastAccessedTimeMs': u'1394138679694',
u'type': u'DESKTOP_APP'
},
{
u"kind": u"sj#devicemanagementinfo",
u'friendlyName': u'Nexus 7',
u'id': u'0x00112233aabbccdd', # remove 0x when streaming
u'lastAccessedTimeMs': u'1344808742774',
u'type': u'ANDROID'
u'smartPhone': True
},
{
u"kind": u"sj#devicemanagementinfo",
u'friendlyName': u'iPhone 6',
u'id': u'ios:01234567-0123-0123-0123-0123456789AB',
u'lastAccessedTimeMs': 1394138679694,
u'type': u'IOS'
u'smartPhone': True
}
{
u'kind': u'sj#devicemanagementinfo',
u'friendlyName': u'Google Play Music for Chrome on Windows',
u'id': u'rt2qfkh0qjhos4bxrgc0oae...', # 64 characters, alphanumeric
u'lastAccessedTimeMs': u'1425602805052',
u'type': u'DESKTOP_APP'
},
]
"""
res = self._make_call(mobileclient.GetDeviceManagementInfo)
return res['data']['items'] if 'data' in res else []
def deauthorize_device(self, device_id):
"""Deauthorize a registered device.
Returns ``True`` on success, ``False`` on failure.
:param device_id: A mobile device id as a string.
Android ids are 16 characters with '0x' prepended,
iOS ids are uuids with 'ios:' prepended,
while desktop ids are in the form of a MAC address.
Providing an invalid or unregistered device id will result in a 400 HTTP error.
Google limits the number of device deauthorizations to 4 per year.
Attempts to deauthorize a device when that limit is reached results in
a 403 HTTP error with: ``X-Rejected-Reason: TOO_MANY_DEAUTHORIZATIONS``.
"""
try:
self._make_call(mobileclient.DeauthDevice, device_id)
except CallFailure:
self.logger.exception("Deauthorization failure.")
return False
return True
def get_promoted_songs(self):
"""Returns a list of dictionaries that each represent a track.
Only store tracks will be returned.
Promoted tracks are determined in an unknown fashion,
but positively-rated library tracks are common.
See :func:`get_track_info` for the format of a track dictionary.
"""
return self._get_all_items(mobileclient.ListPromotedTracks,
incremental=False,
updated_after=None)
def get_listen_now_items(self):
"""Returns a list of dictionaries of Listen Now albums and stations.
See :func:`get_listen_now_situations` for Listen Now situations.
Here is an example Listen Now album::
{
'album': {
'artist_metajam_id': 'A2mfgoustq7iqjdbvlenw7pnap4',
'artist_name': 'Justin Bieber',
'artist_profile_image': {
'url': 'http://lh3.googleusercontent.com/XgktDR74DWE9xD...'',
},
'description': 'Purpose is the fourth studio album by Canadian...',
'description_attribution': {
'kind': 'sj#attribution',
'license_title': 'Creative Commons Attribution CC-BY-SA 4.0',
'license_url': 'http://creativecommons.org/licenses/by-sa/4.0/legalcode',
'source_title': 'Wikipedia',
'source_url': 'http://en.wikipedia.org/wiki/Purpose_(Justin_Bieber_album)',
},
'id': {
'artist': 'Justin Bieber',
'metajamCompactKey': 'Bqpez5cimsze2fh6w7j2rcf55xa',
'title': 'Purpose (Deluxe)',
},
'title': 'Purpose (Deluxe)'
'images': [
{
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/m66cbl4Jl3VNz...',
},
],
}
'kind': 'sj#listennowitem',
'suggestion_reason': '9',
'suggestion_text': 'Popular album on Google Play Music',
'type': '1'
}
Here is an example Listen Now station::
{
'radio_station': {
'id': {
'seeds': [
{
'artistId': 'Ax6ociylvowozcz2iepfqsar54i',
'kind': 'sj#radioSeed',
'metadataSeed': {
'artist': {
'artistArtRef': 'http://lh3.googleusercontent.com/x9qukAx...',
'artistArtRefs': [
{
'aspectRatio': '2',
'autogen': False,
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/x9qukAx...',
},
],
'artistId': 'Ax6ociylvowozcz2iepfqsar54i',
'artist_bio_attribution': {
'kind': 'sj#attribution',
'source_title': 'artist representative',
},
'kind': 'sj#artist',
'name': 'Drake',
},
'kind': 'sj#radioSeedMetadata',
},
'seedType': '3',
},
]
},
'title': 'Drake',
},
'compositeArtRefs': [
{
'aspectRatio': '2',
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/rE39ky1yZN...',
},
{
'aspectRatio': '1',
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/Pcwg_HngBr...',
},
],
'images': [
{
'aspectRatio': '2',
'autogen': False,
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/x9qukAx_TMam...',
},
],
'suggestion_reason': '9',
'suggestion_text': 'Popular artist on Google Play Music',
'type': '3'
}
"""
res = self._make_call(mobileclient.ListListenNowItems)
return res['listennow_items']
def get_listen_now_situations(self):
"""Returns a list of dictionaries that each represent a Listen Now situation.
See :func:`get_listen_now_items` for Listen Now albums and stations.
A situation contains a list of related stations or other situations.
Here is an example situation::
{
'description': 'Select a station of today's most popular songs.',
'id': 'Ntiiwllegkw73p27o236mfsj674',
'imageUrl': 'http://lh3.googleusercontent.com/egm4NgIK-Cmh84GjVgH...',
'stations': [
{
'compositeArtRefs': [
{
'aspectRatio': '2',
'kind': 'sj#imageRef',
'url': 'http://lh3.googleusercontent.com/ffDI377y...',
},
],
'contentTypes': ['1'],
'description': "This playlist features today's biggest pop songs...",
'imageUrls': [
{