初版:抖音自动续火花(从线上实例导出)
This commit is contained in:
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
"""多账号管理:账号注册表、账号目录解析与全局并发控制。
|
||||
|
||||
设计参考「抖音自动续火花 2.1」商业版的多账号模式:
|
||||
- 每个账号独立的数据目录(state/config/ledger/runtime 相互隔离,可单独备份/删除);
|
||||
- 全局并发上限 MAX_CONCURRENT_BROWSERS=5,防止同时打开过多浏览器触发风控;
|
||||
- 账号级启停开关,调度器按账号注册定时任务,互不影响。
|
||||
|
||||
兼容性:`default` 账号即旧版单账号布局(data/ 根目录),旧数据原地生效,升级零迁移。
|
||||
新建账号统一落在 data/accounts/{account_id}/ 下。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shutil
|
||||
import threading
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .config import ACCOUNTS_DIR, DATA_DIR, account_dir
|
||||
|
||||
REGISTRY_PATH = DATA_DIR / "accounts" / "accounts.json"
|
||||
|
||||
MAX_CONCURRENT_BROWSERS = 5 # 全局最大并发浏览器会话数(参考 2.1 商业版)
|
||||
|
||||
_lock = threading.Lock()
|
||||
_current_account: threading.local = threading.local()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _default_account(account_id: str) -> dict:
|
||||
return {
|
||||
"id": account_id,
|
||||
"name": "默认账号",
|
||||
"enabled": True,
|
||||
"device": "",
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
|
||||
|
||||
def _load_registry() -> dict[str, dict]:
|
||||
if not REGISTRY_PATH.exists():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
return {}
|
||||
if not isinstance(data, list):
|
||||
return {}
|
||||
out: dict[str, dict] = {}
|
||||
for item in data:
|
||||
if isinstance(item, dict) and item.get("id"):
|
||||
out[str(item["id"])] = item
|
||||
return out
|
||||
|
||||
|
||||
def _save_registry(reg: dict[str, dict]) -> None:
|
||||
REGISTRY_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
entries = sorted(reg.values(), key=lambda a: a.get("created_at", ""))
|
||||
REGISTRY_PATH.write_text(
|
||||
json.dumps(entries, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def list_accounts() -> list[dict]:
|
||||
"""返回全部账号(含隐式 default),附带各账号数据目录与启用状态。"""
|
||||
reg = _load_registry()
|
||||
out: list[dict] = []
|
||||
ids = ["default"] + sorted(k for k in reg if k != "default")
|
||||
for aid in ids:
|
||||
meta = reg.get(aid) or _default_account(aid)
|
||||
d = account_dir(aid)
|
||||
entry = {
|
||||
**meta,
|
||||
"is_default": aid == "default",
|
||||
"dir": str(d),
|
||||
"state_file_exists": (d / "state.json").exists(),
|
||||
"config_file_exists": (d / "config.json").exists(),
|
||||
}
|
||||
out.append(entry)
|
||||
return out
|
||||
|
||||
|
||||
def get_account(account_id: str) -> dict | None:
|
||||
if account_id == "default":
|
||||
return {
|
||||
**_default_account("default"),
|
||||
"is_default": True,
|
||||
"dir": str(account_dir("default")),
|
||||
}
|
||||
return _load_registry().get(account_id)
|
||||
|
||||
|
||||
def account_exists(account_id: str) -> bool:
|
||||
if account_id == "default":
|
||||
return True
|
||||
return account_id in _load_registry()
|
||||
|
||||
|
||||
def create_account(name: str = "", device: str = "") -> dict:
|
||||
"""新建账号:生成唯一 ID,创建独立数据目录,写入注册表。"""
|
||||
with _lock:
|
||||
reg = _load_registry()
|
||||
while True:
|
||||
aid = f"acc_{uuid.uuid4().hex[:8]}"
|
||||
if aid not in reg:
|
||||
break
|
||||
meta = _default_account(aid)
|
||||
meta["name"] = (name or "").strip() or f"账号 {aid[4:8]}"
|
||||
meta["device"] = (device or "").strip()
|
||||
reg[aid] = meta
|
||||
_save_registry(reg)
|
||||
d = account_dir(aid)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
(d / "logs").mkdir(parents=True, exist_ok=True)
|
||||
return {**meta, "is_default": False, "dir": str(d)}
|
||||
|
||||
|
||||
def update_account(account_id: str, name: str | None = None, device: str | None = None, enabled: bool | None = None) -> dict | None:
|
||||
"""更新账号元信息(改名/备注/启停)。default 账号只允许改名与备注,不允许停用。"""
|
||||
if account_id == "default":
|
||||
return None
|
||||
with _lock:
|
||||
reg = _load_registry()
|
||||
if account_id not in reg:
|
||||
return None
|
||||
meta = reg[account_id]
|
||||
if name is not None:
|
||||
meta["name"] = (name or "").strip() or meta["name"]
|
||||
if device is not None:
|
||||
meta["device"] = (device or "").strip()
|
||||
if enabled is not None:
|
||||
meta["enabled"] = bool(enabled)
|
||||
meta["updated_at"] = _now()
|
||||
_save_registry(reg)
|
||||
return get_account(account_id)
|
||||
|
||||
|
||||
def remove_account(account_id: str) -> bool:
|
||||
"""删除账号:从注册表移除,并将数据目录归档到 data/archived/ 以便恢复。"""
|
||||
if account_id == "default":
|
||||
return False
|
||||
with _lock:
|
||||
reg = _load_registry()
|
||||
if account_id not in reg:
|
||||
return False
|
||||
del reg[account_id]
|
||||
_save_registry(reg)
|
||||
|
||||
d = account_dir(account_id)
|
||||
if d.exists():
|
||||
archived = DATA_DIR / "archived" / f"{account_id}_{datetime.now().strftime('%Y%m%d%H%M%S')}"
|
||||
try:
|
||||
archived.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.move(str(d), str(archived))
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
|
||||
|
||||
def set_current_account(account_id: str) -> None:
|
||||
"""线程局部设置当前账号,供无显式参数的兼容调用读取。"""
|
||||
_current_account.id = account_id
|
||||
|
||||
|
||||
def current_account() -> str:
|
||||
"""线程当前账号;未设置时返回空串(全局日志不归属任何账号)。"""
|
||||
return getattr(_current_account, "id", "") or ""
|
||||
|
||||
|
||||
def acquire_browser_slot() -> None:
|
||||
"""获取一个浏览器并发名额(阻塞等待)。"""
|
||||
_BROWSER_SLOT.acquire()
|
||||
|
||||
|
||||
def release_browser_slot() -> None:
|
||||
_BROWSER_SLOT.release()
|
||||
|
||||
|
||||
def browser_slots_available() -> int:
|
||||
return int(_BROWSER_SLOT._value) # noqa: SLF001 内部值,仅供状态展示
|
||||
|
||||
|
||||
_BROWSER_SLOT = threading.BoundedSemaphore(MAX_CONCURRENT_BROWSERS)
|
||||
+315
@@ -0,0 +1,315 @@
|
||||
"""用户注册表与会话令牌:为「按账号分权」提供身份校验。
|
||||
|
||||
- 用户保存在 data/users.json,密码仅存 PBKDF2-HMAC-SHA256 哈希(带随机盐),绝不存明文;
|
||||
- 会话令牌是 HMAC-SHA256 签名的「用户名|过期时间」字符串,无状态可校验、服务重启不失效,
|
||||
签名密钥首次启动时自动生成并保存到 data/auth_secret.key;
|
||||
- 兼容旧版:完全不改动 data/accounts/accounts.json 的结构。首次启动自动创建管理员账号
|
||||
admin(初始密码取 AUTH_TOKEN),历史账号默认全部归管理员,由管理员在网页「用户管理」
|
||||
中按需把账号分配给普通用户;未分配的账号对普通用户完全不可见。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
import secrets
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from .config import DATA_DIR
|
||||
|
||||
USERS_PATH = DATA_DIR / "users.json"
|
||||
SECRET_PATH = DATA_DIR / "auth_secret.key"
|
||||
|
||||
SESSION_COOKIE = "dcs_session"
|
||||
PBKDF2_ITERATIONS = 240_000
|
||||
USERNAME_RE = re.compile(r"^[A-Za-z0-9_\u4e00-\u9fa5]{2,32}$")
|
||||
MIN_PASSWORD_LEN = 6
|
||||
|
||||
ADMIN_USERNAME = "admin"
|
||||
|
||||
_lock = threading.Lock()
|
||||
_users_mtime_cache: tuple[float, list[dict]] | None = None
|
||||
_secret_cache: bytes | None = None
|
||||
|
||||
# 登录失败限流:同一用户名在窗口内连续失败达上限后锁定
|
||||
_login_guard = threading.Lock()
|
||||
_login_failures: dict[str, tuple[int, float]] = {} # username -> (失败次数, 窗口起点)
|
||||
MAX_LOGIN_FAILURES = 5
|
||||
LOGIN_FAILURE_WINDOW = 300 # 秒
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
# ── 密码哈希 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def hash_password(password: str, salt: bytes | None = None) -> str:
|
||||
salt = salt or secrets.token_bytes(16)
|
||||
dk = hashlib.pbkdf2_hmac("sha256", password.encode("utf-8"), salt, PBKDF2_ITERATIONS)
|
||||
return f"{salt.hex()}${dk.hex()}"
|
||||
|
||||
|
||||
def verify_password(password: str, stored: str) -> bool:
|
||||
try:
|
||||
salt_hex, dk_hex = str(stored).split("$", 1)
|
||||
dk = hashlib.pbkdf2_hmac(
|
||||
"sha256", password.encode("utf-8"), bytes.fromhex(salt_hex), PBKDF2_ITERATIONS
|
||||
)
|
||||
return hmac.compare_digest(dk.hex(), dk_hex)
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
# ── 用户注册表(data/users.json)──────────────────────────────────────────
|
||||
|
||||
|
||||
def _load_users() -> list[dict]:
|
||||
global _users_mtime_cache
|
||||
try:
|
||||
mtime = USERS_PATH.stat().st_mtime
|
||||
except OSError:
|
||||
return []
|
||||
if _users_mtime_cache and _users_mtime_cache[0] == mtime:
|
||||
return _users_mtime_cache[1]
|
||||
try:
|
||||
data = json.loads(USERS_PATH.read_text(encoding="utf-8"))
|
||||
except Exception:
|
||||
data = []
|
||||
users = [u for u in data if isinstance(u, dict) and u.get("username")] if isinstance(data, list) else []
|
||||
_users_mtime_cache = (mtime, users)
|
||||
return users
|
||||
|
||||
|
||||
def _save_users(users: list[dict]) -> None:
|
||||
global _users_mtime_cache
|
||||
USERS_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
USERS_PATH.write_text(
|
||||
json.dumps(users, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
try:
|
||||
USERS_PATH.chmod(0o600)
|
||||
except Exception:
|
||||
pass
|
||||
_users_mtime_cache = (USERS_PATH.stat().st_mtime, users)
|
||||
|
||||
|
||||
def _find(users: list[dict], username: str) -> dict | None:
|
||||
key = (username or "").strip().lower()
|
||||
for u in users:
|
||||
if str(u.get("username", "")).lower() == key:
|
||||
return u
|
||||
return None
|
||||
|
||||
|
||||
def get_user(username: str) -> dict | None:
|
||||
return _find(_load_users(), username)
|
||||
|
||||
|
||||
def public_user(u: dict) -> dict:
|
||||
return {k: v for k, v in u.items() if k != "password_hash"}
|
||||
|
||||
|
||||
def list_users() -> list[dict]:
|
||||
return [public_user(u) for u in sorted(_load_users(), key=lambda x: x.get("created_at", ""))]
|
||||
|
||||
|
||||
def admin_count(users: list[dict] | None = None) -> int:
|
||||
users = users if users is not None else _load_users()
|
||||
return sum(1 for u in users if u.get("is_admin"))
|
||||
|
||||
|
||||
def validate_username(username: str) -> str:
|
||||
name = (username or "").strip()
|
||||
if not USERNAME_RE.match(name):
|
||||
raise ValueError("用户名需为 2~32 位中文、字母、数字或下划线")
|
||||
return name
|
||||
|
||||
|
||||
def validate_password(password: str) -> str:
|
||||
pwd = password or ""
|
||||
if len(pwd) < MIN_PASSWORD_LEN:
|
||||
raise ValueError(f"密码长度至少 {MIN_PASSWORD_LEN} 位")
|
||||
if len(pwd) > 128:
|
||||
raise ValueError("密码过长")
|
||||
return pwd
|
||||
|
||||
|
||||
def create_user(
|
||||
username: str,
|
||||
password: str,
|
||||
is_admin: bool = False,
|
||||
account_ids: list[str] | None = None,
|
||||
) -> dict:
|
||||
name = validate_username(username)
|
||||
validate_password(password)
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
if _find(users, name):
|
||||
raise ValueError(f"用户名已存在:{name}")
|
||||
user = {
|
||||
"username": name,
|
||||
"password_hash": hash_password(password),
|
||||
"is_admin": bool(is_admin),
|
||||
"account_ids": [str(a).strip() for a in (account_ids or []) if str(a).strip()],
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
}
|
||||
users.append(user)
|
||||
_save_users(users)
|
||||
return user
|
||||
|
||||
|
||||
def update_user(
|
||||
username: str,
|
||||
password: str | None = None,
|
||||
account_ids: list[str] | None = None,
|
||||
is_admin: bool | None = None,
|
||||
) -> dict | None:
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
user = _find(users, username)
|
||||
if user is None:
|
||||
return None
|
||||
if password is not None:
|
||||
validate_password(password)
|
||||
user["password_hash"] = hash_password(password)
|
||||
if account_ids is not None:
|
||||
user["account_ids"] = [str(a).strip() for a in account_ids if str(a).strip()]
|
||||
if is_admin is not None and user.get("is_admin") and not is_admin and admin_count(users) <= 1:
|
||||
raise ValueError("至少保留一个管理员账号")
|
||||
if is_admin is not None:
|
||||
user["is_admin"] = bool(is_admin)
|
||||
user["updated_at"] = _now()
|
||||
_save_users(users)
|
||||
return user
|
||||
|
||||
|
||||
def delete_user(username: str) -> bool:
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
user = _find(users, username)
|
||||
if user is None:
|
||||
return False
|
||||
if user.get("is_admin") and admin_count(users) <= 1:
|
||||
raise ValueError("至少保留一个管理员账号,不能删除")
|
||||
users.remove(user)
|
||||
_save_users(users)
|
||||
return True
|
||||
|
||||
|
||||
def authenticate(username: str, password: str) -> dict | None:
|
||||
user = get_user(username)
|
||||
if user is None:
|
||||
hash_password(password) # 防用户枚举:不存在的用户也执行一次等价哈希
|
||||
return None
|
||||
if not verify_password(password, user.get("password_hash", "")):
|
||||
return None
|
||||
return user
|
||||
|
||||
|
||||
def ensure_admin(initial_password: str) -> bool:
|
||||
"""首次启动播种管理员账号(旧部署升级零迁移);已有管理员则不做事。返回是否新建。"""
|
||||
with _lock:
|
||||
users = _load_users()
|
||||
if any(u.get("is_admin") for u in users):
|
||||
return False
|
||||
existing = _find(users, ADMIN_USERNAME)
|
||||
if existing:
|
||||
existing["is_admin"] = True
|
||||
existing["updated_at"] = _now()
|
||||
else:
|
||||
users.append({
|
||||
"username": ADMIN_USERNAME,
|
||||
"password_hash": hash_password(initial_password),
|
||||
"is_admin": True,
|
||||
"account_ids": [],
|
||||
"created_at": _now(),
|
||||
"updated_at": _now(),
|
||||
})
|
||||
_save_users(users)
|
||||
return True
|
||||
|
||||
|
||||
# ── 会话令牌(HMAC 签名,无状态)─────────────────────────────────────────
|
||||
|
||||
|
||||
def _secret_key() -> bytes:
|
||||
global _secret_cache
|
||||
if _secret_cache:
|
||||
return _secret_cache
|
||||
try:
|
||||
key = SECRET_PATH.read_bytes().strip()
|
||||
if len(key) >= 32:
|
||||
_secret_cache = key
|
||||
return key
|
||||
except OSError:
|
||||
pass
|
||||
key = secrets.token_hex(32).encode("ascii")
|
||||
SECRET_PATH.parent.mkdir(parents=True, exist_ok=True)
|
||||
SECRET_PATH.write_bytes(key)
|
||||
try:
|
||||
SECRET_PATH.chmod(0o600)
|
||||
except Exception:
|
||||
pass
|
||||
_secret_cache = key
|
||||
return key
|
||||
|
||||
|
||||
def create_session(username: str, ttl_hours: float = 168) -> str:
|
||||
exp = int(time.time()) + int(ttl_hours * 3600)
|
||||
payload = f"{username}|{exp}"
|
||||
sig = hmac.new(_secret_key(), payload.encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
return base64.urlsafe_b64encode(f"{payload}|{sig}".encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def verify_session(token: str) -> str | None:
|
||||
"""校验会话令牌,返回用户名;无效或过期返回 None。"""
|
||||
try:
|
||||
raw = base64.urlsafe_b64decode(token.encode("ascii")).decode("utf-8")
|
||||
username, exp, sig = raw.split("|", 2)
|
||||
expect = hmac.new(
|
||||
_secret_key(), f"{username}|{exp}".encode("utf-8"), hashlib.sha256
|
||||
).hexdigest()
|
||||
if not hmac.compare_digest(expect, sig):
|
||||
return None
|
||||
if int(exp) < time.time():
|
||||
return None
|
||||
return username
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
# ── 登录失败限流 ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def is_locked(username: str) -> bool:
|
||||
with _login_guard:
|
||||
rec = _login_failures.get((username or "").lower())
|
||||
if not rec:
|
||||
return False
|
||||
count, window_start = rec
|
||||
if time.time() - window_start > LOGIN_FAILURE_WINDOW:
|
||||
return False
|
||||
return count >= MAX_LOGIN_FAILURES
|
||||
|
||||
|
||||
def register_login_failure(username: str) -> None:
|
||||
with _login_guard:
|
||||
key = (username or "").lower()
|
||||
count, window_start = _login_failures.get(key, (0, time.time()))
|
||||
if time.time() - window_start > LOGIN_FAILURE_WINDOW:
|
||||
count, window_start = 0, time.time()
|
||||
_login_failures[key] = (count + 1, window_start)
|
||||
|
||||
|
||||
def clear_login_failures(username: str) -> None:
|
||||
with _login_guard:
|
||||
_login_failures.pop((username or "").lower(), None)
|
||||
@@ -0,0 +1,553 @@
|
||||
"""Playwright 自动化:在抖音网页版私信页面给指定好友发送消息。
|
||||
|
||||
发送逻辑参考 douyin-cloud-streak(MIT),要点:
|
||||
- 点击联系人后校验右侧会话确实切换(防止限流时错发给上一个人);
|
||||
- 列表点击失败时用搜索框兜底;
|
||||
- 检测"操作频繁 / 安全验证"等提示,命中即停本轮;
|
||||
- 发送前清空输入框,发送后校验输入框已清空。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .browser import open_browser
|
||||
from . import ledger
|
||||
from .config import DEFAULT_ACCOUNT_ID, account_state_path, load_config
|
||||
from .guard import detect_rate_limit
|
||||
from .msg_builder import build_message
|
||||
from .runtime import load_runtime, update_runtime
|
||||
from .sender import creator_channel
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
CHAT_URL = "https://www.douyin.com/chat"
|
||||
LOGIN_TEXTS = ["扫码登录", "验证码登录", "登录后查看", "登录后即可"]
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _screenshot(page, account_id: str | None = None) -> None:
|
||||
try:
|
||||
path = account_state_path(account_id).with_name("last_error.png")
|
||||
page.screenshot(path=str(path), timeout=5000)
|
||||
logger.info("已保存页面截图: %s", path)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
# ── 登录检测 ──────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def check_login(page) -> tuple[bool, str]:
|
||||
"""返回 (是否已登录, 说明)。宁可误报掉线,也不要带着过期登录态硬跑。"""
|
||||
url = page.url
|
||||
if "login" in url.lower() or "passport" in url.lower():
|
||||
return False, f"页面已跳转到登录页({url})"
|
||||
|
||||
try:
|
||||
qr = page.locator("#animate_qrcode_container")
|
||||
if qr.count() and qr.first.is_visible():
|
||||
return False, "页面出现扫码登录二维码,登录态已过期"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
for text in LOGIN_TEXTS:
|
||||
try:
|
||||
loc = page.get_by_text(text, exact=False)
|
||||
for i in range(min(loc.count(), 3)):
|
||||
if loc.nth(i).is_visible():
|
||||
return False, f"页面出现登录提示「{text}」"
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
cookies = page.context.cookies()
|
||||
if not any(c["name"].startswith("sessionid") for c in cookies):
|
||||
return False, "未检测到 sessionid Cookie"
|
||||
return True, "ok"
|
||||
|
||||
|
||||
# ── 联系人定位 ────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _find_contact(page, name: str):
|
||||
"""优先按全文精确匹配联系人标题,避免误点其他会话里的消息预览。"""
|
||||
exact = page.get_by_text(name, exact=True)
|
||||
if exact.count():
|
||||
return exact.first
|
||||
return page.locator(".conversationConversationItemtitle").filter(has_text=name).first
|
||||
|
||||
|
||||
def _verify_in_conversation(page, name: str) -> bool:
|
||||
"""右侧会话顶部标题区域(x>300 且 y<100)出现目标昵称才算切换成功。"""
|
||||
for exact in (True, False):
|
||||
try:
|
||||
loc = page.get_by_text(name, exact=exact)
|
||||
for i in range(loc.count()):
|
||||
try:
|
||||
box = loc.nth(i).bounding_box()
|
||||
except Exception:
|
||||
continue
|
||||
if box and box.get("x", 0) > 300 and box.get("y", 0) < 100:
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _search_and_open(page, name: str) -> bool:
|
||||
"""搜索兜底:好友不在聊天列表时,用搜索框找到并打开会话。"""
|
||||
try:
|
||||
box = page.get_by_placeholder("搜索", exact=False).first
|
||||
if box.count() == 0:
|
||||
return False
|
||||
box.click()
|
||||
box.fill(name)
|
||||
time.sleep(4)
|
||||
btn = page.get_by_text("发消息", exact=False).first
|
||||
if btn.count():
|
||||
btn.click(force=True)
|
||||
time.sleep(4)
|
||||
return True
|
||||
candidate = page.get_by_text(name, exact=True).first
|
||||
if candidate.count() == 0:
|
||||
candidate = page.get_by_text(name, exact=False).first
|
||||
if candidate.count() == 0:
|
||||
return False
|
||||
candidate.click(force=True)
|
||||
time.sleep(3)
|
||||
btn = page.get_by_text("发消息", exact=False).first
|
||||
if btn.count():
|
||||
btn.click(force=True)
|
||||
time.sleep(3)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.info("搜索打开 %s 失败: %s", name, e)
|
||||
return False
|
||||
|
||||
|
||||
def _locate_contact(page, name: str) -> bool:
|
||||
"""尝试点击联系人并校验切换成功,最多重试 5 次。"""
|
||||
for attempt in range(5):
|
||||
try:
|
||||
target = _find_contact(page, name)
|
||||
if target.count():
|
||||
target.click(force=True, timeout=10000)
|
||||
time.sleep(random.uniform(2, 4))
|
||||
if _verify_in_conversation(page, name):
|
||||
return True
|
||||
else:
|
||||
try:
|
||||
page.mouse.move(200, 350)
|
||||
page.mouse.wheel(0, 600)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1.5)
|
||||
except Exception as e:
|
||||
logger.info("点击联系人 %s 异常: %s", name, str(e)[:100])
|
||||
time.sleep(random.uniform(1, 2))
|
||||
|
||||
if _search_and_open(page, name):
|
||||
time.sleep(random.uniform(1, 3))
|
||||
return _verify_in_conversation(page, name)
|
||||
return False
|
||||
|
||||
|
||||
# ── 消息输入与发送 ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _type_and_send(page, input_box, msg_text: str) -> bool:
|
||||
"""把文字输入输入框并按 Enter 发送,返回文字是否成功进入输入框。"""
|
||||
try:
|
||||
input_box.click()
|
||||
time.sleep(0.4)
|
||||
page.keyboard.press("Control+A")
|
||||
page.keyboard.press("Delete")
|
||||
time.sleep(0.3)
|
||||
page.keyboard.type(msg_text, delay=100)
|
||||
time.sleep(0.8)
|
||||
cur = input_box.inner_text() or ""
|
||||
if msg_text not in cur:
|
||||
logger.warning("文字未进入输入框,当前内容: %r", cur[:30])
|
||||
return False
|
||||
page.keyboard.press("Enter")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.info("输入/发送异常: %s", str(e)[:100])
|
||||
return False
|
||||
|
||||
|
||||
def _wait_input_cleared(input_box, msg_text: str, wait: float = 8) -> bool:
|
||||
"""消息发出后输入框应不再包含发送文字,以此确认真正发出。"""
|
||||
deadline = time.time() + wait
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
try:
|
||||
cur = input_box.inner_text() or ""
|
||||
if msg_text not in cur:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _send_message(page, msg_text: str, dry_run: bool) -> tuple[bool, str]:
|
||||
"""在当前会话中输入并发送消息,返回 (是否成功, 说明)。"""
|
||||
if detect_rate_limit(page):
|
||||
return False, "发送前检测到验证提示"
|
||||
|
||||
input_box = page.locator('div[contenteditable="true"]').first
|
||||
try:
|
||||
if input_box.count() == 0 or input_box.bounding_box() is None:
|
||||
return False, "找不到聊天输入框"
|
||||
input_box.wait_for(state="visible", timeout=8000)
|
||||
except Exception:
|
||||
return False, "找不到聊天输入框"
|
||||
|
||||
if dry_run:
|
||||
return True, "dry-run"
|
||||
|
||||
if not _type_and_send(page, input_box, msg_text):
|
||||
return False, "文字未能输入到输入框"
|
||||
|
||||
if _wait_input_cleared(input_box, msg_text, wait=8):
|
||||
return True, "ok"
|
||||
|
||||
# 重试一次
|
||||
logger.warning("未检测到消息发出,重试一次")
|
||||
if detect_rate_limit(page):
|
||||
return False, "重试时检测到验证提示"
|
||||
if not _type_and_send(page, input_box, msg_text):
|
||||
return False, "重试时文字未能输入"
|
||||
if _wait_input_cleared(input_box, msg_text, wait=8):
|
||||
return True, "ok"
|
||||
return False, "发送后输入框未清空,消息可能未发出"
|
||||
|
||||
|
||||
def send_to_contact(page, name: str, msg_text: str, dry_run: bool) -> tuple[bool, str]:
|
||||
"""完整流程:定位好友 → 校验切换 → 发送消息。"""
|
||||
if not _locate_contact(page, name):
|
||||
return False, "未能切换到该好友会话(名字不在聊天列表,或页面结构变化)"
|
||||
if detect_rate_limit(page):
|
||||
return False, "检测到「操作频繁 / 安全验证」提示"
|
||||
return _send_message(page, msg_text, dry_run)
|
||||
|
||||
|
||||
# ── 联系人同步 ────────────────────────────────────────────────────────────
|
||||
|
||||
_EXTRACT_JS = """
|
||||
() => {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
|
||||
// 每个会话一行:conversationConversationItemwrapper
|
||||
const rows = document.querySelectorAll('[class*="conversationConversationItemwrapper"]');
|
||||
|
||||
// 名字是标题节点的直接文本;火花/时间等标签可能嵌在其中,需剔除
|
||||
const cleanName = (el) => {
|
||||
let direct = "";
|
||||
el.childNodes.forEach(n => { if (n.nodeType === 3) direct += n.textContent; });
|
||||
let name = direct.trim();
|
||||
if (!name) {
|
||||
const clone = el.cloneNode(true);
|
||||
clone.querySelectorAll(
|
||||
'[class*="TagNextToTitle"], [class*="timeStr"], [class*="streak"], [class*="Streak"]'
|
||||
).forEach(x => x.remove());
|
||||
name = (clone.textContent || "").trim();
|
||||
}
|
||||
return name.replace(/\\s+/g, " ").trim();
|
||||
};
|
||||
|
||||
rows.forEach(row => {
|
||||
const rect = row.getBoundingClientRect();
|
||||
if (rect.height < 30 || rect.width < 100) return;
|
||||
|
||||
// 精确类名优先;未命中时在标题容器内继续找,最后整行清洗兜底
|
||||
let finalName = "";
|
||||
let titleEl = row.querySelector('.conversationConversationItemtitle');
|
||||
const wrap = titleEl ? null : row.querySelector('[class*="Itemtitle"]');
|
||||
if (!titleEl && wrap) titleEl = wrap.querySelector('.conversationConversationItemtitle');
|
||||
|
||||
if (titleEl) {
|
||||
finalName = cleanName(titleEl);
|
||||
} else if (wrap) {
|
||||
const c2 = wrap.cloneNode(true);
|
||||
c2.querySelectorAll(
|
||||
'[class*="TagNextToTitle"], [class*="timeStr"], [class*="streak"], [class*="Streak"], [class*="badge"]'
|
||||
).forEach(x => x.remove());
|
||||
finalName = (c2.textContent || "").replace(/\\s+/g, " ").trim();
|
||||
}
|
||||
|
||||
if (!finalName) return;
|
||||
if (/^\\d+$/.test(finalName)) return; // 纯数字:未读数/火花天数误当昵称
|
||||
if (/^\\d{1,2}:\\d{2}$/.test(finalName)) return; // 时间
|
||||
if (finalName === '消息' || finalName === '私信' || finalName === '朋友私信' || finalName === '通知') return;
|
||||
if (finalName.length > 40) return;
|
||||
if (seen.has(finalName)) return;
|
||||
seen.add(finalName);
|
||||
|
||||
// 火花天数:行内 commonStreak 容器(normalText 为数字)
|
||||
let streak = "";
|
||||
const st = row.querySelector('[class*="commonStreaknormalText"], [class*="commonStreakstreakContainer"]');
|
||||
if (st) streak = (st.textContent || "").trim();
|
||||
|
||||
// 头像:行内第一个非火花图标的 img(头像无 class,位于行首 50x50)
|
||||
let avatar = "";
|
||||
const avImg = row.querySelector('img');
|
||||
if (avImg) {
|
||||
const asrc = avImg.src || "";
|
||||
if (!asrc.includes('flame_icon')) avatar = asrc;
|
||||
}
|
||||
|
||||
out.push({ name: finalName, streak: streak, avatar: avatar });
|
||||
});
|
||||
return out;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _open_chat_page(page) -> bool:
|
||||
"""打开抖音私信页并等待加载,返回是否成功。"""
|
||||
for attempt in range(3):
|
||||
try:
|
||||
page.goto(CHAT_URL, timeout=90000, wait_until="domcontentloaded")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.info("打开页面失败(第 %s 次): %s", attempt + 1, str(e)[:80])
|
||||
time.sleep(5)
|
||||
return False
|
||||
|
||||
|
||||
def _scroll_and_extract(page, collected: list[dict], max_rounds: int = 28) -> None:
|
||||
"""滚动聊天列表并提取联系人,直到没有新数据。
|
||||
|
||||
列表为虚拟滚动,步长过大会跳过部分行导致火花遗漏,故小步慢滚。
|
||||
"""
|
||||
for _ in range(max_rounds):
|
||||
data = page.evaluate(_EXTRACT_JS) or []
|
||||
new_items = [x for x in data if x not in collected]
|
||||
if new_items:
|
||||
collected.extend(new_items)
|
||||
stable = 0
|
||||
else:
|
||||
stable = getattr(_scroll_and_extract, "_stable", 0) + 1
|
||||
_scroll_and_extract._stable = stable
|
||||
if stable >= 3:
|
||||
break
|
||||
try:
|
||||
page.mouse.move(200, 350)
|
||||
page.mouse.wheel(0, 450)
|
||||
except Exception:
|
||||
pass
|
||||
page.wait_for_timeout(1000)
|
||||
|
||||
|
||||
def fetch_chat_contacts(account_id: str | None = None) -> dict:
|
||||
"""从抖音私信页左侧聊天列表读取联系人(含火花天数),供网页端勾选。"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
result = {"at": _now(), "names": [], "error": None}
|
||||
state = account_state_path(aid)
|
||||
if not state.exists():
|
||||
result["error"] = "该账号尚未上传登录态 state.json"
|
||||
return result
|
||||
|
||||
try:
|
||||
with open_browser(state_path=state) as (p, browser, context, page):
|
||||
if not _open_chat_page(page):
|
||||
result["error"] = "无法打开抖音私信页面"
|
||||
return result
|
||||
|
||||
page.wait_for_timeout(10000)
|
||||
logged, why = check_login(page)
|
||||
if not logged:
|
||||
result["error"] = why
|
||||
return result
|
||||
|
||||
collected: list[dict] = []
|
||||
for attempt in range(3):
|
||||
try:
|
||||
page.wait_for_selector(".conversationConversationItemtitle", timeout=45000)
|
||||
except Exception:
|
||||
logger.info("第 %s 次等待联系人列表超时", attempt + 1)
|
||||
|
||||
_scroll_and_extract._stable = 0
|
||||
_scroll_and_extract(page, collected)
|
||||
|
||||
if collected:
|
||||
break
|
||||
try:
|
||||
page.reload(wait_until="domcontentloaded", timeout=90000)
|
||||
page.wait_for_timeout(12000)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
result["names"] = collected
|
||||
logger.info("已读取聊天列表联系人 %s 个", len(result["names"]))
|
||||
except Exception as e:
|
||||
logger.error("获取联系人异常: %s", e)
|
||||
result["error"] = f"获取联系人异常: {e}"
|
||||
return result
|
||||
|
||||
|
||||
# ── 通道选择 ───────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _b_channel_daily(account_id: str | None = None) -> tuple[str, int]:
|
||||
"""通道 B 今日已发条数:优先 runtime 计数,跨天自动归零。"""
|
||||
today = datetime.now().astimezone().date().isoformat()
|
||||
rec = load_runtime(account_id).get("b_channel_daily") or {}
|
||||
if rec.get("date") != today:
|
||||
return today, 0
|
||||
return today, int(rec.get("count", 0) or 0)
|
||||
|
||||
|
||||
def compute_pending(cfg: dict | None = None, account_id: str | None = None) -> list[dict]:
|
||||
"""预测本次运行会真实发送的名单(与 run_send 通道判定一致)。"""
|
||||
cfg = cfg or load_config(account_id)
|
||||
entries = ledger.get_selected(account_id)
|
||||
daily_limit = max(1, int(cfg.get("first_message_daily_limit", 1) or 1))
|
||||
_, creator_sent_today = _b_channel_daily(account_id)
|
||||
allow_first = bool(cfg.get("allow_first_message"))
|
||||
pending: list[dict] = []
|
||||
for e in entries:
|
||||
if e.get("has_conversation"):
|
||||
pending.append({**e, "send_channel": "consumer"})
|
||||
elif allow_first and creator_sent_today < daily_limit:
|
||||
pending.append({**e, "send_channel": "creator"})
|
||||
return pending
|
||||
|
||||
|
||||
# ── 主发送流程 ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _send_consumer(page, entry: dict, msg: str, dry_run: bool, result: dict, account_id: str | None = None) -> None:
|
||||
"""通道 A:consumer 重防护发送。"""
|
||||
name = entry["display_name"]
|
||||
ok, why = send_to_contact(page, name, msg, dry_run)
|
||||
if ok:
|
||||
result["ok"].append(name)
|
||||
ledger.confirm_join(name, account_id)
|
||||
logger.info("[%s] 已发送给 %s:%s", account_id, name, msg if not dry_run else "(干跑)")
|
||||
else:
|
||||
if entry.get("channel") == "creator":
|
||||
result["skipped"].append({
|
||||
"name": name,
|
||||
"reason": "consumer 定位失败(该好友为 creator-only),已降级跳过",
|
||||
})
|
||||
ledger.mark_no_consumer_conversation(name, account_id)
|
||||
else:
|
||||
result["failed"].append({"name": name, "reason": why})
|
||||
logger.warning("[%s] 发送给 %s 失败:%s", account_id, name, why)
|
||||
if detect_rate_limit(page):
|
||||
result["rate_limited"] = True
|
||||
logger.warning("[%s] 疑似触发限流,停止本轮", account_id)
|
||||
if not dry_run:
|
||||
ledger.update_send_result(name, ok, _now(), account_id=account_id)
|
||||
|
||||
|
||||
def _send_creator(entry: dict, msg: str, dry_run: bool, result: dict, p, account_id: str | None = None) -> None:
|
||||
"""通道 B:creator 首条消息。"""
|
||||
name = entry["display_name"]
|
||||
cfg = load_config(account_id)
|
||||
allow_first = bool(cfg.get("allow_first_message"))
|
||||
daily_limit = max(1, int(cfg.get("first_message_daily_limit", 1) or 1))
|
||||
today, count = _b_channel_daily(account_id)
|
||||
|
||||
if not allow_first:
|
||||
result["skipped"].append({"name": name, "reason": "无会话且未开启「允许首条消息」"})
|
||||
return
|
||||
if count >= daily_limit:
|
||||
result["skipped"].append({
|
||||
"name": name,
|
||||
"reason": f"今日已发送首条消息 {count}/{daily_limit}",
|
||||
})
|
||||
return
|
||||
|
||||
ok, why = creator_channel.send_first_message(entry, msg, dry_run, p, account_id)
|
||||
if ok:
|
||||
result["ok"].append(name)
|
||||
logger.info("[%s] 通道 B 已发送给 %s:%s", account_id, name, msg if not dry_run else "(干跑)")
|
||||
if not dry_run:
|
||||
ledger.update_send_result(name, True, _now(), via_creator=True, account_id=account_id)
|
||||
update_runtime(account_id, b_channel_daily={"date": today, "count": count + 1})
|
||||
else:
|
||||
result["failed"].append({"name": name, "reason": f"通道B: {why}"})
|
||||
logger.warning("[%s] 通道 B 发送给 %s 失败:%s", account_id, name, why)
|
||||
if "限流" in why or "停止" in why:
|
||||
result["rate_limited"] = True
|
||||
logger.warning("[%s] 通道 B 触发限流,停止本轮", account_id)
|
||||
|
||||
|
||||
def run_send(dry_run: bool = False, only_names: list[str] | None = None, account_id: str | None = None) -> dict:
|
||||
"""主入口:从好友台账读取勾选目标,逐个发送。"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
cfg = load_config(aid)
|
||||
messages = cfg.get("messages") or ["🔥"]
|
||||
max_n = int(cfg.get("max_friends_per_run", 20) or 20)
|
||||
gap_min = max(1, int(cfg.get("send_gap_min", 6) or 6))
|
||||
gap_max = max(gap_min, int(cfg.get("send_gap_max", 12) or 12))
|
||||
|
||||
result = {
|
||||
"at": _now(), "dry_run": bool(dry_run),
|
||||
"ok": [], "failed": [], "skipped": [],
|
||||
"logged_out": False, "rate_limited": False,
|
||||
"account_id": aid,
|
||||
}
|
||||
|
||||
state = account_state_path(aid)
|
||||
if not state.exists():
|
||||
result["failed"].append({"name": "_system", "reason": "该账号尚未上传登录态 state.json"})
|
||||
return result
|
||||
|
||||
targets = ledger.get_selected(aid)
|
||||
if not targets and cfg.get("friends"):
|
||||
stats = ledger.import_config_friends(cfg["friends"], aid)
|
||||
logger.info("[%s] 已从 config.friends 迁移进台账:新增 %s 人,勾选 %s 人",
|
||||
aid, stats["added"], stats["selected"])
|
||||
targets = ledger.get_selected(aid)
|
||||
if only_names is not None:
|
||||
targets = [t for t in targets if t.get("display_name") in only_names]
|
||||
targets = targets[:max_n] if max_n > 0 else targets
|
||||
|
||||
if not targets:
|
||||
logger.info("[%s] 未配置任何好友,跳过发送", aid)
|
||||
return result
|
||||
|
||||
try:
|
||||
with open_browser(state_path=state) as (p, browser, context, page):
|
||||
if not _open_chat_page(page):
|
||||
result["failed"].append({"name": "_system", "reason": "无法打开抖音私信页面"})
|
||||
return result
|
||||
|
||||
time.sleep(8)
|
||||
logged, why = check_login(page)
|
||||
if not logged:
|
||||
result["logged_out"] = True
|
||||
result["failed"].append({"name": "_system", "reason": why})
|
||||
_screenshot(page, aid)
|
||||
return result
|
||||
|
||||
logger.info("[%s] 待发送好友 %s 人,dry_run=%s", aid, len(targets), dry_run)
|
||||
for entry in targets:
|
||||
msg = build_message(messages, last_sent_msg=str(entry.get("last_msg", "")))
|
||||
if entry.get("has_conversation"):
|
||||
_send_consumer(page, entry, msg, dry_run, result, aid)
|
||||
else:
|
||||
_send_creator(entry, msg, dry_run, result, p, aid)
|
||||
|
||||
if result["rate_limited"]:
|
||||
break
|
||||
time.sleep(random.uniform(gap_min, gap_max))
|
||||
except Exception as e:
|
||||
logger.error("[%s] 运行异常: %s", aid, e)
|
||||
result["failed"].append({"name": "_system", "reason": f"运行异常: {e}"})
|
||||
return result
|
||||
|
||||
|
||||
# 别名兼容
|
||||
sync_contacts = fetch_chat_contacts
|
||||
@@ -0,0 +1,63 @@
|
||||
"""抖音好友头像本地化缓存。
|
||||
|
||||
抖音网页版头像 URL 带签名参数,过期后无法再访问。
|
||||
同步联系人时把头像下载到本地 data/avatars/<account_id>/<hash>.<ext>,
|
||||
前端通过 /avatars/... 访问本地文件,长期有效。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import logging
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
from .config import DEFAULT_ACCOUNT_ID, DATA_DIR
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
_TIMEOUT = 12
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
|
||||
def avatar_dir(account_id: str | None = None) -> Path:
|
||||
return DATA_DIR / "avatars" / (account_id or DEFAULT_ACCOUNT_ID)
|
||||
|
||||
|
||||
def _public_url(account_id: str, fname: str) -> str:
|
||||
return f"/avatars/{account_id}/{fname}"
|
||||
|
||||
|
||||
def fetch_and_save_avatar(url: str, account_id: str | None = None) -> str | None:
|
||||
"""下载头像到本地,返回可公开访问的相对路径;失败返回 None。
|
||||
|
||||
URL 为空或下载失败时不抛异常,保证同步流程不受影响。
|
||||
"""
|
||||
if not url or not isinstance(url, str):
|
||||
return None
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
try:
|
||||
ext = Path(url.split("?")[0]).suffix.lower()
|
||||
if ext not in (".jpg", ".jpeg", ".png", ".webp"):
|
||||
ext = ".jpg"
|
||||
fname = f"{hashlib.md5(url.encode('utf-8')).hexdigest()[:16]}{ext}"
|
||||
d = avatar_dir(aid)
|
||||
fp = d / fname
|
||||
if fp.exists() and fp.stat().st_size > 0:
|
||||
return _public_url(aid, fname)
|
||||
with _LOCK:
|
||||
if fp.exists() and fp.stat().st_size > 0:
|
||||
return _public_url(aid, fname)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
r = requests.get(url, timeout=_TIMEOUT, headers={"Referer": "https://www.douyin.com/"})
|
||||
r.raise_for_status()
|
||||
tmp = fp.with_suffix(fp.suffix + ".tmp")
|
||||
tmp.write_bytes(r.content)
|
||||
tmp.replace(fp)
|
||||
logger.info("[%s] 头像已缓存: %s", aid, fname)
|
||||
return _public_url(aid, fname)
|
||||
except Exception as e:
|
||||
logger.warning("[%s] 头像下载失败: %s", aid, str(e)[:120])
|
||||
return None
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
"""共享的 Playwright 浏览器启动器。
|
||||
|
||||
统一集成:
|
||||
- 反爬对抗参数与真实 Chrome 指纹;
|
||||
- playwright_stealth 自动注入(若安装);
|
||||
- 中文环境(zh-CN)与 Asia/Shanghai 时区模拟;
|
||||
- 全局并发信号量:最多 MAX_CONCURRENT_BROWSERS 个浏览器会话同时存在
|
||||
(参考「抖音自动续火花 2.1」的会话池并发上限,防多账号同时开太多浏览器触发风控);
|
||||
- 完善的生命周期管理与异常兜底。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
from .accounts import acquire_browser_slot, release_browser_slot
|
||||
from .config import account_state_path, get_valid_state_path
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
_CHROME_UA = (
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"(KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
||||
)
|
||||
|
||||
_COMMON_ARGS = [
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
]
|
||||
|
||||
|
||||
def _apply_stealth(page) -> None:
|
||||
"""尝试注入 stealth 脚本规避常见浏览器自动化指纹检测。"""
|
||||
try:
|
||||
from playwright_stealth import Stealth
|
||||
Stealth().apply_stealth_sync(page)
|
||||
except Exception:
|
||||
try:
|
||||
from playwright_stealth import stealth_sync
|
||||
stealth_sync(page)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@contextmanager
|
||||
def open_browser(state_path: Path | str | None = None, headless: bool = True, **ctx_kwargs):
|
||||
"""启动 Chromium 并返回 (playwright, browser, context, page)。
|
||||
|
||||
用法::
|
||||
|
||||
with open_browser() as (p, browser, context, page):
|
||||
page.goto(url)
|
||||
...
|
||||
|
||||
退出 with 块时自动关闭浏览器和 playwright。
|
||||
state_path 默认自愈寻找账号目录 data/state.json 或根目录 state.json(默认账号)。
|
||||
并发控制:进入时占用一个全局浏览器名额,超过上限会阻塞等待。
|
||||
"""
|
||||
valid_state = Path(state_path) if state_path else get_valid_state_path()
|
||||
state_file = str(valid_state) if valid_state and valid_state.exists() else None
|
||||
|
||||
acquire_browser_slot()
|
||||
p = sync_playwright().start()
|
||||
browser = None
|
||||
try:
|
||||
browser = p.chromium.launch(headless=headless, args=_COMMON_ARGS)
|
||||
defaults = {
|
||||
"viewport": {"width": 1366, "height": 768},
|
||||
"user_agent": _CHROME_UA,
|
||||
"locale": "zh-CN",
|
||||
"timezone_id": "Asia/Shanghai",
|
||||
"ignore_https_errors": True,
|
||||
}
|
||||
if state_file:
|
||||
defaults["storage_state"] = state_file
|
||||
defaults.update(ctx_kwargs)
|
||||
|
||||
context = browser.new_context(**defaults)
|
||||
page = context.new_page()
|
||||
_apply_stealth(page)
|
||||
|
||||
yield p, browser, context, page
|
||||
finally:
|
||||
if browser:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
p.stop()
|
||||
except Exception:
|
||||
pass
|
||||
release_browser_slot()
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
"""配置读写。配置保存在 data/config.json(默认账号)或 data/accounts/{id}/config.json,由网页端编辑。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import threading
|
||||
from pathlib import Path
|
||||
|
||||
BASE_DIR = Path(__file__).resolve().parent.parent
|
||||
DATA_DIR = BASE_DIR / "data"
|
||||
ACCOUNTS_DIR = DATA_DIR / "accounts"
|
||||
CONFIG_PATH = DATA_DIR / "config.json"
|
||||
STATE_PATH = DATA_DIR / "state.json"
|
||||
ROOT_STATE_PATH = BASE_DIR / "state.json"
|
||||
|
||||
# 兼容旧版直接引用(默认账号即 data/ 根目录)
|
||||
DEFAULT_ACCOUNT_ID = "default"
|
||||
|
||||
|
||||
def account_dir(account_id: str | None = None) -> Path:
|
||||
"""返回账号数据目录。默认账号(None 或 'default')使用旧版 data/ 根目录,零迁移兼容。"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
if aid == DEFAULT_ACCOUNT_ID:
|
||||
return DATA_DIR
|
||||
return ACCOUNTS_DIR / aid
|
||||
|
||||
|
||||
def account_config_path(account_id: str | None = None) -> Path:
|
||||
return account_dir(account_id) / "config.json"
|
||||
|
||||
|
||||
def account_state_path(account_id: str | None = None) -> Path:
|
||||
return account_dir(account_id) / "state.json"
|
||||
|
||||
|
||||
def get_valid_state_path(account_id: str | None = None) -> Path | None:
|
||||
"""自动兼容并双向自愈检查账号目录 state.json 与根目录 state.json(仅默认账号)。"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
sp = account_state_path(aid)
|
||||
if sp.exists() and sp.stat().st_size > 30:
|
||||
return sp
|
||||
if aid == DEFAULT_ACCOUNT_ID and ROOT_STATE_PATH.exists() and ROOT_STATE_PATH.stat().st_size > 30:
|
||||
try:
|
||||
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
||||
import shutil
|
||||
shutil.copy2(ROOT_STATE_PATH, sp)
|
||||
except Exception:
|
||||
pass
|
||||
return sp
|
||||
return None
|
||||
|
||||
|
||||
DEFAULT_CONFIG = {
|
||||
"schedule_time": "21:00", # 每天发送时间 HH:MM(服务器时区 Asia/Shanghai)
|
||||
"jitter_minutes": 30, # 时间抖动窗口:实际在 [schedule_time, schedule_time+30min] 内随机开始
|
||||
"send_gap_min": 6, # 相邻两个好友之间的最小间隔(秒)
|
||||
"send_gap_max": 12, # 相邻两个好友之间的最大间隔(秒)
|
||||
"max_friends_per_run": 20, # 每次最多发送的好友数(0 表示不限制)
|
||||
"friends": [], # 好友列表:聊天列表里显示的备注 / 昵称 / 抖音号
|
||||
"messages": ["🔥 续火花", "今天也要开心哦 🔥", "晚上好 🔥"],
|
||||
# creator 页抖音号采集(P1):
|
||||
"creator_user_detail_path": "aweme/v1/creator/im/user_detail/", # user_detail 接口路径前缀(接口变动只改这里)
|
||||
"creator_max_scrolls": 80, # 单次采集最大滚动轮数
|
||||
# 通道 B / 调度(P2):
|
||||
"auto_run_enabled": True, # 自动运行总开关:关闭后定时任务不发送(手动「立即续火花」不受影响)
|
||||
"allow_first_message": False, # 允许对无会话好友发送首条消息(通道 B,高风险,默认关闭)
|
||||
"first_message_daily_limit": 1, # 通道 B 单日上限
|
||||
"schedule_harvest_day": "mon", # 周级 creator 采集:mon/tue/.../sun 或空字符串关闭,默认周一 03:00
|
||||
}
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def load_config(account_id: str | None = None) -> dict:
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
cfg = dict(DEFAULT_CONFIG)
|
||||
cpath = account_config_path(aid)
|
||||
if cpath.exists():
|
||||
try:
|
||||
data = json.loads(cpath.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
cfg.update(data)
|
||||
except Exception:
|
||||
pass
|
||||
return cfg
|
||||
|
||||
|
||||
def save_config(cfg: dict | None, account_id: str | None = None) -> dict:
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
merged = dict(DEFAULT_CONFIG)
|
||||
if cfg:
|
||||
merged.update(cfg)
|
||||
|
||||
merged["friends"] = [str(x).strip() for x in merged.get("friends", []) if str(x).strip()]
|
||||
merged["messages"] = [str(x) for x in merged.get("messages", []) if str(x).strip()]
|
||||
if not merged["messages"]:
|
||||
merged["messages"] = ["🔥"]
|
||||
|
||||
schedule = str(merged.get("schedule_time", "21:00"))
|
||||
try:
|
||||
hh, mm = schedule.split(":")
|
||||
if not (0 <= int(hh) <= 23 and 0 <= int(mm) <= 59):
|
||||
raise ValueError
|
||||
merged["schedule_time"] = f"{int(hh):02d}:{int(mm):02d}"
|
||||
except Exception:
|
||||
raise ValueError("schedule_time 必须是 HH:MM 格式")
|
||||
|
||||
for key in ("jitter_minutes", "send_gap_min", "send_gap_max", "max_friends_per_run", "creator_max_scrolls", "first_message_daily_limit"):
|
||||
try:
|
||||
merged[key] = max(0, int(merged.get(key, DEFAULT_CONFIG[key])))
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"{key} 必须是整数")
|
||||
if merged["send_gap_max"] < merged["send_gap_min"]:
|
||||
merged["send_gap_max"] = merged["send_gap_min"]
|
||||
merged["auto_run_enabled"] = bool(merged.get("auto_run_enabled"))
|
||||
merged["allow_first_message"] = bool(merged.get("allow_first_message"))
|
||||
day = str(merged.get("schedule_harvest_day") or "").strip().lower()
|
||||
merged["schedule_harvest_day"] = day if day in {"mon", "tue", "wed", "thu", "fri", "sat", "sun", "off"} else "off"
|
||||
|
||||
with _lock:
|
||||
d = account_dir(aid)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
cpath = account_config_path(aid)
|
||||
cpath.write_text(json.dumps(merged, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
return merged
|
||||
@@ -0,0 +1,33 @@
|
||||
"""共享防护:限流关键词与安全验证浮层检测。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
RATE_LIMIT_KEYWORDS = [
|
||||
"操作频繁",
|
||||
"操作太频繁",
|
||||
"发送过于频繁",
|
||||
"请稍后再试",
|
||||
"稍后再试",
|
||||
"请稍后",
|
||||
"安全验证",
|
||||
"滑动验证",
|
||||
"验证码",
|
||||
"验证中心",
|
||||
"人机验证",
|
||||
"网络异常",
|
||||
"请勿频繁",
|
||||
]
|
||||
|
||||
|
||||
def detect_rate_limit(page) -> str | None:
|
||||
"""扫描页面上可见的限流/验证提示,命中返回关键词,未命中返回 None。"""
|
||||
for kw in RATE_LIMIT_KEYWORDS:
|
||||
try:
|
||||
loc = page.get_by_text(kw, exact=False)
|
||||
for i in range(loc.count()):
|
||||
box = loc.nth(i).bounding_box()
|
||||
if box: # 可见才计,避免匹配到隐藏节点
|
||||
return kw
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,184 @@
|
||||
"""creator 页抖音号采集:滚动好友列表 + 拦截 user_detail 接口响应。
|
||||
|
||||
实测依据:
|
||||
- 接口带 msToken + a_bogus 签名,无法用裸 HTTP 复现,只能浏览器内拦截;
|
||||
- ShortId 为原样值(可能含末尾点),只做空白 trim,禁止去点归一化;
|
||||
- 全程只读(滚动 + 监听响应),不发送任何消息;
|
||||
- 采集频率控制:滚动间隔可配(默认 500ms)、连续 6 轮无新映射即停。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ..browser import open_browser
|
||||
from ..config import DEFAULT_ACCOUNT_ID, account_state_path, load_config
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
CREATOR_CHAT_URL = "https://creator.douyin.com/creator-micro/data/following/chat"
|
||||
|
||||
FRIENDS_TAB_CANDIDATES = [
|
||||
'xpath=//*[@id="sub-app"]/div/div/div[1]/div[2]',
|
||||
'xpath=//*[contains(text(),"好友")]',
|
||||
]
|
||||
|
||||
SCROLL_JS = """
|
||||
() => {
|
||||
const els = document.querySelectorAll('[class*="semi-list"], #sub-app ul');
|
||||
let el = null;
|
||||
for (const e of els) { if (e.scrollHeight > e.clientHeight + 10) { el = e; break; } }
|
||||
if (!el) {
|
||||
const all = [...document.querySelectorAll('div')].filter(
|
||||
x => x.scrollHeight > x.clientHeight + 100 && x.clientHeight > 100
|
||||
);
|
||||
if (all.length) el = all[0];
|
||||
}
|
||||
if (el && el.scrollTop + el.clientHeight < el.scrollHeight - 10) {
|
||||
el.scrollTop += 600;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _click_friends_tab(page) -> bool:
|
||||
"""点击「好友」tab,返回是否成功。"""
|
||||
for sel in FRIENDS_TAB_CANDIDATES:
|
||||
try:
|
||||
loc = page.locator(sel)
|
||||
if loc.count() and loc.first.is_visible():
|
||||
loc.first.click(timeout=3000)
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _check_session(page, context) -> str | None:
|
||||
"""检查登录态,返回错误信息或 None。"""
|
||||
if "passport" in page.url.lower() or "login" in page.url.lower():
|
||||
return f"creator 页跳转到登录页({page.url})"
|
||||
if not any(c["name"].startswith("sessionid") for c in context.cookies()):
|
||||
return "creator 页未检测到 sessionid cookie,登录态可能已过期"
|
||||
return None
|
||||
|
||||
|
||||
def _on_response_factory(mapping: dict, urls: list[str], path: str):
|
||||
"""创建 response 拦截回调,把 user_detail 接口的映射收集到 mapping 中。"""
|
||||
def on_response(resp):
|
||||
try:
|
||||
if path not in resp.url:
|
||||
return
|
||||
if len(urls) < 3:
|
||||
urls.append(resp.url)
|
||||
if resp.status != 200:
|
||||
return
|
||||
data = resp.json()
|
||||
for item in data.get("user_list", []) or []:
|
||||
user = item.get("user", {}) or {}
|
||||
sid = str(user.get("ShortId", "")).strip()
|
||||
nick = str(user.get("nickname", "")).strip()
|
||||
uid = str(item.get("user_id", ""))
|
||||
if sid:
|
||||
mapping[sid] = {"nickname": nick, "user_id": uid}
|
||||
except Exception:
|
||||
pass
|
||||
return on_response
|
||||
|
||||
|
||||
def collect_short_id_map(
|
||||
state_path=None,
|
||||
target_short_ids: list[str] | None = None,
|
||||
max_scrolls: int | None = None,
|
||||
stop_when_found: bool = True,
|
||||
scroll_interval: float = 0.5,
|
||||
account_id: str | None = None,
|
||||
) -> dict:
|
||||
"""打开 creator 消息页,滚动好友列表并拦截 user_detail 响应,采集 short_id 映射。
|
||||
|
||||
返回 {"at", "mapping", "count", "hit", "sample_urls", "error"}
|
||||
"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
result: dict = {
|
||||
"at": _now(), "mapping": {}, "count": 0, "hit": False,
|
||||
"sample_urls": [], "error": None,
|
||||
}
|
||||
cfg = load_config(aid)
|
||||
api_path = str(cfg.get("creator_user_detail_path") or "aweme/v1/creator/im/user_detail/")
|
||||
if max_scrolls is None:
|
||||
max_scrolls = int(cfg.get("creator_max_scrolls", 80) or 80)
|
||||
|
||||
mapping: dict[str, dict] = {}
|
||||
urls: list[str] = []
|
||||
targets = set(target_short_ids or [])
|
||||
|
||||
try:
|
||||
ctx_kwargs = {"viewport": {"width": 1366, "height": 900}, "locale": "zh-CN"}
|
||||
with open_browser(state_path or account_state_path(aid), **ctx_kwargs) as (p, browser, context, page):
|
||||
page.on("response", _on_response_factory(mapping, urls, api_path))
|
||||
|
||||
page.goto(CREATOR_CHAT_URL, wait_until="domcontentloaded", timeout=90000)
|
||||
page.wait_for_timeout(10000)
|
||||
|
||||
error = _check_session(page, context)
|
||||
if error:
|
||||
result["error"] = error
|
||||
return result
|
||||
|
||||
_click_friends_tab(page)
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 滚动 + 拦截
|
||||
stagnant = 0
|
||||
last_size = 0
|
||||
for _ in range(max_scrolls):
|
||||
try:
|
||||
moved = bool(page.evaluate(SCROLL_JS))
|
||||
except Exception:
|
||||
moved = False
|
||||
page.wait_for_timeout(int(scroll_interval * 1000))
|
||||
grew = len(mapping) > last_size
|
||||
last_size = len(mapping)
|
||||
if not moved and not grew:
|
||||
stagnant += 1
|
||||
if stagnant >= 6:
|
||||
break
|
||||
else:
|
||||
stagnant = 0
|
||||
if stop_when_found and targets and targets.issubset(mapping):
|
||||
break
|
||||
|
||||
result["mapping"] = mapping
|
||||
result["count"] = len(mapping)
|
||||
result["sample_urls"] = urls
|
||||
result["hit"] = bool(targets and targets.issubset(mapping))
|
||||
logger.info("creator 采集完成:%s 条映射,命中目标 %s", len(mapping), result["hit"])
|
||||
except Exception as e:
|
||||
logger.error("creator 采集异常: %s", e)
|
||||
result["error"] = f"creator 采集异常: {e}"
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
targets = sys.argv[1:] or None
|
||||
res = collect_short_id_map(target_short_ids=targets)
|
||||
out = {
|
||||
"at": res["at"], "count": res["count"], "hit": res["hit"],
|
||||
"targets": targets, "error": res["error"],
|
||||
"sample_urls": res["sample_urls"],
|
||||
"sample_mapping": dict(list(res["mapping"].items())[:5]),
|
||||
}
|
||||
report = account_state_path(aid).parent / "harvest_report.json"
|
||||
report.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print("采集完成,report ->", report)
|
||||
print("count:", res["count"], "hit:", res["hit"], "error:", res["error"])
|
||||
+424
@@ -0,0 +1,424 @@
|
||||
"""好友台账:以会话显示名为键的本地持久化好友库(每账号独立 ledger.json)。
|
||||
|
||||
v1(P0):仅 consumer 数据(显示名 + 火花天数 + 会话存在性 + 勾选状态 + 最后发送时间)。
|
||||
P1 起扩展 short_id / nickname / user_id / 置信度,业务主键升级为 short_id(不可变),
|
||||
display_name 变为可变字段。匹配铁律:display_name 相同即视为同一人(P0 阶段约束)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
from .config import DEFAULT_ACCOUNT_ID, account_dir
|
||||
from .avatar import fetch_and_save_avatar
|
||||
|
||||
|
||||
def ledger_path(account_id: str | None = None) -> Path:
|
||||
return account_dir(account_id) / "ledger.json"
|
||||
|
||||
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def _now() -> str:
|
||||
return datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
|
||||
|
||||
def _default_entry(display_name: str) -> dict:
|
||||
"""P1 完整 schema:display_name 为 P0 主键,short_id 为业务主键(不可变)。"""
|
||||
return {
|
||||
"display_name": display_name,
|
||||
"nickname": "",
|
||||
"short_id": "",
|
||||
"user_id": "",
|
||||
"avatar": "", # 本地缓存头像路径 /avatars/<aid>/<hash>.<ext>
|
||||
"streak_days": 0,
|
||||
"has_conversation": False,
|
||||
"selected": False,
|
||||
"selected_order": None, # 勾选顺序(越小越靠前,仅勾选时有效;持久化保证重启后置顶顺序不丢)
|
||||
"last_sent_at": None,
|
||||
"channel": "none", # consumer | creator | none
|
||||
"join_confidence": "low", # high: display_name 与 nickname 已对上;low: 未确认
|
||||
"source": {"creator": False, "consumer": False},
|
||||
}
|
||||
|
||||
|
||||
def _parse_streak(text) -> int:
|
||||
"""从火花文本(如 '🔥 81' / '81' / '81天')提取天数,解析失败返回 0。"""
|
||||
m = re.search(r"\d+", str(text or ""))
|
||||
return int(m.group()) if m else 0
|
||||
|
||||
|
||||
def _norm_ws(s) -> str:
|
||||
"""空白归一化(仅用于 join 匹配,不改存储原样值):
|
||||
consumer 页显示名可能含不间断空格(U+00A0),creator 接口返回普通空格。"""
|
||||
return str(s or "").replace("\u00a0", " ").strip()
|
||||
|
||||
|
||||
def load_ledger(account_id: str | None = None) -> list[dict]:
|
||||
entries: list[dict] = []
|
||||
lp = ledger_path(account_id)
|
||||
if lp.exists():
|
||||
try:
|
||||
data = json.loads(lp.read_text(encoding="utf-8"))
|
||||
if isinstance(data, list):
|
||||
entries = [dict(e) for e in data if isinstance(e, dict) and e.get("display_name")]
|
||||
for e in entries:
|
||||
# 派生标记(不持久化,读时计算保证一致):
|
||||
# no_consumer_conversation:consumer 私信无会话(自动识别,不限来源)
|
||||
# → 勾选也不会被通道 A 发送(默认 skipped 或降级),除非开启通道 B
|
||||
# creator_only:creator 页有记录 且 consumer 无会话(creator 来源子集)
|
||||
e["no_consumer_conversation"] = not e.get("has_conversation")
|
||||
e["creator_only"] = e.get("channel") == "creator" and e["no_consumer_conversation"]
|
||||
except Exception:
|
||||
pass
|
||||
return entries
|
||||
|
||||
|
||||
def _save(entries: list[dict], account_id: str | None = None) -> None:
|
||||
with _lock:
|
||||
d = account_dir(account_id)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
lp = ledger_path(account_id)
|
||||
lp.write_text(
|
||||
json.dumps(entries, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
|
||||
|
||||
def _upsert(entries: list[dict], entry: dict) -> dict:
|
||||
"""按 display_name upsert:更新新字段,但保留已有条目的 selected / last_sent_at。
|
||||
|
||||
新增条目补齐默认字段,保证 schema 一致。返回命中/新增的条目。
|
||||
"""
|
||||
for e in entries:
|
||||
if e.get("display_name") == entry["display_name"]:
|
||||
selected = e.get("selected", False)
|
||||
last_sent = e.get("last_sent_at")
|
||||
e.update(entry)
|
||||
for k, v in _default_entry(entry["display_name"]).items():
|
||||
e.setdefault(k, v)
|
||||
e["selected"] = selected
|
||||
e["last_sent_at"] = last_sent
|
||||
return e
|
||||
base = _default_entry(entry["display_name"])
|
||||
base.update(entry)
|
||||
entries.append(base)
|
||||
return base
|
||||
|
||||
|
||||
def merge_consumer_contacts(contacts: list[dict], account_id: str | None = None) -> dict:
|
||||
"""把 consumer 会话列表(fetch_chat_contacts 的 names 字段)upsert 进台账。
|
||||
|
||||
只更新火花天数与会话存在性,不覆盖用户勾选与历史发送时间。
|
||||
返回 {"added", "updated", "total"} 统计。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
added = 0
|
||||
updated = 0
|
||||
for c in contacts or []:
|
||||
name = str(c.get("name", "")).strip()
|
||||
if not name:
|
||||
continue
|
||||
exists = any(e.get("display_name") == name for e in entries)
|
||||
old_avatar = next((e.get("avatar") or "" for e in entries if e.get("display_name") == name), "")
|
||||
avatar_url = c.get("avatar") or ""
|
||||
new_avatar = fetch_and_save_avatar(avatar_url, account_id) if avatar_url else None
|
||||
avatar_path = new_avatar if new_avatar else old_avatar
|
||||
e = _upsert(entries, {
|
||||
"display_name": name,
|
||||
"streak_days": _parse_streak(c.get("streak")),
|
||||
"has_conversation": True,
|
||||
"channel": "consumer",
|
||||
"avatar": avatar_path,
|
||||
})
|
||||
e.setdefault("source", {})["consumer"] = True
|
||||
# creator 侧已确认且两侧名字一致 → 置信度升级 high
|
||||
if e.get("source", {}).get("creator") and e.get("nickname") == name:
|
||||
e["join_confidence"] = "high"
|
||||
if exists:
|
||||
updated += 1
|
||||
else:
|
||||
added += 1
|
||||
if added or updated:
|
||||
_save(entries, account_id)
|
||||
return {"added": added, "updated": updated, "total": len(entries)}
|
||||
|
||||
|
||||
def import_config_friends(friends: list[str], account_id: str | None = None) -> dict:
|
||||
"""兼容迁移:把 config.json 的 friends 同步进台账并默认勾选。
|
||||
|
||||
- 已存在条目:置 selected=True(保持原发送目标集合不变)
|
||||
- 不存在条目:新增并 selected=True
|
||||
返回 {"added", "selected"}。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
by_name = {e.get("display_name"): e for e in entries}
|
||||
added = 0
|
||||
selected = 0
|
||||
for name in friends or []:
|
||||
name = str(name).strip()
|
||||
if not name:
|
||||
continue
|
||||
if name in by_name:
|
||||
if not by_name[name].get("selected"):
|
||||
by_name[name]["selected"] = True
|
||||
selected += 1
|
||||
else:
|
||||
entries.append({
|
||||
**_default_entry(name),
|
||||
"has_conversation": False,
|
||||
"selected": True,
|
||||
})
|
||||
by_name[name] = entries[-1]
|
||||
added += 1
|
||||
if added or selected:
|
||||
_save(entries, account_id)
|
||||
return {"added": added, "selected": selected}
|
||||
|
||||
|
||||
def get_selected(account_id: str | None = None) -> list[dict]:
|
||||
return [e for e in load_ledger(account_id) if e.get("selected")]
|
||||
|
||||
|
||||
def merge_creator_map(mapping: dict, account_id: str | None = None) -> dict:
|
||||
"""把 creator 采集的 {short_id: {nickname, user_id}} 合并进台账(预 join,乐观)。
|
||||
|
||||
- display_name == nickname 或 display_name == short_id → 回填并 high(两侧确认同一人)
|
||||
- 否则新建条目:display_name=nickname(假定)、confidence=low、channel=creator
|
||||
返回 {"joined", "added", "updated", "total"}。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
by_display = {e.get("display_name"): e for e in entries}
|
||||
# 归一化匹配:consumer 显示名可能含 NBSP(U+00A0),creator 昵称是普通空格。
|
||||
# 用「归一化名 → 条目列表」保留同名全部候选,避免 stub 覆盖真实条目。
|
||||
by_display_norm: dict[str, list[dict]] = {}
|
||||
for e in entries:
|
||||
by_display_norm.setdefault(_norm_ws(e.get("display_name")), []).append(e)
|
||||
|
||||
def _pick_target(exact, by_sid, norm_list):
|
||||
"""从候选条目里择优:优先有 consumer 数据(会话/勾选/历史发送)的真实条目,避免命中孤立 stub。"""
|
||||
seen: list[dict] = []
|
||||
for c in ([exact, by_sid] + (norm_list or [])):
|
||||
if c is not None and c not in seen:
|
||||
seen.append(c)
|
||||
if not seen:
|
||||
return None
|
||||
for c in seen:
|
||||
if (
|
||||
c.get("has_conversation")
|
||||
or c.get("source", {}).get("consumer")
|
||||
or c.get("last_sent_at")
|
||||
):
|
||||
return c
|
||||
return seen[0]
|
||||
|
||||
joined = added = updated = 0
|
||||
for sid, info in (mapping or {}).items():
|
||||
sid = str(sid).strip()
|
||||
if not sid:
|
||||
continue
|
||||
nick = str(info.get("nickname", "")).strip()
|
||||
uid = str(info.get("user_id", ""))
|
||||
target = _pick_target(
|
||||
by_display.get(nick),
|
||||
by_display.get(sid),
|
||||
by_display_norm.get(nick),
|
||||
)
|
||||
if target is not None:
|
||||
changed = False
|
||||
if target.get("short_id") != sid:
|
||||
target["short_id"] = sid
|
||||
changed = True
|
||||
if target.get("nickname") != nick:
|
||||
target["nickname"] = nick
|
||||
changed = True
|
||||
if target.get("user_id") != uid:
|
||||
target["user_id"] = uid
|
||||
changed = True
|
||||
src = target.setdefault("source", {})
|
||||
# 旧 schema 数据恢复:有会话即视为 consumer 侧出现过
|
||||
if target.get("has_conversation") and not src.get("consumer"):
|
||||
src["consumer"] = True
|
||||
if not src.get("creator"):
|
||||
src["creator"] = True
|
||||
changed = True
|
||||
# high 需两侧确认:display_name 已在 consumer 页出现 且 == nickname(或 == short_id)
|
||||
if target.get("join_confidence") != "high" and src.get("consumer"):
|
||||
target["join_confidence"] = "high"
|
||||
changed = True
|
||||
if target.get("has_conversation") and target.get("channel") != "consumer":
|
||||
target["channel"] = "consumer"
|
||||
changed = True
|
||||
if changed:
|
||||
updated += 1
|
||||
joined += 1
|
||||
# 清理同 short_id 的孤立 stub(creator-only 无会话/未发送的条目,被真实 join 后删除)
|
||||
target_idx = entries.index(target)
|
||||
for i in range(len(entries) - 1, -1, -1):
|
||||
e = entries[i]
|
||||
if (
|
||||
i != target_idx
|
||||
and e.get("short_id") == sid
|
||||
and not e.get("has_conversation")
|
||||
and not e.get("last_sent_at")
|
||||
):
|
||||
del entries[i]
|
||||
else:
|
||||
entries.append({
|
||||
**_default_entry(nick),
|
||||
"nickname": nick,
|
||||
"short_id": sid,
|
||||
"user_id": uid,
|
||||
"source": {"creator": True, "consumer": False},
|
||||
"join_confidence": "low",
|
||||
"channel": "creator",
|
||||
})
|
||||
by_display[nick] = entries[-1]
|
||||
added += 1
|
||||
if added or updated:
|
||||
_save(entries, account_id)
|
||||
return {"joined": joined, "added": added, "updated": updated, "total": len(entries)}
|
||||
|
||||
|
||||
def confirm_join(display_name: str, account_id: str | None = None) -> None:
|
||||
"""发送时确认(P1 关键兜底):该 display_name 的会话已在 consumer 页成功定位+标题校验通过。
|
||||
|
||||
标记 source.consumer=true、channel=consumer;若 nickname == display_name(两侧名字一致)
|
||||
→ join_confidence 升级为 high。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
for e in entries:
|
||||
if e.get("display_name") == display_name:
|
||||
e.setdefault("source", {})["consumer"] = True
|
||||
e["channel"] = "consumer"
|
||||
if e.get("nickname") and e["nickname"] == display_name:
|
||||
e["join_confidence"] = "high"
|
||||
break
|
||||
_save(entries, account_id)
|
||||
|
||||
|
||||
def set_selected(entries_in: list[dict], account_id: str | None = None) -> dict:
|
||||
"""批量更新勾选与勾选顺序:entries: [{display_name, selected, selected_order}]。
|
||||
|
||||
已存在条目更新勾选;不存在的条目新增并置勾选(支持手动添加好友)。
|
||||
selected_order 随勾选持久化(勾选组内排序,重启后置顶顺序不丢);
|
||||
取消勾选时清空 selected_order。
|
||||
返回 {"updated", "added"}。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
by_name = {e.get("display_name"): e for e in entries}
|
||||
updated = 0
|
||||
added = 0
|
||||
for it in entries_in:
|
||||
name = str(it.get("display_name", "")).strip()
|
||||
sel = bool(it.get("selected"))
|
||||
order = it.get("selected_order")
|
||||
if not name:
|
||||
continue
|
||||
if name in by_name:
|
||||
e = by_name[name]
|
||||
if bool(e.get("selected")) != sel:
|
||||
e["selected"] = sel
|
||||
updated += 1
|
||||
new_order = order if sel else None
|
||||
if e.get("selected_order") != new_order:
|
||||
e["selected_order"] = new_order
|
||||
updated += 1
|
||||
else:
|
||||
entries.append({
|
||||
**_default_entry(name),
|
||||
"has_conversation": False,
|
||||
"selected": sel,
|
||||
"selected_order": order if sel else None,
|
||||
})
|
||||
by_name[name] = entries[-1]
|
||||
added += 1
|
||||
if updated or added:
|
||||
_save(entries, account_id)
|
||||
return {"updated": updated, "added": added}
|
||||
|
||||
|
||||
def update_send_result(
|
||||
display_name: str,
|
||||
ok: bool,
|
||||
at: str | None = None,
|
||||
via_creator: bool = False,
|
||||
account_id: str | None = None,
|
||||
) -> None:
|
||||
"""发送后回写台账:更新 last_sent_at;成功时标记会话存在。
|
||||
|
||||
via_creator=True(通道 B 首条消息):只记时间、不置 has_conversation——
|
||||
creator 侧发过首条消息 ≠ consumer 私信页有会话;否则 run_send 会误判
|
||||
走通道 A 去 consumer 页定位,而列表里根本没有该会话导致失败。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
for e in entries:
|
||||
if e.get("display_name") == display_name:
|
||||
e["last_sent_at"] = at or _now()
|
||||
if ok and not via_creator:
|
||||
e["has_conversation"] = True
|
||||
break
|
||||
_save(entries, account_id)
|
||||
|
||||
|
||||
def mark_no_consumer_conversation(display_name: str, account_id: str | None = None) -> None:
|
||||
"""自愈:通道 A 在 consumer 页定位失败时调用(仅对 creator-only 条目)。
|
||||
|
||||
把误标的 has_conversation 修正回 false,避免每轮都误走通道 A 失败;
|
||||
channel 保持 creator,之后走通道 B 或 skipped。
|
||||
"""
|
||||
entries = load_ledger(account_id)
|
||||
changed = False
|
||||
for e in entries:
|
||||
if e.get("display_name") == display_name and e.get("channel") == "creator":
|
||||
if e.get("has_conversation"):
|
||||
e["has_conversation"] = False
|
||||
changed = True
|
||||
break
|
||||
if changed:
|
||||
_save(entries, account_id)
|
||||
|
||||
|
||||
def stats(account_id: str | None = None) -> dict:
|
||||
"""台账自愈报表:分布统计、连续成功 Top、low 待确认、近 7 天发送。"""
|
||||
entries = load_ledger(account_id)
|
||||
now = datetime.now().astimezone()
|
||||
week_ago = (now - timedelta(days=7)).isoformat()
|
||||
high = sum(1 for e in entries if e.get("join_confidence") == "high")
|
||||
no_conv = [
|
||||
{"display_name": e["display_name"], "channel": e.get("channel")}
|
||||
for e in entries
|
||||
if not e.get("has_conversation")
|
||||
]
|
||||
low_pending = [
|
||||
e["display_name"]
|
||||
for e in entries
|
||||
if e.get("join_confidence") == "low" and e.get("has_conversation")
|
||||
]
|
||||
recent_sent = [
|
||||
e["display_name"]
|
||||
for e in entries
|
||||
if str(e.get("last_sent_at") or "") >= week_ago
|
||||
]
|
||||
top_streak = sorted(entries, key=lambda e: -(e.get("streak_days") or 0))[:10]
|
||||
return {
|
||||
"total": len(entries),
|
||||
"selected": sum(1 for e in entries if e.get("selected")),
|
||||
"confidence": {"high": high, "low": len(entries) - high},
|
||||
"with_short_id": sum(1 for e in entries if e.get("short_id")),
|
||||
"no_conversation": no_conv,
|
||||
"low_pending": low_pending,
|
||||
"recent_sent_7d": recent_sent,
|
||||
"top_streak": [
|
||||
{"display_name": e["display_name"], "streak_days": e.get("streak_days")}
|
||||
for e in top_streak
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
# 别名兼容
|
||||
update_from_sync = merge_consumer_contacts
|
||||
@@ -0,0 +1,560 @@
|
||||
"""网页端扫码登录会话管理(复刻「抖音自动续火花 2.1」的扫码机制)。
|
||||
|
||||
与 2.1 商业版 huohua.py 的流程一致,但基于 Playwright 实现且更简洁:
|
||||
|
||||
1. start(account_id) 为账号启动专属无头 Chromium(占用全局并发名额),
|
||||
打开抖音并唤起登录二维码;
|
||||
2. status(account_id) 前端轮询:返回当前状态与二维码 data URL;
|
||||
3. 成功检测 轮询 cookie 出现 sessionid/sessionid_ss 即视为登录成功,
|
||||
自动导出 storage_state 覆盖该账号 state.json 并销毁浏览器;
|
||||
4. cancel(account_id) 手动取消;二维码过期自动点击刷新重新提取;
|
||||
5. GC 会话整体超时(默认 5 分钟)自动回收,防浏览器泄漏。
|
||||
|
||||
同账号同时只允许一个扫码会话;不同账号可各自扫码(受全局并发上限约束)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
from .accounts import acquire_browser_slot, release_browser_slot
|
||||
from .config import DEFAULT_ACCOUNT_ID, ROOT_STATE_PATH, account_state_path
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
CHAT_URL = "https://www.douyin.com/chat?isPopup=1"
|
||||
|
||||
# 扫码等待总时长:覆盖"掏手机 -> 打开抖音 -> 扫码 -> 确认"的完整动作
|
||||
SESSION_TIMEOUT = 300
|
||||
# 二维码自动刷新次数上限(抖音二维码约 2~3 分钟过期一次)
|
||||
QR_REFRESH_LIMIT = 5
|
||||
|
||||
# 登录成功判定 Cookie:覆盖抖音各端变体(sid_guard/sid_tt/uid_tt 与 sessionid 同批下发)
|
||||
_LOGIN_COOKIE_NAMES = {"sessionid", "sessionid_ss", "sid_tt", "sid_guard", "uid_tt"}
|
||||
|
||||
_slot_guard = threading.Lock()
|
||||
_slot_holders: set[str] = set()
|
||||
|
||||
|
||||
def _acquire_slot_tracked(aid: str) -> None:
|
||||
"""获取全局并发名额并登记归属,保证释放幂等(线程卡死被强制接管时不重复释放)。"""
|
||||
acquire_browser_slot()
|
||||
with _slot_guard:
|
||||
_slot_holders.add(aid)
|
||||
|
||||
|
||||
def _release_slot_once(aid: str) -> None:
|
||||
with _slot_guard:
|
||||
if aid not in _slot_holders:
|
||||
return
|
||||
_slot_holders.discard(aid)
|
||||
release_browser_slot()
|
||||
|
||||
|
||||
def _hard_expire(aid: str) -> None:
|
||||
"""硬超时保护:工作线程卡死(如浏览器进程被杀后同步调用挂起)时强制终态。"""
|
||||
flag = _stop_flags.get(aid)
|
||||
if flag:
|
||||
flag.set()
|
||||
with _guard:
|
||||
st = _sessions.get(aid)
|
||||
if st and st["status"] in ("queuing", "starting", "waiting_scan"):
|
||||
st.update(status="expired", message="扫码会话超时,请重新发起扫码", qrcode="")
|
||||
logger.warning("[%s] 扫码会话触发硬超时保护(工作线程疑似卡死)", aid)
|
||||
_release_slot_once(aid)
|
||||
|
||||
_QR_SELECTORS = [
|
||||
"#animate_qrcode_container img",
|
||||
'[data-e2e="login-qrcode"] img',
|
||||
'div[class*="qrcode"] img',
|
||||
]
|
||||
|
||||
_QR_EXPIRED_TEXTS = ["二维码已过期", "已失效", "已过期", "点击刷新", "刷新"]
|
||||
|
||||
_guard = threading.Lock()
|
||||
_sessions: dict[str, dict] = {}
|
||||
_stop_flags: dict[str, threading.Event] = {}
|
||||
|
||||
|
||||
def _new_state(aid: str, **fields) -> dict:
|
||||
st = {
|
||||
"status": "starting",
|
||||
"message": "正在启动扫码环境…",
|
||||
"qrcode": "",
|
||||
"started_at": time.time(),
|
||||
"last_active": time.time(),
|
||||
"error": "",
|
||||
}
|
||||
st.update(fields)
|
||||
return st
|
||||
|
||||
|
||||
def start(account_id: str) -> dict:
|
||||
"""为指定账号启动扫码会话(幂等:已有活跃会话则直接返回其状态)。"""
|
||||
with _guard:
|
||||
old = _sessions.get(account_id)
|
||||
if old and old["status"] in ("queuing", "starting", "waiting_scan"):
|
||||
return {"ok": True, "resumed": True, **_public(old)}
|
||||
flag = threading.Event()
|
||||
_stop_flags[account_id] = flag
|
||||
st = _new_state(
|
||||
account_id,
|
||||
status="queuing",
|
||||
message="正在排队获取浏览器名额…",
|
||||
)
|
||||
_sessions[account_id] = st
|
||||
|
||||
t = threading.Thread(target=_session_worker, args=(account_id, flag), daemon=True)
|
||||
t.start()
|
||||
watchdog = threading.Timer(SESSION_TIMEOUT + 90, lambda: _hard_expire(account_id))
|
||||
watchdog.daemon = True
|
||||
watchdog.start()
|
||||
logger.info("[%s] 网页扫码会话已启动", account_id)
|
||||
return {"ok": True, "resumed": False, **_public(st)}
|
||||
|
||||
|
||||
def status(account_id: str) -> dict:
|
||||
"""查询会话状态(前端轮询入口)。无会话时返回 idle。"""
|
||||
with _guard:
|
||||
st = _sessions.get(account_id)
|
||||
if not st:
|
||||
return {"status": "idle", "message": "", "qrcode": ""}
|
||||
if st["status"] == "waiting_scan":
|
||||
st["last_active"] = time.time()
|
||||
return _public(st)
|
||||
|
||||
|
||||
def cancel(account_id: str) -> dict:
|
||||
"""取消/终止会话并释放浏览器。"""
|
||||
with _guard:
|
||||
st = _sessions.get(account_id)
|
||||
if not st or st["status"] in ("success", "failed", "expired", "cancelled"):
|
||||
_sessions.pop(account_id, None)
|
||||
return {"ok": True, "message": "无进行中的扫码会话"}
|
||||
flag = _stop_flags.get(account_id)
|
||||
if flag:
|
||||
flag.set()
|
||||
# 给线程一点时间自行清理,随后强制标记
|
||||
for _ in range(30):
|
||||
time.sleep(0.1)
|
||||
with _guard:
|
||||
cur = _sessions.get(account_id)
|
||||
if not cur or cur["status"] not in ("queuing", "starting", "waiting_scan"):
|
||||
break
|
||||
else:
|
||||
with _guard:
|
||||
cur = _sessions.get(account_id)
|
||||
if cur and cur["status"] in ("waiting_scan",):
|
||||
cur["status"] = "cancelled"
|
||||
cur["message"] = "已取消"
|
||||
logger.info("[%s] 扫码会话已取消", account_id)
|
||||
return {"ok": True, "message": "已取消"}
|
||||
|
||||
|
||||
def _public(st: dict) -> dict:
|
||||
return {
|
||||
"status": st["status"],
|
||||
"message": st["message"],
|
||||
"qrcode": st["qrcode"] if st["status"] == "waiting_scan" else "",
|
||||
"error": st["error"],
|
||||
}
|
||||
|
||||
|
||||
def _set(aid: str, **fields) -> None:
|
||||
with _guard:
|
||||
st = _sessions.get(aid)
|
||||
if st is None:
|
||||
return
|
||||
st.update(fields)
|
||||
st["last_active"] = time.time()
|
||||
|
||||
|
||||
def _is_stopped(aid: str) -> bool:
|
||||
flag = _stop_flags.get(aid)
|
||||
return bool(flag and flag.is_set())
|
||||
|
||||
|
||||
def _launch_browser(pw):
|
||||
"""优先在 Xvfb 虚拟屏幕中启动有头 Chromium:真实有头内核的风控识别率远低于无头模式。
|
||||
|
||||
返回 (browser, xvfb_proc);Xvfb 不可用或启动失败时回退为无头模式。
|
||||
"""
|
||||
common = dict(
|
||||
args=[
|
||||
"--no-sandbox",
|
||||
"--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage",
|
||||
"--disable-gpu",
|
||||
"--disable-blink-features=AutomationControlled",
|
||||
"--disable-extensions",
|
||||
"--disable-software-rasterizer",
|
||||
# 小内存服务器 (2G) 防崩参数:限制渲染进程数、减少常驻进程
|
||||
"--renderer-process-limit=2",
|
||||
"--no-zygote",
|
||||
"--mute-audio",
|
||||
],
|
||||
# 排除自动化开关,与商业版 excludeSwitches 等效
|
||||
ignore_default_args=["--enable-automation"],
|
||||
)
|
||||
if shutil.which("Xvfb"):
|
||||
for _ in range(4):
|
||||
display = f":{random.randint(90, 180)}"
|
||||
try:
|
||||
xproc = subprocess.Popen(
|
||||
["Xvfb", display, "-screen", "0", "1280x800x24", "-nolisten", "tcp"],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
)
|
||||
time.sleep(0.8)
|
||||
if xproc.poll() is not None:
|
||||
continue # 显示号被占用等,换一个重试
|
||||
try:
|
||||
browser = pw.chromium.launch(
|
||||
headless=False, env={**os.environ, "DISPLAY": display}, **common
|
||||
)
|
||||
return browser, xproc
|
||||
except Exception:
|
||||
xproc.terminate()
|
||||
except Exception:
|
||||
continue
|
||||
return pw.chromium.launch(headless=True, **common), None
|
||||
|
||||
|
||||
def _session_worker(aid: str, stop_flag: threading.Event) -> None:
|
||||
pw = None
|
||||
browser = None
|
||||
xvfb_proc = None
|
||||
try:
|
||||
_acquire_slot_tracked(aid)
|
||||
if _is_stopped(aid):
|
||||
raise CancelledError()
|
||||
|
||||
_set(aid, status="starting", message="正在打开抖音登录页…")
|
||||
pw = sync_playwright().start()
|
||||
browser, xvfb_proc = _launch_browser(pw)
|
||||
# UA 版本号与真实内核保持一致,固定旧版本号容易被风控识别为伪造环境
|
||||
chrome_major = (browser.version or "").split(".")[0] or "124"
|
||||
context = browser.new_context(
|
||||
viewport={"width": 1366, "height": 900},
|
||||
user_agent=(
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
f"(KHTML, like Gecko) Chrome/{chrome_major}.0.0.0 Safari/537.36"
|
||||
),
|
||||
locale="zh-CN",
|
||||
timezone_id="Asia/Shanghai",
|
||||
ignore_https_errors=True,
|
||||
)
|
||||
# 与 2.1 商业版 stealth(webgl_vendor="Intel Inc.", renderer="Intel Iris OpenGL Engine") 对齐
|
||||
context.add_init_script(
|
||||
"const _spoof=(proto)=>{const g=proto.getParameter;"
|
||||
"proto.getParameter=function(p){if(p===37445)return 'Intel Inc.';"
|
||||
"if(p===37446)return 'Intel Iris OpenGL Engine';return g.apply(this,[p]);};};"
|
||||
"if(window.WebGLRenderingContext)_spoof(WebGLRenderingContext.prototype);"
|
||||
"if(window.WebGL2RenderingContext)_spoof(WebGL2RenderingContext.prototype);"
|
||||
)
|
||||
page = context.new_page()
|
||||
try:
|
||||
from .browser import _apply_stealth
|
||||
_apply_stealth(page)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
page.goto(CHAT_URL, timeout=60000, wait_until="domcontentloaded")
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 复刻 2.1 GetLoginPng 前置动作:收起面板残留 -> 切「扫码登录」标签 -> 点二维码容器
|
||||
try:
|
||||
page.locator(
|
||||
"#douyin_login_comp_flat_panel > div > div:nth-child(2) > div > div:nth-child(4) > p"
|
||||
).click(timeout=1500)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.get_by_text("扫码登录").first.click(timeout=1500)
|
||||
except Exception:
|
||||
pass
|
||||
page.wait_for_timeout(1000)
|
||||
try:
|
||||
page.locator("#animate_qrcode_container").first.click(timeout=1500)
|
||||
except Exception:
|
||||
pass
|
||||
page.wait_for_timeout(2000)
|
||||
|
||||
qr_data = _wait_and_extract_qrcode(page)
|
||||
if not qr_data:
|
||||
raise RuntimeError("未能从页面提取到登录二维码,请稍后重试")
|
||||
_set(aid, status="waiting_scan", message="请使用抖音 App 扫码登录", qrcode=qr_data)
|
||||
|
||||
deadline = time.time() + SESSION_TIMEOUT
|
||||
refresh_count = 0
|
||||
face_clicked = False
|
||||
polls = 0
|
||||
while time.time() < deadline:
|
||||
if _is_stopped(aid):
|
||||
raise CancelledError()
|
||||
|
||||
cookies = context.cookies("https://www.douyin.com")
|
||||
if any(c.get("name") in _LOGIN_COOKIE_NAMES and c.get("value") for c in cookies):
|
||||
_save_state(context, aid)
|
||||
_set(aid, status="success",
|
||||
message=f"登录成功!已保存该账号的登录态({len(cookies)} 条 Cookie)")
|
||||
logger.info("[%s] 网页扫码登录成功,state.json 已更新", aid)
|
||||
return
|
||||
|
||||
polls += 1
|
||||
if polls % 10 == 0:
|
||||
names = ",".join(sorted({c.get("name", "") for c in cookies if c.get("name")}))
|
||||
logger.info("[%s] 等待扫码确认中,当前 Cookie:%s", aid, names or "无")
|
||||
|
||||
if _qr_expired(page):
|
||||
refresh_count += 1
|
||||
if refresh_count > QR_REFRESH_LIMIT:
|
||||
raise RuntimeError("二维码刷新次数过多,请重新发起扫码")
|
||||
logger.info("[%s] 登录二维码已过期,第 %s 次自动刷新", aid, refresh_count)
|
||||
_click_qr_refresh(page)
|
||||
page.wait_for_timeout(2500)
|
||||
qr_data = _wait_and_extract_qrcode(page, timeout_ms=30000)
|
||||
if qr_data:
|
||||
_set(aid, qrcode=qr_data,
|
||||
message=f"二维码已自动刷新(第 {refresh_count} 次),请重新扫码")
|
||||
|
||||
# 复刻 2.1 GetCooker 的二次刷脸风控处理:确认登录后可能要求刷脸,
|
||||
# 页面会展示新二维码供手机扫描,需持续提取并点击「已完成」
|
||||
if not face_clicked:
|
||||
if _js_click_first(page, ["手机刷脸验证", "刷脸验证"]):
|
||||
face_clicked = True
|
||||
logger.info("[%s] 触发二次安全验证,已点击刷脸按钮", aid)
|
||||
_set(aid, message="触发安全验证:请用抖音 App 扫描下方新二维码并按提示完成验证")
|
||||
page.wait_for_timeout(3000)
|
||||
else:
|
||||
_js_click_first(page, ["已完成", "验证成功"])
|
||||
qr_face = _extract_face_qr(page)
|
||||
if qr_face:
|
||||
_set(aid, qrcode=qr_face)
|
||||
|
||||
page.wait_for_timeout(1500)
|
||||
|
||||
_set(aid, status="expired", message="扫码超时,请重新发起扫码", qrcode="")
|
||||
logger.info("[%s] 扫码会话超时结束", aid)
|
||||
|
||||
except CancelledError:
|
||||
_set(aid, status="cancelled", message="已取消", qrcode="")
|
||||
except Exception as e:
|
||||
msg = str(e)[:200]
|
||||
_set(aid, status="failed", message="扫码会话异常", error=msg, qrcode="")
|
||||
logger.warning("[%s] 扫码会话异常:%s", aid, msg)
|
||||
finally:
|
||||
if browser:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
if pw:
|
||||
try:
|
||||
pw.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if xvfb_proc:
|
||||
try:
|
||||
xvfb_proc.terminate()
|
||||
except Exception:
|
||||
pass
|
||||
_release_slot_once(aid)
|
||||
_stop_flags.pop(aid, None)
|
||||
# 终态保留 120 秒供前端读取,之后由 GC 或下次 start 清理
|
||||
threading.Timer(120, lambda: _sessions.pop(aid, None)).start()
|
||||
|
||||
|
||||
class CancelledError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def _js_click_first(page, texts: list[str]) -> bool:
|
||||
"""对包含指定文本的首个元素执行 JS 点击(绕过遮挡),成功返回 True。"""
|
||||
for t in texts:
|
||||
try:
|
||||
loc = page.get_by_text(t, exact=False)
|
||||
if loc.count():
|
||||
loc.first.evaluate("el => el.click()")
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
_FACE_QR_JS = """
|
||||
() => {
|
||||
const pick = (el) => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
if (rect.width < 100 || rect.width > 350 || Math.abs(rect.width - rect.height) > 15) return null;
|
||||
const src = el.src || "";
|
||||
if (src.includes("base64,")) return src;
|
||||
try {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = el.naturalWidth || rect.width;
|
||||
c.height = el.naturalHeight || rect.height;
|
||||
c.getContext("2d").drawImage(el, 0, 0, c.width, c.height);
|
||||
return c.toDataURL("image/png");
|
||||
} catch (e) { return null; }
|
||||
};
|
||||
const imgs = document.querySelectorAll("img");
|
||||
for (let i = imgs.length - 1; i >= 0; i--) {
|
||||
const r = pick(imgs[i]);
|
||||
if (r) return r;
|
||||
}
|
||||
const canvases = document.querySelectorAll("canvas");
|
||||
for (let j = canvases.length - 1; j >= 0; j--) {
|
||||
const c = canvases[j];
|
||||
const rect = c.getBoundingClientRect();
|
||||
if (rect.width >= 100 && rect.width <= 350 && Math.abs(rect.width - rect.height) <= 15) {
|
||||
try { return c.toDataURL("image/png"); } catch (e) {}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def _extract_face_qr(page) -> str | None:
|
||||
"""复刻 2.1 二次验证取码:按尺寸启发式扫描页面中的 img/canvas。"""
|
||||
try:
|
||||
data = page.evaluate(_FACE_QR_JS)
|
||||
return data if data and data.startswith("data:image") else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _wait_and_extract_qrcode(page, timeout_ms: int = 45000) -> str | None:
|
||||
"""等待二维码出现并提取为 data URL;失败时整页截图兜底。
|
||||
|
||||
容器冷启动首次加载可能超过 20s,窗口过短会把慢加载误判为失败。
|
||||
"""
|
||||
deadline = time.time() + timeout_ms / 1000
|
||||
src = ""
|
||||
while time.time() < deadline:
|
||||
for sel in _QR_SELECTORS:
|
||||
try:
|
||||
loc = page.locator(sel)
|
||||
if loc.count():
|
||||
first = loc.first
|
||||
if first.is_visible():
|
||||
candidate = first.get_attribute("src") or ""
|
||||
if len(candidate) > 50:
|
||||
src = candidate
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if src:
|
||||
break
|
||||
# 二维码可能在 iframe 中
|
||||
for frame in page.frames:
|
||||
if frame == page.main_frame:
|
||||
continue
|
||||
for sel in _QR_SELECTORS:
|
||||
try:
|
||||
loc = frame.locator(sel)
|
||||
if loc.count() and loc.first.is_visible():
|
||||
candidate = loc.first.get_attribute("src") or ""
|
||||
if len(candidate) > 50:
|
||||
src = candidate
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if src:
|
||||
break
|
||||
if src:
|
||||
break
|
||||
page.wait_for_timeout(800)
|
||||
|
||||
if src.startswith("data:image"):
|
||||
return src
|
||||
if src.startswith("http"):
|
||||
try:
|
||||
resp = requests.get(src, timeout=8)
|
||||
b64 = base64.b64encode(resp.content).decode()
|
||||
return f"data:image/png;base64,{b64}"
|
||||
except Exception:
|
||||
pass
|
||||
if src:
|
||||
return f"data:image/png;base64,{src}"
|
||||
# 兜底:整页截图(用户至少能看到登录框与二维码);渲染进程繁忙时可能瞬时失败,重试一次
|
||||
for _attempt in range(2):
|
||||
try:
|
||||
shot = page.screenshot(timeout=8000)
|
||||
return "data:image/png;base64," + base64.b64encode(shot).decode()
|
||||
except Exception:
|
||||
try:
|
||||
page.wait_for_timeout(1500)
|
||||
except Exception:
|
||||
break
|
||||
return None
|
||||
|
||||
|
||||
def _qr_expired(page) -> bool:
|
||||
"""检测二维码是否已过期(出现过期提示文本)。"""
|
||||
for text in _QR_EXPIRED_TEXTS:
|
||||
try:
|
||||
loc = page.get_by_text(text, exact=False)
|
||||
if loc.count():
|
||||
for i in range(min(loc.count(), 3)):
|
||||
if loc.nth(i).is_visible():
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def _click_qr_refresh(page) -> None:
|
||||
"""点击二维码区域的刷新按钮重新出码。"""
|
||||
candidates = [
|
||||
"#animate_qrcode_container",
|
||||
'div[class*="qrcode"]',
|
||||
'div[class*="refresh"]',
|
||||
]
|
||||
for sel in candidates:
|
||||
try:
|
||||
loc = page.locator(sel)
|
||||
if loc.count() and loc.first.is_visible():
|
||||
loc.first.click(timeout=3000)
|
||||
return
|
||||
except Exception:
|
||||
continue
|
||||
try:
|
||||
page.reload(wait_until="domcontentloaded")
|
||||
page.wait_for_timeout(3000)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _save_state(context, account_id: str) -> None:
|
||||
"""导出 storage_state 覆盖该账号 state.json(default 账号同步根目录副本)。"""
|
||||
state = context.storage_state()
|
||||
raw = _ensure_origins(state)
|
||||
path: Path = account_state_path(account_id)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
import json
|
||||
path.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
|
||||
if account_id == DEFAULT_ACCOUNT_ID:
|
||||
try:
|
||||
ROOT_STATE_PATH.write_text(json.dumps(raw, ensure_ascii=False), encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _ensure_origins(state) -> dict:
|
||||
"""storage_state 兼容处理:确保结构与上传校验一致(cookies 列表 + origins)。"""
|
||||
if isinstance(state, dict):
|
||||
state.setdefault("cookies", [])
|
||||
state.setdefault("origins", [])
|
||||
return state
|
||||
return {"cookies": [], "origins": []}
|
||||
@@ -0,0 +1,55 @@
|
||||
"""消息文案构建与防风控轮换引擎。
|
||||
|
||||
支持:
|
||||
1. 静态文案池随机抽取;
|
||||
2. 防连续重复算法(同一好友不连续两天发送相同文案);
|
||||
3. 节日与时间变量自动填充(如 [日期]、[时间])。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import random
|
||||
from datetime import datetime
|
||||
from typing import List, Optional
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
|
||||
def render_template(template: str) -> str:
|
||||
"""渲染消息模板,替换变量。"""
|
||||
msg = template.strip()
|
||||
now = datetime.now()
|
||||
|
||||
if "[日期]" in msg or "[date]" in msg.lower():
|
||||
date_str = now.strftime("%m月%d日")
|
||||
msg = msg.replace("[日期]", date_str).replace("[date]", date_str)
|
||||
|
||||
if "[时间]" in msg or "[time]" in msg.lower():
|
||||
time_str = now.strftime("%H:%M")
|
||||
msg = msg.replace("[时间]", time_str).replace("[time]", time_str)
|
||||
|
||||
return msg.strip()
|
||||
|
||||
|
||||
def build_message(templates: List[str], last_sent_msg: str = "") -> str:
|
||||
"""从模板池中选择一条消息,并尽量避免与上次发送的内容相同。"""
|
||||
if not templates:
|
||||
templates = ["🔥 续火花", "今天也要开心哦 🔥", "晚上好 🔥"]
|
||||
|
||||
# 预渲染所有候选
|
||||
candidates = []
|
||||
for t in templates:
|
||||
rendered = render_template(t)
|
||||
if rendered:
|
||||
candidates.append(rendered)
|
||||
|
||||
if not candidates:
|
||||
return "🔥 续火花"
|
||||
|
||||
# 过滤掉与上次相同的消息
|
||||
diff_candidates = [m for m in candidates if m != last_sent_msg]
|
||||
if diff_candidates:
|
||||
return random.choice(diff_candidates)
|
||||
|
||||
return random.choice(candidates)
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
"""运行状态与日志。运行结果持久化到账号目录 runtime.json,日志同时写文件与内存环形缓冲。
|
||||
|
||||
v0.4 按账号分权:日志路由器会根据行内的 [账号ID] 前缀(无前缀时回退读线程当前账号)
|
||||
把日志同步路由进对应账号的环形缓冲,`recent_account_logs()` 只返回该账号自己的日志。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
from collections import deque
|
||||
from pathlib import Path
|
||||
|
||||
from . import accounts
|
||||
from .config import DATA_DIR, account_dir, DEFAULT_ACCOUNT_ID
|
||||
|
||||
LOG_DIR = DATA_DIR / "logs"
|
||||
|
||||
# 行内账号标识:[default] 或 [acc_xxxxxxxx](与服务端所有 logger 调用一致)
|
||||
_ACCOUNT_RE = re.compile(r"\[(default|acc_[0-9a-f]{8})\]")
|
||||
|
||||
|
||||
def runtime_path(account_id: str | None = None) -> Path:
|
||||
return account_dir(account_id) / "runtime.json"
|
||||
|
||||
|
||||
_lock = threading.Lock()
|
||||
_ring_lock = threading.Lock()
|
||||
_ring: deque[str] = deque(maxlen=600)
|
||||
_account_rings: dict[str, deque[str]] = {} # account_id -> 该账号专属日志缓冲
|
||||
|
||||
|
||||
def _default() -> dict:
|
||||
return {"session_status": "unknown", "running": False, "last_run": None, "history": []}
|
||||
|
||||
|
||||
def load_runtime(account_id: str | None = None) -> dict:
|
||||
rt = _default()
|
||||
rp = runtime_path(account_id)
|
||||
if rp.exists():
|
||||
try:
|
||||
data = json.loads(rp.read_text(encoding="utf-8"))
|
||||
if isinstance(data, dict):
|
||||
rt.update(data)
|
||||
except Exception:
|
||||
pass
|
||||
return rt
|
||||
|
||||
|
||||
def _save(rt: dict, account_id: str | None = None) -> None:
|
||||
with _lock:
|
||||
d = account_dir(account_id)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
rp = runtime_path(account_id)
|
||||
rp.write_text(json.dumps(rt, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
|
||||
def set_running(value: bool, account_id: str | None = None) -> None:
|
||||
rt = load_runtime(account_id)
|
||||
rt["running"] = bool(value)
|
||||
_save(rt, account_id)
|
||||
|
||||
|
||||
def record_run(result: dict, account_id: str | None = None) -> None:
|
||||
rt = load_runtime(account_id)
|
||||
rt["last_run"] = result
|
||||
history = rt.get("history", [])
|
||||
history.insert(0, result)
|
||||
rt["history"] = history[:30]
|
||||
|
||||
if result.get("logged_out"):
|
||||
rt["session_status"] = "expired"
|
||||
elif result.get("ok") and not result.get("failed"):
|
||||
rt["session_status"] = "ok"
|
||||
elif result.get("ok"):
|
||||
rt["session_status"] = "partial"
|
||||
elif not result.get("failed"):
|
||||
rt["session_status"] = "ok"
|
||||
else:
|
||||
rt["session_status"] = "failed"
|
||||
_save(rt, account_id)
|
||||
|
||||
|
||||
def record_contacts(data: dict, account_id: str | None = None) -> None:
|
||||
rt = load_runtime(account_id)
|
||||
rt["contacts"] = data.get("names", [])
|
||||
rt["contacts_at"] = data.get("at")
|
||||
rt["contacts_error"] = data.get("error")
|
||||
_save(rt, account_id)
|
||||
|
||||
|
||||
def update_runtime(account_id: str | None = None, **fields) -> None:
|
||||
rt = load_runtime(account_id)
|
||||
rt.update(fields)
|
||||
_save(rt, account_id)
|
||||
|
||||
|
||||
def record_harvest(harvest_last: dict | None, account_id: str | None = None) -> None:
|
||||
"""持久化最近一次 creator 采集摘要,服务重启后不丢(台账数据本身持久化不受影响)。"""
|
||||
rt = load_runtime(account_id)
|
||||
if harvest_last is None:
|
||||
rt.pop("harvest_last", None)
|
||||
else:
|
||||
rt["harvest_last"] = harvest_last
|
||||
_save(rt, account_id)
|
||||
|
||||
|
||||
def load_harvest_last(account_id: str | None = None) -> dict | None:
|
||||
"""读取持久化的采集摘要;无记录返回 None。"""
|
||||
return load_runtime(account_id).get("harvest_last")
|
||||
|
||||
|
||||
class RoutingHandler(logging.Handler):
|
||||
"""统一日志路由:全局环形缓冲 + 按账号环形缓冲。
|
||||
|
||||
行内带 [账号ID] 前缀的日志按前缀归入该账号;不带前缀的回退到
|
||||
线程当前账号(accounts.set_current_account,由各工作线程设置),
|
||||
保证 automation 内部的发送细节日志也能出现在对应账号的日志页。
|
||||
"""
|
||||
|
||||
def emit(self, record: logging.LogRecord) -> None:
|
||||
try:
|
||||
line = self.format(record)
|
||||
m = _ACCOUNT_RE.search(line)
|
||||
aid = m.group(1) if m else (accounts.current_account() or "")
|
||||
with _ring_lock:
|
||||
_ring.append(line)
|
||||
if aid:
|
||||
_account_rings.setdefault(aid, deque(maxlen=600)).append(line)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def setup_logging() -> logging.Logger:
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
if logger.handlers:
|
||||
return logger
|
||||
logger.setLevel(logging.INFO)
|
||||
fmt = logging.Formatter("%(asctime)s [%(levelname)s] %(message)s")
|
||||
|
||||
LOG_DIR.mkdir(parents=True, exist_ok=True)
|
||||
fh = logging.FileHandler(LOG_DIR / "app.log", encoding="utf-8")
|
||||
fh.setFormatter(fmt)
|
||||
logger.addHandler(fh)
|
||||
|
||||
sh = logging.StreamHandler()
|
||||
sh.setFormatter(fmt)
|
||||
logger.addHandler(sh)
|
||||
|
||||
rh = RoutingHandler()
|
||||
rh.setFormatter(fmt)
|
||||
logger.addHandler(rh)
|
||||
return logger
|
||||
|
||||
|
||||
def recent_logs(n: int = 300) -> list[str]:
|
||||
return list(_ring)[-n:]
|
||||
|
||||
|
||||
def recent_account_logs(account_id: str, n: int = 300) -> list[str]:
|
||||
"""仅返回指定账号的日志(其他账号与全局启动日志不可见)。
|
||||
|
||||
内存缓冲为空时(如服务刚重启),回退扫描全局日志文件尾部按 [账号ID] 过滤。
|
||||
"""
|
||||
with _ring_lock:
|
||||
lines = list(_account_rings.get(account_id, ()))
|
||||
if not lines:
|
||||
try:
|
||||
log_file = LOG_DIR / "app.log"
|
||||
if log_file.exists():
|
||||
with log_file.open("r", encoding="utf-8", errors="replace") as f:
|
||||
f.seek(0, 2)
|
||||
size = f.tell()
|
||||
f.seek(max(0, size - 512 * 1024))
|
||||
tail = f.read().splitlines()
|
||||
lines = [l for l in tail if f"[{account_id}]" in l]
|
||||
except OSError:
|
||||
lines = []
|
||||
return lines[-n:]
|
||||
@@ -0,0 +1,160 @@
|
||||
"""每天定时触发发送任务(按账号独立注册 job)。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import random
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Callable
|
||||
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from apscheduler.triggers.cron import CronTrigger
|
||||
from apscheduler.triggers.date import DateTrigger
|
||||
|
||||
from .accounts import list_accounts
|
||||
from .config import DEFAULT_ACCOUNT_ID, load_config
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
TZ = "Asia/Shanghai"
|
||||
|
||||
_scheduler: BackgroundScheduler | None = None
|
||||
_run_func: Callable | None = None
|
||||
_harvest_func: Callable | None = None
|
||||
|
||||
|
||||
def _job_id(account_id: str, kind: str) -> str:
|
||||
return f"{kind}_{account_id}"
|
||||
|
||||
|
||||
def _daily_job(account_id: str) -> None:
|
||||
cfg = load_config(account_id)
|
||||
if not bool(cfg.get("auto_run_enabled", True)):
|
||||
logger.info("[%s] 自动运行已关闭(auto_run_enabled=false),本次定时任务跳过", account_id)
|
||||
return
|
||||
jitter = max(0, int(cfg.get("jitter_minutes", 30) or 30))
|
||||
if jitter:
|
||||
delay = random.uniform(0, jitter * 60)
|
||||
logger.info("[%s] 随机延迟 %.0f 秒后开始发送(抖动窗口 %s 分钟)", account_id, delay, jitter)
|
||||
time.sleep(delay)
|
||||
if _run_func:
|
||||
_run_func(account_id=account_id)
|
||||
|
||||
|
||||
def _harvest_job(account_id: str) -> None:
|
||||
if _harvest_func:
|
||||
_harvest_func(account_id=account_id)
|
||||
|
||||
|
||||
def configure(run_func: Callable, harvest_func: Callable | None = None) -> None:
|
||||
"""注册每日发送任务与(可选)周级 creator 采集任务,按账号逐个注册。"""
|
||||
global _scheduler, _run_func, _harvest_func
|
||||
_run_func = run_func
|
||||
_harvest_func = harvest_func
|
||||
if _scheduler is None:
|
||||
_scheduler = BackgroundScheduler(timezone=TZ)
|
||||
_scheduler.start()
|
||||
apply_schedule()
|
||||
|
||||
|
||||
def apply_schedule(account_id: str | None = None) -> None:
|
||||
"""按账号应用/更新定时任务。account_id 为 None 时对全部账号执行。"""
|
||||
if _scheduler is None:
|
||||
return
|
||||
|
||||
accounts = list_accounts()
|
||||
if account_id is not None:
|
||||
accounts = [a for a in accounts if a["id"] == account_id]
|
||||
if not accounts:
|
||||
return
|
||||
|
||||
for acc in accounts:
|
||||
aid = acc["id"]
|
||||
if not acc.get("enabled", True):
|
||||
_scheduler.remove_job(_job_id(aid, "daily_send"))
|
||||
_scheduler.remove_job(_job_id(aid, "weekly_harvest"))
|
||||
logger.info("[%s] 账号已停用,定时任务已移除", aid)
|
||||
continue
|
||||
|
||||
cfg = load_config(aid)
|
||||
hh, mm = cfg.get("schedule_time", "21:00").split(":")
|
||||
_scheduler.add_job(
|
||||
_daily_job,
|
||||
CronTrigger(hour=int(hh), minute=int(mm), timezone=TZ),
|
||||
args=[aid],
|
||||
id=_job_id(aid, "daily_send"),
|
||||
replace_existing=True,
|
||||
coalesce=True,
|
||||
misfire_grace_time=3600,
|
||||
)
|
||||
logger.info("[%s] 定时任务已更新:每天 %s:%s (%s)", aid, hh, mm, TZ)
|
||||
|
||||
# 周级 creator 抖音号采集(默认周一 03:00;off/空 = 关闭)
|
||||
day = str(cfg.get("schedule_harvest_day") or "off").strip().lower()
|
||||
if day in {"mon", "tue", "wed", "thu", "fri", "sat", "sun"} and _harvest_func:
|
||||
_scheduler.add_job(
|
||||
_harvest_job,
|
||||
CronTrigger(day_of_week=day, hour=3, minute=0, timezone=TZ),
|
||||
args=[aid],
|
||||
id=_job_id(aid, "weekly_harvest"),
|
||||
replace_existing=True,
|
||||
coalesce=True,
|
||||
misfire_grace_time=3600,
|
||||
)
|
||||
logger.info("[%s] 周级采集已更新:每周 %s 03:00 (%s)", aid, day, TZ)
|
||||
else:
|
||||
_scheduler.remove_job(_job_id(aid, "weekly_harvest"))
|
||||
if day not in {"mon", "tue", "wed", "thu", "fri", "sat", "sun"}:
|
||||
logger.info("[%s] 周级采集已关闭", aid)
|
||||
|
||||
|
||||
def _next_run(job) -> str | None:
|
||||
if job and job.next_run_time:
|
||||
return job.next_run_time.isoformat()
|
||||
return None
|
||||
|
||||
|
||||
def next_run_time(account_id: str | None = None) -> str | None:
|
||||
if _scheduler is None:
|
||||
return None
|
||||
if account_id is None:
|
||||
return next_run_time(DEFAULT_ACCOUNT_ID)
|
||||
return _next_run(_scheduler.get_job(_job_id(account_id, "daily_send")))
|
||||
|
||||
|
||||
def next_harvest_time(account_id: str | None = None) -> str | None:
|
||||
if _scheduler is None:
|
||||
return None
|
||||
if account_id is None:
|
||||
return next_harvest_time(DEFAULT_ACCOUNT_ID)
|
||||
return _next_run(_scheduler.get_job(_job_id(account_id, "weekly_harvest")))
|
||||
|
||||
|
||||
def schedule_retry(run_func: Callable, delay_minutes: int = 45, account_id: str | None = None) -> None:
|
||||
if _scheduler is None:
|
||||
return
|
||||
job_id = _job_id(account_id or DEFAULT_ACCOUNT_ID, "retry")
|
||||
if _scheduler.get_job(job_id):
|
||||
return
|
||||
run_at = datetime.now() + timedelta(minutes=delay_minutes)
|
||||
_scheduler.add_job(
|
||||
run_func,
|
||||
DateTrigger(run_date=run_at, timezone=TZ),
|
||||
id=job_id,
|
||||
replace_existing=True,
|
||||
)
|
||||
logger.info("[%s] 已安排 %s 分钟后自动补发本次失败的好友", account_id or DEFAULT_ACCOUNT_ID, delay_minutes)
|
||||
|
||||
|
||||
def cancel_retry(account_id: str | None = None) -> None:
|
||||
job_id = _job_id(account_id or DEFAULT_ACCOUNT_ID, "retry")
|
||||
if _scheduler and _scheduler.get_job(job_id):
|
||||
_scheduler.remove_job(job_id)
|
||||
logger.info("[%s] 已取消待执行的补发任务", account_id or DEFAULT_ACCOUNT_ID)
|
||||
|
||||
|
||||
def shutdown() -> None:
|
||||
global _scheduler
|
||||
if _scheduler:
|
||||
_scheduler.shutdown(wait=False)
|
||||
_scheduler = None
|
||||
@@ -0,0 +1,186 @@
|
||||
"""通道 B:creator 页首条消息发送(默认禁用,高风险)。
|
||||
|
||||
适用场景:对无会话好友发首条消息(想建立火花但还没聊过)。
|
||||
方案约束:
|
||||
- 默认禁用:需 config.allow_first_message = true(UI 显式勾选);
|
||||
- 单日 ≤1 条、每次运行 ≤1 人(在 run_send 层强制);
|
||||
- 按昵称滚动匹配命中后点击,绝不盲发;
|
||||
- 命中限流关键词立即停止本轮,不重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from ..browser import open_browser
|
||||
from ..config import DEFAULT_ACCOUNT_ID, account_state_path, load_config
|
||||
from ..guard import detect_rate_limit
|
||||
|
||||
logger = logging.getLogger("douyin-cloud-streak")
|
||||
|
||||
CREATOR_CHAT_URL = "https://creator.douyin.com/creator-micro/data/following/chat"
|
||||
|
||||
FRIENDS_TAB_CANDIDATES = [
|
||||
'xpath=//*[@id="sub-app"]/div/div/div[1]/div[2]',
|
||||
'xpath=//*[contains(text(),"好友")]',
|
||||
]
|
||||
|
||||
FRIEND_ITEM_SELECTOR = 'xpath=//div[contains(@class, "semi-list-item-body")]'
|
||||
NAME_SPAN_SELECTOR = 'xpath=.//span[contains(@class, "item-header-name-")]'
|
||||
CHAT_INPUT_SELECTOR = "xpath=//div[contains(@class, 'chat-input-')]"
|
||||
|
||||
SCROLL_JS = """
|
||||
() => {
|
||||
const els = document.querySelectorAll('[class*="semi-list"], #sub-app ul');
|
||||
let el = null;
|
||||
for (const e of els) { if (e.scrollHeight > e.clientHeight + 10) { el = e; break; } }
|
||||
if (!el) {
|
||||
const all = [...document.querySelectorAll('div')].filter(
|
||||
x => x.scrollHeight > x.clientHeight + 100 && x.clientHeight > 100
|
||||
);
|
||||
if (all.length) el = all[0];
|
||||
}
|
||||
if (el && el.scrollTop + el.clientHeight < el.scrollHeight - 10) {
|
||||
el.scrollTop += 600;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
def send_first_message(
|
||||
entry: dict,
|
||||
msg_text: str,
|
||||
dry_run: bool = False,
|
||||
playwright: object | None = None,
|
||||
account_id: str | None = None,
|
||||
) -> tuple[bool, str]:
|
||||
"""通过 creator 页给无会话好友发送首条消息。
|
||||
|
||||
playwright 参数:复用调用方已启动的 sync playwright 实例。
|
||||
返回 (是否成功, 说明)。
|
||||
"""
|
||||
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||
nickname = str(entry.get("nickname") or entry.get("display_name") or "").strip()
|
||||
if not nickname:
|
||||
return False, "台账缺少昵称/显示名,无法定位"
|
||||
cfg = load_config(aid)
|
||||
max_scrolls = int(cfg.get("creator_max_scrolls", 80) or 80)
|
||||
state_file = str(account_state_path(aid))
|
||||
|
||||
try:
|
||||
# 复用调用方的 playwright 实例
|
||||
if playwright is not None:
|
||||
p = playwright
|
||||
owns_p = False
|
||||
browser = p.chromium.launch(
|
||||
headless=True,
|
||||
args=["--no-sandbox", "--disable-setuid-sandbox",
|
||||
"--disable-dev-shm-usage", "--disable-gpu"],
|
||||
)
|
||||
try:
|
||||
context = browser.new_context(
|
||||
storage_state=state_file,
|
||||
viewport={"width": 1366, "height": 900},
|
||||
locale="zh-CN",
|
||||
)
|
||||
page = context.new_page()
|
||||
result = _do_send(page, context, nickname, msg_text, dry_run, max_scrolls)
|
||||
return result
|
||||
finally:
|
||||
try:
|
||||
browser.close()
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
ctx_kwargs = {"viewport": {"width": 1366, "height": 900}, "locale": "zh-CN"}
|
||||
with open_browser(state_path=account_state_path(aid), **ctx_kwargs) as (p, browser, context, page):
|
||||
return _do_send(page, context, nickname, msg_text, dry_run, max_scrolls)
|
||||
except Exception as e:
|
||||
logger.error("通道 B 发送异常: %s", e)
|
||||
return False, f"通道 B 异常: {e}"
|
||||
|
||||
|
||||
def _do_send(page, context, nickname: str, msg_text: str, dry_run: bool, max_scrolls: int) -> tuple[bool, str]:
|
||||
"""实际发送逻辑:打开页面 → 定位好友 → 输入消息 → 发送。"""
|
||||
page.goto(CREATOR_CHAT_URL, wait_until="domcontentloaded", timeout=90000)
|
||||
page.wait_for_timeout(10000)
|
||||
|
||||
if "passport" in page.url.lower() or "login" in page.url.lower():
|
||||
return False, f"creator 页跳转到登录页({page.url})"
|
||||
if not any(c["name"].startswith("sessionid") for c in context.cookies()):
|
||||
return False, "creator 页未检测到 sessionid cookie,登录态可能已过期"
|
||||
|
||||
# 点击「好友」tab
|
||||
for sel in FRIENDS_TAB_CANDIDATES:
|
||||
try:
|
||||
loc = page.locator(sel)
|
||||
if loc.count() and loc.first.is_visible():
|
||||
loc.first.click(timeout=3000)
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
page.wait_for_timeout(3000)
|
||||
|
||||
# 滚动列表,按昵称匹配并点击
|
||||
found = False
|
||||
stagnant = 0
|
||||
last_names: set[str] = set()
|
||||
for _ in range(max_scrolls):
|
||||
if detect_rate_limit(page):
|
||||
return False, "检测到「操作频繁/验证码」提示,通道 B 停止本轮"
|
||||
|
||||
items = page.locator(FRIEND_ITEM_SELECTOR).all()
|
||||
names_now: set[str] = set()
|
||||
for it in items:
|
||||
try:
|
||||
span = it.locator(NAME_SPAN_SELECTOR)
|
||||
if span.count() == 0:
|
||||
continue
|
||||
name = span.inner_text().strip()
|
||||
names_now.add(name)
|
||||
if name == nickname:
|
||||
it.click(timeout=5000)
|
||||
found = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if found:
|
||||
break
|
||||
|
||||
grew = len(names_now) > len(last_names)
|
||||
last_names = names_now
|
||||
try:
|
||||
moved = bool(page.evaluate(SCROLL_JS))
|
||||
except Exception:
|
||||
moved = False
|
||||
page.wait_for_timeout(500)
|
||||
if not moved and not grew:
|
||||
stagnant += 1
|
||||
if stagnant >= 6:
|
||||
break
|
||||
else:
|
||||
stagnant = 0
|
||||
|
||||
if not found:
|
||||
return False, f"好友列表未找到「{nickname}」(无会话好友可能不在列表中)"
|
||||
|
||||
try:
|
||||
page.wait_for_selector(CHAT_INPUT_SELECTOR, timeout=15000)
|
||||
except Exception:
|
||||
return False, "未找到聊天输入框"
|
||||
|
||||
if dry_run:
|
||||
return True, "dry-run(通道 B 定位成功)"
|
||||
|
||||
if detect_rate_limit(page):
|
||||
return False, "发送前检测到「操作频繁/验证码」提示"
|
||||
|
||||
input_box = page.locator(CHAT_INPUT_SELECTOR).first
|
||||
input_box.click()
|
||||
page.keyboard.type(msg_text, delay=100)
|
||||
page.keyboard.press("Enter")
|
||||
time.sleep(3)
|
||||
return True, "ok"
|
||||
Reference in New Issue
Block a user