forked from gmusicproxy/gmusicproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
GMusicProxy
658 lines (605 loc) · 38.1 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
#!/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 >
#
# 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, socket, urlparse, urllib2, requests
import signal, os, sys, errno, tempfile, netifaces, pprint, argparse, ConfigParser, xdg.BaseDirectory, StringIO, logging, daemon, distutils.version
import gmusicapi, gmusicapi.utils, eyed3.id3
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.send_response(200)
self.send_header('Content-type', 'audio/mpeg')
self.send_header('Content-disposition', 'inline; filename=%s.mp3' % params['id'][0].strip())
self.end_headers()
self._get_song(id=params['id'][0])
elif parsedPath.path == '/get_all_stations':
self.send_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.%s' % 'txt' if ('format' in params and params['format'][0].lower().strip() == 'text') else 'm3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.%s' % 'txt' if ('format' in params and params['format'][0].lower().strip() == 'text') else 'm3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
self._get_playlist(id=params['id'][0])
elif parsedPath.path == '/get_album' and 'id' in params:
self.send_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_collection':
self.send_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
self._get_collection()
elif parsedPath.path == '/search_id' and 'type' in params and ('title' in params or 'artist' in params):
self.send_response(200)
self.end_headers()
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):
self.send_response(200)
self.send_header('Content-type', 'audio/mpeg' if ('type' in params and params['type'][0].lower().strip() == 'song') else 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=%s' % 'track.mp3' if ('type' in params and params['type'][0].lower().strip() == 'song') else 'playlist.m3u')
self.end_headers()
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 '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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_response(200)
self.send_header('Content-type', 'audio/mpegurl')
self.send_header('Content-disposition', 'inline; filename=playlist.m3u')
self.end_headers()
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_response(200)
self.end_headers()
self._rate_song(id=params['id'][0], rating=5)
elif parsedPath.path == '/dislike_song' and 'id' in params:
self.send_response(200)
self.end_headers()
self._rate_song(id=params['id'][0], rating=1)
else:
self.send_response(500)
self.end_headers()
logger.warning('Unknown command \'%s\' or missing required parameter!', parsedPath.path)
return
def _check_aa(self):
if config['disable_all_access']:
logger.warning('This functionality requires an All Access subscription!')
return config['disable_all_access']
def _get_song(self, id):
if config['disable_all_access']:
info = None
# a not so nice trick: we can't use the All Access 'get_track_info' method so we have to download the complete list of all the tracks in collection to get the information about this specific track
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.info('Streaming song with id \'%s\'', id)
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']
if 'albumArtist' in info and 'album_artist' in dir(tags): ## extra check for support of 'album_artist' by eyed3: https://bitbucket.org/nicfit/eyed3/commits/9071bba4977f
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")
# 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()
tempFile.close()
os.unlink(tempFile.name)
self.wfile.write(tagsBin)
url = self._robust_retry(lambda:api.get_stream_url(song_id=id, device_id=config['device_id']))
logger.debug('streaming url: %s', url)
mp3 = opener.open(url)
block = mp3.read(downloadBlockSize)
while len(block) > 0:
self.wfile.write(block)
block = mp3.read(downloadBlockSize)
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:
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'])
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'])
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):
logger.info('Getting tracks from playlist with id \'%s\'', id)
# 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))
# also use own uploaded songs for playlists
own_songs = self._robust_retry(lambda:api.get_all_songs())
logger.debug(pprint.pformat(own_songs))
self.wfile.write('#EXTM3U\n')
logger.debug('generated playlist:\n#EXTM3U')
found=False
for playlist in playlistsWithContents:
if 'id' in playlist and playlist['id'] == id:
for track in playlist['tracks']:
if 'trackId' in track:
if 'track' in track:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(track['track']['durationMillis'])/1000) if 'durationMillis' in track['track'] else -1, '%s - ' % track['track']['artist'] if 'artist' in track['track'] else '', track['track']['title'] if 'title' in track['track'] else '', ' - %s' % track['track']['album'] if config['extended_m3u'] and 'album' in track['track'] else '', config['host'], config['port'], track['trackId'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
else:
own_found=None
for song in own_songs:
if song['id'] == track['trackId']:
own_found = song
break
if own_found:
line = '#EXTINF:%s,%s%s%s\nhttp://%s:%s/get_song?id=%s' % ((int(own_found['durationMillis'])/1000) if 'durationMillis' in own_found else -1, '%s - ' % own_found['artist'] if 'artist' in own_found else '', own_found['title'] if 'title' in own_found else '', ' - %s' % own_found['album'] if config['extended_m3u'] and 'album' in own_found else '', config['host'], config['port'], own_found['nid'])
self.wfile.write(('%s\n' % line).encode('utf-8'))
logger.debug(line)
found=True
if not found: 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_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):
songs = self._robust_retry(lambda:api.get_all_songs())
if len(songs) == 0:
logger.warning("No songs in your collection!?!")
return
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 '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 _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_all_access(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_all_access('%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_all_access('%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_all_access('%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 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 device [required]')
parser.add_argument('-H', '--host', help='host in the generated URLs [default: autodetected local ip address]')
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')
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
if 'device-id' in configValues: configValues['device_id'] = configValues.pop('device-id')
if 'list-devices' in configValues: configValues['list_devices'] = configValues.pop('list-devices')
if 'disable-all-access' in configValues: configValues['disable_all_access'] = configValues.pop('disable-all-access')
if 'disable-version-check' in configValues: configValues['disable_version_check'] = configValues.pop('disable-version-check')
if 'extended-m3u' in configValues: configValues['extended_m3u'] = configValues.pop('extended-m3u')
# some defaults
if 'host' not in configValues: configValues['host']='**auto**'
if 'port' not in configValues: configValues['port']='9999'
parser.set_defaults(**configValues)
args = parser.parse_args()
config = vars(args)
return config
def listDevices(email, password):
api = gmusicapi.Webclient(debug_logging=config['debug'])
if config['debug']:
api.logger = logger
api.login(email, password)
if not api.is_authenticated():
logger.error('Sorry, those credentials weren\'t accepted.')
sys.exit(1)
devices = api.get_registered_devices()
api.logout()
if len(devices)==0:
logger.warning('No Android phone-like devices registered in your Google account.')
else:
for d in devices:
if d['type'] == 'PHONE':
logger.info('- %s (%s - %s) --> device-id=%s', d['name'], d['manufacturer'], d['model'], d['id'].replace('0x',''))
sys.exit()
def loginGM(email, password):
api = gmusicapi.Mobileclient(debug_logging=config['debug'])
if config['debug']:
api.logger = logger
api.login(email, password, config['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)
latestVersion = opener.open(urlLatestVersion).read()
logger.debug('latest available version: %s', latestVersion)
logger.debug('installed version: %s', programVersion)
try:
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 ValueError:
logger.debug('Error in fetching version information or malformed data (\'%s\', \'%s\')', latestVersion, programVersion)
if __name__ == '__main__':
downloadBlockSize = 40*1024
defaultNumberTracksStation = 50
defaultNumberTopTracks = 20
programDescription = 'Google Play Music Proxy'
programName = 'gmusicproxy'
programMainAuthor = 'Mario Di Raimondo'
programVersion = '0.9.9'
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']:
contextDaemon = daemon.DaemonContext(files_preserve=[])
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['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.')
sys.exit(1)
if config['list_devices']:
listDevices(config['email'], config['password'])
if config['device_id'] is None or len(config['device_id']) == 0:
logger.error('Please, specify the ID of an Android device registered in your Google account in the config file or on the command-line. Use the option \'--list-devices=true\' to auto-discover the IDs.')
sys.exit(1)
api = loginGM(config['email'], config['password'])
if config['host'] == '**auto**':
config['host'] = autodetectLocalIP()
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', '%s %s' % (programDescription, programVersion))]
signal.signal(signal.SIGINT, signalHandler)
if not config['disable_version_check']:
checkLatestVersion()
server = BaseHTTPServer.HTTPServer(('0.0.0.0', config['port']), GetHandler)
logger.info('Listening on port %s...', config['port'])
if config['daemon']:
contextDaemon.files_preserve.append(server.fileno())
with contextDaemon:
server.serve_forever()
else:
server.serve_forever()