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:
@@ -0,0 +1,210 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""自动评论:导入解析 / 去重 / 原子领取 / foreach_comment / 剪贴板变量。
|
||||
|
||||
铁律:临时 SQLite + 假设备;不连真机、不碰真实数据。
|
||||
"""
|
||||
import io
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
|
||||
_TMP = tempfile.mkdtemp(prefix="comment_test_")
|
||||
os.environ["DATABASE_URL"] = "sqlite:///" + os.path.join(_TMP, "ac.db").replace("\\", "/")
|
||||
os.environ["DEPLOY_ENV"] = "dev"
|
||||
os.environ["DB_ALLOW_SQLITE_FALLBACK"] = "1"
|
||||
_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
sys.path.insert(0, _ROOT)
|
||||
os.chdir(_ROOT)
|
||||
|
||||
from flask import Flask # noqa: E402
|
||||
from core.models import db, init_db, DeviceAccount, CommentItem # noqa: E402
|
||||
from core import comment as cm # noqa: E402
|
||||
from tasks.generic import task as gt # noqa: E402
|
||||
|
||||
fails = []
|
||||
|
||||
|
||||
def check(label, got, want):
|
||||
ok = got == want
|
||||
if not ok:
|
||||
fails.append(label)
|
||||
print((" ✅ " if ok else " ❌ ") + label +
|
||||
("" if ok else "\n 得到 %r\n 期望 %r" % (got, want)))
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
app.config["SQLALCHEMY_DATABASE_URI"] = os.environ["DATABASE_URL"]
|
||||
with app.app_context():
|
||||
init_db(app)
|
||||
cm.init_app(app)
|
||||
|
||||
|
||||
def reset_db():
|
||||
with app.app_context():
|
||||
CommentItem.query.delete()
|
||||
DeviceAccount.query.delete()
|
||||
db.session.commit()
|
||||
db.session.add_all([
|
||||
DeviceAccount(id="a1", device_name="A01", nickname="号甲", douyin_id="111"),
|
||||
DeviceAccount(id="b1", device_name="A02", nickname="号乙", douyin_id="222"),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
reset_db()
|
||||
|
||||
print("=== 1. 表格解析 ===")
|
||||
rows = cm.parse_rows("视频链接\t账号\t评论内容\nhttps://v.douyin.com/abc/\t号甲\t你好")
|
||||
check("表头 + Tab", len(rows), 1)
|
||||
check("链接", rows[0]["url"], "https://v.douyin.com/abc")
|
||||
check("账号", rows[0]["account"], "号甲")
|
||||
check("评论", rows[0]["comment"], "你好")
|
||||
rows = cm.parse_rows("8.97 复制打开抖音 https://v.douyin.com/xyz/ [email protected] 02/15\t号甲\t不错")
|
||||
check("从整段分享文本抠链接", rows[0]["url"], "https://v.douyin.com/xyz")
|
||||
rows = cm.parse_rows("v.douyin.com/bare\t号甲\t你好")
|
||||
check("不带 scheme 的短链", rows[0]["url"], "https://v.douyin.com/bare")
|
||||
rows = cm.parse_rows("https://example.com/a\t号甲\t你好")
|
||||
check("非抖音链接报错", bool(rows[0]["error"]), True)
|
||||
rows = cm.parse_rows("https://v.douyin.com/a/,号甲,\"你好, 世界\"")
|
||||
check("逗号 CSV + 引号", rows[0]["comment"], "你好, 世界")
|
||||
rows = cm.parse_rows("https://v.douyin.com/a/\t号甲\t")
|
||||
check("空评论报错", bool(rows[0]["error"]), True)
|
||||
|
||||
print("=== 2. 导入 / 去重 / 状态 ===")
|
||||
txt = "视频链接\t账号\t评论内容\nhttps://v.douyin.com/a/\t号甲\t第一条"
|
||||
r = cm.import_comments(txt)
|
||||
check("新增", (r["added"], r["updated"], r["errors"]), (1, 0, 0))
|
||||
with app.app_context():
|
||||
row = CommentItem.query.filter_by(account_name="号甲").first()
|
||||
check("入库 pending", row.status, "pending")
|
||||
check("account_id", row.account_id, "a1")
|
||||
r = cm.import_comments(txt.replace("第一条", "改过的"))
|
||||
check("重复导入更新", (r["added"], r["updated"]), (0, 1))
|
||||
with app.app_context():
|
||||
check("文字已更新", CommentItem.query.filter_by(account_name="号甲").first().comment_text, "改过的")
|
||||
CommentItem.query.filter_by(account_name="号甲").first().status = "done"
|
||||
db.session.commit()
|
||||
r = cm.import_comments(txt)
|
||||
check("已评论的跳过", (r["added"], r["updated"], r["skipped"]), (0, 0, 1))
|
||||
r = cm.import_comments("https://v.douyin.com/dry/\t号乙\t预演", dry_run=True)
|
||||
check("dry_run 计数", (r["added"], r["dry_run"]), (1, True))
|
||||
with app.app_context():
|
||||
check("dry_run 不写库", CommentItem.query.filter_by(account_name="号乙").count(), 0)
|
||||
|
||||
print("=== 3. 原子领取 / 标记 / 重试 / 僵尸 ===")
|
||||
reset_db()
|
||||
cm.import_comments("https://v.douyin.com/a/\t号甲\t一\nhttps://v.douyin.com/b/\t号甲\t二")
|
||||
it = cm.claim_next("号甲", run_id="r1")
|
||||
check("领取一条", (it or {}).get("status"), "running")
|
||||
check("attempts=1", (it or {}).get("attempts"), 1)
|
||||
it_other = cm.claim_next("号甲", run_id="r1")
|
||||
check("第二条是不同的一条", (it_other or {}).get("id") != it.get("id"), True)
|
||||
cm.mark_done(it["id"])
|
||||
with app.app_context():
|
||||
check("标记 done", CommentItem.query.get(it["id"]).status, "done")
|
||||
# 失败可重试
|
||||
cm.mark_failed(it_other["id"], "没打开视频")
|
||||
with app.app_context():
|
||||
check("标记 failed", CommentItem.query.get(it_other["id"]).status, "failed")
|
||||
it2 = cm.claim_next("号甲", run_id="r1")
|
||||
check("failed 可再次领取", (it2 or {}).get("id"), it_other["id"])
|
||||
cm.mark_unknown(it2["id"], "拿不准")
|
||||
check("unknown 不再领取", cm.claim_next("号甲", run_id="r1"), None)
|
||||
# 僵尸回收
|
||||
with app.app_context():
|
||||
row = CommentItem.query.get(it2["id"])
|
||||
row.status = "running"
|
||||
row.updated_at = "2020-01-01 00:00:00"
|
||||
db.session.commit()
|
||||
cm.reclaim_stale()
|
||||
with app.app_context():
|
||||
check("running 超时 → unknown", CommentItem.query.get(it2["id"]).status, "unknown")
|
||||
|
||||
print("=== 4. foreach_comment + mark_comment ===")
|
||||
reset_db()
|
||||
cm.import_comments("https://v.douyin.com/a/\t号甲\t一\nhttps://v.douyin.com/b/\t号甲\t二")
|
||||
w = gt.GenericStepsWorker("S1", {"steps": []})
|
||||
w._vars["target_name"] = "号甲"
|
||||
w._exec_foreach_comment(None, {"children": [
|
||||
{"type": "mark_comment", "params": {"result": "done"}}]})
|
||||
with app.app_context():
|
||||
sts = [x.status for x in CommentItem.query.filter_by(account_name="号甲").all()]
|
||||
check("两条都 done", sorted(sts), ["done", "done"])
|
||||
check("循环结束清理 _last_comment", w._last_comment, None)
|
||||
|
||||
reset_db()
|
||||
cm.import_comments("https://v.douyin.com/a/\t号甲\t一")
|
||||
w2 = gt.GenericStepsWorker("S1", {"steps": []})
|
||||
w2._vars["target_name"] = "号甲"
|
||||
w2._exec_fake = lambda d, p, depth=0: False
|
||||
w2._exec_foreach_comment(None, {"children": [{"type": "fake", "params": {}}]})
|
||||
with app.app_context():
|
||||
check("未标记 → unknown", CommentItem.query.filter_by(account_name="号甲").first().status, "unknown")
|
||||
|
||||
reset_db()
|
||||
cm.import_comments("https://v.douyin.com/a/\t号甲\t一\nhttps://v.douyin.com/b/\t号甲\t二")
|
||||
w3 = gt.GenericStepsWorker("S1", {"steps": []})
|
||||
w3._vars["target_name"] = "号甲"
|
||||
w3._exec_foreach_comment(None, {"max_items": 1, "children": [
|
||||
{"type": "mark_comment", "params": {"result": "done"}}]})
|
||||
with app.app_context():
|
||||
sts = sorted(x.status for x in CommentItem.query.filter_by(account_name="号甲").all())
|
||||
check("max_items=1", sts, ["done", "pending"])
|
||||
|
||||
print("=== 5. 剪贴板 / 输入文字取评论 ===")
|
||||
captured = {}
|
||||
from core import clipboard_helper as ch # noqa: E402
|
||||
_orig_inject = ch.inject_clipboard
|
||||
|
||||
|
||||
def _fake_inject(serial, text, d=None):
|
||||
captured["text"] = text
|
||||
return True, "ok"
|
||||
|
||||
|
||||
ch.inject_clipboard = _fake_inject
|
||||
try:
|
||||
w4 = gt.GenericStepsWorker("S1", {"steps": []})
|
||||
w4._vars["comment_text"] = "这条评论"
|
||||
w4._exec_clipboard(None, {"text": "{comment_text}", "paste": False})
|
||||
check("剪贴板变量替换", captured.get("text"), "这条评论")
|
||||
finally:
|
||||
ch.inject_clipboard = _orig_inject
|
||||
|
||||
sent = {}
|
||||
|
||||
|
||||
class _D:
|
||||
def send_keys(self, text, clear=True):
|
||||
sent["text"] = text
|
||||
|
||||
|
||||
w5 = gt.GenericStepsWorker("S1", {"steps": []})
|
||||
w5._vars["comment"] = {"text": "输入框评论"}
|
||||
w5._verify_input = lambda d, text, clear: True
|
||||
w5._exec_input_text(_D(), {"text_source": "comment", "clear_first": True})
|
||||
check("input_text 取评论内容", sent.get("text"), "输入框评论")
|
||||
|
||||
print("=== 6. 计划构建:评论任务段 ===")
|
||||
from core import account_folder as af # noqa: E402
|
||||
app_row = {"id": "app1", "name": "抖音", "package": "com.ss.android.ugc.aweme",
|
||||
"home_selector_type": "xpath", "home_selector_value": "//x",
|
||||
"home_what": "首页", "launch_timeout": 2}
|
||||
segments = [{"source": "task", "task_id": "t1", "name": "评论", "app_id": "app1",
|
||||
"publish": False,
|
||||
"steps": [{"type": "foreach_comment", "params": {"children": []}}]}]
|
||||
steps = af.build_segmented_steps(app_row, segments, {}, account="号甲",
|
||||
opts={"accounts": ["号甲"]})
|
||||
fa = steps[-1]
|
||||
check("计划外层 foreach_account", fa.get("type"), "foreach_account")
|
||||
check("评论段 require_pending=False", fa.get("params", {}).get("require_pending"), False)
|
||||
check("保留 foreach_comment", any(s.get("type") == "foreach_comment"
|
||||
for s in fa.get("params", {}).get("children", [])), True)
|
||||
|
||||
print()
|
||||
if fails:
|
||||
print("❌ 失败 %d 项:%s" % (len(fails), "、".join(fails)))
|
||||
sys.exit(1)
|
||||
print("✅ test_comment 全部通过(临时库 + 假设备,没连设备)")
|
||||
Reference in New Issue
Block a user