Merge branch 'dev' —— 定时触发修复 + 账号状态历史

This commit is contained in:
2026-10-22 07:59:18 +08:00
13 changed files with 222 additions and 18 deletions
+27 -7
View File
@@ -173,6 +173,7 @@ def list_accounts(prof=None):
"has_dir": has_dir,
"device_name": rr.get("device_name") or "",
"account_status": rr.get("account_status") or "",
"status_checked_at": rr.get("status_checked_at") or "",
"serial": rr.get("serial") or "",
"pooled": bool(rr.get("pooled")),
"online": bool(rr.get("online")),
@@ -1144,24 +1145,43 @@ def roster_rows():
return out
def set_account_status(name, status=""):
"""按账号名写账号库的「账号状态」(任务变量回写用)。
def set_account_status(name, status="", source="", run_id=""):
"""按账号名写账号库的「账号状态」,并追加一条检测记录。
名字先精确匹配昵称,再按抖音号兜底;账号库里没有这个号 → 返回 False(**不新建行**)。
供任务里的「读取文字」在变量名是 `account_status` 时调用:读到什么写什么,
读不到(元素不存在)写「正常」。
供任务里的「读取文字」在变量名是 `account_status` 时调用:读到什么写什么;
读不到时调用方不调用(保留原值)。同一 `run_id` + 账号只留一条记录
(一次运行里重复写时更新那一条,不刷重复历史)。
"""
from core.models import db, DeviceAccount
from core.models import db, DeviceAccount, AccountStatusLog
key = (name or "").strip()
if not key:
return False
now = _now()
val = (status or "").strip()[:80]
with _ctx():
row = (DeviceAccount.query.filter_by(nickname=key).first()
or DeviceAccount.query.filter_by(douyin_id=key).first())
if row is None:
return False
row.account_status = (status or "").strip()[:80]
row.updated_at = _now()
row.account_status = val
row.status_checked_at = now
row.updated_at = now
log = None
if run_id:
log = AccountStatusLog.query.filter_by(
nickname=row.nickname, run_id=str(run_id)[:32]).first()
if log is not None:
log.status = val
log.detected_at = now
log.device_name = row.device_name or log.device_name
else:
db.session.add(AccountStatusLog(
id=uuid.uuid4().hex[:8], account_id=row.id,
nickname=row.nickname, device_name=row.device_name or "",
serial=row.serial or "", status=val,
source=(source or "")[:40], run_id=str(run_id or "")[:32],
detected_at=now, created_at=now))
db.session.commit()
return True
+35
View File
@@ -565,6 +565,8 @@ class DeviceAccount(db.Model):
# 账号状态(正常 / 账号异常 / 限流…):资产管理里可手改;任务里「读取文字」
# 存到变量 `account_status` 时会自动回写这一列(见 tasks/generic/task.py)。
account_status = db.Column(db.String(80), default="")
# 最近一次「检测到状态」的时间(历史明细在 account_status_log)
status_checked_at = db.Column(db.String(20), default="")
created_at = db.Column(db.String(20), default="")
updated_at = db.Column(db.String(20), default="")
@@ -577,12 +579,43 @@ class DeviceAccount(db.Model):
"can_post_video": bool(self.can_post_video),
"bio": self.bio or "", "note": self.note or "",
"account_status": self.account_status or "",
"status_checked_at": self.status_checked_at or "",
"created_at": self.created_at or "", "updated_at": self.updated_at or ""}
def __repr__(self):
return f"<DeviceAccount {self.device_name} {self.nickname}>"
class AccountStatusLog(db.Model):
"""账号状态检测记录:每次检测(或手动修改)追加一行。
资产页「账号状态」列只显示最新值;点「记录」看这个账号的历史:
时间 + 状态 + 设备 + 来源(计划运行/任务运行/手动修改)。
"""
__tablename__ = "account_status_log"
id = db.Column(db.String(32), primary_key=True)
account_id = db.Column(db.String(32), default="", index=True)
nickname = db.Column(db.String(80), default="", index=True)
device_name = db.Column(db.String(80), default="")
serial = db.Column(db.String(120), default="")
status = db.Column(db.String(80), default="")
source = db.Column(db.String(40), default="")
run_id = db.Column(db.String(32), default="", index=True)
detected_at = db.Column(db.String(20), default="", index=True)
created_at = db.Column(db.String(20), default="")
def to_dict(self):
return {"id": self.id, "account_id": self.account_id or "",
"nickname": self.nickname or "", "device_name": self.device_name or "",
"serial": self.serial or "", "status": self.status or "",
"source": self.source or "", "run_id": self.run_id or "",
"detected_at": self.detected_at or "",
"created_at": self.created_at or ""}
def __repr__(self):
return f"<AccountStatusLog {self.nickname} {self.status} @{self.detected_at}>"
class VideoPlan(db.Model):
"""视频发布计划:账号 × 发布日期 × 编号 → 一个视频素材 + 一条标题 + 发布结果。
@@ -1043,6 +1076,8 @@ SCHEMA_MIGRATIONS = [
"「读取文字」写变量 account_status 时自动回写,用于创作者中心/异常检测)", None),
(22, "应用管理·自动下载:新增 apk_source 表(下载直链、检查间隔、上次检查结果)",
None),
(23, "账号状态历史:device_account 新增 status_checked_at(最近检测时间);"
"新增 account_status_log(每次检测/手改追加一行:状态/时间/设备/来源)", None),
]
# 当前 schema 版本(备份/恢复用它判断新旧,也写进 app_meta.schema_version)
+7 -4
View File
@@ -1000,15 +1000,18 @@ def _fire(plan_id):
"""到点触发(APScheduler 调的,在自己的线程里)。失败只记日志,不冒泡。"""
try:
from core.models import AePlan
# ⚠ `run_plan` 内部要查库/建 AeRun —— **必须在 app context 里调**;
# APScheduler 的线程没有请求上下文,之前放在 with 外面会报
# "Working outside of application context"(2026-10-21 18:00 实测)。
with _ctx():
row = AePlan.query.get(plan_id)
if row is None or not row.enabled:
return
plan = row.to_dict()
if not _in_date_range(plan) or not _in_window(plan):
_log.info("计划 %s 到点但不在日期范围/运行窗口内 → 跳过", plan_id)
return
res = run_plan(plan_id, trigger="cron")
if not _in_date_range(plan) or not _in_window(plan):
_log.info("计划 %s 到点但不在日期范围/运行窗口内 → 跳过", plan_id)
return
res = run_plan(plan_id, trigger="cron")
if not res.get("ok"):
_log.warning("计划 %s 到点触发失败:%s", plan_id, res.get("error"))
except Exception as e:
+1
View File
@@ -60,6 +60,7 @@ TABLE_LABELS = {
"task_step_log": "任务步骤明细",
"done_mark": "去重记录(已做过)",
"device_account": "账号库(名字 ↔ 哪台手机)",
"account_status_log": "账号状态检测记录(每次检测/手改)",
"ae_plan": "计划调度(一行一个计划:干什么/给谁/发什么/什么时候/怎么跑)",
"ae_plan_run": "计划运行记录(每次触发的成功/失败/跳过统计)",
"video_publish_log": "素材发布记录(每条素材每次发布的时间/结果/设备/链接)",
+1 -1
View File
@@ -300,7 +300,7 @@ App 从每段的动作组/任务带出来(列表里显示"动作组 · App"或
|---|---|---|
| 账号 | 昵称(+ 抖音号小字);不在账号库的会标「账号库没有」 | 编辑走账号库 |
| **所属手机** | `A01` / 未登记 / 未入池;下拉直接**改 `device_account.device_name`** | ✅ 换机就在这里改 |
| **账号状态** | `正常` / `账号异常` / `限流`…(`device_account.account_status`) | ✅ 点「改」手填;任务「读取文字」写变量 `account_status` 时自动回写(元素不存在=正常) |
| **账号状态** | `正常` / `账号异常` / `限流`…(`device_account.account_status`)+ **最近检测时间**(`status_checked_at`) | ✅ 点「改」手填;点「记录」看历史(时间/状态/设备/来源);任务「读取文字」写变量 `account_status` 时自动回写(读到什么写什么,读不到不写) |
| 素材库 | `入库 N · 未发布 N · 已发布 N`(+ 文件夹里还没入库的个数) | 点开进二级页 |
| 最近发布 | 该账号最后一条的 `published_at` | — |
| 操作 | 扫描 · 编辑账号 · **上传素材**(单个文件,见下)· **删除**(见下) | — |
+1
View File
@@ -1098,6 +1098,7 @@ multipart 上传 `.zip` 或 `.db`(字段 `file`)→ 校验并暂存:
| GET | `/api/af/item/<id>/publish_logs` | 素材的发布记录 |
| GET | `/api/af/devices` · POST `/api/af/probe` | 设备卡片 / 实时探测每台登着哪个号 |
| GET | `/api/af/roster` | **账号库**(名字 ↔ 哪台手机,每行带 `serial/pooled/online`) |
| GET | `/api/af/account_status_logs?name=<昵称>` | **账号状态检测记录**(时间/状态/设备/来源,最近 100 条) |
| POST | `/api/af/roster/import` · `/resolve` | 粘贴导入(**按抖音号认同一行**,永不删)/ 只算名字→设备 |
| DELETE | `/api/af/roster/<row_id>` | 删一行账号库(只有这里会删) |
| GET | `/api/account_pool/accounts` | **账号池对外只读 API**(独立令牌,给其他应用;见下) |
+29
View File
@@ -957,3 +957,32 @@ warning,否则 success。单字段展示上限从 400 字放宽到 800 字(
计划收尾按 `status_watch` 触发;`web_server.py` 启动每日汇总线程。
- 单测:`test_roster.py` ⑧(只发一条、按 3 个类型分行、账号清单、无统计字段)、
`test_plan.py`(识别 read_text 状态步骤)。
## 35. 2026-10-22 修复:计划「检测账号」18:00 没有运行记录
用户:"计划调度怎么没有运行,我写了 18:00,没有运行记录。"
- 计划本身是对的:`enabled=1`、`points=["9:00","18:00"]`,17:13 保存后调度器已重载
(日志:`计划调度已重载:1 条启用中`)。
- 18:00:00 实际触发了,但立即异常:
`[WARNING] [core.plan] 计划 e6c936d3 触发异常:Working outside of application context.`
- 原因:APScheduler 的线程没有请求上下文,`_fire()` 只在查计划时开了 `with _ctx()`,
真正调用 `run_plan()` 在 with 外面 —— `run_plan` 查库/建 `AeRun` 直接抛异常,
所以连 `ae_plan_run` 记录都没创建。
- 修复:把 `run_plan()` 移到 `with _ctx()` 内调用。
- 回归测试:`test_plan.py` ⑥ 在新线程里调 `_fire`,断言 `run_plan` 内
`has_app_context()==True`。
## 36. 2026-10-22 新增:账号状态「检测时间」+ 检测记录表
用户:"账号状态要加一个检测时间,和账号状态记录,比如这次账号异常、下次正常,要有个记录表。"
- `device_account` 新增 `status_checked_at`(最近一次**真检测**时间;手改不刷新)。
- 新表 `account_status_log`(schema v23):每次检测/手改追加一行
`昵称 / 状态 / 设备 / 来源(计划运行/任务运行/手动修改)/ run_id / 检测时间`;
同一 `run_id` + 账号只留一条(一次运行里重复写会更新那条,不刷重复历史)。
- 资产表「账号状态」列下方显示「检测 2026-10-22 09:00:12」,行内多了「记录」按钮,
点开看该账号的历史(时间/状态/设备/来源)。
- 接口:`GET /api/af/account_status_logs?name=<昵称>&limit=100`。
- 备份:新表自动进 `SUMMARY_TABLES`,`TABLE_LABELS` 已登记。
- 测试:`test_roster.py` ⑨(同一 run 去重、下一次状态入库、检测时间写入)。
+3
View File
@@ -51,6 +51,8 @@
| 18 | `ae_app` · `ae_profile` · `ae_run` | 流水线:App 注册表 / 三层配置 / 每轮运行记录 |
| 19 | `ae_plan` · `ae_plan_run` | **计划调度**:一行一个计划 + 每次触发的成功/失败/跳过(见 §2.13) |
| 20 | `video_publish_log` | **素材发布记录**:每次发布一行(时间/结果/账号/设备/链接/失败原因),素材详情与 ④ 运行监测共用(见 §2.11) |
| 21 | `apk_source` | **APK 自动下载源**:直链 / 包名 / 检查间隔 / 上次检查结果(应用管理,2026-10-21) |
| 22 | `account_status_log` | **账号状态检测记录**:每次检测/手改一行(昵称/状态/设备/来源/时间/run_id;2026-10-22) |
> 2026-09-13 之前,`app_meta` 与 4 张 `agent_*` 表是各模块里的裸 `CREATE TABLE`
> (不进模型层)。迁 MySQL 时那批 SQL 的 `AUTOINCREMENT`/`TEXT DEFAULT ''`/`TEXT PRIMARY KEY`
@@ -221,6 +223,7 @@
| `douyin_id` | String(64) | **抖音号 = 真正的身份**(纯号,不带 `抖音号:` 前缀) |
| `serial` / `phone` / `registered_at` / `sim_in_device` / `can_post_video` / `bio` / `note` | | 历史列,保留 |
| `account_status` | String(80) | **账号状态**(正常 / 账号异常 / 限流…):资产管理里可手改;任务「读取文字」写变量 `account_status` 时自动回写 |
| `status_checked_at` | String(20) | **最近一次检测到状态的时间**(手改不刷新;历史明细在 `account_status_log`) |
**三条语义(都是刻意设计)**:
+34
View File
@@ -363,6 +363,40 @@ finally:
device_pool.list_devices, device_pool.list_online, device_pool.serial_of = (
_orig_devices, _orig_online, _orig_serial_of)
print("▶ ⑥ 定时触发:run_plan 必须在 app context 内调用")
import threading # noqa: E402
from flask import has_app_context # noqa: E402
with app.app_context():
db.session.add(AePlan(id="firetest", name="firetest", enabled=True,
accounts=json.dumps(["号甲"]),
segments=json.dumps([]),
schedule=json.dumps({"points": ["09:00"]}),
created_at="2026-10-17 00:00:00",
updated_at="2026-10-17 00:00:00"))
db.session.commit()
_seen = []
_orig_run = plan_mod.run_plan
def _fake_run(pid, trigger="manual"):
_seen.append((pid, trigger, has_app_context()))
return {"ok": True}
plan_mod.run_plan = _fake_run
try:
_t = threading.Thread(target=plan_mod._fire, args=("firetest",))
_t.start()
_t.join(timeout=10)
finally:
plan_mod.run_plan = _orig_run
with app.app_context():
_row = AePlan.query.get("firetest")
if _row:
db.session.delete(_row)
db.session.commit()
check("定时触发时 run_plan 有 app context", _seen, [("firetest", "cron", True)])
print()
if fails:
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
+16 -1
View File
@@ -21,7 +21,8 @@ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspa
os.chdir(sys.path[0])
from flask import Flask # noqa: E402
from core.models import db, init_db, DeviceAccount, Device # noqa: E402
from core.models import (db, init_db, DeviceAccount, Device, # noqa: E402
AccountStatusLog)
from core import account_folder as af # noqa: E402
from core import account_probe as ap # noqa: E402
from core import device_pool # noqa: E402
@@ -249,6 +250,20 @@ check("账号正常列表", "锋哥苏州百业探访" in groups, True)
check("没有统计字段(一个消息按类型列账号)",
("total" in kw or "normal" in kw or "abnormal" in kw), False)
print("▶ ⑨ 账号状态检测记录(每次检测/手改留痕)")
af.set_account_status("锋哥苏州乙探访", "作品异常", source="任务运行", run_id="runA")
af.set_account_status("锋哥苏州乙探访", "作品异常", source="任务运行", run_id="runA")
af.set_account_status("锋哥苏州乙探访", "账号正常", source="任务运行", run_id="runB")
with app.app_context():
logs = (AccountStatusLog.query.filter_by(nickname="锋哥苏州乙探访")
.order_by(AccountStatusLog.detected_at).all())
check("同一次运行只留一条", len([x for x in logs if x.run_id == "runA"]), 1)
check("下一次运行记录新状态",
[x.status for x in logs if x.run_id == "runB"], ["账号正常"])
row = DeviceAccount.query.filter_by(nickname="锋哥苏州乙探访").first()
check("账号库最新状态", row.account_status, "账号正常")
check("检测时间已写", bool(row.status_checked_at), True)
print()
if fails:
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
+31 -2
View File
@@ -332,8 +332,12 @@ function afHtmlAsset() {
(a.in_roster
? '<button class="btn btn-xs" title="手动改账号状态" ' +
'onclick="afAssetEditStatus(\'' + esc(a.roster_id) + '\',\'' + esc(a.name) + '\',\'' +
esc(a.account_status || '') + '\')">改</button>'
esc(a.account_status || '') + '\')">改</button> ' +
'<button class="btn btn-xs" onclick="afAssetStatusLogs(\'' + esc(a.name) + '\')">记录</button>'
: '') +
(a.status_checked_at
? '<div class="text-muted" style="font-size:11px;margin-top:2px">检测 ' +
esc(a.status_checked_at) + '</div>' : '') +
'</td>' +
'<td><button class="btn btn-xs btn-primary" onclick="afAssetOpenAccount(\'' + esc(a.name) + '\')">' +
'入库 <b>' + (a.total || 0) + '</b> · 未发布 <b style="color:#b45309">' + (a.pending || 0) + '</b>' +
@@ -390,7 +394,7 @@ function afHtmlAsset() {
'</div>' +
'<table class="table"><thead><tr>' +
'<th style="width:230px">账号</th><th style="width:210px">所属手机</th>' +
'<th style="width:150px">账号状态</th>' +
'<th style="width:190px">账号状态</th>' +
'<th style="width:400px">素材库</th><th style="width:140px">最近发布</th><th style="width:190px">操作</th>' +
'</tr></thead><tbody>' +
(rows || '<tr><td colspan="6" class="empty">' +
@@ -444,6 +448,31 @@ async function afSaveRosterStatus(rosterId, status) {
await afRefreshAll();
}
async function afAssetStatusLogs(name) {
const r = await apiGet('/api/af/account_status_logs?name=' +
encodeURIComponent(name) + '&limit=100');
if (!r || !r.ok) { showToast((r && r.error) || '读取状态记录失败', 'error'); return; }
const rows = (r.rows || []).map(function (x) {
const good = (x.status === '正常' || x.status === '账号正常');
const st = x.status
? '<span class="label ' + (good ? 'label-success' : 'label-warning') + '">' +
esc(x.status) + '</span>'
: '<span class="text-muted">(空)</span>';
return '<tr><td style="white-space:nowrap">' + esc(x.detected_at || '') + '</td>' +
'<td>' + st + '</td><td>' + esc(x.device_name || '') + '</td>' +
'<td>' + esc(x.source || '') + '</td></tr>';
}).join('');
document.getElementById('modal-title').textContent = '账号状态记录 · ' + name;
document.getElementById('modal-body').innerHTML =
'<table class="table"><thead><tr><th>时间</th><th>状态</th><th>设备</th>' +
'<th>来源</th></tr></thead><tbody>' +
(rows || '<tr><td colspan="4" class="empty">还没有检测记录</td></tr>') +
'</tbody></table>';
document.getElementById('modal-footer').innerHTML =
'<button class="btn" onclick="closeModal()">关闭</button>';
showModal();
}
function afAssetScan(name) {
afScan(name);
}
+5 -1
View File
@@ -1289,7 +1289,11 @@ class GenericStepsWorker(BaseWorker):
if text:
try:
from core import account_folder as _af
if not _af.set_account_status(who, text):
_ctx = getattr(self, "ctx", None) or {}
_src = "计划运行" if _ctx.get("plan_id") else "任务运行"
if not _af.set_account_status(
who, text, source=_src,
run_id=str(_ctx.get("run_id") or "")):
_log.warning(f"[{self.serial}] 账号状态未回写:账号库里没有『{who}』")
except Exception as e:
_log.warning(f"[{self.serial}] 账号状态回写失败(不影响任务): {e}")
+32 -2
View File
@@ -360,8 +360,18 @@ def api_af_roster_update(row_id):
row.douyin_id = (data.get("douyin_id") or "").strip()[:64]
if "account_status" in data:
# 账号状态:手改(正常/账号异常/限流…);任务里「读取文字」写
# 变量 account_status 时也会走同一列(见 af.set_account_status)
row.account_status = (data.get("account_status") or "").strip()[:80]
# 变量 account_status 时也会走同一列(见 af.set_account_status)。
# 手改也进历史表(source=手动修改),但**不刷新检测时间**(那列只表示真检测)。
from core.models import AccountStatusLog
new_st = (data.get("account_status") or "").strip()[:80]
if new_st != (row.account_status or ""):
db.session.add(AccountStatusLog(
id=uuid.uuid4().hex[:8], account_id=row.id,
nickname=row.nickname, device_name=row.device_name or "",
serial=row.serial or "", status=new_st, source="手动修改",
run_id="", detected_at=time.strftime("%Y-%m-%d %H:%M:%S"),
created_at=time.strftime("%Y-%m-%d %H:%M:%S")))
row.account_status = new_st
row.updated_at = time.strftime("%Y-%m-%d %H:%M:%S")
db.session.commit()
_log.info("账号库编辑:%s → 昵称 %s / 设备 %s", row_id, row.nickname, row.device_name)
@@ -405,6 +415,26 @@ def api_af_roster():
return jsonify({"ok": True, "rows": rows, "groups": groups, "total": len(rows)})
@bp.route("/api/af/account_status_logs")
@perm_required(PERM_DEVICES)
def api_af_account_status_logs():
"""账号状态检测记录(资产管理 → 账号状态 → 记录)。"""
from core.models import AccountStatusLog
name = (request.args.get("name") or "").strip()
try:
limit = max(1, min(200, int(request.args.get("limit", 50) or 50)))
except (TypeError, ValueError):
limit = 50
q = AccountStatusLog.query
if name:
q = q.filter(AccountStatusLog.nickname == name)
rows = (q.order_by(AccountStatusLog.detected_at.desc(),
AccountStatusLog.id.desc())
.limit(limit).all())
return jsonify({"ok": True, "rows": [r.to_dict() for r in rows],
"total": len(rows)})
# ==================== 账号池对外只读 API ====================
# 其他应用用 `X-Account-Token`(或 Bearer)访问,不需要登录会话。
@bp.route("/api/account_pool/accounts", methods=["GET", "OPTIONS"])