-
Notifications
You must be signed in to change notification settings - Fork 5
/
koditidal.py
1451 lines (1298 loc) · 66.2 KB
/
koditidal.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016 Arne Svenson
#
# 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/>.
from __future__ import unicode_literals
import os, sys, re
import json
import datetime
from urlparse import urlsplit
import xbmc
import xbmcvfs
import xbmcgui
import xbmcaddon
import xbmcplugin
import requests
from xbmcgui import ListItem
from routing import Plugin
from tidalapi import Config, Session, User, Favorites
from tidalapi.models import Quality, SubscriptionType, AlbumType, BrowsableMedia, Artist, Album, PlayableMedia, Track, Video, Playlist, Promotion, Category, CutInfo
from m3u8 import load as m3u8_load
from debug import DebugHelper
class KodiPlugin(Plugin):
def __init__(self, base_url=None):
try:
# Creates a Dump is sys.argv[] is empty !
Plugin.__init__(self, base_url=base_url)
except:
pass
self.base_url = base_url
_addon_id = 'plugin.audio.tidal2'
addon = xbmcaddon.Addon(id=_addon_id)
plugin = KodiPlugin(base_url = "plugin://" + _addon_id)
plugin.name = addon.getAddonInfo('name')
_addon_icon = os.path.join(addon.getAddonInfo('path'), 'icon.png')
_addon_fanart = os.path.join(addon.getAddonInfo('path'), 'fanart.jpg')
debug = DebugHelper(pluginName=addon.getAddonInfo('name'),
detailLevel=2 if addon.getSetting('debug_log') == 'true' else 1,
enableTidalApiLog= True if addon.getSetting('debug_log') == 'true' else False)
log = debug.log
try:
version = json.loads(xbmc.executeJSONRPC('{ "jsonrpc": "2.0", "method": "Application.GetProperties", "params": {"properties": ["version", "name"]}, "id": 1 }'))['result']['version']
KODI_VERSION = (version['major'], version['minor'])
except:
KODI_VERSION = (16, 1)
CACHE_DIR = xbmc.translatePath(addon.getAddonInfo('profile')).decode('utf-8')
FAVORITES_FILE = os.path.join(CACHE_DIR, 'favorites.cfg')
PLAYLISTS_FILE = os.path.join(CACHE_DIR, 'playlists.cfg')
ALBUM_PLAYLIST_TAG = 'ALBUM'
VARIOUS_ARTIST_ID = '2935'
def _T(txtid):
if isinstance(txtid, basestring):
# Map TIDAL texts to Text IDs
newid = {'artist': 30101, 'album': 30102, 'playlist': 30103, 'track': 30104, 'video': 30105,
'artists': 30101, 'albums': 30102, 'playlists': 30103, 'tracks': 30104, 'videos': 30105,
'featured': 30203, 'rising': 30211, 'discovery': 30212, 'movies': 30115, 'shows': 30116, 'genres': 30117, 'moods': 30118
}.get(txtid.lower(), None)
if not newid: return txtid
txtid = newid
try:
txt = addon.getLocalizedString(txtid)
return txt
except:
return '%s' % txtid
def _P(key, default_txt=None):
# Plurals of some Texts
newid = {'new': 30111, 'local': 30112, 'exclusive': 30113, 'recommended': 30114, 'top': 30119,
'artists': 30106, 'albums': 30107, 'playlists': 30108, 'tracks': 30109, 'videos': 30110
}.get(key.lower(), None)
if newid:
return _T(newid)
return default_txt if default_txt else key
# Convert TIDAL-API Media into Kodi List Items
class HasListItem(object):
_is_logged_in = False
def setLabelFormat(self):
self._favorites_in_labels = True if addon.getSetting('favorites_in_labels') == 'true' else False
self._user_playlists_in_labels = True if addon.getSetting('user_playlists_in_labels') == 'true' else False
self.FOLDER_MASK = '{label}'
if self._favorites_in_labels:
self.FAVORITE_MASK = '<{label}>'
else:
self.FAVORITE_MASK = '{label}'
self.STREAM_LOCKED_MASK = '{label} ({info})'
if self._user_playlists_in_labels:
self.USER_PLAYLIST_MASK = '{label} [{userpl}]'
else:
self.USER_PLAYLIST_MASK = '{label}'
self.DEFAULT_PLAYLIST_MASK = '{label} ({mediatype})'
self.MASTER_AUDIO_MASK = '{label} (MQA)'
def getLabel(self, extended=True):
return self.name
def getListItem(self):
li = ListItem(self.getLabel())
if isinstance(self, PlayableMedia) and getattr(self, 'available', True):
li.setProperty('isplayable', 'true')
artwork = {'thumb': _addon_icon, 'fanart': _addon_fanart}
if getattr(self, 'image', None):
artwork['thumb'] = self.image
if getattr(self, 'fanart', None):
artwork['fanart'] = self.fanart
li.setArt(artwork)
# In Favorites View everything as a Favorite
if self._is_logged_in and hasattr(self, '_isFavorite') and '/favorites/' in sys.argv[0]:
self._isFavorite = True
cm = self.getContextMenuItems()
if len(cm) > 0:
li.addContextMenuItems(cm)
return li
def getContextMenuItems(self):
return []
def getSortText(self, mode=None):
return self.getLabel(extended=False)
class AlbumItem(Album, HasListItem):
def __init__(self, item):
self.__dict__.update(vars(item))
self.artist = ArtistItem(self.artist)
self.artists = [ArtistItem(artist) for artist in self.artists]
self._ftArtists = [ArtistItem(artist) for artist in self._ftArtists]
self._userplaylists = {} # Filled by parser
self._playlist_id = None # ID of the Playlist
self._playlist_pos = -1 # Item position in playlist
self._etag = None # ETag for User Playlists
self._playlist_name = None # Name of Playlist
self._playlist_type = '' # Playlist Type
self._playlist_track_id = 0 # Track-ID of item which is shown as Album Item
def getLabel(self, extended=True):
self.setLabelFormat()
label = self.getLongTitle()
if extended and self._isFavorite and not '/favorites/' in sys.argv[0]:
label = self.FAVORITE_MASK.format(label=label)
label = '%s - %s' % (self.artist.getLabel(extended), label)
txt = []
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
txt.append('%s' % self._userplaylists.get(plid).get('title'))
if extended and txt:
label = self.USER_PLAYLIST_MASK.format(label=label, userpl=', '.join(txt))
return label
def getLongTitle(self):
self.setLabelFormat()
longTitle = self.title
if self.type == AlbumType.ep:
longTitle += ' (EP)'
elif self.type == AlbumType.single:
longTitle += ' (Single)'
if getattr(self, 'year', None) and addon.getSetting('album_year_in_labels') == 'true':
longTitle += ' (%s)' % self.year
if self.audioQuality == Quality.hi_res and addon.getSetting('mqa_in_labels') == 'true':
longTitle = self.MASTER_AUDIO_MASK.format(label=longTitle)
return longTitle
def getSortText(self, mode=None):
return '%s - (%s) %s' % (self.artist.getLabel(extended=False), getattr(self, 'year', ''), self.getLongTitle())
def getListItem(self):
li = HasListItem.getListItem(self)
url = plugin.url_for_path('/album/%s' % self.id)
infoLabels = {
'title': self.title,
'album': self.title,
'artist': self.artist.name,
'year': getattr(self, 'year', None),
'tracknumber': self._itemPosition + 1 if self._itemPosition >= 0 else 0,
}
if KODI_VERSION >= (17, 0):
infoLabels.update({'mediatype': 'album',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('music', infoLabels)
return (url, li, True)
def getContextMenuItems(self):
cm = []
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/albums/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/albums/%s' % self.id)))
if self._playlist_type == 'USER':
cm.append((_T(30240), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove/%s/%s' % (self._playlist_id, self._playlist_pos))))
cm.append((_T(30248), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/move/%s/%s/%s' % (self._playlist_id, self._playlist_pos, self._playlist_track_id))))
cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/album/%s' % self.id)))
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
cm.append(((_T(30247) % self._userplaylists[plid].get('title'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove_album/%s/%s' % (plid, self.id)))))
cm.append((_T(30221), 'Container.Update(%s)' % plugin.url_for_path('/artist/%s' % self.artist.id)))
return cm
class ArtistItem(Artist, HasListItem):
def __init__(self, item):
self.__dict__.update(vars(item))
def getLabel(self, extended=True):
self.setLabelFormat()
if extended and self._isFavorite and not '/favorites/artists' in sys.argv[0]:
return self.FAVORITE_MASK.format(label=self.name)
return self.name
def getListItem(self):
li = HasListItem.getListItem(self)
url = plugin.url_for_path('/artist/%s' % self.id)
infoLabel = {'artist': self.name}
if KODI_VERSION >= (17, 0):
infoLabel.update({'mediatype': 'artist',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('music', infoLabel)
return (url, li, True)
def getContextMenuItems(self):
cm = []
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/artists/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/artists/%s' % self.id)))
return cm
class PlaylistItem(Playlist, HasListItem):
def __init__(self, item):
self.__dict__.update(vars(item))
def getLabel(self, extended=True):
self.setLabelFormat()
label = self.name
if extended and self._isFavorite and not '/favorites/' in sys.argv[0]:
label = self.FAVORITE_MASK.format(label=label)
if self.type == 'USER' and sys.argv[0].lower().find('user_playlists') >= 0:
defaultpl = []
if str(self.id) == addon.getSetting('default_trackplaylist_id'):
defaultpl.append(_P('tracks'))
if str(self.id) == addon.getSetting('default_videoplaylist_id'):
defaultpl.append(_P('videos'))
if str(self.id) == addon.getSetting('default_albumplaylist_id'):
defaultpl.append(_P('albums'))
if len(defaultpl) > 0:
return self.DEFAULT_PLAYLIST_MASK.format(label=label, mediatype=', '.join(defaultpl))
return label
def getListItem(self):
li = HasListItem.getListItem(self)
path = '/playlist/%s/items/0'
if self.type == 'USER' and ALBUM_PLAYLIST_TAG in self.description:
path = '/playlist/%s/albums/0'
url = plugin.url_for_path(path % self.id)
infoLabel = {
'artist': self.title,
'album': self.description,
'title': _T(30243).format(tracks=self.numberOfTracks, videos=self.numberOfVideos),
'genre': _T(30243).format(tracks=self.numberOfTracks, videos=self.numberOfVideos),
'tracknumber': self._itemPosition + 1 if self._itemPosition >= 0 else 0
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'userrating': '%s' % int(round(self.popularity / 10.0))})
li.setInfo('music', infoLabel)
return (url, li, True)
def getContextMenuItems(self):
cm = []
if self.numberOfVideos > 0:
cm.append((_T(30252), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/tracks/0' % self.id)))
if self.type == 'USER' and ALBUM_PLAYLIST_TAG in self.description:
cm.append((_T(30254), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/items/0' % self.id)))
else:
cm.append((_T(30255), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/albums/0' % self.id)))
if self._is_logged_in:
if self.type == 'USER':
cm.append((_T(30251), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/rename/%s' % self.id)))
cm.append((_T(30235), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/delete/%s' % self.id)))
else:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/playlists/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/playlists/%s' % self.id)))
cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/playlist/%s' % self.id)))
if self.type == 'USER' and sys.argv[0].lower().find('user_playlists') >= 0:
if str(self.id) == addon.getSetting('default_trackplaylist_id'):
cm.append((_T(30250) % _T('Track'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/tracks')))
else:
cm.append((_T(30249) % _T('Track'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/tracks/%s' % self.id)))
if str(self.id) == addon.getSetting('default_videoplaylist_id'):
cm.append((_T(30250) % _T('Video'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/videos')))
else:
cm.append((_T(30249) % _T('Video'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/videos/%s' % self.id)))
if str(self.id) == addon.getSetting('default_albumplaylist_id'):
cm.append((_T(30250) % _T('Album'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_reset_default/albums')))
else:
cm.append((_T(30249) % _T('Album'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist_set_default/albums/%s' % self.id)))
return cm
class TrackItem(Track, HasListItem):
def __init__(self, item):
self.__dict__.update(vars(item))
if self.version and not self.version in self.title:
self.title += ' (%s)' % self.version
self.version = None
self.artist = ArtistItem(self.artist)
self.artists = [ArtistItem(artist) for artist in self.artists]
self._ftArtists = [ArtistItem(artist) for artist in self._ftArtists]
self.album = AlbumItem(self.album)
self._userplaylists = {} # Filled by parser
def getLabel(self, extended=True):
self.setLabelFormat()
label1 = self.artist.getLabel(extended=extended if self.available else False)
label2 = self.getLongTitle()
if extended and self._isFavorite and self.available and not '/favorites/' in sys.argv[0]:
label2 = self.FAVORITE_MASK.format(label=label2)
label = '%s - %s' % (label1, label2)
if extended and not self.available:
label = self.STREAM_LOCKED_MASK.format(label=label, info=_T(30242))
txt = []
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
txt.append('%s' % self._userplaylists.get(plid).get('title'))
if extended and txt:
label = self.USER_PLAYLIST_MASK.format(label=label, userpl=', '.join(txt))
return label
def getLongTitle(self):
self.setLabelFormat()
longTitle = self.title
if self.version and not self.version in self.title:
longTitle += ' (%s)' % self.version
if self.explicit and not 'Explicit' in self.title:
longTitle += ' (Explicit)'
if self.editable and isinstance(self._cut, CutInfo):
if self._cut.name:
longTitle += ' (%s)' % self._cut.name
if self.audioQuality == Quality.hi_res and addon.getSetting('mqa_in_labels') == 'true':
longTitle = self.MASTER_AUDIO_MASK.format(label=longTitle)
return longTitle
def getSortText(self, mode=None):
if mode == 'ALBUM':
return self.album.getSortText(mode=mode)
return self.getLabel(extended=False)
def getFtArtistsText(self):
text = ''
for item in self._ftArtists:
if len(text) > 0:
text = text + ', '
text = text + item.name
if len(text) > 0:
text = 'ft. by ' + text
return text
def getComment(self):
return self.getFtArtistsText()
def getListItem(self):
li = HasListItem.getListItem(self)
if self.available:
if isinstance(self._cut, CutInfo):
url = plugin.url_for_path('/play_track_cut/%s/%s/%s' % (self.id, self._cut.id, self.album.id))
else:
url = plugin.url_for_path('/play_track/%s/%s' % (self.id, self.album.id))
isFolder = False
else:
url = plugin.url_for_path('/stream_locked')
isFolder = True
infoLabel = {
'title': self.title,
'tracknumber': self._playlist_pos + 1 if self._playlist_id else self._itemPosition + 1 if self._itemPosition >= 0 else self.trackNumber,
'discnumber': self.volumeNumber,
'duration': self.duration,
'artist': self.artist.name,
'album': self.album.title,
'year': getattr(self, 'year', None),
'rating': '%s' % int(round(self.popularity / 20.0)),
'comment': self.getComment()
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'mediatype': 'song',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('music', infoLabel)
return (url, li, isFolder)
def getContextMenuItems(self):
cm = []
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/tracks/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/tracks/%s' % self.id)))
if self._playlist_type == 'USER':
cm.append((_T(30240), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove/%s/%s' % (self._playlist_id, self._playlist_pos))))
item_id = self.id if not isinstance(self._cut, CutInfo) else self._cut.id
cm.append((_T(30248), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/move/%s/%s/%s' % (self._playlist_id, self._playlist_pos, item_id))))
else:
cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/track/%s' % self.id)))
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
playlist = self._userplaylists[plid]
if '%s' % self.album.id in playlist.get('album_ids', []):
cm.append(((_T(30247) % playlist.get('title'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove_album/%s/%s' % (plid, self.album.id)))))
else:
cm.append(((_T(30247) % playlist.get('title'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove_id/%s/%s' % (plid, self.id)))))
cm.append((_T(30221), 'Container.Update(%s)' % plugin.url_for_path('/artist/%s' % self.artist.id)))
cm.append((_T(30245), 'Container.Update(%s)' % plugin.url_for_path('/album/%s' % self.album.id)))
cm.append((_T(30222), 'Container.Update(%s)' % plugin.url_for_path('/track_radio/%s' % self.id)))
cm.append((_T(30223), 'Container.Update(%s)' % plugin.url_for_path('/recommended/tracks/%s' % self.id)))
return cm
class VideoItem(Video, HasListItem):
def __init__(self, item):
self.__dict__.update(vars(item))
self.artist = ArtistItem(self.artist)
self.artists = [ArtistItem(artist) for artist in self.artists]
self._ftArtists = [ArtistItem(artist) for artist in self._ftArtists]
self._userplaylists = {} # Filled by parser
def getLabel(self, extended=True):
self.setLabelFormat()
label1 = self.artist.name
if extended and self.artist._isFavorite and self.available:
label1 = self.FAVORITE_MASK.format(label=label1)
label2 = self.getLongTitle()
if extended and self._isFavorite and self.available and not '/favorites/' in sys.argv[0]:
label2 = self.FAVORITE_MASK.format(label=label2)
label = '%s - %s' % (label1, label2)
if extended and not self.available:
label = self.STREAM_LOCKED_MASK.format(label=label, info=_T(30242))
txt = []
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
txt.append('%s' % self._userplaylists.get(plid).get('title'))
if extended and txt:
label = self.USER_PLAYLIST_MASK.format(label=label, userpl=', '.join(txt))
return label
def getLongTitle(self):
longTitle = self.title
if self.explicit and not 'Explicit' in self.title:
longTitle += ' (Explicit)'
if getattr(self, 'year', None):
longTitle += ' (%s)' % self.year
return longTitle
def getFtArtistsText(self):
text = ''
for item in self._ftArtists:
if len(text) > 0:
text = text + ', '
text = text + item.name
if len(text) > 0:
text = 'ft. by ' + text
return text
def getComment(self):
return self.getFtArtistsText()
def getListItem(self):
li = HasListItem.getListItem(self)
if self.available:
url = plugin.url_for_path('/play_video/%s' % self.id)
isFolder = False
else:
url = plugin.url_for_path('/stream_locked')
isFolder = True
infoLabel = {
'artist': [self.artist.name],
'title': self.title,
'tracknumber': self._playlist_pos + 1 if self._playlist_id else self._itemPosition + 1,
'year': getattr(self, 'year', None),
'plotoutline': self.getComment(),
'plot': self.getFtArtistsText()
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'mediatype': 'musicvideo',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('video', infoLabel)
li.addStreamInfo('video', { 'codec': 'h264', 'aspect': 1.78, 'width': 1920,
'height': 1080, 'duration': self.duration })
li.addStreamInfo('audio', { 'codec': 'AAC', 'language': 'en', 'channels': 2 })
return (url, li, isFolder)
def getContextMenuItems(self):
cm = []
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/videos/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/videos/%s' % self.id)))
if self._playlist_type == 'USER':
cm.append((_T(30240), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove/%s/%s' % (self._playlist_id, self._playlist_pos))))
cm.append((_T(30248), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/move/%s/%s/%s' % (self._playlist_id, self._playlist_pos, self.id))))
else:
cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/video/%s' % self.id)))
plids = self._userplaylists.keys()
for plid in plids:
if plid <> self._playlist_id:
cm.append(((_T(30247) % self._userplaylists[plid].get('title'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove_id/%s/%s' % (plid, self.id)))))
cm.append((_T(30221), 'Container.Update(%s)' % plugin.url_for_path('/artist/%s' % self.artist.id)))
cm.append((_T(30224), 'Container.Update(%s)' % plugin.url_for_path('/recommended/videos/%s' % self.id)))
return cm
class PromotionItem(Promotion, HasListItem):
def __init__(self, item):
if item.type != 'EXTURL' and item.id.startswith('http:'):
item.type = 'EXTURL' # Fix some defect TIDAL Promotions
self.__dict__.update(vars(item))
self._userplaylists = {} # Filled by parser
def getLabel(self, extended=True):
self.setLabelFormat()
if self.type in ['ALBUM', 'VIDEO']:
label = '%s - %s' % (self.shortHeader, self.shortSubHeader)
else:
label = self.shortHeader
if extended and self._isFavorite:
label = self.FAVORITE_MASK.format(label=label)
txt = []
plids = self._userplaylists.keys()
for plid in plids:
txt.append('%s' % self._userplaylists.get(plid).get('title'))
if extended and txt:
label = self.USER_PLAYLIST_MASK.format(label=label, userpl=', '.join(txt))
return label
def getListItem(self):
li = HasListItem.getListItem(self)
isFolder = True
if self.type == 'PLAYLIST':
url = plugin.url_for_path('/playlist/%s/items/0' % self.id)
infoLabel = {
'artist': self.shortHeader,
'album': self.text,
'title': self.shortSubHeader
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'userrating': '%s' % int(round(self.popularity / 10.0))})
li.setInfo('music', infoLabel)
elif self.type == 'ALBUM':
url = plugin.url_for_path('/album/%s' % self.id)
infoLabel = {
'artist': self.shortHeader,
'album': self.text,
'title': self.shortSubHeader
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'mediatype': 'album',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('music', infoLabel)
elif self.type == 'VIDEO':
url = plugin.url_for_path('/play_video/%s' % self.id)
infoLabel = {
'artist': [self.shortHeader],
'album': self.text,
'title': self.shortSubHeader
}
if KODI_VERSION >= (17, 0):
infoLabel.update({'mediatype': 'musicvideo',
'userrating': '%s' % int(round(self.popularity / 10.0))
})
li.setInfo('video', infoLabel)
li.setProperty('isplayable', 'true')
isFolder = False
li.addStreamInfo('video', { 'codec': 'h264', 'aspect': 1.78, 'width': 1920,
'height': 1080, 'duration': self.duration })
li.addStreamInfo('audio', { 'codec': 'AAC', 'language': 'en', 'channels': 2 })
else:
return (None, None, False)
return (url, li, isFolder)
def getContextMenuItems(self):
cm = []
if self.type == 'PLAYLIST':
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/playlists/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/playlists/%s' % self.id)))
cm.append((_T(30255), 'Container.Update(%s)' % plugin.url_for_path('/playlist/%s/albums/0' % self.id)))
elif self.type == 'ALBUM':
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/albums/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/albums/%s' % self.id)))
elif self.type == 'VIDEO':
if self._is_logged_in:
if self._isFavorite:
cm.append((_T(30220), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/remove/videos/%s' % self.id)))
else:
cm.append((_T(30219), 'RunPlugin(%s)' % plugin.url_for_path('/favorites/add/videos/%s' % self.id)))
cm.append((_T(30239), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/add/video/%s' % self.id)))
plids = self._userplaylists.keys()
for plid in plids:
cm.append(((_T(30247) % self._userplaylists[plid].get('title'), 'RunPlugin(%s)' % plugin.url_for_path('/user_playlist/remove_id/%s/%s' % (plid, self.id)))))
cm.append((_T(30224), 'Container.Update(%s)' % plugin.url_for_path('/recommended/videos/%s' % self.id)))
return cm
class CategoryItem(Category, HasListItem):
_force_subfolders = False
_label = None
def __init__(self, item):
self.__dict__.update(vars(item))
def getLabel(self, extended=True):
self.setLabelFormat()
if extended:
return self.FOLDER_MASK.format(label=self._label)
return self._label
def getListItems(self):
content_types = self.content_types
items = []
if len(content_types) > 1 and self._group in ['moods', 'genres'] and not self._force_subfolders:
# Use sub folders for multiple Content Types
url = plugin.url_for_path('/category/%s/%s' % (self._group, self.path))
self._label = _P(self.path, self.name)
li = HasListItem.getListItem(self)
li.setInfo('music', {
'artist': self._label
})
items.append((url, li, True))
else:
for content_type in content_types:
url = plugin.url_for_path('/category/%s/%s/%s/%s' % (self._group, self.path, content_type, 0))
if len(content_types) > 1:
if self._force_subfolders:
# Show only Content Type as sub folders
self._label = _P(content_type)
else:
# Show Path and Content Type as sub folder
self._label = '%s %s' % (_P(self.path, self.name), _P(content_type))
else:
# Use Path as folder because content type is shows as sub foldes
self._label = _P(self.path, self.name)
li = HasListItem.getListItem(self)
li.setInfo('music', {
'artist': _P(self.path, self.name),
'album': _P(content_type)
})
items.append((url, li, True))
return items
class FolderItem(BrowsableMedia, HasListItem):
def __init__(self, label, url, thumb=None, fanart=None, isFolder=True, otherLabel=None):
self.name = label
self._url = url
self._thumb = thumb
self._fanart = fanart
self._isFolder = isFolder
self._otherLabel = otherLabel
def getLabel(self, extended=True):
self.setLabelFormat()
label = self._otherLabel if self._otherLabel else self.name
if extended:
label = self.FOLDER_MASK.format(label=label)
return label
def getListItem(self):
li = HasListItem.getListItem(self)
li.setInfo('music', {
'artist': self.name
})
return (self._url, li, self._isFolder)
@property
def image(self):
return self._thumb
@property
def fanart(self):
return self._fanart
class LoginToken(object):
browser = 'wdgaB1CilGA-S_s2' # Streams HIGH/LOW Quality over RTMP, FLAC and Videos over HTTP, but many Lossless Streams are encrypted.
android = 'kgsOOmYk3zShYrNP' # All Streams are HTTP Streams. Correct numberOfVideos in Playlists (best Token to use)
ios = '_DSTon1kC8pABnTw' # Same as Android Token, but uses ALAC instead of FLAC
native = '4zx46pyr9o8qZNRw' # Same as Android Token, but FLAC streams are encrypted
audirvana = 'BI218mwp9ERZ3PFI' # Like Android Token, supports MQA, but returns 'numberOfVideos = 0' in Playlists
amarra = 'wc8j_yBJd20zOmx0' # Like Android Token, but returns 'numberOfVideos = 0' in Playlists
# Unkown working Tokens
token1 = 'P5Xbeo5LFvESeDy6' # Like Android Token, but returns 'numberOfVideos = 0' in Playlists
token2 = 'oIaGpqT_vQPnTr0Q' # Like token1, but uses RTMP for HIGH/LOW Quality
token3 = '_KM2HixcUBZtmktH' # Same as token1
features = {
# token: Login-Token to get a Session-ID
# codecs: Supported Audio Codecs without encryption
# rtmp: Uses RTMP Protocol for HIGH/LOW Quality Audio Streams
# videosInPlaylists: True: numberOfVideos in Playlists is correct, False: returns 'numberOfVideos = 0' in Playlists
# user-agent: Special User-Agent in HTTP-Request-Header
'browser': { 'token': browser, 'codecs': ['AAC'], 'rtmp': True, 'videoMode': 'HLS', 'videosInPlaylists': True, 'user-agent': None },
'android': { 'token': android, 'codecs': ['AAC', 'FLAC'], 'rtmp': False, 'videoMode': 'HTTP','videosInPlaylists': True, 'user-agent': 'TIDAL_ANDROID/686 okhttp/3.3.1' },
'ios': { 'token': ios, 'codecs': ['AAC', 'ALAC'], 'rtmp': False, 'videoMode': 'HLS', 'videosInPlaylists': True, 'user-agent': 'TIDAL/546 CFNetwork/808.2.16 Darwin/16.3.0' },
'native': { 'token': native, 'codecs': ['AAC'], 'rtmp': False, 'videoMode': 'HLS', 'videosInPlaylists': True, 'user-agent': 'TIDAL_NATIVE_PLAYER/OSX/2.3.20' },
'audirvana': { 'token': audirvana, 'codecs': ['AAC', 'FLAC', 'MQA'], 'rtmp': False, 'videoMode': 'HLS', 'videosInPlaylists': False, 'user-agent': 'Audirvana Plus/2.6.4 CFNetwork/807.2.14 Darwin/16.3.0 (x86_64)' },
'amarra': { 'token': amarra, 'codecs': ['AAC', 'FLAC'], 'rtmp': False, 'videoMode': 'HLS', 'videosInPlaylists': False, 'user-agent': 'Amarra for TIDAL/2.2.1261 CFNetwork/807.2.14 Darwin/16.3.0 (x86_64)' },
# Unknown working Tokens
'token1': { 'token': token1, 'codecs': ['AAC', 'FLAC'], 'rtmp': False, 'videoMode': 'HTTP','videosInPlaylists': False, 'user-agent': None },
'token2': { 'token': token2, 'codecs': ['AAC', 'FLAC'], 'rtmp': True, 'videoMode': 'HLS', 'videosInPlaylists': False, 'user-agent': None },
'token3': { 'token': token3, 'codecs': ['AAC', 'FLAC'], 'rtmp': False, 'videoMode': 'HTTP','videosInPlaylists': False, 'user-agent': None }
}
priority = ['android', 'ios', 'audirvana', 'browser', 'native', 'amarra', 'token1', 'token2', 'token3']
@staticmethod
def getFeatures(tokenName='android'):
return LoginToken.features.get(tokenName, None)
@staticmethod
def getToken(tokenName='android'):
return LoginToken.getFeatures(tokenName).get('token')
@staticmethod
def select(codec, rtmp=False, api=True, forceHttpVideo=False):
primary_tokens = []
secondary_tokens = []
lossless = codec in ['FLAC', 'ALAC', 'MQA']
rtmp_relevant = False if api or lossless else True
video_modes = ['HTTP'] if api and forceHttpVideo else ['HLS', 'HTTP'] if api or forceHttpVideo else ['HLS']
for tokenName in LoginToken.priority:
token = LoginToken.getFeatures(tokenName)
if codec in token.get('codecs') and \
(token.get('videoMode') in video_modes) and \
(not rtmp_relevant or token.get('rtmp') == rtmp) and \
(not api or token.get('videosInPlaylists') == api):
if api and token.get('videoMode') == 'HTTP' and not forceHttpVideo:
secondary_tokens.append(tokenName)
else:
primary_tokens.append(tokenName)
tokens = primary_tokens + secondary_tokens
if not tokens:
log('No Token found for Codec:%s, RTMP:%s, API:%s, HTTP:%s' % (codec, rtmp, api, forceHttpVideo) )
return tokens
# Session from the TIDAL-API to parse Items into Kodi List Items
class TidalConfig(Config):
def __init__(self):
Config.__init__(self)
self.load()
def load(self):
self.session_id = addon.getSetting('session_id')
self.session_token_name = addon.getSetting('session_token_name')
self.stream_session_id = addon.getSetting('stream_session_id')
self.stream_token_name = addon.getSetting('stream_token_name')
if not self.stream_session_id:
self.stream_session_id = self.session_id
self.stream_token_name = self.session_token_name
self.country_code = addon.getSetting('country_code')
self.user_id = addon.getSetting('user_id')
self.subscription_type = [SubscriptionType.hifi, SubscriptionType.premium][min(1, int('0' + addon.getSetting('subscription_type')))]
self.client_unique_key = addon.getSetting('client_unique_key')
self.quality = [Quality.lossless, Quality.high, Quality.low][min(2, int('0' + addon.getSetting('quality')))]
self.use_rtmp = True if addon.getSetting('music_option') == '3' and self.quality <> Quality.lossless else False
self.codec = ['FLAC', 'AAC', 'AAC'][min([2, int('0' + addon.getSetting('quality'))])]
if addon.getSetting('music_option') == '1' and self.quality == Quality.lossless:
self.codec = 'ALAC'
elif addon.getSetting('music_option') == '2' and self.quality == Quality.lossless:
self.codec = 'MQA'
self.maxVideoHeight = [9999, 1080, 720, 540, 480, 360, 240][min(6, int('0%s' % addon.getSetting('video_quality')))]
self.pageSize = max(10, min(9999, int('0%s' % addon.getSetting('page_size'))))
self.debug = True if addon.getSetting('debug_log') == 'true' else False
self.debug_json = True if addon.getSetting('debug_json') == 'true' else False
self.forceHttpVideo = True if addon.getSetting('http_for_videos') == 'true' else False
self.http_video_session_id = self.stream_session_id
if self.forceHttpVideo:
apiFeatures = LoginToken.getFeatures(self.session_token_name)
if apiFeatures and apiFeatures.get('videoMode') == 'HTTP':
self.http_video_session_id = self.session_id
class TidalSession(Session):
errorCodes = []
def __init__(self, config=TidalConfig()):
Session.__init__(self, config=config)
def init_user(self, user_id, subscription_type):
return TidalUser(self, user_id, subscription_type)
def load_session(self):
if not self._config.country_code:
self._config.country_code = self.local_country_code()
addon.setSetting('country_code', self._config.country_code)
Session.load_session(self, self._config.session_id, self._config.country_code, self._config.user_id,
self._config.subscription_type, self._config.client_unique_key)
self.stream_session_id = self._config.stream_session_id
self.http_video_session_id = self._config.http_video_session_id
def generate_client_unique_key(self):
unique_key = addon.getSetting('client_unique_key')
if not unique_key:
unique_key = Session.generate_client_unique_key(self)
return unique_key
def login_with_token(self, username, password, subscription_type, tokenName, api=True):
old_token = self._config.api_token
old_session_id = self.session_id
self._config.api_token = LoginToken.getToken(tokenName)
self.session_id = None
Session.login(self, username, password, subscription_type)
success = True if self.session_id else False
if not api:
self.stream_session_id = self.session_id
if old_session_id:
self.session_id = old_session_id
self._config.api_token = old_token
return success
def login(self, username, password, subscription_type=None):
if not username or not password:
return False
if not subscription_type:
# Set Subscription Type corresponding to the given playback quality
subscription_type = SubscriptionType.hifi if self._config.quality == Quality.lossless else SubscriptionType.premium
if not self.client_unique_key:
# Generate a random client key if no key is given
self.client_unique_key = self.generate_client_unique_key()
api_token = ''
stream_token = ''
# Get working Tokens with correct numberOfVideos in Playlists which can be used for API calls and for Streaming
tokenNames = LoginToken.select(codec=self._config.codec, rtmp=self._config.use_rtmp, api=True, forceHttpVideo=self._config.forceHttpVideo)
if not tokenNames:
# Get a default API Token
tokenNames = LoginToken.select(codec='AAC', rtmp=self._config.use_rtmp, api=True, forceHttpVideo=self._config.forceHttpVideo)
# if not tokenNames:
for tokenName in tokenNames:
log('Try Login for API Session with %s Token %s ...' % (tokenName, LoginToken.getToken(tokenName)))
loginOk = self.login_with_token(username, password, subscription_type, tokenName, api=True)
if loginOk:
api_token = tokenName
# Use the API Session also for Streaming as default
stream_token = api_token
self.stream_session_id = self.session_id
break
# Get Tokens which are necessary for Streaming
tokenNames = LoginToken.select(codec=self._config.codec, rtmp=self._config.use_rtmp, api=False, forceHttpVideo=False)
if api_token in tokenNames:
log('Using API Session also for Streaming.')
else:
# Get Session-ID for Streaming
for tokenName in tokenNames:
log('Try Login for Stream Session with %s Token %s ...' % (tokenName, LoginToken.getToken(tokenName)))
loginOk = self.login_with_token(username, password, subscription_type, tokenName, api=False)
if loginOk:
stream_token = tokenName
break
# Save Session Data into Addon-Settings
if self.is_logged_in:
addon.setSetting('session_id', self.session_id)
addon.setSetting('session_token_name', api_token)
addon.setSetting('stream_session_id', self.stream_session_id)
addon.setSetting('stream_token_name', stream_token)
addon.setSetting('country_code', self.country_code)
addon.setSetting('user_id', unicode(self.user.id))
addon.setSetting('subscription_type', '0' if self.user.subscription.type == SubscriptionType.hifi else '1')
addon.setSetting('client_unique_key', self.client_unique_key)
# Reload the Configuration after Settings are saved.
self._config.load()
self.load_session()
if self._config.forceHttpVideo and self.http_video_session_id == self.session_id and self.session_id <> self.stream_session_id:
log('Using API Session for HTTP Video Streaming. Videos are limited to 720p !')
return self.is_logged_in
def logout(self):
Session.logout(self)
self.stream_session_id = None
addon.setSetting('session_id', '')
addon.setSetting('stream_session_id', '')
addon.setSetting('user_id', '')
self._config.load()
def get_album_tracks(self, album_id, withAlbum=True):
items = Session.get_album_tracks(self, album_id)
if withAlbum:
album = self.get_album(album_id)
if album:
for item in items:
item.album = album
return items
def get_playlist_tracks(self, playlist_id, offset=0, limit=9999):
# keeping 1st parameter as playlist_id for backward compatibility
if isinstance(playlist_id, Playlist):
playlist = playlist_id
playlist_id = playlist.id
else:
playlist = self.get_playlist(playlist_id)
# Don't read empty playlists
if not playlist or playlist.numberOfItems == 0:
return []
items = Session.get_playlist_tracks(self, playlist.id, offset=offset, limit=limit)
if items:
for item in items:
item._etag = playlist._etag
item._playlist_name = playlist.title
item._playlist_type = playlist.type
return items
def get_item_albums(self, items):
albums = []
for item in items:
album = item.album
if not album.releaseDate:
album.releaseDate = item.streamStartDate
# Item-Position in the Kodi-List (filled by _map_request)
album._itemPosition = item._itemPosition
album._offset = item._offset
album._totalNumberOfItems = item._totalNumberOfItems
# Infos for Playlist-Item-Position (filled by get_playlist_tracks, get_playlist_items)
album._playlist_id = item._playlist_id
album._playlist_pos = item._playlist_pos
album._etag = item._etag
album._playlist_name = item._playlist_name
album._playlist_type = item._playlist_type
# Track-ID in TIDAL-Playlist
album._playlist_track_id = item.id
albums.append(album)
return albums
def get_playlist_albums(self, playlist, offset=0, limit=9999):
return self.get_item_albums(self.get_playlist_tracks(self, playlist, offset=offset, limit=limit))
def get_artist_top_tracks(self, artist_id, offset=0, limit=999):
items = Session.get_artist_top_tracks(self, artist_id, offset=offset, limit=limit)
if not items and limit >= 100:
items = Session.get_artist_top_tracks(self, artist_id, offset=offset, limit=100)
if not items and limit >= 50:
items = Session.get_artist_top_tracks(self, artist_id, offset=offset, limit=50)
if not items:
items = Session.get_artist_top_tracks(self, artist_id, offset=offset, limit=20)
return items
def get_artist_radio(self, artist_id, offset=0, limit=999):
items = Session.get_artist_radio(self, artist_id, offset=offset, limit=limit)
if not items and limit >= 100: