v1进行时:UpsertUserAll回归基础包体(附加数据一律走extra_data)、解锁位串默认0、适配2026-10服务器维护(token一次性、上传冷却50s、买票冷却40s写入config)、新增落盘与日志开关

This commit is contained in:
Txiaochen committed 2026-11-07 20:34:24 +08:00
1 parent 1d365cc948
commit ed7d463519
12 files changed
+552 -271

No files matched your search

+28 -4
View File
@@ -82,6 +82,23 @@ def user_data_path(user_id: int) -> Path:
return DATA_DIR / (str(int(user_id)) + ".json")
def config_save_default() -> bool:
"""
读 config.py 的 SAVE_USER_DATA 阀门(默认 True = 自动落盘)。
★ 只在调用方**没有显式传** save 时生效:
GetNeedUserData(uid) -> 看这个阀门
GetNeedUserData(uid, save=False) -> 强制不落盘
GetNeedUserData(uid, save=True) -> 强制落盘
GetNeedUserData(uid, save_path="x") -> 一定写,路径优先
"""
try:
import config as _cfg # type: ignore
return bool(getattr(_cfg, "SAVE_USER_DATA", True))
except Exception:
return True
def save_user_data(snapshot: Dict[str, Any], user_id: int,
path: Optional[str] = None) -> str:
"""
@@ -181,7 +198,7 @@ def GetNeedUserData(
timeout_ms: Optional[int] = None,
client: Optional[MaimaiNetClient] = None,
strict: bool = False,
save: bool = True,
save: Optional[bool] = None,
save_path: Optional[str] = None,
) -> Dict[str, Any]:
"""
@@ -199,9 +216,11 @@ def GetNeedUserData(
client: 可复用的 MaimaiNetClient
strict: True = 任一接口失败就抛异常;
False(默认)= 记录失败并跳过,保证链路不崩
save: True(默认)= 抓完自动落盘到 <工程根>/data/<userId>.json
save: 是否落盘到 <工程根>/data/<userId>.json
None(默认)= 读 config.py 的 SAVE_USER_DATA 阀门
True = 强制保存;False = 强制不保存
(★ 新数据总是覆盖老数据)
save_path: 自定义落盘路径(可选,给了就忽略 save 的默认路径规则)
save_path: 自定义落盘路径(可选,给了就一定写,忽略 save 的判定)
返回:
{
@@ -311,11 +330,16 @@ def GetNeedUserData(
+ str(len(failed)) + " 个")
# ★ 落盘:<工程根>/data/<userId>.json(覆盖式)
if save or save_path:
# 显式给了 save_path 就一定要写;否则看 save(None = 读 config.SAVE_USER_DATA)
save_flag = config_save_default() if save is None else bool(save)
if save_path or save_flag:
try:
save_user_data(raw, user_id, path=save_path)
except Exception as exc:
log_warning("用户数据落盘失败(不影响本次运行):" + str(exc))
else:
log_debug("自动落盘已关闭(config.SAVE_USER_DATA=False),本次不写 data/"
+ str(int(user_id)) + ".json")
return raw
+43 -7
View File
@@ -38,6 +38,15 @@ LogSetup.py —— 统一日志模块(INFO / DEBUG 双模式)
每行都带 [YYYY-MM-DD HH:MM:SS] 时间戳。
【要不要生成日志文件】
优先级: setup_logging(enabled=...) 显式传参 > config.py 的 LOG_ENABLED > 开
LOG_ENABLED = True # 照常写两个日志文件
LOG_ENABLED = False # 一个字节都不落盘(控制台输出照旧)
单次运行想临时关掉:setup_logging("名字", enabled=False)
【主脚本怎么用】
from api import setup_logging, teardown_logging, ParseQRCode, UserLogin
@@ -101,6 +110,8 @@ _session_started = False
_session_script_name = ""
_current_level = LEVEL_INFO
_value_max = 0
# 是否写日志文件(False = 一个字节都不落盘,控制台照旧)
_enabled = True
_date_log_path: Optional[str] = None
_latest_log_path: Optional[str] = None
@@ -145,6 +156,15 @@ def _config_value_max() -> int:
return 0
def _config_enabled() -> bool:
"""从 config.py 读 LOG_ENABLED;读不到就当 True(默认照常记日志)。"""
try:
import config # type: ignore
return bool(getattr(config, "LOG_ENABLED", True))
except Exception:
return True
def get_level() -> str:
"""返回当前日志模式('info' / 'debug')。"""
return _current_level
@@ -155,6 +175,11 @@ def is_debug() -> bool:
return _LEVEL_RANK.get(_current_level, 20) <= _LEVEL_RANK[LEVEL_DEBUG]
def is_log_enabled() -> bool:
"""当前是否写日志文件(config.LOG_ENABLED / setup_logging(enabled=...))。"""
return bool(_enabled)
def set_level(level: Any) -> str:
"""运行时切换模式(一般不用,改 config.py 即可)。返回切换后的模式。"""
global _current_level
@@ -340,40 +365,49 @@ def get_called_apis() -> list:
# 会话:初始化 / 收尾
# =============================================================================
def setup_logging(script_name: str, level: Any = None) -> str:
def setup_logging(script_name: str, level: Any = None,
enabled: Optional[bool] = None) -> str:
"""
初始化日志会话(主脚本开头调用一次)。
做三件事:
1. 确定日志模式(level 显式传参 > config.LOG_LEVEL > INFO)
2. 打开两个日志文件:日期日志(追加)+ latest.log(覆盖)
(enabled=False 或 config.LOG_ENABLED=False 时一个都不开)
3. 打印会话横幅
参数:
script_name: 脚本名,显示在横幅上
level: 日志模式;None(默认)= 读 config.py 的 LOG_LEVEL
enabled: 是否写日志文件;None(默认)= 读 config.py 的 LOG_ENABLED
False = 不创建、不写任何日志文件(控制台输出照旧)
返回:
实际生效的模式('info' / 'debug')
"""
global _session_started, _session_script_name, _value_max
global _session_started, _session_script_name, _value_max, _enabled
global _date_log_path, _latest_log_path, _date_log_file, _latest_log_file
set_level(level if level is not None else _config_level())
_value_max = _config_value_max()
_enabled = _config_enabled() if enabled is None else bool(enabled)
if _session_started:
return _current_level
_ensure_logs_dir()
_session_script_name = script_name
_date_log_path = _get_date_log_path()
_latest_log_path = _get_latest_log_path()
_called_apis.clear()
_date_log_file = open(_date_log_path, "a", encoding="utf-8") # 追加:当日全部
_latest_log_file = open(_latest_log_path, "w", encoding="utf-8") # 覆盖:仅当次
if _enabled:
_ensure_logs_dir()
_date_log_file = open(_date_log_path, "a", encoding="utf-8") # 追加:当日全部
_latest_log_file = open(_latest_log_path, "w", encoding="utf-8") # 覆盖:仅当次
else:
_date_log_file = None
_latest_log_file = None
_print_banner(script_name)
_session_started = True
@@ -394,8 +428,10 @@ def _print_banner(script_name: str) -> None:
_INDENT * 2 + "工作目录 : " + os.getcwd(),
_INDENT * 2 + "已挂载 api : " + str(len(_tracked_api_names))
+ " 个(自动跟踪,主脚本无需写日志代码)",
_INDENT * 2 + "当次日志 : " + str(_latest_log_path),
_INDENT * 2 + "日期日志 : " + str(_date_log_path),
_INDENT * 2 + "当次日志 : "
+ (str(_latest_log_path) if _enabled else "已关闭(不写日志文件)"),
_INDENT * 2 + "日期日志 : "
+ (str(_date_log_path) if _enabled else "已关闭(config.LOG_ENABLED=False)"),
_SEPARATOR,
]
_emit("\n".join(lines))
+24 -173
View File
@@ -1894,117 +1894,6 @@ def apply_play_effects(
# 十二、组装 upsertUserAll
# =============================================================================
# -----------------------------------------------------------------------------
# ★ 歌曲解锁(解禁):MusicUnlock* 不是独立节点,而是并入 userItemList 的 UserItem
# -----------------------------------------------------------------------------
# 依据 source/Assembly-CSharp/Manager/UserData.cs:132-138 —— 客户端有四个解锁列表:
# MusicUnlockList / MusicUnlockMasterList / MusicUnlockReMasterList / MusicUnlockStrongList
# 它们**没有**对应的 userXxxList 节点,导出时统一并进 userItemList:
# source/Assembly-CSharp/Net.VO.Mai2/VOExtensions.cs:981-1008
# MusicUnlockList -> itemKind = 5
# MusicUnlockMasterList -> itemKind = 6
# MusicUnlockReMasterList -> itemKind = 7
# MusicUnlockStrongList -> itemKind = 8
# 条目形如 {"itemKind":5,"itemId":1085,"stock":1,"isValid":true}
# (真机 data/12570152.json 的 userItemList 里 kind5=77 条、kind6=446 条、kind7=34 条)
#
# ★ 难度解锁的「天生免费」规则:
# source/Assembly-CSharp/Manager/NotesListManager.cs:415-453 IsUnlockMaster
# source/Assembly-CSharp/Manager/NotesListManager.cs:455-494 IsUnlockReMaster
# 两个函数开头都有 `if (id < 10000) return true;`
# -> musicId < 10000(标准谱)的 Master / Re:Master **天生解锁**,不必写 kind6/7;
# 只有 musicId >= 10000(DX 谱)才需要额外解锁。
# ★ 另外 Re:Master 还受活动开关约束(IsUnlockReMaster 里的
# `if (!instance.IsOpenEvent(subEventId)) return false;`),
# 那是机台/服务端侧的开关,脚本改不了 —— 写了 kind7 也可能进游戏仍是灰的。
#
# ★ 写 kind5 只是「把这首歌标记为已解锁」,不携带任何成绩;
# 成绩另由 userMusicDetailList 承载,纯解锁不需要打歌。
#: 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
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 build_user_all(
snapshot: Optional[Any] = None,
play: Optional[PlayData] = None,
@@ -2020,10 +1909,6 @@ def build_user_all(
playlog_id: int = 0,
play_date_time: Optional[int] = None,
extra_data: Optional[Any] = None,
unlock_music_ids: Optional[Sequence[int]] = None,
unlock_master: bool = True,
unlock_remaster: bool = True,
unlock_base: bool = True,
) -> Dict[str, Any]:
"""
组装 upsertUserAll 的 36 个节点。
@@ -2045,15 +1930,15 @@ def build_user_all(
用于 lastPlayDate / userGamePlaylogList.playDate。
不传则退回 login_date_time。
playlog_id: UserLoginApi 的 loginId(用于 userGamePlaylogList)
extra_data: ★ 额外 JSON(dict / JSON 字符串 / 文件路径),
自动匹配插入 36 节点,**优先级高于 patch**。见 merge_extra_data。
unlock_music_ids: ★ 要解锁(解禁)的 musicId 列表。见 build_unlock_items。
写进 userItemList:kind5=歌曲本体、kind6=Master、kind7=Re:Master。
unlock_master: 解锁时是否一并解禁 Master(仅 DX 谱 musicId >= 10000 生效)
unlock_remaster: 解锁时是否一并解禁 Re:Master(同上)
unlock_base: False = **不解锁歌曲本体**(不写 kind5),只解禁难度。
注意:歌曲本体没解锁时,游戏里可能连谱面都进不去,
所以这个开关是「只补难度」的场景用的。
extra_data: ★ 额外 JSON,自动匹配到 36 节点并**整体覆盖**,
**优先级高于 patch**。见 merge_extra_data。支持四种形态:
dict 直接合并
JSON 字符串 json.loads 后合并
文件路径(.json / .txt) 读文件后合并
callable(snapshot, user_all) -> dict
★ 需要「按服务器现状现算」时用(例如只插入还不存在的
条目):拿到**归一化后的快照**(dict,键=节点名)与
当前已组装好的 user_all 后再产出要覆盖的节点字典。
返回:
36 节点的 dict
@@ -2157,39 +2042,19 @@ def build_user_all(
user_all[node] = coerce_node_value(node, value)
# ---- extra_data 覆盖(★ 最高优先级)----
if load_extra_data(extra_data):
for note in merge_extra_data(user_all, extra_data):
# ★ 这是「附加功能」的唯一入口:本函数只负责组装**基础包体**,
# 任何额外内容(解锁歌曲、点灯、自定义节点…)都由调用方通过 extra_data 传入,
# 这里自动匹配到 36 节点并整体覆盖,不需要改本文件。
_extra = extra_data
if callable(_extra):
# 允许按快照现算:callable(snapshot, user_all) -> dict
_extra = _extra(base, user_all)
log_debug("extra_data 由 callable 现算,产出 "
+ str(len(_extra or {})) + " 个节点")
if load_extra_data(_extra):
for note in merge_extra_data(user_all, _extra):
log_info(note)
# ---- ★ 歌曲解锁(解禁)----
# 放在 extra_data 之后:extra_data 可能整体替换了 userItemList,
# 解锁条目追加到最终列表末尾,位串补 "1"(= 服务端侧新增该 item)。
# 依据见本文件「歌曲解锁」注释块。
if unlock_music_ids:
unlock_items, unlock_notes = build_unlock_items(
unlock_music_ids,
existing=user_all.get("userItemList") or [],
master=unlock_master,
remaster=unlock_remaster,
unlock_base=unlock_base,
)
for note in unlock_notes:
log_info(note)
if unlock_items:
old_items = list(user_all.get("userItemList") or [])
old_bits = user_all.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)]
user_all["userItemList"] = old_items + unlock_items
user_all["isNewItemList"] = old_bits + "1" * len(unlock_items)
log_info("★ 本次解锁共新增 " + str(len(unlock_items))
+ " 个 userItem 条目(位串补 " + "1" * len(unlock_items) + ")")
else:
log_info("解锁检查:指定的歌曲/难度在服务器上都已经解锁,无需改动")
# ---- 清理内部字段 ----
for key in list(user_all.keys()):
if key.startswith("_"):
@@ -2629,10 +2494,6 @@ def UpsertUserAll(
auto_characters: bool = True,
play: Optional[PlayData] = None,
extra_data: Optional[Any] = None,
unlock_music_ids: Optional[Sequence[int]] = None,
unlock_master: bool = True,
unlock_remaster: bool = True,
unlock_base: bool = True,
patch: Optional[Dict[str, Any]] = None,
user_playlog_list: Optional[List[Any]] = None,
pre_new_item_list: bool = True,
@@ -2682,21 +2543,14 @@ def UpsertUserAll(
userCharacterList 推出本局 5 只角色(**游玩前**等级)。
这样 PLAY_CHARACTERS(现在 selftest.py 里) 过期也不影响。
play: 本局数据(可选,默认按 config.PLAY_*)
extra_data: ★ 额外 JSON,自动匹配插入 upsertUserAll 的 36 个节点。
接受 dict / JSON 字符串 / JSON 文件路径,例如:
extra_data: ★ 额外 JSON,自动匹配到 upsertUserAll 的 36 个节点并覆盖。
接受 dict / JSON 字符串 / JSON 文件路径 /
callable(snapshot, user_all) -> dict,例如:
extra_data={"userKaleidxScopeList": [{...}],
"isNewKaleidxScopeList": "1"}
优先级最高(覆盖快照演算出的同名字段)。
没给位串时会按数组长度补 "0" 并给出提示。
unlock_music_ids: ★ 要解锁(解禁)的 musicId 列表,例如 [1085, 11414]。
写进 userItemList:kind5=歌曲本体、kind6=Master、kind7=Re:Master。
★ musicId < 10000(标准谱)的 Master/Re:Master 天生解锁,
只写 kind5;只有 DX 谱(>= 10000)才写 kind6/7。
★ 已存在的条目自动跳过(重复插入服务端会报错)。
见 build_unlock_items 上方的源码依据。
unlock_master: 解锁时是否一并解禁 Master 难度(默认 True)
unlock_remaster: 解锁时是否一并解禁 Re:Master 难度(默认 True)
unlock_base: False = 只解禁难度,**不解锁歌曲本体**(不写 kind5)
★ 本接口只产「基础包体」,所有附加功能都走这个入口。
patch: 同 extra_data 的旧接口(只收 dict,不补位串提示)。
user_playlog_list: 本局成绩明细(可选;不传则用 play 自动构造一条)
pre_new_item_list: True(默认)= 发包前先调 GetUserNewItemListApi
@@ -2788,9 +2642,6 @@ def UpsertUserAll(
# ---------- 阶段 5:组装 upsertUserAll(快照基线 + 本局演算 + 差分)----------
user_all = build_user_all(
snapshot=snapshot, play=p, patch=patch, extra_data=extra_data,
unlock_music_ids=unlock_music_ids,
unlock_master=unlock_master, unlock_remaster=unlock_remaster,
unlock_base=unlock_base,
login_date_time=login_date_time, auth_date_time=auth_date_time,
place_id=place_id, place_name=place_name,
region_id=region_id, region_name=region_name, client_id=client_id,
+6 -15
View File
@@ -34,7 +34,7 @@ api 包 —— 统一导出
UserLogout.py UserLogoutApi(登出)
上传 / 结算(有副作用的接口)
UpsertUserAll.py ★ UpsertUserAllApi(上传成绩 + 解锁歌曲/解禁难度)
UpsertUserAll.py ★ UpsertUserAllApi(上传成绩;附加内容一律走 extra_data)
UpsertUserChargelog.py UpsertUserChargelogApi(购买功能票)
GetNeedUserData.py ★ 结算快照编排(统一调用下面的取数脚本),
并把结果落盘到 <工程根>/data/<userId>.json
@@ -84,6 +84,7 @@ from .LogSetup import (
get_level,
set_level,
is_debug,
is_log_enabled,
LEVEL_INFO,
LEVEL_DEBUG,
# 装饰器 / 兼容
@@ -237,13 +238,6 @@ from .UpsertUserAll import (
load_extra_data,
merge_extra_data,
verify_upsert_landing,
# ★ 歌曲解锁(解禁):写进 userItemList 的 itemKind 5/6/7
build_unlock_items,
ITEM_KIND_MUSIC_UNLOCK,
ITEM_KIND_MUSIC_UNLOCK_MASTER,
ITEM_KIND_MUSIC_UNLOCK_REMASTER,
ITEM_KIND_MUSIC_UNLOCK_STRONG,
UNLOCK_MASTER_MIN_MUSIC_ID,
default_user_weekly_data,
default_user_2p_playlog,
calc_play_special,
@@ -273,6 +267,7 @@ from .GetNeedUserData import (
PROJECT_ROOT,
DATA_DIR,
user_data_path,
config_save_default,
save_user_data,
load_user_data,
list_saved_user_ids,
@@ -393,7 +388,6 @@ _API_FUNCS = (
"merge_extra_data",
"verify_upsert_landing",
"build_user_all",
"build_unlock_items",
# --- 购买功能票 ---
"UpsertUserChargelog",
"ticket_name",
@@ -467,7 +461,8 @@ __all__ = [
# ---- 日志:自动跟踪 ----
"autowrap", "get_called_apis",
# ---- 日志:模式 ----
"get_level", "set_level", "is_debug", "LEVEL_INFO", "LEVEL_DEBUG",
"get_level", "set_level", "is_debug", "is_log_enabled",
"LEVEL_INFO", "LEVEL_DEBUG",
# ---- 日志:装饰器 / 兼容 ----
"api_log", "get_logger",
# ---- 日志:流程 ----
@@ -496,10 +491,6 @@ __all__ = [
# ---- 上传成绩 ----
"UpsertUserAll", "PlayData", "build_play_from_config", "derive_play_characters",
"load_extra_data", "merge_extra_data", "verify_upsert_landing",
# ---- 歌曲解锁(解禁)----
"build_unlock_items", "UNLOCK_MASTER_MIN_MUSIC_ID",
"ITEM_KIND_MUSIC_UNLOCK", "ITEM_KIND_MUSIC_UNLOCK_MASTER",
"ITEM_KIND_MUSIC_UNLOCK_REMASTER", "ITEM_KIND_MUSIC_UNLOCK_STRONG",
# ---- 购买功能票 ----
"UpsertUserChargelog", "ChargelogConfirmError", "ChargelogGuardError",
# ---- 买票前置闸门(GetUserCharge 必须先跑过)----
@@ -525,7 +516,7 @@ __all__ = [
# ---- 快照编排 ----
"GetNeedUserData", "save_snapshot", "load_snapshot",
"summarize_snapshot", "DEFAULT_SNAPSHOT_NODES",
"PROJECT_ROOT", "DATA_DIR", "user_data_path",
"PROJECT_ROOT", "DATA_DIR", "user_data_path", "config_save_default",
"save_user_data", "load_user_data", "list_saved_user_ids",
# ---- 取数公共底座 ----
"GetterEmptyRequestVO", "GetterUserIdRequestVO", "UserIdPageRequestVO",