-
Notifications
You must be signed in to change notification settings - Fork 19
/
api.py
527 lines (452 loc) · 19.5 KB
/
api.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
# -*- coding:utf-8 -*-
import json
import os
import sys
import time
import requests
from encrypt import encrypted_request
from xbmcswift2 import xbmc, xbmcaddon, xbmcplugin
from http.cookiejar import Cookie
from http.cookiejar import MozillaCookieJar
import xbmcvfs
try:
xbmc.translatePath = xbmcvfs.translatePath
except AttributeError:
pass
DEFAULT_TIMEOUT = 10
BASE_URL = "https://music.163.com"
PROFILE = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile'))
if not os.path.exists(PROFILE):
os.makedirs(PROFILE)
COOKIE_PATH = os.path.join(PROFILE, 'cookie.txt')
if not os.path.exists(COOKIE_PATH):
with open(COOKIE_PATH, 'w') as f:
f.write('# Netscape HTTP Cookie File\n')
class NetEase(object):
def __init__(self):
self.header = {
"Accept": "*/*",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "zh-CN,zh;q=0.8,gl;q=0.6,zh-TW;q=0.4",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "music.163.com",
"Referer": "http://music.163.com",
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36",
}
cookie_jar = MozillaCookieJar(COOKIE_PATH)
cookie_jar.load()
self.session = requests.Session()
self.session.cookies = cookie_jar
for cookie in cookie_jar:
if cookie.is_expired():
cookie_jar.clear()
break
self.enable_proxy = False
if xbmcplugin.getSetting(int(sys.argv[1]), 'enable_proxy') == 'true':
self.enable_proxy = True
proxy = xbmcplugin.getSetting(int(sys.argv[1]), 'host').strip(
) + ':' + xbmcplugin.getSetting(int(sys.argv[1]), 'port').strip()
self.proxies = {
'http': 'http://' + proxy,
'https': 'https://' + proxy,
}
def _raw_request(self, method, endpoint, data=None):
if method == "GET":
if not self.enable_proxy:
resp = self.session.get(
endpoint, params=data, headers=self.header, timeout=DEFAULT_TIMEOUT
)
else:
resp = self.session.get(
endpoint, params=data, headers=self.header, timeout=DEFAULT_TIMEOUT, proxies=self.proxies, verify=False
)
elif method == "POST":
if not self.enable_proxy:
resp = self.session.post(
endpoint, data=data, headers=self.header, timeout=DEFAULT_TIMEOUT
)
else:
resp = self.session.post(
endpoint, data=data, headers=self.header, timeout=DEFAULT_TIMEOUT, proxies=self.proxies, verify=False
)
return resp
# 生成Cookie对象
def make_cookie(self, name, value):
return Cookie(
version=0,
name=name,
value=value,
port=None,
port_specified=False,
domain="music.163.com",
domain_specified=True,
domain_initial_dot=False,
path="/",
path_specified=True,
secure=False,
expires=None,
discard=False,
comment=None,
comment_url=None,
rest={},
)
def request(self, method, path, params={}, default={"code": -1}, custom_cookies={'os': 'android', 'appver': '8.20.20'}):
endpoint = "{}{}".format(BASE_URL, path)
csrf_token = ""
for cookie in self.session.cookies:
if cookie.name == "__csrf":
csrf_token = cookie.value
break
params.update({"csrf_token": csrf_token})
data = default
for key, value in custom_cookies.items():
cookie = self.make_cookie(key, value)
self.session.cookies.set_cookie(cookie)
params = encrypted_request(params)
try:
resp = self._raw_request(method, endpoint, params)
data = resp.json()
except requests.exceptions.RequestException as e:
print(e)
except ValueError as e:
print("Path: {}, response: {}".format(path, resp.text[:200]))
finally:
return data
def login(self, username, password):
if username.isdigit():
path = "/weapi/login/cellphone"
params = dict(phone=username, password=password,
rememberLogin="true")
else:
# magic token for login
# see https://github.com/Binaryify/NeteaseCloudMusicApi/blob/master/router/login.js#L15
client_token = (
"1_jVUMqWEPke0/1/Vu56xCmJpo5vP1grjn_SOVVDzOc78w8OKLVZ2JH7IfkjSXqgfmh"
)
path = "/weapi/login"
params = dict(
username=username,
password=password,
rememberLogin="true",
clientToken=client_token,
)
data = self.request("POST", path, params)
# 保存cookie
self.session.cookies.save()
return data
# 每日签到
def daily_task(self, is_mobile=True):
path = "/weapi/point/dailyTask"
params = dict(type=0 if is_mobile else 1)
return self.request("POST", path, params)
# 用户歌单
def user_playlist(self, uid, offset=0, limit=1000, includeVideo=True):
path = "/weapi/user/playlist"
params = dict(uid=uid, offset=offset, limit=limit,
includeVideo=includeVideo, csrf_token="")
return self.request("POST", path, params)
# specialType:5 喜欢的歌曲; 200 视频歌单; 0 普通歌单
# 每日推荐歌单
def recommend_resource(self):
path = "/weapi/v1/discovery/recommend/resource"
return self.request("POST", path)
# 每日推荐歌曲
def recommend_playlist(self, total=True, offset=0, limit=20):
path = "/weapi/v3/discovery/recommend/songs"
params = dict(total=total, offset=offset, limit=limit, csrf_token="")
return self.request("POST", path, params)
# 获取历史日推可用日期
def history_recommend_recent(self):
path = "/weapi/discovery/recommend/songs/history/recent"
return self.request("POST", path)
# 获取历史日推
def history_recommend_detail(self, date=''):
path = "/weapi/discovery/recommend/songs/history/detail"
params = dict(date=date)
return self.request("POST", path, params)
# 私人FM
def personal_fm(self):
path = "/weapi/v1/radio/get"
return self.request("POST", path)
# 搜索单曲(1),歌手(100),专辑(10),歌单(1000),用户(1002),歌词(1006),主播电台(1009),MV(1004),视频(1014),综合(1018) *(type)*
def search(self, keywords, stype=1, offset=0, total="true", limit=100):
path = "/weapi/search/get"
params = dict(s=keywords, type=stype, offset=offset,
total=total, limit=limit)
return self.request("POST", path, params)
# 新碟上架
def new_albums(self, offset=0, limit=50):
path = "/weapi/album/new"
params = dict(area="ALL", offset=offset, total=True, limit=limit)
return self.request("POST", path, params)
# 歌单(网友精选碟) hot||new http://music.163.com/#/discover/playlist/
def top_playlists(self, category="全部", order="hot", offset=0, limit=50):
path = "/weapi/playlist/list"
params = dict(
cat=category, order=order, offset=offset, total="true", limit=limit
)
return self.request("POST", path, params)
def playlist_catelogs(self):
path = "/weapi/playlist/catalogue"
return self.request("POST", path)
# 歌单详情
def playlist_detail(self, id, shareUserId=0):
path = "/weapi/v6/playlist/detail"
params = dict(id=id, t=int(time.time()), n=1000,
s=5, shareUserId=shareUserId)
return (self.request("POST", path, params))
# 热门歌手 http://music.163.com/#/discover/artist/
def top_artists(self, offset=0, limit=100, total=True):
path = "/weapi/artist/top"
params = dict(offset=offset, total=total, limit=limit)
return self.request("POST", path, params)
# 歌手单曲
def artists(self, artist_id):
path = "/weapi/v1/artist/{}".format(artist_id)
return self.request("POST", path)
def artist_album(self, artist_id, offset=0, limit=50):
path = "/weapi/artist/albums/{}".format(artist_id)
params = dict(offset=offset, total=True, limit=limit)
return self.request("POST", path, params)
# album id --> song id set
def album(self, album_id):
path = "/weapi/v1/album/{}".format(album_id)
return self.request("POST", path)
def song_comments(self, music_id, offset=0, total="false", limit=100):
path = "/weapi/v1/resource/comments/R_SO_4_{}/".format(music_id)
params = dict(rid=music_id, offset=offset, total=total, limit=limit)
return self.request("POST", path, params)
# song ids --> song urls ( details )
def songs_detail(self, ids):
path = "/weapi/v3/song/detail"
params = dict(c=json.dumps([{"id": _id}
for _id in ids]), ids=json.dumps(ids))
return self.request("POST", path, params)
def songs_url(self, ids, bitrate):
path = "/weapi/song/enhance/player/url"
params = dict(ids=ids, br=bitrate)
return self.request("POST", path, params)
def songs_url_v1(self, ids, level):
path = "/weapi/song/enhance/player/url/v1"
if level == 'dolby':
params = dict(ids=ids, level='hires', effects='["dolby"]', encodeType='mp4')
return self.request("POST", path, params, custom_cookies={'os': 'pc', 'appver': '2.10.11.201538'})
else:
params = dict(ids=ids, level=level, encodeType='flac')
return self.request("POST", path, params)
# lyric http://music.163.com/api/song/lyric?os=osx&id= &lv=-1&kv=-1&tv=-1
def song_lyric(self, music_id):
path = "/weapi/song/lyric"
params = dict(os="osx", id=music_id, lv=-1, kv=-1, tv=-1)
return self.request("POST", path, params)
# 今日最热(0), 本周最热(10),历史最热(20),最新节目(30)
def djchannels(self, offset=0, limit=50):
path = "/weapi/djradio/hot/v1"
params = dict(limit=limit, offset=offset)
return self.request("POST", path, params)
def dj_program(self, radio_id, asc=False, offset=0, limit=50):
path = "/weapi/dj/program/byradio"
params = dict(asc=asc, radioId=radio_id, offset=offset, limit=limit)
return self.request("POST", path, params)
def dj_sublist(self, offset=0, limit=50):
path = "/weapi/djradio/get/subed"
params = dict(offset=offset, limit=limit, total=True)
return self.request("POST", path, params)
def dj_detail(self, id):
path = "/weapi/dj/program/detail"
params = dict(id=id)
return self.request("POST", path, params)
# 打卡
def daka(self, id, sourceId=0, time=240):
path = "/weapi/feedback/weblog"
params = {'logs': json.dumps([{
'action': 'play',
'json': {
"download": 0,
"end": 'playend',
"id": id,
"sourceId": sourceId,
"time": time,
"type": 'song',
"wifi": 0,
}
}])}
return self.request("POST", path, params)
# 云盘歌曲
def cloud_songlist(self, offset=0, limit=50):
path = "/weapi/v1/cloud/get"
params = dict(offset=offset, limit=limit, csrf_token="")
return self.request("POST", path, params)
# 歌手信息
def artist_info(self, artist_id):
path = "/weapi/v1/artist/{}".format(artist_id)
return self.request("POST", path)
def artist_songs(self, id, limit=50, offset=0):
path = "/weapi/v1/artist/songs"
params = dict(id=id, limit=limit, offset=offset,
private_cloud=True, work_type=1, order='hot')
return self.request("POST", path, params)
# 获取MV url
def mv_url(self, id, r=1080):
path = "/weapi/song/enhance/play/mv/url"
params = dict(id=id, r=r)
return self.request("POST", path, params)
# 收藏的歌手
def artist_sublist(self, offset=0, limit=50, total=True):
path = "/weapi/artist/sublist"
params = dict(offset=offset, limit=limit, total=total)
return self.request("POST", path, params)
# 收藏的专辑
def album_sublist(self, offset=0, limit=50, total=True):
path = "/weapi/album/sublist"
params = dict(offset=offset, limit=limit, total=total)
return self.request("POST", path, params)
# 收藏的视频
def video_sublist(self, offset=0, limit=50, total=True):
path = "/weapi/cloudvideo/allvideo/sublist"
params = dict(offset=offset, limit=limit, total=total)
return self.request("POST", path, params)
# 获取视频url
def video_url(self, id, resolution=1080):
path = "/weapi/cloudvideo/playurl"
params = dict(ids='["' + id + '"]', resolution=resolution)
return self.request("POST", path, params)
# 我的数字专辑
def digitalAlbum_purchased(self, offset=0, limit=50, total=True):
path = "/api/digitalAlbum/purchased"
params = dict(offset=offset, limit=limit, total=total)
return self.request("POST", path, params)
# 已购单曲
def single_purchased(self, offset=0, limit=1000, total=True):
path = "/weapi/single/mybought/song/list"
params = dict(offset=offset, limit=limit)
return self.request("POST", path, params)
# 排行榜
def toplists(self):
path = "/api/toplist"
return self.request("POST", path)
# 新歌速递 全部:0 华语:7 欧美:96 日本:8 韩国:16
def new_songs(self, areaId=0, total=True):
path = "/weapi/v1/discovery/new/songs"
params = dict(areaId=areaId, total=total)
return self.request("POST", path, params)
# 歌手MV
def artist_mvs(self, id, offset=0, limit=50, total=True):
path = "/weapi/artist/mvs"
params = dict(artistId=id, offset=offset, limit=limit, total=total)
return self.request("POST", path, params)
# 相似歌手
def similar_artist(self, artistid):
path = "/weapi/discovery/simiArtist"
params = dict(artistid=artistid)
return self.request("POST", path, params)
# 用户信息
def user_detail(self, id):
path = "/weapi/v1/user/detail/{}".format(id)
return self.request("POST", path)
# 关注用户
def user_follow(self, id):
path = "/weapi/user/follow/{}".format(id)
return self.request("POST", path)
# 取消关注用户
def user_delfollow(self, id):
path = "/weapi/user/delfollow/{}".format(id)
return self.request("POST", path)
# 用户关注列表
def user_getfollows(self, id, offset=0, limit=50, order=True):
path = "/weapi/user/getfollows/{}".format(id)
params = dict(offset=offset, limit=limit, order=order)
return self.request("POST", path, params)
# 用户粉丝列表
def user_getfolloweds(self, userId, offset=0, limit=30):
path = "/weapi/user/getfolloweds"
params = dict(userId=userId, offset=offset,
limit=limit, getcounts=True)
return self.request("POST", path, params)
# 听歌排行 type: 0 全部时间 1最近一周
def play_record(self, uid, type=0):
path = "/weapi/v1/play/record"
params = dict(uid=uid, type=type)
return self.request("POST", path, params)
# MV排行榜 area: 地区,可选值为内地,港台,欧美,日本,韩国,不填则为全部
def top_mv(self, area='', limit=50, offset=0, total=True):
path = "/weapi/mv/toplist"
params = dict(area=area, limit=limit, offset=offset, total=total)
return self.request("POST", path, params)
def mlog_socialsquare(self, channelId=1001, pagenum=0):
path = "/weapi/socialsquare/v1/get"
params = dict(pagenum=pagenum, netstate=1, first=(
str(pagenum) == '0'), channelId=channelId, dailyHot=(str(pagenum) == '0'))
return self.request("POST", path, params)
# 推荐MLOG
def mlog_rcmd(self, id, limit=3, type=1, rcmdType=0, lastRcmdResType=1, lastRcmdResId='', viewCount=1, channelId=1001):
path = "/weapi/mlog/rcmd/v3"
params = dict(id=id, limit=limit, type=type, rcmdType=rcmdType,
lastRcmdResType=lastRcmdResType, extInfo=dict(channelId=channelId), viewCount=viewCount)
return self.request("POST", path, params)
# MLOG详情
def mlog_detail(self, id, resolution=720, type=1):
path = "/weapi/mlog/detail/v1"
params = dict(id=id, resolution=resolution, type=type)
return self.request("POST", path, params)
# 创建歌单 privacy:0 为普通歌单,10 为隐私歌单;type:NORMAL|VIDEO
def playlist_create(self, name, privacy=0, ptype='NORMAL'):
path = "/weapi/playlist/create"
params = dict(name=name, privacy=privacy, type=ptype)
return self.request("POST", path, params)
# 删除歌单
def playlist_delete(self, ids):
path = "/weapi/playlist/remove"
params = dict(ids=ids)
return self.request("POST", path, params)
# {'code': 200}
# 添加MV到视频歌单中
def playlist_add(self, pid, ids):
path = "/weapi/playlist/track/add"
ids = [{'type': 3, 'id': song_id} for song_id in ids]
params = {'id': pid, 'tracks': json.dumps(ids)}
return self.request("POST", path, params)
# 添加/删除单曲到歌单
# op:'add'|'del'
def playlist_tracks(self, pid, ids, op='add'):
path = "/weapi/playlist/manipulate/tracks"
params = {'op': op, 'pid': pid,
'trackIds': json.dumps(ids), 'imme': 'true'}
result = self.request("POST", path, params)
# 可以收藏收费歌曲和下架歌曲
if result['code'] != 200:
ids.extend(ids)
params = {'op': op, 'pid': pid,
'trackIds': json.dumps(ids), 'imme': 'true'}
result = self.request("POST", path, params)
return result
# 收藏歌单
def playlist_subscribe(self, id):
path = "/weapi/playlist/subscribe"
params = dict(id=id)
return self.request("POST", path, params)
# 取消收藏歌单
def playlist_unsubscribe(self, id):
path = "/weapi/playlist/unsubscribe"
params = dict(id=id)
return self.request("POST", path, params)
def user_level(self):
path = "/weapi/user/level"
return self.request("POST", path)
def login_qr_key(self):
path = '/weapi/login/qrcode/unikey'
params = dict(type=1)
return self.request("POST", path, params)
def login_qr_check(self, key):
path = '/weapi/login/qrcode/client/login'
params = dict(key=key, type=1)
data = self.request("POST", path, params)
if data.get('code', 0) == 803:
self.session.cookies.save()
return data
def vip_timemachine(self, startTime, endTime, limit=60):
path = '/weapi/vipmusic/newrecord/weekflow'
params = dict(startTime=startTime,
endTime=endTime, type=1, limit=limit)
return self.request("POST", path, params)