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
15 changes: 2 additions & 13 deletions backend/core/accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
38 changes: 38 additions & 0 deletions backend/core/applog.py
Original file line number Diff line number Diff line change
@@ -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))
10 changes: 9 additions & 1 deletion backend/core/copilot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'}
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 11 additions & 3 deletions backend/core/gacha.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 校验要求十六进制)
Expand Down Expand Up @@ -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:
Expand Down
14 changes: 14 additions & 0 deletions backend/core/net.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"""
from __future__ import annotations

import gzip
import http.client
import socket
import time
Expand All @@ -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),不能跟"""

Expand Down
13 changes: 12 additions & 1 deletion backend/core/skland.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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:
Expand Down
11 changes: 11 additions & 0 deletions backend/core/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import traceback
import uuid

from . import applog

_tasks = {}
_lock = threading.Lock()
_keep = 40
Expand Down Expand Up @@ -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):
Expand Down
11 changes: 2 additions & 9 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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,两个独立写端会竞争轮转


# ---------------------------------------------------------------- 解除网络锁定
Expand Down
2 changes: 1 addition & 1 deletion docs/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)),返回建号摘要 |
Expand Down
59 changes: 58 additions & 1 deletion frontend/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ function renderAccounts() {
<span class="acct-name">${esc(a.nickName)}${ef ? '<i class="acct-tag">终末地</i>' : ''}</span>
<span class="acct-sub">${sub}</span>
</span>
<span class="acct-del" data-file="${esc(a.file)}" role="button" title="删除这个账号">✕</span>
</button>`;
}).join('');
}
Expand Down Expand Up @@ -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);
});
Expand Down Expand Up @@ -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(`
<h3>删除账号</h3>
<div class="sub">确定删除「${esc(a.nickName || file)}」?删除后不可恢复,练度数据需要重新同步。</div>
<div class="modal-foot">
<button class="btn-plain" data-close>取消</button>
<button class="btn-solid" id="acct-del-yes">删除</button>
</div>`, {
onMount(el, close) {
$('#acct-del-yes', el).addEventListener('click', async () => {
const yes = $('#acct-del-yes', el);
yes.disabled = true;
try {
await api('/api/account/remove', { file });
close();
const acc = await api('/api/accounts');
S.accounts = acc.accounts;
if (wasCurrent) {
// 换到同栏剩下的第一个;同栏空了就另一栏;全空清掉选中
const next = (S.accounts.find(x => gameOf(x) === game) || S.accounts[0] || {}).file || '';
if (next) await selectAccount(next, true);
else {
S.current = ''; S.detail = null; S.sideGame = 'arknights';
renderHero();
applyModuleAvailability();
}
}
renderAccounts();
toast(`已删除「${a.nickName || file}」`);
} catch (e) {
yes.disabled = false;
toast('删除失败:' + e.message, 'err', 5000);
}
});
}
});
}

/* 切号请求的代数:快速连点 A→B 时两个请求并发,晚归的旧响应不能
覆盖新选择(详情串台:头像/统计是 A 的、高亮在 B 上) */
let _selectSeq = 0;
Expand Down Expand Up @@ -408,7 +456,16 @@ function renderHero() {
algoSel.disabled = !d || ef;
if (d) algoSel.value = d.preferAlgo || 'rating';
}
if (!d) return;
if (!d) {
// 没有选中账号(删光了):回到 index.html 的初始占位,别残留上一个
// 账号的头像/统计
$('#hero-name').textContent = '未选择账号';
$('#hero-sub').textContent = '用森空岛 token 添加一个账号开始';
$('#hero-avatar').textContent = '?';
$('#hero-avatar').classList.remove('ef');
$('#hero-stats').innerHTML = '';
return;
}
const a = d.account || {}, st = d.stats || {};
const name = a.nickName || '未知账号';
$('#hero-name').textContent = name;
Expand Down
14 changes: 14 additions & 0 deletions frontend/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,20 @@ input:focus, select:focus, button:focus-visible { outline: none; }
}
.acct-sub { font-size: 11.5px; color: var(--text-3); white-space: nowrap; }
.acct-sub b { color: var(--text-2); font-weight: 500; }
/* 删除 ✕:平时不占视觉,悬停卡片才出现(span 而非 button——卡片本身
是 button,HTML 不允许按钮嵌按钮) */
.acct-del {
flex: 0 0 auto;
display: none;
width: 20px; height: 20px;
border-radius: 6px;
place-items: center;
font-size: 11px;
color: var(--text-3);
cursor: pointer;
}
.acct:hover .acct-del { display: grid; }
.acct-del:hover { color: var(--rose); background: rgba(255, 122, 138, 0.13); }

.add-account {
margin-top: 10px;
Expand Down
Loading
Loading