-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathaddon.py
2193 lines (1960 loc) · 84 KB
/
addon.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding:utf-8 -*-
from api import NetEase
from xbmcswift2 import Plugin, xbmcgui, xbmcplugin, xbmc, xbmcaddon
import re
import sys
import hashlib
import time
import os
import xbmcvfs
import qrcode
from datetime import datetime
import json
try:
xbmc.translatePath = xbmcvfs.translatePath
except AttributeError:
pass
PY3 = sys.version_info.major >= 3
if not PY3:
reload(sys)
sys.setdefaultencoding('utf-8')
plugin = Plugin()
account = plugin.get_storage('account')
if 'uid' not in account:
account['uid'] = ''
if 'logined' not in account:
account['logined'] = False
if 'first_run' not in account:
account['first_run'] = True
music = NetEase()
PROFILE = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
qrcode_path = os.path.join(PROFILE, 'qrcode')
def delete_files(path):
files = os.listdir(path)
for f in files:
f_path = os.path.join(path, f)
if os.path.isdir(f_path):
delete_files(f_path)
else:
os.remove(f_path)
def caculate_size(path):
count = 0
size = 0
files = os.listdir(path)
for f in files:
f_path = os.path.join(path, f)
if os.path.isdir(f_path):
count_, size_ = caculate_size(f_path)
count += count_
size += size_
else:
count += 1
size += os.path.getsize(f_path)
return count, size
@plugin.route('/delete_thumbnails/')
def delete_thumbnails():
path = xbmc.translatePath('special://thumbnails')
count, size = caculate_size(path)
dialog = xbmcgui.Dialog()
result = dialog.yesno('删除缩略图', '一共 {} 个文件,{} MB,确认删除吗?'.format(
count, B2M(size)), '取消', '确认')
if not result:
return
delete_files(path)
dialog.notification('删除缩略图', '删除成功',
xbmcgui.NOTIFICATION_INFO, 800, False)
@plugin.route('/login/')
def login():
keyboard = xbmc.Keyboard('', '请输入手机号或邮箱')
keyboard.doModal()
if (keyboard.isConfirmed()):
username = keyboard.getText().strip()
if not username:
return
else:
return
keyboard = xbmc.Keyboard('', '请输入密码')
keyboard.doModal()
if (keyboard.isConfirmed()):
password = keyboard.getText().strip()
if not username:
return
else:
return
password = hashlib.md5(password.encode('UTF-8')).hexdigest()
login = music.login(username, password)
if login['code'] == 200:
account['logined'] = True
account['uid'] = login['profile']['userId']
dialog = xbmcgui.Dialog()
dialog.notification('登录成功', '请重启软件以解锁更多功能',
xbmcgui.NOTIFICATION_INFO, 800, False)
elif login['code'] == -1:
dialog = xbmcgui.Dialog()
dialog.notification('登录失败', '可能是网络问题',
xbmcgui.NOTIFICATION_INFO, 800, False)
elif login['code'] == -462:
dialog = xbmcgui.Dialog()
dialog.notification('登录失败', '-462: 需要验证',
xbmcgui.NOTIFICATION_INFO, 800, False)
else:
dialog = xbmcgui.Dialog()
dialog.notification('登录失败', str(login['code']) + ': ' + login.get('msg', ''),
xbmcgui.NOTIFICATION_INFO, 800, False)
@plugin.route('/logout/')
def logout():
account['logined'] = False
account['uid'] = ''
liked_songs = plugin.get_storage('liked_songs')
liked_songs['pid'] = 0
liked_songs['ids'] = []
COOKIE_PATH = os.path.join(PROFILE, 'cookie.txt')
with open(COOKIE_PATH, 'w') as f:
f.write('# Netscape HTTP Cookie File\n')
dialog = xbmcgui.Dialog()
dialog.notification(
'退出成功', '账号退出成功', xbmcgui.NOTIFICATION_INFO, 800, False)
#limit = int(xbmcplugin.getSetting(int(sys.argv[1]),'number_of_songs_per_page'))
limit = xbmcplugin.getSetting(int(sys.argv[1]), 'number_of_songs_per_page')
if limit == '':
limit = 100
else:
limit = int(limit)
quality = xbmcplugin.getSetting(int(sys.argv[1]), 'quality')
if quality == '0':
level = 'standard'
elif quality == '1':
level = 'higher'
elif quality == '2':
level = 'exhigh'
elif quality == '3':
level = 'lossless'
elif quality == '4':
level = 'hires'
elif quality == '5':
level = 'jyeffect'
elif quality == '6':
level = 'sky'
elif quality == '7':
level = 'jymaster'
elif quality == '8':
level = 'dolby'
else:
level = 'standard'
resolution = xbmcplugin.getSetting(int(sys.argv[1]), 'resolution')
if resolution == '0':
r = 240
elif resolution == '1':
r = 480
elif resolution == '2':
r = 720
elif resolution == '3':
r = 1080
else:
r = 720
def tag(info, color='red'):
return '[COLOR ' + color + ']' + info + '[/COLOR]'
def trans_num(num):
if num > 100000000:
return str(round(num/100000000, 1)) + '亿'
elif num > 10000:
return str(round(num/10000, 1)) + '万'
else:
return str(num)
def trans_time(t):
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t//1000))
def trans_date(t):
return time.strftime('%Y-%m-%d', time.localtime(t//1000))
def B2M(size):
return str(round(size/1048576, 1))
def get_songs(songs, privileges=[], picUrl=None, source=''):
datas = []
for i in range(len(songs)):
song = songs[i]
# song data
if 'song' in song:
song = song['song']
# 云盘
elif 'simpleSong' in song:
tempSong = song
song = song['simpleSong']
elif 'songData' in song:
song = song['songData']
elif 'mainSong' in song:
song = song['mainSong']
data = {}
# song id
if 'id' in song:
data['id'] = song['id']
elif 'songId' in song:
data['id'] = song['songId']
data['name'] = song['name']
# mv id
if 'mv' in song:
data['mv_id'] = song['mv']
elif 'mvid' in song:
data['mv_id'] = song['mvid']
elif 'mv_id' in song:
data['mv_id'] = song['mv_id']
artist = ""
artists = []
data['picUrl'] = None
if 'ar' in song:
if song['ar'] is not None:
artist = "/".join([a["name"]
for a in song["ar"] if a["name"] is not None])
artists = [[a['name'], a['id']] for a in song["ar"] if a["name"] is not None]
if artist == "" and "pc" in song:
artist = "未知艺术家" if song["pc"]["ar"] is None else song["pc"]["ar"]
if picUrl is not None:
data['picUrl'] = picUrl
elif 'picUrl' in song['ar'] and song['ar']['picUrl'] is not None:
data['picUrl'] = song['ar']['picUrl']
elif 'img1v1Url' in song['ar'] and song['ar']['img1v1Url'] is not None:
data['picUrl'] = song['ar']['img1v1Url']
else:
if 'simpleSong' in tempSong and 'artist' in tempSong and tempSong['artist'] != '':
artist = tempSong['artist']
else:
artist = "未知艺术家"
elif 'artists' in song:
artists = [[a['name'], a['id']] for a in song["artists"]]
artist = "/".join([a["name"] for a in song["artists"]])
if picUrl is not None:
data['picUrl'] = picUrl
elif 'picUrl' in song['artists'][0] and song['artists'][0]['picUrl'] is not None:
data['picUrl'] = song['artists'][0]['picUrl']
elif 'img1v1Url' in song['artists'][0] and song['artists'][0]['img1v1Url'] is not None:
data['picUrl'] = song['artists'][0]['img1v1Url']
else:
artist = "未知艺术家"
artists = []
# if 'simpleSong' in tempSong and 'ar' not in song and 'artist' in tempSong and tempSong['artist']!='':
# artist = tempSong['artist']
# else:
# artist = "未知艺术家"
data['artist'] = artist
data['artists'] = artists
if "al" in song:
if song["al"] is not None:
album_name = song["al"]["name"]
album_id = song["al"]["id"]
if 'picUrl' in song['al']:
data['picUrl'] = song['al']['picUrl']
else:
if 'simpleSong' in tempSong and 'album' in tempSong and tempSong['album'] != '':
album_name = tempSong['album']
album_id = 0
else:
album_name = "未知专辑"
album_id = 0
elif "album" in song:
if song["album"] is not None:
album_name = song["album"]["name"]
album_id = song["album"]["id"]
else:
album_name = "未知专辑"
album_id = 0
if 'picUrl' in song['album']:
data['picUrl'] = song['album']['picUrl']
data['album_name'] = album_name
data['album_id'] = album_id
if 'alia' in song and song['alia'] is not None and len(song['alia']) > 0:
data['alia'] = song['alia'][0]
if 'cd' in song:
data['disc'] = song['cd']
elif 'disc' in song:
data['disc'] = song['disc']
else:
data['disc'] = 1
if 'no' in song:
data['no'] = song['no']
else:
data['no'] = 1
if 'dt' in song:
data['dt'] = song['dt']
elif 'duration' in song:
data['dt'] = song['duration']
if 'privilege' in song:
privilege = song['privilege']
elif len(privileges) > 0:
privilege = privileges[i]
else:
privilege = None
if privilege is None:
data['privilege'] = None
else:
data['privilege'] = privilege
# 搜索歌词
if source == 'search_lyric' and 'lyrics' in song:
data['lyrics'] = song['lyrics']
data['second_line'] = ''
txt = song['lyrics']['txt']
index_list = [i.start() for i in re.finditer('\n', txt)]
temps = []
for words in song['lyrics']['range']:
first = words['first']
second = words['second']
left = -1
right = -1
for index in range(len(index_list)):
if index_list[index] <= first:
left = index
if index_list[index] >= second:
right = index
break
temps.append({'first': first, 'second': second,
'left': left, 'right': right})
skip = []
for index in range(len(temps)):
if index in skip:
break
line = ''
if left == -1:
line += txt[0:temps[index]['first']]
else:
line += txt[index_list[temps[index]['left']] +
1:temps[index]['first']]
line += tag(txt[temps[index]['first']: temps[index]['second']], 'blue')
for index2 in range(index+1, len(temps)):
if temps[index2]['left'] == temps[index]['left']:
line += txt[temps[index2-1]['second']: temps[index2]['first']]
line += tag(txt[temps[index2]['first']: temps[index2]['second']], 'blue')
skip.append(index2)
else:
break
if right == -1:
line += txt[temps[index]['second']: len(txt)]
else:
line += txt[temps[index]['second']: index_list[temps[index]['right']]] + '...'
data['second_line'] += line
else:
if xbmcplugin.getSetting(int(sys.argv[1]), 'show_album_name') == 'true':
data['second_line'] = data['album_name']
datas.append(data)
return datas
def get_songs_items(datas, privileges=[], picUrl=None, offset=0, getmv=True, source='', sourceId=0, enable_index=True):
songs = get_songs(datas, privileges, picUrl, source)
items = []
for play in songs:
# 隐藏不能播放的歌曲
if play['privilege']['pl'] == 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'hide_songs') == 'true':
continue
# 显示序号
if xbmcplugin.getSetting(int(sys.argv[1]), 'show_index') == 'true' and enable_index:
offset += 1
if offset < 10:
str_offset = '0' + str(offset) + '.'
else:
str_offset = str(offset) + '.'
else:
str_offset = ''
ar_name = play['artist']
mv_id = play['mv_id']
song_naming_format = xbmcplugin.getSetting(int(sys.argv[1]), 'song_naming_format')
if song_naming_format == '0':
label = str_offset + ar_name + ' - ' + play['name']
elif song_naming_format == '1':
label = str_offset + play['name'] + ' - ' + ar_name
elif song_naming_format == '2':
label = str_offset + play['name']
else:
label = str_offset + ar_name + ' - ' + play['name']
if 'alia' in play:
label += tag('('+play['alia']+')', 'gray')
if play['privilege'] and play['privilege']['st'] < 0:
label = tag(label, 'grey')
liked_songs = plugin.get_storage('liked_songs')
if play['id'] in liked_songs['ids'] and xbmcplugin.getSetting(int(sys.argv[1]), 'like_tag') == 'true':
label = tag('♥ ') + label
if play['privilege'] is not None:
if play['privilege']['st'] < 0:
label = tag(label, 'grey')
if play['privilege']['fee'] == 1 and xbmcplugin.getSetting(int(sys.argv[1]), 'vip_tag') == 'true':
label += tag(' vip')
if play['privilege']['cs'] and xbmcplugin.getSetting(int(sys.argv[1]), 'cloud_tag') == 'true':
label += ' ☁'
if (play['privilege']['flag'] & 64) > 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'exclusive_tag') == 'true':
label += tag(' 独家')
# if play['privilege']['downloadMaxbr']>=999000 and xbmcplugin.getSetting(int(sys.argv[1]),'sq_tag') == 'true':
if xbmcplugin.getSetting(int(sys.argv[1]), 'sq_tag') == 'true':
if 'playMaxBrLevel' in play['privilege']:
if play['privilege']['playMaxBrLevel'] == 'hires':
label += tag(' Hi-Res')
elif play['privilege']['playMaxBrLevel'] == 'lossless':
label += tag(' SQ')
elif play['privilege']['playMaxBrLevel'] == 'jyeffect':
label += tag(' 环绕声')
elif play['privilege']['playMaxBrLevel'] == 'sky':
label += tag(' 沉浸声')
elif play['privilege']['playMaxBrLevel'] == 'jymaster':
label += tag(' 超清母带')
elif play['privilege']['playMaxBrLevel'] == 'dolby':
label += tag(' 杜比全景声')
elif play['privilege']['maxbr'] >= 999000:
label += tag(' SQ')
# payed: 0 未付费 | 3 付费单曲 | 5 付费专辑
if 'preSell' in play['privilege'] and play['privilege']['preSell'] == True and xbmcplugin.getSetting(int(sys.argv[1]), 'presell_tag') == 'true':
label += tag(' 预售')
elif play['privilege']['fee'] == 4 and play['privilege']['pl'] == 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'pay_tag') == 'true':
label += tag(' 付费')
if mv_id > 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'mv_tag') == 'true':
label += tag(' MV', 'green')
if 'second_line' in play and play['second_line']:
label += '\n' + play['second_line']
context_menu = []
if play['artists']:
context_menu.append(('跳转到歌手: ' + play['artist'], 'RunPlugin(%s)' % plugin.url_for('to_artist', artists=json.dumps(play['artists']))))
if play['album_name'] and play['album_id']:
context_menu.append(('跳转到专辑: ' + play['album_name'], 'Container.Update(%s)' % plugin.url_for('album', id=play['album_id'])))
if mv_id > 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'mvfirst') == 'true' and getmv:
context_menu.extend([
('播放歌曲', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='play_song', meida_type='song',
song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))),
('收藏到歌单', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='sub_playlist', meida_type='song',
song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))),
('收藏到视频歌单', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='sub_video_playlist', meida_type='song',
song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))),
])
items.append({
'label': label,
'path': plugin.url_for('play', meida_type='mv', song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000)),
'is_playable': True,
'icon': play.get('picUrl', None),
'thumbnail': play.get('picUrl', None),
'context_menu': context_menu,
'info': {
'mediatype': 'video',
'title': play['name'],
'album': play['album_name'],
},
'info_type': 'video',
})
else:
context_menu.extend([
('收藏到歌单', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='sub_playlist', meida_type='song',
song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))),
('歌曲ID:'+str(play['id']), ''),
])
if mv_id > 0:
context_menu.append(('收藏到视频歌单', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='sub_video_playlist',
meida_type='song', song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))))
context_menu.append(('播放MV', 'RunPlugin(%s)' % plugin.url_for('song_contextmenu', action='play_mv', meida_type='song', song_id=str(
play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000))))
# 歌曲不能播放时播放MV
if play['privilege'] is not None and play['privilege']['st'] < 0 and mv_id > 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'auto_play_mv') == 'true':
items.append({
'label': label,
'path': plugin.url_for('play', meida_type='song', song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000)),
'is_playable': True,
'icon': play.get('picUrl', None),
'thumbnail': play.get('picUrl', None),
'context_menu': context_menu,
'info': {
'mediatype': 'video',
'title': play['name'],
'album': play['album_name'],
},
'info_type': 'video',
})
else:
items.append({
'label': label,
'path': plugin.url_for('play', meida_type='song', song_id=str(play['id']), mv_id=str(mv_id), sourceId=str(sourceId), dt=str(play['dt']//1000)),
'is_playable': True,
'icon': play.get('picUrl', None),
'thumbnail': play.get('picUrl', None),
'fanart': play.get('picUrl', None),
'context_menu': context_menu,
'info': {
'mediatype': 'music',
'title': play['name'],
'artist': ar_name,
'album': play['album_name'],
'tracknumber': play['no'],
'discnumber': play['disc'],
'duration': play['dt']//1000,
'dbid': play['id'],
},
'info_type': 'music',
'properties': {
'ncmid': str(play['id'])
},
})
return items
@plugin.route('/to_artist/<artists>/')
def to_artist(artists):
artists = json.loads(artists)
if len(artists) == 1:
xbmc.executebuiltin('Container.Update(%s)' % plugin.url_for('artist', id=artists[0][1]))
return
sel = xbmcgui.Dialog().select('选择要跳转的歌手', [a[0] for a in artists])
if sel < 0:
return
xbmc.executebuiltin('Container.Update(%s)' % plugin.url_for('artist', id=artists[sel][1]))
@plugin.route('/song_contextmenu/<action>/<meida_type>/<song_id>/<mv_id>/<sourceId>/<dt>/')
def song_contextmenu(action, meida_type, song_id, mv_id, sourceId, dt):
if action == 'sub_playlist':
ids = []
names = []
names.append('+ 新建歌单')
playlists = music.user_playlist(
account['uid'], includeVideo=False).get('playlist', [])
for playlist in playlists:
if str(playlist['userId']) == str(account['uid']):
ids.append(playlist['id'])
names.append(playlist['name'])
dialog = xbmcgui.Dialog()
ret = dialog.contextmenu(names)
if ret == 0:
keyboard = xbmc.Keyboard('', '请输入歌单名称')
keyboard.doModal()
if (keyboard.isConfirmed()):
name = keyboard.getText()
else:
return
create_result = music.playlist_create(name)
if create_result['code'] == 200:
playlist_id = create_result['id']
else:
dialog = xbmcgui.Dialog()
dialog.notification(
'创建失败', '歌单创建失败', xbmcgui.NOTIFICATION_INFO, 800, False)
elif ret >= 1:
playlist_id = ids[ret-1]
if ret >= 0:
result = music.playlist_tracks(playlist_id, [song_id], op='add')
msg = ''
if result['code'] == 200:
msg = '收藏成功'
liked_songs = plugin.get_storage('liked_songs')
if liked_songs['pid'] == playlist_id:
liked_songs['ids'].append(int(song_id))
xbmc.executebuiltin('Container.Refresh')
elif 'message' in result and result['message'] is not None:
msg = str(result['code'])+'错误:'+result['message']
else:
msg = str(result['code'])+'错误'
dialog = xbmcgui.Dialog()
dialog.notification(
'收藏', msg, xbmcgui.NOTIFICATION_INFO, 800, False)
elif action == 'sub_video_playlist':
ids = []
names = []
playlists = music.user_playlist(
account['uid'], includeVideo=True).get("playlist", [])
for playlist in playlists:
if str(playlist['userId']) == str(account['uid']) and playlist['specialType'] == 200:
ids.append(playlist['id'])
names.append(playlist['name'])
dialog = xbmcgui.Dialog()
ret = dialog.contextmenu(names)
if ret >= 0:
result = music.playlist_add(ids[ret], [mv_id])
msg = ''
if result['code'] == 200:
msg = '收藏成功'
elif 'msg' in result:
msg = result['message']
else:
msg = '收藏失败'
dialog = xbmcgui.Dialog()
dialog.notification(
'收藏', msg, xbmcgui.NOTIFICATION_INFO, 800, False)
elif action == 'play_song':
songs = music.songs_url_v1([song_id], level=level).get("data", [])
urls = [song['url'] for song in songs]
url = urls[0]
if url is None:
dialog = xbmcgui.Dialog()
dialog.notification(
'播放', '该歌曲无法播放', xbmcgui.NOTIFICATION_INFO, 800, False)
else:
xbmc.executebuiltin('PlayMedia(%s)' % url)
elif action == 'play_mv':
mv = music.mv_url(mv_id, r).get("data", {})
url = mv['url']
if url is None:
dialog = xbmcgui.Dialog()
dialog.notification(
'播放', '该视频已删除', xbmcgui.NOTIFICATION_INFO, 800, False)
else:
xbmc.executebuiltin('PlayMedia(%s)' % url)
@plugin.route('/play/<meida_type>/<song_id>/<mv_id>/<sourceId>/<dt>/')
def play(meida_type, song_id, mv_id, sourceId, dt):
if meida_type == 'mv':
mv = music.mv_url(mv_id, r).get("data", {})
url = mv['url']
if url is None:
dialog = xbmcgui.Dialog()
dialog.notification('MV播放失败', '自动播放歌曲',
xbmcgui.NOTIFICATION_INFO, 800, False)
songs = music.songs_url_v1([song_id], level=level).get("data", [])
urls = [song['url'] for song in songs]
if len(urls) == 0:
url = None
else:
url = urls[0]
elif meida_type == 'song':
songs = music.songs_url_v1([song_id], level=level).get("data", [])
urls = [song['url'] for song in songs]
# 一般是网络错误
if len(urls) == 0:
url = None
else:
url = urls[0]
if url is None:
if int(mv_id) > 0 and xbmcplugin.getSetting(int(sys.argv[1]), 'auto_play_mv') == 'true':
mv = music.mv_url(mv_id, r).get("data", {})
url = mv['url']
if url is not None:
msg = '该歌曲无法播放,自动播放MV'
else:
msg = '该歌曲和MV无法播放'
else:
msg = '该歌曲无法播放'
dialog = xbmcgui.Dialog()
dialog.notification(
'播放失败', msg, xbmcgui.NOTIFICATION_INFO, 800, False)
else:
if xbmcplugin.getSetting(int(sys.argv[1]), 'upload_play_record') == 'true':
music.daka(song_id, time=dt)
elif meida_type == 'dj':
result = music.dj_detail(song_id)
song_id = result['program']['mainSong']['id']
songs = music.songs_url_v1([song_id], level=level).get("data", [])
urls = [song['url'] for song in songs]
if len(urls) == 0:
url = None
else:
url = urls[0]
if url is None:
msg = '该节目无法播放'
dialog = xbmcgui.Dialog()
dialog.notification(
'播放失败', msg, xbmcgui.NOTIFICATION_INFO, 800, False)
elif meida_type == 'mlog':
result = music.mlog_detail(mv_id, r)
url = result['data']['resource']['content']['video']['urlInfo']['url']
# else:
# music.daka(song_id,sourceId,dt)
plugin.set_resolved_url(url)
# 主目录
@plugin.route('/')
def index():
if account['first_run']:
account['first_run'] = False
xbmcgui.Dialog().ok('使用提示', '在设置中登录账号以解锁更多功能')
items = []
status = account['logined']
liked_songs = plugin.get_storage('liked_songs')
if 'pid' not in liked_songs:
liked_songs['pid'] = 0
if 'ids' not in liked_songs:
liked_songs['ids'] = []
if xbmcplugin.getSetting(int(sys.argv[1]), 'like_tag') == 'true' and liked_songs['pid']:
res = music.playlist_detail(liked_songs['pid'])
if res['code'] == 200:
liked_songs['ids'] = [s['id'] for s in res.get('playlist', {}).get('trackIds', [])]
if xbmcplugin.getSetting(int(sys.argv[1]), 'daily_recommend') == 'true' and status:
items.append(
{'label': '每日推荐', 'path': plugin.url_for('recommend_songs')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'personal_fm') == 'true' and status:
items.append({'label': '私人FM', 'path': plugin.url_for('personal_fm')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'my_playlists') == 'true' and status:
items.append({'label': '我的歌单', 'path': plugin.url_for(
'user_playlists', uid=account['uid'])})
if xbmcplugin.getSetting(int(sys.argv[1]), 'sublist') == 'true' and status:
items.append({'label': '我的收藏', 'path': plugin.url_for('sublist')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'recommend_playlists') == 'true' and status:
items.append(
{'label': '推荐歌单', 'path': plugin.url_for('recommend_playlists')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'vip_timemachine') == 'true' and status:
items.append(
{'label': '黑胶时光机', 'path': plugin.url_for('vip_timemachine')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'rank') == 'true':
items.append({'label': '排行榜', 'path': plugin.url_for('toplists')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'top_artist') == 'true':
items.append({'label': '热门歌手', 'path': plugin.url_for('top_artists')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'top_mv') == 'true':
items.append(
{'label': '热门MV', 'path': plugin.url_for('top_mvs', offset='0')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'search') == 'true':
items.append({'label': '搜索', 'path': plugin.url_for('search')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'cloud_disk') == 'true' and status:
items.append(
{'label': '我的云盘', 'path': plugin.url_for('cloud', offset='0')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'home_page') == 'true' and status:
items.append(
{'label': '我的主页', 'path': plugin.url_for('user', id=account['uid'])})
if xbmcplugin.getSetting(int(sys.argv[1]), 'new_albums') == 'true':
items.append(
{'label': '新碟上架', 'path': plugin.url_for('new_albums', offset='0')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'new_albums') == 'true':
items.append({'label': '新歌速递', 'path': plugin.url_for('new_songs')})
if xbmcplugin.getSetting(int(sys.argv[1]), 'mlog') == 'true':
items.append(
{'label': 'Mlog', 'path': plugin.url_for('mlog_category')})
return items
@plugin.route('/vip_timemachine/')
def vip_timemachine():
time_machine = plugin.get_storage('time_machine')
items = []
now = datetime.now()
this_year_start = datetime(now.year, 1, 1)
next_year_start = datetime(now.year + 1, 1, 1)
this_year_start_timestamp = int(
time.mktime(this_year_start.timetuple()) * 1000)
this_year_end_timestamp = int(time.mktime(
next_year_start.timetuple()) * 1000) - 1
resp = music.vip_timemachine(
this_year_start_timestamp, this_year_end_timestamp)
if resp['code'] != 200:
return items
weeks = resp.get('data', {}).get('detail', [])
time_machine['weeks'] = weeks
for index, week in enumerate(weeks):
start_date = time.strftime(
"%m.%d", time.localtime(week['weekStartTime']//1000))
end_date = time.strftime(
"%m.%d", time.localtime(week['weekEndTime']//1000))
title = week['data']['keyword'] + ' ' + \
tag(start_date + '-' + end_date, 'red')
if 'subTitle' in week['data'] and week['data']['subTitle']:
second_line = ''
subs = week['data']['subTitle'].split('##1')
for i, sub in enumerate(subs):
if i % 2 == 0:
second_line += tag(sub, 'gray')
else:
second_line += tag(sub, 'blue')
title += '\n' + second_line
plot_info = ''
plot_info += '[B]听歌数据:[/B]' + '\n'
listenSongs = tag(str(week['data']['listenSongs']) + '首', 'pink')
listenCount = tag(str(week['data']['listenWeekCount']) + '次', 'pink')
listentime = ''
t = week['data']['listenWeekTime']
if t == 0:
listentime += '0秒钟'
else:
if t >= 3600:
listentime += str(t//3600) + '小时'
if t % 3600 >= 0:
listentime += str((t % 3600)//60) + '分钟'
if t % 60 > 0:
listentime += str(t % 60) + '秒钟'
listentime = tag(listentime, 'pink')
plot_info += '本周听歌{},共听了{}\n累计时长{}\n'.format(
listenSongs, listenCount, listentime)
styles = (week['data'].get('listenCommonStyle', {})
or {}).get('styleDetailList', [])
if styles:
# if plot_info:
# plot_info += '\n'
plot_info += '[B]常听曲风:[/B]' + '\n'
for style in styles:
plot_info += tag(style['styleName'], 'blue') + tag(' %.2f%%' %
round(float(style['percent']) * 100, 2), 'pink') + '\n'
emotions = (week['data'].get('musicEmotion', {})
or {}).get('subTitle', [])
if emotions:
# if plot_info:
# plot_info += '\n'
plot_info += '[B]音乐情绪:[/B]' + '\n' + '你本周的音乐情绪是'
emotions = [tag(e, 'pink') for e in emotions]
if len(emotions) > 2:
plot_info += '、'.join(emotions[:-1]) + \
'与' + emotions[-1] + '\n'
else:
plot_info += '与'.join(emotions) + '\n'
items.append({
'label': title,
'path': plugin.url_for('vip_timemachine_week', index=index),
'info': {
'plot': plot_info
},
'info_type': 'video',
})
return items
@plugin.route('/vip_timemachine_week/<index>/')
def vip_timemachine_week(index):
time_machine = plugin.get_storage('time_machine')
data = time_machine['weeks'][int(index)]['data']
temp = []
if 'song' in data:
if 'tag' not in data['song'] or not data['song']['tag']:
data['song']['tag'] = '高光歌曲'
temp.append(data['song'])
temp.extend(data.get('favoriteSongs', []))
temp.extend((data.get('musicYear', {}) or {}).get('yearSingles', []))
temp.extend((data.get('listenSingle', {}) or {}).get('singles', []))
temp.extend(data.get('songInfos', []))
songs_dict = {}
for s in temp:
if s['songId'] not in songs_dict:
songs_dict[s['songId']] = s
elif not songs_dict[s['songId']]['tag']:
songs_dict[s['songId']]['tag'] = s['tag']
ids = list(songs_dict.keys())
songs = list(songs_dict.values())
resp = music.songs_detail(ids)
datas = resp['songs']
privileges = resp['privileges']
items = get_songs_items(datas, privileges=privileges, enable_index=False)
for i, item in enumerate(items):
if songs[i]['tag']:
item['label'] = tag('[{}]'.format(
songs[i]['tag']), 'pink') + item['label']
return items
def qrcode_check():
if not os.path.exists(qrcode_path):
SUCCESS = xbmcvfs.mkdir(qrcode_path)
if not SUCCESS:
dialog = xbmcgui.Dialog()
dialog.notification('失败', '目录创建失败,无法使用该功能',
xbmcgui.NOTIFICATION_INFO, 800, False)
return False
else:
temp_path = os.path.join(qrcode_path, str(int(time.time()))+'.png')
img = qrcode.make('temp_img')
img.save(temp_path)
_, files = xbmcvfs.listdir(qrcode_path)
for file in files:
xbmcvfs.delete(os.path.join(qrcode_path, file))
return True
def check_login_status(key):
for i in range(10):
check_result = music.login_qr_check(key)
if check_result['code'] == 803:
account['logined'] = True
resp = music.user_level()
account['uid'] = resp['data']['userId']
dialog = xbmcgui.Dialog()
dialog.notification('登录成功', '请重启软件以解锁更多功能',
xbmcgui.NOTIFICATION_INFO, 800, False)
xbmc.executebuiltin('Action(Back)')
break
time.sleep(3)
xbmc.executebuiltin('Action(Back)')
@plugin.route('/qrcode_login/')
def qrcode_login():
if not qrcode_check():
return
result = music.login_qr_key()
key = result.get('unikey', '')
login_path = 'https://music.163.com/login?codekey={}'.format(key)
temp_path = os.path.join(qrcode_path, str(int(time.time()))+'.png')
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_H,
box_size=10,
border=20
)
qr.add_data(login_path)
qr.make(fit=True)
img = qr.make_image()
img.save(temp_path)
dialog = xbmcgui.Dialog()
result = dialog.yesno('扫码登录', '请在在30秒内扫码登录', '取消', '确认')
if not result:
return
xbmc.executebuiltin('ShowPicture(%s)' % temp_path)
check_login_status(key)
# Mlog广场
@plugin.route('/mlog_category/')
def mlog_category():
categories = {
'广场': 1001,
'热门': 2124301,
'MV': 1002,
'演唱': 4,
'现场': 2,
'情感': 2130301,
'ACG': 2131301,
'明星': 2132301,
'演奏': 3,
'生活': 8001,
'舞蹈': 6001,
'影视': 3001,
'知识': 2125301,
}
items = []
for category in categories:
if categories[category] == 1001:
items.append({'label': category, 'path': plugin.url_for(
'mlog', cid=categories[category], pagenum=1)})
else:
items.append({'label': category, 'path': plugin.url_for(
'mlog', cid=categories[category], pagenum=0)})
return items
# Mlog
@plugin.route('/mlog/<cid>/<pagenum>/')
def mlog(cid, pagenum):
items = []
resp = music.mlog_socialsquare(cid, pagenum)
mlogs = resp['data']['feeds']
for video in mlogs:
mid = video['id']
if cid == '1002':
path = plugin.url_for('play', meida_type='mv',
song_id=0, mv_id=mid, sourceId=cid, dt=0)
else:
path = plugin.url_for('play', meida_type='mlog',