Skip to content

Commit

Permalink
Version 1.6.8.4
Browse files Browse the repository at this point in the history
apis/user : added `SetWeblog` (#23)
demos : added `足迹伪装.py`
demos : demos can now be accessed as a anonymous user
qol : added a option to specifiy debug verbosity with user's env
  • Loading branch information
mos9527 committed Dec 11, 2022
1 parent 1a4ea53 commit 44dafcf
Show file tree
Hide file tree
Showing 9 changed files with 87 additions and 27 deletions.
8 changes: 6 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
- `coloredlogs` : 彩色日志输出

**Windows 用户**: 在 [Releases](https://github.com/mos9527/pyncm/releases) 可下载已打包 `.exe` 版本
# 使用
# 命令行使用
positional arguments:
链接 网易云音乐分享链接

Expand Down Expand Up @@ -60,7 +60,11 @@
--http 优先使用 HTTP,不保证不被升级
--log-level LOG_LEVEL
日志等级

## 环境变量
|变量名|说明|
|-|-|
|`PYNCM_DEBUG`|调试日志输出等级,`'CRITICAL', 'DEBUG', 'ERROR','FATAL','INFO','WARNING'` 之一|
### 使用示例
## 下载单曲
[![asciicast](https://asciinema.org/a/4PEC5977rTcm4hp9jLuPFYUM1.svg)](https://asciinema.org/a/4PEC5977rTcm4hp9jLuPFYUM1)
Expand Down
30 changes: 17 additions & 13 deletions demos/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import importlib
import sys,os

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

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

methods = {"手机登录": 手机登录, "二维码登录": 二维码登录}
class 匿名登陆:
@staticmethod
def login():
from pyncm.apis.login import LoginViaAnonymousAccount
return LoginViaAnonymousAccount()
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

print(
"已登录",
GetCurrentSession().nickname,
"曾用 IP:",
GetCurrentSession().lastIP,
"用户 ID:",
GetCurrentSession().uid,
)
Expand All @@ -30,9 +32,11 @@ def login():

assert_dep("pyncm")
assert_dep("inquirer")
# Find pyncm from working directories first
import sys
sys.path.insert(0,'.')

from pyncm import __version__,__file__
print("PyNCM %s" % __version__,__file__)
# 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__)
1 change: 0 additions & 1 deletion demos/二维码登录.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
"""二维码登录 Demo"""
from __init__ import assert_dep

assert_dep("qrcode")
Expand Down
6 changes: 2 additions & 4 deletions demos/云盘上传.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import hashlib, os

from __init__ import login

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


if __name__ == "__main__":
from __init__ import login

if __name__ == "__main__":
assert login(), "登录失败"
# login via phone,may change as you like
upload_one(input("文件路径:"))
36 changes: 36 additions & 0 deletions demos/足迹伪装.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
__desc__ = '''user.SetWeblog API 功能演示
摘自 https://github.com/Binaryify/NeteaseCloudMusicApi
听歌打卡
说明 : 调用此接口 , 传入音乐 id, 来源 id,歌曲时间 time,更新听歌排行数据
必选参数 : id: 歌曲 id, sourceid: 歌单或专辑 id
可选参数 : time: 歌曲播放时间,单位为秒
接口地址 : /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',
}
}
))
5 changes: 4 additions & 1 deletion pyncm/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,10 @@
import requests, logging, json, os
logger = logging.getLogger("pyncm.api")
if 'PYNCM_DEBUG' in os.environ:
logging.basicConfig(level='DEBUG', format="[%(levelname).4s] %(name)s %(message)s")
debug_level = os.environ['PYNCM_DEBUG'].upper()
if not debug_level in {'CRITICAL', 'DEBUG', 'ERROR','FATAL','INFO','WARNING'}:
debug_level = 'DEBUG'
logging.basicConfig(level=debug_level, format="[%(levelname).4s] %(name)s %(message)s")
__version__ = "1.6.8.4"

DEVICE_ID_DEFAULT = "pyncm!"
Expand Down
7 changes: 4 additions & 3 deletions pyncm/__main__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
# -*- coding: utf-8 -*-
# PyNCM CLI interface

import logging
from pyncm import (
DumpSessionAsString,
GetCurrentSession,
Expand All @@ -21,7 +20,7 @@
from os import remove, makedirs

from logging import exception, getLogger, basicConfig
import sys, argparse, re
import sys, argparse, re , os
logger = getLogger('pyncm.main')
# Import checks
OPTIONALS = {"mutagen": False, "tqdm": False, "coloredlogs": False}
Expand Down Expand Up @@ -476,7 +475,7 @@ def parse_args():
"--load", metavar="[保存的登陆信息文件]", default="", help="从文件读取登录信息供本次登陆使用"
)
group.add_argument("--http", action="store_true", help="优先使用 HTTP,不保证不被升级")
group.add_argument("--log-level", help="日志等级", default="INFO")
group.add_argument("--log-level", help="日志等级", default="NOTSET")

args = parser.parse_args()

Expand Down Expand Up @@ -506,6 +505,8 @@ def write(__s):
return sys.stdout.write(__s)

log_stream = SemaphoreStdout
if args.log_level == 'NOTSET':
args.log_level = os.environ.get('PYNCM_DEBUG','INFO')
if OPTIONALS["coloredlogs"]:
import coloredlogs

Expand Down
4 changes: 3 additions & 1 deletion pyncm/apis/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,10 @@ def wrapper(*a, **k):
ret = apiFunc(*a, **k)
url, payload = ret[:2]
method = ret[-1] if ret[-1] in ["POST", "GET"] else "POST"
logger.debug('API=%s %s url=%s deviceId=%s payload=%s' % (
logger.debug('TYPE=%s API=%s.%s %s url=%s deviceId=%s payload=%s' % (
requestFunc.__name__.split('Crypto')[0].upper(),
apiFunc.__module__,
apiFunc,
method,
url,
GetCurrentSession().deviceId,
Expand Down
17 changes: 15 additions & 2 deletions pyncm/apis/user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""用户 - User APIs"""
from . import WeapiCryptoRequest, UserIDBasedApi, LoginRequiredApi

from json import dumps

@WeapiCryptoRequest
@UserIDBasedApi
Expand Down Expand Up @@ -62,9 +62,22 @@ def SetSignin(dtype=0):
"""移动端、PC端 - 每日签到
Args:
dtype (int, optional): 签到类型,请使用本模块内 SIGNIN_TYPE_... 之一 .Defaults to SIGNIN_TYPE_MOBILE.
dtype (int, optional): 签到类型,(user.SIGNIN_TYPE_MOBILE/user.SIGNIN_TYPE_WEB). Defaults to SIGNIN_TYPE_MOBILE
Returns:
dict
"""
return "/weapi/point/dailyTask", {"type": str(dtype)}


@WeapiCryptoRequest
@LoginRequiredApi
def SetWeblog(logs):
'''移动端、PC端 - 用户足迹
网易云跟踪用户行为 API,可记录内容繁多。这里暂不描述
Args:
logs (dict): 操作记录
'''
return "/weapi/feedback/weblog" , {"logs" : dumps(logs)}

0 comments on commit 44dafcf

Please sign in to comment.