feat(评论/账号): 自动评论导入 + 账号导出 + 切号参数全局化
- 新表 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 同步
This commit is contained in:
+79
-20
@@ -16,6 +16,8 @@
|
||||
(`purge_files`)也只清平台那份 —— 绝不删用户目录里的原件。
|
||||
"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
@@ -189,6 +191,48 @@ def list_accounts(prof=None):
|
||||
return out
|
||||
|
||||
|
||||
def export_accounts_csv(prof=None):
|
||||
"""导出资产管理里的**账号列表 + 状态**(CSV,UTF-8 BOM,Excel 直接打开)。
|
||||
|
||||
列:设备号 / 账号昵称 / 抖音号 / 手机号 / 在线 / 自动状态 / 人工标记 / 有效状态 /
|
||||
检测时间 / 可发视频 / 备注 / 素材入库 / 未发布 / 已发布 / 最近发布。
|
||||
"""
|
||||
rows = list_accounts(prof)
|
||||
roster = {}
|
||||
try:
|
||||
for r in roster_rows():
|
||||
if r.get("nickname"):
|
||||
roster[r["nickname"]] = r
|
||||
except Exception:
|
||||
roster = {}
|
||||
out = io.StringIO()
|
||||
w = csv.writer(out)
|
||||
w.writerow(["设备号", "账号昵称", "抖音号", "手机号", "在线", "自动状态",
|
||||
"人工标记", "有效状态", "检测时间", "可发视频", "备注",
|
||||
"素材入库", "未发布", "已发布", "最近发布"])
|
||||
for a in rows:
|
||||
name = a.get("name") or ""
|
||||
rr = roster.get(name) or {}
|
||||
w.writerow([
|
||||
a.get("device_name") or "",
|
||||
name,
|
||||
rr.get("douyin_id") or "",
|
||||
rr.get("phone") or "",
|
||||
"在线" if a.get("online") else "离线",
|
||||
a.get("account_status") or "",
|
||||
a.get("manual_status") or "",
|
||||
a.get("effective_status") or a.get("account_status") or "",
|
||||
a.get("status_checked_at") or "",
|
||||
"是" if rr.get("can_post_video") else "否",
|
||||
rr.get("note") or "",
|
||||
a.get("total") or 0,
|
||||
a.get("pending") or 0,
|
||||
a.get("done") or 0,
|
||||
a.get("last_published_at") or "",
|
||||
])
|
||||
return out.getvalue().encode("utf-8-sig")
|
||||
|
||||
|
||||
def _has_log_dir(acc_dir):
|
||||
from core.account_log import _LOG_DIR
|
||||
return os.path.isdir(os.path.join(acc_dir, _LOG_DIR))
|
||||
@@ -1769,36 +1813,51 @@ def build_ready_step(prof, overrides=None):
|
||||
"label": "① 账号就绪(切到这次要发的号;切不过来就跳过这个号)",
|
||||
"params": {"target": "var:target_name", "target_value": "",
|
||||
"switch_selector_type": sw.get("entry_selector_type")
|
||||
or sw.get("switch_selector_type") or "xpath",
|
||||
"switch_selector_value": sw.get("entry_selector_value")
|
||||
or sw.get("switch_selector_value") or "",
|
||||
"name_selector_type": sw.get("name_selector_type")
|
||||
or DOUYIN_NAME_SELECTOR_TYPE or "xpath",
|
||||
"switch_selector_value": sw.get("entry_selector_value") or "",
|
||||
"name_selector_type": DOUYIN_NAME_SELECTOR_TYPE or "xpath",
|
||||
"name_selector_value": DOUYIN_NAME_SELECTOR_VALUE or "",
|
||||
"name_selector_value": sw.get("name_selector_value")
|
||||
or DOUYIN_NAME_SELECTOR_VALUE or "",
|
||||
# ⚠ 精确页签(别用 descriptionContains=我:会被音乐条撞到「拍同款」)
|
||||
"me_selector_type": DOUYIN_ME_SELECTOR_TYPE or "xpath",
|
||||
"me_selector_value": DOUYIN_ME_SELECTOR_VALUE,
|
||||
"timeout": 8,
|
||||
"me_selector_type": sw.get("me_selector_type")
|
||||
or DOUYIN_ME_SELECTOR_TYPE or "xpath",
|
||||
"me_selector_value": sw.get("me_selector_value")
|
||||
or DOUYIN_ME_SELECTOR_VALUE,
|
||||
"timeout": float(sw.get("timeout") or 8),
|
||||
"wait_after": float(sw.get("wait_after") if sw.get("wait_after") is not None else 15),
|
||||
"max_attempts": max(1, int(sw.get("retries") or 2)),
|
||||
"on_login_page": sw.get("on_login") or "stop",
|
||||
"on_fail": "skip_account", "probability": 100}}
|
||||
"on_fail": sw.get("on_fail") or "skip_account",
|
||||
"probability": 100}}
|
||||
if not ready["params"]["switch_selector_value"]:
|
||||
# 切号入口没配 → 用 .env 默认(build_switch_step 里那套),仍然留痕提示
|
||||
from config import DOUYIN_SWITCH_SELECTOR_TYPE, DOUYIN_SWITCH_SELECTOR_VALUE
|
||||
ready["params"]["switch_selector_type"] = DOUYIN_SWITCH_SELECTOR_TYPE or "xpath"
|
||||
ready["params"]["switch_selector_value"] = DOUYIN_SWITCH_SELECTOR_VALUE or ""
|
||||
# 计划里对这条内置步骤的覆盖(页面「内置·账号就绪」→ 编辑参数)
|
||||
for k in ("switch_selector_type", "switch_selector_value",
|
||||
"me_selector_type", "me_selector_value",
|
||||
"name_selector_type", "name_selector_value",
|
||||
"on_login_page", "on_fail"):
|
||||
if ov.get(k) not in (None, ""):
|
||||
ready["params"][k] = ov[k]
|
||||
for k in ("timeout", "wait_after", "max_attempts"):
|
||||
if ov.get(k) is not None:
|
||||
try:
|
||||
ready["params"][k] = float(ov[k]) if k == "wait_after" else int(float(ov[k]))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
# 计划覆盖**默认不生效**(`use_global` 未显式 false 时一律用全局参数):
|
||||
# 用户 2026-10-31:"内置动作切换账号是公共参数,元素变了不想一个一个计划改"。
|
||||
# 老计划里存的是整份副本、没有 use_global 字段 → 也按全局走;要覆盖就勾
|
||||
# 「本计划单独覆盖」再保存(use_global=false)。
|
||||
use_global = ov.get("use_global")
|
||||
if use_global is None:
|
||||
use_global = True
|
||||
if str(use_global).lower() in ("false", "0"):
|
||||
use_global = False
|
||||
if not use_global:
|
||||
for k in ("switch_selector_type", "switch_selector_value",
|
||||
"me_selector_type", "me_selector_value",
|
||||
"name_selector_type", "name_selector_value",
|
||||
"on_login_page", "on_fail"):
|
||||
if ov.get(k) not in (None, ""):
|
||||
ready["params"][k] = ov[k]
|
||||
for k in ("timeout", "wait_after", "max_attempts"):
|
||||
if ov.get(k) is not None:
|
||||
try:
|
||||
ready["params"][k] = float(ov[k]) if k == "wait_after" else int(float(ov[k]))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
ready["params"]["probability"] = 100
|
||||
return ready
|
||||
|
||||
|
||||
+438
@@ -0,0 +1,438 @@
|
||||
"""评论数据:导入视频链接 + 每账号评论内容,按账号原子领取/标记。
|
||||
|
||||
一条 `comment_item` = 某账号在某条抖音视频下要发的一条评论。
|
||||
任务里的 `foreach_comment` 按当前账号领取 pending/failed 行,跑完由 `mark_comment` 写结果。
|
||||
|
||||
**评论不可逆**,所以状态语义照搬 `video_plan`:
|
||||
· failed = 确定没发出去,可重试(attempts < MAX_ATTEMPTS)
|
||||
· unknown = 可能已经发出去了,**绝不自动重试**,等人工在页面裁决
|
||||
· running 超过 STALE_MIN 分钟视为僵尸 → 回收成 unknown(不是 failed)
|
||||
"""
|
||||
import csv
|
||||
import io
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from core.logger import get_logger
|
||||
from core.models import db, CommentItem
|
||||
|
||||
_log = get_logger("core.comment")
|
||||
|
||||
_app = None
|
||||
MAX_ATTEMPTS = 3
|
||||
STALE_MIN = 30
|
||||
STATUSES = ("pending", "running", "done", "failed", "unknown")
|
||||
|
||||
# 宽一点的抖音 URL(v.douyin.com 短链 / www.douyin.com/video/... / iesdouyin)
|
||||
_URL_RE = re.compile(r"https?://[^\s'\"<>,。;;))】\]]+", re.I)
|
||||
_DOUYIN_RE = re.compile(r"(^|\.)douyin\.com|iesdouyin\.com", re.I)
|
||||
_HEADER_WORDS = ("视频链接", "链接", "url", "账号", "昵称", "评论", "内容", "comment", "account")
|
||||
|
||||
|
||||
def init_app(app):
|
||||
global _app
|
||||
_app = app
|
||||
try:
|
||||
reclaim_stale()
|
||||
except Exception as e:
|
||||
_log.debug(f"评论僵尸回收失败(不影响启动): {e}")
|
||||
|
||||
|
||||
def _ctx():
|
||||
if _app is None:
|
||||
raise RuntimeError("comment 未关联 Flask app(web_server 启动时调用 init_app)")
|
||||
return _app.app_context()
|
||||
|
||||
|
||||
def _now():
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
|
||||
# ================== URL / 表格解析 ==================
|
||||
def normalize_url(raw):
|
||||
"""从分享文本/URL 里抠出抖音链接;不是抖音域名返回空串。"""
|
||||
raw = (raw or "").strip()
|
||||
if not raw:
|
||||
return ""
|
||||
url = ""
|
||||
try:
|
||||
from core import video_plan as vp
|
||||
url = vp.extract_share_url(raw) or ""
|
||||
except Exception:
|
||||
url = ""
|
||||
if not url:
|
||||
m = _URL_RE.search(raw)
|
||||
if m:
|
||||
url = m.group(0)
|
||||
if not url:
|
||||
m = re.search(r"(?:v|www|m)\.douyin\.com/[^\s'\"<>,。;;))】\]]+", raw, re.I)
|
||||
if m:
|
||||
url = "https://" + m.group(0)
|
||||
url = url.rstrip(",。,.;;))】]")
|
||||
if not url or not _DOUYIN_RE.search(url):
|
||||
return ""
|
||||
return url[:500]
|
||||
|
||||
|
||||
def _delimiter(text):
|
||||
first = next((ln for ln in text.splitlines() if ln.strip()), "")
|
||||
return "\t" if first.count("\t") >= first.count(",") else ","
|
||||
|
||||
|
||||
def _header_map(row):
|
||||
"""表头 → 列号;不是表头返回 None。"""
|
||||
cells = [(c or "").strip().lower() for c in row]
|
||||
# 数据行里也可能有"评论"两个字;表头至少不能含 http
|
||||
if any("http" in c for c in cells):
|
||||
return None
|
||||
if not any(any(w in c for w in _HEADER_WORDS) for c in cells):
|
||||
return None
|
||||
m = {}
|
||||
for i, c in enumerate(cells):
|
||||
if not c:
|
||||
continue
|
||||
if "video_url" not in m and any(k in c for k in ("视频链接", "链接", "url", "link", "视频")):
|
||||
m["video_url"] = i
|
||||
elif "account" not in m and any(k in c for k in ("账号", "昵称", "account", "name")):
|
||||
m["account"] = i
|
||||
elif "comment" not in m and any(k in c for k in ("评论内容", "评论", "内容", "comment")):
|
||||
m["comment"] = i
|
||||
if "video_url" in m and "account" in m and "comment" in m:
|
||||
return m
|
||||
return None
|
||||
|
||||
|
||||
def parse_rows(text):
|
||||
"""解析粘贴/CSV 文本,返回 [{line,url,share_text,account,comment,error}](尚未校验账号)。"""
|
||||
text = (text or "").lstrip("")
|
||||
if not text.strip():
|
||||
return []
|
||||
reader = csv.reader(io.StringIO(text), delimiter=_delimiter(text))
|
||||
raw_rows = list(reader)
|
||||
if not raw_rows:
|
||||
return []
|
||||
hmap = _header_map(raw_rows[0])
|
||||
start = 1 if hmap else 0
|
||||
if hmap is None:
|
||||
hmap = {"video_url": 0, "account": 1, "comment": 2}
|
||||
out = []
|
||||
for i in range(start, len(raw_rows)):
|
||||
row = raw_rows[i]
|
||||
if not any((c or "").strip() for c in row):
|
||||
continue
|
||||
def cell(key):
|
||||
idx = hmap.get(key)
|
||||
return (row[idx].strip() if idx is not None and idx < len(row) else "")
|
||||
raw_url, account, comment = cell("video_url"), cell("account"), cell("comment")
|
||||
url = normalize_url(raw_url)
|
||||
err = ""
|
||||
if not raw_url:
|
||||
err = "视频链接为空"
|
||||
elif not url:
|
||||
err = "不是抖音链接(支持 v.douyin.com / douyin.com)"
|
||||
elif not account:
|
||||
err = "账号为空"
|
||||
elif not comment:
|
||||
err = "评论内容为空"
|
||||
out.append({"line": i + 1, "url": url, "share_text": raw_url or url,
|
||||
"account": account, "comment": comment[:500], "error": err})
|
||||
return out
|
||||
|
||||
|
||||
def template_csv(sample_account=""):
|
||||
acc = sample_account or "周周苏州寻宝藏小店"
|
||||
content = ("视频链接,账号,评论内容\n"
|
||||
"https://v.douyin.com/xxxxxx/,%s,这里填这个账号要发的评论\n" % acc)
|
||||
return content.encode("utf-8-sig")
|
||||
|
||||
|
||||
def _decode(data):
|
||||
if isinstance(data, str):
|
||||
return data
|
||||
for enc in ("utf-8-sig", "utf-8", "gbk"):
|
||||
try:
|
||||
return data.decode(enc)
|
||||
except Exception:
|
||||
continue
|
||||
return data.decode("utf-8", errors="replace")
|
||||
|
||||
|
||||
def _resolve_accounts():
|
||||
"""昵称/抖音号 → (规范昵称, DeviceAccount.id);重名昵称不猜。"""
|
||||
from core.models import DeviceAccount
|
||||
rows = DeviceAccount.query.all()
|
||||
by_name, by_id = {}, {}
|
||||
for r in rows:
|
||||
name = (r.nickname or "").strip()
|
||||
if name:
|
||||
by_name.setdefault(name, []).append(r)
|
||||
did = (r.douyin_id or "").strip()
|
||||
if did and did not in by_id:
|
||||
by_id[did] = r
|
||||
return by_name, by_id
|
||||
|
||||
|
||||
def _lookup_account(account, by_name, by_id):
|
||||
key = (account or "").strip()
|
||||
if not key:
|
||||
return None, "账号为空"
|
||||
hits = by_name.get(key) or []
|
||||
if len(hits) > 1:
|
||||
return None, "昵称命中多条账号记录,请改用抖音号"
|
||||
if len(hits) == 1:
|
||||
return hits[0], ""
|
||||
row = by_id.get(key)
|
||||
if row is not None:
|
||||
return row, ""
|
||||
return None, "账号库里没有这个号"
|
||||
|
||||
|
||||
# ================== 导入 ==================
|
||||
def import_comments(text, dry_run=False):
|
||||
"""解析并写入 comment_item。有效行入库,错误行只报告;返回逐行报告。"""
|
||||
parsed = parse_rows(_decode(text))
|
||||
if not parsed:
|
||||
return {"ok": False, "error": "没有解析到有效行(需要三列:视频链接、账号、评论内容)",
|
||||
"added": 0, "updated": 0, "skipped": 0, "errors": 0, "rows": []}
|
||||
added = updated = skipped = 0
|
||||
rows_out = []
|
||||
with _ctx():
|
||||
by_name, by_id = _resolve_accounts()
|
||||
for p in parsed:
|
||||
if p["error"]:
|
||||
rows_out.append(dict(p, action="error", msg=p["error"]))
|
||||
continue
|
||||
acct, err = _lookup_account(p["account"], by_name, by_id)
|
||||
if err:
|
||||
rows_out.append(dict(p, action="error", msg=err))
|
||||
continue
|
||||
name, aid = (acct.nickname or "").strip(), (acct.id or "")
|
||||
existing = (CommentItem.query.filter_by(video_url=p["url"], account_id=aid).first()
|
||||
if aid else None)
|
||||
if existing is None:
|
||||
existing = (CommentItem.query.filter_by(video_url=p["url"],
|
||||
account_name=name).first())
|
||||
if existing is not None:
|
||||
if existing.status in ("done", "unknown", "running"):
|
||||
skipped += 1
|
||||
msg = {"done": "已经评论过", "unknown": "可能已发出,等人工裁决",
|
||||
"running": "正在执行"}[existing.status]
|
||||
rows_out.append(dict(p, account=name, action="skipped", msg=msg))
|
||||
continue
|
||||
if not dry_run:
|
||||
existing.account_name = name
|
||||
existing.account_id = aid
|
||||
existing.comment_text = p["comment"]
|
||||
existing.video_share_text = p["share_text"]
|
||||
existing.status = "pending"
|
||||
existing.attempts = 0
|
||||
existing.error = ""
|
||||
existing.updated_at = _now()
|
||||
updated += 1
|
||||
rows_out.append(dict(p, account=name, action="updated", msg="已更新待执行"))
|
||||
continue
|
||||
added += 1
|
||||
if not dry_run:
|
||||
now = _now()
|
||||
db.session.add(CommentItem(
|
||||
id=uuid.uuid4().hex[:8], video_url=p["url"],
|
||||
video_share_text=p["share_text"], account_name=name,
|
||||
account_id=aid, comment_text=p["comment"], status="pending",
|
||||
attempts=0, run_id="", error="", created_at=now, updated_at=now,
|
||||
done_at=""))
|
||||
rows_out.append(dict(p, account=name, action="added", msg="已加入待执行"))
|
||||
if not dry_run:
|
||||
db.session.commit()
|
||||
errors = sum(1 for r in rows_out if r.get("action") == "error")
|
||||
_log.info("评论导入%s:新增 %d / 更新 %d / 跳过 %d / 错误 %d",
|
||||
"(预演)" if dry_run else "", added, updated, skipped, errors)
|
||||
return {"ok": True, "dry_run": bool(dry_run), "added": added, "updated": updated,
|
||||
"skipped": skipped, "errors": errors, "rows": rows_out}
|
||||
|
||||
|
||||
# ================== 查询 / 统计 ==================
|
||||
def list_comments(account="", status="", q="", limit=200):
|
||||
with _ctx():
|
||||
query = CommentItem.query
|
||||
if account:
|
||||
query = query.filter(CommentItem.account_name == account.strip())
|
||||
if status:
|
||||
query = query.filter(CommentItem.status == status.strip())
|
||||
if q:
|
||||
kw = "%" + q.strip() + "%"
|
||||
query = query.filter(db.or_(CommentItem.comment_text.like(kw),
|
||||
CommentItem.video_url.like(kw),
|
||||
CommentItem.account_name.like(kw)))
|
||||
rows = query.order_by(CommentItem.created_at.desc(),
|
||||
CommentItem.id.desc()).limit(int(limit or 200)).all()
|
||||
return [r.to_dict() for r in rows]
|
||||
|
||||
|
||||
def stats():
|
||||
with _ctx():
|
||||
counts = {}
|
||||
for st in STATUSES:
|
||||
counts[st] = CommentItem.query.filter_by(status=st).count()
|
||||
pending_accounts = (db.session.query(
|
||||
db.func.count(db.distinct(CommentItem.account_name)))
|
||||
.filter(CommentItem.status.in_(("pending", "failed"))).scalar() or 0)
|
||||
return {"counts": counts, "pending": counts["pending"] + counts["failed"],
|
||||
"accounts": int(pending_accounts), "total": CommentItem.query.count()}
|
||||
|
||||
|
||||
def pending_accounts():
|
||||
"""有 pending/failed 评论的账号(导入后建计划时给用户参考)。"""
|
||||
with _ctx():
|
||||
rows = (CommentItem.query
|
||||
.filter(CommentItem.status.in_(("pending", "failed")))
|
||||
.with_entities(CommentItem.account_name, CommentItem.account_id,
|
||||
db.func.count(CommentItem.id))
|
||||
.group_by(CommentItem.account_name, CommentItem.account_id).all())
|
||||
return [{"account_name": n or "", "account_id": i or "", "pending": int(c or 0)}
|
||||
for n, i, c in rows]
|
||||
|
||||
|
||||
# ================== 原子领取 / 标记 ==================
|
||||
def _reclaim_stale_locked():
|
||||
cutoff = time.strftime("%Y-%m-%d %H:%M:%S",
|
||||
time.localtime(time.time() - STALE_MIN * 60))
|
||||
r = db.session.execute(db.text(
|
||||
"UPDATE comment_item SET status='unknown', error=:err, updated_at=:ts "
|
||||
"WHERE status='running' AND updated_at < :cutoff"),
|
||||
{"err": "运行中断(超过 %d 分钟),可能已发出,请人工确认" % STALE_MIN,
|
||||
"ts": _now(), "cutoff": cutoff})
|
||||
db.session.commit()
|
||||
if (r.rowcount or 0) > 0:
|
||||
_log.warning("评论僵尸回收:%d 条 running → unknown", r.rowcount)
|
||||
|
||||
|
||||
def reclaim_stale():
|
||||
with _ctx():
|
||||
_reclaim_stale_locked()
|
||||
|
||||
|
||||
def claim_next(account_name, run_id="", retry_failed=True):
|
||||
"""为当前账号原子领取一条 pending(可选 failed);没有返回 None。"""
|
||||
from core.models import DeviceAccount
|
||||
key = (account_name or "").strip()
|
||||
if not key:
|
||||
return None
|
||||
allowed = ("pending", "failed") if retry_failed else ("pending",)
|
||||
with _ctx():
|
||||
acct = DeviceAccount.query.filter_by(nickname=key).first()
|
||||
aid = acct.id if acct else ""
|
||||
_reclaim_stale_locked()
|
||||
for _ in range(8):
|
||||
q = CommentItem.query.filter(
|
||||
CommentItem.status.in_(allowed),
|
||||
CommentItem.attempts < MAX_ATTEMPTS)
|
||||
if aid:
|
||||
q = q.filter(db.or_(CommentItem.account_id == aid,
|
||||
db.and_(CommentItem.account_id == "",
|
||||
CommentItem.account_name == key)))
|
||||
else:
|
||||
q = q.filter(CommentItem.account_name == key)
|
||||
row = q.order_by(CommentItem.created_at, CommentItem.id).first()
|
||||
if row is None:
|
||||
return None
|
||||
r = db.session.execute(db.text(
|
||||
"UPDATE comment_item SET status='running', run_id=:rid, "
|
||||
"attempts=COALESCE(attempts,0)+1, updated_at=:ts "
|
||||
"WHERE id=:id AND status IN ('pending','failed') "
|
||||
"AND COALESCE(attempts,0) < :mx"),
|
||||
{"rid": (run_id or "")[:32], "ts": _now(), "id": row.id,
|
||||
"mx": MAX_ATTEMPTS})
|
||||
db.session.commit()
|
||||
if (r.rowcount or 0) > 0:
|
||||
fresh = CommentItem.query.get(row.id)
|
||||
return fresh.to_dict() if fresh else None
|
||||
return None
|
||||
|
||||
|
||||
def _finish(item_id, status, error="", run_id=""):
|
||||
if not item_id:
|
||||
return False
|
||||
with _ctx():
|
||||
now = _now()
|
||||
r = db.session.execute(db.text(
|
||||
"UPDATE comment_item SET status=:st, error=:err, updated_at=:ts, "
|
||||
"done_at=CASE WHEN :st='done' THEN :ts ELSE done_at END "
|
||||
"WHERE id=:id AND status='running'"),
|
||||
{"st": status, "err": (error or "")[:300], "ts": now, "id": item_id})
|
||||
db.session.commit()
|
||||
return (r.rowcount or 0) > 0
|
||||
|
||||
|
||||
def mark_done(item_id, run_id="", note=""):
|
||||
return _finish(item_id, "done", note, run_id)
|
||||
|
||||
|
||||
def mark_failed(item_id, error="", run_id=""):
|
||||
return _finish(item_id, "failed", error, run_id)
|
||||
|
||||
|
||||
def mark_unknown(item_id, error="", run_id=""):
|
||||
return _finish(item_id, "unknown", error, run_id)
|
||||
|
||||
|
||||
def reset(item_id):
|
||||
"""人工把 done/failed/unknown 改回 pending(清零尝试次数)。"""
|
||||
with _ctx():
|
||||
row = CommentItem.query.get(item_id)
|
||||
if not row:
|
||||
return False
|
||||
row.status = "pending"
|
||||
row.attempts = 0
|
||||
row.error = ""
|
||||
row.run_id = ""
|
||||
row.updated_at = _now()
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def resolve(item_id, result):
|
||||
"""人工裁决:pending/done/failed/unknown(用于 unknown 行)。"""
|
||||
result = (result or "").strip()
|
||||
if result not in STATUSES:
|
||||
return False
|
||||
with _ctx():
|
||||
row = CommentItem.query.get(item_id)
|
||||
if not row:
|
||||
return False
|
||||
row.status = result
|
||||
row.error = ""
|
||||
row.updated_at = _now()
|
||||
row.done_at = _now() if result == "done" else ""
|
||||
if result == "pending":
|
||||
row.attempts = 0
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def get(item_id):
|
||||
with _ctx():
|
||||
row = CommentItem.query.get(item_id)
|
||||
return row.to_dict() if row else None
|
||||
|
||||
|
||||
def delete(item_id):
|
||||
with _ctx():
|
||||
row = CommentItem.query.get(item_id)
|
||||
if not row:
|
||||
return False
|
||||
db.session.delete(row)
|
||||
db.session.commit()
|
||||
return True
|
||||
|
||||
|
||||
def clear(status):
|
||||
"""批量删除某个终态的行(done/failed/unknown),返回删除条数。"""
|
||||
status = (status or "").strip()
|
||||
if status not in ("done", "failed", "unknown"):
|
||||
return 0
|
||||
with _ctx():
|
||||
n = CommentItem.query.filter_by(status=status).delete()
|
||||
db.session.commit()
|
||||
_log.info("评论清理:删除 %s 状态 %d 条", status, n)
|
||||
return int(n or 0)
|
||||
@@ -783,6 +783,57 @@ class VideoPublishLog(db.Model):
|
||||
return f"<VideoPublishLog {self.plan_id} {self.at} {self.result}>"
|
||||
|
||||
|
||||
class CommentItem(db.Model):
|
||||
"""**评论数据**:一行 = 某账号在某个抖音视频下要发的一条评论。
|
||||
|
||||
来源是用户在「计划调度 → 导入评论」粘贴/上传的表格(视频链接 / 账号 / 评论内容)。
|
||||
执行由任务里的 `foreach_comment` 按当前账号领取;状态机照搬 `video_plan` 的
|
||||
failed/unknown 区分 —— **评论不可撤销**,不确定是否发出去时绝不自动重试。
|
||||
|
||||
| status | 含义 |
|
||||
|---|---|
|
||||
| pending | 待执行 |
|
||||
| running | 已被某个任务原子领取 |
|
||||
| done | 确认发出 |
|
||||
| failed | 确定没发出去,可重试(attempts < 3) |
|
||||
| unknown | 可能已经发出去,等人工裁决,**不自动重试** |
|
||||
"""
|
||||
__tablename__ = "comment_item"
|
||||
id = db.Column(db.String(32), primary_key=True)
|
||||
video_url = db.Column(db.String(500), default="", index=True) # 规整后的抖音链接
|
||||
video_share_text = db.Column(db.Text, default="") # 原始分享文本(给抖音识别)
|
||||
account_name = db.Column(db.String(80), default="", index=True) # 账号库规范昵称
|
||||
account_id = db.Column(db.String(32), default="", index=True) # DeviceAccount.id(防改名)
|
||||
comment_text = db.Column(db.Text, default="")
|
||||
status = db.Column(db.String(16), default="pending", index=True)
|
||||
attempts = db.Column(db.Integer, default=0)
|
||||
run_id = db.Column(db.String(32), default="", index=True)
|
||||
error = db.Column(db.String(300), default="")
|
||||
created_at = db.Column(db.String(20), default="")
|
||||
updated_at = db.Column(db.String(20), default="", index=True)
|
||||
done_at = db.Column(db.String(20), default="")
|
||||
|
||||
__table_args__ = (
|
||||
db.Index("ix_comment_account_status", "account_id", "status"),
|
||||
db.Index("ix_comment_name_status", "account_name", "status"),
|
||||
)
|
||||
|
||||
def to_dict(self):
|
||||
return {"id": self.id, "video_url": self.video_url or "",
|
||||
"video_share_text": self.video_share_text or "",
|
||||
"account_name": self.account_name or "",
|
||||
"account_id": self.account_id or "",
|
||||
"comment_text": self.comment_text or "",
|
||||
"status": self.status or "", "attempts": int(self.attempts or 0),
|
||||
"run_id": self.run_id or "", "error": self.error or "",
|
||||
"created_at": self.created_at or "",
|
||||
"updated_at": self.updated_at or "",
|
||||
"done_at": self.done_at or ""}
|
||||
|
||||
def __repr__(self):
|
||||
return f"<CommentItem {self.account_name} {self.status} {self.video_url}>"
|
||||
|
||||
|
||||
class AeApp(db.Model):
|
||||
"""流水线的 **App 注册表**:一个手机上的 App + 怎么打开它 + 怎么算"到首页了"。
|
||||
|
||||
@@ -1090,6 +1141,8 @@ SCHEMA_MIGRATIONS = [
|
||||
"新增 account_status_log(每次检测/手改追加一行:状态/时间/设备/来源)", None),
|
||||
(24, "账号人工标记:device_account 新增 manual_status(人工选择的异常/正常;"
|
||||
"优先于任务自动写入的 account_status,对外 API 同时返回两者)", None),
|
||||
(25, "自动评论:新增 comment_item(视频链接/账号/评论内容/状态;"
|
||||
"pending/running/done/failed/unknown,failed 可重试、unknown 等人工裁决)", None),
|
||||
]
|
||||
|
||||
# 当前 schema 版本(备份/恢复用它判断新旧,也写进 app_meta.schema_version)
|
||||
|
||||
@@ -197,6 +197,10 @@ def clean_ready(r):
|
||||
out = {"enabled": bool(r.get("enabled", True))}
|
||||
except Exception:
|
||||
out = {"enabled": True}
|
||||
# 2026-10-31:内置切号默认用**全局参数**;只有明确 use_global=false 的旧/新建计划
|
||||
# 才读取下面的覆盖字段。老计划没有这个键 → 按全局走(不用逐个改)。
|
||||
ug = r.get("use_global")
|
||||
out["use_global"] = (str(ug).lower() not in ("false", "0")) if ug is not None else True
|
||||
for k in READY_STR_FIELDS:
|
||||
if k in r and r.get(k) is not None:
|
||||
out[k] = str(r.get(k) or "").strip()[:500]
|
||||
|
||||
@@ -64,6 +64,7 @@ TABLE_LABELS = {
|
||||
"ae_plan": "计划调度(一行一个计划:干什么/给谁/发什么/什么时候/怎么跑)",
|
||||
"ae_plan_run": "计划运行记录(每次触发的成功/失败/跳过统计)",
|
||||
"video_publish_log": "素材发布记录(每条素材每次发布的时间/结果/设备/链接)",
|
||||
"comment_item": "评论数据(视频链接/账号/评论内容/状态)",
|
||||
"video_plan": "视频发布计划",
|
||||
"ae_app": "流水线·App 注册表",
|
||||
"ae_profile": "流水线·配置",
|
||||
|
||||
+1
-1
@@ -60,7 +60,7 @@ NEED_SELECTOR = ("click", "long_click", "wait_el", "swipe_until", "if_el", "expe
|
||||
# 需要包名的步骤类型
|
||||
NEED_PACKAGE = ("open_app", "stop_app")
|
||||
# 需要非空 children 的容器
|
||||
NEED_CHILDREN = ("loop", "group", "foreach_account")
|
||||
NEED_CHILDREN = ("loop", "group", "foreach_account", "foreach_comment")
|
||||
# 需要 action_id 的步骤类型(动作引用:指着一个组合,执行时现展开)
|
||||
NEED_ACTION_ID = ("action_ref",)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user