初版:抖音自动续火花(从线上实例导出)
This commit is contained in:
@@ -0,0 +1,20 @@
|
|||||||
|
# 隐私保护:禁止将敏感数据打入镜像
|
||||||
|
data/
|
||||||
|
*.log
|
||||||
|
*.png
|
||||||
|
*.jpg
|
||||||
|
*.jpeg
|
||||||
|
|
||||||
|
# Python 缓存
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
|
||||||
|
# 版本控制
|
||||||
|
.git/
|
||||||
|
.gitignore
|
||||||
|
|
||||||
|
# 编辑器与系统文件
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
|
.idea/
|
||||||
|
.vscode/
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Web 服务监听端口与地址
|
||||||
|
PORT=8000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
|
||||||
|
# 网页管理后台访问令牌 (建议修改为长随机字符串)
|
||||||
|
AUTH_TOKEN=spark_secret_token_change_me
|
||||||
|
|
||||||
|
# 时区配置
|
||||||
|
TZ=Asia/Shanghai
|
||||||
|
|
||||||
|
# ── 用户登录系统(v0.4 按账号分权)──
|
||||||
|
# 是否开放网页自助注册(1=开放,0=仅管理员在「用户管理」中手动创建)
|
||||||
|
ALLOW_REGISTRATION=1
|
||||||
|
# 网页登录会话有效期(小时),默认 7 天
|
||||||
|
SESSION_TTL_HOURS=168
|
||||||
|
# 首次启动播种管理员 admin 的初始密码(不设置则用 AUTH_TOKEN 作为初始密码)
|
||||||
|
ADMIN_INITIAL_PASSWORD=070517
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
---
|
||||||
|
name: 🐛 Bug 报告
|
||||||
|
about: 创建一份问题报告以帮助我们修复缺陷
|
||||||
|
title: "[BUG] "
|
||||||
|
labels: bug
|
||||||
|
assignees: ''
|
||||||
|
---
|
||||||
|
|
||||||
|
**问题描述**
|
||||||
|
清晰简洁地描述遇到的问题。
|
||||||
|
|
||||||
|
**复现步骤**
|
||||||
|
1. 运行了什么命令 / 双击了哪个脚本:
|
||||||
|
2. 触发了什么操作:
|
||||||
|
3. 出现的错误提示或截图:
|
||||||
|
|
||||||
|
**运行环境**
|
||||||
|
- 操作系统: [如 Windows 11 / Ubuntu 22.04 / macOS]
|
||||||
|
- Python 版本: [如 Python 3.11]
|
||||||
|
- 运行模式: [如 Web 控制台 / CLI 命令行 / 云端 systemd]
|
||||||
|
|
||||||
|
**错误日志截图/输出**
|
||||||
|
```
|
||||||
|
在这里粘贴终端日志输出
|
||||||
|
```
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
name: 💡 功能建议 / 需求提出
|
||||||
|
about: 为本项目提出一个新的功能或优化建议
|
||||||
|
title: "[FEAT] "
|
||||||
|
labels: enhancement
|
||||||
|
assignees: ''
|
||||||
|
---
|
||||||
|
|
||||||
|
**您希望增加什么新功能?**
|
||||||
|
详细描述您期望的新特性或改进。
|
||||||
|
|
||||||
|
**应用场景 / 解决什么痛点?**
|
||||||
|
描述这个功能将如何帮助您或其他用户更好地使用本项目。
|
||||||
|
|
||||||
|
**可能的实现思路(可选)**
|
||||||
|
如果您有关于该功能实现的思路或建议,请在此补充。
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
.venv/
|
||||||
|
data/
|
||||||
|
__pycache__/
|
||||||
|
*.pyc
|
||||||
|
.env
|
||||||
|
state.json
|
||||||
|
*.zip
|
||||||
|
*.log
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
@echo off␍
|
||||||
|
title 抖音云端自动续火花 - 提取登录通行证␍
|
||||||
|
cd /d "%~dp0"␍
|
||||||
|
␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo 抖音云端自动续火花 - 提取登录通行证␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo.␍
|
||||||
|
␍
|
||||||
|
python --version >nul 2>&1␍
|
||||||
|
if errorlevel 1 (␍
|
||||||
|
echo [未检测到 Python 环境]␍
|
||||||
|
echo 正在为您打开 Python 官网下载页面...␍
|
||||||
|
start https://www.python.org/downloads/␍
|
||||||
|
echo.␍
|
||||||
|
echo 【提示】安装 Python 时,请务必勾选底部选项:␍
|
||||||
|
echo [√] Add Python to PATH␍
|
||||||
|
echo 安装完成后,请重新双击此脚本!␍
|
||||||
|
echo.␍
|
||||||
|
pause␍
|
||||||
|
exit /b␍
|
||||||
|
)␍
|
||||||
|
␍
|
||||||
|
echo [*] 正在检查并自动安装依赖包...␍
|
||||||
|
pip install -r requirements.txt >nul 2>&1␍
|
||||||
|
if errorlevel 1 (␍
|
||||||
|
echo [*] 正在使用国内镜像源加速下载依赖...␍
|
||||||
|
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt␍
|
||||||
|
)␍
|
||||||
|
␍
|
||||||
|
echo [*] 正在确保 Chromium 浏览器内核就绪...␍
|
||||||
|
playwright install chromium >nul 2>&1␍
|
||||||
|
␍
|
||||||
|
echo.␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo [*] 即将启动浏览器,请在弹出的网页右上角扫码登录抖音...␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo.␍
|
||||||
|
python extract_cookie.py␍
|
||||||
|
␍
|
||||||
|
echo.␍
|
||||||
|
pause␍
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
@echo off␍
|
||||||
|
title 抖音云端自动续火花 - 桌面端立即运行␍
|
||||||
|
cd /d "%~dp0"␍
|
||||||
|
␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo 抖音云端自动续火花 - 桌面端立即运行␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo.␍
|
||||||
|
␍
|
||||||
|
if not exist "data\state.json" (␍
|
||||||
|
if not exist "state.json" (␍
|
||||||
|
echo [提示] 未找到登录凭据 state.json!␍
|
||||||
|
echo 正在自动为您启动扫码登录程序...␍
|
||||||
|
python extract_cookie.py␍
|
||||||
|
)␍
|
||||||
|
)␍
|
||||||
|
␍
|
||||||
|
echo 请选择运行模式:␍
|
||||||
|
echo [1] 正式发送续火花 (默认)␍
|
||||||
|
echo [2] 模拟演练模式 (Dry-Run,不真正发送消息)␍
|
||||||
|
echo [3] 同步抖音联系人列表到本地台账␍
|
||||||
|
echo.␍
|
||||||
|
set /p choice="请输入数字 (1/2/3,直接回车默认1): "␍
|
||||||
|
␍
|
||||||
|
if "%choice%"=="2" (␍
|
||||||
|
echo.␍
|
||||||
|
echo [*] 正在以【模拟演练模式】启动...␍
|
||||||
|
python run_cli.py --dry-run␍
|
||||||
|
) else if "%choice%"=="3" (␍
|
||||||
|
echo.␍
|
||||||
|
echo [*] 正在同步联系人列表...␍
|
||||||
|
python run_cli.py --sync-contacts␍
|
||||||
|
) else (␍
|
||||||
|
echo.␍
|
||||||
|
echo [*] 正在启动【正式发送】...␍
|
||||||
|
python run_cli.py␍
|
||||||
|
)␍
|
||||||
|
␍
|
||||||
|
echo.␍
|
||||||
|
pause␍
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
@echo off␍
|
||||||
|
title 抖音云端自动续火花 - 启动 Web 管理后台␍
|
||||||
|
cd /d "%~dp0"␍
|
||||||
|
␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo 抖音云端自动续火花 - 启动 Web 管理后台␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo.␍
|
||||||
|
␍
|
||||||
|
if not exist ".env" (␍
|
||||||
|
if exist ".env.example" (␍
|
||||||
|
copy .env.example .env >nul␍
|
||||||
|
) else (␍
|
||||||
|
echo PORT=8000 > .env␍
|
||||||
|
echo HOST=0.0.0.0 >> .env␍
|
||||||
|
echo AUTH_TOKEN=spark_secret_token_change_me >> .env␍
|
||||||
|
)␍
|
||||||
|
)␍
|
||||||
|
␍
|
||||||
|
echo [*] 正在启动 Web 管理后台服务...␍
|
||||||
|
echo [*] 服务地址: http://127.0.0.1:8000␍
|
||||||
|
echo.␍
|
||||||
|
echo [*] 正在自动打开默认浏览器...␍
|
||||||
|
start http://127.0.0.1:8000␍
|
||||||
|
␍
|
||||||
|
echo.␍
|
||||||
|
echo [提示] 保持此窗口开启即可维持后台服务。关闭窗口将停止服务。␍
|
||||||
|
echo =======================================================␍
|
||||||
|
echo.␍
|
||||||
|
python app.py␍
|
||||||
|
␍
|
||||||
|
pause␍
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@echo off␍
|
||||||
|
title 抖音云端自动续火花 - 同步登录凭证到云服务器␍
|
||||||
|
cd /d "%~dp0"␍
|
||||||
|
␍
|
||||||
|
python sync_to_server.py␍
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
@echo off␍
|
||||||
|
title 抖音云端自动续火花 - 一键全自动部署到云服务器␍
|
||||||
|
cd /d "%~dp0"␍
|
||||||
|
␍
|
||||||
|
python deploy_to_server.py␍
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# 贡献指南 (Contributing Guide)
|
||||||
|
|
||||||
|
欢迎参与 **Douyin Cloud Streak Pro** 的开发与维护!无论是提交 Bug 反馈、完善文档还是提交功能代码,我们都非常感谢您的贡献。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🛠️ 本地开发环境准备
|
||||||
|
|
||||||
|
1. **Fork 本仓库** 到你自己的 GitHub 账号;
|
||||||
|
2. **克隆代码到本地**:
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/<你的用户名>/douyin-cloud-streak.git
|
||||||
|
cd douyin-cloud-streak
|
||||||
|
```
|
||||||
|
3. **创建 Python 虚拟环境并安装依赖**:
|
||||||
|
```bash
|
||||||
|
python -m venv .venv
|
||||||
|
# Windows 激活
|
||||||
|
.venv\Scripts\activate
|
||||||
|
# Linux/macOS 激活
|
||||||
|
source .venv/bin/activate
|
||||||
|
|
||||||
|
pip install -r requirements.txt
|
||||||
|
playwright install chromium
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 代码提交规范 (Pull Request)
|
||||||
|
|
||||||
|
1. **创建功能分支**:
|
||||||
|
```bash
|
||||||
|
git checkout -b feature/your-feature-name
|
||||||
|
# 或者修复分支
|
||||||
|
git checkout -b fix/your-bug-fix
|
||||||
|
```
|
||||||
|
2. **保持代码风格统一**:
|
||||||
|
- Python 代码遵循 PEP 8 规范;
|
||||||
|
- 保持路径的相对自感知设计(避免硬编码任何绝对路径);
|
||||||
|
- 前端采用标准的现代 CSS Glassmorphism 规范与 Vue 3 Composition API。
|
||||||
|
3. **本地测试验证**:
|
||||||
|
- 运行 `python run_cli.py --dry-run` 确保 CLI 运行正常;
|
||||||
|
- 运行 `python app.py` 确保 Web 控制台能正常打开与交互。
|
||||||
|
4. **提交 PR**:
|
||||||
|
- 提交前请清晰描述您所做的更改及解决的问题。
|
||||||
+44
@@ -0,0 +1,44 @@
|
|||||||
|
FROM python:3.11-slim
|
||||||
|
|
||||||
|
# 设置工作目录
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
# 设置时区与环境变量
|
||||||
|
ENV TZ=Asia/Shanghai \
|
||||||
|
DEBIAN_FRONTEND=noninteractive \
|
||||||
|
PYTHONUNBUFFERED=1
|
||||||
|
|
||||||
|
# 安装系统渲染依赖
|
||||||
|
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||||
|
tzdata \
|
||||||
|
libnss3 \
|
||||||
|
libnspr4 \
|
||||||
|
libasound2 \
|
||||||
|
libatk1.0-0 \
|
||||||
|
libatk-bridge2.0-0 \
|
||||||
|
libcups2 \
|
||||||
|
libdrm2 \
|
||||||
|
libxkbcommon0 \
|
||||||
|
libxcomposite1 \
|
||||||
|
libxdamage1 \
|
||||||
|
libxfixes3 \
|
||||||
|
libxrandr2 \
|
||||||
|
libgbm1 \
|
||||||
|
libpango-1.0-0 \
|
||||||
|
libcairo2 \
|
||||||
|
xvfb \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
|
||||||
|
# 复制依赖清单并安装
|
||||||
|
COPY requirements.txt .
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt && \
|
||||||
|
playwright install --with-deps chromium || playwright install chromium
|
||||||
|
|
||||||
|
# 复制源码
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# 暴露端口
|
||||||
|
EXPOSE 8000
|
||||||
|
|
||||||
|
# 启动命令
|
||||||
|
CMD ["python", "app.py"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Douyin Spark Keeper Contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,254 @@
|
|||||||
|
# 抖音云端自动续火花 3.0 正式版 · 零基础纯小白完整教程 (Douyin Cloud Streak)
|
||||||
|
|
||||||
|
> 🎁 **【福利】新手免费获取云服务器教程(零成本搭建)**:
|
||||||
|
> * 🆓 **白嫖 MonkeyCode 理论永久服务器教程**:👉 [DOCX 下载点击查看](https://ncstatic-file.clewm.net/rsrc/2026/0809/10/785d5018effb6e5e4dbbc25f4bdcaef7.docx)
|
||||||
|
> * 🎓 **白嫖阿里云服务器 300 学生优惠(免费至少半年)**:👉 [DOCX 下载点击查看](https://ncstatic-file.clewm.net/rsrc/2026/0809/10/4d72a60d69ad91eef2fe2bea28086b79.docx)
|
||||||
|
|
||||||
|
> 💡 **这是什么**:用一台云服务器(或你家里的常开电脑),每天在你设定的时间(如 **21:00**)自动给你的抖音好友发一条消息(如 🔥),帮你把「火花 / 连续聊天天数」一直养下去——再也不用每天定闹钟手动发。
|
||||||
|
>
|
||||||
|
> 👶 **给零基础小白的话**:本教程假设你**完全没有碰过服务器、没写过任何代码**。从领免费服务器、扫码登录,到一键部署和网页端勾选好友,每一步都写清楚了「点哪里、输什么、会看到什么」,跟着做 **10 分钟** 即可搞定!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. 能做什么 / 注意事项
|
||||||
|
|
||||||
|
| ✅ 能做的 | ⚠️ 注意 / 限制 |
|
||||||
|
|---|---|
|
||||||
|
| 每天定时自动给**选中的火花好友**发消息(内容与时间随时在网页上修改) | 依赖抖音网页版登录态,Cookie 会定期过期(几天到几周),过期后在网页上重新扫码即可 |
|
||||||
|
| **图形化网页后台**:一键自动识别火花好友,点点鼠标就能管理 | 抖音对「机房 IP + 异地登录」较敏感,强烈建议先用小号试跑确认 |
|
||||||
|
| **云端 24 小时全自动运行**,关掉电脑、断网、手机关机也照常执行 | 需要一台国内云服务器(或家里一台不关机的旧电脑) |
|
||||||
|
| **极速一键部署**:双击脚本输入 IP 密码,全自动完成安装启动 | 云服务器安全组需放行 **22 端口 (SSH)** 与 **8000 端口 (Web控制台)** |
|
||||||
|
| **🆕 手机直接扫码登录**:部署完成后用手机浏览器打开控制台,在「凭证」页点一下就能扫码登录,全程可以不用电脑提取凭证 | 扫码偶尔会触发抖音二次安全验证(如刷脸),按网页提示继续扫新二维码即可 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 新手先看:我该点哪个脚本?1~5 号按钮都是干嘛的?
|
||||||
|
|
||||||
|
项目文件夹里有 **5 个带编号的脚本**,每个都是一个独立功能按钮:
|
||||||
|
|
||||||
|
### 1.1 五个编号脚本作用速查表
|
||||||
|
|
||||||
|
| 脚本 | 名字 | 什么时候需要点它 | 点了会发生什么 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| **`1.本地提取通行证.bat`** | 电脑上提取登录凭证 | 只有走「路线 B」时才需要。会弹出一个浏览器窗口,你用手机抖音扫码登录,程序把登录凭证保存在自己电脑上 | 自动装好依赖 → 弹出 Chromium 浏览器打开抖音登录页 → 你扫码 → 回车保存 `data\state.json` |
|
||||||
|
| **`2.桌面端立即运行.bat`** | 电脑上立刻跑一次任务 | 只用「家里电脑运行」模式时才会用到。可选正式发送 / 模拟演练 / 仅同步好友列表三种模式 | 直接在电脑上执行一次续火花流程(不发消息的演练模式也有) |
|
||||||
|
| **`3.启动管理后台.bat`** | 在自己电脑上启动网页控制台 | 只用「家里电脑运行」模式时才需要。启动后浏览器自动打开 `http://127.0.0.1:8000` | 启动 Web 控制台并自动打开浏览器,黑框窗口保持开着就一直运行 |
|
||||||
|
| **`4.同步登录态到服务器.bat`** | 把电脑上的凭证秒传到服务器 | 只有走「路线 B」且凭证过期时才需要。输入服务器 IP 和密码,1 秒传完 | 把本机 `data\state.json` 上传到服务器对应账号目录,云端立即生效 |
|
||||||
|
| **`5.一键部署整站到服务器.bat`** | 全自动把整个项目装到云服务器 | **⭐ 最常用的一个!首次部署必点**。输入服务器 IP 和密码,全自动完成一切 | 自动打包上传 → 远程安装环境 → 注册开机自启 → 输出你的专属网址 `http://服务器IP:8000` |
|
||||||
|
|
||||||
|
> 📌 **一句话记住**:买好服务器后,**只需要点 `5`** 就能完成部署;之后登录、管理好友全部在**手机/电脑浏览器网页**里完成。`1` 和 `4` 是给不想用网页扫码的老用户的备选方案,`2` 和 `3` 是给不用云服务器、想在自己电脑上跑的人准备的。
|
||||||
|
|
||||||
|
### 1.2 两条部署路线,选一条跟着做
|
||||||
|
|
||||||
|
| | 🌟 路线 A:纯手机全流程(推荐) | 路线 B:电脑提取凭证(传统) |
|
||||||
|
|---|---|---|
|
||||||
|
| **适合谁** | 所有人,尤其是没有电脑 / 不想折腾的 | 之前用过老版本的用户 |
|
||||||
|
| **需要点** | 只点 **`5`** | 点 **`1`** → 点 **`5`** → 点 **`4`** |
|
||||||
|
| **登录方式** | 手机浏览器打开网址,在网页「凭证」页**直接扫码** | 先在电脑浏览器扫码提取,再上传到服务器 |
|
||||||
|
| **总共耗时** | 约 10 分钟 | 约 15 分钟 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 第一步:准备一台国内云服务器(重要)
|
||||||
|
|
||||||
|
### 2.1 为什么强烈建议买「国内、最好同城」的服务器?
|
||||||
|
抖音判断「是不是你本人在登录」,核心依据是 **登录 IP 的城市特征**:
|
||||||
|
1. **IP 归属地一致性**:如果你常住**上海**,服务器也买在**上海**节点,登录 IP 和日常城市完全吻合,被风控拦截的概率极低;
|
||||||
|
2. **避免境外节点**:境外节点(香港、日本、美国等)极易触发抖音「境外/异地登录」风控,导致消息发不出去或频繁弹验证码;
|
||||||
|
3. **低延迟稳定**:同城网络延迟仅几毫秒,页面秒加载,任务执行最稳定。
|
||||||
|
|
||||||
|
> 💡 **购买推荐**:阿里云「轻量应用服务器」或腾讯云「轻量服务器」,选择 **Ubuntu 22.04 / 24.04 64位** 系统,设置好 **root 登录密码**。
|
||||||
|
|
||||||
|
### 2.2 关键设置:放行防火墙端口(防网页打不开)
|
||||||
|
服务器创建好后,打开云控制台的 **「防火墙 / 安全组」** 设置,确保添加了以下两条入方向规则:
|
||||||
|
* **`22 端口 (TCP)`**:用于本地连接服务器进行一键部署;
|
||||||
|
* **`8000 端口 (TCP)`**:用于打开网页控制台管理好友。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 第二步(路线 A):双击 `5`,一键部署到云服务器
|
||||||
|
|
||||||
|
无需掌握任何 Linux 命令,无需手动敲 SSH,双击即可全自动完成整站配置!
|
||||||
|
|
||||||
|
1. 把本项目源码下载解压到**任意一台装有 Python 的电脑**上(借朋友的电脑装一次也行,部署完就还回去 😄);
|
||||||
|
2. 打开文件夹,**双击运行**:
|
||||||
|
👉 **`5.一键部署整站到服务器.bat`**
|
||||||
|
3. 按屏幕提示依次输入(记不清的直接回车用默认值):
|
||||||
|
|
||||||
|
| 提示 | 输入什么 |
|
||||||
|
|---|---|
|
||||||
|
| 👉 云服务器公网 IP 地址 | 你的服务器 IP,例如 `123.45.67.89`(云控制台首页复制) |
|
||||||
|
| 👉 SSH 用户名 | 直接回车(默认 `root`) |
|
||||||
|
| 👉 SSH 端口号 | 直接回车(默认 `22`) |
|
||||||
|
| 👉 部署路径 | 直接回车(默认 `/opt/douyin-cloud-streak`) |
|
||||||
|
| 🔑 服务器密码 | 你的 root 密码(支持右键粘贴,输入时明文可见) |
|
||||||
|
|
||||||
|
4. 脚本会在 **1~2 分钟内** 全自动完成:
|
||||||
|
* 生产代码极速打包与秒级上传;
|
||||||
|
* 自动配置 Python 虚拟环境与 Playwright 浏览器内核;
|
||||||
|
* 自动注册 Linux Systemd 开机自启守护进程并启动服务!
|
||||||
|
5. 当屏幕输出下面的信息时,部署就全部搞定了:
|
||||||
|
|
||||||
|
```
|
||||||
|
🎉🎉🎉 恭喜!云服务器已全部部署完成并成功启动!
|
||||||
|
🌐 Web 管理后台地址: http://123.45.67.89:8000 ← 这就是你的专属网址
|
||||||
|
🔑 访问安全令牌 (Token): spark_secret_token_change_me
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 第三步(路线 A):手机打开网址,直接扫码登录 🆕
|
||||||
|
|
||||||
|
**从这一步开始,再也不需要电脑了,一部手机搞定!**
|
||||||
|
|
||||||
|
1. 用手机浏览器(或电脑浏览器)打开刚才输出的网址:
|
||||||
|
👉 **`http://你的服务器IP:8000`**
|
||||||
|
2. 若提示输入访问令牌 Token:点击右上角「**令牌**」,填入部署完成时显示的 Token(默认 `spark_secret_token_change_me`)后保存;
|
||||||
|
3. 点击左侧菜单进入 **「凭证」** 页面;
|
||||||
|
4. 点击蓝色的 **「📱 手机扫码登录」** 按钮,会先弹出一份《扫码须知》,确认自己已备好手机后点击「**已备好手机,开始扫码**」;
|
||||||
|
5. 页面会在 **20~40 秒** 内生成二维码 → 用**另一台手机的抖音 App** 扫一扫(或者截图后用抖音内置扫一扫识别相册图片);
|
||||||
|
|
||||||
|
> 💡 也可以直接用当前这台手机:长按二维码保存图片,再到抖音 App「我-右上角菜单-扫一扫-相册」选取该图片。
|
||||||
|
6. 扫码确认后,页面提示「登录成功」即大功告成!
|
||||||
|
|
||||||
|
### ❓ 关于「人脸验证」的疑问:登录一定要刷脸吗?
|
||||||
|
|
||||||
|
**不是的,平时登录就是普通的扫二维码,90% 以上的情况直接扫码就成功了。**
|
||||||
|
|
||||||
|
你遇到的「人脸验证」,其实是抖音的**二次安全验证(风控)**机制,跟本项目的登录方式无关:
|
||||||
|
|
||||||
|
| 场景 | 发生了什么 | 你要做什么 |
|
||||||
|
|---|---|---|
|
||||||
|
| ✅ 绝大多数情况 | 扫码确认后直接登录成功 | 无 |
|
||||||
|
| ⚠️ 偶尔触发风控 | 抖音要求「二次验证」,页面出现**新的二维码**,常见形式是「手机刷脸验证」 | 按网页提示,用抖音 App 扫这个新二维码,在手机上完成刷脸/确认后回到网页,系统会自动检测通过 |
|
||||||
|
|
||||||
|
几点说明:
|
||||||
|
1. **是否触发验证、给哪种验证方式(刷脸 / 短信等),完全由抖音的风控系统临时决定**,任何工具都无法指定;本项目已按商业版逻辑实现了「刷脸验证」分支的自动化引导,实测可通过;
|
||||||
|
2. 触发概率与服务器 IP 归属地有关——这也是教程反复强调**买同城国内节点**的原因;
|
||||||
|
3. 如果实在过不了验证,可改走「路线 B」:在家里常用网络的电脑上双击 `1.本地提取通行证.bat` 登录(家庭宽带 IP 风控最宽松),再用 `4` 上传到服务器。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 第四步:同步联系人,勾选好友,开启自动续火花
|
||||||
|
|
||||||
|
### 5.1 同步并勾选火花好友(3 步搞定)
|
||||||
|
1. 在左侧菜单点击进入 **「好友」** 页面;
|
||||||
|
2. 点击上方 **「🚀 同步联系人」** 按钮,系统会在后台自动拉取你的抖音好友列表与当前火花天数(约 10~30 秒,人多会稍慢,请勿关闭页面),列表默认**按火花天数从高到低排列**;
|
||||||
|
3. 点击 **「✨ 一键勾选火花好友」**(系统自动勾选所有带火花的好友),也可手动增删;
|
||||||
|
4. 最后点击 **「💾 保存勾选配置」** 生效!
|
||||||
|
|
||||||
|
### 5.2 设置发送时间与内容(可选)
|
||||||
|
* 点击左侧 **「定时」**:
|
||||||
|
* **定时时间**:默认每天 `21:00`,可随意修改;
|
||||||
|
* **随机浮动时间**:如 `30` 分钟(系统会在 20:30~21:30 之间随机挑选时间发送,模拟真人行为);
|
||||||
|
* **发送内容**:默认每行一条(支持 `🔥`、`早安`、`今天也要开心哦` 等自定义文案);
|
||||||
|
* 修改后点击 **「保存设置」** 即可实时生效,无需重启!
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 路线 B(备选):在电脑上提取凭证再上传
|
||||||
|
|
||||||
|
如果你更习惯老版本的方式,或网页扫码遇到风控过不去,走这条路:
|
||||||
|
|
||||||
|
1. 在本地电脑双击 **`1.本地提取通行证.bat`**:脚本自动装依赖 → 弹出浏览器 → 手机抖音扫码登录 → 回到黑框按回车,提示 `[✓] 登录凭证提取成功!`;
|
||||||
|
2. 双击 **`5.一键部署整站到服务器.bat`** 完成部署(见第 3 步);
|
||||||
|
3. 双击 **`4.同步登录态到服务器.bat`**:输入服务器 IP 和密码,把刚提取的凭证秒传上去;
|
||||||
|
4. 打开 `http://服务器IP:8000` 即可直接去同步好友、勾选保存。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 备选方案:不买服务器,用家里电脑运行
|
||||||
|
|
||||||
|
如果不想购买云服务器,也可以直接用家里**长期开机的旧电脑/台式机**运行:
|
||||||
|
|
||||||
|
1. 双击 **`1.本地提取通行证.bat`** 提取登录凭证;
|
||||||
|
2. 双击 **`3.启动管理后台.bat`**,浏览器自动打开 `http://127.0.0.1:8000`;
|
||||||
|
3. 同样在「好友」页同步并勾选保存,「定时」页设置时间;
|
||||||
|
4. 保持黑色窗口开启(可最小化),电脑就会每日按时自动续火花!
|
||||||
|
(进阶:双击 `2.桌面端立即运行.bat` 可随时手动跑一次,支持模拟演练模式。)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 日常维护:凭证过期了怎么办?
|
||||||
|
|
||||||
|
由于抖音安全机制,网页登录态一般维持 **几天到几周** 后会自然过期。当控制台顶部提示「未检测到登录凭证」或发送失败提示登录失效时:
|
||||||
|
|
||||||
|
| 你用的路线 | 复活方法 |
|
||||||
|
|---|---|
|
||||||
|
| 🌟 路线 A(网页扫码) | 打开控制台 → 「凭证」页 → 再点一次「📱 手机扫码登录」重新扫即可,**30 秒搞定** |
|
||||||
|
| 路线 B(电脑提取) | 电脑双击 `1.本地提取通行证.bat` 重新扫码 → 双击 `4.同步登录态到服务器.bat` 上传 |
|
||||||
|
|
||||||
|
凭证更新后云端自动无缝采用,无需重新部署。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 常见问题排错 (FAQ)
|
||||||
|
|
||||||
|
### Q1: 部署完成后,浏览器打不开 `http://服务器IP:8000`?
|
||||||
|
* **检查 1**:请在云厂商控制台「**防火墙 / 安全组**」中放行 **8000 端口 (TCP)** 入方向规则;
|
||||||
|
* **检查 2**:确认访问地址格式为 `http://` 开头(本系统暂不支持 https 直连)。
|
||||||
|
|
||||||
|
### Q2: 扫码页面的二维码一直出不来 / 显示等待超时?
|
||||||
|
* 二维码生成约需 **20~40 秒**(首次冷启动稍慢),请耐心等待并留意弹窗提示;
|
||||||
|
* 若超过 1 分钟仍无二维码,点击「取消」后重新发起一次;
|
||||||
|
* 多次失败通常是服务器网络无法访问抖音,可在「日志」页查看具体报错。
|
||||||
|
|
||||||
|
### Q3: 扫码后一直转圈不出结果?
|
||||||
|
* 大概率触发了二次安全验证:请仔细观察页面上的提示与新出现的二维码,按第 4 步的「人脸验证」说明处理;
|
||||||
|
* 仍未解决可点「取消」释放名额,等 1 分钟后重试。
|
||||||
|
|
||||||
|
### Q4: 点击「同步联系人」或「立即续火花」提示执行中,怎么停止?
|
||||||
|
* 在网页顶部点击红色的 **「强制停止 / 重置」** 按钮,系统会秒级释放后台锁并恢复空闲状态。
|
||||||
|
|
||||||
|
### Q5: 换了一台新电脑使用,程序怎么找到项目文件?
|
||||||
|
* 本项目全部采用 **动态相对寻路(`%~dp0` 与 `Path(__file__)`)**,无论放在桌面、D 盘还是移动硬盘,直接双击运行即可,无需配置路径。
|
||||||
|
|
||||||
|
### Q6: 如何查看真实的运行日志?
|
||||||
|
* 网页端点击左侧 **「日志」** 页实时查看;
|
||||||
|
* 服务器端可执行:`journalctl -u douyin-cloud-streak -f`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 多账号同时续火花 (Multi-Account)
|
||||||
|
|
||||||
|
支持**一个服务同时管理多个抖音账号**,每个账号独立登录、独立勾选好友、独立定时:
|
||||||
|
|
||||||
|
### 10.1 核心特性
|
||||||
|
- **数据完全隔离**:每个账号拥有独立的 `data/accounts/{id}/` 目录,互不串数据,删除账号自动归档;
|
||||||
|
- **独立定时任务**:每个账号可设置各自的发送时间,调度器按账号分别注册 job;
|
||||||
|
- **全局并发保护**:同时最多开 **5 个**浏览器会话(可在 `core/accounts.py` 的 `MAX_CONCURRENT_BROWSERS` 修改),超出自动排队,防风控;
|
||||||
|
- **兼容旧版**:原 `data/` 根目录数据自动作为 **默认账号(default)** 原地生效,零迁移升级。
|
||||||
|
|
||||||
|
### 10.2 使用步骤
|
||||||
|
1. 网页后台左侧点 **「账号」** → **「+ 新建账号」**;
|
||||||
|
2. 顶部下拉框切换到新账号 → 「凭证」页扫码登录或上传 `state.json`;
|
||||||
|
3. 「好友」页同步并勾选 →「定时」页设置发送时间;
|
||||||
|
4. 「账号」页可查看各账号状态,支持启停 / 改名 / 删除。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 目录文件速查
|
||||||
|
|
||||||
|
| 文件 / 文件夹 | 作用说明 | 运行环境 |
|
||||||
|
|---|---|---|
|
||||||
|
| `1.本地提取通行证.bat` | 电脑端唤起浏览器扫码,生成登录凭证 | 本地 Windows 双击 |
|
||||||
|
| `2.桌面端立即运行.bat` | 电脑端立即跑一次任务(正式/演练/仅同步三选一) | 本地 Windows 双击 |
|
||||||
|
| `3.启动管理后台.bat` | 启动本地 Web 管理控制台 (`:8000`) 并自动打开浏览器 | 本地 Windows 双击 |
|
||||||
|
| `4.同步登录态到服务器.bat` | 凭证过期后,一键将新凭证同步到云服务器 | 本地 Windows 双击 |
|
||||||
|
| `5.一键部署整站到服务器.bat` | ⭐ 全自动打包整站、上传并在云服务器完成部署 | 本地 Windows 双击 |
|
||||||
|
| `app.py` | Web 后端服务(Flask):API、扫码会话、多账号管理 | 云端 / 本地 Python |
|
||||||
|
| `core/` | 自动化引擎、扫码登录会话、多账号、台账与调度底层模块 | Python 核心库 |
|
||||||
|
| `static/` | 黑白极简风 Web 前端管理控制台 | 静态网页 |
|
||||||
|
| `run_cli.py` | 命令行运行入口(供脚本 2 调用,也支持多账号参数) | Python CLI |
|
||||||
|
| `extract_cookie.py` | 电脑端凭证提取脚本(供脚本 1 调用) | 本地 Python |
|
||||||
|
| `sync_to_server.py` / `deploy_to_server.py` | 凭证同步 / 整站部署的 Python 实现(供脚本 4 / 5 调用) | 本地 Python |
|
||||||
|
| `Dockerfile` / `docker-compose.yml` | Docker 容器化部署方案(可选) | Docker |
|
||||||
|
| `data/` | 运行数据目录(多账号在 `data/accounts/{id}/`,已自动忽略防止隐私泄露) | 本地存储 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 12. 免责声明与合规提示 (Disclaimer)
|
||||||
|
|
||||||
|
1. 本项目仅供个人学习、自动化测试与亲友间互动交流使用;
|
||||||
|
2. 请合理设置发送频率与好友数量,切勿用于商业营销、批量骚扰等违规用途;
|
||||||
|
3. 使用本项目所产生的一切账号与法律后果均由使用者自行承担。
|
||||||
+17
@@ -0,0 +1,17 @@
|
|||||||
|
# 安全策略与合规免责声明 (Security & Disclaimer)
|
||||||
|
|
||||||
|
## ⚠️ 免责声明 (Disclaimer)
|
||||||
|
|
||||||
|
1. 本项目仅供 Python 自动化与 Web 开发技术学习研究使用,作者及贡献者不对任何因使用本项目造成的账号异常、封禁、数据丢失或法律纠纷承担责任。
|
||||||
|
2. 请严格遵守《抖音用户服务协议》与社区公约,请勿将本项目用于任何商业牟利、批量营销、违规引流或骚扰他人等违法违规行为。
|
||||||
|
3. 请合理控制每日自动续火花人数(建议不超过 20 人),并保留随机延迟间隔以降低平台风控风险。
|
||||||
|
|
||||||
|
## 🔐 凭据与隐私保护 (Privacy Protection)
|
||||||
|
|
||||||
|
1. **登录通行证保密**:`data/state.json` 包含您抖音账号的完整登录 Session 与 Cookie,等同于账号密码,**严禁将其发送给他人或提交到任何公开代码仓库**!
|
||||||
|
2. **仓库零泄漏机制**:本项目已在 `.gitignore` 中默认排除了所有凭证与私有数据文件,正常情况下 `git commit` 不会包含私密数据。
|
||||||
|
3. **后台访问安全**:在公网云服务器上部署时,请务必在 `.env` 中设置高强度的 `AUTH_TOKEN` 访问令牌,避免未授权人员访问您的管理控制台。
|
||||||
|
|
||||||
|
## 🐛 漏洞反馈 (Reporting Security Issues)
|
||||||
|
|
||||||
|
如果您在本项目中发现了任何安全漏洞或敏感信息泄漏风险,请不要公开创建 Issue,请通过 GitHub 私信或邮件联系项目维护者进行负责任的披露。
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"schedule_time": "21:00",
|
||||||
|
"jitter_minutes": 30,
|
||||||
|
"send_gap_min": 6,
|
||||||
|
"send_gap_max": 12,
|
||||||
|
"max_friends_per_run": 20,
|
||||||
|
"friends": [
|
||||||
|
"好友昵称1",
|
||||||
|
"好友昵称2"
|
||||||
|
],
|
||||||
|
"messages": [
|
||||||
|
"🔥 续火花",
|
||||||
|
"今天也要开心哦 🔥",
|
||||||
|
"晚上好 🔥"
|
||||||
|
],
|
||||||
|
"auto_run_enabled": true,
|
||||||
|
"allow_first_message": false,
|
||||||
|
"first_message_daily_limit": 1,
|
||||||
|
"schedule_harvest_day": "off"
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
echo "======================================================"
|
||||||
|
echo " 🔥 抖音云端自动续火花助手 · Linux 一键安装部署"
|
||||||
|
echo "======================================================"
|
||||||
|
|
||||||
|
if [ "$(id -u)" -ne 0 ]; then
|
||||||
|
echo "[错误] 请以 root 用户运行:sudo bash deploy/deploy.sh"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
SERVICE_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
VENV="$SERVICE_DIR/.venv"
|
||||||
|
UNIT_SRC="$SERVICE_DIR/deploy/douyin-cloud-streak.service"
|
||||||
|
UNIT_DST="/etc/systemd/system/douyin-cloud-streak.service"
|
||||||
|
|
||||||
|
echo "==> 1. 安装系统依赖..."
|
||||||
|
if command -v apt-get &>/dev/null; then
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y python3 python3-venv python3-pip xvfb libnss3 libnspr4 libasound2 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2t64 2>/dev/null || apt-get install -y python3 python3-venv python3-pip xvfb
|
||||||
|
elif command -v dnf &>/dev/null; then
|
||||||
|
dnf install -y python3 python3-pip
|
||||||
|
elif command -v yum &>/dev/null; then
|
||||||
|
yum install -y python3 python3-pip
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 2. 创建 Python 虚拟环境..."
|
||||||
|
if [ ! -x "$VENV/bin/python" ]; then
|
||||||
|
python3 -m venv "$VENV"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 3. 安装 Python 依赖..."
|
||||||
|
"$VENV/bin/pip" install --upgrade pip
|
||||||
|
"$VENV/bin/pip" install -r "$SERVICE_DIR/requirements.txt"
|
||||||
|
|
||||||
|
echo "==> 4. 安装 Playwright Chromium 浏览器内核与依赖..."
|
||||||
|
"$VENV/bin/playwright" install --with-deps chromium || "$VENV/bin/playwright" install chromium
|
||||||
|
|
||||||
|
echo "==> 5. 检查并配置 4G 交换空间 (Swap,防止小内存服务器被系统 OOM 崩溃)..."
|
||||||
|
if ! swapon --show | grep -q 'swap'; then
|
||||||
|
fallocate -l 4G /swapfile || dd if=/dev/zero of=/swapfile bs=1M count=4096
|
||||||
|
chmod 600 /swapfile
|
||||||
|
mkswap /swapfile
|
||||||
|
swapon /swapfile
|
||||||
|
grep -q '/swapfile' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab
|
||||||
|
echo "[✓] 4G Swap 已成功创建并启用"
|
||||||
|
else
|
||||||
|
echo "[✓] 检测到已有 Swap 空间,跳过"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 6. 设置时区为 Asia/Shanghai..."
|
||||||
|
timedatectl set-timezone Asia/Shanghai 2>/dev/null || true
|
||||||
|
|
||||||
|
echo "==> 7. 配置访问令牌 (Token)..."
|
||||||
|
if [ ! -f "$SERVICE_DIR/.env" ]; then
|
||||||
|
TOKEN="$(head -c 24 /dev/urandom | sha256sum | head -c 24)"
|
||||||
|
cat > "$SERVICE_DIR/.env" <<EOF
|
||||||
|
AUTH_TOKEN=$TOKEN
|
||||||
|
PORT=8000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
TZ=Asia/Shanghai
|
||||||
|
EOF
|
||||||
|
fi
|
||||||
|
|
||||||
|
TOKEN_VALUE="$(grep '^AUTH_TOKEN=' "$SERVICE_DIR/.env" | cut -d= -f2- | tr -d '\r\n')"
|
||||||
|
if [ -z "$TOKEN_VALUE" ]; then
|
||||||
|
TOKEN_VALUE="$(head -c 24 /dev/urandom | sha256sum | head -c 24)"
|
||||||
|
sed -i "s/^AUTH_TOKEN=.*/AUTH_TOKEN=$TOKEN_VALUE/" "$SERVICE_DIR/.env"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "==> 8. 注册并启动 systemd 开机自启服务..."
|
||||||
|
systemctl stop douyin-spark 2>/dev/null || true
|
||||||
|
systemctl disable douyin-spark 2>/dev/null || true
|
||||||
|
systemctl stop douyin-cloud-streak 2>/dev/null || true
|
||||||
|
pkill -9 -f "python.*app.py" 2>/dev/null || true
|
||||||
|
fuser -k -9 8000/tcp 2>/dev/null || true
|
||||||
|
sed "s|__DIR__|$SERVICE_DIR|g; s|__VENV__|$VENV|g" "$UNIT_SRC" > "$UNIT_DST"
|
||||||
|
systemctl daemon-reload
|
||||||
|
systemctl enable --now douyin-cloud-streak
|
||||||
|
systemctl restart douyin-cloud-streak
|
||||||
|
sleep 2
|
||||||
|
|
||||||
|
IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
|
||||||
|
if [ -z "$IP" ]; then
|
||||||
|
IP="你的服务器公网IP"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "======================================================"
|
||||||
|
echo " 🎉 恭喜!抖音云端续火花助手服务部署完成并已启动!"
|
||||||
|
echo "======================================================"
|
||||||
|
echo "Web 管理后台地址: http://$IP:8000"
|
||||||
|
echo "后台访问安全令牌: $TOKEN_VALUE"
|
||||||
|
echo "配置文件位置: $SERVICE_DIR/.env"
|
||||||
|
echo "======================================================"
|
||||||
|
echo "【下一步操作】"
|
||||||
|
echo "1. 请在服务器安全组/防火墙中放行 8000 端口 (TCP);"
|
||||||
|
echo "2. 在电脑上运行「1.本地提取通行证.bat」扫码获取登录态;"
|
||||||
|
echo "3. 运行「4.同步登录态到服务器.bat」上传通行证(或直接在网页后台上传);"
|
||||||
|
echo "4. 浏览器访问 http://$IP:8000 输入令牌,勾选好友开启每日自动续火花!"
|
||||||
|
echo "======================================================"
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
[Unit]
|
||||||
|
Description=Douyin Cloud Streak Service
|
||||||
|
After=network.target
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
Type=simple
|
||||||
|
User=root
|
||||||
|
WorkingDirectory=__DIR__
|
||||||
|
ExecStart=__VENV__/bin/python app.py
|
||||||
|
Restart=always
|
||||||
|
RestartSec=5
|
||||||
|
EnvironmentFile=-__DIR__/.env
|
||||||
|
|
||||||
|
# 内存紧张时系统优先回收浏览器子进程而非主服务 (防止整站崩溃)
|
||||||
|
OOMScoreAdjust=-300
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
# Nginx 反向代理配置示例(可选)
|
||||||
|
# 如需绑定自己的域名或开启 HTTPS / SSL,请参考此配置:
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name your-domain.com; # 替换为你的实际域名
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8000;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 300s;
|
||||||
|
proxy_connect_timeout 60s;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
"""一键将整站源码与环境全自动部署到云服务器 (Zero-Touch Remote Deployer)
|
||||||
|
|
||||||
|
极速优化版:
|
||||||
|
1. 自动过滤开发依赖与临时文件;
|
||||||
|
2. 采用内存级 tar.gz 压缩包单文件毫秒级极速上传(从 5 分钟加速至 2 秒!);
|
||||||
|
3. 远程一键解压并执行 deploy/deploy.sh 启动后台守护服务!
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import io
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tarfile
|
||||||
|
import tempfile
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 确保控制台 UTF-8
|
||||||
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
|
try:
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
|
||||||
|
# 仅跳过通用编译缓存与本地虚拟环境
|
||||||
|
IGNORE_NAMES = {".git", "__pycache__", ".venv", "venv", ".pytest_cache", ".idea", ".vscode"}
|
||||||
|
|
||||||
|
|
||||||
|
def print_banner():
|
||||||
|
print("=" * 65)
|
||||||
|
print(" 🚀 抖音云端自动续火花 · 云服务器一键自动化极速部署工具")
|
||||||
|
print("=" * 65)
|
||||||
|
|
||||||
|
|
||||||
|
def create_deploy_archive() -> Path:
|
||||||
|
"""通用全量打包:自动打包当前项目所有文件与目录"""
|
||||||
|
temp_tar = Path(tempfile.gettempdir()) / "douyin_cloud_streak_deploy.tar.gz"
|
||||||
|
|
||||||
|
print("[*] 正在全量打包项目文件 (包含所有模块、配置、前端与数据)...")
|
||||||
|
with tarfile.open(temp_tar, "w:gz") as tar:
|
||||||
|
for item in BASE_DIR.iterdir():
|
||||||
|
if item.name in IGNORE_NAMES:
|
||||||
|
continue
|
||||||
|
|
||||||
|
def _filter(tarinfo):
|
||||||
|
for ign in IGNORE_NAMES:
|
||||||
|
if f"/{ign}/" in f"/{tarinfo.name}/" or tarinfo.name == ign:
|
||||||
|
return None
|
||||||
|
if tarinfo.name.endswith(".pyc") or tarinfo.name.endswith(".pid"):
|
||||||
|
return None
|
||||||
|
return tarinfo
|
||||||
|
|
||||||
|
tar.add(str(item), arcname=item.name, filter=_filter)
|
||||||
|
|
||||||
|
size_kb = temp_tar.stat().st_size / 1024
|
||||||
|
print(f"[✓] 全量打包完成!压缩包大小: {size_kb:.1f} KB\n")
|
||||||
|
return temp_tar
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print_banner()
|
||||||
|
|
||||||
|
server_ip = input("👉 请输入云服务器公网 IP 地址 (例如 123.45.67.89): ").strip()
|
||||||
|
if not server_ip:
|
||||||
|
print("[❌ 错误] 服务器 IP 不能为空!")
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
server_user = input("👉 请输入 SSH 用户名 [直接回车默认 root]: ").strip() or "root"
|
||||||
|
port_input = input("👉 请输入 SSH 端口号 [直接回车默认 22]: ").strip()
|
||||||
|
server_port = int(port_input) if port_input.isdigit() else 22
|
||||||
|
remote_dir = input("👉 请输入部署路径 [直接回车默认 /opt/douyin-cloud-streak]: ").strip() or "/opt/douyin-cloud-streak"
|
||||||
|
|
||||||
|
print("-" * 65)
|
||||||
|
password = input("🔑 请输入服务器密码 (明文可见,支持右键直接粘贴): ").strip()
|
||||||
|
print("-" * 65)
|
||||||
|
|
||||||
|
if not password:
|
||||||
|
print("[❌ 错误] 密码不能为空!")
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"\n[*] 正在连接到服务器 {server_user}@{server_ip}:{server_port} ...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
import paramiko
|
||||||
|
ssh = paramiko.SSHClient()
|
||||||
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
ssh.connect(
|
||||||
|
hostname=server_ip,
|
||||||
|
port=server_port,
|
||||||
|
username=server_user,
|
||||||
|
password=password,
|
||||||
|
timeout=15,
|
||||||
|
banner_timeout=15,
|
||||||
|
auth_timeout=15
|
||||||
|
)
|
||||||
|
print("[✓] SSH 连接成功!\n")
|
||||||
|
|
||||||
|
# 1. 打包并极速上传
|
||||||
|
archive_path = create_deploy_archive()
|
||||||
|
remote_tar = f"/tmp/douyin_cloud_streak_deploy.tar.gz"
|
||||||
|
|
||||||
|
print(f"[*] 正在将打包文件秒级上传至服务器 /tmp ...")
|
||||||
|
sftp = ssh.open_sftp()
|
||||||
|
sftp.put(str(archive_path), remote_tar)
|
||||||
|
sftp.close()
|
||||||
|
archive_path.unlink(missing_ok=True)
|
||||||
|
print("[✓] 上传完成!\n")
|
||||||
|
|
||||||
|
# 2. 远程解压并部署 (强制覆盖旧版本文件)
|
||||||
|
print(f"[*] 正在远程强制覆盖解压至 {remote_dir} 并启动部署...")
|
||||||
|
extract_cmd = f"mkdir -p '{remote_dir}' && tar --overwrite -xzf '{remote_tar}' -C '{remote_dir}' && rm -f '{remote_tar}'"
|
||||||
|
stdin, stdout, stderr = ssh.exec_command(extract_cmd)
|
||||||
|
stdout.channel.recv_exit_status()
|
||||||
|
print("[✓] 远程代码覆盖解压就绪!\n")
|
||||||
|
|
||||||
|
# 3. 执行 deploy/deploy.sh
|
||||||
|
print("=" * 65)
|
||||||
|
print(" [*] 正在云端服务器自动安装依赖环境并启动守护进程...")
|
||||||
|
print(" [*] 这通常需要 1~2 分钟(配置 Python 虚拟环境与 Playwright 内核)...")
|
||||||
|
print("=" * 65)
|
||||||
|
|
||||||
|
cmd = f"cd '{remote_dir}' && sed -i 's/\\r$//' deploy/deploy.sh deploy/*.service 2>/dev/null || true; chmod +x deploy/deploy.sh && bash deploy/deploy.sh"
|
||||||
|
stdin, stdout, stderr = ssh.exec_command(cmd, get_pty=True)
|
||||||
|
|
||||||
|
for line in iter(stdout.readline, ""):
|
||||||
|
print(line, end="")
|
||||||
|
|
||||||
|
exit_status = stdout.channel.recv_exit_status()
|
||||||
|
|
||||||
|
if exit_status == 0:
|
||||||
|
# 读取 .env 里的 AUTH_TOKEN
|
||||||
|
token_cmd = f"grep '^AUTH_TOKEN=' '{remote_dir}/.env' | cut -d= -f2- | tr -d '\\r\\n'"
|
||||||
|
_, token_out, _ = ssh.exec_command(token_cmd)
|
||||||
|
token = token_out.read().decode('utf-8', 'ignore').strip()
|
||||||
|
|
||||||
|
print("\n" + "=" * 65)
|
||||||
|
print(" 🎉🎉🎉 恭喜!云服务器已全部部署完成并成功启动!")
|
||||||
|
print("=" * 65)
|
||||||
|
print(f"🌐 Web 管理后台地址: http://{server_ip}:8000")
|
||||||
|
print(f"🔑 访问安全令牌 (Token): {token or 'spark_secret_token_change_me'}")
|
||||||
|
print("=" * 65)
|
||||||
|
print("【接下来只需】:")
|
||||||
|
print(f"1. 浏览器打开: http://{server_ip}:8000")
|
||||||
|
print("2. 在「好友与消息」页面点击「一键勾选火花好友」并保存;")
|
||||||
|
print("3. 云服务器将在每天设定的时间 24 小时全自动为您维持火花!")
|
||||||
|
print("=" * 65)
|
||||||
|
else:
|
||||||
|
print(f"\n[⚠️ 部署脚本返回状态码 {exit_status}] 请查看上方输出信息。")
|
||||||
|
|
||||||
|
ssh.close()
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n[❌ 部署发生异常] {e}")
|
||||||
|
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
version: '3.8'
|
||||||
|
|
||||||
|
services:
|
||||||
|
douyin-cloud-streak:
|
||||||
|
build: .
|
||||||
|
container_name: douyin-cloud-streak
|
||||||
|
restart: always
|
||||||
|
ports:
|
||||||
|
- "8000:8000"
|
||||||
|
environment:
|
||||||
|
- PORT=8000
|
||||||
|
- HOST=0.0.0.0
|
||||||
|
- AUTH_TOKEN=spark_secret_token_change_me
|
||||||
|
- TZ=Asia/Shanghai
|
||||||
|
volumes:
|
||||||
|
- ./data:/app/data
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
"""抖音通行证 / 登录态 (state.json) 本地提取工具
|
||||||
|
|
||||||
|
在你的个人电脑(Windows / macOS)上有界面环境下运行:
|
||||||
|
1. 启动 Chromium 浏览器打开抖音;
|
||||||
|
2. 你使用手机抖音 App 扫码登录(或短信登录);
|
||||||
|
3. 登录成功后,脚本自动检测并导出 state.json 凭证文件。
|
||||||
|
|
||||||
|
此凭证用于在云端/桌面端复用登录态,免去在机房环境直接登录触发的风控异常。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 确保在 Windows 控制台下输出 emoji 与特殊字符不崩溃
|
||||||
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
|
try:
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
from playwright.sync_api import sync_playwright
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
DATA_STATE = BASE_DIR / "data" / "state.json"
|
||||||
|
ROOT_STATE = BASE_DIR / "state.json"
|
||||||
|
|
||||||
|
|
||||||
|
def print_banner():
|
||||||
|
print("=" * 65)
|
||||||
|
print(" 🔑 抖音登录通行证 (state.json) 快速提取工具")
|
||||||
|
print("=" * 65)
|
||||||
|
print("【使用提示】")
|
||||||
|
print("1. 稍后会自动弹出一个浏览器窗口并打开抖音官网;")
|
||||||
|
print("2. 请在弹出的网页右上角点击「登录」,使用【手机抖音 App 扫码】或【短信】登录;")
|
||||||
|
print("3. 登录成功后,脚本会自动检测并保存通行证(也可回到本窗口按回车保存)。")
|
||||||
|
print("=" * 65 + "\n")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print_banner()
|
||||||
|
DATA_STATE.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
print("[*] 正在启动本地浏览器,请稍候...")
|
||||||
|
with sync_playwright() as p:
|
||||||
|
try:
|
||||||
|
browser = p.chromium.launch(
|
||||||
|
headless=False,
|
||||||
|
args=["--disable-blink-features=AutomationControlled"]
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n[❌ 启动浏览器失败] {e}")
|
||||||
|
print("👉 如果是第一次运行,请先在终端执行: playwright install chromium")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
context = browser.new_context(
|
||||||
|
viewport={"width": 1280, "height": 800},
|
||||||
|
locale="zh-CN",
|
||||||
|
timezone_id="Asia/Shanghai",
|
||||||
|
user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
|
||||||
|
)
|
||||||
|
page = context.new_page()
|
||||||
|
|
||||||
|
try:
|
||||||
|
page.goto("https://www.douyin.com/", wait_until="domcontentloaded", timeout=60000)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"[⚠️ 提示] 打开主页稍慢,请直接在弹出的浏览器中操作: {e}")
|
||||||
|
|
||||||
|
print("[*] 浏览器已就绪,请在页面中登录你的抖音账号...")
|
||||||
|
print(" (登录成功后脚本将自动识别,最长等待 5 分钟)\n")
|
||||||
|
|
||||||
|
deadline = time.time() + 300
|
||||||
|
logged_in = False
|
||||||
|
|
||||||
|
while time.time() < deadline:
|
||||||
|
cookies = context.cookies()
|
||||||
|
has_session = any(c["name"].startswith("sessionid") for c in cookies)
|
||||||
|
|
||||||
|
if has_session:
|
||||||
|
logged_in = True
|
||||||
|
break
|
||||||
|
time.sleep(1.5)
|
||||||
|
|
||||||
|
if logged_in:
|
||||||
|
time.sleep(2) # 等待 Cookie 完全落盘
|
||||||
|
context.storage_state(path=str(DATA_STATE))
|
||||||
|
# 同时也复制一份到根目录备用
|
||||||
|
shutil.copy2(DATA_STATE, ROOT_STATE)
|
||||||
|
|
||||||
|
print("\n" + "=" * 65)
|
||||||
|
print(" 🎉 恭喜!抖音登录态提取成功!")
|
||||||
|
print(f" [✓] 凭据已保存至: {DATA_STATE}")
|
||||||
|
print(f" [✓] 副本已保存至: {ROOT_STATE}")
|
||||||
|
print("=" * 65)
|
||||||
|
print("\n【下一步推荐操作】")
|
||||||
|
print("👉 方案 A (本地电脑运行):")
|
||||||
|
print(" 双击「2.桌面端立即运行.bat」,或者双击「3.启动管理后台.bat」")
|
||||||
|
print("\n👉 方案 B (云服务器运行):")
|
||||||
|
print(" 1. 首次部署:双击运行「5.一键部署整站到服务器.bat」")
|
||||||
|
print(" 2. 日常维护:若后续服务器登录凭证过期,重新点击「1.本地提取通行证.bat」提取;")
|
||||||
|
print(" 提取完成后,只用双击运行「4.同步登录态到服务器.bat」上传登录凭证即可!")
|
||||||
|
print("=" * 65)
|
||||||
|
browser.close()
|
||||||
|
return
|
||||||
|
else:
|
||||||
|
print("\n[❌ 超时] 5分钟内未检测到成功登录,请重新运行本工具。")
|
||||||
|
browser.close()
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Executable
+68
@@ -0,0 +1,68 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# ======================================================
|
||||||
|
# 抖音云端自动续火花助手 · Linux 一键安装依赖
|
||||||
|
# 对应 Windows「1.本地提取通行证.bat」安装部分
|
||||||
|
# ======================================================
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
echo "======================================================"
|
||||||
|
echo " 🔥 抖音云端自动续火花助手 · 依赖安装"
|
||||||
|
echo "======================================================"
|
||||||
|
|
||||||
|
# 1. 系统依赖(playwright 浏览器运行库)
|
||||||
|
echo "==> 1. 安装系统依赖..."
|
||||||
|
if command -v apt-get &>/dev/null; then
|
||||||
|
apt-get update -y
|
||||||
|
apt-get install -y python3 python3-venv python3-pip xvfb \
|
||||||
|
libnss3 libnspr4 libasound2 libatk1.0-0 libatk-bridge2.0-0 \
|
||||||
|
libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 \
|
||||||
|
libxfixes3 libxrandr2 libgbm1 libpango-1.0-0 libcairo2 \
|
||||||
|
libasound2t64 2>/dev/null || \
|
||||||
|
apt-get install -y python3 python3-venv python3-pip xvfb
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 2. 创建虚拟环境
|
||||||
|
echo "==> 2. 创建虚拟环境 .venv ..."
|
||||||
|
if [ ! -x ".venv/bin/python" ]; then
|
||||||
|
python3 -m venv .venv
|
||||||
|
fi
|
||||||
|
# shellcheck disable=SC1091
|
||||||
|
source .venv/bin/activate
|
||||||
|
pip install --upgrade pip -q
|
||||||
|
|
||||||
|
# 3. 安装 Python 依赖
|
||||||
|
echo "==> 3. 安装 Python 依赖..."
|
||||||
|
if ! pip install -q -r requirements.txt; then
|
||||||
|
echo "[*] 默认源失败,使用清华镜像源重试..."
|
||||||
|
pip install -q -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 4. 安装 Playwright Chromium 内核
|
||||||
|
echo "==> 4. 安装 Playwright Chromium 浏览器内核..."
|
||||||
|
playwright install --with-deps chromium 2>/dev/null || playwright install chromium
|
||||||
|
|
||||||
|
# 5. 检查 .env 配置
|
||||||
|
echo "==> 5. 检查 .env 配置..."
|
||||||
|
if [ ! -f ".env" ]; then
|
||||||
|
if [ -f ".env.example" ]; then
|
||||||
|
cp .env.example .env
|
||||||
|
echo "[✓] 已从 .env.example 创建 .env"
|
||||||
|
else
|
||||||
|
cat > .env <<'ENVEOF'
|
||||||
|
PORT=8000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
AUTH_TOKEN=spark_secret_token_change_me
|
||||||
|
TZ=Asia/Shanghai
|
||||||
|
ENVEOF
|
||||||
|
echo "[✓] 已创建默认 .env"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo ""
|
||||||
|
echo "======================================================"
|
||||||
|
echo " ✅ 依赖安装完成!"
|
||||||
|
echo " 启动 Web 管理后台: ./start.sh"
|
||||||
|
echo " 模拟运行测试: ./start.sh --dry-run"
|
||||||
|
echo "======================================================"
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
fastapi>=0.110.0
|
||||||
|
uvicorn>=0.28.0
|
||||||
|
playwright>=1.42.0
|
||||||
|
playwright-stealth>=1.0.6
|
||||||
|
apscheduler>=3.10.4
|
||||||
|
python-multipart>=0.0.9
|
||||||
|
pydantic>=2.6.0
|
||||||
|
python-dotenv>=1.0.1
|
||||||
|
requests>=2.31.0
|
||||||
|
paramiko>=3.4.0
|
||||||
+210
@@ -0,0 +1,210 @@
|
|||||||
|
"""抖音云端/本地自动续火花 · 命令行/计划任务执行入口 (CLI & Cron Mode)
|
||||||
|
|
||||||
|
用法:
|
||||||
|
python run_cli.py # 执行一次续火花(发送给已勾选好友)
|
||||||
|
python run_cli.py --dry-run # 模拟运行(不实际发消息,仅测试流程)
|
||||||
|
python run_cli.py --sync-contacts # 仅同步联系人列表到台账
|
||||||
|
python run_cli.py --auto-spark # 自动勾选并发送所有已有火花的好友
|
||||||
|
python run_cli.py --friends "张三,李四" # 指定发送给特定好友
|
||||||
|
python run_cli.py --headed # 有头模式(弹出浏览器窗口,便于观察)
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 确保在 Windows 控制台下输出 emoji 与特殊字符不崩溃
|
||||||
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
|
try:
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# 确保项目根目录在 sys.path 中
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
sys.path.insert(0, str(BASE_DIR))
|
||||||
|
|
||||||
|
from core.automation import fetch_chat_contacts, run_send, sync_contacts
|
||||||
|
from core.config import DEFAULT_ACCOUNT_ID, account_state_path, load_config, save_config
|
||||||
|
from core.ledger import (
|
||||||
|
get_selected,
|
||||||
|
load_ledger,
|
||||||
|
merge_consumer_contacts,
|
||||||
|
set_selected,
|
||||||
|
)
|
||||||
|
from core.runtime import load_runtime, record_contacts, record_run, setup_logging
|
||||||
|
from core.accounts import list_accounts
|
||||||
|
|
||||||
|
|
||||||
|
def sync_local_state(account_id: str | None = None) -> bool:
|
||||||
|
"""如果根目录下存在 state.json,自动同步到 data/state.json(仅默认账号)。"""
|
||||||
|
aid = account_id or DEFAULT_ACCOUNT_ID
|
||||||
|
root_state = BASE_DIR / "state.json"
|
||||||
|
data_state = account_state_path(aid)
|
||||||
|
data_state.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
|
||||||
|
if aid == DEFAULT_ACCOUNT_ID and root_state.exists() and not data_state.exists():
|
||||||
|
shutil.copy2(root_state, data_state)
|
||||||
|
print(f"[✓] 已自动将根目录 {root_state.name} 导入到 {data_state}")
|
||||||
|
return data_state.exists()
|
||||||
|
|
||||||
|
|
||||||
|
def parse_args():
|
||||||
|
parser = argparse.ArgumentParser(description="抖音自动续火花 CLI 运行工具")
|
||||||
|
parser.add_argument("--dry-run", action="store_true", help="模拟运行模式(不真正点击发送)")
|
||||||
|
parser.add_argument("--sync-contacts", action="store_true", help="同步抖音聊天列表联系人到本地台账")
|
||||||
|
parser.add_argument("--auto-spark", action="store_true", help="自动勾选所有当前带火花的好友")
|
||||||
|
parser.add_argument("--friends", type=str, default="", help="临时指定好友昵称(英文逗号隔开)")
|
||||||
|
parser.add_argument("--headed", action="store_true", help="弹出浏览器窗口运行(默认无头后台运行)")
|
||||||
|
parser.add_argument("--account", type=str, default="", help="指定账号 ID(默认账号,可用 --list-accounts 查看)")
|
||||||
|
parser.add_argument("--list-accounts", action="store_true", help="列出全部账号")
|
||||||
|
return parser.parse_args()
|
||||||
|
|
||||||
|
|
||||||
|
def print_banner():
|
||||||
|
print("=" * 60)
|
||||||
|
print(" 🔥 抖音自动续火花助手 · CLI 极简运行引擎")
|
||||||
|
print(" Douyin Cloud Streak - Automation Runner")
|
||||||
|
print("=" * 60)
|
||||||
|
|
||||||
|
|
||||||
|
def auto_select_sparking_friends(account_id: str | None = None) -> list[dict]:
|
||||||
|
"""如果未勾选好友,自动扫描台账中带火花的好友并设为已勾选。"""
|
||||||
|
ledger_data = load_ledger(account_id)
|
||||||
|
sparking = [x for x in ledger_data if x.get("streak_days", 0) > 0]
|
||||||
|
if sparking:
|
||||||
|
for x in ledger_data:
|
||||||
|
x["selected"] = x.get("streak_days", 0) > 0
|
||||||
|
set_selected(ledger_data, account_id)
|
||||||
|
return [x for x in ledger_data if x.get("selected")]
|
||||||
|
return []
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = parse_args()
|
||||||
|
logger = setup_logging()
|
||||||
|
print_banner()
|
||||||
|
|
||||||
|
account_id = (args.account or "").strip() or DEFAULT_ACCOUNT_ID
|
||||||
|
|
||||||
|
if args.list_accounts:
|
||||||
|
print("\n[*] 当前配置的账号列表:")
|
||||||
|
for a in list_accounts():
|
||||||
|
mark = "★" if a["is_default"] else " "
|
||||||
|
print(f" {mark} {a['id']:12s} {a['name']} 启用={a['enabled']} state={'✓' if a['state_file_exists'] else '✗'}")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 1. 检查凭据
|
||||||
|
if not sync_local_state(account_id):
|
||||||
|
print("\n[❌ 错误] 未检测到登录凭证 state.json!")
|
||||||
|
print("👉 请先运行「1.本地提取通行证.bat」或执行 `python extract_cookie.py` 扫码登录,")
|
||||||
|
print(f" 或为账号 {account_id} 上传登录态。")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
# 2. 如果指定了仅同步联系人
|
||||||
|
if args.sync_contacts:
|
||||||
|
print("\n[*] 正在启动浏览器同步抖音联系人列表...")
|
||||||
|
res = sync_contacts(account_id)
|
||||||
|
if res.get("error"):
|
||||||
|
print(f"[❌ 同步失败] {res['error']}")
|
||||||
|
sys.exit(1)
|
||||||
|
names = res.get("names", [])
|
||||||
|
stats = merge_consumer_contacts(names, account_id)
|
||||||
|
record_contacts(res, account_id)
|
||||||
|
print(f"[✓] 同步成功!共获取联系人 {len(names)} 人。")
|
||||||
|
print(f" - 新增: {stats.get('added', 0)} 人")
|
||||||
|
print(f" - 更新: {stats.get('updated', 0)} 人")
|
||||||
|
print(f" - 当前有火花: {stats.get('sparking', 0)} 人")
|
||||||
|
return
|
||||||
|
|
||||||
|
# 3. 解析目标好友
|
||||||
|
only_names = None
|
||||||
|
if args.friends.strip():
|
||||||
|
only_names = [x.strip() for x in args.friends.split(",") if x.strip()]
|
||||||
|
print(f"[*] 已指定临时发送目标 ({len(only_names)} 人): {', '.join(only_names)}")
|
||||||
|
else:
|
||||||
|
cfg = load_config(account_id)
|
||||||
|
selected = get_selected(account_id)
|
||||||
|
|
||||||
|
# 尝试从 config.json 的 friends 迁移
|
||||||
|
if not selected and cfg.get("friends"):
|
||||||
|
from core.ledger import import_config_friends
|
||||||
|
import_config_friends(cfg["friends"], account_id)
|
||||||
|
selected = get_selected(account_id)
|
||||||
|
|
||||||
|
# 智能检查:如果台账中有联系人但都没勾选,自动检测是否有带火花的好友
|
||||||
|
if not selected:
|
||||||
|
ledger_data = load_ledger(account_id)
|
||||||
|
sparking = [x for x in ledger_data if x.get("streak_days", 0) > 0]
|
||||||
|
if sparking or args.auto_spark:
|
||||||
|
print(f"\n[💡 智能识别] 检测到台账中有 {len(ledger_data)} 位联系人,其中 {len(sparking)} 位当前有火花标记:")
|
||||||
|
for idx, item in enumerate(sparking, 1):
|
||||||
|
try:
|
||||||
|
print(f" {idx}. {item.get('display_name')} (🔥 {item.get('streak_days')} 天)")
|
||||||
|
except Exception:
|
||||||
|
print(f" {idx}. 好友 (🔥 {item.get('streak_days')} 天)")
|
||||||
|
|
||||||
|
# 自动为用户勾选这些带火花的好友
|
||||||
|
selected = auto_select_sparking_friends(account_id)
|
||||||
|
print(f"[✓] 已自动为您勾选这 {len(selected)} 位火花好友!")
|
||||||
|
|
||||||
|
if not selected:
|
||||||
|
print("\n[⚠️ 提示] 台账中未勾选任何好友,且未检测到带火花的好友!")
|
||||||
|
print("👉 建议双击「3.启动管理后台.bat」进入网页端勾选好友,")
|
||||||
|
print(" 或者在 config.json 填入好友昵称。")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"\n[*] 准备向已选中的 {len(selected)} 位好友发送火花...")
|
||||||
|
for idx, entry in enumerate(selected, 1):
|
||||||
|
spark = f" (🔥 {entry.get('streak_days', 0)}天)" if entry.get('streak_days') else ""
|
||||||
|
try:
|
||||||
|
print(f" {idx}. {entry.get('display_name')}{spark}")
|
||||||
|
except Exception:
|
||||||
|
print(f" {idx}. 好友{spark}")
|
||||||
|
|
||||||
|
# 4. 开始发送
|
||||||
|
mode_str = "【模拟演练 (Dry Run)】" if args.dry_run else "【正式发送】"
|
||||||
|
print(f"\n[*] 任务启动中... 当前模式: {mode_str} (账号 {account_id})")
|
||||||
|
start_time = time.time()
|
||||||
|
|
||||||
|
res = run_send(dry_run=args.dry_run, only_names=only_names, account_id=account_id)
|
||||||
|
record_run(res, account_id)
|
||||||
|
elapsed = time.time() - start_time
|
||||||
|
|
||||||
|
# 5. 输出总结
|
||||||
|
print("\n" + "=" * 60)
|
||||||
|
print(" 📊 本次运行报告")
|
||||||
|
print("=" * 60)
|
||||||
|
print(f"耗时时间: {elapsed:.1f} 秒")
|
||||||
|
print(f"成功发送: {len(res.get('ok', []))} 人 -> {', '.join(res.get('ok', [])) if res.get('ok') else '无'}")
|
||||||
|
|
||||||
|
if res.get("failed"):
|
||||||
|
print(f"\n[⚠️ 失败名单 ({len(res.get('failed'))} 人)]:")
|
||||||
|
for item in res.get("failed"):
|
||||||
|
print(f" - {item.get('name')}: {item.get('reason')}")
|
||||||
|
|
||||||
|
if res.get("skipped"):
|
||||||
|
print(f"\n[ℹ️ 跳过名单 ({len(res.get('skipped'))} 人)]:")
|
||||||
|
for item in res.get("skipped"):
|
||||||
|
print(f" - {item.get('name')}: {item.get('reason')}")
|
||||||
|
|
||||||
|
if res.get("rate_limited"):
|
||||||
|
print("\n[🚨 警报] 触发了抖音限流保护/滑动验证,脚本已自动提前安全熔断!")
|
||||||
|
|
||||||
|
if res.get("logged_out"):
|
||||||
|
print("\n[❌ 登录失效] 登录凭据已过期,请重新运行 `python extract_cookie.py` 扫码!")
|
||||||
|
sys.exit(2)
|
||||||
|
|
||||||
|
print("=" * 60)
|
||||||
|
if res.get("failed") and not res.get("ok"):
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# ======================================================
|
||||||
|
# 抖音云端自动续火花助手 · 启动脚本
|
||||||
|
# 默认: 启动 Web 管理后台 (对应「3.启动管理后台.bat」)
|
||||||
|
# 可选: --cli / --dry-run / --sync-contacts
|
||||||
|
# (对应「2.桌面端立即运行.bat」的模式选项)
|
||||||
|
# ======================================================
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
|
||||||
|
# 加载 .env 到环境变量
|
||||||
|
if [ -f ".env" ]; then
|
||||||
|
set -a
|
||||||
|
# shellcheck disable=SC1091
|
||||||
|
source .env
|
||||||
|
set +a
|
||||||
|
else
|
||||||
|
echo "[警告] 未找到 .env,使用默认配置"
|
||||||
|
export PORT="${PORT:-8000}"
|
||||||
|
export HOST="${HOST:-0.0.0.0}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# 选择 Python 解释器
|
||||||
|
if [ -x ".venv/bin/python" ]; then
|
||||||
|
PY=".venv/bin/python"
|
||||||
|
else
|
||||||
|
PY="python3"
|
||||||
|
echo "[警告] 未找到 .venv,使用系统 python3,建议先运行 ./install.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
MODE="${1:-web}"
|
||||||
|
case "$MODE" in
|
||||||
|
web)
|
||||||
|
echo "======================================================"
|
||||||
|
echo " 🔥 抖音云端自动续火花助手 · Web 管理后台"
|
||||||
|
echo "======================================================"
|
||||||
|
echo " 访问地址: http://127.0.0.1:${PORT:-8000}"
|
||||||
|
echo " 访问令牌: ${AUTH_TOKEN:-未设置(见 .env)}"
|
||||||
|
echo " (保持此窗口运行,关闭即停止服务)"
|
||||||
|
echo "======================================================"
|
||||||
|
exec "$PY" app.py
|
||||||
|
;;
|
||||||
|
--cli)
|
||||||
|
exec "$PY" run_cli.py
|
||||||
|
;;
|
||||||
|
--dry-run)
|
||||||
|
exec "$PY" run_cli.py --dry-run
|
||||||
|
;;
|
||||||
|
--sync-contacts)
|
||||||
|
exec "$PY" run_cli.py --sync-contacts
|
||||||
|
;;
|
||||||
|
*)
|
||||||
|
echo "用法: ./start.sh [web|--cli|--dry-run|--sync-contacts]"
|
||||||
|
echo " web 启动 Web 管理后台 (默认)"
|
||||||
|
echo " --cli 正式运行 CLI 模式"
|
||||||
|
echo " --dry-run 模拟运行模式 (不实际发送消息)"
|
||||||
|
echo " --sync-contacts 同步联系人列表"
|
||||||
|
exit 1
|
||||||
|
;;
|
||||||
|
esac
|
||||||
+2250
File diff suppressed because it is too large
Load Diff
Vendored
+5
File diff suppressed because one or more lines are too long
Vendored
+1
File diff suppressed because one or more lines are too long
+49
File diff suppressed because one or more lines are too long
Vendored
+14
File diff suppressed because one or more lines are too long
@@ -0,0 +1,138 @@
|
|||||||
|
"""一键同步登录凭据 (state.json) 到云服务器工具
|
||||||
|
|
||||||
|
支持:
|
||||||
|
1. 密码明文/可见输入(支持复制粘贴,输入什么显示什么,绝不盲敲!);
|
||||||
|
2. 自动检测并创建远程目录 /opt/douyin-cloud-streak/data;
|
||||||
|
3. SSH/SFTP 直连上传;
|
||||||
|
4. 发生异常时提供详细排查提示。
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
# 确保在 Windows 控制台下输出 UTF-8 正常
|
||||||
|
if hasattr(sys.stdout, "reconfigure"):
|
||||||
|
try:
|
||||||
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
sys.stderr.reconfigure(encoding="utf-8", errors="replace")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
BASE_DIR = Path(__file__).resolve().parent
|
||||||
|
DATA_STATE = BASE_DIR / "data" / "state.json"
|
||||||
|
ROOT_STATE = BASE_DIR / "state.json"
|
||||||
|
|
||||||
|
|
||||||
|
def find_state_file() -> Path | None:
|
||||||
|
if DATA_STATE.exists():
|
||||||
|
return DATA_STATE
|
||||||
|
if ROOT_STATE.exists():
|
||||||
|
return ROOT_STATE
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def print_banner():
|
||||||
|
print("=" * 65)
|
||||||
|
print(" 🚀 抖音登录凭证 (state.json) 云服务器一键同步工具")
|
||||||
|
print("=" * 65)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
print_banner()
|
||||||
|
|
||||||
|
state_path = find_state_file()
|
||||||
|
if not state_path:
|
||||||
|
print("\n[❌ 错误] 本地未找到 state.json 登录凭证!")
|
||||||
|
print("👉 请先双击运行「1.本地提取通行证.bat」扫码登录生成通行证。")
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"[✓] 检测到本地登录凭据: {state_path} ({os.path.getsize(state_path)} 字节)\n")
|
||||||
|
|
||||||
|
# 1. 交互式输入连接信息
|
||||||
|
server_ip = input("👉 请输入云服务器公网 IP 地址 (例如 123.45.67.89): ").strip()
|
||||||
|
if not server_ip:
|
||||||
|
print("[❌ 错误] 服务器 IP 不能为空!")
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
server_user = input("👉 请输入 SSH 登录用户名 [直接回车默认 root]: ").strip() or "root"
|
||||||
|
port_input = input("👉 请输入 SSH 端口号 [直接回车默认 22]: ").strip()
|
||||||
|
server_port = int(port_input) if port_input.isdigit() else 22
|
||||||
|
remote_dir = input("👉 请输入服务器部署路径 [直接回车默认 /opt/douyin-cloud-streak]: ").strip() or "/opt/douyin-cloud-streak"
|
||||||
|
|
||||||
|
# 明文可见输入密码!
|
||||||
|
print("-" * 65)
|
||||||
|
password = input("🔑 请输入服务器密码 (明文直接可见,支持右键直接粘贴): ").strip()
|
||||||
|
print("-" * 65)
|
||||||
|
|
||||||
|
if not password:
|
||||||
|
print("[❌ 错误] 服务器密码不能为空!")
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
print(f"\n[*] 正在连接到服务器 {server_user}@{server_ip}:{server_port} ...")
|
||||||
|
|
||||||
|
try:
|
||||||
|
import paramiko
|
||||||
|
ssh = paramiko.SSHClient()
|
||||||
|
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||||
|
|
||||||
|
ssh.connect(
|
||||||
|
hostname=server_ip,
|
||||||
|
port=server_port,
|
||||||
|
username=server_user,
|
||||||
|
password=password,
|
||||||
|
timeout=15,
|
||||||
|
banner_timeout=15,
|
||||||
|
auth_timeout=15
|
||||||
|
)
|
||||||
|
|
||||||
|
print("[✓] SSH 连接认证成功!")
|
||||||
|
|
||||||
|
# 确保远程目录存在
|
||||||
|
remote_data_dir = f"{remote_dir.rstrip('/')}/data"
|
||||||
|
remote_target_file = f"{remote_data_dir}/state.json"
|
||||||
|
|
||||||
|
print(f"[*] 正在确保远程目录存在: {remote_data_dir}")
|
||||||
|
stdin, stdout, stderr = ssh.exec_command(f"mkdir -p '{remote_data_dir}'")
|
||||||
|
stdout.channel.recv_exit_status()
|
||||||
|
|
||||||
|
# SFTP 上传
|
||||||
|
print(f"[*] 正在上传 {state_path.name} -> {remote_target_file} ...")
|
||||||
|
sftp = ssh.open_sftp()
|
||||||
|
sftp.put(str(state_path), remote_target_file)
|
||||||
|
sftp.close()
|
||||||
|
ssh.close()
|
||||||
|
|
||||||
|
print("\n" + "=" * 65)
|
||||||
|
print(" 🎉🎉 恭喜!抖音登录凭证已成功同步上传至云服务器!")
|
||||||
|
print(f" [✓] 远程文件位置: {remote_target_file}")
|
||||||
|
print("=" * 65)
|
||||||
|
print("\n【下一步推荐】")
|
||||||
|
print(f"1. 浏览器打开管理后台: http://{server_ip}:8000")
|
||||||
|
print("2. 在「好友与消息」页面点击「一键勾选火花好友」并保存;")
|
||||||
|
print("3. 云服务器现在开始将在每天定时为您自动续火花!")
|
||||||
|
print("=" * 65)
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
err_msg = str(e)
|
||||||
|
print(f"\n[❌ 上传失败] 错误详情: {err_msg}")
|
||||||
|
print("\n【排查建议】")
|
||||||
|
if "Authentication failed" in err_msg or "password" in err_msg.lower():
|
||||||
|
print("❌ 密码错误:请仔细核对您的服务器 root 密码是否正确。")
|
||||||
|
elif "timed out" in err_msg or "timeout" in err_msg.lower():
|
||||||
|
print(f"❌ 连接超时:请检查云服务器安全组是否放行了 {server_port} (TCP) 端口。")
|
||||||
|
else:
|
||||||
|
print("❌ 其他错误:请检查 IP 或网络状态。")
|
||||||
|
print(f"\n💡 备选方案:您也可以直接用电脑浏览器打开 http://{server_ip}:8000 在设置页直接上传 state.json。")
|
||||||
|
|
||||||
|
input("\n按回车键退出...")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user