feat(流水线): 资产管理 + 计划编排 + 运行监测 + 切号/发布修复
- 流水线收口为四栏:资产管理 / 动作 / 计划调度 / 运行监测 - 资产管理:账号总表与设备筛选、素材 13 列、模板批量导入(数量+文件名校验)、 单条上传、删除账号(归档不删原件)、发布记录 - 计划调度:segments 多动作组/任务编排(发布素材/循环/条件/回主页)、 内置切号可见可编辑、每账号切号前亮屏 - 运行监测:计划/账号/设备三维度、按需截图、按账号拆分显示 - 修复:图片相册索引误报、切号重试与重复点「我」、发布任务校验跳过、 多号同机假账号目录、编辑器 expect_el 未声明变量 - 文档与测试同步(14/14)
This commit is contained in:
@@ -0,0 +1,220 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""账号文件夹的**日志落盘**:跑完一轮后,把该账号这一轮的操作日志写进它的账号文件夹。
|
||||
|
||||
为什么要落盘:库里的 `task_step_log` 是给**页面**查的;用户还要"**翻文件夹**就能回查
|
||||
每台手机干了什么"。两份数据**同源**(都来自 `step_log.query(run_id=...)`),不是两条链路
|
||||
—— 所以这里只做"把已有明细写成文件",不额外记一套日志。
|
||||
|
||||
目录约定(根目录由 `config.DATA_ACCOUNT_DIR` 决定):
|
||||
|
||||
<根>/<账号>/_日志/<YYYY-MM-DD>/
|
||||
run_<run_id>.csv 每一步一行(UTF-8 BOM,Excel 直接打开不乱码)
|
||||
run_<run_id>.md 人看的汇总(账号/设备/动作/条目结果/链接/失败原因)
|
||||
shot_<HHMMSS>_<tag>.png 失败现场截图(只在非 done 时截)
|
||||
|
||||
**红线:这里只往 `<账号>/_日志/` 写文件,绝不碰账号目录里的素材原件。**
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
_LOG_DIR = "_日志" # 日志子目录(扫描时会跳过它)
|
||||
_KEEP_SEG = re.compile(r'[\\/:*?"<>|\x00-\x1f]+')
|
||||
|
||||
|
||||
def account_root():
|
||||
"""账号根目录。**每次现取** —— 这样测试改 `config.ACCOUNT_DIR` 就能生效。"""
|
||||
import config
|
||||
return config.ACCOUNT_DIR
|
||||
|
||||
|
||||
def safe_seg(name):
|
||||
"""账号名 → 可安全做目录段的名字。
|
||||
|
||||
挡住路径分隔符与 Windows 非法字符(`\\ / : * ? " < > |`)与控制字符,压掉 `..`,
|
||||
末尾的点和空格也去掉(Windows 上会咬人)。**中文与空格保留**(账号名本身就长这样)。
|
||||
"""
|
||||
s = _KEEP_SEG.sub("_", (name or "").strip())
|
||||
s = s.replace("..", "_").strip(" .")
|
||||
return s[:80] or "_"
|
||||
|
||||
|
||||
def account_dir(account, create=False):
|
||||
"""`<根>/<账号>/`。"""
|
||||
d = os.path.join(account_root(), safe_seg(account))
|
||||
if create:
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def run_dir(account, date, create=False):
|
||||
"""`<根>/<账号>/_日志/<日期>/`。"""
|
||||
d = os.path.join(account_dir(account), _LOG_DIR, (date or "")[:10] or "unknown")
|
||||
if create:
|
||||
os.makedirs(d, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def write_csv(account, date, run_id, rows, create=True):
|
||||
"""把该轮每一步写成 CSV。列口径与「日志 → 步骤明细」导出一致(Excel 友好)。
|
||||
|
||||
`rows` 是 `step_log.query(run_id=...)` 返回的 ORM 行(按时间正序)。
|
||||
返回落盘路径;失败返回 ""。
|
||||
"""
|
||||
d = run_dir(account, date, create=create)
|
||||
path = os.path.join(d, "run_%s.csv" % (run_id or "unknown"))
|
||||
try:
|
||||
buf = io.StringIO()
|
||||
w = csv.writer(buf)
|
||||
w.writerow(["时间", "设备", "设备名", "账号", "运行ID", "步骤路径", "步骤",
|
||||
"类型", "选择器", "结果", "耗时(ms)", "详情"])
|
||||
for r in rows or []:
|
||||
w.writerow([getattr(r, "created_at", ""), getattr(r, "serial", ""),
|
||||
getattr(r, "device_name", ""), getattr(r, "account", ""),
|
||||
getattr(r, "run_id", ""), getattr(r, "step_path", ""),
|
||||
getattr(r, "step_label", ""), getattr(r, "step_type", ""),
|
||||
getattr(r, "selector", ""), getattr(r, "result", ""),
|
||||
getattr(r, "duration_ms", ""), getattr(r, "detail", "")])
|
||||
# utf-8-sig = UTF-8 带 BOM:不加的话 Excel 打开中文是乱码(这文件就是给人翻的)
|
||||
with open(path, "wb") as f:
|
||||
f.write(buf.getvalue().encode("utf-8-sig"))
|
||||
return path
|
||||
except Exception as e:
|
||||
_warn("写 CSV 失败(%s): %s" % (path, e))
|
||||
return ""
|
||||
|
||||
|
||||
def write_summary(account, date, run_id, info, create=True):
|
||||
"""写人看的汇总 md:这一轮是谁、在哪台设备、用的哪个动作、每条结果如何。"""
|
||||
d = run_dir(account, date, create=create)
|
||||
path = os.path.join(d, "run_%s.md" % (run_id or "unknown"))
|
||||
try:
|
||||
info = info or {}
|
||||
lines = ["# 账号文件夹流水线 · 运行汇总", ""]
|
||||
lines.append("- 账号:**%s**" % (account or ""))
|
||||
lines.append("- 日期:%s" % (date or ""))
|
||||
lines.append("- 设备:%s(%s)" % (info.get("device_name") or "-", info.get("serial") or "-"))
|
||||
lines.append("- App:%s" % (info.get("app") or "-"))
|
||||
lines.append("- 动作:%s" % (info.get("action") or "-"))
|
||||
lines.append("- 结果:**%s**" % (info.get("status") or "-"))
|
||||
lines.append("- 开始:%s 结束:%s" % (info.get("started_at") or "-", info.get("finished_at") or "-"))
|
||||
if info.get("error"):
|
||||
lines.append("- 失败原因:%s" % info["error"])
|
||||
t = info.get("totals") or {}
|
||||
if t:
|
||||
lines.append("- 条目:共 %s,已推 %s,已发 %s,失败 %s,未知 %s"
|
||||
% (t.get("items_total", 0), t.get("pushed", 0), t.get("published", 0),
|
||||
t.get("failed", 0), t.get("unknown", 0)))
|
||||
items = info.get("items") or []
|
||||
if items:
|
||||
lines += ["", "## 逐条结果", "",
|
||||
"| 编号 | 素材 | 标题 | 状态 | 分享链接 | 说明 |",
|
||||
"|---|---|---|---|---|---|"]
|
||||
for it in items:
|
||||
lines.append("| %s | %s | %s | %s | %s | %s |"
|
||||
% (it.get("seq", ""), it.get("file", ""),
|
||||
(it.get("title") or "")[:40], it.get("status", ""),
|
||||
it.get("share_url") or "", (it.get("note") or "")[:60]))
|
||||
lines += ["", "---", "",
|
||||
"步骤明细见同目录的 `run_%s.csv`;失败截图见 `shot_*.png`。" % (run_id or "")]
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines) + "\n")
|
||||
return path
|
||||
except Exception as e:
|
||||
_warn("写汇总失败(%s): %s" % (path, e))
|
||||
return ""
|
||||
|
||||
|
||||
def save_shot(account, date, png, tag="", create=True):
|
||||
"""把一张截图写进该账号的日志目录。返回路径;没有内容或失败返回 ""。"""
|
||||
if not png:
|
||||
return ""
|
||||
d = run_dir(account, date, create=create)
|
||||
tag = _KEEP_SEG.sub("_", str(tag or ""))[:40]
|
||||
name = "shot_%s%s.png" % (time.strftime("%H%M%S"), ("_" + tag) if tag else "")
|
||||
path = os.path.join(d, name)
|
||||
try:
|
||||
with open(path, "wb") as f:
|
||||
f.write(png)
|
||||
return path
|
||||
except Exception as e:
|
||||
_warn("写截图失败(%s): %s" % (path, e))
|
||||
return ""
|
||||
|
||||
|
||||
def list_files(account, date=""):
|
||||
"""列该账号 `_日志/` 下的文件(可按日期筛)。返回 [{date, name, size, mtime}]。"""
|
||||
base = os.path.join(account_dir(account), _LOG_DIR)
|
||||
out = []
|
||||
try:
|
||||
dates = [date] if date else sorted(os.listdir(base))
|
||||
for d in dates:
|
||||
dd = os.path.join(base, d)
|
||||
if not os.path.isdir(dd):
|
||||
continue
|
||||
for fn in sorted(os.listdir(dd)):
|
||||
fp = os.path.join(dd, fn)
|
||||
try:
|
||||
st = os.stat(fp)
|
||||
except OSError:
|
||||
continue
|
||||
out.append({"date": d, "name": fn, "size": st.st_size,
|
||||
"mtime": time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st.st_mtime))})
|
||||
except FileNotFoundError:
|
||||
return []
|
||||
except Exception as e:
|
||||
_warn("列日志文件失败(%s): %s" % (base, e))
|
||||
return out
|
||||
|
||||
|
||||
def read_file(account, date, name):
|
||||
"""读一个日志文件(下载用)。**双重防穿越**:目录段与文件名都必须是纯名字。"""
|
||||
if not name or os.path.basename(name) != name or "/" in name or "\\" in name:
|
||||
return None, "文件名不合法"
|
||||
if not date or os.path.basename(date) != date or "/" in date or "\\" in date:
|
||||
return None, "日期不合法"
|
||||
fp = os.path.join(run_dir(account, date), name)
|
||||
# 再兜一层:解析后必须仍在账号的 _日志 目录里
|
||||
real = os.path.realpath(fp)
|
||||
base = os.path.realpath(os.path.join(account_dir(account), _LOG_DIR))
|
||||
if not real.startswith(base + os.sep):
|
||||
return None, "路径越界"
|
||||
if not os.path.isfile(real):
|
||||
return None, "文件不存在"
|
||||
try:
|
||||
with open(real, "rb") as f:
|
||||
return f.read(), ""
|
||||
except Exception as e:
|
||||
return None, "读取失败:%s" % e
|
||||
|
||||
|
||||
def dump_run(account, date, run_id, info, rows=None, shot=None):
|
||||
"""一轮跑完的汇总入口:写 CSV + MD(+可选截图)。返回 {csv, md, shot} 路径。
|
||||
|
||||
`rows` 没传就自己按 `run_id` 去 `step_log` 查(页面「运行与日志」用的是同一条路)。
|
||||
"""
|
||||
files = {"csv": "", "md": "", "shot": ""}
|
||||
try:
|
||||
if rows is None:
|
||||
from core import step_log
|
||||
rows, _total = step_log.query(run_id=run_id, limit=2000, offset=0)
|
||||
rows = list(reversed(rows)) # 导出按时间正序(页面是倒序)
|
||||
files["csv"] = write_csv(account, date, run_id, rows)
|
||||
except Exception as e:
|
||||
_warn("查/写步骤明细失败(run=%s): %s" % (run_id, e))
|
||||
files["md"] = write_summary(account, date, run_id, info)
|
||||
if shot:
|
||||
files["shot"] = save_shot(account, date, shot, tag=(info or {}).get("serial", ""))
|
||||
return files
|
||||
|
||||
|
||||
def _warn(msg):
|
||||
"""日志落盘失败**绝不能影响任务结果**(写不进去就记一句)。"""
|
||||
try:
|
||||
from core.logger import get_logger
|
||||
get_logger("core.account_log").warning(msg)
|
||||
except Exception:
|
||||
pass
|
||||
Reference in New Issue
Block a user