Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
428 changes: 428 additions & 0 deletions backend/cli.py

Large diffs are not rendered by default.

80 changes: 73 additions & 7 deletions backend/core/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import threading

from . import settings, tasks, updater
from . import atomicio, paradox
from . import atomicio, paradox, progress

ELITE_CN = {0: '精零', 1: '精一', 2: '精二'}

Expand All @@ -32,6 +32,11 @@ def _load(path):
return None


def _dict(v):
"""取子段:不是 dict(字符串/数组/null)一律当空对象,别让 `or {}` 骗过去"""
return v if isinstance(v, dict) else {}


def list_accounts():
out = []
d = _accounts_dir()
Expand All @@ -43,9 +48,16 @@ def list_accounts():
if name in updater.NON_ACCOUNT_JSON: # 同层的全局文件,不是账号
continue
snap = _load(os.path.join(d, name))
if not snap or not (snap.get('account') or {}).get('uid'):
# account 段必须真的是对象:config/ 下还有我们自己的全局文件
# (train-plan.json 的 account 是**文件名字符串**),`or {}` 挡不住
# 字符串,.get 直接把整个账号列表炸掉——所有 skill 一起挂
# (2026-11-19 01:24 用户实测:培养暂停落盘 train-plan.json 之后,
# 连「开始唤醒」「自动战斗」都报 'str' object has no attribute 'get')
a = snap.get('account') if snap else None
if not isinstance(a, dict) or not a.get('uid'):
continue
a, s = snap.get('account') or {}, snap.get('stats') or {}
s = snap.get('stats')
s = s if isinstance(s, dict) else {}
out.append({
'file': name,
'uid': str(a.get('uid')),
Expand All @@ -57,11 +69,18 @@ def list_accounts():
'serverId': a.get('serverId') or '', # 终末地签到要 gameId_roleId_serverId 三件套
'level': a.get('level'),
# 有没有可用的森空岛 token:抽卡统计/签到都要它,MAA 导入的账号没有
'hasToken': bool((snap.get('skd') or {}).get('data')),
'hasToken': bool(_dict(snap.get('skd')).get('data')),
'secretary': a.get('secretary') or {},
'maaProfile': (snap.get('maa') or {}).get('profile') or '',
'maaDir': (snap.get('maa') or {}).get('dir') or '',
'syncedAt': (snap.get('sync') or {}).get('syncedAt'),
'maaProfile': _dict(snap.get('maa')).get('profile') or '',
# MAA 切号名:官服是手机号掩码(181****5505),B 服是游戏内用户名。
# 存下来就不用每次挂机都问一遍——这是唯一必须问用户的字段,
# 猜错的表现是切号死循环(MAA 找不到账号名,重试到超时)。
'maaAccountName': _dict(snap.get('maa')).get('accountName') or '',
'maaDir': _dict(snap.get('maa')).get('dir') or '',
'syncedAt': _dict(snap.get('sync')).get('syncedAt'),
# 关卡进度摘要(主线还差几关、活动几个区、剿灭几张没满);
# 明细在 account_detail 里,列表页只放这几个数字
'progress': progress.summary(snap.get('progress')),
'stats': {
'charCount': s.get('charCount'),
'charTotal': s.get('charTotal'),
Expand Down Expand Up @@ -126,6 +145,9 @@ def account_detail(file: str) -> dict:
'maa': snap.get('maa') or {},
'sync': snap.get('sync') or {},
'paradox': paradox.plan(snap)['stats'],
# 完整关卡进度(主线明细、活动 zone、剿灭每张图):给「还差哪几关」
# 这类界面和后面的助手工具用
'progress': snap.get('progress') or {},
}


Expand Down Expand Up @@ -328,6 +350,50 @@ def token_for(file: str) -> str:
return ''


def token_state(file: str) -> dict:
"""设置页「账号管理」用:这个账号的 token 到底有没有、能不能解

与 :func:`token_for` 的区别是**分得清三种状态**:没存过 / 存了但解不开
(换电脑、换 Windows 用户)/ 解开了。界面要按这三种给不同的话术,
「没 token」和「token 坏了」混成一句会让人以为重新登录一遍就行——
前者要粘 token,后者才是重新登录。
"""
try:
snap = get_account(file)
except Exception as e:
return {'has': False, 'token': '', 'broken': False, 'error': str(e)}
skd = snap.get('skd') or {}
if not isinstance(skd, dict) or not skd.get('data'):
return {'has': False, 'token': '', 'broken': False, 'error': ''}
try:
token = vault.unprotect(base64.b64decode(skd.get('data'))).decode('utf-8')
except Exception:
return {'has': True, 'token': '', 'broken': True,
'error': '本机解不开这份密文(换电脑 / 换 Windows 用户后会这样),重新粘贴一次 token 即可'}
return {'has': True, 'token': token, 'broken': False, 'error': ''}


def set_token(file: str, token: str) -> dict:
"""把新的森空岛 token 加密写进账号文件(token 失效后重新粘贴用)

只动 ``skd`` 段,练度 / 进度 / MAA 绑定一律原样保留——用户是来换凭证的,
不是来重新同步账号的。调用方负责先验 token 与 uid 是否对得上。
"""
token = (token or '').strip()
if not token:
raise ValueError('token 不能为空')
data = base64.b64encode(vault.protect(token.encode('utf-8'))).decode('ascii')
meta = {'alias': '', 'addedAt': updater.now_iso(), 'data': data}

def mut(snap):
old = snap.get('skd') if isinstance(snap.get('skd'), dict) else {}
meta['alias'] = old.get('alias') or ''
snap['skd'] = dict(meta)

update(file, mut)
return meta


# 启动自检把读不开的条目原因存这里,main 起来后写进 app.log
TOKENS_WARNING = ''
# load_tokens 每次重算:单条解密失败被跳过的受影响文件列表
Expand Down
152 changes: 152 additions & 0 deletions backend/core/acctname.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
r"""切号名(MAA 的 AccountName)的归一化与校验

为什么单独一个模块
------------------
同一件事有三个调用方:agent 的 build_run、multiacct 的多账号编排、maaplan
写档案。之前 agent 那边自己写了一份 ``^\d{3}\*{4}\d{4}$`` 的严格校验,
而 MAA 实际是**子串匹配**:官方说明里明写「可输入 123****4567、4567 或
23****45」三种。用户照 MAA 的说明只给了后四位,我们判成非法 → 助手只能
反复追问 → 任务出不来。规则只放在这里,谁都别再自己写一份。

MAA 到底怎么比
--------------
StartUp 任务的切号是拿 ``AccountName`` 去和登录界面 OCR 出来的那行做
**包含**比较,所以下面三种都认(官方说明原话):

- 纯尾号 ``5505`` —— **首选**。问用户只要后四位,基本不会撞号
- 部分掩码 ``23****45``
- 完整掩码 ``181****5505``

用户手里往往只有一个片段。**能补全的补成完整掩码,补不全的原样保留**,
别拿"格式不对"去卡他——格式错是我们的活,不是他的。

对话里一律问「手机号后 4 位」,别让用户去拼 ``****``:拼错的是他,报错的是我们。
"""
from __future__ import annotations

import re
import unicodedata

# 各种「星号」:全角、数学、装饰符都当打码段。用户从记事本、微信里复制
# 出来的经常是这些变体,NFKC 只转得了全角那一个。
_STARS = '**✱✳﹡∗×✕✖╳•·●○■□'
_ZERO_WIDTH = '\u200b\u200c\u200d\u2060\ufeff'
# 数字之间的分隔符:空格、横线、点、括号、斜杠……用户爱怎么打怎么打
_SEPS = ' \t\r\n\u3000--—_.,,、/\\|::;;()()[]【】<>《》"\'`'

_DIGITS = re.compile(r'\D')


def is_official_channel(channel) -> bool:
"""是不是官服。渠道缺失时按官服算(默认值,最保守)

空渠道当官服:官服的账号名是打码手机号,校验严一点最多是"多问一句";
反过来把官服当 B 服放过去,就是切号死循环 4 分钟——两头代价不对等。
"""
c = str(channel or '')
if not c:
return True
low = c.lower()
if '官服' in c or 'official' in low:
return True
# MAA 支持的四类里,其余三类都不是手机号(B 服/繁中/韩服是用户名或邮箱)
for k in ('bilibili', 'b服', '繁中', '韩', '国际', '日服', '台服', '美服'):
if k in low:
return False
return True


def _mask(digits: str, head: int, tail: int) -> str:
return '%s****%s' % (digits[:head], digits[-tail:])


def normalize(v) -> str:
"""把用户给的切号名整理成 MAA 认的写法

能吃下的写法(结果都是 ``181****5505``):

- ``1815505``(前 3 + 后 4,最常见)
- ``18112345505``(完整手机号)
- ``181****5505`` / ``181*5505`` / ``181*5505`` / ``181***5505``
- ``181 5505`` / ``181-5505`` / ``181_5505`` / ``(181)5505``
- ``18123****45505`` 这种整号打码的(前后段都超长,只留前 3 后 4)

B 服用户名、昵称原样返回(只做去空白、统一星号)。
"""
s = str(v or '')
for ch in _ZERO_WIDTH:
s = s.replace(ch, '')
s = unicodedata.normalize('NFKC', s).strip().strip('"\'`“”‘’ ')
if not s:
return ''
# 星号先统一,否则下面按分隔符切的时候会被当成普通字符
# 只换字符、不合并连续星号:181****5505 的 4 个星是有意义的
# (re.sub 带 + 会压成 1 个,后面的位数判断就全乱了)
s = ''.join('*' if ch in _STARS else ch for ch in s)
body = s
for ch in _SEPS:
body = body.replace(ch, '')
if not body:
return ''

star = '*' in body
digits = _DIGITS.sub('', body)

if star:
# 打码段:只认「纯数字 + 星号」的组合,其余(昵称里带 *)不动
if digits and re.fullmatch(r'[\d*]+', body):
m = re.fullmatch(r'(\d+)\*+(\d+)', body)
if m:
head, tail = m.group(1), m.group(2)
# 前后段加起来就是手机号长度:取前 3 后 4,中间一律 4 个星
if len(head) + len(tail) >= 7:
if len(head) >= 3 and len(tail) >= 4:
return _mask(head + tail, 3, 4)
# 23****45 这种只有 4 位有效数字的,原样保留前后段
return '%s****%s' % (head, tail)
return body
return body

if not digits:
return body
if not re.fullmatch(r'[\d*]+', body):
# 数字和字母混着 → B 服用户名(灰bao#7986),不碰
return body
if len(digits) == 11 and digits.startswith('1'):
return _mask(digits, 3, 4) # 完整手机号
if len(digits) == 7:
return _mask(digits, 3, 4) # 前 3 后 4
# 3~10 位的片段原样给 MAA 做子串匹配(本机档案里就有 '136' / '3635')
return digits if 3 <= len(digits) <= 10 else body


def looks_official(nm) -> bool:
"""长得像不像官服的切号名:只有数字和星号,且至少 3 位数字

这样 ``5505`` / ``136`` / ``23****45`` / ``181****5505`` 都算,昵称
「小卡拉帕鲁灰」不算——官服拿昵称去匹配就是死循环几十次然后切号失败。

3 位也放行的依据:本机 MAA 里用户自己那几份档案写的就是 ``136`` /
``165``(纯数字片段,AccountSwitchEnabled=true),一直能切。
"""
s = str(nm or '')
if not s or not re.fullmatch(r'[\d*]+', s):
return False
return len(_DIGITS.sub('', s)) >= 3


def check(nm, channel=None):
"""校验并归一化;给不出可用的值就返回 ``(None, 原因)``

这层只拦真正跑不起来的东西(空、官服填了昵称)。格式一律先归一再判,
绝不把「星号数量不对」这类问题丢回给用户。
"""
raw = str(nm or '').strip()
s = normalize(raw)
if not s:
return None, '没填'
if is_official_channel(channel) and not looks_official(s):
return None, ('官服切号名要用手机号(给后 4 位就行,如 5505);'
'「%s」不是手机号,像昵称,对不上官服账号列表' % raw)
return s, ''
Loading