"""评论数据:导入视频链接 + 每账号评论内容,按账号原子领取/标记。 一条 `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 has_emoji(text): """是否含表情/符号(含 ZWJ 组合)。用于导入报告和输入校验。""" for ch in text or "": o = ord(ch) if (0x1F000 <= o <= 0x1FAFF or 0x2600 <= o <= 0x27BF or 0xFE00 <= o <= 0xFE0F or o == 0x200D): return True return False 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], "emoji": has_emoji(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 emoji_rows = sum(1 for p in parsed if p.get("emoji") and not p.get("error")) 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 / 含表情 %d", "(预演)" if dry_run else "", added, updated, skipped, errors, emoji_rows) return {"ok": True, "dry_run": bool(dry_run), "added": added, "updated": updated, "skipped": skipped, "errors": errors, "emoji_rows": emoji_rows, "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 pending_counts(): """按账号汇总待评论(pending + failed),给资产/计划页面显示。 返回 `{"by_id": {account_id: n}, "by_name": {nickname: n}}`;两种键都查, 账号改名后 by_id 仍能对上。 """ with _ctx(): rows = (db.session.query(CommentItem.account_id, CommentItem.account_name, db.func.count(CommentItem.id)) .filter(CommentItem.status.in_(("pending", "failed"))) .group_by(CommentItem.account_id, CommentItem.account_name).all()) by_id, by_name = {}, {} for aid, name, n in rows: n = int(n or 0) if aid: by_id[aid] = by_id.get(aid, 0) + n if name: by_name[name] = by_name.get(name, 0) + n return {"by_id": by_id, "by_name": by_name} # ================== 原子领取 / 标记 ================== 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)