- 新表 comment_item(schema v25):视频链接/账号/评论内容/状态 - 新步骤 foreach_comment / mark_comment;clipboard 支持评论变量;input_text 支持当前评论内容 - 计划调度页导入评论、查看/重置/裁决评论数据 - 资产管理导出账号列表 + 自动/人工/有效状态 CSV - 切号参数全局化:fleet.switch 统一选择器,计划默认 use_global=true,老计划也按全局 - 测试 19/19;API/DATA_MODEL/TASK_DEV/ACCOUNT_FOLDER/CHANGES 同步
1012 lines
46 KiB
Python
1012 lines
46 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""账号文件夹流水线 API(新模块,**不动老发布计划页/任务页**)。
|
||
|
||
页面「流水线」用这几个接口:
|
||
配置 GET/PUT /api/af/profile 三层参数(素材/设备账号/动作/日志)—— **所有可变的点都在这**
|
||
素材 GET /api/af/accounts 根目录下的账号(素材数/待发数/上次运行)
|
||
POST /api/af/scan 扫账号目录入库(dry_run=只预览不写库)
|
||
GET /api/af/items 条目列表(读 video_plan)
|
||
设备 GET /api/af/devices 设备卡片(在线/忙/上次探测到的账号)
|
||
POST /api/af/probe 实时探测"每台登着哪个账号"
|
||
动作 GET/POST /api/af/apps PUT/DELETE /api/af/apps/<id> App 注册表(包名 + 首页定位)
|
||
(动作本身用**现有的** /api/custom_actions —— 与任务编辑器共用同一份)
|
||
运行 POST /api/af/run 多选账号(可多选设备)跑一轮,后台线程、立刻返回 run_id
|
||
GET /api/af/runs 运行记录
|
||
GET /api/af/run/<id> 该轮明细(步骤行)
|
||
GET /api/af/log 下载账号文件夹里的日志(csv/md/png)
|
||
抓元素 / 测一下:**复用现有的**(前端 openPicker / `POST /api/steps/test`),这里不重复造
|
||
"""
|
||
import os
|
||
import hmac
|
||
import secrets
|
||
import threading
|
||
import time
|
||
import uuid
|
||
|
||
from flask import Blueprint, jsonify, request, send_file
|
||
from flask_login import current_user
|
||
|
||
from core import account_folder as af
|
||
from core.db_config import meta_get, meta_set
|
||
from core.logger import get_logger
|
||
from web.auth import perm_required, admin_required, PERM_DEVICES
|
||
|
||
_log = get_logger("web")
|
||
bp = Blueprint("account_folder", __name__)
|
||
|
||
PROFILE_ID = "default"
|
||
|
||
# ==================== 账号池对外 API(给其他应用只读访问)====================
|
||
# 与「设备端令牌」分开:这里只读账号库,不暴露设备 Agent 的 bootstrap/上报能力。
|
||
_K_POOL_TOKEN = "account_pool_token"
|
||
_K_POOL_TOKEN_AT = "account_pool_token_at"
|
||
|
||
|
||
def _pool_token():
|
||
"""取(没有就生成)账号池 API 令牌,存 app_meta(随备份走)。"""
|
||
tok = meta_get(_K_POOL_TOKEN) or ""
|
||
if not tok:
|
||
tok = secrets.token_urlsafe(24)
|
||
meta_set(_K_POOL_TOKEN, tok)
|
||
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
_log.info("账号池 API 令牌已生成")
|
||
return tok
|
||
|
||
|
||
def _pool_req_token():
|
||
"""请求里的令牌:`X-Account-Token` 或 `Authorization: Bearer <token>`。"""
|
||
tok = (request.headers.get("X-Account-Token") or "").strip()
|
||
if tok:
|
||
return tok
|
||
auth = (request.headers.get("Authorization") or "").strip()
|
||
if auth.lower().startswith("bearer "):
|
||
return auth[7:].strip()
|
||
return ""
|
||
|
||
|
||
def _pool_json(data, code=200):
|
||
"""账号池 JSON 响应:带 CORS(其他应用/网页可直接读)。"""
|
||
resp = jsonify(data)
|
||
resp.status_code = code
|
||
resp.headers["Access-Control-Allow-Origin"] = "*"
|
||
resp.headers["Access-Control-Allow-Headers"] = "X-Account-Token, Authorization, Content-Type"
|
||
resp.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
|
||
return resp
|
||
|
||
|
||
def _profile_row(create=True):
|
||
"""取(或建)那唯一一条配置。"""
|
||
from core.models import db, AeProfile
|
||
row = AeProfile.query.get(PROFILE_ID)
|
||
if row is None and create:
|
||
row = AeProfile(id=PROFILE_ID, name="默认流水线", version=1,
|
||
updated_at=time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
row.set_params({})
|
||
db.session.add(row)
|
||
db.session.commit()
|
||
return row
|
||
|
||
|
||
def _profile_params():
|
||
row = _profile_row()
|
||
return af.merged(row.get_params() if row else None)
|
||
|
||
|
||
# ==================== 配置 ====================
|
||
|
||
@bp.route("/api/af/profile")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_profile_get():
|
||
"""取三层配置(**与默认值合并后**返回,页面直接照着渲染表单)。"""
|
||
row = _profile_row()
|
||
out = row.to_dict()
|
||
out["params"] = af.merged(out.get("params"))
|
||
out["root"] = af.account_root(out["params"])
|
||
return jsonify({"ok": True, "profile": out, "defaults": af.DEFAULT_PROFILE})
|
||
|
||
|
||
@bp.route("/api/af/profile", methods=["PUT"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_profile_put():
|
||
"""保存三层配置。**改完即生效**(下次扫描/跑一轮用新值),不用重启。"""
|
||
from core.models import db
|
||
data = request.json or {}
|
||
params = data.get("params")
|
||
if not isinstance(params, dict):
|
||
return jsonify({"ok": False, "error": "params 必须是对象"}), 400
|
||
row = _profile_row()
|
||
row.set_params(af.merged(params))
|
||
if data.get("name"):
|
||
row.name = str(data["name"])[:80]
|
||
row.version = int(row.version or 1) + 1
|
||
row.updated_at = time.strftime("%Y-%m-%d %H:%M:%S")
|
||
db.session.commit()
|
||
_log.info("流水线配置已保存:v%s", row.version)
|
||
return jsonify({"ok": True, "msg": "已保存(版本 v%s)" % row.version,
|
||
"version": row.version})
|
||
|
||
|
||
# ==================== 素材层 ====================
|
||
|
||
@bp.route("/api/af/ready_defaults")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_ready_defaults():
|
||
"""**内置「账号就绪(切号)」的默认参数**(计划编排页的"编辑参数"用它回填)。
|
||
|
||
返回的就是 `build_ready_step()` 生成的 params:选择器、超时、切后等待、重试、登录页处置。
|
||
计划里保存的 `ready` 覆盖它;空 = 用这份默认。
|
||
"""
|
||
step = af.build_ready_step(af.merged()) or {}
|
||
return jsonify({"ok": True, "enabled": True, "params": step.get("params") or {}})
|
||
|
||
|
||
@bp.route("/api/af/accounts")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_accounts():
|
||
prof = _profile_params()
|
||
return jsonify({"ok": True, "root": af.account_root(prof),
|
||
"accounts": af.list_accounts(prof)})
|
||
|
||
|
||
@bp.route("/api/af/accounts/export")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_accounts_export():
|
||
"""导出账号列表 + 状态(CSV,UTF-8 BOM,Excel 可直接打开)。"""
|
||
import io
|
||
data = af.export_accounts_csv(_profile_params())
|
||
name = "账号列表_%s.csv" % time.strftime("%Y%m%d_%H%M")
|
||
return send_file(io.BytesIO(data), as_attachment=True, download_name=name,
|
||
mimetype="text/csv; charset=utf-8")
|
||
|
||
|
||
@bp.route("/api/af/scan", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_scan():
|
||
"""扫描账号目录并入库。
|
||
|
||
请求:`{"account": "某账号"}` 扫一个;不传 account = **扫根目录下所有账号**;`dry_run=true` 只预览。
|
||
"""
|
||
data = request.json or {}
|
||
prof = _profile_params()
|
||
account = (data.get("account") or "").strip()
|
||
dry = bool(data.get("dry_run"))
|
||
date = (data.get("date") or "").strip()
|
||
if account:
|
||
r = af.scan_account(account, date=date, dry_run=dry, prof=prof)
|
||
else:
|
||
r = af.scan_all(date=date, dry_run=dry, prof=prof)
|
||
_log.info("流水线扫描:%s → %s", account or "(全部)", (r.get("msg") or r.get("error") or "")[:120])
|
||
return jsonify(r)
|
||
|
||
|
||
@bp.route("/api/af/upload", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_upload():
|
||
"""**在页面上把素材传到某个账号文件夹**(等价于直接往服务器目录里拷文件),传完自动扫描入库。
|
||
|
||
form-data:`account`(账号名,目录不存在会自动建)、`captions`(可选,一行一条文案,
|
||
追加到该账号的 `标题.txt`)、`files`(可多个)。
|
||
"""
|
||
account = (request.form.get("account") or "").strip()
|
||
captions = request.form.get("captions") or ""
|
||
files = request.files.getlist("files") or request.files.getlist("file")
|
||
if not account:
|
||
return jsonify({"ok": False, "error": "先选/填一个账号(= 目录名)"}), 400
|
||
if not files:
|
||
return jsonify({"ok": False, "error": "没选文件"}), 400
|
||
prof = _profile_params()
|
||
r = af.save_upload(account, files, captions=captions, prof=prof)
|
||
if not r.get("ok"):
|
||
return jsonify(r), 400
|
||
scan = af.scan_account(account, prof=prof)
|
||
r["scan"] = scan
|
||
r["msg"] = "%s;%s" % (r.get("msg") or "", scan.get("msg") or "")
|
||
_log.info("流水线上传素材:%s ← %d 个文件,%s", account, len(files), (scan.get("msg") or "")[:80])
|
||
return jsonify(r)
|
||
|
||
|
||
@bp.route("/api/af/items")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_items():
|
||
"""素材列表(资产管理二级页)。过滤:`account/date/status/category/display_mode/q`,`limit`(默认 500)。
|
||
|
||
每行带**派生**的 `media_type`(视频/图片/音频)与 `device_name`(该账号当前所属手机)。
|
||
"""
|
||
return jsonify({"ok": True, "items": af.list_items(
|
||
account=(request.args.get("account") or "").strip(),
|
||
date=(request.args.get("date") or "").strip(),
|
||
status=(request.args.get("status") or "").strip(),
|
||
category=(request.args.get("category") or "").strip(),
|
||
display_mode=(request.args.get("display_mode") or "").strip(),
|
||
q=(request.args.get("q") or "").strip(),
|
||
limit=int(request.args.get("limit") or 500))})
|
||
|
||
|
||
@bp.route("/api/af/item/<plan_id>/meta", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_item_meta(plan_id):
|
||
"""**编辑素材元数据**:只改传入的字段(标题/内容/话题/分类/展示方式/备注/时长)。
|
||
|
||
刻意不走 `PUT /api/video_plan/<id>`:那条老分支带 `body`/名字时会**把标题清空**。
|
||
"""
|
||
from core import video_plan as vp
|
||
data = request.get_json(silent=True) or {}
|
||
want = {k: data[k] for k in ("title", "body", "topics", "category",
|
||
"display_mode", "note", "duration_s") if k in data}
|
||
if not want:
|
||
return jsonify({"ok": False, "error": "没有要改的字段"}), 400
|
||
row, err = vp.set_meta(plan_id, want)
|
||
if err:
|
||
return jsonify({"ok": False, "error": err}), (404 if "不存在" in err else 400)
|
||
return jsonify({"ok": True, "item": row, "msg": "素材已更新"})
|
||
|
||
|
||
@bp.route("/api/af/item/<plan_id>/publish_logs")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_item_publish_logs(plan_id):
|
||
"""某条素材的**发布记录**(时间/结果/设备/链接/失败原因,最近的在前)。"""
|
||
from core import video_plan as vp
|
||
return jsonify({"ok": True, "logs": vp.publish_logs(plan_id,
|
||
int(request.args.get("limit") or 100))})
|
||
|
||
|
||
@bp.route("/api/af/assets/template")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_assets_template():
|
||
"""下载**素材导入模板**(CSV,UTF-8 BOM,Excel 可直接开)。
|
||
|
||
`?account=` 可以带一个真实账号名 → 示例行就用它(复制粘贴就能填)。
|
||
"""
|
||
from io import BytesIO
|
||
acc = (request.args.get("account") or "").strip()
|
||
data = af.asset_template_csv(sample_account=acc)
|
||
return send_file(BytesIO(data), as_attachment=True,
|
||
download_name="素材导入模板.csv",
|
||
mimetype="text/csv; charset=utf-8")
|
||
|
||
|
||
@bp.route("/api/af/assets/import", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_assets_import():
|
||
"""**批量上传素材 + 模板匹配**(用户在资产管理页的主流程)。
|
||
|
||
form-data:
|
||
· `files` 多个素材文件(视频/图片/音频)
|
||
· `table` 填好的 CSV(模板下载 → Excel 填 → 另存为 CSV UTF-8)
|
||
· `durations` JSON:`{"文件名": 秒}`(前端上传前用 `<video>` 读好,服务器不用装 ffprobe)
|
||
· `dry_run` `1` = 只校验+报告,不写文件不入库
|
||
|
||
两项校验(用户明确要求):**数量一致**、**文件名一一对应**;任何一条不过 → **整批不导入**。
|
||
通过后按表里的「账号」列分拣落盘并入库(标题/内容/话题/分类/展示方式/备注/时长)。
|
||
"""
|
||
import json as _json
|
||
files = request.files.getlist("files") or request.files.getlist("file")
|
||
table = request.files.get("table")
|
||
if table is None:
|
||
return jsonify({"ok": False, "error": "没上传表格(先下载模板、填好、另存为 CSV UTF-8)"}), 400
|
||
if not files:
|
||
return jsonify({"ok": False, "error": "没上传素材文件"}), 400
|
||
raw = table.read()
|
||
if not raw:
|
||
return jsonify({"ok": False, "error": "表格是空的"}), 400
|
||
durations = {}
|
||
try:
|
||
durations = _json.loads(request.form.get("durations") or "{}") or {}
|
||
except Exception:
|
||
durations = {}
|
||
dry = (request.form.get("dry_run") or "").strip() in ("1", "true", "yes")
|
||
prof = _profile_params()
|
||
res = af.import_assets(files, raw, durations=durations, dry_run=dry, prof=prof)
|
||
if res.get("ok"):
|
||
_log.info("素材批量导入%s:新增 %s / 更新 %s", "(预演)" if dry else "",
|
||
res.get("added"), res.get("updated"))
|
||
return jsonify(res), (200 if res.get("ok") else 400)
|
||
|
||
|
||
@bp.route("/api/af/item/upload", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_item_upload():
|
||
"""**单条素材上传**(资产管理页每个账号行尾的「上传素材」)。
|
||
|
||
form-data:`file` + `account` + `title/body/topics/category/display_mode/note/
|
||
duration_s/status`。`status=asset` = 仅素材·不发布(音频自动如此)。
|
||
|
||
与批量导入的区别:账号取这一行本身(不要求先在账号库里),一次只传一个文件;
|
||
判重仍按 `(账号, 内容 sha1)` —— 同一份内容再传只更新元数据。
|
||
"""
|
||
f = request.files.get("file")
|
||
if f is None:
|
||
return jsonify({"ok": False, "error": "没有选文件"}), 400
|
||
account = (request.form.get("account") or "").strip()
|
||
if not account:
|
||
return jsonify({"ok": False, "error": "没有指定账号"}), 400
|
||
meta = {k: (request.form.get(k) or "").strip()
|
||
for k in ("title", "body", "topics", "category",
|
||
"display_mode", "note")}
|
||
meta["status"] = "asset" if (request.form.get("status") or "") == "asset" else ""
|
||
res = af.import_one(account, f, meta=meta,
|
||
duration_s=request.form.get("duration_s") or 0,
|
||
prof=_profile_params())
|
||
if res.get("ok"):
|
||
_log.info("单条素材上传:%s → %s(%s)", account, res.get("file"),
|
||
res.get("action"))
|
||
return jsonify(res), (200 if res.get("ok") else 400)
|
||
|
||
|
||
@bp.route("/api/af/roster/<row_id>", methods=["PUT"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_roster_update(row_id):
|
||
"""**编辑一行账号库**:改昵称 / **切换所属设备**(`device_name`,= 重新登记)/ 抖音号。
|
||
|
||
用户原话:"账号还可以切换它所属的设备,切换的话,我就会重新登记" —— 改完
|
||
下一次跑就按新的设备激活(`devices_for_names` / 计划解析都现查这里)。
|
||
"""
|
||
from core.models import db, DeviceAccount
|
||
from core import device_pool
|
||
import core.video_plan as vp
|
||
row = DeviceAccount.query.get(row_id)
|
||
if not row:
|
||
return jsonify({"ok": False, "error": "账号库里没有这一行"}), 404
|
||
data = request.get_json(silent=True) or {}
|
||
if "nickname" in data:
|
||
nick = (data.get("nickname") or "").strip()
|
||
if not nick:
|
||
return jsonify({"ok": False, "error": "昵称不能为空"}), 400
|
||
err = vp.name_error(nick)
|
||
if err:
|
||
return jsonify({"ok": False, "error": "昵称不合法:%s(不许含下划线、不许纯数字)" % err}), 400
|
||
row.nickname = nick[:80]
|
||
if "device_name" in data:
|
||
dev = (data.get("device_name") or "").strip()
|
||
# 允许把"所属设备"清空(未登记);填了就必须是设备池里的名字
|
||
if dev:
|
||
try:
|
||
if not device_pool.serial_of(dev):
|
||
return jsonify({"ok": False,
|
||
"error": "设备池里没有『%s』这个名字" % dev}), 400
|
||
except Exception:
|
||
pass
|
||
row.device_name = dev[:80]
|
||
if "douyin_id" in data:
|
||
row.douyin_id = (data.get("douyin_id") or "").strip()[:64]
|
||
if "account_status" in data:
|
||
# 账号状态:手改(正常/账号异常/限流…);任务里「读取文字」写
|
||
# 变量 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
|
||
if "manual_status" in data:
|
||
# 人工标记:和自动检测的 account_status 分开存;展示/通知/对外 API 里优先。
|
||
# 传空串 = 清除人工标记,回落到自动状态。
|
||
old_manual = (row.manual_status or "").strip()
|
||
row.manual_status = (data.get("manual_status") or "").strip()[:80]
|
||
if row.manual_status != old_manual:
|
||
_log.info("账号人工标记:『%s』%s → %s", row.nickname,
|
||
old_manual or "(未标记)", row.manual_status or "(清除)")
|
||
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)
|
||
return jsonify({"ok": True, "row": row.to_dict(), "msg": "已更新(下次跑按新的登记来)"})
|
||
|
||
|
||
# ==================== 设备与账号层 ====================
|
||
|
||
@bp.route("/api/af/devices")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_devices():
|
||
return jsonify({"ok": True, "devices": af.list_devices()})
|
||
|
||
|
||
@bp.route("/api/af/probe", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_probe():
|
||
"""实时探测每台在线设备当前登着哪个账号(跳过节忙设备)。"""
|
||
data = request.json or {}
|
||
serials = data.get("serials") or None
|
||
rows = af.probe_devices(serials)
|
||
_log.info("流水线探测当前账号:%d 台", len(rows))
|
||
return jsonify({"ok": True, "devices": rows})
|
||
|
||
|
||
# ==================== 账号库(名字 → 哪台手机)====================
|
||
# 用户场景:"输入几个视频,**只有名字对应的那台手机才激活任务**"。
|
||
# 靠这张表把「账号名 ↔ 设备号」存下来(表见 core/models.DeviceAccount),不用每次去探测。
|
||
|
||
@bp.route("/api/af/roster")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_roster():
|
||
"""**账号库**全量 + 按设备分组。每行带 `serial/pooled/online`(按设备名挂上设备池的实际地址)。
|
||
|
||
页面用 `/api/af/roster/resolve` 做预览;`groups` 直接就是"这台手机登着哪几个号"。
|
||
"""
|
||
rows = af.roster_rows()
|
||
groups = {}
|
||
for r in rows:
|
||
groups.setdefault((r.get("device_name") or "").strip() or "(未指定设备)", []).append(r)
|
||
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"])
|
||
def api_account_pool_accounts():
|
||
"""**账号池**(账号库)只读列表:给其他应用看"池子里有哪些号、在哪台手机"。
|
||
|
||
鉴权:`X-Account-Token: <token>` 或 `Authorization: Bearer <token>`
|
||
(令牌在「资产管理 → 🔑 账号池 API」里查看/重置)。
|
||
|
||
可选过滤:`?device=A11`、`?q=锋哥`、`?status=账号异常`(按**有效状态**,
|
||
人工标记优先)、`?manual=账号异常`(只看某个/任意人工标记)、`?online=1`。
|
||
"""
|
||
if request.method == "OPTIONS":
|
||
return _pool_json({"ok": True})
|
||
real = _pool_token()
|
||
got = _pool_req_token()
|
||
if not got or not hmac.compare_digest(got, real):
|
||
_log.warning("账号池 API 鉴权失败(来源 %s)", request.remote_addr)
|
||
return _pool_json({"ok": False, "error": "unauthorized"}, 401)
|
||
|
||
device = (request.args.get("device") or "").strip()
|
||
q = (request.args.get("q") or "").strip().lower()
|
||
status = (request.args.get("status") or "").strip()
|
||
manual = (request.args.get("manual") or "").strip()
|
||
only_online = (request.args.get("online") or "").strip().lower() in ("1", "true", "yes")
|
||
rows = af.roster_rows()
|
||
out = []
|
||
for r in rows:
|
||
if device and (r.get("device_name") or "") != device:
|
||
continue
|
||
eff = (r.get("effective_status") or r.get("account_status") or "").strip()
|
||
if status and eff != status:
|
||
continue
|
||
man = (r.get("manual_status") or "").strip()
|
||
if manual:
|
||
if manual == "1":
|
||
if not man:
|
||
continue
|
||
elif man != manual:
|
||
continue
|
||
if only_online and not r.get("online"):
|
||
continue
|
||
if q and q not in (r.get("nickname") or "").lower() \
|
||
and q not in (r.get("douyin_id") or "").lower():
|
||
continue
|
||
out.append({
|
||
"id": r.get("id") or "",
|
||
"nickname": r.get("nickname") or "",
|
||
"douyin_id": r.get("douyin_id") or "",
|
||
"device_name": r.get("device_name") or "",
|
||
"serial": r.get("serial") or "",
|
||
"phone": r.get("phone") or "",
|
||
"online": bool(r.get("online")),
|
||
"pooled": bool(r.get("pooled")),
|
||
"account_status": r.get("account_status") or "",
|
||
"manual_status": r.get("manual_status") or "",
|
||
"effective_status": eff,
|
||
"can_post_video": bool(r.get("can_post_video")),
|
||
"note": r.get("note") or "",
|
||
"updated_at": r.get("updated_at") or "",
|
||
})
|
||
return _pool_json({"ok": True, "total": len(out), "total_all": len(rows),
|
||
"server_time": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||
"accounts": out})
|
||
|
||
|
||
@bp.route("/api/account_pool/token")
|
||
@admin_required
|
||
def api_account_pool_token():
|
||
"""管理端:查看账号池 API 令牌(仅管理员;页面「资产 → 🔑 账号池 API」)。"""
|
||
tok = _pool_token()
|
||
return jsonify({"ok": True, "token": tok,
|
||
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
|
||
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts"})
|
||
|
||
|
||
@bp.route("/api/account_pool/token/reset", methods=["POST"])
|
||
@admin_required
|
||
def api_account_pool_token_reset():
|
||
"""管理端:重置账号池 API 令牌(旧令牌立即失效)。"""
|
||
tok = secrets.token_urlsafe(24)
|
||
meta_set(_K_POOL_TOKEN, tok)
|
||
meta_set(_K_POOL_TOKEN_AT, time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
_log.info("账号池 API 令牌已重置 by %s", getattr(current_user, "username", ""))
|
||
return jsonify({"ok": True, "token": tok,
|
||
"token_created_at": meta_get(_K_POOL_TOKEN_AT) or "",
|
||
"url": request.host_url.rstrip("/") + "/api/account_pool/accounts",
|
||
"msg": "令牌已重置(旧令牌立即失效)"})
|
||
|
||
|
||
@bp.route("/api/af/roster/import", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_roster_import():
|
||
"""**粘贴导入账号库**:`{"text": "A01\\t账号名\\t抖音号\\n…", "dry_run": true}`。
|
||
|
||
每行三段(设备号 / 账号名 / 抖音号;制表符或空格都行,不用表头)。
|
||
**按抖音号认同一行** —— 改名字不会变成两条;库里多出来的**一条都不删**(回在 `stale` 里让页面提示)。
|
||
`dry_run=true` 只告诉你会改成什么样,不写库。
|
||
"""
|
||
data = request.json or {}
|
||
text = data.get("text") or ""
|
||
if not (text or "").strip():
|
||
return jsonify({"ok": False, "error": "没内容 —— 把表格里的行粘进来"}), 400
|
||
res = af.import_roster(text, dry_run=bool(data.get("dry_run")))
|
||
if res.get("error"):
|
||
return jsonify({"ok": False, "error": res["error"]}), 500
|
||
_log.info("账号库导入%s:新增 %s / 更新 %s / 没变 %s / 库里多出来 %s",
|
||
"(预演)" if res.get("dry_run") else "", res["added"], res["updated"],
|
||
res["unchanged"], len(res["stale"]))
|
||
return jsonify({"ok": True, "result": res, "rows": af.roster_rows()})
|
||
|
||
|
||
@bp.route("/api/af/roster/resolve", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_roster_resolve():
|
||
"""**只算不跑**:一批名字 → 哪几台手机会被激活、哪些不行(页面预览 / 按名字跑之前先看)。
|
||
|
||
`{"names": ["账号甲", "账号乙"]}`(也可以是换行分隔的一整段文本)
|
||
→ 每行 `{name, device_name, serial, online, pooled, reason}`;`reason` 非空 = 这个名字跑不了。
|
||
"""
|
||
data = request.json or {}
|
||
names = data.get("names")
|
||
if isinstance(names, str):
|
||
names = [s.strip() for s in names.splitlines() if s.strip()]
|
||
rows = af.devices_for_names(names or [])
|
||
ok = [r for r in rows if not r.get("reason")]
|
||
return jsonify({"ok": True, "rows": rows, "runnable": len(ok),
|
||
"serial_of": {r["name"]: r["serial"] for r in ok}})
|
||
|
||
|
||
@bp.route("/api/af/account/<name>", methods=["DELETE"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_account_delete(name):
|
||
"""**从资产管理删除一个账号**(页面行内「删除」)。
|
||
|
||
JSON:`{"delete_roster":true,"archive_dir":true,"delete_records":false}`
|
||
· delete_roster 删账号库登记;
|
||
· archive_dir 把账号素材文件夹**移到 `_已删除/`**(不永久删原件);
|
||
· delete_records 删平台素材/发布记录行。
|
||
"""
|
||
data = request.get_json(silent=True) or {}
|
||
res = af.delete_account(
|
||
name,
|
||
delete_roster=bool(data.get("delete_roster", True)),
|
||
archive_dir=bool(data.get("archive_dir")),
|
||
delete_records=bool(data.get("delete_records")),
|
||
prof=_profile_params())
|
||
return jsonify(res), (200 if res.get("ok") else 400)
|
||
|
||
|
||
@bp.route("/api/af/roster/<row_id>", methods=["DELETE"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_roster_delete(row_id):
|
||
"""删一行账号库。**只有这里会删账号库** —— 导入永远不删(删数据不可逆)。"""
|
||
if not af.delete_roster_row(row_id):
|
||
return jsonify({"ok": False, "error": "没有这一行"}), 404
|
||
_log.info("账号库删除一行:%s", row_id)
|
||
return jsonify({"ok": True, "rows": af.roster_rows()})
|
||
|
||
|
||
# ==================== App 注册表(动作层的一半)====================
|
||
|
||
@bp.route("/api/af/apps")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_apps_list():
|
||
return jsonify({"ok": True, "apps": af.list_apps()})
|
||
|
||
|
||
@bp.route("/api/af/apps", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_apps_create():
|
||
from core.models import db, AeApp
|
||
data = request.json or {}
|
||
name = (data.get("name") or "").strip()
|
||
package = (data.get("package") or "").strip()
|
||
if not name or not package:
|
||
return jsonify({"ok": False, "error": "App 名称与包名都要填"}), 400
|
||
row = AeApp(id=uuid.uuid4().hex[:8], name=name[:80], package=package[:120],
|
||
home_selector_type=(data.get("home_selector_type") or "xpath")[:32],
|
||
home_selector_value=(data.get("home_selector_value") or "")[:500],
|
||
home_what=(data.get("home_what") or "")[:80],
|
||
launch_timeout=int(data.get("launch_timeout") or 40),
|
||
note=(data.get("note") or "")[:500],
|
||
created_at=time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
db.session.add(row)
|
||
db.session.commit()
|
||
_log.info("新增 App:%s(%s)", row.name, row.package)
|
||
return jsonify({"ok": True, "msg": "已新增 App", "app": row.to_dict()})
|
||
|
||
|
||
@bp.route("/api/af/apps/<app_id>", methods=["PUT"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_apps_update(app_id):
|
||
from core.models import db, AeApp
|
||
row = AeApp.query.get(app_id)
|
||
if not row:
|
||
return jsonify({"ok": False, "error": "App 不存在"}), 404
|
||
data = request.json or {}
|
||
for k, limit in (("name", 80), ("package", 120), ("home_selector_type", 32),
|
||
("home_selector_value", 500), ("home_what", 80), ("note", 500)):
|
||
if k in data:
|
||
setattr(row, k, (data.get(k) or "")[:limit])
|
||
if "launch_timeout" in data:
|
||
row.launch_timeout = int(data.get("launch_timeout") or 40)
|
||
db.session.commit()
|
||
return jsonify({"ok": True, "msg": "已保存", "app": row.to_dict()})
|
||
|
||
|
||
@bp.route("/api/af/apps/<app_id>/opening", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_app_opening(app_id):
|
||
"""给某个 App **一键新建(或取回)开场动作**。
|
||
|
||
开场动作 = 跑一轮前把设备统一置成初始状态的那组步骤:亮屏 → 结束App → 打开App → 等首页 → 切到目标号。
|
||
步骤由服务端预填(这样能带上 `.env` 里的切号入口选择器),建完可以随便改。
|
||
"""
|
||
from core.models import db, AeApp, CustomAction
|
||
row = AeApp.query.get(app_id)
|
||
if not row:
|
||
return jsonify({"ok": False, "error": "App 不存在"}), 404
|
||
app_d = row.to_dict()
|
||
old = (CustomAction.query
|
||
.filter(CustomAction.kind == "opening", CustomAction.app_id == app_id)
|
||
.order_by(CustomAction.created_at.desc()).first())
|
||
if old:
|
||
return jsonify({"ok": True, "msg": "这个 App 已经有开场动作了", "action": old.to_dict()})
|
||
act = CustomAction(id=uuid.uuid4().hex[:8], name="开场:%s" % (app_d.get("name") or "App"),
|
||
icon="🚀", kind="opening", app_id=app_id,
|
||
created_at=time.strftime("%Y-%m-%d %H:%M:%S"))
|
||
act.set_steps(af.default_opening_steps(app_d))
|
||
db.session.add(act)
|
||
db.session.commit()
|
||
_log.info("新建开场动作:%s → %s", app_d.get("name"), act.id)
|
||
return jsonify({"ok": True, "msg": "已新建开场动作(步骤已预填,可继续编辑)",
|
||
"action": act.to_dict()})
|
||
|
||
|
||
@bp.route("/api/af/apps/<app_id>", methods=["DELETE"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_apps_delete(app_id):
|
||
from core.models import db, AeApp, CustomAction
|
||
row = AeApp.query.get(app_id)
|
||
if not row:
|
||
return jsonify({"ok": False, "error": "App 不存在"}), 404
|
||
used = CustomAction.query.filter(CustomAction.app_id == app_id).count()
|
||
if used:
|
||
return jsonify({"ok": False,
|
||
"error": "还有 %d 个动作归属这个 App,先把它们改到别的 App(或删掉)" % used}), 400
|
||
db.session.delete(row)
|
||
db.session.commit()
|
||
return jsonify({"ok": True, "msg": "已删除"})
|
||
|
||
|
||
# ==================== 跑一轮 ====================
|
||
|
||
@bp.route("/api/af/run", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_run():
|
||
"""多选账号跑一轮(每个账号一条后台线程)。
|
||
|
||
请求:`{"accounts": ["账号A", "账号B"], "action_id": "...", "date": "", "serials": {账号: serial}?}`
|
||
立刻返回 run_id 列表;跑的过程与结果看 `/api/af/runs`。
|
||
"""
|
||
data = request.json or {}
|
||
action_id = (data.get("action_id") or "").strip()
|
||
date = (data.get("date") or "").strip()
|
||
prof = _profile_params()
|
||
mode = (data.get("mode") or (prof.get("fleet") or {}).get("run_mode") or "by_account")
|
||
if not action_id:
|
||
return jsonify({"ok": False, "error": "没选动作(动作库里挑一个)"}), 400
|
||
# **动身前就校验**:开场动作/内置动作不能当业务组用、必须归属 App ——
|
||
# 否则要等后台线程跑起来才在运行记录里报错(用户点了没反应,容易误以为"跑起来了")。
|
||
from core.models import CustomAction as _CA
|
||
_act = _CA.query.get(action_id)
|
||
if not _act:
|
||
return jsonify({"ok": False, "error": "动作不存在(可能刚被删了)"}), 400
|
||
if (_act.kind or "") in ("opening", "builtin"):
|
||
return jsonify({"ok": False,
|
||
"error": "『%s』是%s动作,不能当业务动作组用 —— 请选一个业务动作组"
|
||
% (_act.name, "开场" if _act.kind == "opening" else "内置")}), 400
|
||
if not (_act.app_id or ""):
|
||
return jsonify({"ok": False,
|
||
"error": "动作『%s』还没归属 App(到「③ 动作」里给它选一个)" % _act.name}), 400
|
||
|
||
started = []
|
||
if mode == "by_device":
|
||
# **按设备**:勾几台设备 → 每台一条运行,**同时跑**(每台先跑开场动作把状态统一)
|
||
devices = data.get("devices") or []
|
||
if not devices:
|
||
return jsonify({"ok": False, "error": "没选设备"}), 400
|
||
for d in devices:
|
||
serial = (d.get("serial") or "").strip() if isinstance(d, dict) else str(d or "").strip()
|
||
raw = (d.get("accounts") if isinstance(d, dict) else None) or []
|
||
if isinstance(raw, str):
|
||
raw = [x for x in raw.replace(",", ",").split(",") if x.strip()]
|
||
accounts = [str(x).strip() for x in raw if str(x).strip()]
|
||
if not serial:
|
||
continue
|
||
if not accounts:
|
||
started.append({"serial": serial, "accounts": [], "run_id": "",
|
||
"error": "这台没给要跑的账号:先在「探测当前登录账号」或手工填(可多个,逗号分隔)"})
|
||
continue
|
||
run_id = uuid.uuid4().hex[:12]
|
||
|
||
def _bg_dev(accs=accounts, run_id=run_id, serial=serial):
|
||
try:
|
||
# 按设备:一台机器 + 它负责的几个账号,逐个"就绪 → 发完"
|
||
af.run_device_once(serial, accs, action_id=action_id, profile=prof,
|
||
date=date, run_id=run_id)
|
||
except Exception as e:
|
||
_log.warning("流水线(按设备)线程异常(%s): %s", serial, e)
|
||
|
||
threading.Thread(target=_bg_dev, daemon=True).start()
|
||
started.append({"serial": serial, "accounts": accounts, "run_id": run_id})
|
||
_log.info("流水线触发(按设备):%d 台,动作 %s", len(started), action_id)
|
||
return jsonify({"ok": True,
|
||
"msg": "已触发 %d 台设备(各自先跑开场动作,再跑动作组)" % len(started),
|
||
"runs": started})
|
||
|
||
# **按账号**:勾几个账号 → 谁登着这个号谁跑(一台机器跑多个号时跑在同一台机上)
|
||
accounts = [a for a in (data.get("accounts") or []) if (a or "").strip()]
|
||
serials = data.get("serials") or {}
|
||
if not accounts:
|
||
return jsonify({"ok": False, "error": "没选账号"}), 400
|
||
for acc in accounts:
|
||
run_id = uuid.uuid4().hex[:12]
|
||
serial = (serials.get(acc) or "").strip() if isinstance(serials, dict) else ""
|
||
|
||
def _bg(acc=acc, run_id=run_id, serial=serial):
|
||
try:
|
||
af.run_account_once(acc, action_id=action_id, profile=prof,
|
||
serial=serial or None, date=date, run_id=run_id)
|
||
except Exception as e: # 兜底:线程异常别静默
|
||
_log.warning("流水线跑一轮线程异常(%s): %s", acc, e)
|
||
|
||
threading.Thread(target=_bg, daemon=True).start()
|
||
started.append({"account": acc, "run_id": run_id, "serial": serial})
|
||
_log.info("流水线触发:%d 个账号,动作 %s", len(started), action_id)
|
||
return jsonify({"ok": True, "msg": "已触发 %d 个账号(跑完看「运行与日志」)" % len(started),
|
||
"runs": started})
|
||
|
||
|
||
@bp.route("/api/af/try", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_try():
|
||
"""**单独试跑一个动作**(测"切账号"这类动作用)。
|
||
|
||
请求:`{"serial": "...", "action_id": "...", "target_name": "要切到的账号"}`
|
||
`target_name` 会作为运行期变量 `{本次要发的名字}` 注入 —— 动作里点列表那一行、
|
||
条件判断的候选值来源都用它。后台线程跑,立刻返回 run_id;明细看 `/api/af/run/<id>`。
|
||
"""
|
||
data = request.json or {}
|
||
serial = (data.get("serial") or "").strip()
|
||
action_id = (data.get("action_id") or "").strip()
|
||
target = (data.get("target_name") or "").strip()
|
||
if not serial:
|
||
return jsonify({"ok": False, "error": "先选一台设备"}), 400
|
||
if not action_id:
|
||
return jsonify({"ok": False, "error": "先选一个动作"}), 400
|
||
run_id = uuid.uuid4().hex[:12]
|
||
|
||
def _bg():
|
||
try:
|
||
af.run_action_try(serial, action_id, target_name=target, run_id=run_id)
|
||
except Exception as e:
|
||
_log.warning("试跑线程异常: %s", e)
|
||
|
||
threading.Thread(target=_bg, daemon=True).start()
|
||
_log.info("流水线试跑:%s @ %s(要切的号=%s)", action_id, serial, target or "(空)")
|
||
return jsonify({"ok": True, "run_id": run_id, "msg": "已在 %s 上试跑(看「运行与日志」的明细)" % serial})
|
||
|
||
|
||
@bp.route("/api/af/runs")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_runs():
|
||
from core.models import AeRun
|
||
q = AeRun.query
|
||
if request.args.get("account"):
|
||
q = q.filter(AeRun.account == request.args["account"].strip())
|
||
if request.args.get("date"):
|
||
q = q.filter(AeRun.date == request.args["date"].strip())
|
||
if request.args.get("status"):
|
||
q = q.filter(AeRun.status == request.args["status"].strip())
|
||
rows = q.order_by(AeRun.started_at.desc()).limit(int(request.args.get("limit") or 200)).all()
|
||
return jsonify({"ok": True, "runs": [r.to_dict() for r in rows]})
|
||
|
||
|
||
@bp.route("/api/af/run/<run_id>")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_run_detail(run_id):
|
||
"""该轮的步骤明细(复用现有 `task_step_log`,按 run_id 查)。"""
|
||
from core import step_log
|
||
from core.models import AeRun
|
||
row = AeRun.query.get(run_id)
|
||
if not row:
|
||
return jsonify({"ok": False, "error": "运行记录不存在"}), 404
|
||
rows, total = step_log.query(run_id=run_id, limit=1000, offset=0)
|
||
steps = [{"time": r.created_at, "step_path": r.step_path, "label": r.step_label,
|
||
"type": r.step_type, "selector": r.selector, "result": r.result,
|
||
"detail": r.detail, "ms": r.duration_ms} for r in rows]
|
||
return jsonify({"ok": True, "run": row.to_dict(), "steps": steps, "total": total})
|
||
|
||
|
||
@bp.route("/api/af/log")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_log():
|
||
"""下载账号文件夹里的日志文件(CSV/MD/PNG)。`?account=&date=&name=`。"""
|
||
from core import account_log
|
||
account = (request.args.get("account") or "").strip()
|
||
date = (request.args.get("date") or "").strip()
|
||
name = (request.args.get("name") or "").strip()
|
||
if not (account and date and name):
|
||
return jsonify({"ok": False, "error": "account/date/name 都要给"}), 400
|
||
data, err = account_log.read_file(account, date, name)
|
||
if data is None:
|
||
return jsonify({"ok": False, "error": err}), 404
|
||
mime = ("image/png" if name.endswith(".png")
|
||
else ("text/markdown; charset=utf-8" if name.endswith(".md")
|
||
else "text/csv; charset=utf-8"))
|
||
return send_file(__import__("io").BytesIO(data), as_attachment=True,
|
||
download_name=name, mimetype=mime)
|
||
|
||
|
||
@bp.route("/api/af/logs")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_logs_list():
|
||
"""列某账号 `_日志/` 下的文件(页面「打开目录」用)。`?account=&date=`。"""
|
||
from core import account_log
|
||
account = (request.args.get("account") or "").strip()
|
||
if not account:
|
||
return jsonify({"ok": False, "error": "缺少 account"}), 400
|
||
return jsonify({"ok": True, "files": account_log.list_files(account,
|
||
(request.args.get("date") or "").strip())})
|
||
|
||
|
||
# ==================== 计划调度(2026-10-17 新增)====================
|
||
# 一条计划 = "接下来这段时间,让电脑完成我这一批次的任务"(见 doc/ACCOUNT_FOLDER.md §4.7)。
|
||
# 干什么/给谁干/发什么/什么时候/怎么跑 —— 五件事都写全,外加"发布前准备"(自动检测 + 需要才切号)。
|
||
# 执行完全复用现成链路:内存 TaskJob → TaskManager.run_adhoc → 单设备互斥/错峰/重试/通知。
|
||
|
||
@bp.route("/api/af/plans")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plans():
|
||
from core import plan as plan_mod
|
||
return jsonify({"ok": True, "plans": plan_mod.list_plans()})
|
||
|
||
|
||
@bp.route("/api/af/plans", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plans_create():
|
||
"""新建计划(字段见 `core/plan.py::DEFAULT_PLAN`);`id` 传了就是更新。"""
|
||
from core import plan as plan_mod
|
||
data = request.get_json(silent=True) or {}
|
||
res = plan_mod.save_plan(data, (data.get("id") or "").strip())
|
||
if not res.get("ok"):
|
||
return jsonify(res), 400
|
||
_log.info("计划已保存:%s(%s)", data.get("name"), res["id"])
|
||
return jsonify({"ok": True, "id": res["id"], "plan": plan_mod.get_plan(res["id"]),
|
||
"warning": res.get("warning") or ""})
|
||
|
||
|
||
@bp.route("/api/af/plan/<plan_id>", methods=["PUT"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_update(plan_id):
|
||
from core import plan as plan_mod
|
||
res = plan_mod.save_plan(request.get_json(silent=True) or {}, plan_id)
|
||
if not res.get("ok"):
|
||
return jsonify(res), 400
|
||
return jsonify({"ok": True, "plan": plan_mod.get_plan(plan_id),
|
||
"warning": res.get("warning") or ""})
|
||
|
||
|
||
@bp.route("/api/af/plan/<plan_id>", methods=["DELETE"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_delete(plan_id):
|
||
from core import plan as plan_mod
|
||
if not plan_mod.delete_plan(plan_id):
|
||
return jsonify({"ok": False, "error": "计划不存在"}), 404
|
||
_log.info("计划已删除:%s", plan_id)
|
||
return jsonify({"ok": True, "msg": "计划已删除"})
|
||
|
||
|
||
@bp.route("/api/af/plan/<plan_id>/toggle", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_toggle(plan_id):
|
||
from core import plan as plan_mod
|
||
enabled = bool((request.get_json(silent=True) or {}).get("enabled", True))
|
||
d = plan_mod.toggle_plan(plan_id, enabled)
|
||
if d is None:
|
||
return jsonify({"ok": False, "error": "计划不存在"}), 404
|
||
return jsonify({"ok": True, "plan": d, "msg": "计划已%s" % ("启用" if enabled else "停用")})
|
||
|
||
|
||
@bp.route("/api/af/plan/<plan_id>/preview", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_preview(plan_id):
|
||
"""**只算不跑**:这条计划现在"会激活哪几台手机、哪些号跑不了"(给页面预览/试跑前看)。
|
||
|
||
走的就是触发时的同一段逻辑(`plan.resolve_targets`),所以看到的 = 真跑的。
|
||
"""
|
||
from core import plan as plan_mod
|
||
d = plan_mod.get_plan(plan_id)
|
||
if not d:
|
||
return jsonify({"ok": False, "error": "计划不存在"}), 404
|
||
data = request.get_json(silent=True) or {}
|
||
if data.get("accounts"):
|
||
d = {**d, "accounts": [s.strip() for s in data["accounts"] if str(s).strip()]}
|
||
t = plan_mod.resolve_targets(d)
|
||
return jsonify({"ok": True, "devices": t["devices"], "skipped": t["skipped"],
|
||
"planned": t["planned"], "warning": plan_mod.validate_plan(d)})
|
||
|
||
|
||
@bp.route("/api/af/plan/<plan_id>/run", methods=["POST"])
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_run(plan_id):
|
||
"""跑一次:`{live: true|false, dry_run, accounts:[...]}`。
|
||
|
||
· `dry_run=true`(或 `live=false`):**只预检不跑**(等价 preview);
|
||
· `accounts=["号甲"]`:**试跑** —— 只跑这几个号(其余不动),触发方式记 `try`。
|
||
"""
|
||
from core import plan as plan_mod
|
||
data = request.get_json(silent=True) or {}
|
||
if data.get("dry_run") or data.get("live") is False:
|
||
d = plan_mod.get_plan(plan_id)
|
||
if not d:
|
||
return jsonify({"ok": False, "error": "计划不存在"}), 404
|
||
t = plan_mod.resolve_targets(d)
|
||
return jsonify({"ok": True, "dry_run": True, "devices": t["devices"],
|
||
"skipped": t["skipped"], "warning": plan_mod.validate_plan(d)})
|
||
only = [str(s).strip() for s in (data.get("accounts") or []) if str(s).strip()]
|
||
res = plan_mod.run_plan(plan_id, trigger=("try" if only else "manual"),
|
||
only_accounts=only or None)
|
||
if not res.get("ok"):
|
||
return jsonify(res), 409
|
||
return jsonify(res)
|
||
|
||
|
||
@bp.route("/api/af/plan_runs")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_runs():
|
||
from core import plan as plan_mod
|
||
return jsonify({"ok": True,
|
||
"runs": plan_mod.list_plan_runs((request.args.get("plan_id") or "").strip(),
|
||
int(request.args.get("limit") or 100))})
|
||
|
||
|
||
@bp.route("/api/af/plan_run/<run_id>")
|
||
@perm_required(PERM_DEVICES)
|
||
def api_af_plan_run_detail(run_id):
|
||
"""某次计划运行的明细:每账号的结局 + 原因 + 该账号那一轮 `ae_run`(点进去看步骤)。"""
|
||
from core import plan as plan_mod
|
||
d = plan_mod.get_plan_run(run_id)
|
||
if not d:
|
||
return jsonify({"ok": False, "error": "没有这次运行"}), 404
|
||
return jsonify({"ok": True, "run": d})
|