diff --git a/backend/core/accounts.py b/backend/core/accounts.py index 71dbad3..e618093 100644 --- a/backend/core/accounts.py +++ b/backend/core/accounts.py @@ -6,9 +6,7 @@ import io import json import os -import shutil import threading -import time from . import settings, tasks, updater from . import atomicio, paradox @@ -416,18 +414,9 @@ def go(): return tid -def remove_account(file: str, backup=True): +def remove_account(file: str): path = os.path.join(_accounts_dir(), os.path.basename(file)) if not os.path.isfile(path): raise FileNotFoundError(file) - if backup: - bak_dir = os.path.join(os.path.dirname(path), '_removed') - os.makedirs(bak_dir, exist_ok=True) - # 备份名带时间戳:同名新账号再次删除时 move 目标已存在会退化成 - # 覆盖,旧备份被顶掉(#61) - dst = os.path.join(bak_dir, '%s.%s' % ( - os.path.basename(path), time.strftime('%Y%m%d-%H%M%S'))) - shutil.move(path, dst) - else: - os.remove(path) + os.remove(path) return True diff --git a/backend/core/applog.py b/backend/core/applog.py new file mode 100644 index 0000000..e1370d5 --- /dev/null +++ b/backend/core/applog.py @@ -0,0 +1,38 @@ +# -*- coding: utf-8 -*- +"""debug/app.log 的 core 侧写入端。 + +main.log() 一直能写这个文件,但 core 模块不能 import main(main → core +单向,见 appupdate 的退出注册),于是同步 / 签到 / 抽卡这些后台链路出 +错时只有界面任务日志(内存态,重启即没),app.log 里什么都看不到—— +排障经常拿不到现场。本模块给 core 一个独立的文件写入端:与 main.log +写同一个目标,时间戳前缀、2MB 轮转一致。写失败静默:日志不能拖垮业务。 +""" +from __future__ import annotations + +import os +import threading +import time + +from . import settings + +_lock = threading.Lock() +_MAX_LINE = 4000 # 单行上限:响应体再长也截,防止一条日志撑爆轮转 + + +def write(line: str): + """已带时间戳的原始行落盘(main.log 复用同一实现,避免双写端轮转竞争)。""" + try: + with _lock: + path = settings.LOG_PATH + os.makedirs(os.path.dirname(path), exist_ok=True) + if os.path.isfile(path) and os.path.getsize(path) > 2 * 1024 * 1024: + os.replace(path, path + '.1') + with open(path, 'a', encoding='utf-8') as f: + f.write(str(line).rstrip('\n')[:_MAX_LINE] + '\n') + except Exception: + pass + + +def log(msg: str): + """带时间戳写一行(core 模块用这个)。""" + write('[%s] %s' % (time.strftime('%H:%M:%S'), msg)) diff --git a/backend/core/copilot.py b/backend/core/copilot.py index a4e875c..4a8b2fa 100644 --- a/backend/core/copilot.py +++ b/backend/core/copilot.py @@ -21,7 +21,8 @@ import urllib.request from concurrent.futures import ThreadPoolExecutor -from . import resources, settings +from . import applog, resources, settings +from .net import err_body API = 'https://prts.maa.plus/copilot' UA = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) MAA-PRTS/1.0'} @@ -135,6 +136,13 @@ def _http_json(url, timeout=40, retries=3): req = urllib.request.Request(url, headers=UA) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode('utf-8')) + except urllib.error.HTTPError as e: + # 4xx/5xx 不重试;响应体落 app.log 再抛——搜索/预下载报障时 + # 作业站返回的 code/message 是第一现场 + u = urllib.parse.urlsplit(url) + applog.log('[作业站] HTTP %s GET %s %s' % ( + e.code, u.netloc + u.path, err_body(e) or '(无响应体)')) + raise except (urllib.error.URLError, TimeoutError, OSError) as e: last = e if i == retries - 1: diff --git a/backend/core/gacha.py b/backend/core/gacha.py index b479208..10ac853 100644 --- a/backend/core/gacha.py +++ b/backend/core/gacha.py @@ -33,7 +33,8 @@ import urllib.parse import urllib.request -from . import atomicio, settings, tasks +from . import applog, atomicio, settings, tasks +from .net import err_body # 通行证 appCode:明日方舟与终末地共用同一个(写 'endfield' 会 400: # appCode 校验要求十六进制) @@ -87,8 +88,15 @@ def _http(method, url, data=None, headers=None, timeout=25, retries=3): method=method or ('POST' if body else 'GET')) with urllib.request.urlopen(req, timeout=timeout) as r: return json.loads(r.read().decode('utf-8')), r.headers - except urllib.error.HTTPError: - raise # 4xx/5xx 是明确的业务/接口错误,重试无意义 + except urllib.error.HTTPError as e: + # 4xx/5xx 是明确的业务/接口错误,重试无意义;但响应体(code/msg) + # 是排障关键,先落 app.log 再抛。抽卡记录 URL 的 query 带 authkey, + # 只记 host+path + u = urllib.parse.urlsplit(url) + applog.log('[抽卡] HTTP %s %s %s %s' % ( + e.code, method or ('POST' if body is not None else 'GET'), + u.netloc + u.path, err_body(e) or '(无响应体)')) + raise except (urllib.error.URLError, OSError, ValueError) as e: last = e if attempt >= retries: diff --git a/backend/core/net.py b/backend/core/net.py index 7f79d11..5d48c49 100644 --- a/backend/core/net.py +++ b/backend/core/net.py @@ -17,6 +17,7 @@ """ from __future__ import annotations +import gzip import http.client import socket import time @@ -26,6 +27,19 @@ from . import settings +def err_body(e, limit=4000) -> str: + """HTTPError 响应体摘要(通用工具,不走代理,谁都能用):4xx/5xx 的 + JSON code/message 是排障关键。gzip 错误页解压后再截;响应体到这里就 + 被读掉了,调用方别再 e.read()。""" + try: + raw = e.read() or b'' + if raw[:2] == b'\x1f\x8b': # 网关偶发无视 Accept-Encoding 仍压 gzip + raw = gzip.decompress(raw) + return ' '.join(raw.decode('utf-8', 'replace').split())[:limit] + except Exception: + return '' + + class _NoRedirect(urllib.request.HTTPRedirectHandler): """appupdate 要读 302 的 Location(releases/latest → tag),不能跟""" diff --git a/backend/core/skland.py b/backend/core/skland.py index 2afa5ba..94bd0c3 100644 --- a/backend/core/skland.py +++ b/backend/core/skland.py @@ -22,6 +22,9 @@ import urllib.parse import urllib.request +from . import applog +from .net import err_body + APP_CODE = '4ca99fa6b56cc2ba' GRANT_URL = 'https://as.hypergryph.com/user/oauth2/v2/grant' CRED_URL = 'https://zonai.skland.com/api/v1/user/auth/generate_cred_by_code' @@ -117,11 +120,19 @@ def _http(method, url, headers, body=None, timeout=30, retries=3, note=None): return json.loads(raw.decode('utf-8')) except urllib.error.HTTPError as e: last = e + full = err_body(e, limit=4000) # app.log 记完整响应体 + body = full[:200] # 界面任务日志维持 200 字摘要不变 + u = urllib.parse.urlsplit(url) # 只记 host+path:query 可能带 uid 等账号参数 + applog.log('[森空岛] HTTP %s %s %s %s' % ( + e.code, method, u.netloc + u.path, full or '(无响应体)')) # 401/403 只有「headers 是函数」的可重签名请求才值得重试(时间戳 # 过期);登录链的死 token 重试三次只是浪费 if e.code not in (401, 403) or not callable(headers) or attempt >= retries: + if body: + (note or _note)(' [HTTP %s] %s' % (e.code, body)) raise - (note or _note)(' [签名重试 %d/%d] HTTP %s' % (attempt, retries - 1, e.code)) + (note or _note)(' [签名重试 %d/%d] HTTP %s%s' + % (attempt, retries - 1, e.code, ' ' + body if body else '')) time.sleep(1.0 * attempt) except (urllib.error.URLError, socket.timeout, TimeoutError, ConnectionError, OSError) as e: diff --git a/backend/core/tasks.py b/backend/core/tasks.py index 788f452..360ccf9 100644 --- a/backend/core/tasks.py +++ b/backend/core/tasks.py @@ -7,6 +7,8 @@ import traceback import uuid +from . import applog + _tasks = {} _lock = threading.Lock() _keep = 40 @@ -46,10 +48,19 @@ def finish(tid, result=None, error=None): t = _tasks.get(tid) if not t: return + was_running = t['status'] == 'running' t['status'] = 'error' if error else 'done' t['result'] = result t['error'] = error t['endedAt'] = time.time() + if error and was_running: + # 失败任务此前只存在于内存(前端还能看,重启即没)。摘要 + traceback + # 落一份到 debug/app.log,排障才有现场——文件 IO 放锁外,别卡任务队列 + tb = '' + if isinstance(result, dict): + tb = (result.get('traceback') or '').strip() + applog.log(('[任务失败] %s:%s' % (t['title'], error)) + + (('\n' + tb) if tb else '')) def log(tid, line: str): diff --git a/backend/main.py b/backend/main.py index 6645b65..2824e34 100644 --- a/backend/main.py +++ b/backend/main.py @@ -21,7 +21,7 @@ if HERE not in sys.path: sys.path.insert(0, HERE) -from core import accounts, api, appupdate, settings, tasks, version # noqa: E402 +from core import accounts, api, applog, appupdate, settings, tasks, version # noqa: E402 WEB = settings.static_dir() LOG_PATH = settings.LOG_PATH @@ -38,14 +38,7 @@ def log(msg): print(line, flush=True) except Exception: pass - try: - os.makedirs(os.path.dirname(LOG_PATH), exist_ok=True) - if os.path.isfile(LOG_PATH) and os.path.getsize(LOG_PATH) > 2 * 1024 * 1024: - os.replace(LOG_PATH, LOG_PATH + '.1') - with open(LOG_PATH, 'a', encoding='utf-8') as f: - f.write(line + '\n') - except Exception: - pass + applog.write(line) # 落盘/轮转统一走 core.applog,两个独立写端会竞争轮转 # ---------------------------------------------------------------- 解除网络锁定 diff --git a/docs/backend.md b/docs/backend.md index 28aba4e..44981ef 100644 --- a/docs/backend.md +++ b/docs/backend.md @@ -72,7 +72,7 @@ main() | GET | `/api/accounts` | 账号列表(含每个账号的统计摘要) | | GET | `/api/account?file=` | 单个账号完整配置:account / stats / missing / chars | | POST | `/api/account/maa` | 把 `maa.profile` 等用户字段写回账号 JSON(同步不覆盖的那几个) | -| POST | `/api/account/remove` | 删除账号:不真删,移入 `config/_removed/` 备份。**预留,无界面入口** | +| POST | `/api/account/remove` | 删除账号:直接删除账号 JSON,不备份不可恢复。账号列表卡片悬停 ✕ 触发,前端有二次确认 | | POST | `/api/account/refresh` | 同步账号。带 `token` 同步单个(密文写进账号文件 `skd` 段);不带则按各账号文件 ∪ 旧 `tokens.json` 全部同步。返回 `taskId` | | POST | `/api/account/import-maa` | 从账号绑定的 MAA 目录读干员识别结果(`done=false` 残缺名单拒绝),覆盖练度/统计/缺卡(账号信息与 `skd` 保留),同步任务直接返回摘要 | | POST | `/api/account/create-from-maa` | 不用森空岛 token:用 `dir` 指定 MAA 目录的干员识别结果直接建本地账号(合成 uid、昵称取备注或目录名、无 `skd` 段、重名顺延 (2)(3)),返回建号摘要 | diff --git a/frontend/app.js b/frontend/app.js index 4a5e166..90f5122 100644 --- a/frontend/app.js +++ b/frontend/app.js @@ -282,6 +282,7 @@ function renderAccounts() { ${esc(a.nickName)}${ef ? '终末地' : ''} ${sub} + ✕ `; }).join(''); } @@ -311,6 +312,9 @@ function bindAccountOrder(box) { }; box.addEventListener('click', e => { + // 删除 ✕ 先于选号拦截:点的是卡片里的 ✕ 就不该再把账号切成选中 + const del = e.target.closest('.acct-del'); + if (del) { deleteAccount(del.dataset.file); return; } const b = e.target.closest('.acct'); if (b) selectAccount(b.dataset.file); }); @@ -341,6 +345,50 @@ function bindAccountOrder(box) { }); } +/* 删除账号:卡片 hover 出 ✕,点后二次确认。删就是删——账号文件直接 + 删除,不留备份(要找回只能重新同步)。 */ +async function deleteAccount(file) { + const a = S.accounts.find(x => x.file === file); + if (!a) return; + const game = gameOf(a); + const wasCurrent = S.current === file; + modal(` +