Sync dylive production working tree to test3.

Include latest server fixes for yt-long/disk/ops and related frontend.
Exclude .bak scratch files.
This commit is contained in:
hackrobot 2026-10-14 07:04:18 +00:00
parent 3d417382f0
commit 1e8eb0130a
36 changed files with 13656 additions and 12051 deletions

View File

@ -104,7 +104,7 @@ cd desktop && npm install && npm run electron:dev
| 脚本 | `scripts/bootstrap_vps.sh` |
| TLS | 本机 Nginx / 宝塔 / Caddy → `127.0.0.1:4015/8014` |
| 进程绑定 | 通常 `127.0.0.1` |
| 业务出海(可选) | 文档后文「全局 SOCKS5 / DouyinWEB 专用 sing-box」规划;**勿动** VPS 上已有 v2ray-agent `sing-box` |
| 业务出海(可选) | **静态住宅 IP**:`egress_mode=residential` → 本机 `douyinweb-singbox` `:17891` → 供应商 SOCKS;**默认 off(机房 IP)**;**勿动** v2ray-agent `sing-box.service` |
| ShellCrash | **不是**默认栈;不要在纯 VPS 上假设有 `:7890` ShellCrash |
| Neko WebRTC | `NEKO_WEBRTC_NAT1TO1` / `DY_NEKO_NAT1TO1` = **本机公网 IP**;UDP/TCP mux 在本机安全组放行(无第二跳 DNAT) |
| 边缘 Caddy | 不需要 `bootstrap_physical_edge.sh` |
@ -403,6 +403,50 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
- **全局 SOCKS5**(默认关,目标方案见 [全局 SOCKS5(sing-box + proxychains)](#全局-socks5sing-box--proxychains)):静态住宅 IP;规划覆盖 Shorts / 长视频 / TikTok / X / Neko / FFmpeg;与 v2ray-agent 翻墙 sing-box **隔离共存**
- **频道级联清理**:删除 Shorts 频道时同步删除关联任务与本地成片;孤儿任务可运维 purge
### 长视频(yt-long)
控制台:[`/yt-long`](https://dylive.nomadro.com/yt-long)。与 Shorts / TikTok / X **完全隔离**(独立频道表、独立任务表、独立配额)。
#### 成片时长
| 项 | 值 |
|----|----|
| 随机时长 | **8–15 分钟**(`random.randint(yt_long_min_sec, yt_long_max_sec)`) |
| 常量默认 | `YT_LONG_MIN_SEC=480` · `YT_LONG_MAX_SEC=900`(`backend/app/yt_long_db.py`) |
| 设置键 | `yt_long_min_sec` / `yt_long_max_sec`(API 校验同样限制在 480–900) |
| 画幅 | 默认 **9:16**;`yt_long_landscape_16x9=true` 时才出 16:9 |
录制超时回收按最长片放宽(约 `max(1200, max_sec + 300)` 秒),避免 15 分钟母片被误标 orphan。
#### 上传可靠性(源码策略,非清库补丁)
长视频母片可达数百 MB。相关逻辑:
| 模块 | 行为 |
|------|------|
| `yt_long_upload.py` | **异步分块流式** resumable 上传(`AsyncIterator`,禁止同步 `file` 句柄 / `read_bytes`);HTTP 超时随体积缩放(约 8s/MB,下限 10 分钟、上限 45 分钟);title/description 去掉 `<>` 等非法元数据 |
| `clip_retention.py` | 删除成片前保护 `scheduled/recorded/uploading`;若仍删掉文件,yt_long 任务 **回 pending 重录**(对齐 Shorts),禁止留下「scheduled + 空 clip_path」死任务 |
| `yt_long_db.reclaim_stale_yt_long_uploads` | 按 `clip_seconds` 动态放宽 stale 阈值;有文件则退避重排队,无文件则重录 |
| `yt_long_db.heal_yt_long_orphan_jobs` | 主循环自愈:进程重启后的 `uploading` 孤儿重排队;已有 `youtube_video_id` 的脏 `scheduled` → `uploaded`;缺片 → `pending` |
| 配额 429 | **不**把当前任务标 `failed` 烧掉;改为 `scheduled` + 延后 `upload_at`,并对该 OAuth Client 冷静;太平洋日配额恢复后自动再传 |
| OAuth 401/403 | 标记频道 `oauth_ok=0` 并延后;选频道 / claim 上传时跳过坏授权频道 |
#### 配额与开关(常用)
| 设置 | 含义 |
|------|------|
| `yt_long_enabled` | 总开关(默认关;生产按需开) |
| `yt_long_auto_upload` | 录完是否自动排上传 |
| `yt_long_channel_daily_max` | 每启用频道北京日上传上限 |
| `yt_long_daily_max` / `yt_long_source_daily_max` | 全局上传 / 母片日上限 |
| `yt_long_max_concurrent` | 同时录制/上传并发 |
| `yt_long_upload_min_gap_sec` | 同流水线两次上传最小间隔 |
| `yt_long_delete_clip_after_upload` | 上传成功后删本地成片 |
API:`GET/POST /api/yt-long/settings` · `GET /api/yt-long/status` · `GET /api/yt-long/jobs` · `GET /api/yt-long/channels`。
Studio 里长时间停在 **Processing will begin shortly / Pending**,优先核对本机任务是否已有 `youtube_video_id`、以及 Google Cloud **Video Uploads/天** 是否 429;处理中状态本身不等于本系统上传失败。
#### 分发台全局每日配额(Shorts / 长视频 / TikTok / X)
各业务页顶部 **DailyQuotaGlobalCard**:在保留「单频道编辑」的前提下,可一次改默认并可选同步全部频道。
@ -416,6 +460,10 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
长视频后台 `reconcile_yt_long_upload_caps` **不得**把操作员保存的上限强行改回 5;仅在 API 限流日对「高于有效上限」的频道做软封顶。
#### 配额口径(Shorts / 长视频)
控制台顶部「北京日配额 / YouTube 上传 / 母片录制」**只合计已启用**频道(停用的 Client B 等不计入)。后端缺口与取样同样只看 `enabled=1`。长视频母片上限 = 已启用 oauth 长视频频道 × 每频道日上限,**不再**按 Shorts 舰队规模抬高。
#### YouTube 直播状态(receiving-first)
首页 / live-map / 转播门控:**优先** YouTube 是否在收流(Studio receiving / `on_air` / youtubei·OAuth `is_live`),Neko 上下线不得覆盖「已在收流」。`encoder_lost` / LIVE 计时器 + No data **不算** receiving。细则见 `.cursor/rules/youtube-live-receiving-first.mdc`。
@ -437,7 +485,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
#### API 防挂死 / 直播优先 CPU(双 VPS)
现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。**dylive 同代码**不叠加重转码时即可稳住。对策:
现网根因(尤其 **VPS-B dy.nomadro.live**):直播推流 ffmpeg 与 yt_long/shorts 转码叠在一起 → load 飙高 → uvicorn 事件循环饿死 → `/api/health` 超时 → 整站「宕机」。另有一类反复复发:**前端 `npm run build` 留下孤儿 `usr`/`node` 进程**,可单独把 4 核打到 100%。**dylive 同代码**在未叠加重转码/无孤儿时即可稳住。对策:
| 层 | 机制 | 行为 |
|----|------|------|
@ -446,9 +494,11 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
| 剪辑让路 | `host_metrics.clip_encode_defer_reason()` | 有 YouTube **直播推流** 或 load/CPU 过高时,yt_long / shorts / tiktok / x_clips **不新开** 录制 ffmpeg |
| API 内存 | systemd drop-in(对齐 dylive 紧预算,按机内存微调) | 例:dylive ≈ High **700M** / Max **900M**;dy.live ≈ High **1100M** / Max **1500M**(ffmpeg 已外置) |
| ffmpeg CPU | `douyinweb-ffmpeg.slice` `CPUQuota` | dy.live 现网 **200%**(4 核机留给 API/Neko 余量) |
| Web 加固 | `douyinweb-web.service.d/harden.conf` | `KillMode=control-group` + `CPUQuota=150%`,部署后孤儿随 unit 杀掉 |
| 孤儿守护 | `scripts/linux/build_orphan_watch.sh` + timer(每分钟) | 清 Next SWC `usr` / 假 `pm2` / 无参 `node` / `.d*` `.r*` 临时目录 |
| 看门狗 | `scripts/linux/api_health_watch.sh` → `douyinweb-api-watch.service` | health 连续失败或 `:8014` Recv-Q 过高 → SIGKILL 重启 API |
对齐部署(代码 + systemd):`python scripts/_align_dy_to_dylive_harden.py`(经 VPS-A 跳到 VPS-B);仅 cgroup/watch 骨架也可用 `scripts/_deploy_api_hang_harden.py`。
对齐部署:`python scripts/_stabilize_dy_permanent.py`(孤儿 timer + web/api CPU);配额/代码对齐另用 `scripts/_align_dy_to_dylive_harden.py`。
#### 时段排除名单(timeslot exclude)
@ -505,7 +555,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
| `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 |
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
| `/yt-long` | 长视频成片 / 上传 |
| `/yt-long` | 长视频成片 / 上传(**8–15 分钟**随机母片 → YouTube 长视频) |
| `/yt-revenue` | YPP 预估创收(需 monetary OAuth) |
| `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 |
| `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 |
@ -531,7 +581,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
```
douyinWEB/
backend/app/ FastAPI(auth / monitor / cover / shorts_* / youtube_relay_* / youtube_neko / host_metrics …)
backend/app/ FastAPI(auth / monitor / cover / shorts_* / yt_long_* / youtube_relay_* / youtube_neko / host_metrics / clip_retention …)
backend/tests/ pytest(Shorts / live / reconcile 等)
backend/data/ SQLite、封面/成片缓存
frontend/src/ Next.js 控制台(Web)
@ -666,8 +716,9 @@ python scripts\_deploy.py
- 错误示例:`Quota exceeded for quota metric 'Video Uploads' … Video Uploads per day`
- **不是程序崩溃**:Google Cloud 项目每日 Video Uploads 桶用尽(默认约 100 次/天,[官方文档](https://developers.google.com/youtube/v3/docs/videos/insert))
- 配额在 **太平洋时间 0 点** 重置;Console → YouTube Data API → Quotas 可查看用量与申请提额
- 多 Google 项目:Shorts 频道绑定 OAuth Client **A/B/C/D**,各 Client 独立计数、互不影响
- 多 Google 项目:Shorts / 长视频频道绑定 OAuth Client **A/B/C/D**,各 Client 独立计数、互不影响
- 实现:`backend/app/shorts_yt_quota.py`(按 Client 计数展示、429 识别);Shorts 页展示用量提示与接口错误,**禁止本地自设上传暂停**
- **长视频**:429 时该任务 **延后重试**(保持成片、不标失败烧掉),并对该 Client 进入冷静;详见 [长视频(yt-long)](#长视频yt-long)
## 全局 SOCKS5(sing-box + proxychains)— 主要针对纯 VPS

View File

@ -159,7 +159,12 @@ def _pick_start(master_sec: float, cut_sec: int, window: tuple[float, float]) ->
def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str, int]:
"""How many uploads each platform wants today (enabled channels × per-channel caps)."""
"""Platform daily wants (informational) + authoritative yt-long master count.
Master recordings are owned by **enabled yt_long channels × per-channel cap**.
One master can cascade-cut Shorts/TikTok/X — do **not** inflate masters to
Shorts fleet size (that produced 7×9=63 while only 7 long channels × 2 = 14).
"""
from . import db
from . import tiktok_db
from . import yt_long_db
@ -175,15 +180,17 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or [])
except Exception:
tiktok_n = 0
yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
# Prefer sum of enabled oauth channel caps (respects per-row daily_max).
yt_upload = int(yt_long_db.yt_long_enabled_upload_cap(settings_map) or 0)
if yt_upload <= 0:
yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE)
tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE)
try:
x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20))
except Exception:
x_need = 20
# One master feeds all platforms once → masters needed = max(...)
source_need = max(yt_upload, shorts_need, tiktok_need, x_need, 0)
source_need = max(0, yt_upload)
return {
"yt_long": yt_upload,
"yt_long_upload": yt_upload,
@ -197,23 +204,21 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
def ensure_source_covers_platforms(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Always keep yt_long_source_daily_max ≥ max(platform quotas); never raise upload cap."""
"""Keep yt_long_source_daily_max == enabled long-upload cap (no Shorts inflation)."""
from . import db
from . import yt_long_db
settings_map = cfg if cfg is not None else db.get_settings_map()
need = estimate_platform_daily_need(settings_map)
target = int(need["source_masters"])
upload_cap = int(need.get("yt_long_upload") or yt_long_db.yt_long_daily_max(settings_map) or 0)
target = upload_cap
current = int(yt_long_db.yt_long_source_daily_max(settings_map) or 0)
upload_cap = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
if not bool(settings_map.get("clip_cascade_enabled", True)):
# Without cascade, source only needs to cover YouTube long uploads
target = upload_cap
try:
hard_cap = max(42, min(300, int(settings_map.get("yt_long_source_cap") or 200)))
hard_cap = max(upload_cap, min(300, int(settings_map.get("yt_long_source_cap") or 200)))
except Exception:
hard_cap = 200
new_max = min(hard_cap, max(upload_cap, target))
hard_cap = max(upload_cap, 200)
# Never floor at 42 — that forced 母片≥42 when only 7×2=14 was configured.
new_max = min(hard_cap, max(0, target))
if new_max != int(settings_map.get("yt_long_source_daily_max") or 0):
db.update_settings_map({"yt_long_source_daily_max": new_max})
return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need}

View File

@ -16,7 +16,7 @@ from typing import Any
from .config import settings
_DEFAULT_MAX_AGE_H = 24.0
_DEFAULT_MIN_FREE_GB = 12.0
_DEFAULT_MIN_FREE_GB = 8.0
def _max_age_sec(cfg: dict[str, Any]) -> float:
@ -137,7 +137,7 @@ def _clear_path_refs(path: str, now: float) -> None:
)
except Exception:
pass
for table in ("tiktok_jobs", "x_clip_jobs", "yt_long_jobs"):
for table in ("tiktok_jobs", "x_clip_jobs"):
try:
conn.execute(
f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?",
@ -145,6 +145,32 @@ def _clear_path_refs(path: str, now: float) -> None:
)
except Exception:
continue
# yt_long: mirror Shorts — never leave scheduled/recorded with empty path
try:
conn.execute(
"""
UPDATE yt_long_jobs
SET clip_path = '', status = 'pending', upload_at = 0,
clip_seconds = 0, started_at = 0,
error = '成片被清理,已重新排队录制',
updated_at = ?
WHERE clip_path = ?
AND status IN ('recorded', 'scheduled')
AND IFNULL(youtube_video_id, '') = ''
AND IFNULL(error, '') NOT LIKE 'cascade_only%'
""",
(now, path),
)
conn.execute(
"""
UPDATE yt_long_jobs
SET clip_path = '', updated_at = ?
WHERE clip_path = ?
""",
(now, path),
)
except Exception:
pass
conn.commit()
finally:
conn.close()
@ -155,11 +181,13 @@ def _clear_path_refs(path: str, now: float) -> None:
def _job_still_needs_file(path: str) -> bool:
from . import db
# Protect any job that still needs the file to finish (not only in-flight IO).
# yt_long scheduled/recorded without video_id must keep the master until upload.
checks = (
"SELECT 1 FROM shorts_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
"SELECT 1 FROM tiktok_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
"SELECT 1 FROM x_clip_jobs WHERE clip_path=? AND status IN ('posting','recording') LIMIT 1",
"SELECT 1 FROM yt_long_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1",
"SELECT 1 FROM shorts_jobs WHERE clip_path=? AND status IN ('uploading','recording','scheduled','recorded') AND IFNULL(youtube_video_id,'')='' LIMIT 1",
"SELECT 1 FROM tiktok_jobs WHERE clip_path=? AND status IN ('uploading','recording','scheduled','recorded') AND IFNULL(tiktok_video_id,'')='' LIMIT 1",
"SELECT 1 FROM x_clip_jobs WHERE clip_path=? AND status IN ('posting','recording','scheduled','recorded') AND IFNULL(tweet_id,'')='' LIMIT 1",
"SELECT 1 FROM yt_long_jobs WHERE clip_path=? AND status IN ('uploading','recording','scheduled','recorded') AND IFNULL(youtube_video_id,'')='' AND IFNULL(error,'') NOT LIKE 'cascade_only%' LIMIT 1",
)
try:
with db._lock:

View File

@ -709,8 +709,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"yt_long_daily_max": 70,
"yt_long_source_daily_max": 70,
"yt_long_channel_daily_max": 5,
"yt_long_min_sec": 180,
"yt_long_max_sec": 480,
"yt_long_min_sec": 480,
"yt_long_max_sec": 900,
"yt_long_dedupe_room_day": True,
"yt_long_max_concurrent": 1,
"yt_long_upload_min_gap_sec": 900,
@ -722,7 +722,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"yt_long_description_template": "",
"clip_cascade_enabled": True,
"clips_max_age_hours": 24,
"clips_min_free_gb": 12,
"clips_min_free_gb": 8,
# Seaweed/S3 session covers (covers/*.jpg); avatars kept. Default 2 days.
"covers_s3_keep_days": 2,
"yt_long_monetize_when_ypp": True,
@ -741,8 +741,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"settings_audit_enabled": True,
"db_backup_enabled": False,
"db_backup_interval_hours": 24,
"db_backup_keep_days": 7,
"ops_alerts_enabled": False,
"db_backup_keep_days": 3,
"db_backup_keep_max": 3,
"ops_alerts_enabled": True,
"ops_alert_disk_enabled": False,
"ops_alert_quota_enabled": False,
"ops_alert_interval_sec": 900,

View File

@ -1,5 +1,11 @@
# -*- coding: utf-8 -*-
"""SQLite backup — copy-only, never modifies source DB."""
"""SQLite backup — copy-only, never modifies source DB.
Hardening (disk-safe):
- Cap file count (db_backup_keep_max), not only age
- Skip auto backup if last auto copy is fresher than interval
- Refuse new backup when free disk is below floor (leave headroom for live)
"""
from __future__ import annotations
import shutil
@ -20,17 +26,54 @@ def _db_path() -> Path:
return Path(settings.data_dir) / "monitor.db"
def run_backup(*, label: str = "") -> dict[str, Any]:
def _disk_free_gb(path: Path | None = None) -> float:
try:
usage = shutil.disk_usage(str(path or settings.data_dir))
return float(usage.free) / (1024.0 ** 3)
except Exception:
return 999.0
def _latest_auto_mtime() -> float:
newest = 0.0
for p in _backup_dir().glob("monitor_*_auto.db"):
try:
newest = max(newest, p.stat().st_mtime)
except OSError:
continue
return newest
def run_backup(*, label: str = "", force: bool = False) -> dict[str, Any]:
src = _db_path()
if not src.is_file():
return {"ok": False, "error": "db_not_found"}
free = _disk_free_gb()
# Need room for one full copy + ~2GB headroom
need_gb = max(3.0, (src.stat().st_size / (1024.0 ** 3)) * 1.15 + 2.0)
if (not force) and free < need_gb:
return {
"ok": False,
"error": "disk_too_low",
"disk_free_gb": round(free, 2),
"need_gb": round(need_gb, 2),
}
stamp = time.strftime("%Y%m%d_%H%M%S")
name = f"monitor_{stamp}{('_' + label) if label else ''}.db"
dest = _backup_dir() / name
try:
shutil.copy2(src, dest)
size = dest.stat().st_size
return {"ok": True, "path": str(dest), "name": name, "size": size, "ts": time.time()}
return {
"ok": True,
"path": str(dest),
"name": name,
"size": size,
"ts": time.time(),
"disk_free_gb": round(_disk_free_gb(), 2),
}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
@ -40,13 +83,7 @@ def list_backups(*, limit: int = 20) -> list[dict[str, Any]]:
for p in sorted(_backup_dir().glob("monitor_*.db"), key=lambda x: x.stat().st_mtime, reverse=True):
try:
st = p.stat()
rows.append(
{
"name": p.name,
"size": st.st_size,
"ts": st.st_mtime,
}
)
rows.append({"name": p.name, "size": st.st_size, "ts": st.st_mtime})
except OSError:
continue
if len(rows) >= max(1, limit):
@ -54,14 +91,49 @@ def list_backups(*, limit: int = 20) -> list[dict[str, Any]]:
return rows
def prune_backups(*, keep_days: float = 7.0) -> dict[str, Any]:
def prune_backups(*, keep_days: float = 7.0, keep_max: int = 3) -> dict[str, Any]:
"""Remove aged backups, then enforce a hard max count (newest kept)."""
cutoff = time.time() - max(1.0, keep_days) * 86400.0
keep_max = max(1, min(30, int(keep_max)))
removed = 0
files: list[Path] = []
for p in _backup_dir().glob("monitor_*.db"):
try:
if p.stat().st_mtime < cutoff:
st = p.stat()
if st.st_mtime < cutoff:
p.unlink(missing_ok=True)
removed += 1
else:
files.append(p)
except OSError:
continue
files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
for p in files[keep_max:]:
try:
p.unlink(missing_ok=True)
removed += 1
except OSError:
continue
return {"ok": True, "removed": removed, "kept": min(keep_max, len(files))}
def prune_legacy_db_copies(*, keep_max: int = 2) -> dict[str, Any]:
"""Cull data/monitor.db.bak-* and pre-restore copies that sit beside live DB."""
root = Path(settings.data_dir)
removed = 0
cands: list[Path] = []
for p in root.glob("monitor.db.*"):
name = p.name.lower()
if p.name == "monitor.db":
continue
if any(x in name for x in (".bak", "pre-restore", ".old", ".copy")):
cands.append(p)
cands.sort(key=lambda x: x.stat().st_mtime, reverse=True)
for p in cands[max(0, keep_max) :]:
try:
p.unlink(missing_ok=True)
removed += 1
except OSError:
continue
return {"ok": True, "removed": removed}
@ -72,7 +144,17 @@ async def backup_loop() -> None:
from . import db
await asyncio.sleep(60)
await asyncio.sleep(90)
# One-shot cleanup of legacy piles left by old restarts / restores
try:
cfg0 = db.get_settings_map()
keep_days0 = float(cfg0.get("db_backup_keep_days") or 3)
keep_max0 = int(cfg0.get("db_backup_keep_max") or 3)
prune_backups(keep_days=keep_days0, keep_max=keep_max0)
prune_legacy_db_copies(keep_max=2)
except Exception:
pass
while True:
try:
cfg = db.get_settings_map()
@ -85,12 +167,27 @@ async def backup_loop() -> None:
interval_h = 24.0
interval_h = max(1.0, min(168.0, interval_h))
try:
keep_days = float(cfg.get("db_backup_keep_days") or 7)
keep_days = float(cfg.get("db_backup_keep_days") or 3)
except Exception:
keep_days = 7.0
result = run_backup(label="auto")
keep_days = 3.0
try:
keep_max = int(cfg.get("db_backup_keep_max") or 3)
except Exception:
keep_max = 3
# Skip if an auto backup already exists within the interval.
# Prevents API restart storms from dumping 100+ copies/day.
last = _latest_auto_mtime()
age_h = (time.time() - last) / 3600.0 if last > 0 else 1e9
if age_h < interval_h * 0.95:
prune_backups(keep_days=keep_days, keep_max=keep_max)
await asyncio.sleep(min(3600.0, max(300.0, (interval_h - age_h) * 3600.0)))
continue
result = run_backup(label="auto", force=False)
prune_backups(keep_days=keep_days, keep_max=keep_max)
prune_legacy_db_copies(keep_max=2)
if result.get("ok"):
prune_backups(keep_days=keep_days)
try:
db.add_event(
kind="db_backup",
@ -100,6 +197,16 @@ async def backup_loop() -> None:
)
except Exception:
pass
elif result.get("error") == "disk_too_low":
try:
db.add_event(
kind="db_backup",
level="warn",
message=f"磁盘不足,跳过备份(剩 {result.get('disk_free_gb')} GB)",
meta=result,
)
except Exception:
pass
await asyncio.sleep(interval_h * 3600.0)
except asyncio.CancelledError:
raise

189
backend/app/disk_guard.py Normal file
View File

@ -0,0 +1,189 @@
# -*- coding: utf-8 -*-
"""Proactive disk guard — reclaim before the box wedges API/Caddy.
Runs independently of webhook alerts. Safe defaults for ~60GB VPS.
"""
from __future__ import annotations
import shutil
import time
from pathlib import Path
from typing import Any
def _free_gb(path: str | Path | None = None) -> float:
from .config import settings
try:
usage = shutil.disk_usage(str(path or settings.data_dir))
return float(usage.free) / (1024.0 ** 3)
except Exception:
return 999.0
def _used_pct(path: str | Path | None = None) -> float:
from .config import settings
try:
usage = shutil.disk_usage(str(path or settings.data_dir))
if usage.total <= 0:
return 0.0
return 100.0 * float(usage.used) / float(usage.total)
except Exception:
return 0.0
def reclaim_once(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"""Purge clips + trim backups when disk is tight. Idempotent."""
from . import db
from .clip_retention import purge_stale_clips
from .db_backup import prune_backups, prune_legacy_db_copies
settings_map = cfg if cfg is not None else db.get_settings_map()
try:
min_free = float(settings_map.get("clips_min_free_gb") or 8)
except Exception:
min_free = 8.0
min_free = max(4.0, min(40.0, min_free))
try:
panic_pct = float(settings_map.get("disk_panic_used_pct") or 90)
except Exception:
panic_pct = 90.0
try:
keep_days = float(settings_map.get("db_backup_keep_days") or 3)
except Exception:
keep_days = 3.0
try:
keep_max = int(settings_map.get("db_backup_keep_max") or 3)
except Exception:
keep_max = 3
free_before = _free_gb()
used_before = _used_pct()
actions: list[str] = []
# Always keep backup pile small (cheap).
try:
pr = prune_backups(keep_days=keep_days, keep_max=keep_max)
if pr.get("removed"):
actions.append(f"prune_backups:{pr.get('removed')}")
lg = prune_legacy_db_copies(keep_max=2)
if lg.get("removed"):
actions.append(f"prune_legacy:{lg.get('removed')}")
except Exception as exc:
actions.append(f"prune_err:{exc}"[:80])
under = free_before < min_free or used_before >= panic_pct
purge_result: dict[str, Any] = {}
if under:
# Temporarily tighten max age so purge_stale_clips reclaims faster.
tight = dict(settings_map)
try:
age = float(tight.get("clips_max_age_hours") or 24)
except Exception:
age = 24.0
tight["clips_max_age_hours"] = min(age, 6.0 if used_before >= panic_pct else 12.0)
tight["clips_min_free_gb"] = min_free
try:
purge_result = purge_stale_clips(tight)
actions.append(f"purge_clips:del={purge_result.get('deleted')}")
except Exception as exc:
actions.append(f"purge_err:{exc}"[:80])
# Extreme: drop oldest non-inflight mp4 > 2h if still panic.
if _used_pct() >= panic_pct or _free_gb() < max(3.0, min_free * 0.5):
dropped = _drop_old_mp4(max_age_h=2.0, limit=40)
if dropped:
actions.append(f"drop_mp4:{dropped}")
free_after = _free_gb()
used_after = _used_pct()
out = {
"ok": True,
"under_pressure": under,
"free_gb_before": round(free_before, 2),
"free_gb_after": round(free_after, 2),
"used_pct_before": round(used_before, 1),
"used_pct_after": round(used_after, 1),
"min_free_gb": min_free,
"actions": actions,
"purge": purge_result,
}
if under and (free_after - free_before) > 0.05:
try:
db.add_event(
kind="disk_guard",
level="warn",
message=f"磁盘守护回收:{free_before:.1f}→{free_after:.1f} GB",
meta=out,
)
except Exception:
pass
return out
def _drop_old_mp4(*, max_age_h: float, limit: int) -> int:
from .clip_retention import _job_still_needs_file, unlink_clip
from .config import settings
root = Path(settings.clips_dir)
if not root.is_dir():
return 0
now = time.time()
cands: list[tuple[float, Path]] = []
for p in root.rglob("*.mp4"):
try:
if not p.is_file():
continue
age = now - p.stat().st_mtime
if age < max_age_h * 3600.0:
continue
variants = {str(p)}
try:
variants.add(str(p.resolve()))
except OSError:
pass
if any(_job_still_needs_file(sp) for sp in variants):
continue
cands.append((age, p))
except OSError:
continue
cands.sort(key=lambda x: x[0], reverse=True)
n = 0
for _age, p in cands[: max(1, limit)]:
if unlink_clip(str(p), clear_refs=True):
n += 1
return n
async def disk_guard_loop() -> None:
import asyncio
from . import db
await asyncio.sleep(45)
while True:
try:
cfg = db.get_settings_map()
# Allow kill-switch
if cfg.get("disk_guard_enabled", True) is False:
await asyncio.sleep(300)
continue
reclaim_once(cfg)
try:
interval = float(cfg.get("disk_guard_interval_sec") or 300)
except Exception:
interval = 300.0
# Faster poll when already tight
free = _free_gb()
try:
min_free = float(cfg.get("clips_min_free_gb") or 8)
except Exception:
min_free = 8.0
if free < min_free or _used_pct() >= 90:
interval = min(interval, 120.0)
await asyncio.sleep(max(60.0, interval))
except asyncio.CancelledError:
raise
except Exception:
await asyncio.sleep(180)

View File

@ -1,14 +1,15 @@
# -*- coding: utf-8 -*-
"""Business egress — always via ShellCrash on China physical hosts.
"""Business egress for DouyinWEB.
Correct model (虚空终端 dialer-proxy):
App → 127.0.0.1:7890 (ShellCrash mixed)
├─ 默认:选机场节点直接出海
└─ 勾选「住宅落地」:选 dy-residential(socks5 + dialer-proxy)
→ 先经 ShellCrash 前置节点拨号,再连住宅 SOCKS 落地
(家宽无法直连海外住宅 SOCKS)
US VPS (primary):
off → datacenter IP direct
residential → 127.0.0.1:17891 (douyinweb-singbox) → static residential SOCKS
NEVER touches host sing-box.service / v2ray-agent
Docs: https://wiki.metacubex.one/config/proxies/dialer-proxy/
Physical China (legacy, optional):
shellcrash → 127.0.0.1:7890 (+ optional dialer-proxy residential chain)
Douyin scrape/CDN stays DIRECT in all modes (callers must not inject proxy).
"""
from __future__ import annotations
@ -19,9 +20,9 @@ from pathlib import Path
from typing import Any
from .config import BACKEND, ROOT
from .global_socks import CONFIG_DIR
from .global_socks import CONFIG_DIR, LOCAL_MIXED_HOST, LOCAL_MIXED_PORT, local_mixed_url
MODES = ("off", "shellcrash")
MODES = ("off", "shellcrash", "residential")
PROXYCHAINS_CONF = CONFIG_DIR / "proxychains.conf"
RESIDENTIAL_PROXY_NAME = "dy-residential"
DEFAULT_DIALER = "dialer"
@ -41,38 +42,53 @@ def _settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
return dict(db.get_settings_map())
def _is_vps_host(cfg: dict[str, Any] | None = None) -> bool:
try:
from . import host_profile
return host_profile.infer_profile(cfg) == "vps"
except Exception:
return True
def get_mode(cfg: dict[str, Any] | None = None) -> str:
s = _settings(cfg)
raw = str(s.get(_MODE_KEY) or "").strip().lower()
# Legacy: "residential" meant chain-on ShellCrash, never direct SOCKS.
if raw == "residential":
return "shellcrash"
if raw in MODES:
return raw
# Legacy toggles → residential on VPS, shellcrash elsewhere
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
return "shellcrash"
# Default ON for China physical: all non-Douyin business via ShellCrash.
# Explicit "off" in settings still wins (handled above via MODES).
return "residential" if _is_vps_host(s) else "shellcrash"
if _is_vps_host(s):
return "off"
return "shellcrash"
def local_residential_http_proxy() -> str:
return local_mixed_url()
def local_residential_socks() -> str:
return f"socks5://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}"
def google_http_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT via Clash rules.
- shellcrash mode → mixed :7890
- mode off but ShellCrash still running → still use it (physical soft path)
- mode off + no ShellCrash → empty string (pure VPS direct)
"""
if get_mode(cfg) == "shellcrash":
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT."""
mode = get_mode(cfg)
if mode == "residential":
return local_residential_http_proxy()
if mode == "shellcrash":
return _host_http_proxy(cfg)
try:
from . import shellcrash_hub
# Soft path: ShellCrash still running on physical while mode off
if not _is_vps_host(cfg):
try:
from . import shellcrash_hub
st = shellcrash_hub.status() or {}
if st.get("running"):
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
except Exception:
pass
st = shellcrash_hub.status() or {}
if st.get("running"):
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
except Exception:
pass
return ""
@ -84,20 +100,56 @@ def google_httpx_kwargs(*, timeout: float = 45.0, cfg: dict[str, Any] | None = N
return kw
# Alias — overseas APIs (TikTok Open API, etc.) share the same egress.
def google_http_proxy_candidates(
cfg: dict[str, Any] | None = None,
*,
prefer: str = "",
) -> list[str]:
"""Ordered Google egress attempts.
Residential / ShellCrash first when enabled; on US VPS always append direct
so flaky SOCKS cannot permanently mark Shorts OAuth as「异常」.
"""
out: list[str] = []
primary = str(prefer or "").strip() or google_http_proxy(cfg)
if primary:
out.append(primary)
# Direct fallback on VPS (datacenter reaches Google; residential may timeout).
if _is_vps_host(cfg) and "" not in out:
out.append("")
if not out:
out.append("")
# de-dupe preserving order
seen: set[str] = set()
uniq: list[str] = []
for p in out:
if p in seen:
continue
seen.add(p)
uniq.append(p)
return uniq
def httpx_kwargs_for_proxy(proxy: str, *, timeout: float = 45.0) -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
p = str(proxy or "").strip()
if p:
kw["proxy"] = p
return kw
overseas_httpx_kwargs = google_httpx_kwargs
overseas_http_proxy = google_http_proxy
def chain_residential(cfg: dict[str, Any] | None = None) -> bool:
"""ShellCrash dialer-proxy chain (physical only). VPS residential does not use this."""
s = _settings(cfg)
if get_mode(s) == "residential":
return False
if _CHAIN_KEY in s:
return bool(s.get(_CHAIN_KEY))
# Legacy residential mode / socks toggle → chain on
raw = str(s.get(_MODE_KEY) or "").strip().lower()
if raw == "residential":
return True
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"))
return bool(s.get(_CHAIN_KEY)) and get_mode(s) == "shellcrash"
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled")) and get_mode(s) == "shellcrash"
def cover_neko(cfg: dict[str, Any] | None = None) -> bool:
@ -111,7 +163,7 @@ def cover_relay(cfg: dict[str, Any] | None = None) -> bool:
s = _settings(cfg)
if _RELAY_KEY in s:
return bool(s.get(_RELAY_KEY))
return get_mode(s) == "shellcrash"
return get_mode(s) in {"shellcrash", "residential"}
def cover_uploads(cfg: dict[str, Any] | None = None) -> bool:
@ -139,42 +191,48 @@ def _host_http_proxy(cfg: dict[str, Any] | None = None) -> str:
def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) == "off":
return ""
return _host_http_proxy(cfg)
return google_http_proxy(cfg)
def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str:
if get_mode(cfg) == "off" or not cover_uploads(cfg):
return ""
return _host_http_proxy(cfg)
return google_http_proxy(cfg)
def resolve_business_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Unified overseas business proxy (uploads / OAuth / TikTok fallback)."""
return resolve_upload_proxy(cfg) or google_http_proxy(cfg)
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Chromium inside Neko → host ShellCrash.
Physical (DY_NEKO_EDGE_UPSTREAM set): always inject proxy unless egress mode is explicit off.
"""
"""Chromium inside Neko → host local mixed (no upstream credentials in URL)."""
import os
physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip())
if get_mode(cfg) == "off":
mode = get_mode(cfg)
if mode == "off":
return ""
if not cover_neko(cfg) and not physical:
return ""
if mode == "residential":
return f"http://host.docker.internal:{LOCAL_MIXED_PORT}"
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
"""Always point proxychains at ShellCrash mixed SOCKS — never raw residential."""
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
if get_mode(cfg) != "shellcrash":
mode = get_mode(cfg)
if mode == "off":
PROXYCHAINS_CONF.write_text(
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
encoding="utf-8",
)
return PROXYCHAINS_CONF
port = shellcrash_mixed_port(cfg)
if mode == "residential":
port = LOCAL_MIXED_PORT
else:
port = shellcrash_mixed_port(cfg)
text = (
"strict_chain\n"
"proxy_dns\n"
@ -187,6 +245,12 @@ def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
f"socks5 127.0.0.1 {port}\n"
)
PROXYCHAINS_CONF.write_text(text, encoding="utf-8")
try:
import os
os.chmod(PROXYCHAINS_CONF, 0o600)
except Exception:
pass
return PROXYCHAINS_CONF
@ -220,20 +284,15 @@ def apply_mode(
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
from . import db
from . import shellcrash_hub
from . import singbox_manager
raw = str(mode or "off").strip().lower()
if raw == "residential":
mode = "shellcrash"
if chain is None:
chain = True
elif raw not in MODES:
if raw not in MODES:
raise ValueError(f"unsupported egress mode: {raw}")
else:
mode = raw
mode = raw
s = _settings(cfg)
# dialer-proxy chain only meaningful with ShellCrash
if chain is None:
chain = chain_residential(s) if mode == "shellcrash" else False
chain = bool(chain) and mode == "shellcrash"
@ -241,31 +300,46 @@ def apply_mode(
if cover_neko_flag is None:
cover_neko_flag = mode != "off"
if cover_relay_flag is None:
cover_relay_flag = mode == "shellcrash"
cover_relay_flag = mode in {"shellcrash", "residential"}
if cover_uploads_flag is None:
cover_uploads_flag = mode != "off"
socks_on = mode == "residential" or (mode == "shellcrash" and chain)
updates: dict[str, Any] = {
_MODE_KEY: mode,
_CHAIN_KEY: chain,
_NEKO_KEY: bool(cover_neko_flag),
_RELAY_KEY: bool(cover_relay_flag),
_UPLOADS_KEY: bool(cover_uploads_flag),
# Keep legacy flags aligned with «住宅链式» checkbox only (not a separate engine).
"global_socks_enabled": chain,
"shorts_upload_socks_enabled": chain,
"global_socks_enabled": socks_on,
"shorts_upload_socks_enabled": socks_on,
}
db.update_settings_map(updates)
s = db.get_settings_map()
# Never run douyinweb-singbox as China residential path — stop if leftover.
try:
singbox_manager.stop()
except Exception:
pass
chain_result: dict[str, Any] = {"skipped": True}
residential_result: dict[str, Any] = {"skipped": True}
if mode == "residential":
from . import global_socks
prof = global_socks.active_profile(s)
if not prof:
raise ValueError("已启用静态住宅 IP,但未配置 SOCKS5 账号(网络页「业务 SOCKS」填写)")
# Start DouyinWEB forwarder only — never host sing-box.service
residential_result = singbox_manager.apply_from_settings(s)
if not residential_result.get("ok") and not residential_result.get("running"):
raise ValueError(str(residential_result.get("error") or "douyinweb-singbox 启动失败"))
else:
# Leaving residential: stop app forwarder only
try:
residential_result = {**singbox_manager.stop(), "note": "stopped douyinweb-singbox"}
except Exception as exc:
residential_result = {"ok": False, "error": str(exc)}
if mode == "shellcrash":
from . import shellcrash_hub
if chain:
from . import global_socks
@ -277,7 +351,6 @@ def apply_mode(
dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER,
)
else:
# Normal ShellCrash node (not residential landing).
try:
chain_result = shellcrash_hub.apply_profile(
shellcrash_hub.DEFAULT_PROFILE,
@ -287,7 +360,7 @@ def apply_mode(
chain_result = {"ok": False, "error": str(exc)}
pc_path = ""
if mode == "shellcrash" and (cover_relay_flag or cover_uploads_flag):
if mode != "off" and (cover_relay_flag or cover_uploads_flag):
pc_path = str(write_proxychains_conf(s))
neko_result: dict[str, Any] = {"skipped": True}
@ -303,26 +376,32 @@ def apply_mode(
"ok": True,
"egress": status(s),
"chain": chain_result,
"residential": residential_result,
"proxychains_conf": pc_path,
"neko": neko_result,
"v2ray_agent": singbox_manager.host_v2ray_agent_status(),
}
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
mode = get_mode(cfg)
proxy = _host_http_proxy(cfg) if mode != "off" else ""
proxy = google_http_proxy(cfg) if mode != "off" else ""
targets = [
("google", "https://www.google.com/generate_204"),
("youtube", "https://www.youtube.com/"),
("ip", "https://api.ipify.org"),
("douyin", "https://www.douyin.com/"),
]
rows = []
for name, url in targets:
# Douyin: always probe DIRECT; also via proxy to show rule should still work for pull via ShellCrash
if name == "douyin":
rows.append(_curl_probe("douyin_direct", url, proxy=""))
if proxy:
rows.append(_curl_probe("douyin_via_sc", url, proxy=proxy))
rows.append(_curl_probe("douyin_via_proxy", url, proxy=proxy))
continue
if name == "ip":
rows.append(_curl_probe_body("exit_ip", url, proxy=proxy))
rows.append(_curl_probe_body("exit_ip_direct", url, proxy=""))
continue
rows.append(_curl_probe(name, url, proxy=proxy))
rows.append(_curl_probe(f"{name}_direct", url, proxy=""))
@ -366,29 +445,84 @@ def _curl_probe(name: str, url: str, *, proxy: str) -> dict[str, Any]:
}
def _curl_probe_body(name: str, url: str, *, proxy: str) -> dict[str, Any]:
cmd = ["curl", "-sS", "-m", "10"]
if proxy:
cmd.extend(["-x", proxy])
cmd.append(url)
t0 = time.time()
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=14, check=False)
body = (p.stdout or "").strip()[:64]
ok = p.returncode == 0 and bool(body)
return {
"target": name,
"ok": ok,
"http_code": "200" if ok else "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"body": body,
"error": (p.stderr or "").strip()[:160] if not ok else "",
}
except Exception as exc:
return {
"target": name,
"ok": False,
"http_code": "000",
"elapsed_ms": int((time.time() - t0) * 1000),
"via": proxy or "direct",
"body": "",
"error": str(exc)[:160],
}
def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
from . import shellcrash_hub
from . import singbox_manager
s = _settings(cfg)
mode = get_mode(s)
chain = chain_residential(s) if mode == "shellcrash" else False
sc = shellcrash_hub.status()
host_proxy = _host_http_proxy(s)
chain = chain_residential(s)
vps = _is_vps_host(s)
sc: dict[str, Any] = {}
try:
from . import shellcrash_hub
sc = shellcrash_hub.status() or {}
except Exception:
sc = {}
host_proxy = google_http_proxy(s)
neko_proxy = neko_browser_proxy(s)
pc = proxychains_bin()
exit_label = RESIDENTIAL_PROXY_NAME if chain else (sc.get("selected_node") or shellcrash_hub.DEFAULT_NODE)
return {
"mode": mode,
"chain_residential": chain,
"modes": [
{"id": "off", "label": "直连", "description": "不经 ShellCrash"},
sb = singbox_manager.status()
if mode == "residential":
exit_label = "static-residential"
elif chain:
exit_label = RESIDENTIAL_PROXY_NAME
else:
exit_label = sc.get("selected_node") or "direct"
modes_ui = [
{"id": "off", "label": "机房直连", "description": "美国 VPS 默认:业务用机房 IP"},
{
"id": "residential",
"label": "静态住宅 IP",
"description": f"本机 :{LOCAL_MIXED_PORT} → 住宅 SOCKS(不动 v2ray-agent)",
"ready": True,
},
]
if not vps:
modes_ui.append(
{
"id": "shellcrash",
"label": "ShellCrash",
"description": "业务统一走本机 :7890;可选住宅链式落地",
"description": "物理机出海 :7890;可选住宅链式",
"ready": bool(sc.get("running") or sc.get("installed")),
},
],
}
)
return {
"mode": mode,
"chain_residential": chain,
"host_profile": "vps" if vps else "physical",
"modes": modes_ui,
"cover": {
"neko": cover_neko(s),
"relay": cover_relay(s),
@ -399,13 +533,25 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"exit_node": exit_label,
"dialer": DEFAULT_DIALER,
"residential_proxy_name": RESIDENTIAL_PROXY_NAME,
"socks_url": f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "",
"socks_url": (
local_residential_socks()
if mode == "residential"
else (f"socks5://127.0.0.1:{shellcrash_mixed_port(s)}" if mode == "shellcrash" else "")
),
"local_mixed": local_residential_http_proxy() if mode == "residential" else "",
"proxychains": {
"installed": bool(pc),
"bin": pc,
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
"relay_active": ffmpeg_uses_proxy(s),
},
"douyinweb_singbox": {
"running": bool(sb.get("running")),
"unit": sb.get("unit"),
"mixed": sb.get("mixed"),
"config": sb.get("config"),
},
"v2ray_agent": sb.get("v2ray_agent") or singbox_manager.host_v2ray_agent_status(),
"shellcrash": {
"running": bool(sc.get("running")),
"mixed_port": sc.get("mixed_port") or "7890",
@ -414,48 +560,55 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
"matrix": [
{
"id": "neko",
"label": "Neko Chrome",
"label": "Neko Chrome / X",
"active": bool(neko_proxy),
"detail": (neko_proxy + (f" → {exit_label}" if chain else "")) if neko_proxy else "直连",
"detail": neko_proxy or "直连(机房 IP)",
},
{
"id": "relay",
"label": "直播推流 FFmpeg",
"active": ffmpeg_uses_proxy(s),
"detail": (
f"proxychains → ShellCrash → {exit_label}"
f"proxychains → {exit_label}"
if ffmpeg_uses_proxy(s)
else ("缺 proxychains" if cover_relay(s) and not pc else "直连")
else ("缺 proxychains" if cover_relay(s) and not pc else "直连(机房 IP)")
),
},
{
"id": "uploads",
"label": "Shorts / 长视频 / 上传",
"label": "Shorts / 长视频 / TikTok",
"active": bool(resolve_upload_proxy(s)),
"detail": (host_proxy + (f" → {exit_label}" if chain else "")) if resolve_upload_proxy(s) else "直连",
"detail": (host_proxy + f" → {exit_label}") if resolve_upload_proxy(s) else "直连(机房 IP)",
},
],
"hints": _hints(mode, chain, sc, pc),
"hints": _hints(mode, chain, sc, pc, sb, vps),
"app_root": str(ROOT),
"backend": str(BACKEND),
}
def _hints(mode: str, chain: bool, sc: dict[str, Any], pc: str) -> list[str]:
def _hints(
mode: str,
chain: bool,
sc: dict[str, Any],
pc: str,
sb: dict[str, Any],
vps: bool,
) -> list[str]:
out: list[str] = []
if mode == "shellcrash":
out.append("硬规则:*.douyin.com / 抖音 CDN 必须 DIRECT(拉流与监控不可走机场)")
out.append("硬规则:*.douyin.com / 抖音 CDN 始终直连,不进住宅代理")
out.append("绝不操作宿主机 sing-box.service(v2ray-agent);仅 douyinweb-singbox")
if mode == "residential":
if not sb.get("running"):
out.append("douyinweb-singbox 未运行 — 检查 SOCKS 账号后重新「应用」")
else:
out.append(f"业务入口 {local_residential_http_proxy()} → 静态住宅;默认关=机房 IP")
if mode == "off" and vps:
out.append("当前机房 IP 直出(美国 VPS 默认可访问 Google/YouTube)")
if mode == "shellcrash" and not sc.get("running"):
out.append("ShellCrash 未运行 — 先启动,再应用出海")
out.append("ShellCrash 未运行 — 先启动再应用")
if mode == "shellcrash" and chain:
out.append(
"住宅落地 = ShellCrash 链式(dialer-proxy):家宽 → 前置节点 → 住宅 SOCKS。"
"详见虚空终端 docs:dialer-proxy"
)
if mode == "shellcrash" and not chain:
out.append("当前用 ShellCrash 机场线路出海;勾选「住宅落地」才会链式到 SOCKS5")
out.append("住宅落地 = ShellCrash dialer-proxy 链式(物理机)")
if mode != "off" and not pc:
out.append("未安装 proxychains4 — 直播推流无法走代理")
if mode == "off":
out.append("直连:国内物理机上 YouTube Studio / 推流通常不可用")
return out

View File

@ -123,9 +123,11 @@ def clip_encode_defer_reason(*, respect_live_push: bool = True) -> str:
cores = max(1, int(snap.get("cpu_cores") or 1))
load1 = float(snap.get("load1") or 0.0)
cpu = float(snap.get("cpu_percent") or 0.0)
# Leave ~1 core free for API accept loop + Neko CDP.
if load1 >= max(1.5, cores * 1.15):
# Leave ~1+ core free for API accept loop + Neko CDP + live push.
# 3-core dylive with live RTMP+Neko routinely sits load 3-7; 0.85*cores
# starved yt_long all day (0 uploads). Allow ~2x cores; still block meltdown.
if load1 >= max(12.0, cores * 4.0):
return f"load1={load1}"
if cpu >= 80.0:
if cpu >= 96.0:
return f"cpu={cpu}"
return ""

View File

@ -1,197 +1,198 @@
# -*- coding: utf-8 -*-
"""Host profile: VPS (lean) vs physical (full Neko + ShellCrash).
Does **not** stop VPS edge systemd units (sing-box / frpp / wg-quick@wg-dy*).
Those are infrastructure for the physical site, not app「网络」toggles.
"""
from __future__ import annotations
import os
from typing import Any
PROFILES = ("vps", "physical")
_KEY = "host_profile"
def _settings() -> dict[str, Any]:
from . import db
return dict(db.get_settings_map())
def infer_profile(cfg: dict[str, Any] | None = None) -> str:
s = dict(cfg) if cfg is not None else _settings()
raw = str(s.get(_KEY) or "").strip().lower()
if raw in PROFILES:
return raw
edge = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip()
if edge and edge not in {"127.0.0.1", "localhost", "::1"}:
return "physical"
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "").strip()
if bind in {"0.0.0.0", "*"}:
return "physical"
return "vps"
def status() -> dict[str, Any]:
s = _settings()
profile = infer_profile(s)
return {
"ok": True,
"profile": profile,
"stored": str(s.get(_KEY) or "").strip().lower() in PROFILES,
"profiles": list(PROFILES),
"effects": {
"vps": [
"egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)",
"本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)",
"单路独占默认开启(省内存;可配对物理机 ops-neko)",
],
"physical": [
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
"单路独占默认关闭(允许多 Neko 预热)",
"不自动拉起全部 Neko(由分配页按需开启);ops-neko 优先 .cn / 腾讯云 ICE",
],
},
"never_touches": [
"sing-box.service",
"frpp.service",
"wg-quick@wg-dy.service",
"wg-quick@wg-dy-cn.service",
],
}
def _disable_all_neko() -> dict[str, Any]:
from . import yt_assign_db
from . import youtube_neko
from .db import _connect, _lock
disabled = 0
with _lock:
conn = _connect()
try:
yt_assign_db.ensure_yt_assign_tables(conn)
cur = conn.execute(
"UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0"
)
disabled = int(cur.rowcount or 0)
conn.commit()
finally:
conn.close()
stopped = youtube_neko.stop_instances_except(0)
try:
youtube_neko.sync_for_groups(
yt_assign_db.list_groups(include_urls=False),
reconcile_running=True,
)
except Exception as exc:
return {
"ok": False,
"disabled_flags": disabled,
"stopped_containers": stopped,
"error": str(exc)[:300],
}
return {"ok": True, "disabled_flags": disabled, "stopped_containers": stopped}
def apply_profile(profile: str) -> dict[str, Any]:
from . import db
from . import egress_hub
from . import shellcrash_hub
from . import singbox_manager
raw = str(profile or "").strip().lower()
if raw not in PROFILES:
raise ValueError("profile must be vps or physical")
steps: dict[str, Any] = {}
if raw == "vps":
try:
steps["egress"] = egress_hub.apply_mode(
"off",
chain=False,
cover_neko_flag=False,
cover_relay_flag=False,
cover_uploads_flag=False,
refresh_neko=False,
)
except Exception as exc:
steps["egress"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["singbox_app"] = singbox_manager.stop()
except Exception as exc:
steps["singbox_app"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["shellcrash"] = shellcrash_hub.action("stop")
except Exception as exc:
steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]}
# Do NOT wipe assign Neko — dylive hub needs per-group start/stop like physical
# (local /neko/N/ and/or paired ops-neko). Exclusive-live still pauses siblings at push time.
steps["neko"] = {
"ok": True,
"note": "vps: leave assign Neko as-is; enable/start/stop per group in assign UI",
}
# Exclusive-live in-memory state is applied in apply_profile_async.
db.update_settings_map(
{
_KEY: "vps",
"youtube_relay_exclusive_live": True,
"global_socks_enabled": False,
"shorts_upload_socks_enabled": False,
"egress_chain_residential": False,
}
)
steps["settings"] = {"host_profile": "vps", "youtube_relay_exclusive_live": True}
else:
try:
steps["egress"] = egress_hub.apply_mode(
"shellcrash",
chain=False,
refresh_neko=False,
)
except Exception as exc:
# ShellCrash may be absent on pure VPS — still store profile + exclusive off.
db.update_settings_map({"egress_mode": "shellcrash"})
steps["egress"] = {"ok": False, "error": str(exc)[:300], "settings_only": True}
db.update_settings_map(
{
_KEY: "physical",
"youtube_relay_exclusive_live": False,
}
)
steps["settings"] = {
"host_profile": "physical",
"youtube_relay_exclusive_live": False,
"neko": "not_auto_started",
}
steps["neko"] = {"ok": True, "note": "physical: leave Neko as-is; enable per group in assign UI"}
return {"ok": True, "profile": raw, "steps": steps, **status()}
async def apply_profile_async(profile: str) -> dict[str, Any]:
"""Async wrapper so exclusive-live pipeline state stays consistent."""
import asyncio
from . import db
from . import youtube_relay_pipeline
raw = str(profile or "").strip().lower()
result = await asyncio.to_thread(apply_profile, raw)
# Re-apply exclusive via pipeline so in-memory winner/pause state matches.
exclusive_on = raw == "vps"
try:
result["steps"]["exclusive_live"] = await youtube_relay_pipeline.set_exclusive_live(exclusive_on)
except Exception as exc:
db.update_settings_map({"youtube_relay_exclusive_live": exclusive_on})
result["steps"]["exclusive_live"] = {"ok": False, "error": str(exc)[:300], "settings_written": True}
result["profile"] = raw
return result
# -*- coding: utf-8 -*-
"""Host profile: VPS (lean) vs physical (full Neko + ShellCrash).
Does **not** stop VPS edge systemd units (sing-box / frpp / wg-quick@wg-dy*).
Those are infrastructure for the physical site, not app「网络」toggles.
"""
from __future__ import annotations
import os
from typing import Any
PROFILES = ("vps", "physical")
_KEY = "host_profile"
def _settings() -> dict[str, Any]:
from . import db
return dict(db.get_settings_map())
def infer_profile(cfg: dict[str, Any] | None = None) -> str:
s = dict(cfg) if cfg is not None else _settings()
raw = str(s.get(_KEY) or "").strip().lower()
if raw in PROFILES:
return raw
edge = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip()
if edge and edge not in {"127.0.0.1", "localhost", "::1"}:
return "physical"
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "").strip()
if bind in {"0.0.0.0", "*"}:
return "physical"
return "vps"
def status() -> dict[str, Any]:
s = _settings()
profile = infer_profile(s)
return {
"ok": True,
"profile": profile,
"stored": str(s.get(_KEY) or "").strip().lower() in PROFILES,
"profiles": list(PROFILES),
"effects": {
"vps": [
"默认机房 IP 直出;可选「静态住宅 IP」经 douyinweb-singbox :17891",
"绝不操作宿主机 sing-box.service(v2ray-agent)",
"本机分配 Neko 仍可按频道启停",
"单路独占默认开启(省内存)",
],
"physical": [
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
"单路独占默认关闭(允许多 Neko 预热)",
"不自动拉起全部 Neko(由分配页按需开启);ops-neko 优先 .cn / 腾讯云 ICE",
],
},
"never_touches": [
"sing-box.service",
"frpp.service",
"wg-quick@wg-dy.service",
"wg-quick@wg-dy-cn.service",
],
}
def _disable_all_neko() -> dict[str, Any]:
from . import yt_assign_db
from . import youtube_neko
from .db import _connect, _lock
disabled = 0
with _lock:
conn = _connect()
try:
yt_assign_db.ensure_yt_assign_tables(conn)
cur = conn.execute(
"UPDATE yt_assign_groups SET neko_enabled = 0 WHERE neko_enabled != 0"
)
disabled = int(cur.rowcount or 0)
conn.commit()
finally:
conn.close()
stopped = youtube_neko.stop_instances_except(0)
try:
youtube_neko.sync_for_groups(
yt_assign_db.list_groups(include_urls=False),
reconcile_running=True,
)
except Exception as exc:
return {
"ok": False,
"disabled_flags": disabled,
"stopped_containers": stopped,
"error": str(exc)[:300],
}
return {"ok": True, "disabled_flags": disabled, "stopped_containers": stopped}
def apply_profile(profile: str) -> dict[str, Any]:
from . import db
from . import egress_hub
from . import shellcrash_hub
from . import singbox_manager
raw = str(profile or "").strip().lower()
if raw not in PROFILES:
raise ValueError("profile must be vps or physical")
steps: dict[str, Any] = {}
if raw == "vps":
try:
steps["egress"] = egress_hub.apply_mode(
"off",
chain=False,
cover_neko_flag=False,
cover_relay_flag=False,
cover_uploads_flag=False,
refresh_neko=False,
)
except Exception as exc:
steps["egress"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["singbox_app"] = singbox_manager.stop()
except Exception as exc:
steps["singbox_app"] = {"ok": False, "error": str(exc)[:300]}
try:
steps["shellcrash"] = shellcrash_hub.action("stop")
except Exception as exc:
steps["shellcrash"] = {"ok": False, "skipped": True, "error": str(exc)[:300]}
# Do NOT wipe assign Neko — dylive hub needs per-group start/stop like physical
# (local /neko/N/ and/or paired ops-neko). Exclusive-live still pauses siblings at push time.
steps["neko"] = {
"ok": True,
"note": "vps: leave assign Neko as-is; enable/start/stop per group in assign UI",
}
# Exclusive-live in-memory state is applied in apply_profile_async.
db.update_settings_map(
{
_KEY: "vps",
"youtube_relay_exclusive_live": True,
"global_socks_enabled": False,
"shorts_upload_socks_enabled": False,
"egress_chain_residential": False,
}
)
steps["settings"] = {"host_profile": "vps", "youtube_relay_exclusive_live": True}
else:
try:
steps["egress"] = egress_hub.apply_mode(
"shellcrash",
chain=False,
refresh_neko=False,
)
except Exception as exc:
# ShellCrash may be absent on pure VPS — still store profile + exclusive off.
db.update_settings_map({"egress_mode": "shellcrash"})
steps["egress"] = {"ok": False, "error": str(exc)[:300], "settings_only": True}
db.update_settings_map(
{
_KEY: "physical",
"youtube_relay_exclusive_live": False,
}
)
steps["settings"] = {
"host_profile": "physical",
"youtube_relay_exclusive_live": False,
"neko": "not_auto_started",
}
steps["neko"] = {"ok": True, "note": "physical: leave Neko as-is; enable per group in assign UI"}
return {"ok": True, "profile": raw, "steps": steps, **status()}
async def apply_profile_async(profile: str) -> dict[str, Any]:
"""Async wrapper so exclusive-live pipeline state stays consistent."""
import asyncio
from . import db
from . import youtube_relay_pipeline
raw = str(profile or "").strip().lower()
result = await asyncio.to_thread(apply_profile, raw)
# Re-apply exclusive via pipeline so in-memory winner/pause state matches.
exclusive_on = raw == "vps"
try:
result["steps"]["exclusive_live"] = await youtube_relay_pipeline.set_exclusive_live(exclusive_on)
except Exception as exc:
db.update_settings_map({"youtube_relay_exclusive_live": exclusive_on})
result["steps"]["exclusive_live"] = {"ok": False, "error": str(exc)[:300], "settings_written": True}
result["profile"] = raw
return result

View File

@ -1,114 +1,130 @@
# -*- coding: utf-8 -*-
"""Classify Shorts/TikTok job errors into actionable buckets for UI."""
from __future__ import annotations
from typing import Any
def classify_job_error(error: str = "", *, platform: str = "") -> dict[str, Any]:
text = str(error or "").strip()
low = text.lower()
plat = str(platform or "").strip().lower()
def hit(*needles: str) -> bool:
return any(n in low or n in text for n in needles)
if not text:
return {
"code": "ok",
"label": "正常",
"action": "",
"action_label": "",
"severity": False,
}
if hit("cookie", "sessionid", "登录", "login expired", "未配置 cookie", "会话"):
return {
"code": "cookie",
"label": "Cookie / 登录失效",
"action": "update_cookie",
"action_label": "更新 Cookie",
"severity": False,
}
if hit("2158", "限流", "too fast", "take a rest", "spam", "rate_limit", "rate limit", "官方限流"):
return {
"code": "rate_limit",
"label": "平台限流",
"action": "wait_retry",
"action_label": "等待后自动试传",
"severity": True,
}
if hit("quota", "403", "daily limit", "upload limit", "youtube.*quota", "exceeded"):
return {
"code": "quota",
"label": "平台配额用尽",
"action": "wait_quota",
"action_label": "等配额重置或换 Client",
"severity": True,
}
if hit("成片文件不存在", "clip", "no such file", "过小", "too small", "empty file", "录制失败"):
return {
"code": "clip",
"label": "成片缺失/损坏",
"action": "rerecord",
"action_label": "重新录制",
"severity": True,
}
if hit("黑屏", "静音", "质量不合格", "quality"):
return {
"code": "quality",
"label": "成片质量不合格",
"action": "rerecord",
"action_label": "换时段重录",
"severity": True,
}
if hit("stream", "直播已结束", "not live", "404", "拉流", "cdn"):
return {
"code": "stream",
"label": "直播流不可用",
"action": "skip_or_retry",
"action_label": "跳过或换房",
"severity": False,
}
if hit("socks", "proxy", "代理"):
return {
"code": "proxy",
"label": "代理/网络异常",
"action": "check_socks",
"action_label": "检查 SOCKS",
"retryable": True,
}
if hit("oauth", "token", "unauthorized", "401"):
return {
"code": "oauth",
"label": "OAuth 授权失效",
"action": "reauth",
"action_label": "重新授权",
"retryable": False,
}
if plat == "tiktok" and hit("机房", "datacenter", "tt-target-idc", "project"):
return {
"code": "dc",
"label": "TikTok 机房不匹配",
"action": "update_cookie",
"action_label": "重贴 Cookie + 机房",
"retryable": False,
}
return {
"code": "unknown",
"label": "其他错误",
"action": "retry",
"action_label": "重试",
"retryable": True,
"detail": text[:200],
}
def enrich_job_error(job: dict[str, Any] | None, *, platform: str = "") -> dict[str, Any] | None:
if not job:
return None
out = dict(job)
err = str(out.get("error") or "")
info = classify_job_error(err, platform=platform)
out["error_class"] = info
return out
# -*- coding: utf-8 -*-
"""Classify Shorts/TikTok job errors into actionable buckets for UI."""
from __future__ import annotations
from typing import Any
def classify_job_error(error: str = "", *, platform: str = "") -> dict[str, Any]:
text = str(error or "").strip()
low = text.lower()
plat = str(platform or "").strip().lower()
def hit(*needles: str) -> bool:
return any(n in low or n in text for n in needles)
if not text:
return {
"code": "ok",
"label": "正常",
"action": "",
"action_label": "",
"severity": False,
}
if hit("cookie", "sessionid", "登录", "login expired", "未配置 cookie", "会话"):
return {
"code": "cookie",
"label": "Cookie / 登录失效",
"action": "update_cookie",
"action_label": "更新 Cookie",
"severity": False,
}
if hit("2158", "限流", "too fast", "take a rest", "spam", "rate_limit", "rate limit", "官方限流"):
return {
"code": "rate_limit",
"label": "平台限流",
"action": "wait_retry",
"action_label": "等待后自动试传",
"severity": True,
}
if hit("quota", "403", "daily limit", "upload limit", "youtube.*quota", "exceeded"):
return {
"code": "quota",
"label": "平台配额用尽",
"action": "wait_quota",
"action_label": "等配额重置或换 Client",
"severity": True,
}
if hit("成片文件不存在", "clip", "no such file", "过小", "too small", "empty file", "录制失败"):
return {
"code": "clip",
"label": "成片缺失/损坏",
"action": "rerecord",
"action_label": "重新录制",
"severity": True,
}
if hit("黑屏", "静音", "质量不合格", "quality"):
return {
"code": "quality",
"label": "成片质量不合格",
"action": "rerecord",
"action_label": "换时段重录",
"severity": True,
}
if hit("stream", "直播已结束", "not live", "404", "拉流", "cdn"):
return {
"code": "stream",
"label": "直播流不可用",
"action": "skip_or_retry",
"action_label": "跳过或换房",
"severity": False,
}
if hit("socks", "proxy", "代理"):
return {
"code": "proxy",
"label": "代理/网络异常",
"action": "check_socks",
"action_label": "检查 SOCKS",
"retryable": True,
}
if hit("oauth", "token", "unauthorized", "401"):
return {
"code": "oauth",
"label": "OAuth 授权失效",
"action": "reauth",
"action_label": "重新授权",
"retryable": False,
}
if plat == "tiktok" and hit(
"signature",
"playwright",
"headless_shell",
"executable doesn't exist",
"failed to parse signature",
"failed to generate signatures",
):
return {
"code": "tiktok_signature",
"label": "TikTok 签名失败",
"action": "retry",
"action_label": "重试",
"retryable": True,
}
# Do NOT match bare "Datacenter Assigned" login banner — that line appears on every upload.
if plat == "tiktok" and hit("机房不匹配", "tt-target-idc", "会话机房", "cookie 无效或机房"):
return {
"code": "dc",
"label": "TikTok 机房不匹配",
"action": "update_cookie",
"action_label": "重贴 Cookie + 机房",
"retryable": False,
}
return {
"code": "unknown",
"label": "其他错误",
"action": "retry",
"action_label": "重试",
"retryable": True,
"detail": text[:200],
}
def enrich_job_error(job: dict[str, Any] | None, *, platform: str = "") -> dict[str, Any] | None:
if not job:
return None
out = dict(job)
err = str(out.get("error") or "")
info = classify_job_error(err, platform=platform)
out["error_class"] = info
return out

View File

@ -171,9 +171,11 @@ async def lifespan(_: FastAPI):
return
from .db_backup import backup_loop
from .ops_alerts import alert_loop
from .disk_guard import disk_guard_loop
asyncio.create_task(backup_loop())
asyncio.create_task(alert_loop())
asyncio.create_task(disk_guard_loop())
try:
from . import ops_neko_sync
@ -1686,7 +1688,7 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
raise HTTPException(400, "source_daily_max 无效") from None
if "yt_long_source_cap" in raw:
try:
patch["yt_long_source_cap"] = max(42, min(300, int(raw["yt_long_source_cap"])))
patch["yt_long_source_cap"] = max(0, min(300, int(raw["yt_long_source_cap"])))
except Exception:
raise HTTPException(400, "source_cap 无效") from None
if "yt_long_channel_daily_max" in raw:
@ -1696,12 +1698,12 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
raise HTTPException(400, "channel_daily_max 无效") from None
if "yt_long_min_sec" in raw:
try:
patch["yt_long_min_sec"] = max(180, min(480, int(raw["yt_long_min_sec"])))
patch["yt_long_min_sec"] = max(480, min(900, int(raw["yt_long_min_sec"])))
except Exception:
raise HTTPException(400, "min_sec 无效") from None
if "yt_long_max_sec" in raw:
try:
patch["yt_long_max_sec"] = max(180, min(480, int(raw["yt_long_max_sec"])))
patch["yt_long_max_sec"] = max(480, min(900, int(raw["yt_long_max_sec"])))
except Exception:
raise HTTPException(400, "max_sec 无效") from None
if "yt_long_upload_min_gap_sec" in raw:
@ -1716,8 +1718,8 @@ async def yt_long_settings_update(body: dict[str, Any] | None = None) -> dict[st
if patch:
# Keep min <= max
cfg = {**db.get_settings_map(), **patch}
lo = int(cfg.get("yt_long_min_sec") or 180)
hi = int(cfg.get("yt_long_max_sec") or 480)
lo = int(cfg.get("yt_long_min_sec") or 480)
hi = int(cfg.get("yt_long_max_sec") or 900)
if lo > hi:
patch["yt_long_max_sec"] = lo
db.update_settings_map(patch)
@ -4521,22 +4523,39 @@ async def network_socks_get() -> dict[str, Any]:
@app.patch("/api/network/socks")
async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]:
"""Update global SOCKS profiles — empty list allowed (fresh install)."""
"""Update global SOCKS profiles — empty list allowed (fresh install).
On VPS: enabled → egress_mode=residential + douyinweb-singbox only.
Never touches host sing-box.service (v2ray-agent).
"""
from . import db
from . import egress_hub
from . import global_socks
from . import host_profile
from . import singbox_manager
cfg = await asyncio.to_thread(db.get_settings_map)
updates: dict[str, Any] = {}
want_on: bool | None = None
if "enabled" in body:
updates["global_socks_enabled"] = bool(body.get("enabled"))
updates["shorts_upload_socks_enabled"] = bool(body.get("enabled"))
# 住宅 SOCKS 勾选 = ShellCrash 链式落地,不是独立引擎
updates["egress_chain_residential"] = bool(body.get("enabled"))
if bool(body.get("enabled")):
updates["egress_mode"] = "shellcrash"
elif str(cfg.get("egress_mode") or "") == "residential":
updates["egress_mode"] = "shellcrash"
want_on = bool(body.get("enabled"))
updates["global_socks_enabled"] = want_on
updates["shorts_upload_socks_enabled"] = want_on
is_vps = host_profile.infer_profile(cfg) == "vps"
if want_on:
if is_vps:
updates["egress_mode"] = "residential"
updates["egress_chain_residential"] = False
else:
# Physical: keep ShellCrash dialer-proxy chain semantics
updates["egress_mode"] = "shellcrash"
updates["egress_chain_residential"] = True
else:
updates["egress_chain_residential"] = False
if str(cfg.get("egress_mode") or "") in {"residential", "shellcrash"}:
updates["egress_mode"] = "off" if is_vps else str(cfg.get("egress_mode") or "shellcrash")
if is_vps:
updates["egress_mode"] = "off"
if "active_profile_id" in body:
updates["global_socks_profile_id"] = str(body.get("active_profile_id") or "").strip()
updates["shorts_upload_socks_profile_id"] = updates["global_socks_profile_id"]
@ -4547,7 +4566,6 @@ async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]:
for item in raw:
p = global_socks._norm_profile(item)
if p and p["server"] and p["port"] > 0:
# Keep existing password if client sent masked ***
old = global_socks.get_socks_profile(str(p["id"]), cfg)
pwd = str(p.get("password") or "")
if old and (not pwd or pwd.startswith("***")):
@ -4558,10 +4576,26 @@ async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]:
if updates:
await asyncio.to_thread(db.update_settings_map, updates)
cfg = await asyncio.to_thread(db.get_settings_map)
try:
await asyncio.to_thread(singbox_manager.apply_from_settings, cfg)
except Exception:
pass
mode = str(cfg.get("egress_mode") or "off")
if mode == "residential" and cfg.get("global_socks_enabled"):
try:
await asyncio.to_thread(
egress_hub.apply_mode,
"residential",
chain=False,
refresh_neko=False, # never hang API on docker recreate
cfg=cfg,
)
except Exception:
try:
await asyncio.to_thread(singbox_manager.apply_from_settings, cfg)
except Exception:
pass
elif want_on is False or mode == "off":
try:
await asyncio.to_thread(singbox_manager.stop)
except Exception:
pass
from . import network_hub
return await asyncio.to_thread(network_hub.socks_status)
@ -4593,7 +4627,7 @@ async def network_egress_patch(body: dict[str, Any] = Body(default={})) -> dict[
cover_neko_flag=cover.get("neko") if "neko" in cover else body.get("cover_neko"),
cover_relay_flag=cover.get("relay") if "relay" in cover else body.get("cover_relay"),
cover_uploads_flag=cover.get("uploads") if "uploads" in cover else body.get("cover_uploads"),
refresh_neko=bool(body.get("refresh_neko", True)),
refresh_neko=bool(body.get("refresh_neko", False)),
dialer=str(body.get("dialer") or "") or None,
)
except ValueError as exc:

View File

@ -1,283 +1,285 @@
# -*- coding: utf-8 -*-
"""Network hub — WireGuard primary + FRP auxiliary (SH2-adapted).
Physical dual-path policy:
- Primary: WireGuard (wg-dy) carries app traffic VPS Caddy → 10.8.0.2 and preferred SSH.
- Auxiliary: FRP (frpp :4014) is emergency SSH / ops only — never the app data path.
"""
from __future__ import annotations
import os
import re
import shutil
import time
from pathlib import Path
from typing import Any
from . import global_socks
from . import shellcrash_hub
from . import wireguard_hub
def _run(cmd: list[str], timeout: int = 12) -> tuple[int, str]:
import subprocess
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
except Exception as exc:
return 1, str(exc)
def _unit_active(name: str) -> str:
code, out = _run(["systemctl", "is-active", name], timeout=5)
return (out.splitlines()[0] if out else ("inactive" if code else "unknown")).strip()
def path_roles() -> dict[str, Any]:
"""Declare which transport is primary vs auxiliary."""
cn_up = Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False
wg_target = "10.9.0.2(wg-dy-cn 国内优先)" if cn_up else "10.8.0.2(wg-dy 海外)"
return {
"app_https": {
"primary": "wireguard",
"detail": f"VPS Caddy → WG {wg_target}:4015/8014;wg-dy 海外链路保留作备份",
},
"ops_ssh": {
"primary": "wireguard",
"auxiliary": "frp",
"detail": "优先 WG(wg-dy-cn → 10.9.0.1 或 wg-dy → 10.8.0.1);FRP :4014 仅应急",
},
"policy": "wg_cn_primary_wg_us_backup_frp_aux",
}
def frp_status() -> dict[str, Any]:
"""FRP is auxiliary — SSH/ops fallback only; do not carry app reverse_proxy."""
unit = None
for name in ("frpp", "frpc", "frp-panel"):
st = _unit_active(name)
if st in {"active", "activating"}:
unit = {"name": name, "state": st}
break
if unit is None and st not in {"inactive", "unknown", ""}:
unit = {"name": name, "state": st}
code, ps = _run(["bash", "-lc", "ps aux | grep -E '[f]rpc|[f]rpp|[f]rp-panel' | head -5"], timeout=8)
procs = [ln.strip() for ln in (ps or "").splitlines() if ln.strip()]
# Detect common SSH tunnel port hint
ports: list[int] = []
for ln in procs:
for m in re.finditer(r":(\d{2,5})\b", ln):
try:
ports.append(int(m.group(1)))
except ValueError:
pass
return {
"ok": True,
"role": "auxiliary",
"purpose": "ops_ssh_emergency",
"unit": unit,
"processes": procs[:5],
"hint_ports": sorted(set(ports))[:8],
"detail": "辅路径:仅应急 SSH/运维(如 VPS:4014→guest:22)。应用 HTTPS 必须走 WireGuard,勿把业务反代挂到 FRP。",
}
def socks_status() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
enabled = global_socks.is_global_socks_enabled(cfg)
profiles = global_socks.list_socks_profiles(cfg, public=True)
active_id = global_socks.active_profile_id(cfg)
from . import singbox_manager
return {
"ok": True,
"enabled": enabled,
"active_profile_id": active_id,
"profiles": profiles,
"local_mixed": global_socks.local_mixed_url() if enabled else "",
"singbox_running": bool(singbox_manager.is_running()) if enabled else False,
"hint": "新装默认无住宅节点;自行添加 SOCKS5",
}
def _deploy_shape_hint() -> str:
if Path("/etc/wireguard/wg-dy.conf").is_file() or any(
p.name == "wg-dy" for p in Path("/sys/class/net").iterdir() if Path("/sys/class/net").is_dir()
):
return "physical_or_wg"
return "colocated_or_unknown"
def _wg_handshake_age_sec() -> int | None:
"""Seconds since latest handshake on primary WG iface (wg-dy-cn preferred)."""
for iface in ("wg-dy-cn", "wg-dy"):
code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5)
if code != 0 or not out.strip():
continue
parts = out.split()
if len(parts) < 2:
continue
try:
ts = int(parts[-1])
except ValueError:
continue
if ts <= 0:
continue
return max(0, int(time.time()) - ts)
return None
_ping_wg_cache: tuple[float, dict[str, Any]] | None = None
_PING_WG_CACHE_TTL_SEC = 15.0
def _ping_wg_peer() -> dict[str, Any]:
global _ping_wg_cache
import time as _time
now = _time.time()
if _ping_wg_cache is not None:
cached_at, cached = _ping_wg_cache
if now - cached_at < _PING_WG_CACHE_TTL_SEC:
return dict(cached)
if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False:
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
else:
peer = str(os.environ.get("DY_WG_PEER_IP") or "10.8.0.1").strip() or "10.8.0.1"
code, out = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
ok = code == 0 and "1 received" in out.replace("packets ", "")
if not ok:
ok = code == 0 and ("bytes from" in out or "ttl=" in out.lower())
rtt = ""
m = re.search(r"time[=<]([0-9.]+)\s*ms", out)
if m:
rtt = m.group(1) + "ms"
result = {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
_ping_wg_cache = (now, result)
return dict(result)
def wireguard_watch_status() -> dict[str, Any]:
unit = _unit_active("douyinweb-wireguard-watch")
path = Path("/opt/douyinWEB/scripts/linux/wireguard_watch.sh")
return {
"unit": unit,
"installed": path.is_file(),
"path": str(path) if path.is_file() else "",
"hint": "stale handshake 自动重启 wg-dy-cn / wg-dy(主路径保活)",
}
def network_overview() -> dict[str, Any]:
wg = wireguard_hub.runtime_status()
age = _wg_handshake_age_sec()
ping = _ping_wg_peer()
wg["role"] = "primary"
wg["purpose"] = "app_https_and_ops_ssh"
wg["handshake_age_sec"] = age
wg["handshake_fresh"] = age is not None and age < 180
wg["peer_ping"] = ping
wg["watch"] = wireguard_watch_status()
if age is not None and age >= 300:
wg.setdefault("recommendations", []).append(
f"握手已 {age}s 未刷新 — watch 应重启 wg-dy;勿改用 FRP 扛业务"
)
frp = frp_status()
from . import egress_hub
# One ShellCrash status for this request (status() itself is also TTL-cached).
sc = shellcrash_hub.status()
return {
"ok": True,
"path_roles": path_roles(),
"wireguard": wg,
"frp": frp,
"shellcrash": sc,
"socks": socks_status(),
"egress": egress_hub.status(),
"deploy_shape": _deploy_shape_hint(),
"physical_checklist": physical_checklist(wg=wg, frp=frp, shellcrash=sc),
}
def physical_checklist(
*,
wg: dict[str, Any] | None = None,
frp: dict[str, Any] | None = None,
shellcrash: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Operator checklist — WireGuard primary, FRP auxiliary."""
checks: list[dict[str, Any]] = []
def add(name: str, ok: bool, detail: str = "") -> None:
checks.append({"name": name, "ok": bool(ok), "detail": detail})
pub = str(os.environ.get("DY_PUBLIC_BASE_URL") or "").strip()
add(
"public_base_url",
pub.startswith("https://") and "127.0.0.1" not in pub and not pub.startswith("http://10."),
pub or "missing DY_PUBLIC_BASE_URL",
)
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "127.0.0.1").strip()
shape = _deploy_shape_hint()
if shape.startswith("physical"):
add("neko_http_bind", bind in {"0.0.0.0", "*"}, f"DY_NEKO_HTTP_BIND={bind} (physical needs 0.0.0.0)")
else:
add("neko_http_bind", True, f"DY_NEKO_HTTP_BIND={bind}")
docker_ok = bool(shutil.which("docker"))
add("docker", docker_ok, "docker binary" if docker_ok else "missing")
seed = Path(__file__).resolve().parent.parent / "neko" / "tampermonkey-seed" / "Default" / "Extensions"
add("neko_seed", seed.is_dir(), str(seed))
wg_up = Path("/sys/class/net/wg-dy").exists() if Path("/sys/class/net").is_dir() else False
add("wg_primary_link", wg_up or shape != "physical_or_wg", "wg-dy iface (主路径)" if wg_up else "no wg-dy")
wg = wg or {}
age = wg.get("handshake_age_sec")
if isinstance(age, int):
add("wg_handshake", age < 300, f"age={age}s (主路径保活)")
elif wg_up:
add("wg_handshake", False, "无法读取 handshake")
ping = wg.get("peer_ping") if isinstance(wg.get("peer_ping"), dict) else {}
if ping:
add("wg_peer_ping", bool(ping.get("ok")), f"{ping.get('peer')} {ping.get('rtt') or ''}".strip())
watch = wg.get("watch") if isinstance(wg.get("watch"), dict) else {}
if shape.startswith("physical"):
add(
"wg_watch",
watch.get("unit") == "active",
f"unit={watch.get('unit') or 'missing'} — douyinweb-wireguard-watch 保活主路径",
)
frp = frp or {}
frp_unit = (frp.get("unit") or {}) if isinstance(frp.get("unit"), dict) else {}
add(
"frp_aux_ssh",
True,
f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务",
)
sc = shellcrash if isinstance(shellcrash, dict) else shellcrash_hub.status()
if shape.startswith("physical"):
add(
"shellcrash",
bool(sc.get("installed")) and bool(sc.get("running")),
f"installed={sc.get('installed')} unit={sc.get('unit')} mixed=:{sc.get('mixed_port') or '?'}",
)
failed = sum(1 for c in checks if not c["ok"])
return {
"ok": failed == 0,
"failed": failed,
"checks": checks,
"deploy_shape": shape,
"policy": "wg_primary_frp_aux",
}
# -*- coding: utf-8 -*-
"""Network hub — WireGuard primary + FRP auxiliary (SH2-adapted).
Physical dual-path policy:
- Primary: WireGuard (wg-dy) carries app traffic VPS Caddy → 10.8.0.2 and preferred SSH.
- Auxiliary: FRP (frpp :4014) is emergency SSH / ops only — never the app data path.
"""
from __future__ import annotations
import os
import re
import shutil
import time
from pathlib import Path
from typing import Any
from . import global_socks
from . import shellcrash_hub
from . import wireguard_hub
def _run(cmd: list[str], timeout: int = 12) -> tuple[int, str]:
import subprocess
try:
p = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout, check=False)
return int(p.returncode), ((p.stdout or "") + (p.stderr or "")).strip()
except Exception as exc:
return 1, str(exc)
def _unit_active(name: str) -> str:
code, out = _run(["systemctl", "is-active", name], timeout=5)
return (out.splitlines()[0] if out else ("inactive" if code else "unknown")).strip()
def path_roles() -> dict[str, Any]:
"""Declare which transport is primary vs auxiliary."""
cn_up = Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False
wg_target = "10.9.0.2(wg-dy-cn 国内优先)" if cn_up else "10.8.0.2(wg-dy 海外)"
return {
"app_https": {
"primary": "wireguard",
"detail": f"VPS Caddy → WG {wg_target}:4015/8014;wg-dy 海外链路保留作备份",
},
"ops_ssh": {
"primary": "wireguard",
"auxiliary": "frp",
"detail": "优先 WG(wg-dy-cn → 10.9.0.1 或 wg-dy → 10.8.0.1);FRP :4014 仅应急",
},
"policy": "wg_cn_primary_wg_us_backup_frp_aux",
}
def frp_status() -> dict[str, Any]:
"""FRP is auxiliary — SSH/ops fallback only; do not carry app reverse_proxy."""
unit = None
for name in ("frpp", "frpc", "frp-panel"):
st = _unit_active(name)
if st in {"active", "activating"}:
unit = {"name": name, "state": st}
break
if unit is None and st not in {"inactive", "unknown", ""}:
unit = {"name": name, "state": st}
code, ps = _run(["bash", "-lc", "ps aux | grep -E '[f]rpc|[f]rpp|[f]rp-panel' | head -5"], timeout=8)
procs = [ln.strip() for ln in (ps or "").splitlines() if ln.strip()]
# Detect common SSH tunnel port hint
ports: list[int] = []
for ln in procs:
for m in re.finditer(r":(\d{2,5})\b", ln):
try:
ports.append(int(m.group(1)))
except ValueError:
pass
return {
"ok": True,
"role": "auxiliary",
"purpose": "ops_ssh_emergency",
"unit": unit,
"processes": procs[:5],
"hint_ports": sorted(set(ports))[:8],
"detail": "辅路径:仅应急 SSH/运维(如 VPS:4014→guest:22)。应用 HTTPS 必须走 WireGuard,勿把业务反代挂到 FRP。",
}
def socks_status() -> dict[str, Any]:
from . import db
cfg = db.get_settings_map()
enabled = global_socks.is_global_socks_enabled(cfg)
profiles = global_socks.list_socks_profiles(cfg, public=True)
active_id = global_socks.active_profile_id(cfg)
from . import singbox_manager
return {
"ok": True,
"enabled": enabled,
"active_profile_id": active_id,
"profiles": profiles,
"local_mixed": global_socks.local_mixed_url() if enabled else "",
"singbox_running": bool(singbox_manager.is_running()) if enabled else False,
"unit": "douyinweb-singbox",
"v2ray_agent": singbox_manager.host_v2ray_agent_status(),
"hint": "美国 VPS:填 SOCKS 后开「静态住宅 IP」;永不重启宿主机 sing-box.service",
}
def _deploy_shape_hint() -> str:
if Path("/etc/wireguard/wg-dy.conf").is_file() or any(
p.name == "wg-dy" for p in Path("/sys/class/net").iterdir() if Path("/sys/class/net").is_dir()
):
return "physical_or_wg"
return "colocated_or_unknown"
def _wg_handshake_age_sec() -> int | None:
"""Seconds since latest handshake on primary WG iface (wg-dy-cn preferred)."""
for iface in ("wg-dy-cn", "wg-dy"):
code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5)
if code != 0 or not out.strip():
continue
parts = out.split()
if len(parts) < 2:
continue
try:
ts = int(parts[-1])
except ValueError:
continue
if ts <= 0:
continue
return max(0, int(time.time()) - ts)
return None
_ping_wg_cache: tuple[float, dict[str, Any]] | None = None
_PING_WG_CACHE_TTL_SEC = 15.0
def _ping_wg_peer() -> dict[str, Any]:
global _ping_wg_cache
import time as _time
now = _time.time()
if _ping_wg_cache is not None:
cached_at, cached = _ping_wg_cache
if now - cached_at < _PING_WG_CACHE_TTL_SEC:
return dict(cached)
if Path("/sys/class/net/wg-dy-cn").exists() if Path("/sys/class/net").is_dir() else False:
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
else:
peer = str(os.environ.get("DY_WG_PEER_IP") or "10.8.0.1").strip() or "10.8.0.1"
code, out = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
ok = code == 0 and "1 received" in out.replace("packets ", "")
if not ok:
ok = code == 0 and ("bytes from" in out or "ttl=" in out.lower())
rtt = ""
m = re.search(r"time[=<]([0-9.]+)\s*ms", out)
if m:
rtt = m.group(1) + "ms"
result = {"ok": ok, "peer": peer, "rtt": rtt, "detail": (out.splitlines()[-1] if out else "")[:120]}
_ping_wg_cache = (now, result)
return dict(result)
def wireguard_watch_status() -> dict[str, Any]:
unit = _unit_active("douyinweb-wireguard-watch")
path = Path("/opt/douyinWEB/scripts/linux/wireguard_watch.sh")
return {
"unit": unit,
"installed": path.is_file(),
"path": str(path) if path.is_file() else "",
"hint": "stale handshake 自动重启 wg-dy-cn / wg-dy(主路径保活)",
}
def network_overview() -> dict[str, Any]:
wg = wireguard_hub.runtime_status()
age = _wg_handshake_age_sec()
ping = _ping_wg_peer()
wg["role"] = "primary"
wg["purpose"] = "app_https_and_ops_ssh"
wg["handshake_age_sec"] = age
wg["handshake_fresh"] = age is not None and age < 180
wg["peer_ping"] = ping
wg["watch"] = wireguard_watch_status()
if age is not None and age >= 300:
wg.setdefault("recommendations", []).append(
f"握手已 {age}s 未刷新 — watch 应重启 wg-dy;勿改用 FRP 扛业务"
)
frp = frp_status()
from . import egress_hub
# One ShellCrash status for this request (status() itself is also TTL-cached).
sc = shellcrash_hub.status()
return {
"ok": True,
"path_roles": path_roles(),
"wireguard": wg,
"frp": frp,
"shellcrash": sc,
"socks": socks_status(),
"egress": egress_hub.status(),
"deploy_shape": _deploy_shape_hint(),
"physical_checklist": physical_checklist(wg=wg, frp=frp, shellcrash=sc),
}
def physical_checklist(
*,
wg: dict[str, Any] | None = None,
frp: dict[str, Any] | None = None,
shellcrash: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Operator checklist — WireGuard primary, FRP auxiliary."""
checks: list[dict[str, Any]] = []
def add(name: str, ok: bool, detail: str = "") -> None:
checks.append({"name": name, "ok": bool(ok), "detail": detail})
pub = str(os.environ.get("DY_PUBLIC_BASE_URL") or "").strip()
add(
"public_base_url",
pub.startswith("https://") and "127.0.0.1" not in pub and not pub.startswith("http://10."),
pub or "missing DY_PUBLIC_BASE_URL",
)
bind = str(os.environ.get("DY_NEKO_HTTP_BIND") or "127.0.0.1").strip()
shape = _deploy_shape_hint()
if shape.startswith("physical"):
add("neko_http_bind", bind in {"0.0.0.0", "*"}, f"DY_NEKO_HTTP_BIND={bind} (physical needs 0.0.0.0)")
else:
add("neko_http_bind", True, f"DY_NEKO_HTTP_BIND={bind}")
docker_ok = bool(shutil.which("docker"))
add("docker", docker_ok, "docker binary" if docker_ok else "missing")
seed = Path(__file__).resolve().parent.parent / "neko" / "tampermonkey-seed" / "Default" / "Extensions"
add("neko_seed", seed.is_dir(), str(seed))
wg_up = Path("/sys/class/net/wg-dy").exists() if Path("/sys/class/net").is_dir() else False
add("wg_primary_link", wg_up or shape != "physical_or_wg", "wg-dy iface (主路径)" if wg_up else "no wg-dy")
wg = wg or {}
age = wg.get("handshake_age_sec")
if isinstance(age, int):
add("wg_handshake", age < 300, f"age={age}s (主路径保活)")
elif wg_up:
add("wg_handshake", False, "无法读取 handshake")
ping = wg.get("peer_ping") if isinstance(wg.get("peer_ping"), dict) else {}
if ping:
add("wg_peer_ping", bool(ping.get("ok")), f"{ping.get('peer')} {ping.get('rtt') or ''}".strip())
watch = wg.get("watch") if isinstance(wg.get("watch"), dict) else {}
if shape.startswith("physical"):
add(
"wg_watch",
watch.get("unit") == "active",
f"unit={watch.get('unit') or 'missing'} — douyinweb-wireguard-watch 保活主路径",
)
frp = frp or {}
frp_unit = (frp.get("unit") or {}) if isinstance(frp.get("unit"), dict) else {}
add(
"frp_aux_ssh",
True,
f"role=auxiliary state={frp_unit.get('state') or 'n/a'} — 仅应急 SSH,不扛业务",
)
sc = shellcrash if isinstance(shellcrash, dict) else shellcrash_hub.status()
if shape.startswith("physical"):
add(
"shellcrash",
bool(sc.get("installed")) and bool(sc.get("running")),
f"installed={sc.get('installed')} unit={sc.get('unit')} mixed=:{sc.get('mixed_port') or '?'}",
)
failed = sum(1 for c in checks if not c["ok"])
return {
"ok": failed == 0,
"failed": failed,
"checks": checks,
"deploy_shape": shape,
"policy": "wg_primary_frp_aux",
}

View File

@ -73,7 +73,7 @@ async def check_and_alert() -> dict[str, Any]:
metrics = collect_metrics()
fired: list[str] = []
if cfg.get("ops_alert_disk_enabled", False):
if cfg.get("ops_alert_disk_enabled", True):
try:
min_free = float(cfg.get("clips_min_free_gb") or 12)
except Exception:
@ -127,6 +127,12 @@ async def alert_loop() -> None:
while True:
try:
cfg = db.get_settings_map()
# Always reclaim under pressure (alert webhook remains optional).
try:
from .disk_guard import reclaim_once
reclaim_once(cfg)
except Exception:
pass
if cfg.get("ops_alerts_enabled", False):
await check_and_alert()
try:

View File

@ -50,24 +50,52 @@ _oauth_states: dict[str, tuple[str, float, str, str] | tuple[str, float, str, st
_OAUTH_STATE_KEY = "shorts_oauth_pending_states"
_OAUTH_STATE_TTL_SEC = 1800.0 # 30min — Google consent + brand pick can be slow
def _persist_oauth_states() -> None:
"""Survive API restarts between Google consent and callback."""
now = time.time()
payload: dict[str, list[Any]] = {}
# Merge with DB so another worker's pending states are not wiped.
try:
db._invalidate_settings_cache()
except Exception:
pass
try:
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
except Exception:
raw = {}
merged: dict[str, list[Any]] = {}
if isinstance(raw, dict):
for k, packed in raw.items():
if not isinstance(packed, (list, tuple)) or len(packed) < 4:
continue
try:
exp = float(packed[1])
except Exception:
continue
if exp < now:
continue
merged[str(k)] = list(packed)
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or float(packed[1]) < now:
_oauth_states.pop(k, None)
continue
payload[k] = list(packed)
merged[str(k)] = list(packed)
_oauth_states[str(k)] = packed
try:
db.update_settings_map({_OAUTH_STATE_KEY: payload})
db.update_settings_map({_OAUTH_STATE_KEY: merged})
except Exception:
pass
def _hydrate_oauth_states() -> None:
if _oauth_states:
return
def _hydrate_oauth_states(*, force: bool = False) -> None:
"""Load pending states from DB. Always merge — never skip when memory is non-empty."""
try:
if force:
db._invalidate_settings_cache()
except Exception:
pass
try:
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
except Exception:
@ -84,8 +112,11 @@ def _hydrate_oauth_states() -> None:
continue
if exp < now:
continue
key = str(k)
if (not force) and key in _oauth_states:
continue
if len(packed) >= 5:
_oauth_states[str(k)] = (
_oauth_states[key] = (
str(packed[0]),
exp,
str(packed[2]),
@ -93,7 +124,29 @@ def _hydrate_oauth_states() -> None:
str(packed[4] or ""),
)
else:
_oauth_states[str(k)] = (str(packed[0]), exp, str(packed[2]), str(packed[3]))
_oauth_states[key] = (str(packed[0]), exp, str(packed[2]), str(packed[3]))
def _pop_oauth_state(state: str) -> tuple | None:
"""Pop state from memory+DB (force hydrate first — fixes multi-worker / restart)."""
st = str(state or "").strip()
if not st:
return None
_hydrate_oauth_states(force=True)
packed = _oauth_states.pop(st, None)
if packed is None:
# One more direct DB peek in case cache raced
try:
db._invalidate_settings_cache()
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
if isinstance(raw, dict) and st in raw:
row = raw.get(st)
if isinstance(row, (list, tuple)) and len(row) >= 4:
packed = tuple(row[:5] if len(row) >= 5 else row[:4]) # type: ignore[assignment]
except Exception:
packed = None
_persist_oauth_states()
return packed # type: ignore[return-value]
def _stamp_oauth_error(channel_pk: str, err: str) -> None:
@ -120,13 +173,28 @@ def _oauth_log(msg: str) -> None:
def _google_http_proxy() -> str:
"""Google APIs must egress via ShellCrash on China physical hosts."""
"""Google API egress proxy.
- Prefer egress_hub (China physical / ShellCrash).
- Else use local clash :7890 only if it accepts connections.
- Else direct (overseas VPS / ytshort). Never force a dead 7890.
"""
try:
from . import egress_hub
return egress_hub.google_http_proxy()
p = str(egress_hub.google_http_proxy() or "").strip()
if p:
return p
except Exception:
pass
try:
import socket
s = socket.create_connection(("127.0.0.1", 7890), timeout=0.2)
s.close()
return "http://127.0.0.1:7890"
except Exception:
return ""
def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
@ -142,6 +210,38 @@ def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
return kw
def _find_shorts_by_youtube_id(yt_id: str) -> dict[str, Any] | None:
yt = str(yt_id or "").strip()
if not yt:
return None
for ch in db.list_shorts_channels(enabled=None) or []:
if str(ch.get("youtube_channel_id") or "").strip() == yt:
return ch
return None
def _dedupe_shorts_channel_by_youtube_id(prefer_pk: str, yt_id: str) -> str:
"""Warn-only: never delete cards during/after OAuth (operator data loss)."""
yt_id = str(yt_id or "").strip()
prefer_pk = str(prefer_pk or "").strip()
if not yt_id:
return ""
rows = [
ch
for ch in (db.list_shorts_channels(enabled=None) or [])
if str(ch.get("youtube_channel_id") or "").strip() == yt_id
]
if len(rows) < 2:
return ""
others = [str(r.get("name") or r.get("id") or "") for r in rows if str(r.get("id") or "") != prefer_pk]
if not others:
return ""
return (
f"注意:YouTube 频道 {yt_id} 仍挂在多张卡上({', '.join(others[:3])})。"
"未自动删除任何卡片,请手动删掉重复卡。"
)
def _cfg() -> dict[str, Any]:
return db.get_settings_map()
@ -398,16 +498,21 @@ def build_authorize_url(
if ret and (not ret.startswith("/") or ret.startswith("//")):
ret = ""
now = time.time()
# Drop expired + any prior pending state for this same card (double-click / double-fetch).
# Drop expired + older pending states for this same card (double-click / React remount).
for k, packed in list(_oauth_states.items()):
if len(packed) < 2 or packed[1] < now or str(packed[0]) == str(channel_pk):
if len(packed) < 2 or packed[1] < now:
_oauth_states.pop(k, None)
continue
if str(packed[0]) == str(channel_pk):
_oauth_states.pop(k, None)
state = secrets.token_urlsafe(24)
exp = now + _OAUTH_STATE_TTL_SEC
if ret:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret, ret)
_oauth_states[state] = (channel_pk, exp, client_id, client_secret, ret)
else:
_oauth_states[state] = (channel_pk, now + 600, client_id, client_secret)
_oauth_states[state] = (channel_pk, exp, client_id, client_secret)
_persist_oauth_states()
_oauth_log(f"authorize_start pk={channel_pk} state={state[:10]} exp={int(exp)}")
scope = authorize_scopes(include_monetary=bool(include_monetary))
params = {
"client_id": client_id,
@ -445,21 +550,48 @@ def authorize_scopes(*, include_monetary: bool = False) -> str:
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
async def token_scopes(access_token: str) -> set[str]:
"""Granted scopes on an access token (tokeninfo)."""
async def token_scopes(access_token: str) -> set[str] | None:
"""Granted scopes on an access token (tokeninfo).
Returns None when egress/network failed — callers must NOT treat that as
「缺 force-ssl」(empty set used to false-flag OAuth 异常).
"""
if not access_token:
return set()
last_err = ""
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
resp = await client.get(
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
)
data = resp.json() if resp.content else {}
raw = str(data.get("scope") or "")
return {s for s in raw.split() if s.strip()}
from . import egress_hub
proxies = egress_hub.google_http_proxy_candidates()
except Exception:
return set()
proxies = [str((_google_http_proxy() or "")).strip()]
if "" not in proxies:
proxies.append("")
for proxy in proxies:
try:
try:
from . import egress_hub
kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=10.0 if proxy else 20.0)
except Exception:
kw = _google_client_kwargs(timeout=10.0 if proxy else 20.0)
if proxy:
kw = {**kw, "proxy": proxy}
elif "proxy" in kw:
kw = {k: v for k, v in kw.items() if k != "proxy"}
async with httpx.AsyncClient(**kw) as client:
resp = await client.get(
"https://oauth2.googleapis.com/tokeninfo",
params={"access_token": access_token},
)
data = resp.json() if resp.content else {}
raw = str(data.get("scope") or "")
return {s for s in raw.split() if s.strip()}
except Exception as exc:
last_err = f"{type(exc).__name__}: {exc}"[:160]
continue
_oauth_log(f"token_scopes_fail {last_err}")
return None
def missing_required_scopes(granted: set[str]) -> list[str]:
@ -485,21 +617,17 @@ async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", clien
async def prepare_reauthorize(channel_pk: str) -> None:
"""Soft-mark OAuth start on the clicked card — never revoke sibling brands."""
"""Mark OAuth start time only — do not stamp oauth_error (that looks like a failure)."""
ch = db.get_shorts_channel(channel_pk) or {}
if not ch:
return
db.update_shorts_channel(
channel_pk,
oauth_checked_at=time.time(),
oauth_error="授权中:完成 Google 后凭证写入本卡片",
)
# Keep existing oauth_ok / oauth_error so the board does not flash「OAuth 异常」
# while the operator is mid-consent on Google.
db.update_shorts_channel(channel_pk, oauth_checked_at=time.time())
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
_hydrate_oauth_states()
packed = _oauth_states.pop(state, None)
_persist_oauth_states()
packed = _pop_oauth_state(state)
if not packed:
_oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}")
raise ValueError("授权 state 无效或已过期,请重新点击授权")
@ -509,7 +637,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
return_to = str(packed[4]).strip() if len(packed) >= 5 else ""
if return_to and (not return_to.startswith("/") or return_to.startswith("//")):
return_to = ""
if exp < time.time():
if float(exp) < time.time():
_stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权")
raise ValueError("授权已过期,请重新点击授权")
cfg = _cfg()
@ -535,6 +663,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
f"exchange pk={channel_pk} redirect={redirect_uri} "
f"secret_tail={client_secret[-4:]} proxy={proxy or 'direct'}"
)
yt_id = ""
yt_title = ""
yt_handle = ""
google_email = ""
access = ""
refresh = ""
expected_uc = str(channel.get("youtube_channel_id") or "").strip()
expected_name = str(channel.get("name") or "").strip()
mismatch_warn = ""
dup_warn = ""
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) as client:
token_resp = await client.post(
@ -588,7 +726,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
items = ch_data.get("items") or []
# Prefer the brand that already matches this card's UC (multi-brand Google logins).
# Card name ≠ brand title. Prefer UC match in token list; else authorized brand (items[0]).
expected_uc = str(channel.get("youtube_channel_id") or "").strip()
expected_name = str(channel.get("name") or "").strip()
chosen: dict[str, Any] | None = None
@ -617,66 +755,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
# Hard lock: re-auth must not rewrite this card into another brand.
# (Previously we overwrote youtube_channel_id + name → duplicate 「nomad Street Food」.)
if expected_uc and yt_id != expected_uc:
err = (
f"授权选中的 YouTube 频道是「{yt_title or yt_id}」({yt_id}),"
f"但本卡绑定的是「{expected_name or expected_uc}」({expected_uc})。"
"凭证未写入。请重新点授权,在 Google 账号/品牌列表里选对本卡的频道。"
)
_stamp_oauth_error(channel_pk, err)
# Best-effort revoke the wrong-brand grant so it does not linger.
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=15.0)) as client:
await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": access},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
if refresh:
await client.post(
"https://oauth2.googleapis.com/revoke",
data={"token": refresh},
headers={"Content-Type": "application/x-www-form-urlencoded"},
)
except Exception:
pass
raise ValueError(err)
google_email = await fetch_google_account_email(access)
# Soft-warn if the same YouTube channel is already bound to another Shorts card.
dup_warn = ""
if yt_id:
try:
for other in db.list_shorts_channels(enabled=None):
oid = str(other.get("id") or "")
if oid == channel_pk:
continue
if str(other.get("youtube_channel_id") or "").strip() == yt_id:
dup_warn = (
f"注意:YouTube 频道 {yt_id} 已挂在另一张卡 "
f"「{other.get('name') or oid}」。两张卡会共用同一频道身份,建议删掉重复卡。"
)
try:
db.add_event(
kind="ops",
level="warn",
message=dup_warn,
meta={"channel_pk": channel_pk, "dup_channel_pk": oid, "youtube_channel_id": yt_id},
)
except Exception:
pass
break
except Exception:
pass
# Resolve target card by authorized brand UC:
# exist → update that card; missing → create new card.
# Never delete the clicked card. Never wipe unrelated cards.
had_old = bool(str(channel.get("refresh_token") or "").strip())
if not refresh:
if had_old:
refresh = str(channel.get("refresh_token") or "").strip()
else:
# Revoke this access so the next consent can mint a refresh_token.
try:
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
await client.post(
@ -694,28 +782,133 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
_stamp_oauth_error(channel_pk, err)
raise ValueError(err)
click_pk = str(channel_pk)
click_name = str(channel.get("name") or click_pk)
existing = _find_shorts_by_youtube_id(yt_id) if yt_id else None
target_pk = click_pk
resolve_note = ""
created_new = False
removed_stub = False
def _is_empty_stub(ch: dict[str, Any]) -> bool:
return (
not str(ch.get("youtube_channel_id") or "").strip()
and not str(ch.get("refresh_token") or "").strip()
)
if existing and str(existing.get("id") or "") != click_pk:
target_pk = str(existing.get("id") or click_pk)
resolve_note = (
f"选中品牌「{yt_title or yt_id}」已有卡片「{existing.get('name') or target_pk}」,"
f"凭证已写入该卡。"
)
elif existing:
target_pk = str(existing.get("id") or click_pk)
resolve_note = ""
elif expected_uc and expected_uc != yt_id:
# Clicked card bound to another UC; brand is new → create.
try:
created = db.create_shorts_channel(
name=(yt_title or "Shorts Channel").strip() or "Shorts Channel",
youtube_channel_id=yt_id,
oauth_profile_id=profile_id or str(channel.get("oauth_profile_id") or ""),
enabled=True,
)
target_pk = str(created.get("id") or "")
created_new = True
resolve_note = (
f"选中品牌「{yt_title or yt_id}」原先没有卡片,已新建;"
f"你点的「{click_name}」保持原样。"
)
except ValueError as exc:
again = _find_shorts_by_youtube_id(yt_id)
if again:
target_pk = str(again.get("id") or click_pk)
resolve_note = (
f"选中品牌「{yt_title or yt_id}」已有卡片「{again.get('name') or target_pk}」,"
f"凭证已写入该卡({exc})。"
)
else:
raise
else:
# Clicked card empty UC or same UC → update clicked card in place.
target_pk = click_pk
if expected_uc and expected_uc != yt_id:
resolve_note = (
f"选中品牌「{yt_title or yt_id}」与原绑定不同,已更新本卡 UC"
"(卡片显示名不改成品牌名)。"
)
# Empty stub (no UC / no token) used only as authorize entry → remove after
# credentials land on the real brand card. Never delete cards that already have UC/tokens.
if target_pk != click_pk and _is_empty_stub(channel):
try:
db.delete_shorts_channel(click_pk)
removed_stub = True
resolve_note = (
f"{resolve_note} 已自动移除空壳卡「{click_name}」。".strip()
)
_oauth_log(f"removed_empty_stub click={click_pk} target={target_pk}")
except Exception as exc:
_oauth_log(f"remove_stub_fail click={click_pk} err={exc!r}")
try:
db.update_shorts_channel(
click_pk,
enabled=False,
oauth_ok=0,
oauth_error=f"空壳卡:授权已写入「{(existing or {}).get('name') or target_pk}」,可手动删除",
)
except Exception:
pass
elif target_pk != click_pk:
# Real card clicked but brand bound elsewhere — clear stuck「授权中」.
try:
db.update_shorts_channel(
click_pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error=(
f"本次授权写入了「{(db.get_shorts_channel(target_pk) or existing or {}).get('name') or target_pk}」,"
f"本卡「{click_name}」未改动。"
)[:500],
)
except Exception:
pass
patch: dict[str, Any] = {
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh,
"youtube_channel_id": yt_id,
}
# Only set UC when card had none; never swap to a different UC (guarded above).
if yt_id and not expected_uc:
patch["youtube_channel_id"] = yt_id
if google_email:
patch["oauth_email"] = google_email
# Keep operator card title on reauth — never auto-rename into another brand's title.
if yt_title and not expected_name:
patch["name"] = yt_title
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
if profile_id:
patch["oauth_profile_id"] = profile_id
# Never rename operator card into brand title on update — except empty / 未命名 stubs.
target_row = db.get_shorts_channel(target_pk) or {}
cur_name = str(target_row.get("name") or "").strip()
if (not created_new) and yt_title and (
not cur_name or cur_name in ("未命名频道", "Shorts Channel", "Shorts")
):
patch["name"] = yt_title
elif created_new and yt_title:
pass # create already named
# Success card: keep oauth_error clean (info goes to warning toast, not 「OAuth 异常」).
updated = db.update_shorts_channel(
channel_pk,
target_pk,
**patch,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
)
dup_warn = _dedupe_shorts_channel_by_youtube_id(target_pk, yt_id) if yt_id else ""
mismatch_warn = resolve_note
brand_mismatch = bool(resolve_note) and (
created_new or (existing is not None and str(existing.get("id") or "") != click_pk)
)
if google_email and profile_id:
try:
set_oauth_profile_email(profile_id, google_email)
@ -732,22 +925,29 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
try:
from . import youtube_manage as ytm
await ytm.fetch_channel_profile(channel_pk)
await ytm.fetch_channel_profile(target_pk)
except Exception as exc:
profile_err = str(exc).strip() or "拉取频道资料失败"
try:
from .yt_long_monetize import refresh_ypp_for_shorts_channel
ypp_r = await refresh_ypp_for_shorts_channel(channel_pk)
ypp_r = await refresh_ypp_for_shorts_channel(target_pk)
if not ypp_r.get("ok"):
ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200]
except Exception as exc:
ypp_err = str(exc).strip() or "YPP 探测失败"
note = " · ".join(x for x in (profile_err, ypp_err) if x)
if note:
db.update_shorts_channel(channel_pk, oauth_error=note)
updated = db.get_shorts_channel(channel_pk) or updated
_oauth_log(f"exchange_ok pk={channel_pk} yt={yt_id} title={yt_title} profile_err={profile_err!r} ypp_err={ypp_err!r}")
try:
db.update_shorts_channel(target_pk, oauth_error=note[:500])
updated = db.get_shorts_channel(target_pk) or updated
except Exception:
pass
_oauth_log(
f"exchange_ok click={click_pk} target={target_pk} created={created_new} "
f"removed_stub={removed_stub} yt={yt_id} title={yt_title} note={resolve_note!r}"
)
warn_out = " · ".join(x for x in (mismatch_warn, dup_warn) if x)
return {
"ok": True,
"channel": updated,
@ -762,7 +962,11 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
"ypp_ok": not bool(ypp_err),
"profile_error": profile_err,
"ypp_error": ypp_err,
"duplicate_channel_warning": dup_warn,
"brand_mismatch": brand_mismatch,
"created_channel": created_new,
"removed_empty_stub": removed_stub,
"target_channel_pk": target_pk,
"duplicate_channel_warning": warn_out,
"return_to": return_to,
}
except ValueError:
@ -807,7 +1011,13 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
missing = missing_required_scopes(await token_scopes(str(access)))
granted = await token_scopes(str(access))
if granted is None:
# Token refresh succeeded; scope check egress failed — do not false-flag.
err = "OAuth 出口不稳定:令牌可用但权限校验超时,请稍后重试或检查住宅代理"
db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error=err)
return {"ok": True, "channel_id": cid, "warning": err, "scopes_unchecked": True}
missing = missing_required_scopes(granted)
if missing:
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
@ -825,7 +1035,7 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non
db.update_shorts_channel(cid, **patch)
return {"ok": True, "channel_id": cid, "oauth_email": google_email}
except Exception as exc:
err = str(exc)[:240]
err = str(exc).strip()[:240] or f"{type(exc).__name__}: OAuth 探测失败"
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
return {"ok": False, "error": err, "channel_id": cid}

View File

@ -60,6 +60,16 @@ def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]:
return kw
def _proxy_candidates(proxy_url: str = "") -> list[str]:
try:
from . import egress_hub
return egress_hub.google_http_proxy_candidates(prefer=str(proxy_url or "").strip())
except Exception:
p = str(proxy_url or "").strip()
return [p] if p else [""]
async def refresh_access_token(
*,
client_id: str,
@ -69,20 +79,40 @@ async def refresh_access_token(
) -> str:
if not (client_id and client_secret and refresh_token):
raise ValueError("缺少 OAuth client_id / client_secret / refresh_token")
async with httpx.AsyncClient(**_client_kwargs(timeout=30.0, proxy_url=proxy_url)) as client:
resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
"grant_type": "refresh_token",
},
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400 or not data.get("access_token"):
raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}")
return str(data["access_token"])
last_transport = ""
for proxy in _proxy_candidates(proxy_url):
# Flaky residential: fail fast then fall back to VPS direct.
attempt_timeout = 12.0 if proxy else 30.0
try:
from . import egress_hub
kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=attempt_timeout)
except Exception:
kw = _client_kwargs(timeout=attempt_timeout, proxy_url=proxy)
try:
async with httpx.AsyncClient(**kw) as client:
resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
"client_id": client_id,
"client_secret": client_secret,
"refresh_token": refresh_token,
"grant_type": "refresh_token",
},
)
data = resp.json() if resp.content else {}
if resp.status_code >= 400 or not data.get("access_token"):
# Auth/config errors: do not fall through to another egress.
raise ValueError(
f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}"
)
return str(data["access_token"])
except ValueError:
raise
except Exception as exc:
last_transport = f"{type(exc).__name__}: {exc}"[:240]
continue
raise ValueError(f"OAuth 刷新失败(出口不可用): {last_transport or 'unknown'}")
async def upload_shorts_mp4(

View File

@ -1,5 +1,14 @@
# -*- coding: utf-8 -*-
"""sing-box local mixed inbound → remote SOCKS5 upstream."""
"""DouyinWEB-only sing-box: local mixed → residential SOCKS5.
HARD ISOLATION from v2ray-agent:
- Never systemctl start/stop/restart the host unit ``sing-box.service``
- Never read/write ``/etc/v2ray-agent/``
- Only manage ``douyinweb-singbox`` (systemd) or a subprocess with
``${APP}/config/sing-box.json`` mixed on :17891
- Listen ``0.0.0.0:17891`` so Neko ``host.docker.internal`` can reach it;
callers still use ``127.0.0.1`` URLs. Block eth0:17891 at the host firewall.
"""
from __future__ import annotations
import json
@ -21,18 +30,99 @@ from .global_socks import (
is_global_socks_enabled,
)
# Bind all interfaces so Docker Neko (host.docker.internal) can use residential.
# Host-side clients keep using LOCAL_MIXED_HOST (127.0.0.1) in URLs.
_MIXED_LISTEN_HOST = "0.0.0.0"
# App-owned unit only — NEVER bare "sing-box" (v2ray-agent).
UNIT_NAME = "douyinweb-singbox"
FORBIDDEN_UNITS = frozenset({"sing-box", "sing-box.service", "xray", "xray.service", "v2ray", "v2ray.service"})
V2RAY_AGENT_DIR = Path("/etc/v2ray-agent")
# Dedicated binary — NEVER use /etc/v2ray-agent/sing-box/sing-box
APP_BIN_DIR = BACKEND.parent / "bin"
APP_SINGBOX = APP_BIN_DIR / "sing-box"
# Pin a known-good release; install only into APP_BIN_DIR.
SINGBOX_VERSION = "1.11.15"
SINGBOX_ASSET = f"sing-box-{SINGBOX_VERSION}-linux-amd64.tar.gz"
SINGBOX_URL = f"https://github.com/SagerNet/sing-box/releases/download/v{SINGBOX_VERSION}/{SINGBOX_ASSET}"
_PID_FILE = CONFIG_DIR / "sing-box.pid"
_LOG_PATH = CONFIG_DIR / "sing-box.log"
def _assert_safe_unit(name: str) -> str:
raw = str(name or "").strip()
base = raw.removesuffix(".service")
if raw in FORBIDDEN_UNITS or base in FORBIDDEN_UNITS or base == "sing-box":
raise RuntimeError(f"refusing to touch host unit {raw!r} (v2ray-agent / edge)")
if base != UNIT_NAME and raw != UNIT_NAME:
raise RuntimeError(f"only {UNIT_NAME} is allowed, got {raw!r}")
return UNIT_NAME
def _assert_safe_binary(path: str) -> str:
"""Refuse any binary under v2ray-agent tree."""
p = Path(path).resolve()
try:
p.relative_to(V2RAY_AGENT_DIR.resolve())
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
except ValueError:
pass
if "v2ray-agent" in str(p):
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
return str(p)
def _find_binary() -> str:
for name in ("sing-box", "/usr/bin/sing-box", "/usr/local/bin/sing-box"):
p = shutil.which(name) if not name.startswith("/") else (name if Path(name).is_file() else None)
if p and Path(p).is_file():
return str(p)
"""Only DouyinWEB-owned paths — never PATH /usr/bin or v2ray-agent."""
candidates = [
APP_SINGBOX,
Path("/opt/douyinWEB/bin/sing-box"),
]
for cand in candidates:
if cand.is_file() and os.access(cand, os.X_OK):
try:
return _assert_safe_binary(str(cand))
except RuntimeError:
continue
return ""
def ensure_binary() -> str:
"""Install dedicated sing-box into /opt/douyinWEB/bin if missing."""
found = _find_binary()
if found:
return found
APP_BIN_DIR.mkdir(parents=True, exist_ok=True)
import tempfile
import urllib.request
tmp_dir = Path(tempfile.mkdtemp(prefix="dy-singbox-"))
try:
tgz = tmp_dir / SINGBOX_ASSET
urllib.request.urlretrieve(SINGBOX_URL, tgz) # noqa: S310
subprocess.run(
["tar", "-xzf", str(tgz), "-C", str(tmp_dir)],
check=True,
capture_output=True,
timeout=120,
)
# tarball contains sing-box-<ver>-linux-amd64/sing-box
extracted = next(tmp_dir.rglob("sing-box"), None)
if extracted is None or not extracted.is_file() or extracted.name != "sing-box":
# rglob may hit the dir; prefer the file
files = [p for p in tmp_dir.rglob("sing-box") if p.is_file()]
extracted = files[0] if files else None
if not extracted or not extracted.is_file():
raise RuntimeError("sing-box binary missing from release tarball")
dest = APP_SINGBOX
shutil.copy2(extracted, dest)
os.chmod(dest, 0o755)
return _assert_safe_binary(str(dest))
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
if not profile:
raise ValueError("SOCKS 配置无效")
@ -59,7 +149,7 @@ def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
{
"type": "mixed",
"tag": "mixed-in",
"listen": LOCAL_MIXED_HOST,
"listen": _MIXED_LISTEN_HOST,
"listen_port": LOCAL_MIXED_PORT,
"sniff": True,
}
@ -75,9 +165,92 @@ def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
}
def _force_mixed_listen_all_interfaces(cfg_dict: dict[str, Any]) -> dict[str, Any]:
"""Neko uses host.docker.internal → docker bridge IP; 127.0.0.1-only = ERR_PROXY."""
inbounds = list(cfg_dict.get("inbounds") or [])
fixed: list[dict[str, Any]] = []
for ib in inbounds:
if not isinstance(ib, dict):
continue
if ib.get("type") == "mixed" or ib.get("tag") == "mixed-in":
row = dict(ib)
row["type"] = "mixed"
row["tag"] = "mixed-in"
row["listen"] = _MIXED_LISTEN_HOST
row["listen_port"] = int(row.get("listen_port") or LOCAL_MIXED_PORT)
row.setdefault("sniff", True)
fixed.append(row)
if not fixed:
fixed = [
{
"type": "mixed",
"tag": "mixed-in",
"listen": _MIXED_LISTEN_HOST,
"listen_port": LOCAL_MIXED_PORT,
"sniff": True,
}
]
out = dict(cfg_dict)
out["inbounds"] = fixed[:1]
return out
def ensure_mixed_not_public() -> dict[str, Any]:
"""Block eth0 abuse of :17891 while keeping docker bridge reachability."""
comment = "douyinweb-res-no-public"
check = [
"iptables",
"-C",
"INPUT",
"-i",
"eth0",
"-p",
"tcp",
"--dport",
str(LOCAL_MIXED_PORT),
"-j",
"DROP",
]
insert = [
"iptables",
"-I",
"INPUT",
"-i",
"eth0",
"-p",
"tcp",
"--dport",
str(LOCAL_MIXED_PORT),
"-m",
"comment",
"--comment",
comment,
"-j",
"DROP",
]
try:
exists = subprocess.run(check, capture_output=True, timeout=5).returncode == 0
if not exists:
r = subprocess.run(insert, capture_output=True, text=True, timeout=5)
if r.returncode != 0:
return {"ok": False, "error": (r.stderr or r.stdout or "")[:200]}
return {"ok": True, "eth0_drop": True, "port": LOCAL_MIXED_PORT}
except Exception as exc:
return {"ok": False, "error": str(exc)[:200]}
def write_config(cfg_dict: dict[str, Any]) -> Path:
if V2RAY_AGENT_DIR in SINGBOX_CONFIG_PATH.parents or str(SINGBOX_CONFIG_PATH).startswith(
str(V2RAY_AGENT_DIR)
):
raise RuntimeError("refusing to write config under /etc/v2ray-agent")
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
cfg_dict = _force_mixed_listen_all_interfaces(cfg_dict)
SINGBOX_CONFIG_PATH.write_text(json.dumps(cfg_dict, ensure_ascii=False, indent=2), encoding="utf-8")
try:
os.chmod(SINGBOX_CONFIG_PATH, 0o600)
except Exception:
pass
return SINGBOX_CONFIG_PATH
@ -102,10 +275,9 @@ def is_running() -> bool:
pid = _read_pid()
if _pid_alive(pid):
return True
# systemd fallback
try:
r = subprocess.run(
["systemctl", "is-active", "douyinweb-singbox"],
["systemctl", "is-active", UNIT_NAME],
capture_output=True,
text=True,
timeout=5,
@ -116,25 +288,40 @@ def is_running() -> bool:
def stop() -> dict[str, Any]:
"""Stop DouyinWEB residential forwarder only — never host sing-box.service."""
pid = _read_pid()
if _pid_alive(pid):
try:
os.kill(pid, signal.SIGTERM)
time.sleep(0.8)
if _pid_alive(pid):
os.kill(pid, signal.SIGKILL)
except Exception:
pass
try:
subprocess.run(["systemctl", "stop", "douyinweb-singbox"], capture_output=True, timeout=15)
_assert_safe_unit(UNIT_NAME)
subprocess.run(["systemctl", "stop", UNIT_NAME], capture_output=True, timeout=15)
except Exception:
pass
_PID_FILE.unlink(missing_ok=True)
return {"ok": True, "running": False}
return {"ok": True, "running": False, "unit": UNIT_NAME}
def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
binary = _find_binary()
try:
binary = ensure_binary()
except Exception as exc:
return {
"ok": False,
"running": False,
"error": f"无法安装 DouyinWEB 专用 sing-box: {exc}",
}
if not binary:
return {"ok": False, "running": False, "error": "未安装 sing-box(apt install sing-box 或官方脚本)"}
return {
"ok": False,
"running": False,
"error": "未找到 DouyinWEB 专用 sing-box(应位于 /opt/douyinWEB/bin/sing-box,不使用 v2ray-agent)",
}
write_config(cfg_dict)
stop()
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
@ -159,8 +346,16 @@ def start_with_config(cfg_dict: dict[str, Any]) -> dict[str, Any]:
tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:]
except Exception:
pass
return {"ok": False, "running": False, "error": f"sing-box 启动失败: {tail}"}
return {"ok": True, "running": True, "pid": proc.pid, "binary": binary}
return {"ok": False, "running": False, "error": f"douyinweb-singbox 启动失败: {tail}"}
return {
"ok": True,
"running": True,
"pid": proc.pid,
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
}
def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
@ -169,21 +364,32 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
settings = _settings_dict(cfg)
if not is_global_socks_enabled(settings):
stop()
return {"ok": True, "running": False, "enabled": False}
return {"ok": True, "running": False, "enabled": False, "unit": UNIT_NAME}
prof = active_profile(settings)
if not prof:
stop()
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置"}
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置", "unit": UNIT_NAME}
try:
cfg_dict = build_config(prof)
except ValueError as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc)}
# Prefer systemd unit when present.
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
write_config(cfg_dict)
fw = ensure_mixed_not_public()
try:
ensure_binary()
except Exception as exc:
stop()
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
# Rewrite unit ExecStart to app-owned binary (never /usr/bin or v2ray-agent).
try:
_install_unit_file()
except Exception:
pass
try:
_assert_safe_unit(UNIT_NAME)
r = subprocess.run(
["systemctl", "restart", "douyinweb-singbox"],
["systemctl", "restart", UNIT_NAME],
capture_output=True,
text=True,
timeout=20,
@ -191,10 +397,72 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
if r.returncode == 0:
time.sleep(0.5)
if is_running():
return {"ok": True, "running": True, "enabled": True, "via": "systemd"}
return {
"ok": True,
"running": True,
"enabled": True,
"via": "systemd",
"unit": UNIT_NAME,
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"listen": _MIXED_LISTEN_HOST,
"firewall": fw,
}
except Exception:
pass
return {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
out = {**start_with_config(cfg_dict), "enabled": True, "via": "subprocess"}
out["firewall"] = fw
out["listen"] = _MIXED_LISTEN_HOST
return out
def host_v2ray_agent_status() -> dict[str, Any]:
"""Read-only peek at v2ray-agent edge (never mutate)."""
active = ""
try:
r = subprocess.run(
["systemctl", "is-active", "sing-box"],
capture_output=True,
text=True,
timeout=5,
)
active = (r.stdout or "").strip()
except Exception as exc:
active = f"error:{exc}"
return {
"unit": "sing-box.service",
"active": active,
"config_dir_exists": V2RAY_AGENT_DIR.is_dir(),
"note": "read-only; DouyinWEB never restarts this unit",
}
def _install_unit_file() -> None:
binary = ensure_binary()
unit = f"""[Unit]
Description=DouyinWEB residential SOCKS forwarder (isolated from v2ray-agent)
Documentation=file:/opt/douyinWEB/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
WorkingDirectory=/opt/douyinWEB/backend
ExecStart={binary} run -c /opt/douyinWEB/config/sing-box.json
Restart=on-failure
RestartSec=3
Nice=5
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
ReadOnlyPaths=/etc/v2ray-agent
[Install]
WantedBy=multi-user.target
"""
path = Path(f"/etc/systemd/system/{UNIT_NAME}.service")
path.write_text(unit, encoding="utf-8")
subprocess.run(["systemctl", "daemon-reload"], capture_output=True, timeout=15)
def status() -> dict[str, Any]:
@ -206,5 +474,12 @@ def status() -> dict[str, Any]:
"binary": binary,
"config": str(SINGBOX_CONFIG_PATH),
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
"unit": UNIT_NAME,
"v2ray_agent": host_v2ray_agent_status(),
"isolation": {
"app_bin": str(APP_SINGBOX),
"never_uses": str(V2RAY_AGENT_DIR),
"never_restarts": "sing-box.service",
},
"error": "",
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,337 +1,337 @@
# -*- coding: utf-8 -*-
"""TikTok cookie session — TiktokAutoUploader style, no developer OAuth."""
from __future__ import annotations
import os
import pickle
import sys
import time
from pathlib import Path
from typing import Any
from . import db
from . import tiktok_db
_VENDOR_ROOT = Path(__file__).resolve().parent.parent / "third_party" / "TiktokAutoUploader"
if str(_VENDOR_ROOT) not in sys.path:
sys.path.insert(0, str(_VENDOR_ROOT))
DEFAULT_DC = "useast2a"
COOKIE_TTL_DAYS = 30.0
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
_DC_CANDIDATES = ("useast5a", "useast1a", "useast2a", "euwest1a", "alisg", "no1a", "useast8")
_PROBE_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
def cookies_dir() -> Path:
raw = str(db.get_settings_map().get("tiktok_cookies_dir") or "").strip()
if raw:
p = Path(raw)
else:
p = Path(__file__).resolve().parent.parent / "data" / "tiktok_cookies"
p.mkdir(parents=True, exist_ok=True)
return p
def session_filename(channel_pk: str) -> str:
return f"tiktok_session-{channel_pk}"
def session_cookie_path(channel_pk: str) -> Path:
return cookies_dir() / f"{session_filename(channel_pk)}.cookie"
def _normalize_cookie(raw: dict[str, Any]) -> dict[str, Any]:
c = dict(raw)
if c.get("sameSite") == "None":
c["sameSite"] = "Strict"
return c
def load_session_cookies(channel_pk: str) -> list[dict[str, Any]]:
path = session_cookie_path(channel_pk)
if not path.is_file():
return []
try:
data = pickle.load(path.open("rb"))
except Exception:
return []
if not isinstance(data, list):
return []
out: list[dict[str, Any]] = []
for item in data:
if isinstance(item, dict) and item.get("name"):
out.append(_normalize_cookie(item))
return out
def save_session_cookies(channel_pk: str, cookies: list[dict[str, Any]]) -> None:
path = session_cookie_path(channel_pk)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as f:
pickle.dump([_normalize_cookie(c) for c in cookies if c.get("name")], f)
def delete_session_cookies(channel_pk: str) -> None:
path = session_cookie_path(channel_pk)
if path.is_file():
path.unlink()
def save_session_from_values(
channel_pk: str,
*,
sessionid: str,
dc_id: str = "",
username: str = "",
) -> dict[str, Any]:
sid = str(sessionid or "").strip()
if not sid:
raise ValueError("sessionid 不能为空")
dc = str(dc_id or "").strip()
if not dc:
dc = detect_working_datacenter(sid)
cookies = [
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": dc, "domain": ".tiktok.com", "path": "/"},
]
save_session_cookies(channel_pk, cookies)
now = time.time()
patch: dict[str, Any] = {
"oauth_ok": 1,
"oauth_checked_at": now,
"oauth_error": "",
"refresh_token": "cookie",
"cookie_saved_at": now,
}
if username.strip():
patch["tiktok_username"] = username.strip()
updated = tiktok_db.update_tiktok_channel(channel_pk, **patch) or {}
try:
from . import tiktok_profile
refreshed = tiktok_profile.fetch_profile_for_channel(
channel_pk,
username_hint=str(username or patch.get("tiktok_username") or ""),
)
if isinstance(refreshed, dict) and refreshed.get("channel"):
updated = refreshed["channel"]
except Exception as exc:
try:
tiktok_db.update_tiktok_channel(channel_pk, profile_error=str(exc)[:240])
updated = tiktok_db.get_tiktok_channel(channel_pk) or updated
except Exception:
pass
return updated
def channel_has_session(channel: dict[str, Any] | None) -> bool:
if not channel:
return False
pk = str(channel.get("id") or "")
if not pk:
return False
cookies = load_session_cookies(pk)
names = {str(c.get("name") or "") for c in cookies}
return "sessionid" in names and bool(next((c.get("value") for c in cookies if c.get("name") == "sessionid"), ""))
def cookie_age_info(channel: dict[str, Any] | None, *, persist_backfill: bool = False) -> dict[str, Any]:
"""Days since this account's Cookie was pasted. Probe/DC rewrite must not reset the clock."""
ch = channel or {}
pk = str(ch.get("id") or "")
has = channel_has_session(ch) if pk else False
saved = float(ch.get("cookie_saved_at") or 0)
if has and saved <= 0 and pk:
path = session_cookie_path(pk)
if path.is_file():
saved = float(path.stat().st_mtime)
if persist_backfill:
tiktok_db.update_tiktok_channel(pk, cookie_saved_at=saved)
if not has or saved <= 0:
return {
"cookie_saved_at": 0.0,
"cookie_age_days": None,
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": None,
"cookie_status": "missing",
}
age_days = max(0.0, (time.time() - saved) / 86400.0)
left_days = COOKIE_TTL_DAYS - age_days
if left_days <= 0:
status = "expired"
elif left_days <= 5:
status = "warn"
else:
status = "ok"
return {
"cookie_saved_at": saved,
"cookie_age_days": round(age_days, 1),
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": round(max(0.0, left_days), 1),
"cookie_status": status,
}
def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]:
ch = channel or {}
pk = str(ch.get("id") or "")
if not pk:
return {"ok": False, "error": "账号不存在"}
if channel_has_session(ch):
tiktok_db.update_tiktok_channel(
pk,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
refresh_token="cookie",
)
try:
from . import tiktok_profile
tiktok_profile.refresh_profile_if_stale(pk, force=False)
except Exception:
pass
return {"ok": True, "channel_pk": pk, "mode": "cookie"}
tiktok_db.update_tiktok_channel(
pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error="未配置 Cookie 会话",
refresh_token="",
)
return {"ok": False, "channel_pk": pk, "error": "未配置 Cookie 会话"}
def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
channels = tiktok_db.list_tiktok_channels()
ready = [c for c in channels if channel_has_session(c)]
vendor_ok = _VENDOR_ROOT.is_dir() and (_VENDOR_ROOT / "tiktok_uploader" / "tiktok.py").is_file()
sig_js = _VENDOR_ROOT / "tiktok_uploader" / "tiktok-signature" / "browser.js"
node_ok = bool(os.environ.get("NODE_PATH") or _which("node"))
return {
"mode": "cookie",
"vendor_ready": vendor_ok,
"signature_ready": sig_js.is_file(),
"node_available": node_ok,
"cookies_dir": str(cookies_dir()),
"steps": [
{
"id": "browser_login",
"title": "浏览器登录 tiktok.com,导出 sessionid(及 tt-target-idc)",
"url": "https://www.tiktok.com",
"done": len(ready) > 0,
},
{
"id": "paste_cookie",
"title": "在 TikTok 页为每个账号粘贴 Cookie / sessionid",
"done": len(ready) > 0,
},
{
"id": "account",
"title": "添加 TikTok 账号并完成 Cookie 授权",
"done": len(channels) > 0 and len(ready) == len(channels),
},
],
"note": (
"使用 TiktokAutoUploader Cookie 方案,无需 TikTok 开发者应用。"
" sessionid 等同账号密码,请勿泄露;约 30 天过期需重新粘贴。"
),
"note_unaudited": "",
}
def _which(name: str) -> str | None:
from shutil import which
return which(name)
def probe_project_create(sessionid: str, dc_id: str) -> dict[str, Any]:
"""Hit TikTok project/create to see if this sessionid + datacenter works."""
import secrets
import string
import requests
sid = str(sessionid or "").strip()
dc = str(dc_id or "").strip()
if not sid or not dc:
return {"ok": False, "dc_id": dc, "error": "缺少 sessionid 或机房"}
sess = requests.Session()
sess.cookies.set("sessionid", sid, domain=".tiktok.com")
sess.cookies.set("sessionid_ss", sid, domain=".tiktok.com")
sess.cookies.set("tt-target-idc", dc, domain=".tiktok.com")
sess.headers.update({"User-Agent": _PROBE_UA, "Accept": "application/json, text/plain, */*"})
cid = "".join(secrets.choice(string.ascii_letters + string.digits + "_") for _ in range(21))
url = f"https://www.tiktok.com/api/v1/web/project/create/?creation_id={cid}&type=1&aid=1988"
try:
r = sess.post(url, timeout=20)
payload = r.json()
except Exception as exc:
return {"ok": False, "dc_id": dc, "error": str(exc)[:160]}
project = payload.get("project") if isinstance(payload, dict) else None
ok = isinstance(project, dict) and bool(project.get("project_id"))
return {
"ok": ok,
"dc_id": dc,
"status_code": payload.get("status_code") if isinstance(payload, dict) else None,
"status_msg": str((payload or {}).get("status_msg") or "")[:160],
}
def detect_working_datacenter(sessionid: str, preferred: str = "") -> str:
order: list[str] = []
pref = str(preferred or "").strip()
if pref:
order.append(pref)
for item in _DC_CANDIDATES:
if item not in order:
order.append(item)
last: dict[str, Any] = {}
for dc in order:
last = probe_project_create(sessionid, dc)
if last.get("ok"):
return dc
msg = str(last.get("status_msg") or last.get("error") or "").strip()
code = last.get("status_code")
hint = f"(status_code={code} {msg})" if code is not None or msg else ""
raise ValueError(
f"TikTok Cookie 无效或机房不匹配{hint}。请重新从已登录的 tiktok.com 复制 sessionid 和 tt-target-idc"
)
def ensure_working_datacenter(channel_pk: str) -> str:
cookies = load_session_cookies(channel_pk)
sid = next((str(c.get("value") or "") for c in cookies if c.get("name") == "sessionid"), "")
dc = next((str(c.get("value") or "") for c in cookies if c.get("name") == "tt-target-idc"), "")
if not sid:
raise ValueError("Cookie 缺少 sessionid")
working = detect_working_datacenter(sid, dc)
if working != dc:
save_session_cookies(
channel_pk,
[
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": working, "domain": ".tiktok.com", "path": "/"},
],
)
return working
def configure_vendor_paths() -> None:
"""Point vendored Config at our cookies directory."""
os.environ.setdefault("TIKTOK_VENDOR_ROOT", str(_VENDOR_ROOT))
try:
from tiktok_uploader.Config import Config
cfg = Config.get()
cfg._insert_option("COOKIES_DIR", str(cookies_dir()))
cfg._insert_option("VIDEOS_DIR", str(cookies_dir()))
except Exception:
pass
# -*- coding: utf-8 -*-
"""TikTok cookie session — TiktokAutoUploader style, no developer OAuth."""
from __future__ import annotations
import os
import pickle
import sys
import time
from pathlib import Path
from typing import Any
from . import db
from . import tiktok_db
_VENDOR_ROOT = Path(__file__).resolve().parent.parent / "third_party" / "TiktokAutoUploader"
if str(_VENDOR_ROOT) not in sys.path:
sys.path.insert(0, str(_VENDOR_ROOT))
DEFAULT_DC = "useast2a"
COOKIE_TTL_DAYS = 30.0
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
_DC_CANDIDATES = ("useast5a", "useast5", "useast1a", "useast2a", "euwest1a", "alisg", "no1a", "useast8")
_PROBE_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
def cookies_dir() -> Path:
raw = str(db.get_settings_map().get("tiktok_cookies_dir") or "").strip()
if raw:
p = Path(raw)
else:
p = Path(__file__).resolve().parent.parent / "data" / "tiktok_cookies"
p.mkdir(parents=True, exist_ok=True)
return p
def session_filename(channel_pk: str) -> str:
return f"tiktok_session-{channel_pk}"
def session_cookie_path(channel_pk: str) -> Path:
return cookies_dir() / f"{session_filename(channel_pk)}.cookie"
def _normalize_cookie(raw: dict[str, Any]) -> dict[str, Any]:
c = dict(raw)
if c.get("sameSite") == "None":
c["sameSite"] = "Strict"
return c
def load_session_cookies(channel_pk: str) -> list[dict[str, Any]]:
path = session_cookie_path(channel_pk)
if not path.is_file():
return []
try:
data = pickle.load(path.open("rb"))
except Exception:
return []
if not isinstance(data, list):
return []
out: list[dict[str, Any]] = []
for item in data:
if isinstance(item, dict) and item.get("name"):
out.append(_normalize_cookie(item))
return out
def save_session_cookies(channel_pk: str, cookies: list[dict[str, Any]]) -> None:
path = session_cookie_path(channel_pk)
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("wb") as f:
pickle.dump([_normalize_cookie(c) for c in cookies if c.get("name")], f)
def delete_session_cookies(channel_pk: str) -> None:
path = session_cookie_path(channel_pk)
if path.is_file():
path.unlink()
def save_session_from_values(
channel_pk: str,
*,
sessionid: str,
dc_id: str = "",
username: str = "",
) -> dict[str, Any]:
sid = str(sessionid or "").strip()
if not sid:
raise ValueError("sessionid 不能为空")
dc = str(dc_id or "").strip()
if not dc:
dc = detect_working_datacenter(sid)
cookies = [
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": dc, "domain": ".tiktok.com", "path": "/"},
]
save_session_cookies(channel_pk, cookies)
now = time.time()
patch: dict[str, Any] = {
"oauth_ok": 1,
"oauth_checked_at": now,
"oauth_error": "",
"refresh_token": "cookie",
"cookie_saved_at": now,
}
if username.strip():
patch["tiktok_username"] = username.strip()
updated = tiktok_db.update_tiktok_channel(channel_pk, **patch) or {}
try:
from . import tiktok_profile
refreshed = tiktok_profile.fetch_profile_for_channel(
channel_pk,
username_hint=str(username or patch.get("tiktok_username") or ""),
)
if isinstance(refreshed, dict) and refreshed.get("channel"):
updated = refreshed["channel"]
except Exception as exc:
try:
tiktok_db.update_tiktok_channel(channel_pk, profile_error=str(exc)[:240])
updated = tiktok_db.get_tiktok_channel(channel_pk) or updated
except Exception:
pass
return updated
def channel_has_session(channel: dict[str, Any] | None) -> bool:
if not channel:
return False
pk = str(channel.get("id") or "")
if not pk:
return False
cookies = load_session_cookies(pk)
names = {str(c.get("name") or "") for c in cookies}
return "sessionid" in names and bool(next((c.get("value") for c in cookies if c.get("name") == "sessionid"), ""))
def cookie_age_info(channel: dict[str, Any] | None, *, persist_backfill: bool = False) -> dict[str, Any]:
"""Days since this account's Cookie was pasted. Probe/DC rewrite must not reset the clock."""
ch = channel or {}
pk = str(ch.get("id") or "")
has = channel_has_session(ch) if pk else False
saved = float(ch.get("cookie_saved_at") or 0)
if has and saved <= 0 and pk:
path = session_cookie_path(pk)
if path.is_file():
saved = float(path.stat().st_mtime)
if persist_backfill:
tiktok_db.update_tiktok_channel(pk, cookie_saved_at=saved)
if not has or saved <= 0:
return {
"cookie_saved_at": 0.0,
"cookie_age_days": None,
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": None,
"cookie_status": "missing",
}
age_days = max(0.0, (time.time() - saved) / 86400.0)
left_days = COOKIE_TTL_DAYS - age_days
if left_days <= 0:
status = "expired"
elif left_days <= 5:
status = "warn"
else:
status = "ok"
return {
"cookie_saved_at": saved,
"cookie_age_days": round(age_days, 1),
"cookie_ttl_days": COOKIE_TTL_DAYS,
"cookie_expires_in_days": round(max(0.0, left_days), 1),
"cookie_status": status,
}
def probe_channel_session(channel: dict[str, Any] | None) -> dict[str, Any]:
ch = channel or {}
pk = str(ch.get("id") or "")
if not pk:
return {"ok": False, "error": "账号不存在"}
if channel_has_session(ch):
tiktok_db.update_tiktok_channel(
pk,
oauth_ok=1,
oauth_checked_at=time.time(),
oauth_error="",
refresh_token="cookie",
)
try:
from . import tiktok_profile
tiktok_profile.refresh_profile_if_stale(pk, force=False)
except Exception:
pass
return {"ok": True, "channel_pk": pk, "mode": "cookie"}
tiktok_db.update_tiktok_channel(
pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error="未配置 Cookie 会话",
refresh_token="",
)
return {"ok": False, "channel_pk": pk, "error": "未配置 Cookie 会话"}
def setup_checklist(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
channels = tiktok_db.list_tiktok_channels()
ready = [c for c in channels if channel_has_session(c)]
vendor_ok = _VENDOR_ROOT.is_dir() and (_VENDOR_ROOT / "tiktok_uploader" / "tiktok.py").is_file()
sig_js = _VENDOR_ROOT / "tiktok_uploader" / "tiktok-signature" / "browser.js"
node_ok = bool(os.environ.get("NODE_PATH") or _which("node"))
return {
"mode": "cookie",
"vendor_ready": vendor_ok,
"signature_ready": sig_js.is_file(),
"node_available": node_ok,
"cookies_dir": str(cookies_dir()),
"steps": [
{
"id": "browser_login",
"title": "浏览器登录 tiktok.com,导出 sessionid(及 tt-target-idc)",
"url": "https://www.tiktok.com",
"done": len(ready) > 0,
},
{
"id": "paste_cookie",
"title": "在 TikTok 页为每个账号粘贴 Cookie / sessionid",
"done": len(ready) > 0,
},
{
"id": "account",
"title": "添加 TikTok 账号并完成 Cookie 授权",
"done": len(channels) > 0 and len(ready) == len(channels),
},
],
"note": (
"使用 TiktokAutoUploader Cookie 方案,无需 TikTok 开发者应用。"
" sessionid 等同账号密码,请勿泄露;约 30 天过期需重新粘贴。"
),
"note_unaudited": "",
}
def _which(name: str) -> str | None:
from shutil import which
return which(name)
def probe_project_create(sessionid: str, dc_id: str) -> dict[str, Any]:
"""Hit TikTok project/create to see if this sessionid + datacenter works."""
import secrets
import string
import requests
sid = str(sessionid or "").strip()
dc = str(dc_id or "").strip()
if not sid or not dc:
return {"ok": False, "dc_id": dc, "error": "缺少 sessionid 或机房"}
sess = requests.Session()
sess.cookies.set("sessionid", sid, domain=".tiktok.com")
sess.cookies.set("sessionid_ss", sid, domain=".tiktok.com")
sess.cookies.set("tt-target-idc", dc, domain=".tiktok.com")
sess.headers.update({"User-Agent": _PROBE_UA, "Accept": "application/json, text/plain, */*"})
cid = "".join(secrets.choice(string.ascii_letters + string.digits + "_") for _ in range(21))
url = f"https://www.tiktok.com/api/v1/web/project/create/?creation_id={cid}&type=1&aid=1988"
try:
r = sess.post(url, timeout=20)
payload = r.json()
except Exception as exc:
return {"ok": False, "dc_id": dc, "error": str(exc)[:160]}
project = payload.get("project") if isinstance(payload, dict) else None
ok = isinstance(project, dict) and bool(project.get("project_id"))
return {
"ok": ok,
"dc_id": dc,
"status_code": payload.get("status_code") if isinstance(payload, dict) else None,
"status_msg": str((payload or {}).get("status_msg") or "")[:160],
}
def detect_working_datacenter(sessionid: str, preferred: str = "") -> str:
order: list[str] = []
pref = str(preferred or "").strip()
if pref:
order.append(pref)
for item in _DC_CANDIDATES:
if item not in order:
order.append(item)
last: dict[str, Any] = {}
for dc in order:
last = probe_project_create(sessionid, dc)
if last.get("ok"):
return dc
msg = str(last.get("status_msg") or last.get("error") or "").strip()
code = last.get("status_code")
hint = f"(status_code={code} {msg})" if code is not None or msg else ""
raise ValueError(
f"TikTok Cookie 无效或机房不匹配{hint}。请重新从已登录的 tiktok.com 复制 sessionid 和 tt-target-idc"
)
def ensure_working_datacenter(channel_pk: str) -> str:
cookies = load_session_cookies(channel_pk)
sid = next((str(c.get("value") or "") for c in cookies if c.get("name") == "sessionid"), "")
dc = next((str(c.get("value") or "") for c in cookies if c.get("name") == "tt-target-idc"), "")
if not sid:
raise ValueError("Cookie 缺少 sessionid")
working = detect_working_datacenter(sid, dc)
if working != dc:
save_session_cookies(
channel_pk,
[
{"name": "sessionid", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "sessionid_ss", "value": sid, "domain": ".tiktok.com", "path": "/"},
{"name": "tt-target-idc", "value": working, "domain": ".tiktok.com", "path": "/"},
],
)
return working
def configure_vendor_paths() -> None:
"""Point vendored Config at our cookies directory."""
os.environ.setdefault("TIKTOK_VENDOR_ROOT", str(_VENDOR_ROOT))
try:
from tiktok_uploader.Config import Config
cfg = Config.get()
cfg._insert_option("COOKIES_DIR", str(cookies_dir()))
cfg._insert_option("VIDEOS_DIR", str(cookies_dir()))
except Exception:
pass

View File

@ -1,132 +1,138 @@
# -*- coding: utf-8 -*-
"""TikTok upload SOCKS5 profiles (optional per account, default off)."""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import quote
SETTINGS_KEY = "tiktok_upload_socks_profiles"
def _norm_profile(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
pid = str(raw.get("id") or "").strip() or str(uuid.uuid4())
server = str(raw.get("server") or "").strip()
try:
port = int(raw.get("port") or 0)
except Exception:
port = 0
ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5"
if ptype not in {"socks5", "socks5h"}:
ptype = "socks5"
return {
"id": pid,
"label": str(raw.get("label") or server or pid).strip() or pid,
"type": ptype,
"server": server,
"port": port,
"username": str(raw.get("username") or ""),
"password": str(raw.get("password") or ""),
}
def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
raw = settings.get(SETTINGS_KEY)
rows: list[dict[str, Any]] = []
if isinstance(raw, list):
for item in raw:
p = _norm_profile(item)
if p and p["server"] and p["port"] > 0:
rows.append(p)
if not public:
return rows
out = []
for p in rows:
pwd = str(p.get("password") or "")
q = dict(p)
q["has_password"] = bool(pwd.strip())
q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "")
out.append(q)
return out
def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
pid = str(profile_id or "").strip()
if not pid:
return None
for p in list_socks_profiles(cfg, public=False):
if str(p.get("id") or "") == pid:
return p
return None
def socks_proxy_url(profile: dict[str, Any] | None) -> str:
"""Build SOCKS URL for requests/TiktokAutoUploader. Prefer socks5h (remote DNS)."""
if not profile:
return ""
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
if not server or port <= 0:
return ""
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
scheme = "socks5h"
if user or pwd:
return f"{scheme}://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}"
return f"{scheme}://{server}:{port}"
def resolve_channel_socks_proxy(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> str:
"""Return proxy URL only when this TikTok account opted into SOCKS; else empty (direct)."""
if not channel:
return ""
enabled = channel.get("socks_enabled")
if isinstance(enabled, str):
enabled = enabled.strip().lower() in {"1", "true", "yes", "on"}
if not enabled:
return ""
pid = str(channel.get("socks_profile_id") or "").strip()
prof = get_socks_profile(pid, cfg)
if not prof:
rows = list_socks_profiles(cfg, public=False)
prof = rows[0] if rows else None
return socks_proxy_url(prof)
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Merge UI patch; keep existing password when incoming is blank or ***masked."""
existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)}
out: list[dict[str, Any]] = []
src = incoming if isinstance(incoming, list) else []
for item in src:
p = _norm_profile(item)
if not p:
continue
pid = str(p["id"])
old = existing.get(pid) or {}
pwd = str(p.get("password") or "")
if (not pwd.strip()) or pwd.startswith("***"):
p["password"] = str(old.get("password") or "")
if not p["server"] or int(p.get("port") or 0) <= 0:
continue
out.append(p)
if not src:
return list(existing.values())
return out
def save_socks_profiles(profiles: list[dict[str, Any]]) -> list[dict[str, Any]]:
from . import db
cfg = db.get_settings_map()
merged = merge_socks_profiles_patch(profiles, cfg)
db.update_settings_map({SETTINGS_KEY: merged})
return list_socks_profiles(db.get_settings_map(), public=True)
# -*- coding: utf-8 -*-
"""TikTok upload SOCKS5 profiles (optional per account, default off)."""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import quote
SETTINGS_KEY = "tiktok_upload_socks_profiles"
def _norm_profile(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
pid = str(raw.get("id") or "").strip() or str(uuid.uuid4())
server = str(raw.get("server") or "").strip()
try:
port = int(raw.get("port") or 0)
except Exception:
port = 0
ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5"
if ptype not in {"socks5", "socks5h"}:
ptype = "socks5"
return {
"id": pid,
"label": str(raw.get("label") or server or pid).strip() or pid,
"type": ptype,
"server": server,
"port": port,
"username": str(raw.get("username") or ""),
"password": str(raw.get("password") or ""),
}
def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
raw = settings.get(SETTINGS_KEY)
rows: list[dict[str, Any]] = []
if isinstance(raw, list):
for item in raw:
p = _norm_profile(item)
if p and p["server"] and p["port"] > 0:
rows.append(p)
if not public:
return rows
out = []
for p in rows:
pwd = str(p.get("password") or "")
q = dict(p)
q["has_password"] = bool(pwd.strip())
q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "")
out.append(q)
return out
def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
pid = str(profile_id or "").strip()
if not pid:
return None
for p in list_socks_profiles(cfg, public=False):
if str(p.get("id") or "") == pid:
return p
return None
def socks_proxy_url(profile: dict[str, Any] | None) -> str:
"""Build SOCKS URL for requests/TiktokAutoUploader. Prefer socks5h (remote DNS)."""
if not profile:
return ""
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
if not server or port <= 0:
return ""
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
scheme = "socks5h"
if user or pwd:
return f"{scheme}://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}"
return f"{scheme}://{server}:{port}"
def resolve_channel_socks_proxy(channel: dict[str, Any] | None, cfg: dict[str, Any] | None = None) -> str:
"""Per-account SOCKS if opted in; else fall back to global residential / egress uploads proxy."""
if channel:
enabled = channel.get("socks_enabled")
if isinstance(enabled, str):
enabled = enabled.strip().lower() in {"1", "true", "yes", "on"}
if enabled:
pid = str(channel.get("socks_profile_id") or "").strip()
prof = get_socks_profile(pid, cfg)
if not prof:
rows = list_socks_profiles(cfg, public=False)
prof = rows[0] if rows else None
url = socks_proxy_url(prof)
if url:
return url
try:
from . import egress_hub
return egress_hub.resolve_upload_proxy(cfg) or ""
except Exception:
return ""
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Merge UI patch; keep existing password when incoming is blank or ***masked."""
existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)}
out: list[dict[str, Any]] = []
src = incoming if isinstance(incoming, list) else []
for item in src:
p = _norm_profile(item)
if not p:
continue
pid = str(p["id"])
old = existing.get(pid) or {}
pwd = str(p.get("password") or "")
if (not pwd.strip()) or pwd.startswith("***"):
p["password"] = str(old.get("password") or "")
if not p["server"] or int(p.get("port") or 0) <= 0:
continue
out.append(p)
if not src:
return list(existing.values())
return out
def save_socks_profiles(profiles: list[dict[str, Any]]) -> list[dict[str, Any]]:
from . import db
cfg = db.get_settings_map()
merged = merge_socks_profiles_patch(profiles, cfg)
db.update_settings_map({SETTINGS_KEY: merged})
return list_socks_profiles(db.get_settings_map(), public=True)

File diff suppressed because it is too large Load Diff

View File

@ -52,10 +52,10 @@ async def record_long_clip(
job_id: str,
stream_urls: list[str] | None = None,
stream_url: str = "",
seconds: int = 300,
seconds: int = 600,
cfg: dict[str, Any] | None = None,
) -> dict[str, Any]:
"""Pull live stream for 3–8 minutes into a 9:16 mp4 (16:9 only if explicitly enabled)."""
"""Pull live stream for 8–15 minutes into a 9:16 mp4 (16:9 only if explicitly enabled)."""
urls: list[str] = []
for u in list(stream_urls or []) + [stream_url]:
s = str(u or "").strip()
@ -64,7 +64,7 @@ async def record_long_clip(
if not urls:
return {"ok": False, "error": "无可用流地址"}
sec = max(YT_LONG_MIN_SEC, min(int(seconds or 300), YT_LONG_MAX_SEC))
sec = max(YT_LONG_MIN_SEC, min(int(seconds or 600), YT_LONG_MAX_SEC))
out_path = clips_dir() / f"{job_id}.mp4"
vf = _vf_for_settings(cfg)
last_err = ""

View File

@ -32,8 +32,8 @@ YT_LONG_CHANNEL_DEFAULT = 5 # Beijing-day target per channel (normal)
YT_LONG_CHANNEL_LIMITED = 4 # when shared YouTube API quota is limited (3 < n < 5)
YT_LONG_DAILY_DEFAULT = 70 # 14 channels × 5
YT_LONG_SOURCE_DEFAULT = 70
YT_LONG_MIN_SEC = 180 # 3 min
YT_LONG_MAX_SEC = 480 # 8 min
YT_LONG_MIN_SEC = 480 # 8 min
YT_LONG_MAX_SEC = 900 # 15 min
def ensure_yt_long_tables(conn: sqlite3.Connection) -> None:
@ -144,23 +144,39 @@ def yt_long_daily_max(cfg: dict[str, Any] | None = None) -> int:
return max(0, min(200, v))
def yt_long_enabled_upload_cap(cfg: dict[str, Any] | None = None) -> int:
"""Sum of daily_max for enabled oauth yt_long channels (authoritative upload/master cap)."""
per = effective_yt_long_channel_daily_max(cfg)
total = 0
n = 0
for ch in list_yt_long_channels(enabled=True):
if not ch.get("enabled", True):
continue
if not str(ch.get("refresh_token") or "").strip():
continue
n += 1
try:
row_max = int(ch.get("daily_max") or 0)
except Exception:
row_max = 0
if row_max <= 0:
row_max = per
# Soft API limit: never count above effective per-channel cap.
total += min(row_max, per) if per > 0 else row_max
if n <= 0:
return max(0, per)
return max(0, total)
def yt_long_source_daily_max(cfg: dict[str, Any] | None = None) -> int:
"""Master recording daily cap — must cover cascade platform needs."""
"""Master recording daily cap — equals enabled long-upload quota (not Shorts fleet)."""
from . import db
settings = cfg if cfg is not None else db.get_settings_map()
upload_cap = yt_long_daily_max(settings)
try:
v = int(settings.get("yt_long_source_daily_max") or 0)
except Exception:
v = 0
if v <= 0:
v = max(upload_cap, YT_LONG_SOURCE_DEFAULT)
try:
hard = max(42, min(300, int(settings.get("yt_long_source_cap") or 200)))
except Exception:
hard = 200
return max(upload_cap, min(hard, v))
upload_cap = yt_long_enabled_upload_cap(settings)
if upload_cap <= 0:
upload_cap = yt_long_daily_max(settings)
return max(0, upload_cap)
def youtube_api_upload_limited(cfg: dict[str, Any] | None = None) -> bool:
@ -234,14 +250,27 @@ def reconcile_yt_long_upload_caps(cfg: dict[str, Any] | None = None) -> dict[str
limited = youtube_api_upload_limited(settings)
per = effective_yt_long_channel_daily_max(settings)
n = count_oauth_yt_long_channels(enabled_only=True)
global_max = max(per, n * per) if n else max(per, YT_LONG_DAILY_DEFAULT)
# Enabled channels only — never multiply by disabled Account B rows.
global_max = yt_long_enabled_upload_cap(settings)
if global_max <= 0:
global_max = max(per, n * per) if n else max(per, 0)
try:
stored_global = int(settings.get("yt_long_daily_max") or 0)
except Exception:
stored_global = 0
patch: dict[str, Any] = {}
if stored_global != global_max:
patch["yt_long_daily_max"] = global_max
# Keep source in lockstep with enabled upload cap (clear Shorts-inflated 63 etc.).
try:
stored_src = int(settings.get("yt_long_source_daily_max") or 0)
except Exception:
stored_src = 0
if stored_src != global_max:
patch["yt_long_source_daily_max"] = global_max
if patch:
try:
db.update_settings_map({"yt_long_daily_max": global_max})
db.update_settings_map(patch)
settings = db.get_settings_map()
except Exception:
pass
@ -777,27 +806,43 @@ def claim_due_yt_long_upload(*, skip_profile_ids: set[str] | None = None) -> dic
ensure_yt_long_tables(conn)
rows = conn.execute(
"""
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id,
IFNULL(c.oauth_ok, -1) AS ch_oauth_ok
FROM yt_long_jobs j
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
WHERE j.status = 'scheduled'
AND c.enabled = 1
AND IFNULL(c.oauth_ok, -1) != 0
AND j.clip_path != ''
AND j.upload_at > 0
AND j.upload_at <= ?
ORDER BY j.upload_at ASC, j.created_at ASC
LIMIT 30
LIMIT 40
""",
(now,),
).fetchall()
import os
picked = None
for row in rows:
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
if pid in skip:
continue
path = str(row["clip_path"] or "").strip()
if not (path and os.path.isfile(path) and os.path.getsize(path) > 1024):
conn.execute(
"""
UPDATE yt_long_jobs
SET status='pending', clip_path='', clip_seconds=0, upload_at=0,
started_at=0, error='成片丢失,已重新排队录制', updated_at=?
WHERE id=? AND status='scheduled'
""",
(now, str(row["id"])),
)
continue
picked = row
break
if not picked:
conn.commit()
return None
jid = str(picked["id"])
cur = conn.execute(
@ -877,9 +922,9 @@ def count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int:
conn.close()
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 720) -> int:
"""Reclaim orphan recording rows. Never reclaim before ~12 min (3–8 min clip + encode slack)."""
age = max(720.0, float(max_age_sec))
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 1200) -> int:
"""Reclaim orphan recording rows. Never reclaim before ~20 min (8–15 min clip + encode slack)."""
age = max(1200.0, float(max_age_sec))
cutoff = time.time() - age
with _lock:
conn = _connect()
@ -904,24 +949,184 @@ def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 720) -> int:
def reclaim_stale_yt_long_uploads(*, max_age_sec: float = 1800) -> int:
cutoff = time.time() - max(180.0, float(max_age_sec))
"""Requeue orphan uploading rows; scale age by clip length; drop if file gone."""
import os
base = max(1800.0, float(max_age_sec))
now = time.time()
n = 0
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
rows = conn.execute(
"""
SELECT id, clip_path, clip_seconds, updated_at, attempts
FROM yt_long_jobs
WHERE status = 'uploading' AND IFNULL(youtube_video_id, '') = ''
"""
).fetchall()
for row in rows:
jid = str(row["id"])
clip_sec = float(row["clip_seconds"] or 0)
# Allow ~3x clip duration + 10m encode/upload slack (15m clip => ~55m)
need = max(base, clip_sec * 3.0 + 600.0)
if float(row["updated_at"] or 0) > now - need:
continue
path = str(row["clip_path"] or "").strip()
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
attempts = int(row["attempts"] or 0)
if alive:
backoff = min(3600.0, 60.0 * (2 ** min(6, max(0, attempts - 1))))
conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'scheduled',
error = 'upload_stale_reclaim',
upload_at = ?,
updated_at = ?
WHERE id = ? AND status = 'uploading'
""",
(now + backoff, now, jid),
)
else:
conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'pending',
clip_path = '',
clip_seconds = 0,
upload_at = 0,
started_at = 0,
error = '成片丢失,已重新排队录制',
updated_at = ?
WHERE id = ? AND status = 'uploading'
""",
(now, jid),
)
n += 1
if n:
conn.commit()
return n
finally:
conn.close()
def heal_yt_long_orphan_jobs() -> dict[str, int]:
"""Self-heal impossible/orphan jobs so every enabled channel can progress."""
import os
now = time.time()
missing = 0
promoted = 0
restart_orphans = 0
with _lock:
conn = _connect()
try:
ensure_yt_long_tables(conn)
# 1) Already have YouTube id but stuck in scheduled/uploading → uploaded
cur = conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'scheduled', error = 'upload_stale_reclaim', updated_at = ?
WHERE status = 'uploading' AND updated_at < ?
AND IFNULL(youtube_video_id, '') = ''
SET status = 'uploaded',
error = CASE
WHEN IFNULL(error,'') = '' THEN 'heal_promoted_existing_video_id'
ELSE error
END,
finished_at = CASE WHEN IFNULL(finished_at,0)=0 THEN ? ELSE finished_at END,
updated_at = ?
WHERE status IN ('scheduled', 'uploading', 'recorded')
AND IFNULL(youtube_video_id, '') != ''
""",
(time.time(), cutoff),
(now, now),
)
conn.commit()
return int(cur.rowcount or 0)
promoted = int(cur.rowcount or 0)
# 2) uploading after process restart is never resumed → requeue/fail by file
rows = conn.execute(
"""
SELECT id, clip_path, clip_seconds, attempts
FROM yt_long_jobs
WHERE status = 'uploading' AND IFNULL(youtube_video_id, '') = ''
"""
).fetchall()
for row in rows:
jid = str(row["id"])
path = str(row["clip_path"] or "").strip()
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
attempts = int(row["attempts"] or 0)
if alive:
backoff = min(900.0, 30.0 * (2 ** min(5, max(0, attempts - 1))))
conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'scheduled',
error = 'upload_restart_requeue',
upload_at = ?,
updated_at = ?
WHERE id = ? AND status = 'uploading'
""",
(now + backoff, now, jid),
)
else:
conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'pending',
clip_path = '',
clip_seconds = 0,
upload_at = 0,
started_at = 0,
error = '成片丢失,已重新排队录制',
updated_at = ?
WHERE id = ? AND status = 'uploading'
""",
(now, jid),
)
restart_orphans += 1
# 3) scheduled/recorded without master file → re-record
rows = conn.execute(
"""
SELECT id, clip_path, status, error
FROM yt_long_jobs
WHERE status IN ('scheduled', 'recorded')
AND IFNULL(youtube_video_id, '') = ''
"""
).fetchall()
for row in rows:
err = str(row["error"] or "")
if err.startswith("cascade_only"):
continue
path = str(row["clip_path"] or "").strip()
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
if alive:
continue
conn.execute(
"""
UPDATE yt_long_jobs
SET status = 'pending',
clip_path = '',
clip_seconds = 0,
upload_at = 0,
started_at = 0,
error = '成片丢失,已重新排队录制',
updated_at = ?
WHERE id = ?
""",
(now, str(row["id"])),
)
missing += 1
if missing or promoted or restart_orphans:
conn.commit()
finally:
conn.close()
return {
"requeued_missing_clip": missing,
"promoted_existing_video_id": promoted,
"restart_upload_orphans": restart_orphans,
}
def yt_long_stats(push_date: str = "") -> dict[str, Any]:

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
"""Isolated YouTube long-form (default 9:16) pipeline.
Records 3–8 min masters; optionally cascades cuts to TikTok / Shorts / X
Records 8–15 min masters; optionally cascades cuts to TikTok / Shorts / X
via clip_cascade (each platform keeps its own tables and quotas).
Default: disabled (yt_long_enabled=false) until an operator turns this on.
"""
@ -76,6 +76,12 @@ def pick_yt_long_channel(cfg: dict[str, Any], push_date: str = "") -> dict[str,
cid = str(ch.get("id") or "")
if not cid:
continue
# oauth_ok=0 means last upload auth failed — skip until re-authorized
try:
if int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) == 0:
continue
except Exception:
pass
creds = _channel_creds(ch, cfg)
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
continue
@ -453,7 +459,7 @@ class YtLongPipeline:
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
"yt_long_monetize_when_ypp": bool(cfg.get("yt_long_monetize_when_ypp", True)),
"clips_max_age_hours": float(cfg.get("clips_max_age_hours") or 24),
"clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 12),
"clips_min_free_gb": float(cfg.get("clips_min_free_gb") or 8),
},
}
self._status_cache = payload
@ -534,11 +540,11 @@ class YtLongPipeline:
async def kick_pending_records(self, ids: list[str] | None = None) -> int:
cfg = db.get_settings_map()
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
# Never reclaim active long recordings here (3–8 min + encode); loop handles orphans safely
# Never reclaim active long recordings here (8–15 min + encode); loop handles orphans safely
try:
from .host_metrics import clip_encode_defer_reason
if clip_encode_defer_reason():
if clip_encode_defer_reason(respect_live_push=False):
return 0
except Exception:
pass
@ -588,13 +594,20 @@ class YtLongPipeline:
if n:
self.sampled += n
try:
# Long clips are 3–8 min (+ ffmpeg slack); reclaim only true orphans
# Long clips are 8–15 min (+ ffmpeg slack); reclaim only true orphans
max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC)
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(720, max_clip + 240))
yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(1200, max_clip + 300))
except Exception:
pass
try:
yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800)
max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC)
yt_long_db.reclaim_stale_yt_long_uploads(
max_age_sec=max(1800, max_clip * 3 + 600)
)
except Exception:
pass
try:
yt_long_db.heal_yt_long_orphan_jobs()
except Exception:
pass
@ -651,9 +664,14 @@ class YtLongPipeline:
pass
# Never steal CPU from live YouTube push (site hang root cause on dy VPS).
try:
from .host_metrics import clip_encode_defer_reason
from .host_metrics import clip_encode_defer_reason, live_youtube_push_active
defer = clip_encode_defer_reason()
# Live RTMP must keep headroom, but blocking *all* long encodes whenever
# any relay pushes caused day-long 0 uploads. Only defer on load/CPU;
# while live is pushing, cap concurrent long records at 1.
defer = clip_encode_defer_reason(respect_live_push=False)
if (not defer) and live_youtube_push_active():
max_rec = min(max_rec, 1)
except Exception:
defer = ""
while (
@ -742,7 +760,7 @@ class YtLongPipeline:
try:
from .clip_retention import disk_free_gb
if disk_free_gb() < 16.0:
if disk_free_gb() < float(cfg.get("clips_min_free_gb") or 8):
sec = min(sec, max(YT_LONG_MIN_SEC, int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC) + 60))
except Exception:
pass
@ -848,6 +866,7 @@ class YtLongPipeline:
)
if is_quota:
should_notify = True
until = time.time() + 3600
try:
from .shorts_yt_quota import mark_api_quota_cooldown, profile_id_for_channel
@ -868,19 +887,57 @@ class YtLongPipeline:
yt_long_db.reconcile_yt_long_upload_caps()
except Exception:
should_notify = True
# Keep the master: defer this job instead of burning it as failed.
yt_long_db.update_yt_long_job(
str(job.get("id") or ""),
status="failed",
error=str(exc)[:500],
finished_at=time.time(),
status="scheduled",
upload_at=float(until) + 30,
error=f"QUOTA_DEFER: {str(exc)[:400]}",
finished_at=0,
)
if should_notify:
_emit(
"yt_long_fail",
"warn",
f"长视频:YouTube 接口配额用尽(冷静后重试,不拦手动):{str(exc)[:80]}",
f"长视频:YouTube 接口配额用尽(已延后自动重试):{str(exc)[:80]}",
job,
)
elif "OAUTH_INVALID" in msg or "invalid_grant" in msg.lower() or "401" in msg[:80]:
try:
ch_pk = str(job.get("channel_pk") or "")
if ch_pk:
yt_long_db.update_yt_long_channel(
ch_pk,
oauth_ok=0,
oauth_checked_at=time.time(),
oauth_error=str(exc)[:240],
)
except Exception:
pass
yt_long_db.update_yt_long_job(
str(job.get("id") or ""),
status="scheduled",
upload_at=time.time() + 1800,
error=f"OAUTH_DEFER: {str(exc)[:400]}",
finished_at=0,
)
_emit(
"yt_long_fail",
"warn",
f"长视频:频道授权异常已延后:{job.get('anchor_name') or job.get('id')} — {str(exc)[:80]}",
job,
)
elif "成片文件不存在" in msg:
yt_long_db.update_yt_long_job(
str(job.get("id") or ""),
status="pending",
clip_path="",
clip_seconds=0,
upload_at=0,
started_at=0,
error="成片丢失,已重新排队录制",
finished_at=0,
)
else:
yt_long_db.update_yt_long_job(
str(job.get("id") or ""),

View File

@ -1,104 +1,148 @@
# -*- coding: utf-8 -*-
"""YouTube long-form upload — same OAuth transport as Shorts, watch URL not /shorts/."""
from __future__ import annotations
from pathlib import Path
from typing import Any
import httpx
from .shorts_upload import (
_client_kwargs,
is_upload_quota_error,
quota_error_message,
refresh_access_token,
)
async def upload_youtube_long_mp4(
*,
file_path: str,
title: str,
description: str = "",
privacy: str = "public",
client_id: str = "",
client_secret: str = "",
refresh_token: str = "",
proxy_url: str = "",
) -> dict[str, Any]:
path = Path(file_path)
if not path.is_file():
raise ValueError("成片文件不存在")
access = await refresh_access_token(
client_id=client_id,
client_secret=client_secret,
refresh_token=refresh_token,
proxy_url=proxy_url,
)
try:
size = path.stat().st_size
raw = path.read_bytes()
except FileNotFoundError as exc:
raise ValueError("成片文件不存在") from exc
# No #Shorts — this is a normal YouTube watch video (9:16 vertical by default).
# Strip <> — YouTube API rejects them (invalidTitle); caption pool may contain ">".
import re
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()
clean_title = re.sub(r"[<>]+", " ", clean_title)
clean_title = re.sub(r"\s+", " ", clean_title).strip()[:100]
meta = {
"snippet": {
"title": clean_title or "Live clip",
"description": description or "",
"categoryId": "22",
},
"status": {
"privacyStatus": privacy if privacy in {"public", "unlisted", "private"} else "public",
"selfDeclaredMadeForKids": False,
},
}
init_url = (
"https://www.googleapis.com/upload/youtube/v3/videos"
"?uploadType=resumable&part=snippet,status"
)
async with httpx.AsyncClient(**_client_kwargs(timeout=600.0, proxy_url=proxy_url)) as client:
init = await client.post(
init_url,
headers={
"Authorization": f"Bearer {access}",
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Length": str(size),
"X-Upload-Content-Type": "video/mp4",
},
json=meta,
)
upload_url = init.headers.get("location") or init.headers.get("Location")
if init.status_code >= 400 or not upload_url:
body = init.text[:800]
if init.status_code == 429 or is_upload_quota_error(body):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})")
raise ValueError(f"初始化上传失败: {body[:400]}")
put = await client.put(
upload_url,
headers={
"Authorization": f"Bearer {access}",
"Content-Type": "video/mp4",
"Content-Length": str(size),
},
content=raw,
)
data = put.json() if put.content else {}
if put.status_code >= 400 or not data.get("id"):
err_text = str(data.get("error") or put.text[:800])
if put.status_code == 429 or is_upload_quota_error(err_text):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})")
raise ValueError(f"上传失败: {err_text[:400]}")
vid = str(data["id"])
return {
"ok": True,
"video_id": vid,
"url": f"https://www.youtube.com/watch?v={vid}",
"raw": data,
}
# -*- coding: utf-8 -*-
"""YouTube long-form upload — same OAuth transport as Shorts, watch URL not /shorts/.
Streams the mp4 via an *async* byte iterator (no full-file RAM load, compatible
with httpx.AsyncClient). Size-aware timeout so 8–15 min masters do not hang.
"""
from __future__ import annotations
import asyncio
import re
from collections.abc import AsyncIterator
from pathlib import Path
from typing import Any
import httpx
from .shorts_upload import (
_client_kwargs,
is_upload_quota_error,
quota_error_message,
refresh_access_token,
)
_CHUNK = 1024 * 1024 # 1 MiB
def _sanitize_yt_text(text: str, *, limit: int) -> str:
"""YouTube rejects angle brackets in title/description (invalid metadata)."""
t = re.sub(r"[<>]+", " ", str(text or ""))
t = re.sub(r"\s+", " ", t).strip()
return t[:limit]
def _upload_timeout_sec(size_bytes: int) -> float:
"""Scale HTTP timeout with file size (min 10m, ~8s/MB, cap 45m)."""
mb = max(1.0, float(size_bytes) / (1024.0 * 1024.0))
return float(min(2700.0, max(600.0, mb * 8.0 + 120.0)))
async def _aiter_file_chunks(path: Path, *, chunk_size: int = _CHUNK) -> AsyncIterator[bytes]:
"""Yield file bytes without blocking the event loop (AsyncClient-safe)."""
loop = asyncio.get_running_loop()
fh = await loop.run_in_executor(None, path.open, "rb")
try:
while True:
chunk = await loop.run_in_executor(None, fh.read, chunk_size)
if not chunk:
break
yield chunk
finally:
await loop.run_in_executor(None, fh.close)
async def upload_youtube_long_mp4(
*,
file_path: str,
title: str,
description: str = "",
privacy: str = "public",
client_id: str = "",
client_secret: str = "",
refresh_token: str = "",
proxy_url: str = "",
) -> dict[str, Any]:
path = Path(file_path)
if not path.is_file():
raise ValueError("成片文件不存在")
access = await refresh_access_token(
client_id=client_id,
client_secret=client_secret,
refresh_token=refresh_token,
proxy_url=proxy_url,
)
try:
size = path.stat().st_size
except FileNotFoundError as exc:
raise ValueError("成片文件不存在") from exc
if size <= 0:
raise ValueError("成片文件为空")
# No #Shorts — this is a normal YouTube watch video (9:16 vertical by default).
clean_title = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()
clean_title = _sanitize_yt_text(clean_title, limit=100) or "Live clip"
clean_desc = _sanitize_yt_text(description or "", limit=4900)
meta = {
"snippet": {
"title": clean_title,
"description": clean_desc,
"categoryId": "22",
},
"status": {
"privacyStatus": privacy if privacy in {"public", "unlisted", "private"} else "public",
"selfDeclaredMadeForKids": False,
},
}
init_url = (
"https://www.googleapis.com/upload/youtube/v3/videos"
"?uploadType=resumable&part=snippet,status"
)
timeout = _upload_timeout_sec(size)
async with httpx.AsyncClient(**_client_kwargs(timeout=timeout, proxy_url=proxy_url)) as client:
init = await client.post(
init_url,
headers={
"Authorization": f"Bearer {access}",
"Content-Type": "application/json; charset=UTF-8",
"X-Upload-Content-Length": str(size),
"X-Upload-Content-Type": "video/mp4",
},
json=meta,
)
upload_url = init.headers.get("location") or init.headers.get("Location")
if init.status_code >= 400 or not upload_url:
body = init.text[:800]
if init.status_code == 429 or is_upload_quota_error(body):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})")
if init.status_code in (401, 403):
raise ValueError(f"OAUTH_INVALID: 初始化上传失败: {body[:400]}")
raise ValueError(f"初始化上传失败: {body[:400]}")
# AsyncClient rejects sync file objects ("Attempted to send an sync request…").
# Stream via async chunk iterator instead of path.open() / read_bytes().
put = await client.put(
upload_url,
headers={
"Authorization": f"Bearer {access}",
"Content-Type": "video/mp4",
"Content-Length": str(size),
},
content=_aiter_file_chunks(path),
)
data = put.json() if put.content else {}
if put.status_code >= 400 or not data.get("id"):
err_text = str(data.get("error") or put.text[:800])
if put.status_code == 429 or is_upload_quota_error(err_text):
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})")
if put.status_code in (401, 403):
raise ValueError(f"OAUTH_INVALID: 上传失败: {err_text[:400]}")
raise ValueError(f"上传失败: {err_text[:400]}")
vid = str(data["id"])
return {
"ok": True,
"video_id": vid,
"url": f"https://www.youtube.com/watch?v={vid}",
"raw": data,
"bytes": size,
"timeout_sec": timeout,
}

0
backend/neko/browser-launch.sh Normal file → Executable file
View File

BIN
bin/sing-box Executable file

Binary file not shown.

9
config/proxychains.conf Normal file
View File

@ -0,0 +1,9 @@
strict_chain
proxy_dns
tcp_read_time_out 15000
tcp_connect_time_out 8000
localnet 127.0.0.0/8
localnet 10.0.0.0/8
localnet 192.168.0.0/16
[ProxyList]
socks5 127.0.0.1 17891

34
config/sing-box.json Normal file
View File

@ -0,0 +1,34 @@
{
"log": {
"level": "warn",
"timestamp": true
},
"inbounds": [
{
"type": "mixed",
"tag": "mixed-in",
"listen": "0.0.0.0",
"listen_port": 17891,
"sniff": true
}
],
"outbounds": [
{
"type": "socks",
"tag": "upstream",
"server": "178.92.61.73",
"server_port": 43027,
"version": "5",
"username": "NY9ZrHJKgv0Dwid",
"password": "7ktx7HZ3agK50I4"
},
{
"type": "direct",
"tag": "direct"
}
],
"route": {
"rules": [],
"final": "upstream"
}
}

12823
frontend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,29 +1,29 @@
{
"name": "douyin-live-monitor",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"echarts": "^5.5.1",
"lucide-react": "^0.468.0",
"next": "15.1.0",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9",
"eslint-config-next": "15.1.0",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"
}
}
{
"name": "douyin-live-monitor",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"echarts": "^5.5.1",
"lucide-react": "^0.468.0",
"next": "15.1.11",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@types/node": "^20",
"@types/react": "^19",
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9",
"eslint-config-next": "15.1.11",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -466,17 +466,20 @@ export default function ShortsPage() {
}, [status?.oauth_profiles, channels]);
const totals = useMemo(() => {
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
const recorded = displayChannels.reduce((s, c) => s + (c.recorded || 0), 0);
const pending = displayChannels.reduce((s, c) => s + (c.pending || 0), 0);
const recording = displayChannels.reduce((s, c) => s + (c.recording || 0), 0);
// Only **enabled** channels count toward 北京日配额 X/Y (same bug as yt-long).
const active = displayChannels.filter((c) => c.enabled !== false);
const uploaded = active.reduce((s, c) => s + (c.uploaded || 0), 0);
const scheduled = active.reduce((s, c) => s + (c.scheduled || 0), 0);
const recorded = active.reduce((s, c) => s + (c.recorded || 0), 0);
const pending = active.reduce((s, c) => s + (c.pending || 0), 0);
const recording = active.reduce((s, c) => s + (c.recording || 0), 0);
const used = uploaded;
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 9), 0);
const minTarget = displayChannels.filter((c) => c.enabled !== false).reduce((s, c) => s + (c.daily_min || 9), 0);
const gap = displayChannels
.filter((c) => c.enabled !== false)
.reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0);
const cap = active.reduce((s, c) => s + (c.daily_max || 9), 0);
const minTarget = active.reduce((s, c) => s + (c.daily_min || 9), 0);
const gap = active.reduce(
(s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))),
0,
);
const queuedUpload = scheduled + recorded;
const pendingRecord = pending + recording;
return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap };
@ -975,8 +978,14 @@ export default function ShortsPage() {
<>
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
{[
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"],
["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"],
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)· 仅已启用` : "仅已启用频道日上限合计"],
[
"当日缺口",
String(totals.gap || quotaGap),
minUnmet > 0
? `${minUnmet} 个启用频道未达每日最少`
: "启用频道已达每日最少",
],
["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`],
[
"抖音在播源",

View File

@ -379,14 +379,16 @@ export default function YtLongPage() {
}, [upcoming, channelProfileMap]);
const totals = useMemo(() => {
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
// Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。
// Only **enabled** channels count toward YouTube 上传 3/14 (not disabled Account B).
const active = displayChannels.filter((c) => c.enabled !== false);
const uploaded = active.reduce((s, c) => s + (c.uploaded || 0), 0);
const scheduled = active.reduce((s, c) => s + (c.scheduled || 0), 0);
const used = uploaded;
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0);
const gap = displayChannels
.filter((c) => c.enabled !== false)
.reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0);
const cap = active.reduce((s, c) => s + (c.daily_max || 0), 0);
const gap = active.reduce(
(s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)),
0,
);
return { uploaded, scheduled, used, cap, gap };
}, [displayChannels]);
@ -521,7 +523,7 @@ export default function YtLongPage() {
<p className="font-display text-xs uppercase tracking-[0.28em] text-amber-300/80">Long Video Pipeline</p>
<h2 className="font-display text-3xl font-semibold tracking-tight">📺 长视频分发台</h2>
<p className="mt-1 max-w-2xl text-sm text-slate-400">
在播放样 → 9:16 成片(3–8 分钟)→ 上传为普通 YouTube 视频(watch?v=)。成片可 cascade 切 TikTok / Shorts / X。频道 OAuth 可从 Shorts 同步,业务数据隔离。
在播放样 → 9:16 成片(8–15 分钟随机)→ 上传为普通 YouTube 视频(watch?v=)。成片可 cascade 切 TikTok / Shorts / X。频道 OAuth 可从 Shorts 同步,业务数据隔离。
</p>
</div>
<div className="flex flex-wrap gap-2">
@ -562,7 +564,7 @@ export default function YtLongPage() {
],
[
"成片规格",
`${Math.round(Number(settings.yt_long_min_sec || 180) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 480) / 60)}分`,
`${Math.round(Number(settings.yt_long_min_sec || 480) / 60)}–${Math.round(Number(settings.yt_long_max_sec || 900) / 60)}分`,
status?.api_quota_limited
? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}`
: "9:16 竖屏 · cascade 切短片",
@ -585,7 +587,7 @@ export default function YtLongPage() {
<DailyQuotaGlobalCard
accent="amber"
title="长视频 · 每频道每日上限"
subtitle="全局默认写入「每频道每日上限」;可一键同步到全部长视频频道。母片/总上传上限仍由系统按频道数推算。"
subtitle="全局默认写入「每频道每日上限」;可一键同步到全部长视频频道。母片/总上传上限 = 已启用且已授权频道 × 每频道上限。"
showMin={false}
dailyMin={0}
dailyMax={Number(settings.yt_long_channel_daily_max ?? status?.channel_daily_max ?? 5)}

View File

@ -0,0 +1,83 @@
#!/usr/bin/env bash
# Kill leftover Next.js / npm build orphans that pin VPS CPU after frontend deploys.
# Safe to run every minute via systemd timer.
set +e
FRONTEND_DIR="${DY_FRONTEND_DIR:-/opt/douyinWEB/frontend}"
LOG_TAG="[build-orphan-watch]"
log() { printf '%s %s\n' "$LOG_TAG" "$*"; }
_kill_if_frontend() {
# $1=pid $2=label
local p="$1" label="$2"
local exe cwd
exe=$(readlink /proc/$p/exe 2>/dev/null || true)
cwd=$(readlink /proc/$p/cwd 2>/dev/null || true)
case "$exe$cwd" in
*douyinWEB*|*frontend*|*deleted*)
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed $label pid=$p"
;;
esac
}
# 1) SWC/native binary named "usr" (Next turbopack/swc temp)
killed=0
for p in $(pgrep -x usr 2>/dev/null || true); do
_kill_if_frontend "$p" usr
done
# 1b) Fake "pm2" left in Next build cache (.d* / .r*) — not real PM2 daemon
for p in $(pgrep -x pm2 2>/dev/null || true); do
_kill_if_frontend "$p" pm2
done
# 2) Bare "node" with no args (orphaned build helper) — never touch youtube-svc / next-server
for p in $(pgrep -x node 2>/dev/null || true); do
cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null)
# exact "node" or "node " only
if [ "$cmd" = "node" ] || [ "$cmd" = "node " ]; then
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed bare node pid=$p"
fi
done
# 2b) Any process whose CWD is a Next temp dir under frontend (.d* / .r*)
if [ -d "$FRONTEND_DIR" ]; then
for p in $(ls -1 /proc 2>/dev/null | grep -E '^[0-9]+$' || true); do
cwd=$(readlink /proc/$p/cwd 2>/dev/null || true)
case "$cwd" in
"$FRONTEND_DIR"/.d*|"$FRONTEND_DIR"/.r*)
# Keep next-server / node server.mjs alone if they somehow land here (shouldn't)
cmd=$(tr '\0' ' ' < /proc/$p/cmdline 2>/dev/null)
case "$cmd" in
*next-server*|*server.mjs*|*/.next/standalone*)
;;
*)
kill -9 "$p" 2>/dev/null && killed=$((killed + 1)) && log "killed tempdir pid=$p cwd=$cwd"
;;
esac
;;
esac
done
fi
# 3) Stale Next temp dirs under frontend (.r* and .d* build caches)
if [ -d "$FRONTEND_DIR" ]; then
find "$FRONTEND_DIR" -maxdepth 1 -type d \( -name '.r*' -o -name '.d*' \) -mmin +5 -print0 2>/dev/null \
| xargs -0 -r rm -rf
fi
# 4) If load is insane and Recv-Q on API is climbing, poke api-watch by failing health? No —
# just log load for journal.
load1=$(awk '{print $1}' /proc/loadavg 2>/dev/null)
cores=$(nproc 2>/dev/null || echo 1)
if [ -n "$load1" ]; then
# bash float compare via awk
hot=$(awk -v l="$load1" -v c="$cores" 'BEGIN{print (l+0 >= c*1.5) ? 1 : 0}')
if [ "$hot" = "1" ]; then
log "high_load load1=$load1 cores=$cores killed=$killed"
fi
fi
[ "$killed" -gt 0 ] && log "total_killed=$killed"
exit 0

View File

@ -0,0 +1,22 @@
[Unit]
Description=DouyinWEB residential SOCKS forwarder (isolated from v2ray-agent)
Documentation=file:/opt/douyinWEB/README.md
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
# Binary is DouyinWEB-owned ONLY — never /etc/v2ray-agent/sing-box/sing-box
WorkingDirectory=/opt/douyinWEB/backend
ExecStart=/opt/douyinWEB/bin/sing-box run -c /opt/douyinWEB/config/sing-box.json
Restart=on-failure
RestartSec=3
Nice=5
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true
ReadOnlyPaths=/etc/v2ray-agent
[Install]
WantedBy=multi-user.target