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:
parent
3d417382f0
commit
1e8eb0130a
63
README.md
63
README.md
@ -104,7 +104,7 @@ cd desktop && npm install && npm run electron:dev
|
|||||||
| 脚本 | `scripts/bootstrap_vps.sh` |
|
| 脚本 | `scripts/bootstrap_vps.sh` |
|
||||||
| TLS | 本机 Nginx / 宝塔 / Caddy → `127.0.0.1:4015/8014` |
|
| TLS | 本机 Nginx / 宝塔 / Caddy → `127.0.0.1:4015/8014` |
|
||||||
| 进程绑定 | 通常 `127.0.0.1` |
|
| 进程绑定 | 通常 `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 |
|
| ShellCrash | **不是**默认栈;不要在纯 VPS 上假设有 `:7890` ShellCrash |
|
||||||
| Neko WebRTC | `NEKO_WEBRTC_NAT1TO1` / `DY_NEKO_NAT1TO1` = **本机公网 IP**;UDP/TCP mux 在本机安全组放行(无第二跳 DNAT) |
|
| Neko WebRTC | `NEKO_WEBRTC_NAT1TO1` / `DY_NEKO_NAT1TO1` = **本机公网 IP**;UDP/TCP mux 在本机安全组放行(无第二跳 DNAT) |
|
||||||
| 边缘 Caddy | 不需要 `bootstrap_physical_edge.sh` |
|
| 边缘 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 **隔离共存**
|
- **全局 SOCKS5**(默认关,目标方案见 [全局 SOCKS5(sing-box + proxychains)](#全局-socks5sing-box--proxychains)):静态住宅 IP;规划覆盖 Shorts / 长视频 / TikTok / X / Neko / FFmpeg;与 v2ray-agent 翻墙 sing-box **隔离共存**
|
||||||
- **频道级联清理**:删除 Shorts 频道时同步删除关联任务与本地成片;孤儿任务可运维 purge
|
- **频道级联清理**:删除 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)
|
#### 分发台全局每日配额(Shorts / 长视频 / TikTok / X)
|
||||||
|
|
||||||
各业务页顶部 **DailyQuotaGlobalCard**:在保留「单频道编辑」的前提下,可一次改默认并可选同步全部频道。
|
各业务页顶部 **DailyQuotaGlobalCard**:在保留「单频道编辑」的前提下,可一次改默认并可选同步全部频道。
|
||||||
@ -416,6 +460,10 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
|
|||||||
|
|
||||||
长视频后台 `reconcile_yt_long_upload_caps` **不得**把操作员保存的上限强行改回 5;仅在 API 限流日对「高于有效上限」的频道做软封顶。
|
长视频后台 `reconcile_yt_long_upload_caps` **不得**把操作员保存的上限强行改回 5;仅在 API 限流日对「高于有效上限」的频道做软封顶。
|
||||||
|
|
||||||
|
#### 配额口径(Shorts / 长视频)
|
||||||
|
|
||||||
|
控制台顶部「北京日配额 / YouTube 上传 / 母片录制」**只合计已启用**频道(停用的 Client B 等不计入)。后端缺口与取样同样只看 `enabled=1`。长视频母片上限 = 已启用 oauth 长视频频道 × 每频道日上限,**不再**按 Shorts 舰队规模抬高。
|
||||||
|
|
||||||
#### YouTube 直播状态(receiving-first)
|
#### 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`。
|
首页 / 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)
|
#### 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 |
|
| 剪辑让路 | `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 已外置) |
|
| 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 余量) |
|
| 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 |
|
| 看门狗 | `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)
|
#### 时段排除名单(timeslot exclude)
|
||||||
|
|
||||||
@ -505,7 +555,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
|
|||||||
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
|
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
|
||||||
| `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 |
|
| `/youtube` → **分配** | Pro 转播:KEY / 精选源 / 时间段 / Neko / FFmpeg 实况 |
|
||||||
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
|
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
|
||||||
| `/yt-long` | 长视频成片 / 上传 |
|
| `/yt-long` | 长视频成片 / 上传(**8–15 分钟**随机母片 → YouTube 长视频) |
|
||||||
| `/yt-revenue` | YPP 预估创收(需 monetary OAuth) |
|
| `/yt-revenue` | YPP 预估创收(需 monetary OAuth) |
|
||||||
| `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 |
|
| `/settings` | 防风控、通知、静默、YT/Shorts、**全局 SOCKS5**、改密、PB/S3 运维 |
|
||||||
| `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 |
|
| `/ops` | 运维:Umami / ntfy / DNS / systemd;顶栏另有 CPU·内存条 |
|
||||||
@ -531,7 +581,7 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
|
|||||||
|
|
||||||
```
|
```
|
||||||
douyinWEB/
|
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/tests/ pytest(Shorts / live / reconcile 等)
|
||||||
backend/data/ SQLite、封面/成片缓存
|
backend/data/ SQLite、封面/成片缓存
|
||||||
frontend/src/ Next.js 控制台(Web)
|
frontend/src/ Next.js 控制台(Web)
|
||||||
@ -666,8 +716,9 @@ python scripts\_deploy.py
|
|||||||
- 错误示例:`Quota exceeded for quota metric 'Video Uploads' … Video Uploads per day`
|
- 错误示例:`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))
|
- **不是程序崩溃**:Google Cloud 项目每日 Video Uploads 桶用尽(默认约 100 次/天,[官方文档](https://developers.google.com/youtube/v3/docs/videos/insert))
|
||||||
- 配额在 **太平洋时间 0 点** 重置;Console → YouTube Data API → Quotas 可查看用量与申请提额
|
- 配额在 **太平洋时间 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 页展示用量提示与接口错误,**禁止本地自设上传暂停**
|
- 实现:`backend/app/shorts_yt_quota.py`(按 Client 计数展示、429 识别);Shorts 页展示用量提示与接口错误,**禁止本地自设上传暂停**
|
||||||
|
- **长视频**:429 时该任务 **延后重试**(保持成片、不标失败烧掉),并对该 Client 进入冷静;详见 [长视频(yt-long)](#长视频yt-long)
|
||||||
|
|
||||||
## 全局 SOCKS5(sing-box + proxychains)— 主要针对纯 VPS
|
## 全局 SOCKS5(sing-box + proxychains)— 主要针对纯 VPS
|
||||||
|
|
||||||
|
|||||||
@ -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]:
|
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 db
|
||||||
from . import tiktok_db
|
from . import tiktok_db
|
||||||
from . import yt_long_db
|
from . import yt_long_db
|
||||||
@ -175,15 +180,17 @@ def estimate_platform_daily_need(cfg: dict[str, Any] | None = None) -> dict[str,
|
|||||||
tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or [])
|
tiktok_n = len(tiktok_db.list_tiktok_channels(enabled=True) or [])
|
||||||
except Exception:
|
except Exception:
|
||||||
tiktok_n = 0
|
tiktok_n = 0
|
||||||
yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
|
# Prefer sum of enabled oauth channel caps (respects per-row daily_max).
|
||||||
|
yt_upload = int(yt_long_db.yt_long_enabled_upload_cap(settings_map) or 0)
|
||||||
|
if yt_upload <= 0:
|
||||||
|
yt_upload = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
|
||||||
shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE)
|
shorts_need = shorts_n * int(db.SHORTS_DAILY_FORCE)
|
||||||
tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE)
|
tiktok_need = tiktok_n * int(db.TIKTOK_DAILY_FORCE)
|
||||||
try:
|
try:
|
||||||
x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20))
|
x_need = max(0, int(settings_map.get("x_clips_daily_max") or 20))
|
||||||
except Exception:
|
except Exception:
|
||||||
x_need = 20
|
x_need = 20
|
||||||
# One master feeds all platforms once → masters needed = max(...)
|
source_need = max(0, yt_upload)
|
||||||
source_need = max(yt_upload, shorts_need, tiktok_need, x_need, 0)
|
|
||||||
return {
|
return {
|
||||||
"yt_long": yt_upload,
|
"yt_long": yt_upload,
|
||||||
"yt_long_upload": 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]:
|
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 db
|
||||||
from . import yt_long_db
|
from . import yt_long_db
|
||||||
|
|
||||||
settings_map = cfg if cfg is not None else db.get_settings_map()
|
settings_map = cfg if cfg is not None else db.get_settings_map()
|
||||||
need = estimate_platform_daily_need(settings_map)
|
need = estimate_platform_daily_need(settings_map)
|
||||||
target = int(need["source_masters"])
|
upload_cap = int(need.get("yt_long_upload") or yt_long_db.yt_long_daily_max(settings_map) or 0)
|
||||||
|
target = upload_cap
|
||||||
current = int(yt_long_db.yt_long_source_daily_max(settings_map) or 0)
|
current = int(yt_long_db.yt_long_source_daily_max(settings_map) or 0)
|
||||||
upload_cap = int(yt_long_db.yt_long_daily_max(settings_map) or 0)
|
|
||||||
if not bool(settings_map.get("clip_cascade_enabled", True)):
|
|
||||||
# Without cascade, source only needs to cover YouTube long uploads
|
|
||||||
target = upload_cap
|
|
||||||
try:
|
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:
|
except Exception:
|
||||||
hard_cap = 200
|
hard_cap = max(upload_cap, 200)
|
||||||
new_max = min(hard_cap, max(upload_cap, target))
|
# 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):
|
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})
|
db.update_settings_map({"yt_long_source_daily_max": new_max})
|
||||||
return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need}
|
return {"ok": True, "adjusted": True, "from": current, "to": new_max, **need}
|
||||||
|
|||||||
@ -16,7 +16,7 @@ from typing import Any
|
|||||||
from .config import settings
|
from .config import settings
|
||||||
|
|
||||||
_DEFAULT_MAX_AGE_H = 24.0
|
_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:
|
def _max_age_sec(cfg: dict[str, Any]) -> float:
|
||||||
@ -137,7 +137,7 @@ def _clear_path_refs(path: str, now: float) -> None:
|
|||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
for table in ("tiktok_jobs", "x_clip_jobs", "yt_long_jobs"):
|
for table in ("tiktok_jobs", "x_clip_jobs"):
|
||||||
try:
|
try:
|
||||||
conn.execute(
|
conn.execute(
|
||||||
f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?",
|
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:
|
except Exception:
|
||||||
continue
|
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()
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
conn.close()
|
||||||
@ -155,11 +181,13 @@ def _clear_path_refs(path: str, now: float) -> None:
|
|||||||
def _job_still_needs_file(path: str) -> bool:
|
def _job_still_needs_file(path: str) -> bool:
|
||||||
from . import db
|
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 = (
|
checks = (
|
||||||
"SELECT 1 FROM shorts_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') 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') 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') 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:
|
try:
|
||||||
with db._lock:
|
with db._lock:
|
||||||
|
|||||||
@ -709,8 +709,8 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"yt_long_daily_max": 70,
|
"yt_long_daily_max": 70,
|
||||||
"yt_long_source_daily_max": 70,
|
"yt_long_source_daily_max": 70,
|
||||||
"yt_long_channel_daily_max": 5,
|
"yt_long_channel_daily_max": 5,
|
||||||
"yt_long_min_sec": 180,
|
"yt_long_min_sec": 480,
|
||||||
"yt_long_max_sec": 480,
|
"yt_long_max_sec": 900,
|
||||||
"yt_long_dedupe_room_day": True,
|
"yt_long_dedupe_room_day": True,
|
||||||
"yt_long_max_concurrent": 1,
|
"yt_long_max_concurrent": 1,
|
||||||
"yt_long_upload_min_gap_sec": 900,
|
"yt_long_upload_min_gap_sec": 900,
|
||||||
@ -722,7 +722,7 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"yt_long_description_template": "",
|
"yt_long_description_template": "",
|
||||||
"clip_cascade_enabled": True,
|
"clip_cascade_enabled": True,
|
||||||
"clips_max_age_hours": 24,
|
"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.
|
# Seaweed/S3 session covers (covers/*.jpg); avatars kept. Default 2 days.
|
||||||
"covers_s3_keep_days": 2,
|
"covers_s3_keep_days": 2,
|
||||||
"yt_long_monetize_when_ypp": True,
|
"yt_long_monetize_when_ypp": True,
|
||||||
@ -741,8 +741,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
|
|||||||
"settings_audit_enabled": True,
|
"settings_audit_enabled": True,
|
||||||
"db_backup_enabled": False,
|
"db_backup_enabled": False,
|
||||||
"db_backup_interval_hours": 24,
|
"db_backup_interval_hours": 24,
|
||||||
"db_backup_keep_days": 7,
|
"db_backup_keep_days": 3,
|
||||||
"ops_alerts_enabled": False,
|
"db_backup_keep_max": 3,
|
||||||
|
"ops_alerts_enabled": True,
|
||||||
"ops_alert_disk_enabled": False,
|
"ops_alert_disk_enabled": False,
|
||||||
"ops_alert_quota_enabled": False,
|
"ops_alert_quota_enabled": False,
|
||||||
"ops_alert_interval_sec": 900,
|
"ops_alert_interval_sec": 900,
|
||||||
|
|||||||
@ -1,5 +1,11 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- 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
|
from __future__ import annotations
|
||||||
|
|
||||||
import shutil
|
import shutil
|
||||||
@ -20,17 +26,54 @@ def _db_path() -> Path:
|
|||||||
return Path(settings.data_dir) / "monitor.db"
|
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()
|
src = _db_path()
|
||||||
if not src.is_file():
|
if not src.is_file():
|
||||||
return {"ok": False, "error": "db_not_found"}
|
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")
|
stamp = time.strftime("%Y%m%d_%H%M%S")
|
||||||
name = f"monitor_{stamp}{('_' + label) if label else ''}.db"
|
name = f"monitor_{stamp}{('_' + label) if label else ''}.db"
|
||||||
dest = _backup_dir() / name
|
dest = _backup_dir() / name
|
||||||
try:
|
try:
|
||||||
shutil.copy2(src, dest)
|
shutil.copy2(src, dest)
|
||||||
size = dest.stat().st_size
|
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:
|
except Exception as exc:
|
||||||
return {"ok": False, "error": str(exc)[:200]}
|
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):
|
for p in sorted(_backup_dir().glob("monitor_*.db"), key=lambda x: x.stat().st_mtime, reverse=True):
|
||||||
try:
|
try:
|
||||||
st = p.stat()
|
st = p.stat()
|
||||||
rows.append(
|
rows.append({"name": p.name, "size": st.st_size, "ts": st.st_mtime})
|
||||||
{
|
|
||||||
"name": p.name,
|
|
||||||
"size": st.st_size,
|
|
||||||
"ts": st.st_mtime,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
except OSError:
|
except OSError:
|
||||||
continue
|
continue
|
||||||
if len(rows) >= max(1, limit):
|
if len(rows) >= max(1, limit):
|
||||||
@ -54,14 +91,49 @@ def list_backups(*, limit: int = 20) -> list[dict[str, Any]]:
|
|||||||
return rows
|
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
|
cutoff = time.time() - max(1.0, keep_days) * 86400.0
|
||||||
|
keep_max = max(1, min(30, int(keep_max)))
|
||||||
removed = 0
|
removed = 0
|
||||||
|
files: list[Path] = []
|
||||||
for p in _backup_dir().glob("monitor_*.db"):
|
for p in _backup_dir().glob("monitor_*.db"):
|
||||||
try:
|
try:
|
||||||
if p.stat().st_mtime < cutoff:
|
st = p.stat()
|
||||||
|
if st.st_mtime < cutoff:
|
||||||
p.unlink(missing_ok=True)
|
p.unlink(missing_ok=True)
|
||||||
removed += 1
|
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:
|
except OSError:
|
||||||
continue
|
continue
|
||||||
return {"ok": True, "removed": removed}
|
return {"ok": True, "removed": removed}
|
||||||
@ -72,7 +144,17 @@ async def backup_loop() -> None:
|
|||||||
|
|
||||||
from . import db
|
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:
|
while True:
|
||||||
try:
|
try:
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
@ -85,12 +167,27 @@ async def backup_loop() -> None:
|
|||||||
interval_h = 24.0
|
interval_h = 24.0
|
||||||
interval_h = max(1.0, min(168.0, interval_h))
|
interval_h = max(1.0, min(168.0, interval_h))
|
||||||
try:
|
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:
|
except Exception:
|
||||||
keep_days = 7.0
|
keep_days = 3.0
|
||||||
result = run_backup(label="auto")
|
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"):
|
if result.get("ok"):
|
||||||
prune_backups(keep_days=keep_days)
|
|
||||||
try:
|
try:
|
||||||
db.add_event(
|
db.add_event(
|
||||||
kind="db_backup",
|
kind="db_backup",
|
||||||
@ -100,6 +197,16 @@ async def backup_loop() -> None:
|
|||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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)
|
await asyncio.sleep(interval_h * 3600.0)
|
||||||
except asyncio.CancelledError:
|
except asyncio.CancelledError:
|
||||||
raise
|
raise
|
||||||
|
|||||||
189
backend/app/disk_guard.py
Normal file
189
backend/app/disk_guard.py
Normal 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)
|
||||||
@ -1,14 +1,15 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""Business egress — always via ShellCrash on China physical hosts.
|
"""Business egress for DouyinWEB.
|
||||||
|
|
||||||
Correct model (虚空终端 dialer-proxy):
|
US VPS (primary):
|
||||||
App → 127.0.0.1:7890 (ShellCrash mixed)
|
off → datacenter IP direct
|
||||||
├─ 默认:选机场节点直接出海
|
residential → 127.0.0.1:17891 (douyinweb-singbox) → static residential SOCKS
|
||||||
└─ 勾选「住宅落地」:选 dy-residential(socks5 + dialer-proxy)
|
NEVER touches host sing-box.service / v2ray-agent
|
||||||
→ 先经 ShellCrash 前置节点拨号,再连住宅 SOCKS 落地
|
|
||||||
(家宽无法直连海外住宅 SOCKS)
|
|
||||||
|
|
||||||
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
|
from __future__ import annotations
|
||||||
|
|
||||||
@ -19,9 +20,9 @@ from pathlib import Path
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
from .config import BACKEND, ROOT
|
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"
|
PROXYCHAINS_CONF = CONFIG_DIR / "proxychains.conf"
|
||||||
RESIDENTIAL_PROXY_NAME = "dy-residential"
|
RESIDENTIAL_PROXY_NAME = "dy-residential"
|
||||||
DEFAULT_DIALER = "dialer"
|
DEFAULT_DIALER = "dialer"
|
||||||
@ -41,38 +42,53 @@ def _settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
|||||||
return dict(db.get_settings_map())
|
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:
|
def get_mode(cfg: dict[str, Any] | None = None) -> str:
|
||||||
s = _settings(cfg)
|
s = _settings(cfg)
|
||||||
raw = str(s.get(_MODE_KEY) or "").strip().lower()
|
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:
|
if raw in MODES:
|
||||||
return raw
|
return raw
|
||||||
|
# Legacy toggles → residential on VPS, shellcrash elsewhere
|
||||||
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
|
if s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled"):
|
||||||
return "shellcrash"
|
return "residential" if _is_vps_host(s) else "shellcrash"
|
||||||
# Default ON for China physical: all non-Douyin business via ShellCrash.
|
if _is_vps_host(s):
|
||||||
# Explicit "off" in settings still wins (handled above via MODES).
|
return "off"
|
||||||
return "shellcrash"
|
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:
|
def google_http_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||||||
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT via Clash rules.
|
"""Proxy for Google / YouTube / TikTok / overseas APIs. Douyin stays DIRECT."""
|
||||||
|
mode = get_mode(cfg)
|
||||||
- shellcrash mode → mixed :7890
|
if mode == "residential":
|
||||||
- mode off but ShellCrash still running → still use it (physical soft path)
|
return local_residential_http_proxy()
|
||||||
- mode off + no ShellCrash → empty string (pure VPS direct)
|
if mode == "shellcrash":
|
||||||
"""
|
|
||||||
if get_mode(cfg) == "shellcrash":
|
|
||||||
return _host_http_proxy(cfg)
|
return _host_http_proxy(cfg)
|
||||||
try:
|
# Soft path: ShellCrash still running on physical while mode off
|
||||||
from . import shellcrash_hub
|
if not _is_vps_host(cfg):
|
||||||
|
try:
|
||||||
|
from . import shellcrash_hub
|
||||||
|
|
||||||
st = shellcrash_hub.status() or {}
|
st = shellcrash_hub.status() or {}
|
||||||
if st.get("running"):
|
if st.get("running"):
|
||||||
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
|
return f"http://127.0.0.1:{shellcrash_mixed_port(cfg)}"
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return ""
|
return ""
|
||||||
|
|
||||||
|
|
||||||
@ -84,20 +100,56 @@ def google_httpx_kwargs(*, timeout: float = 45.0, cfg: dict[str, Any] | None = N
|
|||||||
return kw
|
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_httpx_kwargs = google_httpx_kwargs
|
||||||
overseas_http_proxy = google_http_proxy
|
overseas_http_proxy = google_http_proxy
|
||||||
|
|
||||||
|
|
||||||
def chain_residential(cfg: dict[str, Any] | None = None) -> bool:
|
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)
|
s = _settings(cfg)
|
||||||
|
if get_mode(s) == "residential":
|
||||||
|
return False
|
||||||
if _CHAIN_KEY in s:
|
if _CHAIN_KEY in s:
|
||||||
return bool(s.get(_CHAIN_KEY))
|
return bool(s.get(_CHAIN_KEY)) and get_mode(s) == "shellcrash"
|
||||||
# Legacy residential mode / socks toggle → chain on
|
return bool(s.get("global_socks_enabled") or s.get("shorts_upload_socks_enabled")) and get_mode(s) == "shellcrash"
|
||||||
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"))
|
|
||||||
|
|
||||||
|
|
||||||
def cover_neko(cfg: dict[str, Any] | None = None) -> bool:
|
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)
|
s = _settings(cfg)
|
||||||
if _RELAY_KEY in s:
|
if _RELAY_KEY in s:
|
||||||
return bool(s.get(_RELAY_KEY))
|
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:
|
def cover_uploads(cfg: dict[str, Any] | None = None) -> bool:
|
||||||
@ -139,42 +191,48 @@ def _host_http_proxy(cfg: dict[str, Any] | None = None) -> str:
|
|||||||
|
|
||||||
|
|
||||||
def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str:
|
def resolve_http_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||||||
if get_mode(cfg) == "off":
|
return google_http_proxy(cfg)
|
||||||
return ""
|
|
||||||
return _host_http_proxy(cfg)
|
|
||||||
|
|
||||||
|
|
||||||
def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str:
|
def resolve_upload_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||||||
if get_mode(cfg) == "off" or not cover_uploads(cfg):
|
if get_mode(cfg) == "off" or not cover_uploads(cfg):
|
||||||
return ""
|
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:
|
def neko_browser_proxy(cfg: dict[str, Any] | None = None) -> str:
|
||||||
"""Chromium inside Neko → host ShellCrash.
|
"""Chromium inside Neko → host local mixed (no upstream credentials in URL)."""
|
||||||
|
|
||||||
Physical (DY_NEKO_EDGE_UPSTREAM set): always inject proxy unless egress mode is explicit off.
|
|
||||||
"""
|
|
||||||
import os
|
import os
|
||||||
|
|
||||||
physical = bool(str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip())
|
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 ""
|
return ""
|
||||||
if not cover_neko(cfg) and not physical:
|
if not cover_neko(cfg) and not physical:
|
||||||
return ""
|
return ""
|
||||||
|
if mode == "residential":
|
||||||
|
return f"http://host.docker.internal:{LOCAL_MIXED_PORT}"
|
||||||
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
|
return f"http://host.docker.internal:{shellcrash_mixed_port(cfg)}"
|
||||||
|
|
||||||
|
|
||||||
def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
|
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)
|
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
||||||
if get_mode(cfg) != "shellcrash":
|
mode = get_mode(cfg)
|
||||||
|
if mode == "off":
|
||||||
PROXYCHAINS_CONF.write_text(
|
PROXYCHAINS_CONF.write_text(
|
||||||
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
|
"# egress off\nstrict_chain\nproxy_dns\n[ProxyList]\n",
|
||||||
encoding="utf-8",
|
encoding="utf-8",
|
||||||
)
|
)
|
||||||
return PROXYCHAINS_CONF
|
return PROXYCHAINS_CONF
|
||||||
port = shellcrash_mixed_port(cfg)
|
if mode == "residential":
|
||||||
|
port = LOCAL_MIXED_PORT
|
||||||
|
else:
|
||||||
|
port = shellcrash_mixed_port(cfg)
|
||||||
text = (
|
text = (
|
||||||
"strict_chain\n"
|
"strict_chain\n"
|
||||||
"proxy_dns\n"
|
"proxy_dns\n"
|
||||||
@ -187,6 +245,12 @@ def write_proxychains_conf(cfg: dict[str, Any] | None = None) -> Path:
|
|||||||
f"socks5 127.0.0.1 {port}\n"
|
f"socks5 127.0.0.1 {port}\n"
|
||||||
)
|
)
|
||||||
PROXYCHAINS_CONF.write_text(text, encoding="utf-8")
|
PROXYCHAINS_CONF.write_text(text, encoding="utf-8")
|
||||||
|
try:
|
||||||
|
import os
|
||||||
|
|
||||||
|
os.chmod(PROXYCHAINS_CONF, 0o600)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
return PROXYCHAINS_CONF
|
return PROXYCHAINS_CONF
|
||||||
|
|
||||||
|
|
||||||
@ -220,20 +284,15 @@ def apply_mode(
|
|||||||
cfg: dict[str, Any] | None = None,
|
cfg: dict[str, Any] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> dict[str, Any]:
|
||||||
from . import db
|
from . import db
|
||||||
from . import shellcrash_hub
|
|
||||||
from . import singbox_manager
|
from . import singbox_manager
|
||||||
|
|
||||||
raw = str(mode or "off").strip().lower()
|
raw = str(mode or "off").strip().lower()
|
||||||
if raw == "residential":
|
if raw not in MODES:
|
||||||
mode = "shellcrash"
|
|
||||||
if chain is None:
|
|
||||||
chain = True
|
|
||||||
elif raw not in MODES:
|
|
||||||
raise ValueError(f"unsupported egress mode: {raw}")
|
raise ValueError(f"unsupported egress mode: {raw}")
|
||||||
else:
|
mode = raw
|
||||||
mode = raw
|
|
||||||
|
|
||||||
s = _settings(cfg)
|
s = _settings(cfg)
|
||||||
|
# dialer-proxy chain only meaningful with ShellCrash
|
||||||
if chain is None:
|
if chain is None:
|
||||||
chain = chain_residential(s) if mode == "shellcrash" else False
|
chain = chain_residential(s) if mode == "shellcrash" else False
|
||||||
chain = bool(chain) and mode == "shellcrash"
|
chain = bool(chain) and mode == "shellcrash"
|
||||||
@ -241,31 +300,46 @@ def apply_mode(
|
|||||||
if cover_neko_flag is None:
|
if cover_neko_flag is None:
|
||||||
cover_neko_flag = mode != "off"
|
cover_neko_flag = mode != "off"
|
||||||
if cover_relay_flag is None:
|
if cover_relay_flag is None:
|
||||||
cover_relay_flag = mode == "shellcrash"
|
cover_relay_flag = mode in {"shellcrash", "residential"}
|
||||||
if cover_uploads_flag is None:
|
if cover_uploads_flag is None:
|
||||||
cover_uploads_flag = mode != "off"
|
cover_uploads_flag = mode != "off"
|
||||||
|
|
||||||
|
socks_on = mode == "residential" or (mode == "shellcrash" and chain)
|
||||||
updates: dict[str, Any] = {
|
updates: dict[str, Any] = {
|
||||||
_MODE_KEY: mode,
|
_MODE_KEY: mode,
|
||||||
_CHAIN_KEY: chain,
|
_CHAIN_KEY: chain,
|
||||||
_NEKO_KEY: bool(cover_neko_flag),
|
_NEKO_KEY: bool(cover_neko_flag),
|
||||||
_RELAY_KEY: bool(cover_relay_flag),
|
_RELAY_KEY: bool(cover_relay_flag),
|
||||||
_UPLOADS_KEY: bool(cover_uploads_flag),
|
_UPLOADS_KEY: bool(cover_uploads_flag),
|
||||||
# Keep legacy flags aligned with «住宅链式» checkbox only (not a separate engine).
|
"global_socks_enabled": socks_on,
|
||||||
"global_socks_enabled": chain,
|
"shorts_upload_socks_enabled": socks_on,
|
||||||
"shorts_upload_socks_enabled": chain,
|
|
||||||
}
|
}
|
||||||
db.update_settings_map(updates)
|
db.update_settings_map(updates)
|
||||||
s = db.get_settings_map()
|
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}
|
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":
|
if mode == "shellcrash":
|
||||||
|
from . import shellcrash_hub
|
||||||
|
|
||||||
if chain:
|
if chain:
|
||||||
from . import global_socks
|
from . import global_socks
|
||||||
|
|
||||||
@ -277,7 +351,6 @@ def apply_mode(
|
|||||||
dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER,
|
dialer=(dialer or DEFAULT_DIALER).strip() or DEFAULT_DIALER,
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
# Normal ShellCrash node (not residential landing).
|
|
||||||
try:
|
try:
|
||||||
chain_result = shellcrash_hub.apply_profile(
|
chain_result = shellcrash_hub.apply_profile(
|
||||||
shellcrash_hub.DEFAULT_PROFILE,
|
shellcrash_hub.DEFAULT_PROFILE,
|
||||||
@ -287,7 +360,7 @@ def apply_mode(
|
|||||||
chain_result = {"ok": False, "error": str(exc)}
|
chain_result = {"ok": False, "error": str(exc)}
|
||||||
|
|
||||||
pc_path = ""
|
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))
|
pc_path = str(write_proxychains_conf(s))
|
||||||
|
|
||||||
neko_result: dict[str, Any] = {"skipped": True}
|
neko_result: dict[str, Any] = {"skipped": True}
|
||||||
@ -303,26 +376,32 @@ def apply_mode(
|
|||||||
"ok": True,
|
"ok": True,
|
||||||
"egress": status(s),
|
"egress": status(s),
|
||||||
"chain": chain_result,
|
"chain": chain_result,
|
||||||
|
"residential": residential_result,
|
||||||
"proxychains_conf": pc_path,
|
"proxychains_conf": pc_path,
|
||||||
"neko": neko_result,
|
"neko": neko_result,
|
||||||
|
"v2ray_agent": singbox_manager.host_v2ray_agent_status(),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
def probe(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
mode = get_mode(cfg)
|
mode = get_mode(cfg)
|
||||||
proxy = _host_http_proxy(cfg) if mode != "off" else ""
|
proxy = google_http_proxy(cfg) if mode != "off" else ""
|
||||||
targets = [
|
targets = [
|
||||||
("google", "https://www.google.com/generate_204"),
|
("google", "https://www.google.com/generate_204"),
|
||||||
("youtube", "https://www.youtube.com/"),
|
("youtube", "https://www.youtube.com/"),
|
||||||
|
("ip", "https://api.ipify.org"),
|
||||||
("douyin", "https://www.douyin.com/"),
|
("douyin", "https://www.douyin.com/"),
|
||||||
]
|
]
|
||||||
rows = []
|
rows = []
|
||||||
for name, url in targets:
|
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":
|
if name == "douyin":
|
||||||
rows.append(_curl_probe("douyin_direct", url, proxy=""))
|
rows.append(_curl_probe("douyin_direct", url, proxy=""))
|
||||||
if 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
|
continue
|
||||||
rows.append(_curl_probe(name, url, proxy=proxy))
|
rows.append(_curl_probe(name, url, proxy=proxy))
|
||||||
rows.append(_curl_probe(f"{name}_direct", url, 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]:
|
def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
||||||
from . import shellcrash_hub
|
from . import singbox_manager
|
||||||
|
|
||||||
s = _settings(cfg)
|
s = _settings(cfg)
|
||||||
mode = get_mode(s)
|
mode = get_mode(s)
|
||||||
chain = chain_residential(s) if mode == "shellcrash" else False
|
chain = chain_residential(s)
|
||||||
sc = shellcrash_hub.status()
|
vps = _is_vps_host(s)
|
||||||
host_proxy = _host_http_proxy(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)
|
neko_proxy = neko_browser_proxy(s)
|
||||||
pc = proxychains_bin()
|
pc = proxychains_bin()
|
||||||
exit_label = RESIDENTIAL_PROXY_NAME if chain else (sc.get("selected_node") or shellcrash_hub.DEFAULT_NODE)
|
sb = singbox_manager.status()
|
||||||
return {
|
if mode == "residential":
|
||||||
"mode": mode,
|
exit_label = "static-residential"
|
||||||
"chain_residential": chain,
|
elif chain:
|
||||||
"modes": [
|
exit_label = RESIDENTIAL_PROXY_NAME
|
||||||
{"id": "off", "label": "直连", "description": "不经 ShellCrash"},
|
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",
|
"id": "shellcrash",
|
||||||
"label": "ShellCrash",
|
"label": "ShellCrash",
|
||||||
"description": "业务统一走本机 :7890;可选住宅链式落地",
|
"description": "物理机出海 :7890;可选住宅链式",
|
||||||
"ready": bool(sc.get("running") or sc.get("installed")),
|
"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": {
|
"cover": {
|
||||||
"neko": cover_neko(s),
|
"neko": cover_neko(s),
|
||||||
"relay": cover_relay(s),
|
"relay": cover_relay(s),
|
||||||
@ -399,13 +533,25 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
|||||||
"exit_node": exit_label,
|
"exit_node": exit_label,
|
||||||
"dialer": DEFAULT_DIALER,
|
"dialer": DEFAULT_DIALER,
|
||||||
"residential_proxy_name": RESIDENTIAL_PROXY_NAME,
|
"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": {
|
"proxychains": {
|
||||||
"installed": bool(pc),
|
"installed": bool(pc),
|
||||||
"bin": pc,
|
"bin": pc,
|
||||||
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
|
"conf": str(PROXYCHAINS_CONF) if PROXYCHAINS_CONF.is_file() else "",
|
||||||
"relay_active": ffmpeg_uses_proxy(s),
|
"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": {
|
"shellcrash": {
|
||||||
"running": bool(sc.get("running")),
|
"running": bool(sc.get("running")),
|
||||||
"mixed_port": sc.get("mixed_port") or "7890",
|
"mixed_port": sc.get("mixed_port") or "7890",
|
||||||
@ -414,48 +560,55 @@ def status(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
|||||||
"matrix": [
|
"matrix": [
|
||||||
{
|
{
|
||||||
"id": "neko",
|
"id": "neko",
|
||||||
"label": "Neko Chrome",
|
"label": "Neko Chrome / X",
|
||||||
"active": bool(neko_proxy),
|
"active": bool(neko_proxy),
|
||||||
"detail": (neko_proxy + (f" → {exit_label}" if chain else "")) if neko_proxy else "直连",
|
"detail": neko_proxy or "直连(机房 IP)",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "relay",
|
"id": "relay",
|
||||||
"label": "直播推流 FFmpeg",
|
"label": "直播推流 FFmpeg",
|
||||||
"active": ffmpeg_uses_proxy(s),
|
"active": ffmpeg_uses_proxy(s),
|
||||||
"detail": (
|
"detail": (
|
||||||
f"proxychains → ShellCrash → {exit_label}"
|
f"proxychains → {exit_label}"
|
||||||
if ffmpeg_uses_proxy(s)
|
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",
|
"id": "uploads",
|
||||||
"label": "Shorts / 长视频 / 上传",
|
"label": "Shorts / 长视频 / TikTok",
|
||||||
"active": bool(resolve_upload_proxy(s)),
|
"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),
|
"app_root": str(ROOT),
|
||||||
"backend": str(BACKEND),
|
"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] = []
|
out: list[str] = []
|
||||||
if mode == "shellcrash":
|
out.append("硬规则:*.douyin.com / 抖音 CDN 始终直连,不进住宅代理")
|
||||||
out.append("硬规则:*.douyin.com / 抖音 CDN 必须 DIRECT(拉流与监控不可走机场)")
|
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"):
|
if mode == "shellcrash" and not sc.get("running"):
|
||||||
out.append("ShellCrash 未运行 — 先启动,再应用出海")
|
out.append("ShellCrash 未运行 — 先启动再应用")
|
||||||
if mode == "shellcrash" and chain:
|
if mode == "shellcrash" and chain:
|
||||||
out.append(
|
out.append("住宅落地 = ShellCrash dialer-proxy 链式(物理机)")
|
||||||
"住宅落地 = ShellCrash 链式(dialer-proxy):家宽 → 前置节点 → 住宅 SOCKS。"
|
|
||||||
"详见虚空终端 docs:dialer-proxy"
|
|
||||||
)
|
|
||||||
if mode == "shellcrash" and not chain:
|
|
||||||
out.append("当前用 ShellCrash 机场线路出海;勾选「住宅落地」才会链式到 SOCKS5")
|
|
||||||
if mode != "off" and not pc:
|
if mode != "off" and not pc:
|
||||||
out.append("未安装 proxychains4 — 直播推流无法走代理")
|
out.append("未安装 proxychains4 — 直播推流无法走代理")
|
||||||
if mode == "off":
|
|
||||||
out.append("直连:国内物理机上 YouTube Studio / 推流通常不可用")
|
|
||||||
return out
|
return out
|
||||||
|
|||||||
@ -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))
|
cores = max(1, int(snap.get("cpu_cores") or 1))
|
||||||
load1 = float(snap.get("load1") or 0.0)
|
load1 = float(snap.get("load1") or 0.0)
|
||||||
cpu = float(snap.get("cpu_percent") or 0.0)
|
cpu = float(snap.get("cpu_percent") or 0.0)
|
||||||
# Leave ~1 core free for API accept loop + Neko CDP.
|
# Leave ~1+ core free for API accept loop + Neko CDP + live push.
|
||||||
if load1 >= max(1.5, cores * 1.15):
|
# 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}"
|
return f"load1={load1}"
|
||||||
if cpu >= 80.0:
|
if cpu >= 96.0:
|
||||||
return f"cpu={cpu}"
|
return f"cpu={cpu}"
|
||||||
return ""
|
return ""
|
||||||
|
|||||||
@ -43,9 +43,10 @@ def status() -> dict[str, Any]:
|
|||||||
"profiles": list(PROFILES),
|
"profiles": list(PROFILES),
|
||||||
"effects": {
|
"effects": {
|
||||||
"vps": [
|
"vps": [
|
||||||
"egress / ShellCrash / 业务 SOCKS 全部关闭(本机公网出海)",
|
"默认机房 IP 直出;可选「静态住宅 IP」经 douyinweb-singbox :17891",
|
||||||
"本机分配 Neko 仍可按频道启停(与物理机同 compose / Studio 配置)",
|
"绝不操作宿主机 sing-box.service(v2ray-agent)",
|
||||||
"单路独占默认开启(省内存;可配对物理机 ops-neko)",
|
"本机分配 Neko 仍可按频道启停",
|
||||||
|
"单路独占默认开启(省内存)",
|
||||||
],
|
],
|
||||||
"physical": [
|
"physical": [
|
||||||
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
|
"业务出口切回 ShellCrash(不自动强起边缘 WG/FRP)",
|
||||||
|
|||||||
@ -86,7 +86,23 @@ def classify_job_error(error: str = "", *, platform: str = "") -> dict[str, Any]
|
|||||||
"action_label": "重新授权",
|
"action_label": "重新授权",
|
||||||
"retryable": False,
|
"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 {
|
return {
|
||||||
"code": "dc",
|
"code": "dc",
|
||||||
"label": "TikTok 机房不匹配",
|
"label": "TikTok 机房不匹配",
|
||||||
|
|||||||
@ -171,9 +171,11 @@ async def lifespan(_: FastAPI):
|
|||||||
return
|
return
|
||||||
from .db_backup import backup_loop
|
from .db_backup import backup_loop
|
||||||
from .ops_alerts import alert_loop
|
from .ops_alerts import alert_loop
|
||||||
|
from .disk_guard import disk_guard_loop
|
||||||
|
|
||||||
asyncio.create_task(backup_loop())
|
asyncio.create_task(backup_loop())
|
||||||
asyncio.create_task(alert_loop())
|
asyncio.create_task(alert_loop())
|
||||||
|
asyncio.create_task(disk_guard_loop())
|
||||||
try:
|
try:
|
||||||
from . import ops_neko_sync
|
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
|
raise HTTPException(400, "source_daily_max 无效") from None
|
||||||
if "yt_long_source_cap" in raw:
|
if "yt_long_source_cap" in raw:
|
||||||
try:
|
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:
|
except Exception:
|
||||||
raise HTTPException(400, "source_cap 无效") from None
|
raise HTTPException(400, "source_cap 无效") from None
|
||||||
if "yt_long_channel_daily_max" in raw:
|
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
|
raise HTTPException(400, "channel_daily_max 无效") from None
|
||||||
if "yt_long_min_sec" in raw:
|
if "yt_long_min_sec" in raw:
|
||||||
try:
|
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:
|
except Exception:
|
||||||
raise HTTPException(400, "min_sec 无效") from None
|
raise HTTPException(400, "min_sec 无效") from None
|
||||||
if "yt_long_max_sec" in raw:
|
if "yt_long_max_sec" in raw:
|
||||||
try:
|
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:
|
except Exception:
|
||||||
raise HTTPException(400, "max_sec 无效") from None
|
raise HTTPException(400, "max_sec 无效") from None
|
||||||
if "yt_long_upload_min_gap_sec" in raw:
|
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:
|
if patch:
|
||||||
# Keep min <= max
|
# Keep min <= max
|
||||||
cfg = {**db.get_settings_map(), **patch}
|
cfg = {**db.get_settings_map(), **patch}
|
||||||
lo = int(cfg.get("yt_long_min_sec") or 180)
|
lo = int(cfg.get("yt_long_min_sec") or 480)
|
||||||
hi = int(cfg.get("yt_long_max_sec") or 480)
|
hi = int(cfg.get("yt_long_max_sec") or 900)
|
||||||
if lo > hi:
|
if lo > hi:
|
||||||
patch["yt_long_max_sec"] = lo
|
patch["yt_long_max_sec"] = lo
|
||||||
db.update_settings_map(patch)
|
db.update_settings_map(patch)
|
||||||
@ -4521,22 +4523,39 @@ async def network_socks_get() -> dict[str, Any]:
|
|||||||
|
|
||||||
@app.patch("/api/network/socks")
|
@app.patch("/api/network/socks")
|
||||||
async def network_socks_patch(body: dict[str, Any]) -> dict[str, Any]:
|
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 db
|
||||||
|
from . import egress_hub
|
||||||
from . import global_socks
|
from . import global_socks
|
||||||
|
from . import host_profile
|
||||||
from . import singbox_manager
|
from . import singbox_manager
|
||||||
|
|
||||||
cfg = await asyncio.to_thread(db.get_settings_map)
|
cfg = await asyncio.to_thread(db.get_settings_map)
|
||||||
updates: dict[str, Any] = {}
|
updates: dict[str, Any] = {}
|
||||||
|
want_on: bool | None = None
|
||||||
if "enabled" in body:
|
if "enabled" in body:
|
||||||
updates["global_socks_enabled"] = bool(body.get("enabled"))
|
want_on = bool(body.get("enabled"))
|
||||||
updates["shorts_upload_socks_enabled"] = bool(body.get("enabled"))
|
updates["global_socks_enabled"] = want_on
|
||||||
# 住宅 SOCKS 勾选 = ShellCrash 链式落地,不是独立引擎
|
updates["shorts_upload_socks_enabled"] = want_on
|
||||||
updates["egress_chain_residential"] = bool(body.get("enabled"))
|
is_vps = host_profile.infer_profile(cfg) == "vps"
|
||||||
if bool(body.get("enabled")):
|
if want_on:
|
||||||
updates["egress_mode"] = "shellcrash"
|
if is_vps:
|
||||||
elif str(cfg.get("egress_mode") or "") == "residential":
|
updates["egress_mode"] = "residential"
|
||||||
updates["egress_mode"] = "shellcrash"
|
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:
|
if "active_profile_id" in body:
|
||||||
updates["global_socks_profile_id"] = str(body.get("active_profile_id") or "").strip()
|
updates["global_socks_profile_id"] = str(body.get("active_profile_id") or "").strip()
|
||||||
updates["shorts_upload_socks_profile_id"] = updates["global_socks_profile_id"]
|
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:
|
for item in raw:
|
||||||
p = global_socks._norm_profile(item)
|
p = global_socks._norm_profile(item)
|
||||||
if p and p["server"] and p["port"] > 0:
|
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)
|
old = global_socks.get_socks_profile(str(p["id"]), cfg)
|
||||||
pwd = str(p.get("password") or "")
|
pwd = str(p.get("password") or "")
|
||||||
if old and (not pwd or pwd.startswith("***")):
|
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:
|
if updates:
|
||||||
await asyncio.to_thread(db.update_settings_map, updates)
|
await asyncio.to_thread(db.update_settings_map, updates)
|
||||||
cfg = await asyncio.to_thread(db.get_settings_map)
|
cfg = await asyncio.to_thread(db.get_settings_map)
|
||||||
try:
|
mode = str(cfg.get("egress_mode") or "off")
|
||||||
await asyncio.to_thread(singbox_manager.apply_from_settings, cfg)
|
if mode == "residential" and cfg.get("global_socks_enabled"):
|
||||||
except Exception:
|
try:
|
||||||
pass
|
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
|
from . import network_hub
|
||||||
|
|
||||||
return await asyncio.to_thread(network_hub.socks_status)
|
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_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_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"),
|
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,
|
dialer=str(body.get("dialer") or "") or None,
|
||||||
)
|
)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
|
|||||||
@ -99,7 +99,9 @@ def socks_status() -> dict[str, Any]:
|
|||||||
"profiles": profiles,
|
"profiles": profiles,
|
||||||
"local_mixed": global_socks.local_mixed_url() if enabled else "",
|
"local_mixed": global_socks.local_mixed_url() if enabled else "",
|
||||||
"singbox_running": bool(singbox_manager.is_running()) if enabled else False,
|
"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",
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -73,7 +73,7 @@ async def check_and_alert() -> dict[str, Any]:
|
|||||||
metrics = collect_metrics()
|
metrics = collect_metrics()
|
||||||
fired: list[str] = []
|
fired: list[str] = []
|
||||||
|
|
||||||
if cfg.get("ops_alert_disk_enabled", False):
|
if cfg.get("ops_alert_disk_enabled", True):
|
||||||
try:
|
try:
|
||||||
min_free = float(cfg.get("clips_min_free_gb") or 12)
|
min_free = float(cfg.get("clips_min_free_gb") or 12)
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -127,6 +127,12 @@ async def alert_loop() -> None:
|
|||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
cfg = db.get_settings_map()
|
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):
|
if cfg.get("ops_alerts_enabled", False):
|
||||||
await check_and_alert()
|
await check_and_alert()
|
||||||
try:
|
try:
|
||||||
|
|||||||
@ -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_KEY = "shorts_oauth_pending_states"
|
||||||
|
|
||||||
|
|
||||||
|
_OAUTH_STATE_TTL_SEC = 1800.0 # 30min — Google consent + brand pick can be slow
|
||||||
|
|
||||||
|
|
||||||
def _persist_oauth_states() -> None:
|
def _persist_oauth_states() -> None:
|
||||||
"""Survive API restarts between Google consent and callback."""
|
"""Survive API restarts between Google consent and callback."""
|
||||||
now = time.time()
|
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()):
|
for k, packed in list(_oauth_states.items()):
|
||||||
if len(packed) < 2 or float(packed[1]) < now:
|
if len(packed) < 2 or float(packed[1]) < now:
|
||||||
_oauth_states.pop(k, None)
|
_oauth_states.pop(k, None)
|
||||||
continue
|
continue
|
||||||
payload[k] = list(packed)
|
merged[str(k)] = list(packed)
|
||||||
|
_oauth_states[str(k)] = packed
|
||||||
try:
|
try:
|
||||||
db.update_settings_map({_OAUTH_STATE_KEY: payload})
|
db.update_settings_map({_OAUTH_STATE_KEY: merged})
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
|
||||||
def _hydrate_oauth_states() -> None:
|
def _hydrate_oauth_states(*, force: bool = False) -> None:
|
||||||
if _oauth_states:
|
"""Load pending states from DB. Always merge — never skip when memory is non-empty."""
|
||||||
return
|
try:
|
||||||
|
if force:
|
||||||
|
db._invalidate_settings_cache()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
try:
|
try:
|
||||||
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
|
raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {}
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -84,8 +112,11 @@ def _hydrate_oauth_states() -> None:
|
|||||||
continue
|
continue
|
||||||
if exp < now:
|
if exp < now:
|
||||||
continue
|
continue
|
||||||
|
key = str(k)
|
||||||
|
if (not force) and key in _oauth_states:
|
||||||
|
continue
|
||||||
if len(packed) >= 5:
|
if len(packed) >= 5:
|
||||||
_oauth_states[str(k)] = (
|
_oauth_states[key] = (
|
||||||
str(packed[0]),
|
str(packed[0]),
|
||||||
exp,
|
exp,
|
||||||
str(packed[2]),
|
str(packed[2]),
|
||||||
@ -93,7 +124,29 @@ def _hydrate_oauth_states() -> None:
|
|||||||
str(packed[4] or ""),
|
str(packed[4] or ""),
|
||||||
)
|
)
|
||||||
else:
|
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:
|
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:
|
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:
|
try:
|
||||||
from . import egress_hub
|
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:
|
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"
|
return "http://127.0.0.1:7890"
|
||||||
|
except Exception:
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]:
|
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
|
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]:
|
def _cfg() -> dict[str, Any]:
|
||||||
return db.get_settings_map()
|
return db.get_settings_map()
|
||||||
|
|
||||||
@ -398,16 +498,21 @@ def build_authorize_url(
|
|||||||
if ret and (not ret.startswith("/") or ret.startswith("//")):
|
if ret and (not ret.startswith("/") or ret.startswith("//")):
|
||||||
ret = ""
|
ret = ""
|
||||||
now = time.time()
|
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()):
|
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)
|
_oauth_states.pop(k, None)
|
||||||
state = secrets.token_urlsafe(24)
|
state = secrets.token_urlsafe(24)
|
||||||
|
exp = now + _OAUTH_STATE_TTL_SEC
|
||||||
if ret:
|
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:
|
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()
|
_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))
|
scope = authorize_scopes(include_monetary=bool(include_monetary))
|
||||||
params = {
|
params = {
|
||||||
"client_id": client_id,
|
"client_id": client_id,
|
||||||
@ -445,21 +550,48 @@ def authorize_scopes(*, include_monetary: bool = False) -> str:
|
|||||||
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl"
|
||||||
|
|
||||||
|
|
||||||
async def token_scopes(access_token: str) -> set[str]:
|
async def token_scopes(access_token: str) -> set[str] | None:
|
||||||
"""Granted scopes on an access token (tokeninfo)."""
|
"""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:
|
if not access_token:
|
||||||
return set()
|
return set()
|
||||||
|
last_err = ""
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
|
from . import egress_hub
|
||||||
resp = await client.get(
|
|
||||||
"https://oauth2.googleapis.com/tokeninfo",
|
proxies = egress_hub.google_http_proxy_candidates()
|
||||||
params={"access_token": access_token},
|
|
||||||
)
|
|
||||||
data = resp.json() if resp.content else {}
|
|
||||||
raw = str(data.get("scope") or "")
|
|
||||||
return {s for s in raw.split() if s.strip()}
|
|
||||||
except Exception:
|
except Exception:
|
||||||
return set()
|
proxies = [str((_google_http_proxy() or "")).strip()]
|
||||||
|
if "" not in proxies:
|
||||||
|
proxies.append("")
|
||||||
|
for proxy in proxies:
|
||||||
|
try:
|
||||||
|
try:
|
||||||
|
from . import egress_hub
|
||||||
|
|
||||||
|
kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=10.0 if proxy else 20.0)
|
||||||
|
except Exception:
|
||||||
|
kw = _google_client_kwargs(timeout=10.0 if proxy else 20.0)
|
||||||
|
if proxy:
|
||||||
|
kw = {**kw, "proxy": proxy}
|
||||||
|
elif "proxy" in kw:
|
||||||
|
kw = {k: v for k, v in kw.items() if k != "proxy"}
|
||||||
|
async with httpx.AsyncClient(**kw) as client:
|
||||||
|
resp = await client.get(
|
||||||
|
"https://oauth2.googleapis.com/tokeninfo",
|
||||||
|
params={"access_token": access_token},
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
raw = str(data.get("scope") or "")
|
||||||
|
return {s for s in raw.split() if s.strip()}
|
||||||
|
except Exception as exc:
|
||||||
|
last_err = f"{type(exc).__name__}: {exc}"[:160]
|
||||||
|
continue
|
||||||
|
_oauth_log(f"token_scopes_fail {last_err}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def missing_required_scopes(granted: set[str]) -> list[str]:
|
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:
|
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 {}
|
ch = db.get_shorts_channel(channel_pk) or {}
|
||||||
if not ch:
|
if not ch:
|
||||||
return
|
return
|
||||||
db.update_shorts_channel(
|
# Keep existing oauth_ok / oauth_error so the board does not flash「OAuth 异常」
|
||||||
channel_pk,
|
# while the operator is mid-consent on Google.
|
||||||
oauth_checked_at=time.time(),
|
db.update_shorts_channel(channel_pk, oauth_checked_at=time.time())
|
||||||
oauth_error="授权中:完成 Google 后凭证写入本卡片",
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
|
async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]:
|
||||||
_hydrate_oauth_states()
|
packed = _pop_oauth_state(state)
|
||||||
packed = _oauth_states.pop(state, None)
|
|
||||||
_persist_oauth_states()
|
|
||||||
if not packed:
|
if not packed:
|
||||||
_oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}")
|
_oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}")
|
||||||
raise ValueError("授权 state 无效或已过期,请重新点击授权")
|
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 ""
|
return_to = str(packed[4]).strip() if len(packed) >= 5 else ""
|
||||||
if return_to and (not return_to.startswith("/") or return_to.startswith("//")):
|
if return_to and (not return_to.startswith("/") or return_to.startswith("//")):
|
||||||
return_to = ""
|
return_to = ""
|
||||||
if exp < time.time():
|
if float(exp) < time.time():
|
||||||
_stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权")
|
_stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权")
|
||||||
raise ValueError("授权已过期,请重新点击授权")
|
raise ValueError("授权已过期,请重新点击授权")
|
||||||
cfg = _cfg()
|
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"exchange pk={channel_pk} redirect={redirect_uri} "
|
||||||
f"secret_tail={client_secret[-4:]} proxy={proxy or 'direct'}"
|
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:
|
try:
|
||||||
async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) as client:
|
async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) as client:
|
||||||
token_resp = await client.post(
|
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)
|
_stamp_oauth_error(channel_pk, err)
|
||||||
raise ValueError(err)
|
raise ValueError(err)
|
||||||
items = ch_data.get("items") or []
|
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_uc = str(channel.get("youtube_channel_id") or "").strip()
|
||||||
expected_name = str(channel.get("name") or "").strip()
|
expected_name = str(channel.get("name") or "").strip()
|
||||||
chosen: dict[str, Any] | None = None
|
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)
|
_stamp_oauth_error(channel_pk, err)
|
||||||
raise ValueError(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)
|
google_email = await fetch_google_account_email(access)
|
||||||
|
|
||||||
# Soft-warn if the same YouTube channel is already bound to another Shorts card.
|
# Resolve target card by authorized brand UC:
|
||||||
dup_warn = ""
|
# exist → update that card; missing → create new card.
|
||||||
if yt_id:
|
# Never delete the clicked card. Never wipe unrelated cards.
|
||||||
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
|
|
||||||
had_old = bool(str(channel.get("refresh_token") or "").strip())
|
had_old = bool(str(channel.get("refresh_token") or "").strip())
|
||||||
if not refresh:
|
if not refresh:
|
||||||
if had_old:
|
if had_old:
|
||||||
refresh = str(channel.get("refresh_token") or "").strip()
|
refresh = str(channel.get("refresh_token") or "").strip()
|
||||||
else:
|
else:
|
||||||
# Revoke this access so the next consent can mint a refresh_token.
|
|
||||||
try:
|
try:
|
||||||
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
|
async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client:
|
||||||
await client.post(
|
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)
|
_stamp_oauth_error(channel_pk, err)
|
||||||
raise ValueError(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] = {
|
patch: dict[str, Any] = {
|
||||||
"client_id": client_id,
|
"client_id": client_id,
|
||||||
"client_secret": client_secret,
|
"client_secret": client_secret,
|
||||||
"refresh_token": refresh,
|
"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:
|
if google_email:
|
||||||
patch["oauth_email"] = google_email
|
patch["oauth_email"] = google_email
|
||||||
# Keep operator card title on reauth — never auto-rename into another brand's title.
|
if profile_id:
|
||||||
if yt_title and not expected_name:
|
|
||||||
patch["name"] = yt_title
|
|
||||||
if profile_id and not str(channel.get("oauth_profile_id") or "").strip():
|
|
||||||
patch["oauth_profile_id"] = 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(
|
updated = db.update_shorts_channel(
|
||||||
channel_pk,
|
target_pk,
|
||||||
**patch,
|
**patch,
|
||||||
oauth_ok=1,
|
oauth_ok=1,
|
||||||
oauth_checked_at=time.time(),
|
oauth_checked_at=time.time(),
|
||||||
oauth_error="",
|
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:
|
if google_email and profile_id:
|
||||||
try:
|
try:
|
||||||
set_oauth_profile_email(profile_id, google_email)
|
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:
|
try:
|
||||||
from . import youtube_manage as ytm
|
from . import youtube_manage as ytm
|
||||||
|
|
||||||
await ytm.fetch_channel_profile(channel_pk)
|
await ytm.fetch_channel_profile(target_pk)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
profile_err = str(exc).strip() or "拉取频道资料失败"
|
profile_err = str(exc).strip() or "拉取频道资料失败"
|
||||||
try:
|
try:
|
||||||
from .yt_long_monetize import refresh_ypp_for_shorts_channel
|
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"):
|
if not ypp_r.get("ok"):
|
||||||
ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200]
|
ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200]
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
ypp_err = str(exc).strip() or "YPP 探测失败"
|
ypp_err = str(exc).strip() or "YPP 探测失败"
|
||||||
note = " · ".join(x for x in (profile_err, ypp_err) if x)
|
note = " · ".join(x for x in (profile_err, ypp_err) if x)
|
||||||
if note:
|
if note:
|
||||||
db.update_shorts_channel(channel_pk, oauth_error=note)
|
try:
|
||||||
updated = db.get_shorts_channel(channel_pk) or updated
|
db.update_shorts_channel(target_pk, oauth_error=note[:500])
|
||||||
_oauth_log(f"exchange_ok pk={channel_pk} yt={yt_id} title={yt_title} profile_err={profile_err!r} ypp_err={ypp_err!r}")
|
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 {
|
return {
|
||||||
"ok": True,
|
"ok": True,
|
||||||
"channel": updated,
|
"channel": updated,
|
||||||
@ -762,7 +962,11 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic
|
|||||||
"ypp_ok": not bool(ypp_err),
|
"ypp_ok": not bool(ypp_err),
|
||||||
"profile_error": profile_err,
|
"profile_error": profile_err,
|
||||||
"ypp_error": ypp_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,
|
"return_to": return_to,
|
||||||
}
|
}
|
||||||
except ValueError:
|
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"],
|
client_secret=creds["client_secret"],
|
||||||
refresh_token=creds["refresh_token"],
|
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:
|
if missing:
|
||||||
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
|
err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限"
|
||||||
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
|
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)
|
db.update_shorts_channel(cid, **patch)
|
||||||
return {"ok": True, "channel_id": cid, "oauth_email": google_email}
|
return {"ok": True, "channel_id": cid, "oauth_email": google_email}
|
||||||
except Exception as exc:
|
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)
|
db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err)
|
||||||
return {"ok": False, "error": err, "channel_id": cid}
|
return {"ok": False, "error": err, "channel_id": cid}
|
||||||
|
|
||||||
|
|||||||
@ -60,6 +60,16 @@ def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]:
|
|||||||
return kw
|
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(
|
async def refresh_access_token(
|
||||||
*,
|
*,
|
||||||
client_id: str,
|
client_id: str,
|
||||||
@ -69,20 +79,40 @@ async def refresh_access_token(
|
|||||||
) -> str:
|
) -> str:
|
||||||
if not (client_id and client_secret and refresh_token):
|
if not (client_id and client_secret and refresh_token):
|
||||||
raise ValueError("缺少 OAuth client_id / client_secret / 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 = ""
|
||||||
resp = await client.post(
|
for proxy in _proxy_candidates(proxy_url):
|
||||||
"https://oauth2.googleapis.com/token",
|
# Flaky residential: fail fast then fall back to VPS direct.
|
||||||
data={
|
attempt_timeout = 12.0 if proxy else 30.0
|
||||||
"client_id": client_id,
|
try:
|
||||||
"client_secret": client_secret,
|
from . import egress_hub
|
||||||
"refresh_token": refresh_token,
|
|
||||||
"grant_type": "refresh_token",
|
kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=attempt_timeout)
|
||||||
},
|
except Exception:
|
||||||
)
|
kw = _client_kwargs(timeout=attempt_timeout, proxy_url=proxy)
|
||||||
data = resp.json() if resp.content else {}
|
try:
|
||||||
if resp.status_code >= 400 or not data.get("access_token"):
|
async with httpx.AsyncClient(**kw) as client:
|
||||||
raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}")
|
resp = await client.post(
|
||||||
return str(data["access_token"])
|
"https://oauth2.googleapis.com/token",
|
||||||
|
data={
|
||||||
|
"client_id": client_id,
|
||||||
|
"client_secret": client_secret,
|
||||||
|
"refresh_token": refresh_token,
|
||||||
|
"grant_type": "refresh_token",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
data = resp.json() if resp.content else {}
|
||||||
|
if resp.status_code >= 400 or not data.get("access_token"):
|
||||||
|
# Auth/config errors: do not fall through to another egress.
|
||||||
|
raise ValueError(
|
||||||
|
f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}"
|
||||||
|
)
|
||||||
|
return str(data["access_token"])
|
||||||
|
except ValueError:
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
last_transport = f"{type(exc).__name__}: {exc}"[:240]
|
||||||
|
continue
|
||||||
|
raise ValueError(f"OAuth 刷新失败(出口不可用): {last_transport or 'unknown'}")
|
||||||
|
|
||||||
|
|
||||||
async def upload_shorts_mp4(
|
async def upload_shorts_mp4(
|
||||||
|
|||||||
@ -1,5 +1,14 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- 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
|
from __future__ import annotations
|
||||||
|
|
||||||
import json
|
import json
|
||||||
@ -21,18 +30,99 @@ from .global_socks import (
|
|||||||
is_global_socks_enabled,
|
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"
|
_PID_FILE = CONFIG_DIR / "sing-box.pid"
|
||||||
_LOG_PATH = CONFIG_DIR / "sing-box.log"
|
_LOG_PATH = CONFIG_DIR / "sing-box.log"
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_safe_unit(name: str) -> str:
|
||||||
|
raw = str(name or "").strip()
|
||||||
|
base = raw.removesuffix(".service")
|
||||||
|
if raw in FORBIDDEN_UNITS or base in FORBIDDEN_UNITS or base == "sing-box":
|
||||||
|
raise RuntimeError(f"refusing to touch host unit {raw!r} (v2ray-agent / edge)")
|
||||||
|
if base != UNIT_NAME and raw != UNIT_NAME:
|
||||||
|
raise RuntimeError(f"only {UNIT_NAME} is allowed, got {raw!r}")
|
||||||
|
return UNIT_NAME
|
||||||
|
|
||||||
|
|
||||||
|
def _assert_safe_binary(path: str) -> str:
|
||||||
|
"""Refuse any binary under v2ray-agent tree."""
|
||||||
|
p = Path(path).resolve()
|
||||||
|
try:
|
||||||
|
p.relative_to(V2RAY_AGENT_DIR.resolve())
|
||||||
|
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
if "v2ray-agent" in str(p):
|
||||||
|
raise RuntimeError(f"refusing v2ray-agent binary: {p}")
|
||||||
|
return str(p)
|
||||||
|
|
||||||
|
|
||||||
def _find_binary() -> str:
|
def _find_binary() -> str:
|
||||||
for name in ("sing-box", "/usr/bin/sing-box", "/usr/local/bin/sing-box"):
|
"""Only DouyinWEB-owned paths — never PATH /usr/bin or v2ray-agent."""
|
||||||
p = shutil.which(name) if not name.startswith("/") else (name if Path(name).is_file() else None)
|
candidates = [
|
||||||
if p and Path(p).is_file():
|
APP_SINGBOX,
|
||||||
return str(p)
|
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 ""
|
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]:
|
def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
|
||||||
if not profile:
|
if not profile:
|
||||||
raise ValueError("SOCKS 配置无效")
|
raise ValueError("SOCKS 配置无效")
|
||||||
@ -59,7 +149,7 @@ def build_config(profile: dict[str, Any] | None) -> dict[str, Any]:
|
|||||||
{
|
{
|
||||||
"type": "mixed",
|
"type": "mixed",
|
||||||
"tag": "mixed-in",
|
"tag": "mixed-in",
|
||||||
"listen": LOCAL_MIXED_HOST,
|
"listen": _MIXED_LISTEN_HOST,
|
||||||
"listen_port": LOCAL_MIXED_PORT,
|
"listen_port": LOCAL_MIXED_PORT,
|
||||||
"sniff": True,
|
"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:
|
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)
|
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")
|
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
|
return SINGBOX_CONFIG_PATH
|
||||||
|
|
||||||
|
|
||||||
@ -102,10 +275,9 @@ def is_running() -> bool:
|
|||||||
pid = _read_pid()
|
pid = _read_pid()
|
||||||
if _pid_alive(pid):
|
if _pid_alive(pid):
|
||||||
return True
|
return True
|
||||||
# systemd fallback
|
|
||||||
try:
|
try:
|
||||||
r = subprocess.run(
|
r = subprocess.run(
|
||||||
["systemctl", "is-active", "douyinweb-singbox"],
|
["systemctl", "is-active", UNIT_NAME],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=5,
|
timeout=5,
|
||||||
@ -116,25 +288,40 @@ def is_running() -> bool:
|
|||||||
|
|
||||||
|
|
||||||
def stop() -> dict[str, Any]:
|
def stop() -> dict[str, Any]:
|
||||||
|
"""Stop DouyinWEB residential forwarder only — never host sing-box.service."""
|
||||||
pid = _read_pid()
|
pid = _read_pid()
|
||||||
if _pid_alive(pid):
|
if _pid_alive(pid):
|
||||||
try:
|
try:
|
||||||
os.kill(pid, signal.SIGTERM)
|
os.kill(pid, signal.SIGTERM)
|
||||||
time.sleep(0.8)
|
time.sleep(0.8)
|
||||||
|
if _pid_alive(pid):
|
||||||
|
os.kill(pid, signal.SIGKILL)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
try:
|
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:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
_PID_FILE.unlink(missing_ok=True)
|
_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]:
|
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:
|
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)
|
write_config(cfg_dict)
|
||||||
stop()
|
stop()
|
||||||
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
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:]
|
tail = _LOG_PATH.read_text(encoding="utf-8", errors="replace")[-800:]
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
return {"ok": False, "running": False, "error": f"sing-box 启动失败: {tail}"}
|
return {"ok": False, "running": False, "error": f"douyinweb-singbox 启动失败: {tail}"}
|
||||||
return {"ok": True, "running": True, "pid": proc.pid, "binary": binary}
|
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]:
|
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)
|
settings = _settings_dict(cfg)
|
||||||
if not is_global_socks_enabled(settings):
|
if not is_global_socks_enabled(settings):
|
||||||
stop()
|
stop()
|
||||||
return {"ok": True, "running": False, "enabled": False}
|
return {"ok": True, "running": False, "enabled": False, "unit": UNIT_NAME}
|
||||||
prof = active_profile(settings)
|
prof = active_profile(settings)
|
||||||
if not prof:
|
if not prof:
|
||||||
stop()
|
stop()
|
||||||
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置"}
|
return {"ok": False, "running": False, "enabled": True, "error": "无有效 SOCKS 配置", "unit": UNIT_NAME}
|
||||||
try:
|
try:
|
||||||
cfg_dict = build_config(prof)
|
cfg_dict = build_config(prof)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
stop()
|
stop()
|
||||||
return {"ok": False, "running": False, "enabled": True, "error": str(exc)}
|
return {"ok": False, "running": False, "enabled": True, "error": str(exc), "unit": UNIT_NAME}
|
||||||
# Prefer systemd unit when present.
|
|
||||||
write_config(cfg_dict)
|
write_config(cfg_dict)
|
||||||
|
fw = ensure_mixed_not_public()
|
||||||
try:
|
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(
|
r = subprocess.run(
|
||||||
["systemctl", "restart", "douyinweb-singbox"],
|
["systemctl", "restart", UNIT_NAME],
|
||||||
capture_output=True,
|
capture_output=True,
|
||||||
text=True,
|
text=True,
|
||||||
timeout=20,
|
timeout=20,
|
||||||
@ -191,10 +397,72 @@ def apply_from_settings(cfg: dict[str, Any] | None = None) -> dict[str, Any]:
|
|||||||
if r.returncode == 0:
|
if r.returncode == 0:
|
||||||
time.sleep(0.5)
|
time.sleep(0.5)
|
||||||
if is_running():
|
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:
|
except Exception:
|
||||||
pass
|
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]:
|
def status() -> dict[str, Any]:
|
||||||
@ -206,5 +474,12 @@ def status() -> dict[str, Any]:
|
|||||||
"binary": binary,
|
"binary": binary,
|
||||||
"config": str(SINGBOX_CONFIG_PATH),
|
"config": str(SINGBOX_CONFIG_PATH),
|
||||||
"mixed": f"http://{LOCAL_MIXED_HOST}:{LOCAL_MIXED_PORT}",
|
"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": "",
|
"error": "",
|
||||||
}
|
}
|
||||||
|
|||||||
@ -186,6 +186,34 @@ def tiktok_channel_upload_count(channel_pk: str, push_date: str) -> int:
|
|||||||
conn.close()
|
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(
|
def pick_tiktok_channel(
|
||||||
push_date: str,
|
push_date: str,
|
||||||
*,
|
*,
|
||||||
@ -340,6 +368,7 @@ def update_tiktok_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
|
|||||||
allowed = {
|
allowed = {
|
||||||
"status", "clip_path", "clip_seconds", "tiktok_publish_id", "tiktok_video_id",
|
"status", "clip_path", "clip_seconds", "tiktok_publish_id", "tiktok_video_id",
|
||||||
"error", "channel_pk", "stream_url", "attempts", "started_at", "finished_at", "upload_at",
|
"error", "channel_pk", "stream_url", "attempts", "started_at", "finished_at", "upload_at",
|
||||||
|
"push_date",
|
||||||
}
|
}
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
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:
|
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()
|
now = time.time()
|
||||||
|
today = push_date_from_ts(now)
|
||||||
n = 0
|
n = 0
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
@ -587,7 +617,7 @@ def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
|
|||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT id, channel_pk FROM tiktok_jobs
|
SELECT id, channel_pk FROM tiktok_jobs
|
||||||
WHERE status = 'recorded'
|
WHERE status IN ('recorded', 'scheduled')
|
||||||
AND clip_path != ''
|
AND clip_path != ''
|
||||||
AND IFNULL(tiktok_video_id,'') = ''
|
AND IFNULL(tiktok_video_id,'') = ''
|
||||||
AND (error LIKE '%配额已满%')
|
AND (error LIKE '%配额已满%')
|
||||||
@ -596,31 +626,22 @@ def reschedule_soft_quota_held_jobs(*, limit: int = 50) -> int:
|
|||||||
""",
|
""",
|
||||||
(max(1, int(limit)),),
|
(max(1, int(limit)),),
|
||||||
).fetchall()
|
).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:
|
finally:
|
||||||
conn.close()
|
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
|
return n
|
||||||
|
|
||||||
|
|
||||||
@ -657,49 +678,78 @@ def delete_tiktok_jobs_for_channel(channel_pk: str) -> dict[str, int]:
|
|||||||
return {"jobs": jobs, "clips": clips}
|
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:
|
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()
|
now = time.time()
|
||||||
with _lock:
|
today = push_date_from_ts(now)
|
||||||
conn = _connect()
|
# Try a few candidates: defer over-quota rows then pick the next.
|
||||||
try:
|
for i in range(8):
|
||||||
# Skip disabled accounts and accounts under TikTok platform rate-limit
|
with _lock:
|
||||||
row = conn.execute(
|
conn = _connect()
|
||||||
"""
|
try:
|
||||||
SELECT j.* FROM tiktok_jobs j
|
row = conn.execute(
|
||||||
INNER JOIN tiktok_channels c ON c.id = j.channel_pk
|
"""
|
||||||
WHERE j.status = 'scheduled'
|
SELECT j.* FROM tiktok_jobs j
|
||||||
AND c.enabled = 1
|
INNER JOIN tiktok_channels c ON c.id = j.channel_pk
|
||||||
AND j.clip_path != ''
|
WHERE j.status = 'scheduled'
|
||||||
AND IFNULL(j.tiktok_video_id,'') = ''
|
AND c.enabled = 1
|
||||||
AND IFNULL(j.tiktok_publish_id,'') = ''
|
AND j.clip_path != ''
|
||||||
AND j.upload_at > 0
|
AND IFNULL(j.tiktok_video_id,'') = ''
|
||||||
AND j.upload_at <= ?
|
AND IFNULL(j.tiktok_publish_id,'') = ''
|
||||||
AND IFNULL(c.platform_limit_at, 0) <= 0
|
AND j.upload_at > 0
|
||||||
ORDER BY j.upload_at ASC, j.created_at ASC
|
AND j.upload_at <= ?
|
||||||
LIMIT 1
|
AND IFNULL(c.platform_limit_at, 0) <= 0
|
||||||
""",
|
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||||
(now,),
|
LIMIT 1
|
||||||
).fetchone()
|
""",
|
||||||
if not row:
|
(now,),
|
||||||
return None
|
).fetchone()
|
||||||
jid = str(row["id"])
|
if not row:
|
||||||
conn.execute(
|
return None
|
||||||
"""
|
jid = str(row["id"])
|
||||||
UPDATE tiktok_jobs
|
ch_pk = str(row["channel_pk"] or "")
|
||||||
SET status = 'uploading', updated_at = ?, attempts = attempts + 1
|
finally:
|
||||||
WHERE id = ? AND status = 'scheduled'
|
conn.close()
|
||||||
AND IFNULL(tiktok_video_id,'') = ''
|
if ch_pk and channel_at_daily_upload_max(ch_pk, today):
|
||||||
AND IFNULL(tiktok_publish_id,'') = ''
|
defer_tiktok_job_to_next_day(jid, stagger_sec=60 + i * 90)
|
||||||
""",
|
continue
|
||||||
(now, jid),
|
with _lock:
|
||||||
)
|
conn = _connect()
|
||||||
if conn.total_changes == 0:
|
try:
|
||||||
conn.rollback()
|
conn.execute(
|
||||||
return None
|
"""
|
||||||
conn.commit()
|
UPDATE tiktok_jobs
|
||||||
return _row_to_dict(conn.execute("SELECT * FROM tiktok_jobs WHERE id = ?", (jid,)).fetchone())
|
SET status = 'uploading', updated_at = ?, attempts = attempts + 1, error = ''
|
||||||
finally:
|
WHERE id = ? AND status = 'scheduled'
|
||||||
conn.close()
|
AND IFNULL(tiktok_video_id,'') = ''
|
||||||
|
AND IFNULL(tiktok_publish_id,'') = ''
|
||||||
|
""",
|
||||||
|
(now, jid),
|
||||||
|
)
|
||||||
|
if conn.total_changes == 0:
|
||||||
|
conn.rollback()
|
||||||
|
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:
|
def claim_tiktok_job_manual_upload(job_id: str) -> dict[str, Any] | None:
|
||||||
|
|||||||
@ -390,11 +390,16 @@ class TikTokPipeline:
|
|||||||
retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300))
|
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:
|
if cfg.get("tiktok_auto_retry_failed") and (time.time() - self._last_auto_retry_at) >= retry_interval:
|
||||||
self._last_auto_retry_at = time.time()
|
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):
|
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(
|
tiktok_db.update_tiktok_job(
|
||||||
str(j["id"]),
|
str(j["id"]),
|
||||||
status="scheduled",
|
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="",
|
error="",
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
@ -659,6 +664,11 @@ class TikTokPipeline:
|
|||||||
tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传")
|
tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传")
|
||||||
return
|
return
|
||||||
ch_pk = str(channel["id"])
|
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 (
|
if (
|
||||||
not manual
|
not manual
|
||||||
and not probe
|
and not probe
|
||||||
|
|||||||
@ -19,7 +19,7 @@ if str(_VENDOR_ROOT) not in sys.path:
|
|||||||
DEFAULT_DC = "useast2a"
|
DEFAULT_DC = "useast2a"
|
||||||
COOKIE_TTL_DAYS = 30.0
|
COOKIE_TTL_DAYS = 30.0
|
||||||
REQUIRED_COOKIES = ("sessionid", "tt-target-idc")
|
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 = (
|
_PROBE_UA = (
|
||||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||||
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
"(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
|
||||||
|
|||||||
@ -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:
|
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)."""
|
"""Per-account SOCKS if opted in; else fall back to global residential / egress uploads proxy."""
|
||||||
if not channel:
|
if channel:
|
||||||
|
enabled = channel.get("socks_enabled")
|
||||||
|
if isinstance(enabled, str):
|
||||||
|
enabled = enabled.strip().lower() in {"1", "true", "yes", "on"}
|
||||||
|
if enabled:
|
||||||
|
pid = str(channel.get("socks_profile_id") or "").strip()
|
||||||
|
prof = get_socks_profile(pid, cfg)
|
||||||
|
if not prof:
|
||||||
|
rows = list_socks_profiles(cfg, public=False)
|
||||||
|
prof = rows[0] if rows else None
|
||||||
|
url = socks_proxy_url(prof)
|
||||||
|
if url:
|
||||||
|
return url
|
||||||
|
try:
|
||||||
|
from . import egress_hub
|
||||||
|
|
||||||
|
return egress_hub.resolve_upload_proxy(cfg) or ""
|
||||||
|
except Exception:
|
||||||
return ""
|
return ""
|
||||||
enabled = channel.get("socks_enabled")
|
|
||||||
if isinstance(enabled, str):
|
|
||||||
enabled = enabled.strip().lower() in {"1", "true", "yes", "on"}
|
|
||||||
if not enabled:
|
|
||||||
return ""
|
|
||||||
pid = str(channel.get("socks_profile_id") or "").strip()
|
|
||||||
prof = get_socks_profile(pid, cfg)
|
|
||||||
if not prof:
|
|
||||||
rows = list_socks_profiles(cfg, public=False)
|
|
||||||
prof = rows[0] if rows else None
|
|
||||||
return socks_proxy_url(prof)
|
|
||||||
|
|
||||||
|
|
||||||
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
|
||||||
|
|||||||
@ -111,6 +111,14 @@ def _http_channel_live_probe(channel_id: str) -> dict[str, Any]:
|
|||||||
html = ""
|
html = ""
|
||||||
last_err = ""
|
last_err = ""
|
||||||
proxies_try: list[str] = []
|
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 = (
|
env_proxy = (
|
||||||
str(os.environ.get("HTTPS_PROXY") or os.environ.get("https_proxy") or "").strip()
|
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()
|
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:
|
if env_proxy:
|
||||||
proxies_try.append(env_proxy)
|
proxies_try.append(env_proxy)
|
||||||
proxies_try.append("") # direct
|
proxies_try.append("") # direct
|
||||||
# Physical China guest: ShellCrash (same as douyinweb-yt) if env unset / direct fails
|
# Soft fallbacks (physical ShellCrash / legacy) — only if not already listed
|
||||||
if "127.0.0.1:7890" not in env_proxy:
|
for soft in ("http://127.0.0.1:17891", "http://127.0.0.1:7890"):
|
||||||
proxies_try.append("http://127.0.0.1:7890")
|
if soft not in proxies_try:
|
||||||
|
proxies_try.append(soft)
|
||||||
seen_p: set[str] = set()
|
seen_p: set[str] = set()
|
||||||
for proxy in proxies_try:
|
for proxy in proxies_try:
|
||||||
if proxy in seen_p:
|
if proxy in seen_p:
|
||||||
|
|||||||
@ -52,10 +52,10 @@ async def record_long_clip(
|
|||||||
job_id: str,
|
job_id: str,
|
||||||
stream_urls: list[str] | None = None,
|
stream_urls: list[str] | None = None,
|
||||||
stream_url: str = "",
|
stream_url: str = "",
|
||||||
seconds: int = 300,
|
seconds: int = 600,
|
||||||
cfg: dict[str, Any] | None = None,
|
cfg: dict[str, Any] | None = None,
|
||||||
) -> dict[str, Any]:
|
) -> 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] = []
|
urls: list[str] = []
|
||||||
for u in list(stream_urls or []) + [stream_url]:
|
for u in list(stream_urls or []) + [stream_url]:
|
||||||
s = str(u or "").strip()
|
s = str(u or "").strip()
|
||||||
@ -64,7 +64,7 @@ async def record_long_clip(
|
|||||||
if not urls:
|
if not urls:
|
||||||
return {"ok": False, "error": "无可用流地址"}
|
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"
|
out_path = clips_dir() / f"{job_id}.mp4"
|
||||||
vf = _vf_for_settings(cfg)
|
vf = _vf_for_settings(cfg)
|
||||||
last_err = ""
|
last_err = ""
|
||||||
|
|||||||
@ -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_CHANNEL_LIMITED = 4 # when shared YouTube API quota is limited (3 < n < 5)
|
||||||
YT_LONG_DAILY_DEFAULT = 70 # 14 channels × 5
|
YT_LONG_DAILY_DEFAULT = 70 # 14 channels × 5
|
||||||
YT_LONG_SOURCE_DEFAULT = 70
|
YT_LONG_SOURCE_DEFAULT = 70
|
||||||
YT_LONG_MIN_SEC = 180 # 3 min
|
YT_LONG_MIN_SEC = 480 # 8 min
|
||||||
YT_LONG_MAX_SEC = 480 # 8 min
|
YT_LONG_MAX_SEC = 900 # 15 min
|
||||||
|
|
||||||
|
|
||||||
def ensure_yt_long_tables(conn: sqlite3.Connection) -> None:
|
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))
|
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:
|
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
|
from . import db
|
||||||
|
|
||||||
settings = cfg if cfg is not None else db.get_settings_map()
|
settings = cfg if cfg is not None else db.get_settings_map()
|
||||||
upload_cap = yt_long_daily_max(settings)
|
upload_cap = yt_long_enabled_upload_cap(settings)
|
||||||
try:
|
if upload_cap <= 0:
|
||||||
v = int(settings.get("yt_long_source_daily_max") or 0)
|
upload_cap = yt_long_daily_max(settings)
|
||||||
except Exception:
|
return max(0, upload_cap)
|
||||||
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))
|
|
||||||
|
|
||||||
|
|
||||||
def youtube_api_upload_limited(cfg: dict[str, Any] | None = None) -> bool:
|
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)
|
limited = youtube_api_upload_limited(settings)
|
||||||
per = effective_yt_long_channel_daily_max(settings)
|
per = effective_yt_long_channel_daily_max(settings)
|
||||||
n = count_oauth_yt_long_channels(enabled_only=True)
|
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:
|
try:
|
||||||
stored_global = int(settings.get("yt_long_daily_max") or 0)
|
stored_global = int(settings.get("yt_long_daily_max") or 0)
|
||||||
except Exception:
|
except Exception:
|
||||||
stored_global = 0
|
stored_global = 0
|
||||||
|
patch: dict[str, Any] = {}
|
||||||
if stored_global != global_max:
|
if stored_global != global_max:
|
||||||
|
patch["yt_long_daily_max"] = global_max
|
||||||
|
# Keep source in lockstep with enabled upload cap (clear Shorts-inflated 63 etc.).
|
||||||
|
try:
|
||||||
|
stored_src = int(settings.get("yt_long_source_daily_max") or 0)
|
||||||
|
except Exception:
|
||||||
|
stored_src = 0
|
||||||
|
if stored_src != global_max:
|
||||||
|
patch["yt_long_source_daily_max"] = global_max
|
||||||
|
if patch:
|
||||||
try:
|
try:
|
||||||
db.update_settings_map({"yt_long_daily_max": global_max})
|
db.update_settings_map(patch)
|
||||||
settings = db.get_settings_map()
|
settings = db.get_settings_map()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@ -777,27 +806,43 @@ def claim_due_yt_long_upload(*, skip_profile_ids: set[str] | None = None) -> dic
|
|||||||
ensure_yt_long_tables(conn)
|
ensure_yt_long_tables(conn)
|
||||||
rows = conn.execute(
|
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
|
FROM yt_long_jobs j
|
||||||
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
INNER JOIN yt_long_channels c ON c.id = j.channel_pk
|
||||||
WHERE j.status = 'scheduled'
|
WHERE j.status = 'scheduled'
|
||||||
AND c.enabled = 1
|
AND c.enabled = 1
|
||||||
|
AND IFNULL(c.oauth_ok, -1) != 0
|
||||||
AND j.clip_path != ''
|
AND j.clip_path != ''
|
||||||
AND j.upload_at > 0
|
AND j.upload_at > 0
|
||||||
AND j.upload_at <= ?
|
AND j.upload_at <= ?
|
||||||
ORDER BY j.upload_at ASC, j.created_at ASC
|
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||||
LIMIT 30
|
LIMIT 40
|
||||||
""",
|
""",
|
||||||
(now,),
|
(now,),
|
||||||
).fetchall()
|
).fetchall()
|
||||||
|
import os
|
||||||
picked = None
|
picked = None
|
||||||
for row in rows:
|
for row in rows:
|
||||||
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
|
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
|
||||||
if pid in skip:
|
if pid in skip:
|
||||||
continue
|
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
|
picked = row
|
||||||
break
|
break
|
||||||
if not picked:
|
if not picked:
|
||||||
|
conn.commit()
|
||||||
return None
|
return None
|
||||||
jid = str(picked["id"])
|
jid = str(picked["id"])
|
||||||
cur = conn.execute(
|
cur = conn.execute(
|
||||||
@ -877,9 +922,9 @@ def count_yt_long_jobs_by_status(status: str, *, push_date: str = "") -> int:
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 720) -> int:
|
def reclaim_stale_yt_long_recordings(*, max_age_sec: float = 1200) -> int:
|
||||||
"""Reclaim orphan recording rows. Never reclaim before ~12 min (3–8 min clip + encode slack)."""
|
"""Reclaim orphan recording rows. Never reclaim before ~20 min (8–15 min clip + encode slack)."""
|
||||||
age = max(720.0, float(max_age_sec))
|
age = max(1200.0, float(max_age_sec))
|
||||||
cutoff = time.time() - age
|
cutoff = time.time() - age
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
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:
|
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:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
ensure_yt_long_tables(conn)
|
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(
|
cur = conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE yt_long_jobs
|
UPDATE yt_long_jobs
|
||||||
SET status = 'scheduled', error = 'upload_stale_reclaim', updated_at = ?
|
SET status = 'uploaded',
|
||||||
WHERE status = 'uploading' AND updated_at < ?
|
error = CASE
|
||||||
AND IFNULL(youtube_video_id, '') = ''
|
WHEN IFNULL(error,'') = '' THEN 'heal_promoted_existing_video_id'
|
||||||
|
ELSE error
|
||||||
|
END,
|
||||||
|
finished_at = CASE WHEN IFNULL(finished_at,0)=0 THEN ? ELSE finished_at END,
|
||||||
|
updated_at = ?
|
||||||
|
WHERE status IN ('scheduled', 'uploading', 'recorded')
|
||||||
|
AND IFNULL(youtube_video_id, '') != ''
|
||||||
""",
|
""",
|
||||||
(time.time(), cutoff),
|
(now, now),
|
||||||
)
|
)
|
||||||
conn.commit()
|
promoted = int(cur.rowcount or 0)
|
||||||
return int(cur.rowcount or 0)
|
|
||||||
|
# 2) uploading after process restart is never resumed → requeue/fail by file
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, clip_path, clip_seconds, attempts
|
||||||
|
FROM yt_long_jobs
|
||||||
|
WHERE status = 'uploading' AND IFNULL(youtube_video_id, '') = ''
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
for row in rows:
|
||||||
|
jid = str(row["id"])
|
||||||
|
path = str(row["clip_path"] or "").strip()
|
||||||
|
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
|
||||||
|
attempts = int(row["attempts"] or 0)
|
||||||
|
if alive:
|
||||||
|
backoff = min(900.0, 30.0 * (2 ** min(5, max(0, attempts - 1))))
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE yt_long_jobs
|
||||||
|
SET status = 'scheduled',
|
||||||
|
error = 'upload_restart_requeue',
|
||||||
|
upload_at = ?,
|
||||||
|
updated_at = ?
|
||||||
|
WHERE id = ? AND status = 'uploading'
|
||||||
|
""",
|
||||||
|
(now + backoff, now, jid),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE yt_long_jobs
|
||||||
|
SET status = 'pending',
|
||||||
|
clip_path = '',
|
||||||
|
clip_seconds = 0,
|
||||||
|
upload_at = 0,
|
||||||
|
started_at = 0,
|
||||||
|
error = '成片丢失,已重新排队录制',
|
||||||
|
updated_at = ?
|
||||||
|
WHERE id = ? AND status = 'uploading'
|
||||||
|
""",
|
||||||
|
(now, jid),
|
||||||
|
)
|
||||||
|
restart_orphans += 1
|
||||||
|
|
||||||
|
# 3) scheduled/recorded without master file → re-record
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT id, clip_path, status, error
|
||||||
|
FROM yt_long_jobs
|
||||||
|
WHERE status IN ('scheduled', 'recorded')
|
||||||
|
AND IFNULL(youtube_video_id, '') = ''
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
for row in rows:
|
||||||
|
err = str(row["error"] or "")
|
||||||
|
if err.startswith("cascade_only"):
|
||||||
|
continue
|
||||||
|
path = str(row["clip_path"] or "").strip()
|
||||||
|
alive = bool(path) and os.path.isfile(path) and os.path.getsize(path) > 1024
|
||||||
|
if alive:
|
||||||
|
continue
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE yt_long_jobs
|
||||||
|
SET status = 'pending',
|
||||||
|
clip_path = '',
|
||||||
|
clip_seconds = 0,
|
||||||
|
upload_at = 0,
|
||||||
|
started_at = 0,
|
||||||
|
error = '成片丢失,已重新排队录制',
|
||||||
|
updated_at = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(now, str(row["id"])),
|
||||||
|
)
|
||||||
|
missing += 1
|
||||||
|
|
||||||
|
if missing or promoted or restart_orphans:
|
||||||
|
conn.commit()
|
||||||
finally:
|
finally:
|
||||||
conn.close()
|
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]:
|
def yt_long_stats(push_date: str = "") -> dict[str, Any]:
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""Isolated YouTube long-form (default 9:16) pipeline.
|
"""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).
|
via clip_cascade (each platform keeps its own tables and quotas).
|
||||||
Default: disabled (yt_long_enabled=false) until an operator turns this on.
|
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 "")
|
cid = str(ch.get("id") or "")
|
||||||
if not cid:
|
if not cid:
|
||||||
continue
|
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)
|
creds = _channel_creds(ch, cfg)
|
||||||
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
|
if not (creds.get("refresh_token") and creds.get("client_id") and creds.get("client_secret")):
|
||||||
continue
|
continue
|
||||||
@ -453,7 +459,7 @@ class YtLongPipeline:
|
|||||||
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
|
"clip_cascade_enabled": bool(cfg.get("clip_cascade_enabled", True)),
|
||||||
"yt_long_monetize_when_ypp": bool(cfg.get("yt_long_monetize_when_ypp", 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_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
|
self._status_cache = payload
|
||||||
@ -534,11 +540,11 @@ class YtLongPipeline:
|
|||||||
async def kick_pending_records(self, ids: list[str] | None = None) -> int:
|
async def kick_pending_records(self, ids: list[str] | None = None) -> int:
|
||||||
cfg = db.get_settings_map()
|
cfg = db.get_settings_map()
|
||||||
max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1))
|
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:
|
try:
|
||||||
from .host_metrics import clip_encode_defer_reason
|
from .host_metrics import clip_encode_defer_reason
|
||||||
|
|
||||||
if clip_encode_defer_reason():
|
if clip_encode_defer_reason(respect_live_push=False):
|
||||||
return 0
|
return 0
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@ -588,13 +594,20 @@ class YtLongPipeline:
|
|||||||
if n:
|
if n:
|
||||||
self.sampled += n
|
self.sampled += n
|
||||||
try:
|
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)
|
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:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
try:
|
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:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
@ -651,9 +664,14 @@ class YtLongPipeline:
|
|||||||
pass
|
pass
|
||||||
# Never steal CPU from live YouTube push (site hang root cause on dy VPS).
|
# Never steal CPU from live YouTube push (site hang root cause on dy VPS).
|
||||||
try:
|
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:
|
except Exception:
|
||||||
defer = ""
|
defer = ""
|
||||||
while (
|
while (
|
||||||
@ -742,7 +760,7 @@ class YtLongPipeline:
|
|||||||
try:
|
try:
|
||||||
from .clip_retention import disk_free_gb
|
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))
|
sec = min(sec, max(YT_LONG_MIN_SEC, int(cfg.get("yt_long_min_sec") or YT_LONG_MIN_SEC) + 60))
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@ -848,6 +866,7 @@ class YtLongPipeline:
|
|||||||
)
|
)
|
||||||
if is_quota:
|
if is_quota:
|
||||||
should_notify = True
|
should_notify = True
|
||||||
|
until = time.time() + 3600
|
||||||
try:
|
try:
|
||||||
from .shorts_yt_quota import mark_api_quota_cooldown, profile_id_for_channel
|
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()
|
yt_long_db.reconcile_yt_long_upload_caps()
|
||||||
except Exception:
|
except Exception:
|
||||||
should_notify = True
|
should_notify = True
|
||||||
|
# Keep the master: defer this job instead of burning it as failed.
|
||||||
yt_long_db.update_yt_long_job(
|
yt_long_db.update_yt_long_job(
|
||||||
str(job.get("id") or ""),
|
str(job.get("id") or ""),
|
||||||
status="failed",
|
status="scheduled",
|
||||||
error=str(exc)[:500],
|
upload_at=float(until) + 30,
|
||||||
finished_at=time.time(),
|
error=f"QUOTA_DEFER: {str(exc)[:400]}",
|
||||||
|
finished_at=0,
|
||||||
)
|
)
|
||||||
if should_notify:
|
if should_notify:
|
||||||
_emit(
|
_emit(
|
||||||
"yt_long_fail",
|
"yt_long_fail",
|
||||||
"warn",
|
"warn",
|
||||||
f"长视频:YouTube 接口配额用尽(冷静后重试,不拦手动):{str(exc)[:80]}",
|
f"长视频:YouTube 接口配额用尽(已延后自动重试):{str(exc)[:80]}",
|
||||||
job,
|
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:
|
else:
|
||||||
yt_long_db.update_yt_long_job(
|
yt_long_db.update_yt_long_job(
|
||||||
str(job.get("id") or ""),
|
str(job.get("id") or ""),
|
||||||
|
|||||||
@ -1,7 +1,14 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- 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
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import re
|
||||||
|
from collections.abc import AsyncIterator
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
from typing import Any
|
from typing import Any
|
||||||
|
|
||||||
@ -14,6 +21,35 @@ from .shorts_upload import (
|
|||||||
refresh_access_token,
|
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(
|
async def upload_youtube_long_mp4(
|
||||||
*,
|
*,
|
||||||
@ -37,21 +73,19 @@ async def upload_youtube_long_mp4(
|
|||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
size = path.stat().st_size
|
size = path.stat().st_size
|
||||||
raw = path.read_bytes()
|
|
||||||
except FileNotFoundError as exc:
|
except FileNotFoundError as exc:
|
||||||
raise ValueError("成片文件不存在") from exc
|
raise ValueError("成片文件不存在") from exc
|
||||||
|
if size <= 0:
|
||||||
|
raise ValueError("成片文件为空")
|
||||||
|
|
||||||
# No #Shorts — this is a normal YouTube watch video (9:16 vertical by default).
|
# 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 = (title or "Live clip").replace("#Shorts", "").replace("#shorts", "").strip()
|
||||||
clean_title = re.sub(r"[<>]+", " ", clean_title)
|
clean_title = _sanitize_yt_text(clean_title, limit=100) or "Live clip"
|
||||||
clean_title = re.sub(r"\s+", " ", clean_title).strip()[:100]
|
clean_desc = _sanitize_yt_text(description or "", limit=4900)
|
||||||
meta = {
|
meta = {
|
||||||
"snippet": {
|
"snippet": {
|
||||||
"title": clean_title or "Live clip",
|
"title": clean_title,
|
||||||
"description": description or "",
|
"description": clean_desc,
|
||||||
"categoryId": "22",
|
"categoryId": "22",
|
||||||
},
|
},
|
||||||
"status": {
|
"status": {
|
||||||
@ -63,7 +97,8 @@ async def upload_youtube_long_mp4(
|
|||||||
"https://www.googleapis.com/upload/youtube/v3/videos"
|
"https://www.googleapis.com/upload/youtube/v3/videos"
|
||||||
"?uploadType=resumable&part=snippet,status"
|
"?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 = await client.post(
|
||||||
init_url,
|
init_url,
|
||||||
headers={
|
headers={
|
||||||
@ -79,7 +114,12 @@ async def upload_youtube_long_mp4(
|
|||||||
body = init.text[:800]
|
body = init.text[:800]
|
||||||
if init.status_code == 429 or is_upload_quota_error(body):
|
if init.status_code == 429 or is_upload_quota_error(body):
|
||||||
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({body[:200]})")
|
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]}")
|
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(
|
put = await client.put(
|
||||||
upload_url,
|
upload_url,
|
||||||
headers={
|
headers={
|
||||||
@ -87,13 +127,15 @@ async def upload_youtube_long_mp4(
|
|||||||
"Content-Type": "video/mp4",
|
"Content-Type": "video/mp4",
|
||||||
"Content-Length": str(size),
|
"Content-Length": str(size),
|
||||||
},
|
},
|
||||||
content=raw,
|
content=_aiter_file_chunks(path),
|
||||||
)
|
)
|
||||||
data = put.json() if put.content else {}
|
data = put.json() if put.content else {}
|
||||||
if put.status_code >= 400 or not data.get("id"):
|
if put.status_code >= 400 or not data.get("id"):
|
||||||
err_text = str(data.get("error") or put.text[:800])
|
err_text = str(data.get("error") or put.text[:800])
|
||||||
if put.status_code == 429 or is_upload_quota_error(err_text):
|
if put.status_code == 429 or is_upload_quota_error(err_text):
|
||||||
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()} ({err_text[:200]})")
|
raise ValueError(f"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]}")
|
raise ValueError(f"上传失败: {err_text[:400]}")
|
||||||
vid = str(data["id"])
|
vid = str(data["id"])
|
||||||
return {
|
return {
|
||||||
@ -101,4 +143,6 @@ async def upload_youtube_long_mp4(
|
|||||||
"video_id": vid,
|
"video_id": vid,
|
||||||
"url": f"https://www.youtube.com/watch?v={vid}",
|
"url": f"https://www.youtube.com/watch?v={vid}",
|
||||||
"raw": data,
|
"raw": data,
|
||||||
|
"bytes": size,
|
||||||
|
"timeout_sec": timeout,
|
||||||
}
|
}
|
||||||
|
|||||||
0
backend/neko/browser-launch.sh
Normal file → Executable file
0
backend/neko/browser-launch.sh
Normal file → Executable file
BIN
bin/sing-box
Executable file
BIN
bin/sing-box
Executable file
Binary file not shown.
9
config/proxychains.conf
Normal file
9
config/proxychains.conf
Normal 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
34
config/sing-box.json
Normal 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"
|
||||||
|
}
|
||||||
|
}
|
||||||
175
frontend/package-lock.json
generated
175
frontend/package-lock.json
generated
@ -10,7 +10,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"echarts": "^5.5.1",
|
"echarts": "^5.5.1",
|
||||||
"lucide-react": "^0.468.0",
|
"lucide-react": "^0.468.0",
|
||||||
"next": "15.1.0",
|
"next": "15.1.11",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0"
|
||||||
},
|
},
|
||||||
@ -20,7 +20,7 @@
|
|||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "15.1.0",
|
"eslint-config-next": "15.1.11",
|
||||||
"postcss": "^8.4.49",
|
"postcss": "^8.4.49",
|
||||||
"tailwindcss": "^3.4.17",
|
"tailwindcss": "^3.4.17",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
@ -388,9 +388,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -407,9 +404,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -426,9 +420,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -445,9 +436,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -464,9 +452,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -483,9 +468,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "LGPL-3.0-or-later",
|
"license": "LGPL-3.0-or-later",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -502,9 +484,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -527,9 +506,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -552,9 +528,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -577,9 +550,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -602,9 +572,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -627,9 +594,6 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -764,15 +728,15 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/env": {
|
"node_modules/@next/env": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.11",
|
||||||
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/env/-/env-15.1.11.tgz",
|
||||||
"integrity": "sha512-UcCO481cROsqJuszPPXJnb7GGuLq617ve4xuAyyNG4VSSocJNtMU5Fsx+Lp6mlN8c7W58aZLc5y6D/2xNmaK+w==",
|
"integrity": "sha512-yp++FVldfLglEG5LoS2rXhGypPyoSOyY0kxZQJ2vnlYJeP8o318t5DrDu5Tqzr03qAhDWllAID/kOCsXNLcwKw==",
|
||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/@next/eslint-plugin-next": {
|
"node_modules/@next/eslint-plugin-next": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.11",
|
||||||
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-15.1.11.tgz",
|
||||||
"integrity": "sha512-+jPT0h+nelBT6HC9ZCHGc7DgGVy04cv4shYdAe6tKlEbjQUtwU3LzQhzbDHQyY2m6g39m6B0kOFVuLGBrxxbGg==",
|
"integrity": "sha512-jpAu+46v5FF/TO8YUdOBHn/Wr4SCiU4IgjQ45S9Nn3vR4nZVS2SR+m9lpxcCv/xqMUoYuYFQZUP0H/ptw0W6+w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@ -780,9 +744,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-darwin-arm64": {
|
"node_modules/@next/swc-darwin-arm64": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-15.1.9.tgz",
|
||||||
"integrity": "sha512-ZU8d7xxpX14uIaFC3nsr4L++5ZS/AkWDm1PzPO6gD9xWhFkOj2hzSbSIxoncsnlJXB1CbLOfGVN4Zk9tg83PUw==",
|
"integrity": "sha512-sQF6MfW4nk0PwMYYq8xNgqyxZJGIJV16QqNDgaZ5ze9YoVzm4/YNx17X0exZudayjL9PF0/5RGffDtzXapch0Q==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@ -796,9 +760,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-darwin-x64": {
|
"node_modules/@next/swc-darwin-x64": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-15.1.9.tgz",
|
||||||
"integrity": "sha512-DQ3RiUoW2XC9FcSM4ffpfndq1EsLV0fj0/UY33i7eklW5akPUCo6OX2qkcLXZ3jyPdo4sf2flwAED3AAq3Om2Q==",
|
"integrity": "sha512-fp0c1rB6jZvdSDhprOur36xzQvqelAkNRXM/An92sKjjtaJxjlqJR8jiQLQImPsClIu8amQn+ZzFwl1lsEf62w==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@ -812,15 +776,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-arm64-gnu": {
|
"node_modules/@next/swc-linux-arm64-gnu": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-15.1.9.tgz",
|
||||||
"integrity": "sha512-M+vhTovRS2F//LMx9KtxbkWk627l5Q7AqXWWWrfIzNIaUFiz2/NkOFkxCFyNyGACi5YbA8aekzCLtbDyfF/v5Q==",
|
"integrity": "sha512-77rYykF6UtaXvxh9YyRIKoaYPI6/YX6cy8j1DL5/1XkjbfOwFDfTEhH7YGPqG/ePl+emBcbDYC2elgEqY2e+ag==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -831,15 +792,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-arm64-musl": {
|
"node_modules/@next/swc-linux-arm64-musl": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-15.1.9.tgz",
|
||||||
"integrity": "sha512-Qn6vOuwaTCx3pNwygpSGtdIu0TfS1KiaYLYXLH5zq1scoTXdwYfdZtwvJTpB1WrLgiQE2Ne2kt8MZok3HlFqmg==",
|
"integrity": "sha512-uZ1HazKcyWC7RA6j+S/8aYgvxmDqwnG+gE5S9MhY7BTMj7ahXKunpKuX8/BA2M7OvINLv7LTzoobQbw928p3WA==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -850,15 +808,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-x64-gnu": {
|
"node_modules/@next/swc-linux-x64-gnu": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-15.1.9.tgz",
|
||||||
"integrity": "sha512-yeNh9ofMqzOZ5yTOk+2rwncBzucc6a1lyqtg8xZv0rH5znyjxHOWsoUtSq4cUTeeBIiXXX51QOOe+VoCjdXJRw==",
|
"integrity": "sha512-gQIX1d3ct2RBlgbbWOrp+SHExmtmFm/HSW1Do5sSGMDyzbkYhS2sdq5LRDJWWsQu+/MqpgJHqJT6ORolKp/U1g==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -869,15 +824,12 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-linux-x64-musl": {
|
"node_modules/@next/swc-linux-x64-musl": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-15.1.9.tgz",
|
||||||
"integrity": "sha512-t9IfNkHQs/uKgPoyEtU912MG6a1j7Had37cSUyLTKx9MnUpjj+ZDKw9OyqTI9OwIIv0wmkr1pkZy+3T5pxhJPg==",
|
"integrity": "sha512-fJOwxAbCeq6Vo7pXZGDP6iA4+yIBGshp7ie2Evvge7S7lywyg7b/SGqcvWq/jYcmd0EbXdb7hBfdqSQwTtGTPg==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -888,9 +840,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-win32-arm64-msvc": {
|
"node_modules/@next/swc-win32-arm64-msvc": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-15.1.9.tgz",
|
||||||
"integrity": "sha512-WEAoHyG14t5sTavZa1c6BnOIEukll9iqFRTavqRVPfYmfegOAd5MaZfXgOGG6kGo1RduyGdTHD4+YZQSdsNZXg==",
|
"integrity": "sha512-crfbUkAd9PVg9nGfyjSzQbz82dPvc4pb1TeP0ZaAdGzTH6OfTU9kxidpFIogw0DYIEadI7hRSvuihy2NezkaNQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
@ -904,9 +856,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@next/swc-win32-x64-msvc": {
|
"node_modules/@next/swc-win32-x64-msvc": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.9",
|
||||||
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-15.1.9.tgz",
|
||||||
"integrity": "sha512-J1YdKuJv9xcixzXR24Dv+4SaDKc2jj31IVUEMdO5xJivMTXuE6MAdIi4qPjSymHuFG8O5wbfWKnhJUcHHpj5CA==",
|
"integrity": "sha512-SBB0oA4E2a0axUrUwLqXlLkSn+bRx9OWU6LheqmRrO53QEAJP7JquKh3kF0jRzmlYOWFZtQwyIWJMEJMtvvDcQ==",
|
||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
@ -1460,9 +1412,6 @@
|
|||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1477,9 +1426,6 @@
|
|||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1494,9 +1440,6 @@
|
|||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1511,9 +1454,6 @@
|
|||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1528,9 +1468,6 @@
|
|||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1545,9 +1482,6 @@
|
|||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1562,9 +1496,6 @@
|
|||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1579,9 +1510,6 @@
|
|||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1596,9 +1524,6 @@
|
|||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"glibc"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -1613,9 +1538,6 @@
|
|||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"libc": [
|
|
||||||
"musl"
|
|
||||||
],
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@ -2898,13 +2820,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/eslint-config-next": {
|
"node_modules/eslint-config-next": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.11",
|
||||||
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-15.1.11.tgz",
|
||||||
"integrity": "sha512-gADO+nKVseGso3DtOrYX9H7TxB/MuX7AUYhMlvQMqLYvUWu4HrOQuU7cC1HW74tHIqkAvXdwgAz3TCbczzSEXw==",
|
"integrity": "sha512-RK5q3f8CKMTwNXULOqd2TAsz+7kA5+5fy5YK7T6SeczLFOuOUcuJOGlYUbyoeU6+UKQrpFsYgCz71hI1F9q5Cg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@next/eslint-plugin-next": "15.1.0",
|
"@next/eslint-plugin-next": "15.1.11",
|
||||||
"@rushstack/eslint-patch": "^1.10.3",
|
"@rushstack/eslint-patch": "^1.10.3",
|
||||||
"@typescript-eslint/eslint-plugin": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
|
"@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",
|
"@typescript-eslint/parser": "^5.4.2 || ^6.0.0 || ^7.0.0 || ^8.0.0",
|
||||||
@ -4527,13 +4449,12 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/next": {
|
"node_modules/next": {
|
||||||
"version": "15.1.0",
|
"version": "15.1.11",
|
||||||
"resolved": "https://registry.npmjs.org/next/-/next-15.1.0.tgz",
|
"resolved": "https://registry.npmjs.org/next/-/next-15.1.11.tgz",
|
||||||
"integrity": "sha512-QKhzt6Y8rgLNlj30izdMbxAwjHMFANnLwDwZ+WQh5sMhyt4lEBqDK9QpvWHtIM4rINKPoJ8aiRZKg5ULSybVHw==",
|
"integrity": "sha512-UiVJaOGhKST58AadwbFUZThlNBmYhKqaCs8bVtm4plTxsgKq0mJ0zTsp7t7j/rzsbAEj9WcAMdZCztjByi4EoQ==",
|
||||||
"deprecated": "This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/CVE-2025-66478 for more details.",
|
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@next/env": "15.1.0",
|
"@next/env": "15.1.11",
|
||||||
"@swc/counter": "0.1.3",
|
"@swc/counter": "0.1.3",
|
||||||
"@swc/helpers": "0.5.15",
|
"@swc/helpers": "0.5.15",
|
||||||
"busboy": "1.6.0",
|
"busboy": "1.6.0",
|
||||||
@ -4548,14 +4469,14 @@
|
|||||||
"node": "^18.18.0 || ^19.8.0 || >= 20.0.0"
|
"node": "^18.18.0 || ^19.8.0 || >= 20.0.0"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"optionalDependencies": {
|
||||||
"@next/swc-darwin-arm64": "15.1.0",
|
"@next/swc-darwin-arm64": "15.1.9",
|
||||||
"@next/swc-darwin-x64": "15.1.0",
|
"@next/swc-darwin-x64": "15.1.9",
|
||||||
"@next/swc-linux-arm64-gnu": "15.1.0",
|
"@next/swc-linux-arm64-gnu": "15.1.9",
|
||||||
"@next/swc-linux-arm64-musl": "15.1.0",
|
"@next/swc-linux-arm64-musl": "15.1.9",
|
||||||
"@next/swc-linux-x64-gnu": "15.1.0",
|
"@next/swc-linux-x64-gnu": "15.1.9",
|
||||||
"@next/swc-linux-x64-musl": "15.1.0",
|
"@next/swc-linux-x64-musl": "15.1.9",
|
||||||
"@next/swc-win32-arm64-msvc": "15.1.0",
|
"@next/swc-win32-arm64-msvc": "15.1.9",
|
||||||
"@next/swc-win32-x64-msvc": "15.1.0",
|
"@next/swc-win32-x64-msvc": "15.1.9",
|
||||||
"sharp": "^0.33.5"
|
"sharp": "^0.33.5"
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
|
|||||||
@ -11,7 +11,7 @@
|
|||||||
"dependencies": {
|
"dependencies": {
|
||||||
"echarts": "^5.5.1",
|
"echarts": "^5.5.1",
|
||||||
"lucide-react": "^0.468.0",
|
"lucide-react": "^0.468.0",
|
||||||
"next": "15.1.0",
|
"next": "15.1.11",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
"react-dom": "^19.0.0"
|
"react-dom": "^19.0.0"
|
||||||
},
|
},
|
||||||
@ -21,7 +21,7 @@
|
|||||||
"@types/react-dom": "^19",
|
"@types/react-dom": "^19",
|
||||||
"autoprefixer": "^10.4.20",
|
"autoprefixer": "^10.4.20",
|
||||||
"eslint": "^9",
|
"eslint": "^9",
|
||||||
"eslint-config-next": "15.1.0",
|
"eslint-config-next": "15.1.11",
|
||||||
"postcss": "^8.4.49",
|
"postcss": "^8.4.49",
|
||||||
"tailwindcss": "^3.4.17",
|
"tailwindcss": "^3.4.17",
|
||||||
"typescript": "^5"
|
"typescript": "^5"
|
||||||
|
|||||||
@ -23,6 +23,7 @@ type ScRoot = { root_id: string; label: string; file_count: number; files?: ScFi
|
|||||||
type EgressPayload = {
|
type EgressPayload = {
|
||||||
mode?: string;
|
mode?: string;
|
||||||
chain_residential?: boolean;
|
chain_residential?: boolean;
|
||||||
|
host_profile?: string;
|
||||||
modes?: Array<{ id: string; label: string; description?: string; ready?: boolean }>;
|
modes?: Array<{ id: string; label: string; description?: string; ready?: boolean }>;
|
||||||
cover?: { neko?: boolean; relay?: boolean; uploads?: boolean };
|
cover?: { neko?: boolean; relay?: boolean; uploads?: boolean };
|
||||||
host_proxy?: string;
|
host_proxy?: string;
|
||||||
@ -32,6 +33,8 @@ type EgressPayload = {
|
|||||||
matrix?: Array<{ id: string; label: string; active?: boolean; detail?: string }>;
|
matrix?: Array<{ id: string; label: string; active?: boolean; detail?: string }>;
|
||||||
proxychains?: { installed?: boolean; relay_active?: boolean; bin?: string };
|
proxychains?: { installed?: boolean; relay_active?: boolean; bin?: string };
|
||||||
shellcrash?: { running?: boolean; mixed_port?: string; selected_node?: string | null };
|
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[];
|
hints?: string[];
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -126,7 +129,7 @@ export default function NetworkPage() {
|
|||||||
const [filePath, setFilePath] = useState("");
|
const [filePath, setFilePath] = useState("");
|
||||||
const [fileContent, setFileContent] = useState("");
|
const [fileContent, setFileContent] = useState("");
|
||||||
const [fileImportKey, setFileImportKey] = useState(0);
|
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 [chainResidential, setChainResidential] = useState(false);
|
||||||
const [coverNeko, setCoverNeko] = useState(true);
|
const [coverNeko, setCoverNeko] = useState(true);
|
||||||
const [coverRelay, setCoverRelay] = useState(true);
|
const [coverRelay, setCoverRelay] = useState(true);
|
||||||
@ -185,7 +188,7 @@ export default function NetworkPage() {
|
|||||||
/* editor stays empty if unreadable */
|
/* editor stays empty if unreadable */
|
||||||
}
|
}
|
||||||
const mode = String(r.egress?.mode || "off");
|
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));
|
setChainResidential(Boolean(r.egress?.chain_residential));
|
||||||
setCoverNeko(r.egress?.cover?.neko !== false);
|
setCoverNeko(r.egress?.cover?.neko !== false);
|
||||||
setCoverRelay(Boolean(r.egress?.cover?.relay));
|
setCoverRelay(Boolean(r.egress?.cover?.relay));
|
||||||
@ -217,21 +220,25 @@ export default function NetworkPage() {
|
|||||||
async function applyEgress() {
|
async function applyEgress() {
|
||||||
setBusy("egress:apply");
|
setBusy("egress:apply");
|
||||||
try {
|
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", {
|
await fetchJson("/api/network/egress", {
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
mode: egressMode,
|
mode: egressMode,
|
||||||
chain_residential: chainResidential,
|
chain_residential: chainResidential,
|
||||||
cover: { neko: coverNeko, relay: coverRelay, uploads: coverUploads },
|
cover: { neko: coverNeko, relay: coverRelay, uploads: coverUploads },
|
||||||
refresh_neko: true,
|
refresh_neko: false,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
toast.push(
|
toast.push(
|
||||||
egressMode === "off"
|
egressMode === "off"
|
||||||
? "已切回直连"
|
? "已切回机房直连"
|
||||||
: chainResidential
|
: egressMode === "residential"
|
||||||
? "已启用 ShellCrash + 住宅链式落地"
|
? "已启用静态住宅 IP(:17891)"
|
||||||
: "已启用 ShellCrash 机场线路",
|
: chainResidential
|
||||||
|
? "已启用 ShellCrash + 住宅链式落地"
|
||||||
|
: "已启用 ShellCrash 机场线路",
|
||||||
"ok",
|
"ok",
|
||||||
);
|
);
|
||||||
await load();
|
await load();
|
||||||
@ -250,7 +257,7 @@ export default function NetworkPage() {
|
|||||||
};
|
};
|
||||||
setProbes(r.probes || []);
|
setProbes(r.probes || []);
|
||||||
const ok = (r.probes || []).some((p) => p.target === "google" && p.ok);
|
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) {
|
} catch (e) {
|
||||||
toast.push((e as Error).message, "err");
|
toast.push((e as Error).message, "err");
|
||||||
} finally {
|
} finally {
|
||||||
@ -501,7 +508,7 @@ export default function NetworkPage() {
|
|||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
<div className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div>
|
<div>
|
||||||
<h1 className="font-display text-2xl font-semibold text-white">网络</h1>
|
<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>
|
</div>
|
||||||
<button type="button" className={`inline-flex items-center gap-1.5 ${btnGhost}`} onClick={() => void load()}>
|
<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" />}
|
{loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <RefreshCw className="h-4 w-4" />}
|
||||||
@ -515,22 +522,24 @@ export default function NetworkPage() {
|
|||||||
</div>
|
</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">
|
<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 className="flex flex-wrap items-start justify-between gap-3">
|
||||||
<div>
|
<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">
|
<p className="mt-1 text-xs text-slate-400">
|
||||||
统一走 ShellCrash(:7890)。硬规则:<span className="text-emerald-200">*.douyin.com 必须直连</span>
|
美国 VPS:默认机房 IP 直出。启用后 YT 直播/长视频/Shorts、TikTok、X/Neko 统一经本机{" "}
|
||||||
;YouTube 出海。家宽不能直连海外住宅 SOCKS——勾选「住宅落地」= dialer-proxy 链式。
|
<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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<div className="flex flex-wrap gap-2">
|
||||||
<button type="button" className={btnGhost} disabled={!!busy} onClick={() => void probeEgress()}>
|
<button type="button" className={btnGhost} disabled={!!busy} onClick={() => void probeEgress()}>
|
||||||
{busy === "egress:probe" ? "探测中…" : "探测 Google / YouTube"}
|
{busy === "egress:probe" ? "探测中…" : "探测出口 IP"}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" className={`${btn} bg-cyan-600`} disabled={!!busy} onClick={() => void applyEgress()}>
|
<button type="button" className={`${btn} bg-cyan-600`} disabled={!!busy} onClick={() => void applyEgress()}>
|
||||||
{busy === "egress:apply" ? "应用中…" : "应用出海"}
|
{busy === "egress:apply" ? "应用中…" : "应用"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@ -540,15 +549,25 @@ export default function NetworkPage() {
|
|||||||
[
|
[
|
||||||
{
|
{
|
||||||
id: "off" as const,
|
id: "off" as const,
|
||||||
title: "直连",
|
title: "机房直连",
|
||||||
desc: "不经 ShellCrash,国内机器上 YouTube 通常不可用",
|
desc: "默认 · 业务用美国 VPS 机房 IP(已可访问 Google/YouTube)",
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: "shellcrash" as const,
|
id: "residential" as const,
|
||||||
title: "ShellCrash",
|
title: "静态住宅 IP",
|
||||||
desc: "推荐 · Neko / 推流 / 上传全部进 :7890,由规则分流",
|
desc: "douyinweb-singbox → 下方 SOCKS 账号;Neko 用无认证本机 HTTP,不伤 v2ray-agent",
|
||||||
ready: Boolean(eg?.shellcrash?.running || sc?.running),
|
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: "家宽出海 :7890;可选 dialer 链式住宅",
|
||||||
|
ready: Boolean(eg?.shellcrash?.running || sc?.running),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
: []),
|
||||||
] as const
|
] as const
|
||||||
).map((m) => {
|
).map((m) => {
|
||||||
const active = egressMode === m.id;
|
const active = egressMode === m.id;
|
||||||
@ -558,11 +577,18 @@ export default function NetworkPage() {
|
|||||||
type="button"
|
type="button"
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
setEgressMode(m.id);
|
setEgressMode(m.id);
|
||||||
if (m.id === "shellcrash") {
|
if (m.id === "residential" || m.id === "shellcrash") {
|
||||||
setCoverRelay(true);
|
setCoverRelay(true);
|
||||||
setCoverNeko(true);
|
setCoverNeko(true);
|
||||||
setCoverUploads(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 ${
|
className={`rounded-2xl border p-4 text-left transition ${
|
||||||
active
|
active
|
||||||
@ -584,6 +610,7 @@ export default function NetworkPage() {
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{egressMode === "shellcrash" ? (
|
||||||
<div
|
<div
|
||||||
className={`mt-4 rounded-xl border px-4 py-3 ${
|
className={`mt-4 rounded-xl border px-4 py-3 ${
|
||||||
egressMode === "shellcrash"
|
egressMode === "shellcrash"
|
||||||
@ -603,22 +630,26 @@ export default function NetworkPage() {
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
<span>
|
<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="mt-1 block text-xs text-slate-400">
|
||||||
不勾选:用机场节点出海。勾选:写入 <span className="font-mono">dy-residential</span>
|
美国 VPS 请用上方「静态住宅 IP」,不要用链式。
|
||||||
(socks5 + dialer-proxy → {eg?.dialer || "dialer"}),经前置节点再连住宅 SOCKS。账号在下方「业务 SOCKS」填写。
|
|
||||||
</span>
|
</span>
|
||||||
</span>
|
</span>
|
||||||
</label>
|
</label>
|
||||||
{eg?.exit_node ? (
|
|
||||||
<p className="mt-2 font-mono text-[11px] text-slate-400">当前出口节点:{eg.exit_node}</p>
|
|
||||||
) : null}
|
|
||||||
</div>
|
</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">
|
<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">
|
<label className="inline-flex items-center gap-2">
|
||||||
<input type="checkbox" checked={coverNeko} onChange={(e) => setCoverNeko(e.target.checked)} />
|
<input type="checkbox" checked={coverNeko} onChange={(e) => setCoverNeko(e.target.checked)} />
|
||||||
Neko Chrome
|
Neko / X 浏览器
|
||||||
</label>
|
</label>
|
||||||
<label className="inline-flex items-center gap-2">
|
<label className="inline-flex items-center gap-2">
|
||||||
<input type="checkbox" checked={coverRelay} onChange={(e) => setCoverRelay(e.target.checked)} />
|
<input type="checkbox" checked={coverRelay} onChange={(e) => setCoverRelay(e.target.checked)} />
|
||||||
@ -626,7 +657,7 @@ export default function NetworkPage() {
|
|||||||
</label>
|
</label>
|
||||||
<label className="inline-flex items-center gap-2">
|
<label className="inline-flex items-center gap-2">
|
||||||
<input type="checkbox" checked={coverUploads} onChange={(e) => setCoverUploads(e.target.checked)} />
|
<input type="checkbox" checked={coverUploads} onChange={(e) => setCoverUploads(e.target.checked)} />
|
||||||
Shorts / 长视频上传
|
Shorts / 长视频 / TikTok
|
||||||
</label>
|
</label>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -668,6 +699,9 @@ export default function NetworkPage() {
|
|||||||
</div>
|
</div>
|
||||||
<p className="mt-1 font-mono text-slate-500">
|
<p className="mt-1 font-mono text-slate-500">
|
||||||
{p.http_code} · {p.elapsed_ms}ms · {p.via === "direct" || !p.via ? "直连" : "代理"}
|
{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>
|
</p>
|
||||||
</div>
|
</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">
|
<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 className="flex items-start justify-between gap-2">
|
||||||
<div>
|
<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">
|
<p className="mt-1 text-xs text-slate-400">
|
||||||
仅在出海勾选「住宅落地」时使用:写入 ShellCrash 链式节点,经 dialer 前置再连此 SOCKS。家宽不会直连它。
|
填写供应商 SOCKS5。启用「静态住宅 IP」后由 douyinweb-singbox 转发到此账号;账号不会进 Chrome URL。
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span
|
<span
|
||||||
@ -865,7 +899,7 @@ export default function NetworkPage() {
|
|||||||
|
|
||||||
<label className="mt-4 flex items-center gap-2 text-sm text-slate-300">
|
<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)} />
|
<input type="checkbox" checked={socksEnabled} onChange={(e) => setSocksEnabled(e.target.checked)} />
|
||||||
启用为住宅链式账号(与上方「住宅落地」同步)
|
启用静态住宅账号(与上方「静态住宅 IP」联动)
|
||||||
</label>
|
</label>
|
||||||
|
|
||||||
<div className="mt-3 flex flex-wrap gap-2">
|
<div className="mt-3 flex flex-wrap gap-2">
|
||||||
|
|||||||
@ -466,17 +466,20 @@ export default function ShortsPage() {
|
|||||||
}, [status?.oauth_profiles, channels]);
|
}, [status?.oauth_profiles, channels]);
|
||||||
|
|
||||||
const totals = useMemo(() => {
|
const totals = useMemo(() => {
|
||||||
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
|
// Only **enabled** channels count toward 北京日配额 X/Y (same bug as yt-long).
|
||||||
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
|
const active = displayChannels.filter((c) => c.enabled !== false);
|
||||||
const recorded = displayChannels.reduce((s, c) => s + (c.recorded || 0), 0);
|
const uploaded = active.reduce((s, c) => s + (c.uploaded || 0), 0);
|
||||||
const pending = displayChannels.reduce((s, c) => s + (c.pending || 0), 0);
|
const scheduled = active.reduce((s, c) => s + (c.scheduled || 0), 0);
|
||||||
const recording = displayChannels.reduce((s, c) => s + (c.recording || 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 used = uploaded;
|
||||||
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 9), 0);
|
const cap = active.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 minTarget = active.reduce((s, c) => s + (c.daily_min || 9), 0);
|
||||||
const gap = displayChannels
|
const gap = active.reduce(
|
||||||
.filter((c) => c.enabled !== false)
|
(s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))),
|
||||||
.reduce((s, c) => s + (c.gap ?? Math.max(0, (c.daily_max || 9) - (c.uploaded || 0))), 0);
|
0,
|
||||||
|
);
|
||||||
const queuedUpload = scheduled + recorded;
|
const queuedUpload = scheduled + recorded;
|
||||||
const pendingRecord = pending + recording;
|
const pendingRecord = pending + recording;
|
||||||
return { uploaded, scheduled, recorded, pending, recording, queuedUpload, pendingRecord, used, cap, minTarget, gap };
|
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">
|
<div className="mb-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-5">
|
||||||
{[
|
{[
|
||||||
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)` : "按各频道日上限合计"],
|
["北京日配额", `${totals.uploaded} / ${totals.cap || "—"}`, beijingWindow ? `${beijingWindow}(北京时间)· 仅已启用` : "仅已启用频道日上限合计"],
|
||||||
["当日缺口", String(totals.gap || quotaGap), minUnmet > 0 ? `${minUnmet} 个频道未达 9 条` : "各频道已达 9 条"],
|
[
|
||||||
|
"当日缺口",
|
||||||
|
String(totals.gap || quotaGap),
|
||||||
|
minUnmet > 0
|
||||||
|
? `${minUnmet} 个启用频道未达每日最少`
|
||||||
|
: "启用频道已达每日最少",
|
||||||
|
],
|
||||||
["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`],
|
["已上传", String(totals.uploaded), `待传 ${totals.queuedUpload} · 待录 ${totals.pendingRecord} · 剩余 ${hoursLeft}`],
|
||||||
[
|
[
|
||||||
"抖音在播源",
|
"抖音在播源",
|
||||||
|
|||||||
@ -379,14 +379,16 @@ export default function YtLongPage() {
|
|||||||
}, [upcoming, channelProfileMap]);
|
}, [upcoming, channelProfileMap]);
|
||||||
|
|
||||||
const totals = useMemo(() => {
|
const totals = useMemo(() => {
|
||||||
const uploaded = displayChannels.reduce((s, c) => s + (c.uploaded || 0), 0);
|
// Only **enabled** channels count toward YouTube 上传 3/14 (not disabled Account B).
|
||||||
const scheduled = displayChannels.reduce((s, c) => s + (c.scheduled || 0), 0);
|
const active = displayChannels.filter((c) => c.enabled !== false);
|
||||||
// Progress / 缺口按「已上传」计(与 Shorts 一致);used 含排队占坑,仅作内部参考。
|
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 used = uploaded;
|
||||||
const cap = displayChannels.reduce((s, c) => s + (c.daily_max || 0), 0);
|
const cap = active.reduce((s, c) => s + (c.daily_max || 0), 0);
|
||||||
const gap = displayChannels
|
const gap = active.reduce(
|
||||||
.filter((c) => c.enabled !== false)
|
(s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)),
|
||||||
.reduce((s, c) => s + Math.max(0, (c.daily_max || 0) - Number(c.uploaded || 0)), 0);
|
0,
|
||||||
|
);
|
||||||
return { uploaded, scheduled, used, cap, gap };
|
return { uploaded, scheduled, used, cap, gap };
|
||||||
}, [displayChannels]);
|
}, [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>
|
<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>
|
<h2 className="font-display text-3xl font-semibold tracking-tight">📺 长视频分发台</h2>
|
||||||
<p className="mt-1 max-w-2xl text-sm text-slate-400">
|
<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>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="flex flex-wrap gap-2">
|
<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
|
status?.api_quota_limited
|
||||||
? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}`
|
? `9:16 · API 限流中,每频道 cap ${status?.channel_daily_max_effective ?? 4}`
|
||||||
: "9:16 竖屏 · cascade 切短片",
|
: "9:16 竖屏 · cascade 切短片",
|
||||||
@ -585,7 +587,7 @@ export default function YtLongPage() {
|
|||||||
<DailyQuotaGlobalCard
|
<DailyQuotaGlobalCard
|
||||||
accent="amber"
|
accent="amber"
|
||||||
title="长视频 · 每频道每日上限"
|
title="长视频 · 每频道每日上限"
|
||||||
subtitle="全局默认写入「每频道每日上限」;可一键同步到全部长视频频道。母片/总上传上限仍由系统按频道数推算。"
|
subtitle="全局默认写入「每频道每日上限」;可一键同步到全部长视频频道。母片/总上传上限 = 已启用且已授权频道 × 每频道上限。"
|
||||||
showMin={false}
|
showMin={false}
|
||||||
dailyMin={0}
|
dailyMin={0}
|
||||||
dailyMax={Number(settings.yt_long_channel_daily_max ?? status?.channel_daily_max ?? 5)}
|
dailyMax={Number(settings.yt_long_channel_daily_max ?? status?.channel_daily_max ?? 5)}
|
||||||
|
|||||||
83
scripts/linux/build_orphan_watch.sh
Normal file
83
scripts/linux/build_orphan_watch.sh
Normal 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
|
||||||
22
scripts/linux/douyinweb-singbox.service
Normal file
22
scripts/linux/douyinweb-singbox.service
Normal 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
|
||||||
Loading…
Reference in New Issue
Block a user