Skip to content

Commit

Permalink
Version 1.6.17
Browse files Browse the repository at this point in the history
QoL: Format code with `black`
  • Loading branch information
mos9527 committed Sep 24, 2024
1 parent 468e0ff commit 9a2a33b
Show file tree
Hide file tree
Showing 22 changed files with 1,371 additions and 539 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
![Logo](https://github.com/greats3an/pyncm/raw/master/demos/_logo.png)

# PyNCM
[![Windows Build](https://github.com/mos9527/pyncm/actions/workflows/build-and-publish.yml/badge.svg)](https://github.com/mos9527/pyncm/blob/main/.github/workflows/build-and-publish.yml) [![Releases](https://img.shields.io/github/downloads/mos9527/pyncm/total.svg)](https://GitHub.com/mos9527/pyncm/releases/) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)

第三方网易云音乐 Python API 及个人音乐库离线转储工具

**注意** : 异步使用,请移步 [`async` 分支](https://github.com/mos9527/pyncm/tree/async)
Expand Down
26 changes: 17 additions & 9 deletions demos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import importlib
import sys,os
import sys, os

IS_FIRSTTIME = sys.path[0] != "."

IS_FIRSTTIME = sys.path[0] != '.'

def assert_dep(name):
assert importlib.util.find_spec(name), "需要安装 %s" % name
Expand All @@ -10,14 +11,19 @@ def assert_dep(name):
def login():
import inquirer
import demos.手机登录 as 手机登录, 二维码登录

class 匿名登陆:
@staticmethod
def login():
from pyncm.apis.login import LoginViaAnonymousAccount

return LoginViaAnonymousAccount()
methods = {"手机登录": 手机登录, "二维码登录": 二维码登录,"匿名登陆": 匿名登陆}

methods = {"手机登录": 手机登录, "二维码登录": 二维码登录, "匿名登陆": 匿名登陆}
assert methods[
inquirer.prompt([inquirer.List("method", message="登陆方法", choices=methods)])["method"]
inquirer.prompt([inquirer.List("method", message="登陆方法", choices=methods)])[
"method"
]
].login(), "登录失败"
from pyncm import GetCurrentSession

Expand All @@ -35,8 +41,10 @@ def login():
# Find pyncm from working directories first,
if IS_FIRSTTIME:
import inquirer
if inquirer.confirm('使用调试模式'):
os.environ['PYNCM_DEBUG'] = 'DEBUG'
sys.path.insert(0,'.')
from pyncm import __version__,__file__
print("PyNCM %s" % __version__,__file__)

if inquirer.confirm("使用调试模式"):
os.environ["PYNCM_DEBUG"] = "DEBUG"
sys.path.insert(0, ".")
from pyncm import __version__, __file__

print("PyNCM %s" % __version__, __file__)
3 changes: 2 additions & 1 deletion demos/云盘上传.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import hashlib, os
from __init__ import login


def md5sum(file):
md5sum = hashlib.md5()
with open(file, "rb") as f:
Expand Down Expand Up @@ -60,7 +61,7 @@ def upload_one(path):
print("发布结果", publish_result)


if __name__ == "__main__":
if __name__ == "__main__":
assert login(), "登录失败"
# login via phone,may change as you like
upload_one(input("文件路径:"))
44 changes: 29 additions & 15 deletions demos/手机登录.py
Original file line number Diff line number Diff line change
@@ -1,39 +1,53 @@
from pyncm.apis.login import LoginViaCellphone,SetSendRegisterVerifcationCodeViaCellphone,GetRegisterVerifcationStatusViaCellphone
from pyncm import GetCurrentSession,DumpSessionAsString, LoadSessionFromString, SetCurrentSession
from pyncm.apis.login import (
LoginViaCellphone,
SetSendRegisterVerifcationCodeViaCellphone,
GetRegisterVerifcationStatusViaCellphone,
)
from pyncm import (
GetCurrentSession,
DumpSessionAsString,
LoadSessionFromString,
SetCurrentSession,
)
from pprint import pprint


def login():
import inquirer

query = inquirer.prompt(
[
inquirer.Text("phone", message="手机号"),
inquirer.Text("phone", message="手机号"),
inquirer.Text("ctcode", message="国家代码(默认86)"),
]
)
phone,ctcode = query["phone"], query["ctcode"] or 86
if inquirer.confirm('使用手机验证码登陆?'):
result = SetSendRegisterVerifcationCodeViaCellphone(phone,ctcode)
if not result.get('code',0) == 200:
phone, ctcode = query["phone"], query["ctcode"] or 86
if inquirer.confirm("使用手机验证码登陆?"):
result = SetSendRegisterVerifcationCodeViaCellphone(phone, ctcode)
if not result.get("code", 0) == 200:
pprint(result)
else:
print('[-] 已发送验证码')
print("[-] 已发送验证码")
while True:
captcha = inquirer.text("输入验证码")
verified = GetRegisterVerifcationStatusViaCellphone(phone,captcha,ctcode)
verified = GetRegisterVerifcationStatusViaCellphone(phone, captcha, ctcode)
pprint(verified)
if verified.get('code',0) == 200:
print('[-] 验证成功')
if verified.get("code", 0) == 200:
print("[-] 验证成功")
break
result = LoginViaCellphone(phone,captcha=captcha,ctcode=ctcode)
result = LoginViaCellphone(phone, captcha=captcha, ctcode=ctcode)
pprint(result)
else:
password = inquirer.password("输入密码")
result = LoginViaCellphone(phone,password=password,ctcode=ctcode)
result = LoginViaCellphone(phone, password=password, ctcode=ctcode)
pprint(result)
print('[!] 登录态 Session:',DumpSessionAsString(GetCurrentSession()))
print('[-] 此后可通过 SetCurrentSession(LoadSessionFromString("PYNCMe...")) 恢复当前登录态')
print("[!] 登录态 Session:", DumpSessionAsString(GetCurrentSession()))
print(
'[-] 此后可通过 SetCurrentSession(LoadSessionFromString("PYNCMe...")) 恢复当前登录态'
)
return True


if __name__ == "__main__":
print("[-] 登录测试")
assert login(), "登陆失败"
38 changes: 24 additions & 14 deletions demos/歌单同步.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
'''
"""
以下 .pyncm 即为你保存的登陆凭据
---
使用例 : 同步个人创建的歌单到`NetEase/[专辑名]`
Expand All @@ -7,50 +7,60 @@
python ./demos/歌单同步.py --load .pyncm --quality hires --output NetEase/{album} --user-bookmarks --save-m3u NetEase/PLAYLIST.m3u
使用例 : 同步某一歌单到`NetEase/[专辑名]`
python ./demos/歌单同步.py --load .pyncm --quality hires --output NetEase/{album} https://music.163.com/playlist?id=988690134
'''
"""

from sys import argv
from os import walk,path,remove
from pyncm.__main__ import parse_args ,PLACEHOLDER_URL,__main__
from pyncm import GetCurrentSession,SetCurrentSession,LoadSessionFromString
from os import walk, path, remove
from pyncm.__main__ import parse_args, PLACEHOLDER_URL, __main__
from pyncm import GetCurrentSession, SetCurrentSession, LoadSessionFromString
from pyncm.utils.helper import UserHelper

# 指定 quit_on_empty_args=False 便于传入空 ID
args, _ = parse_args(quit_on_empty_args=False)
print("[-] 读取登录信息 : %s" % args.load)
SetCurrentSession(LoadSessionFromString(open(args.load).read()))
print("[*] 用户 : %s" % UserHelper(GetCurrentSession().uid).UserName)
try:
# 使用未模板化的最高级目录做输出目录起点
output = args.output[:args.output.index('{')]
output = args.output[: args.output.index("{")]
except IndexError:
output = args.output
print("[*] 输出文件夹起点 : %s" % output)


def normalize(path):
return path.replace('\\','/') # 统一 Windows/Unix 路径格式
return path.replace("\\", "/") # 统一 Windows/Unix 路径格式


# 平面化目录结构,准备后期比对
file_tree = [normalize(path.join(root,file)) for root, dirs, files in walk(output,topdown=False) for file in files]
file_tree = [
normalize(path.join(root, file))
for root, dirs, files in walk(output, topdown=False)
for file in files
]
# 调用 pyncm 下载
if args.url == PLACEHOLDER_URL:
# 未填入 ID 则使用用户本人歌单
argv.append('https://music.163.com/#/user/home?id=%s' % GetCurrentSession().uid)
argv.append("https://music.163.com/#/user/home?id=%s" % GetCurrentSession().uid)
argv.append("--no-overwrite")
# 不覆写已存在歌曲
# argv 传参,调用 __main__ 即可
queuedTasks, failed_ids = __main__(return_tasks=True)
# 无视拓展名的文件白名单
file_tree_whitelist = [normalize(task.save_as) for task in queuedTasks]
# 只删除这些拓展名的文件
extension_blacklist = {'m4a','mp3','flac','ogg','lrc','ass'}
extension_blacklist = {"m4a", "mp3", "flac", "ogg", "lrc", "ass"}
for file in file_tree:
delete_flag = True
for file_whitelist in file_tree_whitelist:
if file.startswith(file_whitelist):
delete_flag = False
break
if delete_flag:
ext = file.split('.')[-1].lower()
if ext in extension_blacklist:
ext = file.split(".")[-1].lower()
if ext in extension_blacklist:
try:
print('[!] 删除 %s' % file)
print("[!] 删除 %s" % file)
remove(file)
except Exception as e:
print('[!!] 删除 %s 失败: %s' % (file,e))
print("[!!] 删除 %s 失败: %s" % (file, e))
40 changes: 23 additions & 17 deletions demos/足迹伪装.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__desc__ = '''user.SetWeblog API 功能演示
__desc__ = """user.SetWeblog API 功能演示
摘自 https://github.com/Binaryify/NeteaseCloudMusicApi
Expand All @@ -13,24 +13,30 @@
接口地址 : /scrobble
调用例子 : /scrobble?id=518066366&sourceid=36780169&time=291
'''
"""
from __init__ import login

assert login(), "登录失败"
from pyncm.apis.user import SetWeblog
from pprint import pprint

print(__desc__)
pprint(SetWeblog(
[{
'action': 'play',
'json': {
'download': 0,
'end': 'playend',
'id': input('歌曲 ID:'),
'sourceId': input('来源 ID:'),
'time': input('时长:') or 300,
'type': 'song',
'wifi': 0,
'source' : 'list',
}
}]
))
pprint(
SetWeblog(
[
{
"action": "play",
"json": {
"download": 0,
"end": "playend",
"id": input("歌曲 ID:"),
"sourceId": input("来源 ID:"),
"time": input("时长:") or 300,
"type": "song",
"wifi": 0,
"source": "list",
},
}
]
)
)
18 changes: 10 additions & 8 deletions pyncm.tests.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import unittest,logging
import unittest, logging
import pyncm, pyncm.apis

logging.basicConfig(level=0)
# Account from https://github.com/Binaryify/NeteaseCloudMusicApi/blob/master/test/login.test.js
pyncm.SetCurrentSession(
Expand All @@ -8,30 +9,31 @@
)
)


class APITest(unittest.TestCase):
def test_set_like(self):
self.assertEqual(
pyncm.apis.track.SetLikeTrack(31140560, like=True).get("code", 0),200
pyncm.apis.track.SetLikeTrack(31140560, like=True).get("code", 0), 200
)

def test_set_like_revert(self):
self.assertEqual(
pyncm.apis.track.SetLikeTrack(31140560, like=False).get("code", 0) , 200
pyncm.apis.track.SetLikeTrack(31140560, like=False).get("code", 0), 200
)

def test_manipulate_playlist(self):
playlist = pyncm.apis.playlist.SetCreatePlaylist("Playlist")
self.assertEqual(playlist.get("code", 0) , 200, "Cannot create Playlist")
self.assertEqual(playlist.get("code", 0), 200, "Cannot create Playlist")
self.assertEqual(
pyncm.apis.playlist.SetManipulatePlaylistTracks(
31140560, playlist.get("id", 0)
).get("code", 0)
, 200,
).get("code", 0),
200,
"Cannot add track to playlist created",
)
self.assertEqual(
pyncm.apis.playlist.SetRemovePlaylist(playlist.get("id", 0)).get("code", 0)
, 200,
pyncm.apis.playlist.SetRemovePlaylist(playlist.get("id", 0)).get("code", 0),
200,
"Cannot remove track from playlist created",
)

Expand Down
Loading

0 comments on commit 9a2a33b

Please sign in to comment.