#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ unlockmusic.py —— 主脚本:扫码登录 → 解锁(解禁)歌曲 → 登出 ================================================================================ **它没有自己的协议实现** —— 整个流程直接复用 `upsert.py` 的 `run()`: 扫码 → 预览 → 登录 → UpsertUserAll → 落库回查 → 登出,一模一样。 **它也没有自己的接口** —— `api/UpsertUserAll.py` 只负责组装「基础包体」, 本脚本要做的只是算出「该往 userItemList 里补哪几条」,然后通过 `extra_data` 交给 `UpsertUserAll` 自动匹配并覆盖对应节点。 -------------------------------------------------------------------------------- 为什么解锁不用单独的接口 -------------------------------------------------------------------------------- 游戏里解锁不是一次独立的网络请求,而是**往 userItemList 里补几条 UserItem**: itemKind = 5 歌曲本体解锁(MusicUnlockList) itemKind = 6 Master 难度解锁(MusicUnlockMasterList) itemKind = 7 Re:Master 难度解锁(MusicUnlockReMasterList) 依据 source/Assembly-CSharp/Net.VO.Mai2/VOExtensions.cs:981-1008 (UserData.cs:132-138 那四个解锁列表不是独立节点,是并进 userItemList 的)。 条目长这样: {"itemKind": 5, "itemId": 11414, "stock": 1, "isValid": true} ★ 标准谱(musicId < 10000)的 Master / Re:Master **天生解锁**,不会写 kind6/7 (source/Assembly-CSharp/Manager/NotesListManager.cs:415/455 开头就是 `if (id < 10000) return true;`);只有 DX 谱(>= 10000)才需要额外解禁。 ★ 服务器上已经有的条目**自动跳过** —— 重复插入会让服务端直接 HTTP 500。 所以这里给 `UpsertUserAll` 传的是一个 `callable(snapshot, user_all)`: 等它把服务器快照取回来之后再算,才能知道哪些条目已经存在。 ★ 只想补难度、不想动歌曲本体时用 `--no-unlock-base`(不写 kind5)。 但歌曲本体没解锁时游戏里可能连谱面都进不去,正常场景不要关它。 ★ Re:Master 还受活动开关约束(IsUnlockReMaster 里的 IsOpenEvent), 那是机台侧开关,脚本改不了;写了也可能进游戏仍是灰的。 ★ 位串(isNewItemList)默认写 **0**,不写 1: 0 = 让服务端把这条当作「存量更新」,1 = 当作「新增插入」。 实测写 1 有概率直接报错,写 0 稳;反正条目本身带着完整的 itemKind / itemId / stock / isValid,服务端按主键更新即可。 ★ 本功能**没有真机抓包可对照**(机台侧的解锁不上报),是按源码实现的。 -------------------------------------------------------------------------------- 用法 -------------------------------------------------------------------------------- python unlockmusic.py <二维码> --music 11414 # 预检,不发包 python unlockmusic.py <二维码> --music 11414 --send # ★ 真实解锁 python unlockmusic.py <二维码> --music 1085,11414 --send # 多首,逗号分隔 python unlockmusic.py <二维码> --music 11414 --send --no-unlock-remaster # 只要歌曲本体,不解禁任何难度 python unlockmusic.py <二维码> --music 11414 --send --no-unlock-master --no-unlock-remaster # 反过来:歌已经解锁了,只想补 Master / Re:Master 难度 python unlockmusic.py <二维码> --music 11414 --send --no-unlock-base # 和其它主脚本一样的通用开关 python unlockmusic.py <二维码> --music 11414 --send --debug python unlockmusic.py <二维码> --music 11414 --send --cooldown 0 python unlockmusic.py <二维码> --music 11414 --send --no-verify | 参数 | 说明 | |---|---| | `--music ID[,ID...]` | 要解锁的 musicId,可重复、可逗号分隔(`--unlock-music` 也认) | | `--send` | 真正发包(不加就是预检,零副作用) | | `--no-unlock-master` | 不解禁 Master | | `--no-unlock-remaster` | 不解禁 Re:Master | | `--no-unlock-base` | **不解锁歌曲本体**(不写 kind5),只解禁难度 | | `--extra-data X` | 再额外塞节点(和 `upsert.py` 完全一样) | | `--cooldown N` | 发包前冷却秒数,默认取 config 的 50 秒 | | `--no-verify` | 跳过上传后的落库回查 | | `--debug` | 本次运行打印完整收发报文 | 日志同样是 logs/latest.log(覆盖)+ logs/YYYY-MM-DD.log(追加)。 """ from __future__ import annotations import sys from typing import Any, Dict, List, Optional, Sequence, Tuple import upsert from api import log_error, log_info, setup_logging, teardown_logging #: UserItem.itemKind 取值(source/Assembly-CSharp/Manager/UserData.cs:132-138) ITEM_KIND_MUSIC_UNLOCK = 5 ITEM_KIND_MUSIC_UNLOCK_MASTER = 6 ITEM_KIND_MUSIC_UNLOCK_REMASTER = 7 ITEM_KIND_MUSIC_UNLOCK_STRONG = 8 #: 小于这个 musicId 的谱面 Master / Re:Master 天生解锁(NotesListManager.cs:415/455) UNLOCK_MASTER_MIN_MUSIC_ID = 10000 #: 新条目的位串字符:0 = 存量更新(UPDATE),1 = 新增插入(INSERT) #: ★ 默认 0:写 1 时服务端有概率报错,写 0 稳(条目自带完整字段,按主键更新即可) UNLOCK_NEW_BIT = "0" def build_unlock_items( music_ids: Sequence[int], existing: Optional[Sequence[Any]] = None, *, master: bool = True, remaster: bool = True, unlock_base: bool = True, ) -> Tuple[List[Dict[str, Any]], List[str]]: """ 构造「解锁歌曲 / 解禁难度」要追加的 userItemList 条目。 ★ 只返回**服务器上还没有**的条目;已存在的跳过(重复插入会让服务端报错)。 参数: music_ids: 要解锁的 musicId 列表(重复的自动去掉) existing: 服务器现有的 userItemList(GetUserData 里的那份), 用来判断哪些条目已经存在 master: True = 同时解锁 Master 难度(仅 musicId >= 10000 才写 kind6) remaster: True = 同时解锁 Re:Master 难度(仅 musicId >= 10000 才写 kind7) unlock_base: True = 解锁歌曲本体(kind5) 返回: (条目列表, 说明文字列表) 条目形如 {"itemKind":5,"itemId":1085,"stock":1,"isValid":true} """ have: set = set() for it in existing or []: if isinstance(it, dict): try: have.add((int(it.get("itemKind")), int(it.get("itemId")))) except (TypeError, ValueError): continue ids: List[int] = [] for raw in music_ids or []: try: mid = int(raw) except (TypeError, ValueError): continue if mid <= 0 or mid in ids: continue ids.append(mid) items: List[Dict[str, Any]] = [] notes: List[str] = [] def _add(kind: int, mid: int, what: str) -> None: if (kind, mid) in have: notes.append("解锁检查:musicId=" + str(mid) + " 的" + what + "已经解锁(itemKind=" + str(kind) + "),跳过") return have.add((kind, mid)) items.append({"itemKind": kind, "itemId": mid, "stock": 1, "isValid": True}) notes.append("解锁:musicId=" + str(mid) + " " + what + "(itemKind=" + str(kind) + ")") for mid in ids: if unlock_base: _add(ITEM_KIND_MUSIC_UNLOCK, mid, "歌曲本体") if mid < UNLOCK_MASTER_MIN_MUSIC_ID: # ★ 标准谱(musicId < 10000)Master/Re:Master 天生解锁,不需要条目 if master or remaster: notes.append("解锁检查:musicId=" + str(mid) + " 是标准谱(< " + str(UNLOCK_MASTER_MIN_MUSIC_ID) + "),Master/Re:Master 天生解锁,跳过") continue if master: _add(ITEM_KIND_MUSIC_UNLOCK_MASTER, mid, "Master 难度") if remaster: _add(ITEM_KIND_MUSIC_UNLOCK_REMASTER, mid, "Re:Master 难度") return items, notes def make_unlock_extra( music_ids: Sequence[int], *, master: bool = True, remaster: bool = True, unlock_base: bool = True, new_bit: str = UNLOCK_NEW_BIT, ): """ 生成交给 `UpsertUserAll` 的 `extra_data` 钩子。 返回 `callable(snapshot, user_all) -> dict`: snapshot —— 归一化后的服务器快照(可读 userItemList 判断已解锁) user_all —— 已组装好的基础包体(可读当前 userItemList 差分条目) 产出的 dict 只有两个节点: {"userItemList": [...], "isNewItemList": "..."} 新条目追加在原有条目之后,位串对应位置补 new_bit (默认 "0" = 存量更新;写 "1" = 新增插入,有概率被服务端拒绝)。 没有任何新条目时返回空 dict,基础包体原样不动。 """ bit = str(new_bit or "0")[:1] if bit not in ("0", "1"): bit = UNLOCK_NEW_BIT def _builder(snapshot: Any, user_all: Any) -> Dict[str, Any]: base = snapshot if isinstance(snapshot, dict) else {} current = user_all if isinstance(user_all, dict) else {} items, notes = build_unlock_items( music_ids, existing=base.get("userItemList") or [], master=master, remaster=remaster, unlock_base=unlock_base, ) for note in notes: log_info(note) if not items: log_info("解锁检查:指定的歌曲/难度在服务器上都已经解锁,无需改动") return {} old_items = list(current.get("userItemList") or []) old_bits = current.get("isNewItemList") if not isinstance(old_bits, str): old_bits = "" if len(old_bits) != len(old_items): # 先对齐到旧列表长度,避免新条目被 sync_bits_to_arrays 补成 "0" old_bits = (old_bits + "0" * len(old_items))[:len(old_items)] log_info("★ 本次解锁共新增 " + str(len(items)) + " 个 userItem 条目(位串补 " + bit * len(items) + ",0 = 存量更新)") return { "userItemList": old_items + items, "isNewItemList": old_bits + bit * len(items), } return _builder def parse_args(argv): """极简命令行解析:第一个非 -- 开头的参数是二维码。""" opts = {"qr": "", "send": False, "debug": False, "no_verify": False, "cooldown": None, "extra_data": [], "unlock_music": [], "unlock_master": True, "unlock_remaster": True, "unlock_base": True} i = 0 while i < len(argv): a = argv[i] if a == "--send": opts["send"] = True elif a == "--debug": opts["debug"] = True elif a == "--no-verify": opts["no_verify"] = True elif a == "--extra-data" and i + 1 < len(argv): opts["extra_data"].append(argv[i + 1]) i += 1 elif a == "--cooldown" and i + 1 < len(argv): opts["cooldown"] = float(argv[i + 1]) i += 1 elif a in ("--music", "--unlock-music") and i + 1 < len(argv): # 可重复;也支持逗号分隔(中英文逗号都认) for part in str(argv[i + 1]).replace(",", ",").split(","): part = part.strip() if not part: continue try: opts["unlock_music"].append(int(part)) except ValueError: opts["unlock_bad"] = part i += 1 elif a == "--no-unlock-master": opts["unlock_master"] = False elif a == "--no-unlock-remaster": opts["unlock_remaster"] = False elif a == "--no-unlock-base": # ★ 只解禁难度,不解锁歌曲本体(不写 kind5) opts["unlock_base"] = False elif not a.startswith("--") and not opts["qr"]: opts["qr"] = a i += 1 return opts def main() -> int: opts = parse_args(sys.argv[1:]) if not opts["qr"] or not opts["unlock_music"]: # 没有二维码、或者没有指定要解锁哪首 —— 直接把用法打出来 print(__doc__) return 1 if opts.get("unlock_bad"): # 参数本身就不对,连扫码都不用做 setup_logging("unlockmusic") log_error("--music 里有非法 musicId:" + str(opts["unlock_bad"])) teardown_logging() return 6 # ★ 整个流程复用 upsert.run();解锁只是往 extra_data 里塞一个钩子 extra = make_unlock_extra( opts["unlock_music"], master=opts["unlock_master"], remaster=opts["unlock_remaster"], unlock_base=opts["unlock_base"], ) return upsert.run(opts, extra_data=extra, log_name="unlockmusic") if __name__ == "__main__": sys.exit(main())