forked from gmusicproxy/gmusicproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGMusicProxy
executable file
·1039 lines (943 loc) · 51.3 KB
/
GMusicProxy
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# Google Play Music Proxy © Mario Di Raimondo < mario.diraimondo (at) gmail.com >
# "Let's stream Google Play Music using any music program"
#
# contributors:
# - Nick Depinet < depinetnick (at) gmail.com >
# - Adam Prato < adam.prato (at) gmail.com >
# - Pierre Karashchuk < krchtchk (at) gmail.com >
# - Alex Busenius
# - Mark Gillespie < mark.gillespie (at) gmail.com >
#
# license: GPL v3
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import BaseHTTPServer
import socket
import urlparse
import urllib2
import requests
import signal
import os
import sys
import errno
import tempfile
import netifaces
import pprint
import argparse
import ConfigParser
import xdg.BaseDirectory
import StringIO
import logging
import distutils.version
import threading
import gmusicapi
import gmusicapi.utils
import eyed3.id3
import random
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from SocketServer import ThreadingMixIn
from gmusicapi.exceptions import CallFailure
try:
import daemon
except Exception:
pass
try:
import keyring.core as keyring
except ImportError:
pass
class MultiThreadedHTTPServer(ThreadingMixIn, BaseHTTPServer.HTTPServer):
daemon_threads = True
class GetHandler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
logger.debug('request path: %s', self.path)
parsedPath = urlparse.urlparse(self.path)
params = urlparse.parse_qs(parsedPath.query)
if parsedPath.path == '/get_song' and 'id' in params:
self._get_song(id=params['id'][0])
elif parsedPath.path == '/get_all_stations':
self._send_headers(200, 'audio/mpegurl', 'inline; filename=playlist.%s' % 'txt' if (
'format' in params and params['format'][0].lower().strip() == 'text') else 'm3u')
if self._check_aa():
return
self._get_all_stations(format=params['format'][0] if 'format' in params else 'm3u', separator=params['separator'][
0] if 'separator' in params else '|', onlyUrl=params['only_url'][0] if 'only_url' in params else 'no')
elif parsedPath.path == '/get_all_playlists':
self._send_headers(200, 'audio/mpegurl', 'inline; filename=playlist.%s' % 'txt' if (
'format' in params and params['format'][0].lower().strip() == 'text') else 'm3u')
self._get_all_playlists(format=params['format'][0] if 'format' in params else 'm3u', separator=params['separator'][
0] if 'separator' in params else '|', onlyUrl=params['only_url'][0] if 'only_url' in params else 'no')
elif parsedPath.path == '/get_station' and 'id' in params:
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
self._get_station(id=params['id'][0], numTracks=params['num_tracks'][
0] if 'num_tracks' in params else defaultNumberTracksStation)
elif parsedPath.path == '/get_ifl_station':
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
self._get_station(id='IFL', numTracks=params['num_tracks'][
0] if 'num_tracks' in params else defaultNumberTracksStation)
elif parsedPath.path == '/get_playlist' and 'id' in params:
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
self._get_playlist(id=params['id'][0], shuffle=True if ('shuffle' in params and params['shuffle'][0] == 'yes') else False)
elif parsedPath.path == '/get_album' and 'id' in params:
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
self._get_album(id=params['id'][0])
elif parsedPath.path == '/get_top_tracks_artist' and 'id' in params:
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
self._get_top_tracks_artist(id=params['id'][0], numTracks=params['num_tracks'][
0] if 'num_tracks' in params else defaultNumberTopTracks)
elif parsedPath.path == '/get_discography_artist' and 'id' in params:
self._send_headers(200, 'audio/mpegurl', 'inline; filename=playlist.%s' % 'txt' if (
'format' in params and params['format'][0].lower().strip() == 'text') else 'm3u')
if self._check_aa():
return
self._get_discography_artist(id=params['id'][0], format=params['format'][0] if 'format' in params else 'm3u', separator=params[
'separator'][0] if 'separator' in params else '|', onlyUrl=params['only_url'][0] if 'only_url' in params else 'no')
elif parsedPath.path == '/get_collection':
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
self._get_collection( ratingthreshold=params['rating'][0] if 'rating' in params else 0, shuffle=True if ('shuffle' in params and params['shuffle'][0] == 'yes') else False, )
elif parsedPath.path == '/search_id' and 'type' in params and ('title' in params or 'artist' in params):
self._send_headers(200)
if self._check_aa():
return
result = self._search(type=params['type'][0].lower().strip() if 'type' in params else 'artist', query_title=params['title'][0].decode(
'latin-1') if 'title' in params else '', query_artist=params['artist'][0].decode('latin-1') if 'artist' in params else '', exact=params['exact'][0].lower().strip() if 'exact' in params else 'yes')
if result:
self.wfile.write(result)
elif parsedPath.path == '/get_by_search' and 'type' in params and ('title' in params or 'artist' in params):
if self._check_aa():
return
if ('type' in params and params['type'][0].lower().strip() != 'song'):
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
result = self._search(type=params['type'][0].lower().strip() if 'type' in params else 'artist', query_title=params['title'][0].decode('latin-1') if 'title' in params else '', query_artist=params['artist'][
0].decode('latin-1') if 'artist' in params else '', exact=params['exact'][0].lower().strip() if 'exact' in params else 'no', max_results=params['num_tracks'][0] if 'num_tracks' in params else None)
if result and len(result) > 0:
if params['type'][0].lower().strip() == 'artist':
self._get_top_tracks_artist(result, numTracks=params['num_tracks'][
0] if 'num_tracks' in params else defaultNumberTopTracks)
elif params['type'][0].lower().strip() == 'song':
self._get_song(result)
elif params['type'][0].lower().strip() == 'album':
self._get_album(result)
elif params['type'][0].lower().strip() == 'matches':
self._get_matches(result, numTracks=params['num_tracks'][
0] if 'num_tracks' in params else defaultNumberTopTracks)
elif parsedPath.path == '/get_new_station_by_id' and 'id' in params and 'type' in params:
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
if 'transient' in params and params['transient'][0].lower().strip() == 'no' and ('name' not in params or len(params['name'][0]) == 0):
logger.warning('A new persistent station requires a name!')
return
self._get_new_station(id=params['id'][0], type=params['type'][0].lower().strip(), numTracks=params['num_tracks'][0] if 'num_tracks' in params else defaultNumberTracksStation, transient=params[
'transient'][0].lower().strip() if 'transient' in params else 'yes', name=params['name'][0] if 'name' in params else transientStationName)
elif parsedPath.path == '/get_new_station_by_search' and 'type' in params and ('title' in params or 'artist' in params):
self._send_headers(200, 'audio/mpegurl',
'inline; filename=playlist.m3u')
if self._check_aa():
return
if 'transient' in params and params['transient'][0].lower().strip() == 'no' and ('name' not in params or len(params['name'][0]) == 0):
logger.warning('A new persistent station requires a name!')
return
result = self._search(type=params['type'][0].lower().strip() if 'type' in params else 'artist', query_title=params['title'][0].decode(
'latin-1') if 'title' in params else '', query_artist=params['artist'][0].decode('latin-1') if 'artist' in params else '', exact=params['exact'][0].lower().strip() if 'exact' in params else 'no')
if result and len(result) > 0:
self._get_new_station(id=result, type=params['type'][0].lower().strip(), numTracks=params['num_tracks'][0] if 'num_tracks' in params else defaultNumberTracksStation, transient=params[
'transient'][0].lower().strip() if 'transient' in params else 'yes', name=params['name'][0] if 'name' in params else transientStationName)
elif parsedPath.path == '/like_song' and 'id' in params:
self._send_headers(200)
self._rate_song(id=params['id'][0], rating=5)
elif parsedPath.path == '/dislike_song' and 'id' in params:
self._send_headers(200)
self._rate_song(id=params['id'][0], rating=1)
else:
self._send_headers(500)
logger.warning(
'Unknown command \'%s\' or missing required parameter!', parsedPath.path)
return
def do_HEAD(self):
logger.debug('HEAD request path: %s', self.path)
parsedPath = urlparse.urlparse(self.path)
params = urlparse.parse_qs(parsedPath.query)
if parsedPath.path == '/get_song' and 'id' in params:
self._get_song(id=params['id'][0], only_headers=True)
else:
self._send_headers(500)
logger.warning(
'Unknown command \'%s\' or missing required parameter!', parsedPath.path)
return
def _send_headers(self, response_code=200, content_type=None, content_disposition=None, content_length=None, icy_metaint=None, icy_name=None):
self.send_response(response_code)
if content_type:
self.send_header('Content-Type', content_type)
if content_disposition:
self.send_header('Content-Disposition', content_disposition)
if content_length:
self.send_header('Content-Length', content_length)
if icy_metaint:
self.send_header('icy-metaint', icy_metaint)
if icy_name:
self.send_header('icy-name', icy_name)
self.send_header('Access-Control-Allow-Origin', '*')
self.end_headers()
def _check_aa(self):
if config['disable_all_access']:
logger.warning(
'This functionality requires an All Access subscription!')
return config['disable_all_access']
def _fetch_songs_list_cache(self):
logger.debug('Fetching list of songs in collection')
with self.server.lock:
self.server.allSongsCache = self._robust_retry(
lambda: api.get_all_songs())
def _icy_name(self, album=None, artist=None, title=None):
return ('%s /// %s /// %s' % (artist, album, title)).encode('utf-8')
def _icy_metadata(self, album=None, artist=None, title=None):
text = 'StreamTitle=\'%ss\';' % (
self._icy_name(album, artist, title).decode('utf-8'))
metadata = (chr(len(text)) + text).ljust(len(text) * 16 + 1, chr(0))
return metadata.encode('utf-8')
def _get_song(self, id, only_headers=False):
if config['disable_all_access'] or id[0] != 'T':
info = None
# this more expensive method to get track info is necessary if we can't use the All Access 'get_track_info' method or if we are using the universal (uuid-style) id (tracks in collection)
# I try to mitigate the fetch cost using a RAM-based cache
if not hasattr(self.server, 'allSongsCache'):
self._fetch_songs_list_cache()
refetchOnFailure = True
with self.server.lock:
while True:
for song in self.server.allSongsCache:
if ('nid' in song and song['nid'] == id) or ('id' in song and song['id'] == id):
info = song.copy()
refetchOnFailure = False
break
if info is None and refetchOnFailure:
logger.debug(
'Look-up failure in cache for track info, refetching!')
self._fetch_songs_list_cache()
refetchOnFailure = False
else:
break
else:
info = self._robust_retry(
lambda: api.get_track_info(store_track_id=id))
if info is None:
logger.info('Streaming song with id \'%s\'', id)
tagsBin = None
tagsSize = 0
songSize = 0
else:
logger.info('Streaming song with id \'%s\': %s - %s',
id, info['artist'], info['title'])
logger.debug(pprint.pformat(info))
tags = eyed3.id3.Tag()
if 'artist' in info:
tags.artist = info['artist']
# extra check for support of 'album_artist' by eyed3:
# https://bitbucket.org/nicfit/eyed3/commits/9071bba4977f
if 'albumArtist' in info and 'album_artist' in dir(tags):
tags.album_artist = info['albumArtist']
if 'album' in info:
tags.album = info['album']
if 'title' in info:
tags.title = info['title']
if 'trackNumber' in info:
tags.track_num = info['trackNumber']
if 'discNumber' in info:
tags.disc_num = info['discNumber']
if 'genre' in info:
tags.genre = eyed3.id3.Genre(info['genre'])
if 'albumArtRef' in info:
albumArt = opener.open(info['albumArtRef'][0]['url']).read()
tags.images.set(3, albumArt, "image/jpeg")
if 'estimatedSize' in info:
songSize = int(info['estimatedSize'])
else:
songSize = 0
# weird hack: write the id3 tag on a temporary file and reload it
# (no way to render it on memory...)
tempFile = tempfile.NamedTemporaryFile(delete=False)
tags.save(tempFile.name)
tagsBin = tempFile.read()
tagsSize = len(tagsBin)
tempFile.close()
os.unlink(tempFile.name)
url = self._robust_retry(lambda: api.get_stream_url(song_id=id))
logger.debug('streaming url: %s', url)
do_shoutcast = config[
'shoutcast_metadata'] and 'icy-metadata' in self.headers
mp3 = opener.open(url)
logger.debug('tag size: %s byte', tagsSize)
logger.debug('content estimated size: %s byte', songSize)
if mp3.info().getheader('Content-Length'):
songSize = int(mp3.info().getheader('Content-Length'))
logger.debug('content size from HTTP headers: %s byte', songSize)
self._send_headers(200, 'audio/mpeg', 'inline; filename=%s.mp3' % id.strip(), ((tagsSize if not do_shoutcast else 0) + songSize) if (songSize > 0)
else None, downloadBlockSize if do_shoutcast else None, self._icy_name(tags.album, tags.artist, tags.title) if config['shoutcast_metadata'] else None)
if not only_headers:
if tagsBin and not do_shoutcast:
self.wfile.write(tagsBin)
# prefill cache
writtenBytes = 0
block = mp3.read(downloadBlockSize)
while len(block) > 0:
self.wfile.write(block)
writtenBytes += len(block)
if do_shoutcast:
self.wfile.write(self._icy_metadata(
tags.album, tags.artist, tags.title))
block = mp3.read(downloadBlockSize)
if songSize > 0 and writtenBytes > cachePrefillSize and songSize - writtenBytes < maxCacheSize:
break
if not config['disable_playcount_increment']:
logger.info('Increment playcount')
self._robust_retry(
lambda: api.increment_song_playcount(song_id=id))
if songSize < 0:
return
# consume the end of stream
cache = bytearray(0)
while len(block) > 0:
cache.extend(block)
block = mp3.read(downloadBlockSize)
# serve from cache
cacheSize = len(cache)
position = 0
while position < cacheSize:
self.wfile.write(cache[position:position + min(cacheSize - position, downloadBlockSize)])
position += downloadBlockSize
if do_shoutcast:
self.wfile.write(self._icy_metadata(
tags.album, tags.artist, tags.title))
def _get_all_stations(self, format, separator, onlyUrl):
logger.info('Getting all stations as plain-text list...' if format ==
'text' else 'Getting all stations as M3U list...')
stations = self._robust_retry(lambda: api.get_all_stations())
logger.debug(pprint.pformat(stations))
if format.lower().strip() != 'text':
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:' if format.lower().strip()
== 'text' else 'generated playlist:\n#EXTM3U')
for station in stations:
if 'id' in station:
if format.lower().strip() == 'text':
line = '%shttp://%s:%s/get_station?id=%s' % ('%s%s' % (station['name'], separator) if (
'name' in station and onlyUrl.lower().strip() != 'yes') else '', config['host'], config['port'], station['id'])
else:
line = '#EXTINF:-1,%s\nhttp://%s:%s/get_station?id=%s' % (
station['name'] if 'name' in station else '', config['host'], config['port'], station['id'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_all_playlists(self, format, separator, onlyUrl):
logger.info('Getting all playlists as plain-text list...' if format.lower().strip()
== 'text' else 'Getting all playlists as M3U list...')
playlists = self._robust_retry(lambda: api.get_all_playlists())
logger.debug(pprint.pformat(playlists))
if format.lower().strip() != 'text':
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:' if format.lower().strip()
== 'text' else 'generated playlist:\n#EXTM3U')
for playlist in playlists:
if 'id' in playlist:
useToken = False
if 'type' in playlist and playlist['type'] == 'SHARED':
useToken = True
if format.lower().strip() == 'text':
line = '%shttp://%s:%s/get_playlist?id=%s' % ('%s%s' % (playlist['name'], separator) if (
'name' in playlist and onlyUrl.lower().strip() != 'yes') else '', config['host'], config['port'], playlist['id'] if not useToken else playlist['shareToken'])
else:
line = '#EXTINF:-1,%s\nhttp://%s:%s/get_playlist?id=%s' % (
playlist['name'] if 'name' in playlist else '', config['host'], config['port'], playlist['id'] if not useToken else playlist['shareToken'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_station(self, id, numTracks):
station = self._robust_retry(lambda: api.get_station_tracks(
station_id=id, num_tracks=numTracks))
logger.info(
'Getting %s tracks from station with id \'%s\'', numTracks, id)
logger.debug(pprint.pformat(station))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
for track in station:
if 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_new_station(self, id, type, numTracks, transient, name):
stationId = api.create_station(name=name, track_id=id if type == 'song' else None, artist_id=id if type ==
'artist' else None, album_id=id if type == 'album' else None) # by genre: TO DO
if transient != 'no':
transientStationIds.append(stationId)
station = self._robust_retry(lambda: api.get_station_tracks(
station_id=stationId, num_tracks=numTracks))
if transient != 'no':
self._robust_retry(lambda: api.delete_stations(stationId))
transientStationIds.remove(stationId)
logger.info('Getting %s tracks from a new %s station based on %s id \'%s\'' % (
numTracks, 'transient' if transient != 'no' else 'persistent', type, id))
logger.debug(pprint.pformat(station))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
for track in station:
if 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_playlist(self, id, shuffle=False):
logger.info('Getting tracks from playlist with id \'%s\'', id)
# necessary to get track information on uploaded songs
wholeCollection = self._robust_retry(lambda: api.get_all_songs())
targetPlaylist = None
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
if id[0] == 'A' and id[1] == 'M':
targetPlaylist = self._robust_retry(
lambda: api.get_shared_playlist_contents(id))
logger.debug(pprint.pformat(targetPlaylist))
else:
# we have to download the content of all the playlists (actual API
# limitation)
playlistsWithContents = self._robust_retry(
lambda: api.get_all_user_playlist_contents())
logger.debug(pprint.pformat(playlistsWithContents))
for playlist in playlistsWithContents:
if 'id' in playlist and playlist['id'] == id:
targetPlaylist = playlist['tracks']
if targetPlaylist is not None:
if shuffle:
logger.info('Shuffling the playlist')
random.shuffle(targetPlaylist)
for track in targetPlaylist:
if 'trackId' in track:
foundTrack = None
if 'track' in track:
foundTrack = track['track']
else:
for song in wholeCollection:
if song['id'] == track['trackId']:
foundTrack = song
break
if foundTrack:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(foundTrack['durationMillis']) / 1000) if 'durationMillis' in foundTrack else -1, '%s - ' % foundTrack['artist'] if 'artist' in foundTrack else '', foundTrack[
'title'] if 'title' in foundTrack else '', ' - %s' % foundTrack['album'] if config['extended_m3u'] and 'album' in foundTrack else '', config['host'], config['port'], track['trackId'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
else:
logger.warning(
"no information available in collection of track with id '%s'!", track['trackId'])
else:
logger.warning("Playlist not found!")
def _get_album(self, id):
album = self._robust_retry(lambda: api.get_album_info(
album_id=id, include_tracks=True))
logger.info('Getting the tracks of the album with id \'%s\': %s - %s',
id, album['name'], album['artist'])
logger.debug(pprint.pformat(album))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
if 'tracks' in album:
for track in album['tracks']:
if 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_top_tracks_artist(self, id, numTracks):
artist = self._robust_retry(lambda: api.get_artist_info(
artist_id=id, include_albums=False, max_top_tracks=numTracks, max_rel_artist=0))
logger.info('Getting %s top tracks of the artist with id \'%s\': %s',
numTracks, id, artist['name'])
logger.debug(pprint.pformat(artist))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
if 'topTracks' in artist:
for track in artist['topTracks']:
if 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_discography_artist(self, id, format, separator, onlyUrl):
artist = self._robust_retry(lambda: api.get_artist_info(
artist_id=id, include_albums=True, max_top_tracks=0, max_rel_artist=0))
logger.info('Getting all albums of the artist with id \'%s\' (%s) as a %s list...', id, artist[
'name'], 'plain-text' if format == 'text' else 'M3U')
logger.debug(pprint.pformat(artist))
if format.lower().strip() != 'text':
self.wfile.write('#EXTM3U\n')
logger.debug('generated list:' if format.lower().strip()
== 'text' else 'generated list:\n#EXTM3U')
if 'albums' in artist:
for album in artist['albums']:
if 'albumId' in album:
if format.lower().strip() == 'text':
line = '%shttp://%s:%s/get_album?id=%s' % ('%s%s%s%s' % (album['name'], separator, album['year'], separator) if (
'name' in album and 'year' in album and onlyUrl.lower().strip() != 'yes') else '', config['host'], config['port'], album['albumId'])
else:
line = '#EXTINF:-1,%s [%s]\nhttp://%s:%s/get_album?id=%s' % (album['name'] if 'name' in album else '', album[
'year'] if 'year' in album else '', config['host'], config['port'], album['albumId'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_matches(self, matches, numTracks):
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
for song in matches:
track = song['track']
if 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _get_collection(self, ratingthreshold=0, shuffle=False):
songs = self._robust_retry(lambda: api.get_all_songs())
if len(songs) == 0:
logger.warning("No songs in your collection!?!")
return
if ratingthreshold > 0:
logger.info('Filtering out songs with rating lower than %s', ratingthreshold)
for song in songs:
songrating = song.get('rating')
if songrating is not None:
if int(songrating) < ratingthreshold:
songs.remove(song)
if shuffle:
logger.info('Shuffling the collection')
random.shuffle(songs)
logger.info('Getting your collection: %s tracks', len(songs))
logger.debug(pprint.pformat(songs))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
for track in songs:
if 'id' in track or 'nid' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['durationMillis']) / 1000) if 'durationMillis' in track else -1, '%s - ' % track['artist'] if 'artist' in track else '', track[
'title'] if 'title' in track else '', ' - %s' % track['album'] if config['extended_m3u'] and 'album' in track else '', config['host'], config['port'], track['id'] if 'id' in track else track['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
def _search(self, type, query_title, query_artist, exact, max_results=None):
if type is None or type not in ['artist', 'song', 'album', 'matches']:
logger.warning(
'The type of search has to be specified: artist, song, album or matches!')
return
logger.info('Searching for %s with query: %s %s',
type, query_artist, query_title)
match = None
if type == 'artist':
results = self._robust_retry(lambda: api.search(query_artist))
logger.debug(pprint.pformat(results))
if exact != 'yes' and 'artist_hits' in results and len(results['artist_hits']) > 0:
logger.debug(
'I\'m feeling lucky: lets select the first artist in list!')
match = results['artist_hits'][0]
else:
if 'artist_hits' in results:
for artist in results['artist_hits']:
if 'name' in artist['artist'] and artist['artist']['name'].lower().strip() == query_artist.lower().strip():
logger.debug(
'Found exact matching artist in list!')
match = artist
break
if match and 'artist' in match and 'artistId' in match['artist']:
logger.info('Selected artist: %s (%s)', match['artist'][
'name'], match['artist']['artistId'])
logger.debug(pprint.pformat(match))
return match['artist']['artistId']
else:
logger.warning('No matching found.')
elif type == 'song':
results = self._robust_retry(lambda: api.search(
'%s %s' % (query_artist, query_title)))
logger.debug(pprint.pformat(results))
if exact != 'yes' and 'song_hits' in results and len(results['song_hits']) > 0:
logger.debug('I\'m feeling lucky: lets select the first song!')
match = results['song_hits'][0]
else:
if 'song_hits' in results:
for song in results['song_hits']:
if 'title' in song['track'] and song['track']['title'].lower().strip() == query_title.lower().strip() and 'artist' in song['track'] and song['track']['artist'].lower().strip() == query_artist.lower().strip():
logger.debug('Found exact matching song!')
match = song
break
if match and 'track' in match and 'nid' in match['track']:
logger.info('Selected song: %s - %s (%s)', match['track'][
'artist'], match['track']['title'], match['track']['nid'])
logger.debug(pprint.pformat(match))
return match['track']['nid']
else:
logger.warning('No matching found.')
elif type == 'matches':
results = self._robust_retry(lambda: api.search(
'%s %s' % (query_artist, query_title), max_results))
logger.debug(pprint.pformat(results))
match = results['song_hits']
if match:
return match
else:
logger.warning('No matching found.')
elif type == 'album':
results = self._robust_retry(lambda: api.search(
'%s %s' % (query_artist, query_title)))
logger.debug(pprint.pformat(results))
if exact != 'yes' and 'album_hits' in results and len(results['album_hits']) > 0:
logger.debug(
'I\'m feeling lucky: lets select the first album in list!')
match = results['album_hits'][0]
else:
if 'album_hits' in results:
for album in results['album_hits']:
if 'name' in album['album'] and album['album']['name'].lower().strip() == query_title.lower().strip() and 'artist' in album['album'] and album['album']['artist'].lower().strip() == query_artist.lower().strip():
logger.debug('Found exact matching album in list!')
match = album
break
if match and 'album' in match and 'albumId' in match['album']:
logger.info('Selected album: %s - %s (%s)', match['album'][
'artist'], match['album']['name'], match['album']['albumId'])
logger.debug(pprint.pformat(match))
return match['album']['albumId']
else:
logger.warning('No matching found.')
else:
return
def _rate_song(self, id, rating=0):
if config['disable_all_access']:
info = None
# the same not so nice trick as above
allSongs = self._robust_retry(lambda: api.get_all_songs())
for song in allSongs:
if 'nid' in song and song['nid'] == id:
info = song.copy()
break
allSongs = None
else:
info = self._robust_retry(
lambda: api.get_track_info(store_track_id=id))
if info is None:
logger.warning('Song with id \'%s\' not found.', id)
else:
logger.info('Reporting rating=%s on song with id \'%s\': %s - %s',
rating, id, info['artist'], info['title'])
logger.debug(pprint.pformat(info))
info['rating'] = rating
self._robust_retry(lambda: api.change_song_metadata([info]))
@gmusicapi.utils.utils.retry(retry_exception=requests.exceptions.ConnectionError)
def _robust_retry(self, func):
return func()
def handle_one_request(self):
try:
BaseHTTPServer.BaseHTTPRequestHandler.handle_one_request(self)
except CallFailure, e:
if '401 Client Error: Unauthorized' in e.message and config['device_id'] != '**auto**':
logger.warning(
'Server denied authorization, trying to reconnect...')
api.logout()
api.login(config['email'], config[
'password'], config['device_id'])
if api.is_authenticated():
self.handle_one_request()
else:
logger.error(
'Sorry, could not reconnect, those credentials weren\'t accepted.')
sys.exit(1)
else:
raise
except socket.error, e:
if e[0] == errno.ECONNRESET:
logger.warning('Detected connection reset.')
elif e[0] == errno.EPIPE:
logger.warning('Detected remote peer disconnected.')
elif e[0] == 10053:
logger.warning(
'An established connection was aborted by the software in your host machine.')
else:
raise
def finish(self, *args, **kw):
# fix from http://stackoverflow.com/a/14355079/1834797
try:
if not self.wfile.closed:
self.wfile.flush()
self.wfile.close()
except socket.error:
pass
self.rfile.close()
def signalHandler(signal, frame):
logger.info('Shutting down the proxy...')
if server:
server.socket.close()
if len(transientStationIds) and api:
api.delete_stations(transientStationIds)
if api:
api.logout()
if opener:
opener.close()
sys.exit()
def getOptions(filename):
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', type=file,
help='specific configuration file to use')
parser.add_argument(
'-e', '--email', help='email address of the Google account [required]')
parser.add_argument(
'-p', '--password', help='password of the Google account (or an application-specific one if two-factor authentication is enabled) [required]')
parser.add_argument(
'-d', '--device-id', help='the ID of a registered Android/iOS device [default: fake-id based on mac address of network card]')
parser.add_argument(
'-H', '--host', help='host in the generated URLs [default: autodetected local ip address]')
parser.add_argument(
'-b', '--bind-address', help='ip address to bind to [default: 0.0.0.0=all]')
parser.add_argument('-P', '--port', type=int,
help='default TCP port to use [default: 9999]')
parser.add_argument('-a', '--disable-all-access', default=False,
action='store_true', help='disable All Access functionalities')
parser.add_argument('-L', '--list-devices', default=False,
action='store_true', help='list the registered devices')
parser.add_argument('-D', '--debug', default=False,
action='store_true', help='enable debug messages')
parser.add_argument('-l', '--log', help='log file')
parser.add_argument('-f', '--daemon', default=False,
action='store_true', help='daemonize the program')
parser.add_argument('-v', '--disable-version-check', default=False,
action='store_true', help='disable check for latest available version')
parser.add_argument('-x', '--extended-m3u', default=False,
action='store_true', help='enable non-standard extended m3u headers')
parser.add_argument('-s', '--shoutcast-metadata', default=False, action='store_true',
help='enable Shoutcast metadata protocol support (disabling IDv3 tags)')
parser.add_argument('-C', '--disable-playcount-increment', default=False, action='store_true',
help='disable the automatic increment of playcounts upon song fetch')
parser.add_argument(
'--keyring-backend', help='name of the keyring backend to use instead of the default one')
parser.add_argument('--list-keyring-backends', default=False,
action='store_true', help='list the available keyring backends')
parser.add_argument(
'--keyring-service', help='keyring service to use, takes precedence over --password if set')
parser.add_argument(
'--keyring-entry', help='keyring entry to use, required if --keyring-service is used')
config = ConfigParser.SafeConfigParser()
args = parser.parse_args()
fp = StringIO.StringIO('[dummy]\n')
config.readfp(fp)
if args.config:
fp = StringIO.StringIO('[dummy]\n' + args.config.read())
config.readfp(fp)
else:
for path in reversed(list(xdg.BaseDirectory.load_config_paths(filename))):
fp = StringIO.StringIO('[dummy]\n' + open(path, 'r').read())
config.readfp(fp)
configValues = dict(config.items('dummy'))
# adjust some names in order to make work configparser with argparse
for key in configValues.keys():
if '-' in key:
configValues[key.replace('-', '_')] = configValues.pop(key)
if 'bind_address' in configValues and 'host' not in configValues:
configValues['host'] = configValues['bind_address']
# some defaults
if 'bind_address' not in configValues:
configValues['bind_address'] = '0.0.0.0'
if 'host' not in configValues:
configValues['host'] = '**auto**'
if 'port' not in configValues:
configValues['port'] = '9999'
if 'device_id' not in configValues:
configValues['device_id'] = '**auto**'
parser.set_defaults(**configValues)
args = parser.parse_args()
config = vars(args)
return config
def listDevices():
devices = api.get_registered_devices()
if len(devices) == 0:
logger.warning(
'No Android or iOS devices registered in your Google account.')
else:
api.logout()
for d in devices:
if (d['type'] == 'ANDROID' or d['type'] == 'IOS'):
logger.info('- %s --> device-id=%s', d['friendlyName'] if d['friendlyName'] is not None and len(
d['friendlyName']) > 0 else '(None)', d['id'].replace('0x', ''))
sys.exit()
def loginGM(email, password, device_id=gmusicapi.Mobileclient.FROM_MAC_ADDRESS):
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
api = gmusicapi.Mobileclient(debug_logging=config['debug'])
if config['debug']:
api.logger = logger
api.login(email, password, device_id)
if not api.is_authenticated():
logger.error('Sorry, those credentials weren\'t accepted.')
sys.exit(1)
return api
def autodetectLocalIP():
interfaces = reversed(netifaces.interfaces())
for i in interfaces:
if i == 'lo':
continue
iface = netifaces.ifaddresses(i).get(netifaces.AF_INET)
if iface != None:
for j in iface:
return j['addr']
return '127.0.0.1'
def checkLatestVersion():
logger.debug('Fetching lastest version of %s...', programName)
try:
latestVersion = opener.open(urlLatestVersion).read()
logger.debug('latest available version: %s', latestVersion)
logger.debug('installed version: %s', programVersion)
if latestVersion == '':
raise ValueError
if distutils.version.StrictVersion(programVersion) < distutils.version.StrictVersion(latestVersion):
logger.warning(
'There is a new %s release of %s. Consider the idea to update your installation in order to keep it working!\n', latestVersion, programName)
except urllib2.URLError:
logger.debug('Error in fetching version information')
except ValueError:
logger.debug('Error on malformed version data (\'%s\', \'%s\')',
latestVersion, programVersion)
def checkKeyringModule():
if not 'keyring' in globals():
logger.error('Python \'keyring\' module is not available!\n'
'Please consult https://pypi.python.org/pypi/keyring#installation-instructions to use keyring feature')
sys.exit(1)
def getKeyringPassword():
checkKeyringModule()
try:
if config['keyring_backend']:
keyring.set_keyring(keyring.load_keyring(
config['keyring_backend']))
if config['keyring_service'] is None or config['keyring_entry'] is None:
logger.error(
'Please, specify both keyring service and keyring entry in the config file or on the command-line to use keyring feature.')
sys.exit(1)
password = keyring.get_password(
config['keyring_service'], config['keyring_entry'])
if (password is None):
logger.error('No password is stored in entry \'%s\' of service \'%s\'', config[
'keyring_entry'], config['keyring_service'])
return password
except Exception, e:
logger.error('Failed to access keyring: %s', e.message)
sys.exit(1)
def listKeyringBackends():
checkKeyringModule()
logger.info('Available keyring backends:')
for backend in keyring.backend.get_all_keyring():
logger.info(' %s.%s', type(backend).__module__,
type(backend).__name__)
sys.exit()
if __name__ == '__main__':
downloadBlockSize = 16 * 1024
cachePrefillSize = 60 * 320/8 * 1024 # 60 seconds at 320 kbit/s
maxCacheSize = 180 * 320/8 * 1024 # 180 seconds
defaultNumberTracksStation = 50
defaultNumberTopTracks = 20
programDescription = 'Google Play Music Proxy'
programName = 'gmusicproxy'
programMainAuthor = 'Mario Di Raimondo'
programVersion = '1.0.8b3'
configFilename = '%s.cfg' % programName
transientStationName = '%s station ' % programDescription
transientStationIds = []
urlLatestVersion = 'http://gmusicproxy.net/latest_version.php'
config = dict()
# remove previous root logging handler
logger = logging.getLogger()
map(logger.removeHandler, logger.handlers[:])
# initial setup of my logger
logger = logging.getLogger(programName)
logger.setLevel(logging.INFO)
consoleHandler = logging.StreamHandler(sys.stdout)
consoleHandler.setFormatter(logging.Formatter('%(message)s'))
logger.addHandler(consoleHandler)
config = getOptions(configFilename)
# complete setup of the logger
fileHandler = None
if config['log']:
fileHandler = logging.FileHandler(config['log'], encoding='utf-8')
logger.addHandler(fileHandler)
if config['debug']:
logger.setLevel(logging.DEBUG)
if fileHandler:
fileHandler.setFormatter(logging.Formatter(
'[%(levelname)s] (%(module)s:%(lineno)s): %(message)s'))
logger.info(u'%s %s (© %s)\n', programDescription,
programVersion, programMainAuthor)
# preliminar setup for the daemonaization
if config['daemon']:
if os.name == 'nt':
logger.error('Daemon-mode is not supported under Windows!')
sys.exit(1)
if not 'daemon' in globals():
logger.error('Python \'daemon\' module is not installed!')
sys.exit(1)
contextDaemon = daemon.DaemonContext(files_preserve=[])
# python-daemon>=2.1 has initgroups=True by default but it requires root privs
# older versions don't support initgroups as constructor parameter so
# we set it manually instead
contextDaemon.initgroups = False
if fileHandler:
contextDaemon.files_preserve.append(fileHandler.stream)
consoleHandler.setLevel(logging.ERROR)
safeConfig = config.copy()
safeConfig['password'] = '***OMITTED***' # for debug dump
logger.debug('configuration used:\n%s\n', pprint.pformat(safeConfig))
if config['keyring_service'] is not None or config['keyring_entry'] is not None:
config['password'] = getKeyringPassword()
if config['email'] is None or config['password'] is None or len(config['email']) == 0 or len(config['password']) == 0:
logger.error(
'Please, specify the credentials of your Google account in the config file or on the command-line.')