-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathapi.py
416 lines (359 loc) · 15 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
# -*- coding: utf-8 -*-
import platform
import json
import os
import re
import requests
from http.cookiejar import Cookie, LWPCookieJar
from encrypt import encrypted_request
DEFAULT_TIMEOUT = 10
BASE_URL = "https://music.163.com"
class NetEase(object):
def __init__(self, username=''):
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",
"X-Real-IP": "113.81.100.24",
"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数据
with open('./config.json', 'r', encoding='utf-8') as f:
self.COOKIE_DATA = json.loads(re.sub(r'\/\*[\s\S]*?\/', '', f.read()))["cookie"]
username = str(username)
# 输入的用户名存着
self.username = username
# 创建session
self.session = requests.Session()
if len(username) == 0:
return
# 获取存放cookie文件的路径
cookie_file = self.get_cookie_file(username)
if len(cookie_file) > 0:
cookie_jar = LWPCookieJar(cookie_file)
cookie_jar.load()
self.session.cookies = cookie_jar
self.session.cookies.load()
# print()
# 这个创建cookie保存的数据个人认为可有可无,因为使用了cookie的话就没必要保存了
def get_cookie_file(self, filename):
data_dir = os.path.join(os.path.expanduser("."), ".user_data(存储cookie)")
user_path = os.path.join(data_dir, filename)
cookie_file = os.path.join(user_path, "cookie")
if not os.path.exists(data_dir):
try:
os.makedirs(data_dir)
except:
return ""
if not os.path.exists(user_path):
try:
os.makedirs(user_path)
except:
return ""
if not os.path.exists(cookie_file):
try:
with open(cookie_file, "w", encoding="utf-8") as f:
f.write('#LWP-Cookies-2.0\nSet-Cookie3:')
f.close()
except:
return ""
return cookie_file
def _raw_request(self, method, endpoint, data=None):
if method == "GET":
resp = self.session.get(
endpoint, params=data, headers=self.header, timeout=DEFAULT_TIMEOUT
)
elif method == "POST":
resp = self.session.post(
endpoint, data=data, headers=self.header, timeout=DEFAULT_TIMEOUT
)
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={},
)
# 这个request是对网易云数据进行操作的接口,登录成功之后就会将登录信息存放在token上,这样就可以直接通过request去操作
def request(self, method, path, params={}, base_url=BASE_URL, default={"code": -1}, custom_cookies={'os': 'pc'}):
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
# 这里添加一下cookie,直接就可以用来!
custom_cookies.update({'MUSIC_U': self.COOKIE_DATA})
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):
username = str(username)
cookie_file = self.get_cookie_file(username)
if len(cookie_file) > 0:
if self.username != username:
# 这个是读取存储在文件的cookie,然后赋值给seesion保存
cookie_jar = LWPCookieJar(cookie_file)
cookie_jar.load()
self.session.cookies = cookie_jar
self.session.cookies.load()
self.username = username
# 这个是手机号登录
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
if len(cookie_file) > 0:
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=50, includeVideo=True):
path = "/weapi/user/playlist"
params = dict(uid=uid, offset=offset, limit=limit,
includeVideo=includeVideo)
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)
# 添加/删除单曲到歌单
# 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'] == 512:
ids.extend(ids)
params = {'op': op, 'pid': pid,
'trackIds': json.dumps(ids), 'imme': 'true'}
result = self.request("POST", path, params)
return result
# 更新歌单描述
def playlist_desc_update(self, id, desc):
path = "/weapi/playlist/desc/update"
params = dict(id=id, desc=desc)
return self.request("POST", path, params)
# 每日推荐歌单
def recommend_resource(self):
path = "/weapi/v1/discovery/recommend/resource"
return self.request("POST", path).get("recommend", [])
# 推荐歌单
def personalized_playlist(self, limit=9):
path = "/weapi/personalized/playlist"
params = dict(limit=limit)
return self.request("POST", path, params).get("result", [])
# 私人FM
def personal_fm(self):
path = "/weapi/v1/radio/get"
return self.request("POST", path) # .get("data", [])
# 歌单详情
def playlist_detail(self, playlist_id):
path = "/weapi/v3/playlist/detail"
params = dict(id=playlist_id, total="true",
limit=1000, n=1000, offest=0)
# cookie添加os字段
custom_cookies = dict(os=platform.system())
return self.request("POST", path, params, {"code": -1}, custom_cookies)
# 专辑详情
def album(self, album_id):
path = "/weapi/v1/album/{}".format(album_id)
return self.request("POST", path) # .get("songs", [])
# 歌曲详情
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).get("songs", [])
# 关注用户
def user_follow(self, id):
path = "/weapi/user/follow/{}".format(id)
return self.request("POST", path)
# 听歌排行 type: 0 全部时间 1最近一周
def play_record(self, uid, time_type=0, limit=1000, offset=0, total=True):
path = "/weapi/v1/play/record"
params = dict(uid=uid, type=time_type, limit=limit,
offset=offset, total=total)
return self.request("POST", path, params)
# 创建歌单 privacy:0 为普通歌单,10 为隐私歌单;type:NORMAL|VIDEO
def playlist_creat(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 daka(self, song_datas):
path = "/weapi/feedback/weblog"
songs = []
for i in range(len(song_datas)):
song = {
'action': 'play',
'json': song_datas[i]
}
songs.append(song)
params = {'logs': json.dumps(songs)}
return self.request("POST", path, params)
# 用户信息
def user_detail(self, uid):
path = "/weapi/v1/user/detail/{}".format(uid)
return self.request("POST", path)
def user_level(self):
path = "/weapi/user/level"
return self.request("POST", path)
# 云贝所有任务
def yunbei_task(self):
path = "/weapi/usertool/task/list/all"
return self.request("POST", path) # .get("data", [])
# 云贝todo任务
def yunbei_task_todo(self):
path = "/weapi/usertool/task/todo/query"
return self.request("POST", path) # .get("data", [])
# 完成云贝任务
def yunbei_task_finish(self, userTaskId, depositCode):
path = "/weapi/usertool/task/point/receive"
params = dict(userTaskId=userTaskId, depositCode=depositCode)
return self.request("POST", path, params)
def share_resource(self, type='playlist', msg='', id=''):
path = "/weapi/share/friends/resource"
params = dict(type=type, msg=msg, id=id)
return self.request("POST", path, params)
# 删除动态
def event_delete(self, id):
path = "/weapi/event/delete"
params = dict(id=id)
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)
###########################
# 音乐人
# 概况
def musician_data(self):
path = '/weapi/creator/musician/statistic/data/overview/get'
return self.request("POST", path)
# 获取任务
def mission_cycle_get(self, actionType='', platform=''):
path = '/weapi/nmusician/workbench/mission/cycle/list'
if actionType == '' and platform == '':
return self.request("POST", path)
else:
params = dict(actionType=actionType, platform=platform)
return self.request("POST", path, params)
# 领取云豆
def reward_obtain(self, userMissionId, period):
path = '/weapi/nmusician/workbench/mission/reward/obtain/new'
params = dict(userMissionId=userMissionId, period=period)
return self.request("POST", path, params)
# 账号云豆数
def cloudbean(self):
path = "/weapi/cloudbean/get"
return self.request("POST", path)
def user_access(self):
path = '/weapi/creator/user/access'
return self.request("POST", path)
# 完成云贝任务: 访问商城
def visit_mall(self):
path = "/weapi/yunbei/task/visit/mall"
return self.request("POST", path)
# 对歌曲进行评论
def comments_add(self, song_id, content):
path = "/weapi/resource/comments/add"
params = dict(threadId='R_SO_4_' + str(song_id), content=content)
return self.request("POST", path, params)
# 回复歌曲评论
def comments_reply(self, song_id, commentId, content):
path = "/weapi/v1/resource/comments/reply"
params = dict(commentId=commentId, threadId='R_SO_4_' +
str(song_id), content=content)
return self.request("POST", path, params)
# 删除评论
def comments_delete(self, song_id, commentId):
path = "/weapi/resource/comments/delete"
params = dict(commentId=commentId, threadId='R_SO_4_' + str(song_id))
return self.request("POST", path, params)
# 发送私信
def msg_send(self, msg, userIds, type='text'):
path = "/weapi/msg/private/send"
params = dict(type=type, msg=msg, userIds=userIds)
return self.request("POST", path, params)
def update_playcount(self, id):
path = "/weapi/playlist/update/playcount"
params = dict(id=id)
return self.request("POST", path, params)
# 云贝推歌
def yunbei_rcmd_submit(self, songId, yunbeiNum=10, reason='有些美好会迟到,但音乐能带你找到', scene='', fromUserId=-1):
path = "/weapi/yunbei/rcmd/song/submit"
params = dict(songId=songId, reason=reason, scene=scene,
yunbeiNum=yunbeiNum, fromUserId=fromUserId)
return self.request("POST", path, params)
# vip level
def vip_level(self):
path = "/weapi/music-vip-membership/client/vip/info"
return self.request("POST", path)
# vip任务列表
def vip_task_list(self):
path = "/weapi/vipnewcenter/app/level/task/list"
return self.request("POST", path)
# 领取会员成长值
def vip_reward_get(self, taskIds):
path = "/weapi/vipnewcenter/app/level/task/reward/get"
params = dict(taskIds=','.join(taskIds))
return self.request("POST", path, params)
# 新vip任务列表
def vip_task_newlist(self):
path = "/weapi/vipnewcenter/app/level/task/newlist"
return self.request("POST", path)
# 领取所有会员成长值
def vip_reward_getall(self):
path = "/weapi/vipnewcenter/app/level/task/reward/getall"
return self.request("POST", path)