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,6 +180,9 @@ 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
# 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)
@ -182,8 +190,7 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
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"])
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
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)
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,12 +91,47 @@ 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:
@ -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,30 +42,45 @@ 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 "residential" if _is_vps_host(s) else "shellcrash"
if _is_vps_host(s):
return "off"
return "shellcrash"
# Default ON for China physical: all non-Douyin business via ShellCrash.
# Explicit "off" in settings still wins (handled above via MODES).
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)
# Soft path: ShellCrash still running on physical while mode off
if not _is_vps_host(cfg):
try:
from . import shellcrash_hub
@ -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,41 +191,47 @@ 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
if mode == "residential":
port = LOCAL_MIXED_PORT
else:
port = shellcrash_mixed_port(cfg)
text = (
"strict_chain\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
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

@ -43,9 +43,10 @@ def status() -> dict[str, Any]:
"profiles": list(PROFILES),
"effects": {
"vps": [
"egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)",
"本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)",
"单路独占默认开启(省内存;可配对物理机 ops-neko)",
"默认机房 IP 直出;可选「静态住宅 IP」经 douyinweb-singbox :17891",
"绝不操作宿主机 sing-box.service(v2ray-agent)",
"本机分配 Neko 仍可按频道启停",
"单路独占默认开启(省内存)",
],
"physical": [
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",

View File

@ -86,7 +86,23 @@ def classify_job_error(error: str = "", *, platform: str = "") -> dict[str, Any]
"action_label": "重新授权",
"retryable": False,
}
if plat == "tiktok" and hit("机房", "datacenter", "tt-target-idc", "project"):
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 机房不匹配",

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":
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)
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

@ -99,7 +99,9 @@ def socks_status() -> dict[str, Any]:
"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",
"unit": "douyinweb-singbox",
"v2ray_agent": singbox_manager.host_v2ray_agent_status(),
"hint": "美国 VPS:填 SOCKS 后开「静态住宅 IP」;永不重启宿主机 sing-box.service",
}

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,12 +550,36 @@ 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:
from . import egress_hub
proxies = egress_hub.google_http_proxy_candidates()
except Exception:
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},
@ -458,8 +587,11 @@ async def token_scopes(access_token: str) -> set[str]:
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:
return set()
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,7 +79,18 @@ 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:
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={
@ -81,8 +102,17 @@ async def refresh_access_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}")
# 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 _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():
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:
"""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": "",
}

View File

@ -186,6 +186,34 @@ def tiktok_channel_upload_count(channel_pk: str, push_date: str) -> int:
conn.close()
def tiktok_channel_uploaded_count(channel_pk: str, push_date: str) -> int:
"""Successfully published today (auto upload gate — excludes backlog scheduled)."""
with _lock:
conn = _connect()
try:
row = conn.execute(
"""
SELECT COUNT(*) AS c FROM tiktok_jobs
WHERE channel_pk = ? AND push_date = ?
AND status IN ('uploaded', 'done')
""",
(channel_pk, push_date),
).fetchone()
return int(row["c"]) if row else 0
finally:
conn.close()
def channel_at_daily_upload_max(channel_pk: str, push_date: str = "") -> bool:
"""True when this account already hit daily_max successful uploads today."""
day = push_date or push_date_from_ts(time.time())
ch = get_tiktok_channel(channel_pk)
if not ch:
return True
daily_max = _force_daily(int(ch.get("daily_max") or TIKTOK_DAILY_FORCE))
return tiktok_channel_uploaded_count(channel_pk, day) >= daily_max
def pick_tiktok_channel(
push_date: str,
*,
@ -340,6 +368,7 @@ def update_tiktok_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
allowed = {
"status", "clip_path", "clip_seconds", "tiktok_publish_id", "tiktok_video_id",
"error", "channel_pk", "stream_url", "attempts", "started_at", "finished_at", "upload_at",
"push_date",
}
with _lock:
conn = _connect()
@ -578,8 +607,9 @@ def claim_tiktok_limit_probe_job(channel_pk: str) -> dict[str, Any] | None:
def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
"""Clear legacy soft-quota hold messages and put clips back on the upload schedule."""
"""Clear soft-quota holds only when the account still has remaining daily_max slots."""
now = time.time()
today = push_date_from_ts(now)
n = 0
with _lock:
conn = _connect()
@ -587,7 +617,7 @@ def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
rows = conn.execute(
"""
SELECT id, channel_pk FROM tiktok_jobs
WHERE status = 'recorded'
WHERE status IN ('recorded', 'scheduled')
AND clip_path != ''
AND IFNULL(tiktok_video_id,'') = ''
AND (error LIKE '%配额已满%')
@ -596,31 +626,22 @@ def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
""",
(max(1, int(limit)),),
).fetchall()
for row in rows:
jid = str(row["id"])
conn.execute(
"""
UPDATE tiktok_jobs
SET status = 'scheduled', upload_at = ?, error = '', updated_at = ?
WHERE id = ? AND status = 'recorded'
""",
(now + 30 + n * 120, now, jid),
)
if conn.total_changes:
n += 1
# Also clear soft-quota message on already-scheduled rows
conn.execute(
"""
UPDATE tiktok_jobs
SET error = '', updated_at = ?
WHERE error LIKE '%配额已满%'
AND status IN ('scheduled', 'recorded')
""",
(now,),
)
conn.commit()
finally:
conn.close()
for row in rows:
jid = str(row["id"])
ch_pk = str(row["channel_pk"] or "")
if ch_pk and channel_at_daily_upload_max(ch_pk, today):
defer_tiktok_job_to_next_day(jid, stagger_sec=90 + n * 60)
n += 1
continue
update_tiktok_job(
jid,
status="scheduled",
upload_at=now + 30 + n * 120,
error="",
)
n += 1
return n
@ -657,12 +678,31 @@ def delete_tiktok_jobs_for_channel(channel_pk: str) -> dict[str, int]:
return {"jobs": jobs, "clips": clips}
def defer_tiktok_job_to_next_day(job_id: str, *, stagger_sec: float = 60) -> None:
"""Move a clip to the next Beijing day so it consumes tomorrow's quota, not today's."""
from .timeutil import beijing_day_bounds
today = push_date_from_ts(time.time())
next_start = beijing_day_bounds(today)[1]
next_day = push_date_from_ts(next_start + 1)
update_tiktok_job(
job_id,
status="scheduled",
push_date=next_day,
upload_at=next_start + max(30.0, float(stagger_sec)),
error="账号今日配额已满,已延到次日",
)
def claim_due_tiktok_upload() -> dict[str, Any] | None:
"""Claim next due scheduled upload, skipping accounts already at daily_max published today."""
now = time.time()
today = push_date_from_ts(now)
# Try a few candidates: defer over-quota rows then pick the next.
for i in range(8):
with _lock:
conn = _connect()
try:
# Skip disabled accounts and accounts under TikTok platform rate-limit
row = conn.execute(
"""
SELECT j.* FROM tiktok_jobs j
@ -683,10 +723,19 @@ def claim_due_tiktok_upload() -> dict[str, Any] | None:
if not row:
return None
jid = str(row["id"])
ch_pk = str(row["channel_pk"] or "")
finally:
conn.close()
if ch_pk and channel_at_daily_upload_max(ch_pk, today):
defer_tiktok_job_to_next_day(jid, stagger_sec=60 + i * 90)
continue
with _lock:
conn = _connect()
try:
conn.execute(
"""
UPDATE tiktok_jobs
SET status = 'uploading', updated_at = ?, attempts = attempts + 1
SET status = 'uploading', updated_at = ?, attempts = attempts + 1, error = ''
WHERE id = ? AND status = 'scheduled'
AND IFNULL(tiktok_video_id,'') = ''
AND IFNULL(tiktok_publish_id,'') = ''
@ -695,11 +744,12 @@ def claim_due_tiktok_upload() -> dict[str, Any] | None:
)
if conn.total_changes == 0:
conn.rollback()
return None
continue
conn.commit()
return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone())
finally:
conn.close()
return None
def claim_tiktok_job_manual_upload(job_id: str) -> dict[str, Any] | None:

View File

@ -390,11 +390,16 @@ class TikTokPipeline:
retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300))
if cfg.get("tiktok_auto_retry_failed") and (time.time() - self._last_auto_retry_at) >= retry_interval:
self._last_auto_retry_at = time.time()
today = push_date_from_ts(time.time())
for j in tiktok_db.list_auto_retry_tiktok_failed(limit=10):
ch_pk = str(j.get("channel_pk") or "")
if ch_pk and tiktok_db.channel_at_daily_upload_max(ch_pk, today):
tiktok_db.defer_tiktok_job_to_next_day(str(j["id"]), stagger_sec=120)
continue
tiktok_db.update_tiktok_job(
str(j["id"]),
status="scheduled",
upload_at=pick_upload_at(channel_pk=str(j.get("channel_pk") or ""), cfg=cfg),
upload_at=pick_upload_at(channel_pk=ch_pk, cfg=cfg),
error="",
)
try:
@ -659,6 +664,11 @@ class TikTokPipeline:
tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传")
return
ch_pk = str(channel["id"])
day = str(fresh.get("push_date") or push_date_from_ts(time.time()))
if not manual and not probe and tiktok_db.channel_at_daily_upload_max(ch_pk):
# Auto path must respect per-account daily_max (manual upload-now may bypass).
tiktok_db.defer_tiktok_job_to_next_day(jid, stagger_sec=90)
return
if (
not manual
and not probe

View File

@ -19,7 +19,7 @@ if str(_VENDOR_ROOT) not in sys.path:
DEFAULT_DC = "useast2a"
COOKIE_TTL_DAYS = 30.0
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
_DC_CANDIDATES = ("useast5a", "useast1a", "useast2a", "euwest1a", "alisg", "no1a", "useast8")
_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"

View File

@ -85,20 +85,26 @@ def socks_proxy_url(profile: dict[str, Any] | None) -> str:
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 ""
"""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 not enabled:
return ""
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
return socks_proxy_url(prof)
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]]:

View File

@ -111,6 +111,14 @@ def _http_channel_live_probe(channel_id: str) -> dict[str, Any]:
html = ""
last_err = ""
proxies_try: list[str] = []
try:
from . import egress_hub
hub_proxy = str(egress_hub.google_http_proxy() or "").strip()
if hub_proxy:
proxies_try.append(hub_proxy)
except Exception:
pass
env_proxy = (
str(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "").strip()
or str(os.environ.get("HTTP_PROXY") or os.environ.get("http_proxy") or "").strip()
@ -118,9 +126,10 @@ def _http_channel_live_probe(channel_id: str) -> dict[str, Any]:
if env_proxy:
proxies_try.append(env_proxy)
proxies_try.append("") # direct
# Physical China guest: ShellCrash (same as douyinweb-yt) if env unset / direct fails
if "127.0.0.1:7890" not in env_proxy:
proxies_try.append("http://127.0.0.1:7890")
# Soft fallbacks (physical ShellCrash / legacy) — only if not already listed
for soft in ("http://127.0.0.1:17891", "http://127.0.0.1:7890"):
if soft not in proxies_try:
proxies_try.append(soft)
seen_p: set[str] = set()
for proxy in proxies_try:
if proxy in seen_p:

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_enabled_upload_cap(settings)
if upload_cap <= 0:
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))
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:
db.update_settings_map({"yt_long_daily_max": global_max})
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(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),
)
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()
return int(cur.rowcount or 0)
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,7 +1,14 @@
# -*- coding: utf-8 -*-
"""YouTube long-form upload — same OAuth transport as Shorts, watch URL not /shorts/."""
"""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
@ -14,6 +21,35 @@ from .shorts_upload import (
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(
*,
@ -37,21 +73,19 @@ async def upload_youtube_long_mp4(
)
try:
size = path.stat().st_size
raw = path.read_bytes()
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).
# 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]
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 or "Live clip",
"description": description or "",
"title": clean_title,
"description": clean_desc,
"categoryId": "22",
},
"status": {
@ -63,7 +97,8 @@ async def upload_youtube_long_mp4(
"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:
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={
@ -79,7 +114,12 @@ async def upload_youtube_long_mp4(
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={
@ -87,13 +127,15 @@ async def upload_youtube_long_mp4(
"Content-Type": "video/mp4",
"Content-Length": str(size),
},
content=raw,
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 {
@ -101,4 +143,6 @@ async def upload_youtube_long_mp4(
"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"
}
}

View File

@ -10,7 +10,7 @@
"dependencies": {
"echarts": "^5.5.1",
"lucide-react": "^0.468.0",
"next": "15.1.0",
"next": "15.1.11",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
@ -20,7 +20,7 @@
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9",
"eslint-config-next": "15.1.0",
"eslint-config-next": "15.1.11",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"
@ -388,9 +388,6 @@
"cpu": [
"arm"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -407,9 +404,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -426,9 +420,6 @@
"cpu": [
"s390x"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -445,9 +436,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -464,9 +452,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -483,9 +468,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "LGPL-3.0-or-later",
"optional": true,
"os": [
@ -502,9 +484,6 @@
"cpu": [
"arm"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -527,9 +506,6 @@
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -552,9 +528,6 @@
"cpu": [
"s390x"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -577,9 +550,6 @@
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -602,9 +572,6 @@
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -627,9 +594,6 @@
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "Apache-2.0",
"optional": true,
"os": [
@ -764,15 +728,15 @@
}
},
"node_modules/@next/env": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.1.0.tgz",
"integrity": "sha512-UcCO481cROsqJuszPPXJnb7GGuLq617ve4xuAyyNG4VSSocJNtMU5Fsx+Lp6mlN8c7W58aZLc5y6D/2xNmaK+w==",
"version": "15.1.11",
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.1.11.tgz",
"integrity": "sha512-yp++FVldfLglEG5LoS2rXhGypPyoSOyY0kxZQJ2vnlYJeP8o318t5DrDu5Tqzr03qAhDWllAID/kOCsXNLcwKw==",
"license": "MIT"
},
"node_modules/@next/eslint-plugin-next": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-15.1.0.tgz",
"integrity": "sha512-+jPT0h+nelBT6HC9ZCHGc7DgGVy04cv4shYdAe6tKlEbjQUtwU3LzQhzbDHQyY2m6g39m6B0kOFVuLGBrxxbGg==",
"version": "15.1.11",
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-15.1.11.tgz",
"integrity": "sha512-jpAu+46v5FF/TO8YUdOBHn/Wr4SCiU4IgjQ45S9Nn3vR4nZVS2SR+m9lpxcCv/xqMUoYuYFQZUP0H/ptw0W6+w==",
"dev": true,
"license": "MIT",
"dependencies": {
@ -780,9 +744,9 @@
}
},
"node_modules/@next/swc-darwin-arm64": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.1.0.tgz",
"integrity": "sha512-ZU8d7xxpX14uIaFC3nsr4L++5ZS/AkWDm1PzPO6gD9xWhFkOj2hzSbSIxoncsnlJXB1CbLOfGVN4Zk9tg83PUw==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.1.9.tgz",
"integrity": "sha512-sQF6MfW4nk0PwMYYq8xNgqyxZJGIJV16QqNDgaZ5ze9YoVzm4/YNx17X0exZudayjL9PF0/5RGffDtzXapch0Q==",
"cpu": [
"arm64"
],
@ -796,9 +760,9 @@
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.1.0.tgz",
"integrity": "sha512-DQ3RiUoW2XC9FcSM4ffpfndq1EsLV0fj0/UY33i7eklW5akPUCo6OX2qkcLXZ3jyPdo4sf2flwAED3AAq3Om2Q==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.1.9.tgz",
"integrity": "sha512-fp0c1rB6jZvdSDhprOur36xzQvqelAkNRXM/An92sKjjtaJxjlqJR8jiQLQImPsClIu8amQn+ZzFwl1lsEf62w==",
"cpu": [
"x64"
],
@ -812,15 +776,12 @@
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.1.0.tgz",
"integrity": "sha512-M+vhTovRS2F//LMx9KtxbkWk627l5Q7AqXWWWrfIzNIaUFiz2/NkOFkxCFyNyGACi5YbA8aekzCLtbDyfF/v5Q==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.1.9.tgz",
"integrity": "sha512-77rYykF6UtaXvxh9YyRIKoaYPI6/YX6cy8j1DL5/1XkjbfOwFDfTEhH7YGPqG/ePl+emBcbDYC2elgEqY2e+ag==",
"cpu": [
"arm64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -831,15 +792,12 @@
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.1.0.tgz",
"integrity": "sha512-Qn6vOuwaTCx3pNwygpSGtdIu0TfS1KiaYLYXLH5zq1scoTXdwYfdZtwvJTpB1WrLgiQE2Ne2kt8MZok3HlFqmg==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.1.9.tgz",
"integrity": "sha512-uZ1HazKcyWC7RA6j+S/8aYgvxmDqwnG+gE5S9MhY7BTMj7ahXKunpKuX8/BA2M7OvINLv7LTzoobQbw928p3WA==",
"cpu": [
"arm64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -850,15 +808,12 @@
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.1.0.tgz",
"integrity": "sha512-yeNh9ofMqzOZ5yTOk+2rwncBzucc6a1lyqtg8xZv0rH5znyjxHOWsoUtSq4cUTeeBIiXXX51QOOe+VoCjdXJRw==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.1.9.tgz",
"integrity": "sha512-gQIX1d3ct2RBlgbbWOrp+SHExmtmFm/HSW1Do5sSGMDyzbkYhS2sdq5LRDJWWsQu+/MqpgJHqJT6ORolKp/U1g==",
"cpu": [
"x64"
],
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -869,15 +824,12 @@
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.1.0.tgz",
"integrity": "sha512-t9IfNkHQs/uKgPoyEtU912MG6a1j7Had37cSUyLTKx9MnUpjj+ZDKw9OyqTI9OwIIv0wmkr1pkZy+3T5pxhJPg==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.1.9.tgz",
"integrity": "sha512-fJOwxAbCeq6Vo7pXZGDP6iA4+yIBGshp7ie2Evvge7S7lywyg7b/SGqcvWq/jYcmd0EbXdb7hBfdqSQwTtGTPg==",
"cpu": [
"x64"
],
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -888,9 +840,9 @@
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.1.0.tgz",
"integrity": "sha512-WEAoHyG14t5sTavZa1c6BnOIEukll9iqFRTavqRVPfYmfegOAd5MaZfXgOGG6kGo1RduyGdTHD4+YZQSdsNZXg==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.1.9.tgz",
"integrity": "sha512-crfbUkAd9PVg9nGfyjSzQbz82dPvc4pb1TeP0ZaAdGzTH6OfTU9kxidpFIogw0DYIEadI7hRSvuihy2NezkaNQ==",
"cpu": [
"arm64"
],
@ -904,9 +856,9 @@
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.1.0.tgz",
"integrity": "sha512-J1YdKuJv9xcixzXR24Dv+4SaDKc2jj31IVUEMdO5xJivMTXuE6MAdIi4qPjSymHuFG8O5wbfWKnhJUcHHpj5CA==",
"version": "15.1.9",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.1.9.tgz",
"integrity": "sha512-SBB0oA4E2a0axUrUwLqXlLkSn+bRx9OWU6LheqmRrO53QEAJP7JquKh3kF0jRzmlYOWFZtQwyIWJMEJMtvvDcQ==",
"cpu": [
"x64"
],
@ -1460,9 +1412,6 @@
"arm64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1477,9 +1426,6 @@
"arm64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1494,9 +1440,6 @@
"loong64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1511,9 +1454,6 @@
"loong64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1528,9 +1468,6 @@
"ppc64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1545,9 +1482,6 @@
"riscv64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1562,9 +1496,6 @@
"riscv64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -1579,9 +1510,6 @@
"s390x"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1596,9 +1524,6 @@
"x64"
],
"dev": true,
"libc": [
"glibc"
],
"license": "MIT",
"optional": true,
"os": [
@ -1613,9 +1538,6 @@
"x64"
],
"dev": true,
"libc": [
"musl"
],
"license": "MIT",
"optional": true,
"os": [
@ -2898,13 +2820,13 @@
}
},
"node_modules/eslint-config-next": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-15.1.0.tgz",
"integrity": "sha512-gADO+nKVseGso3DtOrYX9H7TxB/MuX7AUYhMlvQMqLYvUWu4HrOQuU7cC1HW74tHIqkAvXdwgAz3TCbczzSEXw==",
"version": "15.1.11",
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-15.1.11.tgz",
"integrity": "sha512-RK5q3f8CKMTwNXULOqd2TAsz+7kA5+5fy5YK7T6SeczLFOuOUcuJOGlYUbyoeU6+UKQrpFsYgCz71hI1F9q5Cg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@next/eslint-plugin-next": "15.1.0",
"@next/eslint-plugin-next": "15.1.11",
"@rushstack/eslint-patch": "^1.10.3",
"@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
"@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
@ -4527,13 +4449,12 @@
"license": "MIT"
},
"node_modules/next": {
"version": "15.1.0",
"resolved": "https://registry.npmjs.org/next/-/next-15.1.0.tgz",
"integrity": "sha512-QKhzt6Y8rgLNlj30izdMbxAwjHMFANnLwDwZ+WQh5sMhyt4lEBqDK9QpvWHtIM4rINKPoJ8aiRZKg5ULSybVHw==",
"deprecated": "This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/CVE-2025-66478 for more details.",
"version": "15.1.11",
"resolved": "https://registry.npmjs.org/next/-/next-15.1.11.tgz",
"integrity": "sha512-UiVJaOGhKST58AadwbFUZThlNBmYhKqaCs8bVtm4plTxsgKq0mJ0zTsp7t7j/rzsbAEj9WcAMdZCztjByi4EoQ==",
"license": "MIT",
"dependencies": {
"@next/env": "15.1.0",
"@next/env": "15.1.11",
"@swc/counter": "0.1.3",
"@swc/helpers": "0.5.15",
"busboy": "1.6.0",
@ -4548,14 +4469,14 @@
"node": "^18.18.0 || ^19.8.0 || >= 20.0.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "15.1.0",
"@next/swc-darwin-x64": "15.1.0",
"@next/swc-linux-arm64-gnu": "15.1.0",
"@next/swc-linux-arm64-musl": "15.1.0",
"@next/swc-linux-x64-gnu": "15.1.0",
"@next/swc-linux-x64-musl": "15.1.0",
"@next/swc-win32-arm64-msvc": "15.1.0",
"@next/swc-win32-x64-msvc": "15.1.0",
"@next/swc-darwin-arm64": "15.1.9",
"@next/swc-darwin-x64": "15.1.9",
"@next/swc-linux-arm64-gnu": "15.1.9",
"@next/swc-linux-arm64-musl": "15.1.9",
"@next/swc-linux-x64-gnu": "15.1.9",
"@next/swc-linux-x64-musl": "15.1.9",
"@next/swc-win32-arm64-msvc": "15.1.9",
"@next/swc-win32-x64-msvc": "15.1.9",
"sharp": "^0.33.5"
},
"peerDependencies": {

View File

@ -11,7 +11,7 @@
"dependencies": {
"echarts": "^5.5.1",
"lucide-react": "^0.468.0",
"next": "15.1.0",
"next": "15.1.11",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
@ -21,7 +21,7 @@
"@types/react-dom": "^19",
"autoprefixer": "^10.4.20",
"eslint": "^9",
"eslint-config-next": "15.1.0",
"eslint-config-next": "15.1.11",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.17",
"typescript": "^5"

View File

@ -23,6 +23,7 @@ type ScRoot = { root_id: string; label: string; file_count: number; files?: ScFi
type EgressPayload = {
mode?: string;
chain_residential?: boolean;
host_profile?: string;
modes?: Array<{ id: string; label: string; description?: string; ready?: boolean }>;
cover?: { neko?: boolean; relay?: boolean; uploads?: boolean };
host_proxy?: string;
@ -32,6 +33,8 @@ type EgressPayload = {
matrix?: Array<{ id: string; label: string; active?: boolean; detail?: string }>;
proxychains?: { installed?: boolean; relay_active?: boolean; bin?: string };
shellcrash?: { running?: boolean; mixed_port?: string; selected_node?: string | null };
douyinweb_singbox?: { running?: boolean; unit?: string; mixed?: string; config?: string };
v2ray_agent?: { unit?: string; active?: string; config_dir_exists?: boolean; note?: string };
hints?: string[];
};
@ -126,7 +129,7 @@ export default function NetworkPage() {
const [filePath, setFilePath] = useState("");
const [fileContent, setFileContent] = useState("");
const [fileImportKey, setFileImportKey] = useState(0);
const [egressMode, setEgressMode] = useState<"off" | "shellcrash">("off");
const [egressMode, setEgressMode] = useState<"off" | "shellcrash" | "residential">("off");
const [chainResidential, setChainResidential] = useState(false);
const [coverNeko, setCoverNeko] = useState(true);
const [coverRelay, setCoverRelay] = useState(true);
@ -185,7 +188,7 @@ export default function NetworkPage() {
/* editor stays empty if unreadable */
}
const mode = String(r.egress?.mode || "off");
setEgressMode(mode === "shellcrash" ? "shellcrash" : "off");
setEgressMode(mode === "residential" || mode === "shellcrash" ? mode : "off");
setChainResidential(Boolean(r.egress?.chain_residential));
setCoverNeko(r.egress?.cover?.neko !== false);
setCoverRelay(Boolean(r.egress?.cover?.relay));
@ -217,18 +220,22 @@ export default function NetworkPage() {
async function applyEgress() {
setBusy("egress:apply");
try {
// refresh_neko=false: recreating Neko compose often hangs the request (timeout).
// Proxy env is picked up on next Neko start; residential apply must stay fast.
await fetchJson("/api/network/egress", {
method: "PATCH",
body: JSON.stringify({
mode: egressMode,
chain_residential: chainResidential,
cover: { neko: coverNeko, relay: coverRelay, uploads: coverUploads },
refresh_neko: true,
refresh_neko: false,
}),
});
toast.push(
egressMode === "off"
? "已切回直连"
? "已切回机房直连"
: egressMode === "residential"
? "已启用静态住宅 IP(:17891)"
: chainResidential
? "已启用 ShellCrash + 住宅链式落地"
: "已启用 ShellCrash 机场线路",
@ -250,7 +257,7 @@ export default function NetworkPage() {
};
setProbes(r.probes || []);
const ok = (r.probes || []).some((p) => p.target === "google" && p.ok);
toast.push(ok ? "出海探测成功" : "探测未通,检查 ShellCrash / SOCKS", ok ? "ok" : "err");
toast.push(ok ? "出口探测成功" : "探测未通,检查住宅 SOCKS / 本机 :17891", ok ? "ok" : "err");
} catch (e) {
toast.push((e as Error).message, "err");
} finally {
@ -501,7 +508,7 @@ export default function NetworkPage() {
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h1 className="font-display text-2xl font-semibold text-white">网络</h1>
<p className="mt-1 text-sm text-slate-400">业务出海 · ShellCrash · SOCKS · WireGuard · FRP</p>
<p className="mt-1 text-sm text-slate-400">静态住宅 IP · 业务出海 · SOCKS · WireGuard · FRP</p>
</div>
<button type="button" className={`inline-flex items-center gap-1.5 ${btnGhost}`} onClick={() => void load()}>
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
@ -515,22 +522,24 @@ export default function NetworkPage() {
</div>
) : (
<>
{/* ===== 业务出海 ===== */}
{/* ===== 业务出海 / 静态住宅 ===== */}
<section className="overflow-hidden rounded-2xl border border-cyan-400/20 bg-gradient-to-br from-cyan-500/10 via-black/40 to-teal-500/5 p-4 sm:p-5">
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h2 className="text-lg font-semibold text-white">业务出海</h2>
<h2 className="text-lg font-semibold text-white">静态住宅 IP(业务全局)</h2>
<p className="mt-1 text-xs text-slate-400">
统一走 ShellCrash(:7890)。硬规则:<span className="text-emerald-200">*.douyin.com 必须直连</span>
;YouTube 出海。家宽不能直连海外住宅 SOCKS——勾选「住宅落地」= dialer-proxy 链式。
美国 VPS:默认机房 IP 直出。启用后 YT 直播/长视频/Shorts、TikTok、X/Neko 统一经本机{" "}
<span className="font-mono text-cyan-200">:17891</span> → 住宅 SOCKS。
<span className="text-emerald-200"> 抖音始终直连</span>;
<span className="text-amber-200"> 不改动 v2ray-agent 的 sing-box.service</span>。
</p>
</div>
<div className="flex flex-wrap gap-2">
<button type="button" className={btnGhost} disabled={!!busy} onClick={() => void probeEgress()}>
{busy === "egress:probe" ? "探测中…" : "探测 Google / YouTube"}
{busy === "egress:probe" ? "探测中…" : "探测出口 IP"}
</button>
<button type="button" className={`${btn} bg-cyan-600`} disabled={!!busy} onClick={() => void applyEgress()}>
{busy === "egress:apply" ? "应用中…" : "应用出海"}
{busy === "egress:apply" ? "应用中…" : "应用"}
</button>
</div>
</div>
@ -540,15 +549,25 @@ export default function NetworkPage() {
[
{
id: "off" as const,
title: "直连",
desc: "不经 ShellCrash,国内机器上 YouTube 通常不可用",
title: "机房直连",
desc: "默认 · 业务用美国 VPS 机房 IP(已可访问 Google/YouTube)",
},
{
id: "residential" as const,
title: "静态住宅 IP",
desc: "douyinweb-singbox → 下方 SOCKS 账号;Neko 用无认证本机 HTTP,不伤 v2ray-agent",
ready: Boolean(eg?.douyinweb_singbox?.running || data?.socks?.profiles?.length),
},
...(eg?.host_profile === "physical" || eg?.modes?.some((m) => m.id === "shellcrash")
? [
{
id: "shellcrash" as const,
title: "ShellCrash",
desc: "推荐 · Neko / 推流 / 上传全部进 :7890,由规则分流",
title: "ShellCrash(物理机)",
desc: "家宽出海 :7890;可选 dialer 链式住宅",
ready: Boolean(eg?.shellcrash?.running || sc?.running),
},
]
: []),
] as const
).map((m) => {
const active = egressMode === m.id;
@ -558,11 +577,18 @@ export default function NetworkPage() {
type="button"
onClick={() => {
setEgressMode(m.id);
if (m.id === "shellcrash") {
if (m.id === "residential" || m.id === "shellcrash") {
setCoverRelay(true);
setCoverNeko(true);
setCoverUploads(true);
}
if (m.id === "residential") {
setSocksEnabled(true);
setChainResidential(false);
}
if (m.id === "off") {
setSocksEnabled(false);
}
}}
className={`rounded-2xl border p-4 text-left transition ${
active
@ -584,6 +610,7 @@ export default function NetworkPage() {
})}
</div>
{egressMode === "shellcrash" ? (
<div
className={`mt-4 rounded-xl border px-4 py-3 ${
egressMode === "shellcrash"
@ -603,22 +630,26 @@ export default function NetworkPage() {
}}
/>
<span>
<span className="font-medium text-amber-100">住宅落地(ShellCrash 链式代理)</span>
<span className="font-medium text-amber-100">住宅落地(ShellCrash 链式代理 · 物理机)</span>
<span className="mt-1 block text-xs text-slate-400">
不勾选:用机场节点出海。勾选:写入 <span className="font-mono">dy-residential</span>
(socks5 + dialer-proxy → {eg?.dialer || "dialer"}),经前置节点再连住宅 SOCKS。账号在下方「业务 SOCKS」填写。
美国 VPS 请用上方「静态住宅 IP」,不要用链式。
</span>
</span>
</label>
{eg?.exit_node ? (
<p className="mt-2 font-mono text-[11px] text-slate-400">当前出口节点:{eg.exit_node}</p>
) : null}
</div>
) : null}
{eg?.v2ray_agent ? (
<p className="mt-3 font-mono text-[11px] text-slate-500">
v2ray-agent sing-box.service(只读): {String((eg.v2ray_agent as { active?: string }).active || "—")} ·
DouyinWEB 单元: {eg.douyinweb_singbox?.running ? "douyinweb-singbox 运行中" : "douyinweb-singbox 未启"}
</p>
) : null}
<div className="mt-4 flex flex-wrap gap-4 rounded-xl border border-white/10 bg-black/25 px-4 py-3 text-sm text-slate-300">
<label className="inline-flex items-center gap-2">
<input type="checkbox" checked={coverNeko} onChange={(e) => setCoverNeko(e.target.checked)} />
Neko Chrome
Neko / X 浏览器
</label>
<label className="inline-flex items-center gap-2">
<input type="checkbox" checked={coverRelay} onChange={(e) => setCoverRelay(e.target.checked)} />
@ -626,7 +657,7 @@ export default function NetworkPage() {
</label>
<label className="inline-flex items-center gap-2">
<input type="checkbox" checked={coverUploads} onChange={(e) => setCoverUploads(e.target.checked)} />
Shorts / 长视频上传
Shorts / 长视频 / TikTok
</label>
</div>
@ -668,6 +699,9 @@ export default function NetworkPage() {
</div>
<p className="mt-1 font-mono text-slate-500">
{p.http_code} · {p.elapsed_ms}ms · {p.via === "direct" || !p.via ? "直连" : "代理"}
{"body" in p && (p as { body?: string }).body
? ` · ${(p as { body?: string }).body}`
: ""}
</p>
</div>
))}
@ -836,9 +870,9 @@ export default function NetworkPage() {
<article className="rounded-2xl border border-white/10 bg-black/25 p-4 sm:p-5 xl:col-span-4">
<div className="flex items-start justify-between gap-2">
<div>
<h2 className="text-lg font-semibold text-white">业务 SOCKS(住宅落地账号)</h2>
<h2 className="text-lg font-semibold text-white">业务 SOCKS(静态住宅账号)</h2>
<p className="mt-1 text-xs text-slate-400">
仅在出海勾选「住宅落地」时使用:写入 ShellCrash 链式节点,经 dialer 前置再连此 SOCKS。家宽不会直连它。
填写供应商 SOCKS5。启用「静态住宅 IP」后由 douyinweb-singbox 转发到此账号;账号不会进 Chrome URL。
</p>
</div>
<span
@ -865,7 +899,7 @@ export default function NetworkPage() {
<label className="mt-4 flex items-center gap-2 text-sm text-slate-300">
<input type="checkbox" checked={socksEnabled} onChange={(e) => setSocksEnabled(e.target.checked)} />
启用为住宅链式账号(与上方「住宅落地」同步)
启用静态住宅账号(与上方「静态住宅 IP」联动)
</label>
<div className="mt-3 flex flex-wrap gap-2">

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