Skip to content

Commit

Permalink
feat: 可以使用 cookie 登录 (chen310#117)
Browse files Browse the repository at this point in the history
  • Loading branch information
chen310 authored Mar 16, 2022
1 parent 3562bff commit 5e52725
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 44 deletions.
30 changes: 14 additions & 16 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,43 +22,46 @@ def __init__(self, username=''):
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "music.163.com",
"Referer": "http://music.163.com",
"Referer": "https://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",
}
username = str(username)
self.username = username
self.session = requests.Session()
if len(username) == 0:
return

cookie_file = self.get_cookie_file(username)
if len(cookie_file) > 0:
if username and cookie_file:
cookie_jar = LWPCookieJar(cookie_file)
cookie_jar.load()
self.session.cookies = cookie_jar
self.session.cookies.load()
else:
cookie_jar = LWPCookieJar()
self.session.cookies = cookie_jar


def get_cookie_file(self, filename):
if len(filename) == 0:
return None
data_dir = os.path.join(os.path.expanduser("."), ".user_data")
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 ""
return None
if not os.path.exists(user_path):
try:
os.makedirs(user_path)
except:
return ""
return None

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 None

return cookie_file

Expand Down Expand Up @@ -105,11 +108,8 @@ def request(self, method, path, params={}, base_url=BASE_URL, default={"code": -
data = default

for key, value in custom_cookies.items():
if isinstance(self.session.cookies, LWPCookieJar):
cookie = self.make_cookie(key, value)
self.session.cookies.set_cookie(cookie)
else:
self.session.cookies.set(key, value)
cookie = self.make_cookie(key, value)
self.session.cookies.set_cookie(cookie)

params = encrypted_request(params)
try:
Expand All @@ -130,8 +130,6 @@ def login(self, username, password, countrycode='86'):
cookie_jar = LWPCookieJar(cookie_file)
cookie_jar.load()
self.session.cookies = cookie_jar
self.session.cookies.load()
# self.session.cookies.save()
self.username = username
if len(password) < 32:
password = md5(password.encode(encoding='UTF-8')).hexdigest()
Expand Down
16 changes: 6 additions & 10 deletions config.example.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
/* 开源地址: https://github.com/chen310/NeteaseCloudMusicTasks */
"version": "2.19",
/* 多账号的配置详见 https://github.com/chen310/NeteaseCloudMusicTasks#%E5%A4%9A%E8%B4%A6%E5%8F%B7 */
"users": [
{
/* 填写手机号或邮箱 */
Expand All @@ -9,21 +10,16 @@
"countrycode": "",
/* 填写密码或 32 位 md5 加密后的密码 */
"password": "",
/* 若都填写了账号密码和 cookie,优先使用 cookie */
/* cookie 失效后才会使用账号密码登录 */
/* cookie 的格式为 MUSIC_U=xxxxxxxx; */
"cookie": "",
/* 填写国内IP,否则可能会有无法登录等问题出现,多个账号最好设置不同的IP */
/* 可填写本机IP,查看方法:https://www.ip138.com/ 填写显示的ip即可 */
"X-Real-IP": "",
/* 是否运行该账号的任务 */
"enable": true
/* 若每个账号的任务设置不同,请在下方单独设置 */
/* ,"setting":{} */
} /*,{
"username":"",
"countrycode": "",
"password":"",
"X-Real-IP":"",
"enable": true
}*/
/* 多个账号删除上面的注释,以此类推 */
}
],
"setting": {
/* 推送 */
Expand Down
66 changes: 48 additions & 18 deletions user.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@ def errMsg(self, data):
return str(data)

def setUser(self, user_config, user_setting):
if len(user_config['username']) == 0:
self.title += ': 请填写账号密码'
if len(user_config['username']) == 0 and len(user_config['cookie']) == 0:
self.title += ': 请填写账号密码或cookie'
self.taskTitle('用户信息')
self.taskInfo('登录失败,请填写账号密码')
raise Exception('请填写账号密码')
self.music = self.login_check(user_config['username'], user_config['password'], user_config.get(
self.taskInfo('登录失败,请填写账号密码或cookie')
raise Exception('请填写账号密码或cookie')
self.music = self.login_check(user_config['username'], user_config['password'], user_config['cookie'], user_config.get(
'countrycode', ''), user_config['X-Real-IP'])
if self.music.uid != 0:
self.isLogined = True
Expand All @@ -61,25 +61,55 @@ def setUser(self, user_config, user_setting):
self.taskTitle('用户信息')
self.taskInfo('登录失败,' + msg)
self.finishTask()

def login_check(self, username, pwd='', countrycode='', ip=''):
def set_cookies(self, cookie, music):
cookies = {}
sp = cookie.split(";")
cookies = {}
for c in sp:
t = []
if ':' in c:
t = c.split(':')
elif '=' in c:
t = c.split('=')
if len(t) == 2:
cookies[t[0]] = t[1]
if len(cookies) > 0:
cookies['__remember_me'] = 'true'
for key, value in cookies.items():
c = music.make_cookie(key, value)
music.session.cookies.set_cookie(c)

def login_check(self, username, pwd='', cookie='', countrycode='', ip=''):
music = NetEase(username)
if len(ip) > 0:
music.header["X-Real-IP"] = ip

if len(cookie) > 0:
self.set_cookies(cookie, music)
resp = music.user_level()
if resp['code'] == 200:
print('已通过配置文件中的 cookie 登录')
music.uid = resp['data']['userId']
user_resp = music.user_detail(music.uid)
if 'artistId' in user_resp['profile']:
self.artistId = user_resp['profile']['artistId']
self.listenSongs = user_resp['listenSongs']
music.nickname = user_resp['profile']['nickname']
music.userType = user_resp['profile']['userType']
if music.userType != 0 and music.userType != 4:
for authtype in user_resp['profile'].get('allAuthTypes', []):
if authtype['type'] == 4:
music.userType = 4
break
return music
else:
print('配置文件中的 cookie 填写错误或已失效')
music.session.cookies.clear()

if self.runtime == 'tencent-scf':
var_name = 'COOKIE_' + re.sub('[^a-zA-Z0-9]', '_', username)
if var_name in os.environ:
sp = os.environ.get(var_name).split(";")
cookies = {}
for c in sp:
t = c.split(':')
if len(t) == 2:
cookies[t[0]] = t[1]
if len(cookies) > 0:
music.session = requests.Session()
cookies['__remember_me'] = 'true'
requests.utils.add_dict_to_cookiejar(
music.session.cookies, cookies)
self.set_cookies(os.environ.get(var_name), music)
resp = music.user_level()
if resp['code'] == 200:
print('已通过 cookie 登录')
Expand Down

0 comments on commit 5e52725

Please sign in to comment.