forked from gmusicproxy/gmusicproxy
-
Notifications
You must be signed in to change notification settings - Fork 2
/
GMusicProxy
executable file
·1674 lines (1429 loc) · 60.6 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 python3
# -*- coding: utf-8 -*-
#
# Google Play Music Proxy
# © Mario Di Raimondo < mario.diraimondo (at) gmail.com >
# "Let's stream Google Play Music using any media-player"
#
# contributors:
# - Gianluca Boiano
# - 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 argparse
import errno
import logging
import os
import pprint
import random
import signal
import socket
import sys
import tempfile
import threading
from configparser import ConfigParser
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
from urllib.parse import parse_qs, urlparse
from urllib.request import build_opener
import eyed3.id3
import gmusicapi
import gmusicapi.utils
import netifaces
import requests
import urllib3
from gmusicapi.exceptions import CallFailure
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
try:
import daemon
except Exception:
pass
class MultiThreadedHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True
class GetHandler(BaseHTTPRequestHandler):
def do_GET(self):
logger.debug("request path: %s", self.path)
parsedPath = urlparse(self.path)
params = parse_qs(parsedPath.query)
if parsedPath.path == "/get_song" and "id" in params:
if 'quality' in params:
self._get_song(id=params['id'][0], quality=params['quality'][0])
else:
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 == "/get_listen_now":
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_listen_now(
format=params["format"][0] if "format" in params else "m3u",
type=params["type"][0] if "type" in params else "album",
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_situations":
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_situations(
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_promoted":
self._send_headers(
200,
"audio/mpegurl",
"inline; filename=playlist.m3u")
self._get_promoted(
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]
if "title" in params else "",
query_artist=params["artist"][0]
if "artist" in params else "",
exact=params["exact"][0].lower().strip()
if "exact" in params else "yes",
)
if result:
self.wfile.write(result.encode('utf-8'))
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]
if "title" in params else "",
query_artist=params["artist"][0]
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]
if "title" in params else "",
query_artist=params["artist"][0]
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(self.path)
params = 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, quality='hi'):
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
while True:
with self.server.lock:
for song in self.server.allSongsCache:
if (("storeId" in song and song["storeId"] == id)
or ("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:
if id[0] == "T":
info = self._robust_retry(
lambda: api.get_track_info(store_track_id=id))
else:
logger.error(
"Unsupported id '%s': report info to reproduce this to the author",
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 "year" in info and info["year"]:
tags.recording_date = int(info["year"])
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, quality=quality))
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().get("Content-Length"):
songSize = int(mp3.info().get("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".encode("utf-8"))
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_situations(self, format, separator, onlyUrl):
logger.info(
"Getting Listen Now situations as plain-text list..."
if format == "text"
else "Getting Listen Now situations as M3U list...")
situations = self._robust_retry(
lambda: api.get_listen_now_situations())
logger.debug(pprint.pformat(situations))
if format.lower().strip() != "text":
self.wfile.write("#EXTM3U\n".encode("utf-8"))
logger.debug(
"generated playlist:"
if format.lower().strip() == "text"
else "generated playlist:\n#EXTM3U")
for situation in situations:
if "id" in situation:
name = situation["title"]
curatedId = situation["stations"][0]["seed"]["curatedStationId"]
idtype = "situation"
if format.lower().strip() == "text":
line = "%shttp://%s:%s/get_new_station_by_id?id=%s&type=%s" % (
"Listen Now - %s%s" % (name, separator)
if ("title" in situation
and onlyUrl.lower().strip() != "yes")
else "Listen Now",
config["host"],
config["port"],
curatedId,
idtype,
)
else:
line = "#EXTINF:-1,%s\nhttp://%s:%s/get_new_station_by_id?id=%s&type=%s" % (
"Listen Now - %s" % name,
config["host"],
config["port"],
curatedId,
idtype,
)
self.wfile.write(("%s\n" % line).encode("utf-8"))
logger.debug(line)
def _get_listen_now(self, format, type, separator, onlyUrl):
logger.info(
"Getting Listen Now artists or albums as plain-text list..."
if format == "text"
else "Getting Listen Now artists or albums as M3U list...")
items = self._robust_retry(
lambda: api.get_listen_now_items())
logger.debug(pprint.pformat(items))
if format.lower().strip() != "text":
self.wfile.write("#EXTM3U\n".encode("utf-8"))
logger.debug(
"generated playlist:"
if format.lower().strip() == "text"
else "generated playlist:\n#EXTM3U")
for item in items:
if type == "artist":
if "radio_station" in item:
artist = item["radio_station"]["title"]
seed = item["radio_station"]["id"]["seeds"][0]
if "artistId" in seed:
stationId = api.create_station(
name=artist,
artist_id=seed["artistId"],
)
if format.lower().strip() == "text":
line = "%shttp://%s:%s/get_station?id=%s" % (
"Listen Now - %s%s" % (artist, separator) if
onlyUrl.lower().strip() != "yes" else "",
config["host"],
config["port"],
stationId,
)
else:
line = "#EXTINF:-1,%s\nhttp://%s:%s/get_station?id=%s" % (
"Listen Now - %s" % artist,
config["host"],
config["port"],
stationId,
)
self.wfile.write(("%s\n" % line).encode("utf-8"))
logger.debug(line)
else:
if "album" in item:
info = item["album"]["id"]
albumId = info["metajamCompactKey"]
artist = info["artist"]
title = info["title"]
if format.lower().strip() == "text":
line = "%shttp://%s:%s/get_album?id=%s" % (
"Listen Now - %s's %s%s" % (artist, title, separator) if
onlyUrl.lower().strip() != "yes" else "",
config["host"],
config["port"],
albumId,
)
else:
line = "#EXTINF:-1,%s\nhttp://%s:%s/get_album?id=%s" % (
"Listen Now - %s's %s" % (artist, title),
config["host"],
config["port"],
albumId,
)
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(b"#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" % (
str(int(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,
curated_station_id=id if type == "situation" 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(b"#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" % (
str(int(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(b"#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" % (
str(int(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"],