Shorts: SOCKS 代理、OAuth Client 分桶配额、频道级联清理;更新 README

取消本地上传拦截,按 A/B/C/D Client 独立展示配额;新增 SOCKS5 上传代理与删频道级联清理;同步文档与部署脚本。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-14 09:58:04 -05:00
parent 432b1cec9e
commit 01c6bf4507
20 changed files with 1144 additions and 328 deletions

View File

@ -108,7 +108,10 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
- **成片**:默认 **15 秒**,设置可切换 15 / 30 / 60 / 90 秒
- **错峰上传**:录完 → `scheduled` + 抖动 `upload_at`;可「立即上传」绕过排程
- **上传**:每频道 Google OAuth 一键授权;每频道北京日配额固定 **9** 条
- **YouTube 项目配额**:官方默认 **100 次 `videos.insert`/天/项目**(太平洋日独立桶);系统保守限制 **90 次/天**(`shorts_yt_daily_upload_limit`),撞线或 HTTP **429** 时全局暂停至太平洋 0 点,待上传任务自动延后、不再无效重试
- **OAuth Client 分组**:频道绑定 **A / B / C / D**(对应不同 Google Cloud 项目);上传配额按 Client **独立计数展示**,A 用尽不影响 B
- **YouTube 项目配额**:官方默认 **100 次 `videos.insert`/天/项目**(太平洋日独立桶);页面展示本地参考计数(默认 90/Client)。**不自行暂停/拦截上传**;收到 HTTP **429** 时仅把接口反馈写到任务错误,手动「立即上传」始终可点,以 YouTube 返回为准
- **SOCKS5 代理**(默认关):设置页可选;仅 Shorts 上传与 OAuth token 刷新走代理,不影响抖音监控
- **频道级联清理**:删除 Shorts 频道时同步删除关联任务与本地成片;孤儿任务可运维 purge
- **不复用** sh2 RTMP 转播通道
### 封面(S3)
@ -133,7 +136,7 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
| `/groups` | YouTube 频道分组 + 分析页签 |
| `/youtube` | 频道管理(默认)+ InnerTube 探测 |
| `/shorts` | 授权 / 任务 / 排程 / 立即上传 / 在播分析 |
| `/settings` | 防风控、通知、静默、YT/Shorts、改密、PB/S3 运维 |
| `/settings` | 防风控、通知、静默、YT/Shorts、SOCKS 上传代理、改密、PB/S3 运维 |
| `/blacklist` | 黑名单 |
### 运维与通知
@ -148,7 +151,7 @@ HTTPS 由服务器 **Caddy** 自动签发。进程端口:
```
douyinWEB/
backend/app/ FastAPI(auth / monitor / cover / shorts_* / shorts_yt_quota / youtube_* …)
backend/app/ FastAPI(auth / monitor / cover / shorts_* / shorts_socks / shorts_yt_quota / youtube_* …)
backend/tests/ pytest(Shorts / live / reconcile 等)
backend/data/ SQLite、封面/成片缓存
frontend/src/ Next.js 控制台(Web)
@ -199,7 +202,7 @@ cd youtube-svc && npm install
| GET | `/api/youtube/live-map` | YT 分组 + Shorts 在播地图 |
| GET | `/api/youtube/manage/channels` | OAuth 频道管理入口 |
| GET | `/api/groups/analytics` | 分组场次分析 |
| GET | `/api/shorts/status` | Shorts worker / 北京日配额 / OAuth / **YouTube 上传配额**(`upload_quota_blocked`、`yt_upload_used/limit`) |
| GET | `/api/shorts/status` | Shorts worker / 北京日配额 / OAuth Client / **YouTube 上传配额**(`yt_quota_by_profile`、`yt_quota_exhausted_hint`) |
| GET | `/api/shorts/schedule` | 即将上传日程 |
| POST | `/api/shorts/jobs/{id}/upload-now` | 立即上传(绕过错峰) |
| POST | `/api/shorts/fill-quota` | 按配额补取样 |
@ -232,7 +235,10 @@ python scripts\deploy_ubuntu.py # 基础 Ubuntu 部署
python scripts\deploy_seaweedfs.py # SeaweedFS + 封面能力
python scripts\setup_caddy_dylive.py # dylive / feiniu / s3 反代
python scripts\deploy_shorts.py # Shorts 旁路增量
python scripts\deploy_yt_quota_fix.py # YouTube Video Uploads 429 配额暂停/预算
python scripts\deploy_yt_quota_fix.py # YouTube 上传配额:按 Client 展示、取消本地拦截
python scripts\deploy_shorts_socks.py # Shorts 上传 SOCKS5 代理
python scripts\deploy_channel_cascade.py # 删频道级联清理任务/成片
python scripts\deploy_dup_upload_fix.py # 重复上传修复
python scripts\deploy_dual_platform.py # 双平台 / 分组相关增量
python scripts\deploy_site_auth.py # 站点登录
python scripts\deploy_youtube_live.py # 在播地图 / LIVE 角标
@ -264,15 +270,18 @@ python scripts\restart_vps.py # 重启 douyinWEB 进程
| `shorts_sample_any_live` | 默认 `true`;取样不限标签 |
| `shorts_dedupe_room_day` | 默认 `true`;同房北京日仅一次 |
| `shorts_upload_spread` | 默认 `true`;错峰排程 |
| `shorts_yt_daily_upload_limit` | 默认 `90`;YouTube 项目级日上传预算(太平洋日,低于官方 100) |
| `shorts_yt_upload_blocked_until` | 运行时写入;429 或预算用尽后暂停上传至该时间戳(太平洋 0 点) |
| `shorts_yt_daily_upload_limit` | 默认 `90`;各 OAuth Client 本地参考上限(太平洋日,仅展示) |
| `shorts_upload_socks_enabled` | 默认 `false`;Shorts 上传走 SOCKS5 代理 |
| `shorts_upload_socks_profile_id` | `residential-1`;当前 SOCKS 配置 ID |
| `shorts_upload_socks_profiles` | 内置默认;SOCKS5 配置列表(server / port / 认证) |
### YouTube 上传配额(429)
- 错误示例:`Quota exceeded for quota metric 'Video Uploads' … Video Uploads per day`
- **不是程序崩溃**:Google Cloud 项目每日 Video Uploads 桶用尽(默认约 100 次/天,[官方文档](https://developers.google.com/youtube/v3/docs/videos/insert))
- 配额在 **太平洋时间 0 点** 重置;Console → YouTube Data API → Quotas 可查看用量与申请提额
- 实现:`backend/app/shorts_yt_quota.py`(预算计数、429 检测、全局暂停、任务延后);Shorts 页展示暂停横幅与 `已用/上限`
- 多 Google 项目:Shorts 频道绑定 OAuth Client **A/B/C/D**,各 Client 独立计数、互不影响
- 实现:`backend/app/shorts_yt_quota.py`(按 Client 计数展示、429 识别);Shorts 页展示用量提示与接口错误,**禁止本地自设上传暂停**
## 环境变量(`DY_` 前缀)

View File

@ -17,21 +17,19 @@ from typing import Any, Optional
from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_socks import resolve_upload_socks_proxy
from .shorts_yt_quota import (
any_profile_uploads_available,
blocked_profile_ids,
clear_all_upload_self_blocks,
clear_stale_quota_errors_for_open_profiles,
detect_and_block_from_recent_errors,
pause_uploads_until_reset,
profile_id_for_channel,
profile_id_for_job,
profile_upload_blocked,
project_uploads_available,
quota_budgets_by_profile,
reserve_yt_upload_slot,
yt_upload_budget,
)
from .timeutil import format_beijing, push_date_from_ts
from .timeutil import push_date_from_ts
def _room_tags(room: dict[str, Any]) -> list[str]:
@ -98,6 +96,8 @@ def _enqueue_job(
channel_pk=str(channel["id"]),
push_date=day,
)
if not job:
return None
try:
db.add_event(
kind="ops",
@ -449,26 +449,14 @@ class ShortsPipeline:
except Exception:
pass
try:
# Clear wrongly-copied global quota errors on open Clients before scanning
clear_all_upload_self_blocks(cfg)
clear_stale_quota_errors_for_open_profiles(cfg)
except Exception:
pass
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
try:
paused = detect_and_block_from_recent_errors(cfg)
if paused:
quota_blocked = True
quota_until = max([quota_until, *paused.values()])
except Exception:
pass
if not quota_blocked and is_upload_quota_error(self.last_error):
# last_error may belong to one profile — do not freeze all Clients
pass
last_error = self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
blocked_profiles = [r for r in yt_by_profile if r.get("blocked")]
any_blocked = bool(blocked_profiles)
exhausted = [r for r in yt_by_profile if r.get("exhausted_hint")]
return {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
@ -482,9 +470,12 @@ class ShortsPipeline:
"auto_retried": self.auto_retried,
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
"quota_gap": db.shorts_total_quota_gap(),
"upload_quota_blocked": any_blocked,
"upload_quota_blocked_until": max((float(r.get("blocked_until") or 0) for r in blocked_profiles), default=0),
"upload_quota_blocked_profiles": [str(r.get("id") or "") for r in blocked_profiles],
# Informational only — never gates manual/worker uploads
"upload_quota_blocked": False,
"upload_quota_blocked_until": 0,
"upload_quota_blocked_profiles": [],
"yt_quota_exhausted_hint": [str(r.get("id") or "") for r in exhausted],
"yt_quota_reset_at": max((float(r.get("reset_at") or 0) for r in exhausted), default=0),
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
@ -521,8 +512,10 @@ class ShortsPipeline:
if self._task and not self._task.done():
return
try:
clear_all_upload_self_blocks()
clear_stale_quota_errors_for_open_profiles()
detect_and_block_from_recent_errors()
db.purge_orphan_shorts_jobs(limit=500)
db.dedupe_shorts_jobs_room_day()
except Exception:
pass
self._stop.clear()
@ -595,7 +588,7 @@ class ShortsPipeline:
pass
try:
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, retry_at=0.0)
n = db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0)
if n:
self.last_error = ""
except Exception:
@ -617,11 +610,11 @@ class ShortsPipeline:
record_max = self._record_max(cfg)
upload_max = self._upload_max(cfg)
skip_profiles = blocked_profile_ids(cfg)
job: dict[str, Any] | None = None
runner: str = ""
if self._active_uploads < upload_max:
job = db.claim_due_shorts_upload(skip_profile_ids=skip_profiles)
# Never skip profiles for local quota — YouTube API decides
job = db.claim_due_shorts_upload(skip_profile_ids=None)
if job:
runner = "upload"
if not job and self._active_records < record_max:
@ -753,52 +746,40 @@ class ShortsPipeline:
except Exception:
pass
def _upload_quota_blocked(
self,
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "",
) -> tuple[bool, float]:
"""If profile_id set, only that Client; else True when ANY profile is blocked."""
settings = cfg if cfg is not None else db.get_settings_map()
if profile_id:
return profile_upload_blocked(settings, profile_id=profile_id)
blocked = blocked_profile_ids(settings)
if not blocked:
return False, 0.0
until = 0.0
for pid in blocked:
_, u = profile_upload_blocked(settings, profile_id=pid)
until = max(until, u)
return True, until
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
def _record_quota_api_feedback(self, job: dict[str, Any], raw_error: str) -> None:
"""Surface YouTube 429 on the job only — never self-pause the Client."""
pid = profile_id_for_job(job)
until = pause_uploads_until_reset(profile_id=pid, reason=quota_error_message(pid))
# Keep local counter in sync for UI; do not set blocked_until / defer siblings
pause_uploads_until_reset(profile_id=pid, reason="")
friendly = quota_error_message(pid)
# Prefer raw API body when present so operators see the real interface reply
api_snip = (raw_error or "").strip()
if api_snip and api_snip != friendly:
err_text = f"{friendly} | 接口:{api_snip[:280]}"
else:
err_text = friendly
jid = str(job.get("id") or "")
if jid:
db.update_shorts_job(
jid,
status="scheduled",
error=friendly,
upload_at=until + 300,
finished_at=0,
status="failed",
error=err_text[:400],
finished_at=time.time(),
)
self.last_error = friendly
self.last_error = err_text[:300]
self._emit_shorts_event(
kind="shorts_quota",
level="warn",
message=f"Client {pid} Shorts 上传配额用尽,仅暂停该配置档至 {format_beijing(until)}",
message=f"Client {pid} YouTube 接口反馈配额用尽(不拦截手动上传)",
job=job,
extra={"error": raw_error[:200], "blocked_until": until, "oauth_profile_id": pid},
extra={"error": raw_error[:200], "oauth_profile_id": pid},
)
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
"""Return True if handled (quota deferral)."""
"""Return True if handled as YouTube quota API feedback (no local pause)."""
msg = str(exc)
if is_upload_quota_error(msg):
self._pause_uploads_for_quota(job, msg)
self._record_quota_api_feedback(job, msg)
return True
return False
@ -870,13 +851,7 @@ class ShortsPipeline:
raise ValueError(f"状态 {st} 不可手动上传")
cfg = db.get_settings_map()
pid = profile_id_for_job(job)
quota_blocked, quota_until = self._upload_quota_blocked(cfg, profile_id=pid)
if quota_blocked:
raise ValueError(f"{quota_error_message(pid)} 预计 {format_beijing(quota_until)} 恢复。")
if not project_uploads_available(cfg, profile_id=pid):
until = pause_uploads_until_reset(cfg, profile_id=pid)
raise ValueError(f"{quota_error_message(pid)} 预计 {format_beijing(until)} 恢复。")
# No local quota gate — always attempt YouTube; show API feedback on failure
upload_max = self._upload_max(cfg)
if st == "uploading":
@ -929,7 +904,8 @@ class ShortsPipeline:
return done
except Exception as exc:
if self._handle_upload_error(claimed, exc):
raise ValueError(quota_error_message(profile_id_for_job(claimed))) from exc
done = db.get_shorts_job(job_id) or claimed
raise ValueError(str(done.get("error") or quota_error_message(profile_id_for_job(claimed)))) from exc
if "成片文件不存在" in str(exc):
refreshed = db.get_shorts_job(job_id) or claimed
if str(refreshed.get("youtube_video_id") or "").strip():
@ -1075,25 +1051,35 @@ class ShortsPipeline:
from pathlib import Path
jid = str(job["id"])
yt_id = str(job.get("youtube_video_id") or "").strip()
# Re-read: refuse if already uploaded or lease lost (prevents duplicate YouTube inserts)
fresh = db.get_shorts_job(jid) or job
yt_id = str(fresh.get("youtube_video_id") or "").strip()
if yt_id:
db.update_shorts_job(
jid,
status="uploaded",
error="",
clip_path="",
finished_at=float(job.get("finished_at") or 0) or time.time(),
finished_at=float(fresh.get("finished_at") or 0) or time.time(),
)
return
clip = str(job.get("clip_path") or "")
if str(fresh.get("status") or "") != "uploading":
return
if not db.touch_shorts_upload_lease(jid):
return
clip = str(fresh.get("clip_path") or job.get("clip_path") or "")
if not clip:
self._mark_failed(job, "无成片路径")
return
if not Path(clip).is_file():
raise ValueError("成片文件不存在,已重新排队录制")
channel = db.get_shorts_channel(str(job.get("channel_pk") or ""))
channel = db.get_shorts_channel(str(fresh.get("channel_pk") or job.get("channel_pk") or ""))
if not channel:
self._mark_failed(job, "频道不存在")
clip_gone = clip
db.purge_orphan_shorts_jobs(limit=50)
if clip_gone:
self._delete_clip(clip_gone)
return
from .shorts_oauth import channel_oauth_creds
@ -1101,49 +1087,74 @@ class ShortsPipeline:
if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]):
db.update_shorts_job(
jid,
status="scheduled" if float(job.get("upload_at") or 0) else "recorded",
status="scheduled" if float(fresh.get("upload_at") or job.get("upload_at") or 0) else "recorded",
error="频道未授权 Google,已保留成片待上传",
)
return
title_tpl = str(channel.get("title_template") or "{anchor} #Shorts")
desc_tpl = str(channel.get("description_template") or "")
anchor = str(job.get("anchor_name") or job.get("room_id") or "live")
url = str(job.get("source_url") or "")
anchor = str(fresh.get("anchor_name") or job.get("anchor_name") or job.get("room_id") or "live")
url = str(fresh.get("source_url") or job.get("source_url") or "")
title = title_tpl.replace("{anchor}", anchor).replace("{url}", url)
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
if "#Shorts" not in title and "#shorts" not in title.lower():
title = f"{title} #Shorts"
pid = profile_id_for_channel(channel)
if not reserve_yt_upload_slot(cfg, profile_id=pid):
pause_uploads_until_reset(cfg, profile_id=pid)
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message(pid)}")
result = await upload_shorts_mp4(
file_path=clip,
title=title,
description=desc,
privacy=str(channel.get("privacy") or "public"),
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
)
db.update_shorts_job(
jid,
status="uploaded",
youtube_video_id=str(result.get("video_id") or ""),
youtube_url=str(result.get("url") or ""),
error="",
finished_at=time.time(),
clip_path="",
)
reserve_yt_upload_slot(cfg, profile_id=pid)
stop_hb = asyncio.Event()
async def _heartbeat() -> None:
while not stop_hb.is_set():
try:
await asyncio.wait_for(stop_hb.wait(), timeout=20.0)
break
except asyncio.TimeoutError:
if not db.touch_shorts_upload_lease(jid):
break
hb_task = asyncio.create_task(_heartbeat(), name=f"shorts-upload-hb-{jid[:8]}")
result: dict[str, Any] | None = None
try:
# Final gate right before Google API — never double-insert
if not db.touch_shorts_upload_lease(jid):
return
result = await upload_shorts_mp4(
file_path=clip,
title=title,
description=desc,
privacy=str(channel.get("privacy") or "public"),
client_id=creds["client_id"],
client_secret=creds["client_secret"],
refresh_token=creds["refresh_token"],
proxy_url=resolve_upload_socks_proxy(cfg),
)
finally:
stop_hb.set()
hb_task.cancel()
try:
await hb_task
except asyncio.CancelledError:
pass
except Exception:
pass
if not result:
return
vid = str(result.get("video_id") or "")
yt_url = str(result.get("url") or "")
won = db.finalize_shorts_upload(jid, youtube_video_id=vid, youtube_url=yt_url)
if not won:
# Peer already finalized — do not treat as failure; avoid deleting their state
return
if cfg.get("shorts_delete_clip_after_upload", True):
self._delete_clip(clip)
yt_url = str(result.get("url") or "")
self._emit_shorts_event(
kind="shorts_ok",
level="info",
message=f"Shorts 已上传:{yt_url or result.get('video_id')}",
job=job,
extra={"video_id": result.get("video_id"), "youtube_url": yt_url},
message=f"Shorts 已上传:{yt_url or vid}",
job=fresh,
extra={"video_id": vid, "youtube_url": yt_url},
)
@staticmethod

View File

@ -173,8 +173,14 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
channels = db.list_shorts_channels(enabled=None)
channel_map = {str(c["id"]): c for c in channels}
enriched = []
for j in upcoming[:limit]:
ch = channel_map.get(str(j.get("channel_pk") or ""), {})
orphan_pks: list[str] = []
for j in upcoming[: max(limit * 3, limit)]:
pk = str(j.get("channel_pk") or "")
ch = channel_map.get(pk, {})
if not ch:
if pk:
orphan_pks.append(pk)
continue
clip = str(j.get("clip_path") or "").strip()
clip_ready = bool(clip) and Path(clip).is_file()
enriched.append(
@ -192,6 +198,13 @@ def schedule_board(limit: int = 24) -> dict[str, Any]:
and clip_ready,
}
)
if len(enriched) >= limit:
break
if orphan_pks:
try:
db.purge_orphan_shorts_jobs(limit=200)
except Exception:
pass
channel_rows = []
day_progress = max(0.0, min(1.0, (now - day_start) / max(1.0, day_end - day_start)))
total_gap = 0

138
backend/app/shorts_socks.py Normal file
View File

@ -0,0 +1,138 @@
# -*- coding: utf-8 -*-
"""Shorts upload SOCKS5 proxy profiles (optional, default off)."""
from __future__ import annotations
import uuid
from typing import Any
from urllib.parse import quote
DEFAULT_SOCKS_PROFILE_ID = "residential-1"
DEFAULT_SOCKS_PROFILES: list[dict[str, Any]] = [
{
"id": DEFAULT_SOCKS_PROFILE_ID,
"label": "静态住宅 IP",
"type": "socks5",
"server": "185.124.61.35",
"port": 43676,
"username": "V0sI3BsI1bxgKRx",
"password": "QGwGeRTAa9YcVhM",
}
]
def _norm_profile(raw: Any) -> dict[str, Any] | None:
if not isinstance(raw, dict):
return None
pid = str(raw.get("id") or "").strip() or str(uuid.uuid4())
server = str(raw.get("server") or "").strip()
try:
port = int(raw.get("port") or 0)
except Exception:
port = 0
ptype = str(raw.get("type") or "socks5").strip().lower() or "socks5"
if ptype not in {"socks5", "socks5h"}:
ptype = "socks5"
return {
"id": pid,
"label": str(raw.get("label") or server or pid).strip() or pid,
"type": ptype,
"server": server,
"port": port,
"username": str(raw.get("username") or ""),
"password": str(raw.get("password") or ""),
}
def list_socks_profiles(cfg: dict[str, Any] | None = None, *, public: bool = False) -> list[dict[str, Any]]:
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
raw = settings.get("shorts_upload_socks_profiles")
rows: list[dict[str, Any]] = []
if isinstance(raw, list):
for item in raw:
p = _norm_profile(item)
if p and p["server"] and p["port"] > 0:
rows.append(p)
if not rows:
rows = [dict(x) for x in DEFAULT_SOCKS_PROFILES]
if not public:
return rows
out = []
for p in rows:
pwd = str(p.get("password") or "")
q = dict(p)
q["has_password"] = bool(pwd.strip())
q["password"] = ("***" + pwd[-4:]) if len(pwd) > 4 else ("***" if pwd else "")
out.append(q)
return out
def get_socks_profile(profile_id: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
pid = str(profile_id or "").strip()
for p in list_socks_profiles(cfg, public=False):
if str(p.get("id") or "") == pid:
return p
return None
def socks_proxy_url(profile: dict[str, Any] | None) -> str:
"""Build httpx socks URL. Uses socks5h so DNS goes through the proxy."""
if not profile:
return ""
server = str(profile.get("server") or "").strip()
try:
port = int(profile.get("port") or 0)
except Exception:
port = 0
if not server or port <= 0:
return ""
user = str(profile.get("username") or "")
pwd = str(profile.get("password") or "")
# Prefer remote DNS via proxy (socks5h); allow explicit type override
raw_type = str(profile.get("type") or "socks5").strip().lower()
scheme = "socks5h" if raw_type in {"socks5", "socks5h"} else "socks5h"
if user or pwd:
return f"{scheme}://{quote(user, safe='')}:{quote(pwd, safe='')}@{server}:{port}"
return f"{scheme}://{server}:{port}"
def resolve_upload_socks_proxy(cfg: dict[str, Any] | None = None) -> str:
"""Return proxy URL when Shorts SOCKS upload is enabled; else empty (direct)."""
from . import db
settings = dict(cfg if cfg is not None else db.get_settings_map())
if not settings.get("shorts_upload_socks_enabled"):
return ""
pid = str(settings.get("shorts_upload_socks_profile_id") or "").strip() or DEFAULT_SOCKS_PROFILE_ID
prof = get_socks_profile(pid, settings)
if not prof:
rows = list_socks_profiles(settings, public=False)
prof = rows[0] if rows else None
return socks_proxy_url(prof)
def merge_socks_profiles_patch(incoming: Any, existing_cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Merge UI patch; keep existing password when incoming is blank or ***masked."""
existing = {str(p["id"]): p for p in list_socks_profiles(existing_cfg, public=False)}
out: list[dict[str, Any]] = []
seen: set[str] = set()
src = incoming if isinstance(incoming, list) else []
for item in src:
p = _norm_profile(item)
if not p:
continue
pid = str(p["id"])
old = existing.get(pid) or {}
pwd = str(p.get("password") or "")
if (not pwd.strip()) or pwd.startswith("***"):
p["password"] = str(old.get("password") or "")
if not p["server"] or int(p.get("port") or 0) <= 0:
continue
out.append(p)
seen.add(pid)
# Keep any existing profiles not present in patch (UI may send full list; if empty patch keep old)
if not src:
return list(existing.values()) or [dict(x) for x in DEFAULT_SOCKS_PROFILES]
return out or [dict(x) for x in DEFAULT_SOCKS_PROFILES]

View File

@ -30,16 +30,30 @@ def quota_error_message(profile_id: str = "") -> str:
pid = str(profile_id or "").strip().upper()
tag = f"【Client {pid}】" if pid else ""
return (
f"{tag}YouTube 每日 Video Uploads 配额已用尽(429)。"
"仅暂停该 OAuth 配置档下的频道上传,其他 Client(A/B/C/D)不受影响。"
"待太平洋时间 0 点配额重置后会继续。"
f"{tag}YouTube 接口返回:每日 Video Uploads 配额已用尽(429)。"
"其他 Client(A/B/C/D)配额互不影响;"
"太平洋时间 0 点后 YouTube 侧配额重置。本系统不拦截手动上传。"
)
async def refresh_access_token(*, client_id: str, client_secret: str, refresh_token: str) -> str:
def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]:
kw: dict[str, Any] = {"timeout": timeout, "trust_env": False}
proxy = str(proxy_url or "").strip()
if proxy:
kw["proxy"] = proxy
return kw
async def refresh_access_token(
*,
client_id: str,
client_secret: str,
refresh_token: str,
proxy_url: str = "",
) -> str:
if not (client_id and client_secret and refresh_token):
raise ValueError("缺少 OAuth client_id / client_secret / refresh_token")
async with httpx.AsyncClient(timeout=30.0, trust_env=False) as client:
async with httpx.AsyncClient(**_client_kwargs(timeout=30.0, proxy_url=proxy_url)) as client:
resp = await client.post(
"https://oauth2.googleapis.com/token",
data={
@ -64,12 +78,16 @@ async def upload_shorts_mp4(
client_id: str = "",
client_secret: str = "",
refresh_token: str = "",
proxy_url: str = "",
) -> dict[str, Any]:
path = Path(file_path)
if not path.is_file():
raise ValueError("成片文件不存在,已重新排队录制")
access = await refresh_access_token(
client_id=client_id, client_secret=client_secret, refresh_token=refresh_token
client_id=client_id,
client_secret=client_secret,
refresh_token=refresh_token,
proxy_url=proxy_url,
)
try:
size = path.stat().st_size
@ -91,7 +109,7 @@ async def upload_shorts_mp4(
"https://www.googleapis.com/upload/youtube/v3/videos"
"?uploadType=resumable&part=snippet,status"
)
async with httpx.AsyncClient(timeout=180.0, trust_env=False) as client:
async with httpx.AsyncClient(**_client_kwargs(timeout=180.0, proxy_url=proxy_url)) as client:
init = await client.post(
init_url,
headers={

View File

@ -1,8 +1,9 @@
# -*- coding: utf-8 -*-
"""YouTube Data API daily upload budget — per OAuth Client profile (A/B/C/D).
"""YouTube Data API upload counters — per OAuth Client profile (A/B/C/D).
Each Google Cloud project has its own Video Uploads quota. Client A exhaustion
must NOT pause Client B uploads.
Counters are display-only. This module must NEVER gate manual or worker uploads;
YouTube API 429 responses are the sole authority. Client A exhaustion must NOT
pause Client B either.
"""
from __future__ import annotations
@ -10,7 +11,7 @@ import time
from typing import Any
from . import db
from .shorts_upload import is_upload_quota_error, quota_error_message
from .shorts_upload import quota_error_message
from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts
YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90
@ -193,24 +194,30 @@ def yt_upload_budget(
return limit, used, remaining
def note_yt_upload_attempt(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> None:
"""UI counter only — never gates uploads. YouTube API is the sole authority."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
entry["count"] = int(entry.get("count") or 0) + 1
entry["date"] = pacific_day_from_ts(time.time())
entry["blocked_until"] = 0.0
quota_map[pid] = entry
_save_quota_map(quota_map)
def reserve_yt_upload_slot(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> bool:
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
if profile_upload_blocked(settings, profile_id=pid)[0]:
return False
limit, used, remaining = yt_upload_budget(settings, profile_id=pid)
if remaining <= 0:
return False
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
entry["count"] = int(entry.get("count") or 0) + 1
entry["date"] = pacific_day_from_ts(time.time())
quota_map[pid] = entry
_save_quota_map(quota_map)
"""Always allow. Local 90-count is informational only — never refuse uploads."""
note_yt_upload_attempt(cfg, profile_id=profile_id)
return True
@ -219,18 +226,14 @@ def project_uploads_available(
*,
profile_id: str = "A",
) -> bool:
settings = cfg if cfg is not None else db.get_settings_map()
if profile_upload_blocked(settings, profile_id=profile_id)[0]:
return False
return yt_upload_budget(settings, profile_id=profile_id)[2] > 0
"""Never self-block. Local budget is display-only."""
_ = cfg, profile_id
return True
def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
settings = dict(cfg if cfg is not None else db.get_settings_map())
profiles = {"A", "B", "C", "D"}
for ch in db.list_shorts_channels(enabled=True):
profiles.add(profile_id_for_channel(ch))
return any(project_uploads_available(settings, profile_id=p) for p in profiles)
_ = cfg
return True
def profile_upload_blocked(
@ -238,36 +241,22 @@ def profile_upload_blocked(
*,
profile_id: str = "A",
) -> tuple[bool, float]:
"""Self-imposed pause removed: always unblocked. Clears stale blocked_until."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
until = float(entry.get("blocked_until") or 0)
now = time.time()
if until <= now:
if until > 0:
entry["blocked_until"] = 0.0
quota_map[pid] = entry
_save_quota_map(quota_map)
return False, 0.0
return True, until
if float(entry.get("blocked_until") or 0) > 0:
entry["blocked_until"] = 0.0
quota_map[pid] = entry
_save_quota_map(quota_map)
return False, 0.0
def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]:
settings = dict(cfg if cfg is not None else db.get_settings_map())
profiles = {"A", "B", "C", "D"}
for ch in db.list_shorts_channels(enabled=True):
profiles.add(profile_id_for_channel(ch))
bad: set[str] = set()
for pid in profiles:
blocked, _ = profile_upload_blocked(settings, profile_id=pid)
if blocked:
bad.add(pid)
else:
limit, used, _ = yt_upload_budget(settings, profile_id=pid)
if used >= limit:
bad.add(pid)
return bad
"""No local upload pause — never skip profiles in the worker."""
_ = cfg
return set()
def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
@ -282,18 +271,18 @@ def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str
rows = []
for pid in profiles:
limit, used, remaining = yt_upload_budget(settings, profile_id=pid)
blocked, until = profile_upload_blocked(settings, profile_id=pid)
if used >= limit:
blocked = True
until = until or next_youtube_quota_reset_ts()
# Clear any legacy self-pause; never report blocked for local enforcement
profile_upload_blocked(settings, profile_id=pid)
rows.append(
{
"id": pid,
"limit": limit,
"used": used,
"remaining": remaining,
"blocked": blocked,
"blocked_until": until,
"exhausted_hint": used >= limit,
"blocked": False,
"blocked_until": 0.0,
"reset_at": next_youtube_quota_reset_ts() if used >= limit else 0.0,
}
)
return rows
@ -314,134 +303,53 @@ def pause_uploads_until_reset(
profile_id: str = "A",
reason: str = "",
) -> float:
"""Block uploads for ONE OAuth Client profile until Pacific midnight."""
"""Legacy no-op: do NOT self-pause or defer jobs. Snap UI counter only."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
until = next_youtube_quota_reset_ts()
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
entry["blocked_until"] = until
# Snap counter to limit so UI shows exhausted
entry["blocked_until"] = 0.0
limit = yt_daily_limit(settings)
entry["count"] = max(int(entry.get("count") or 0), limit)
entry["date"] = pacific_day_from_ts(time.time())
quota_map[pid] = entry
_save_quota_map(quota_map)
msg = reason or quota_error_message(profile_id=pid)
defer_profile_shorts_uploads(pid, until, reason=msg)
_ = reason
return until
def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
"""Reschedule pending uploads only for channels on this Client profile."""
pid = normalize_profile_id(profile_id)
ch_ids = channel_ids_for_profile(pid)
if not ch_ids:
return 0
now = time.time()
retry_at = max(until_ts, now) + 300
msg = (reason or quota_error_message(profile_id=pid))[:400]
placeholders = ",".join("?" for _ in ch_ids)
with db._lock:
conn = db._connect()
try:
cur = conn.execute(
f"""
UPDATE shorts_jobs
SET status = 'scheduled',
upload_at = ?,
error = ?,
finished_at = 0,
updated_at = ?
WHERE status IN ('scheduled', 'uploading', 'recorded')
AND clip_path != ''
AND youtube_video_id = ''
AND channel_pk IN ({placeholders})
""",
(retry_at, msg, now, *ch_ids),
)
conn.commit()
return int(cur.rowcount)
finally:
conn.close()
"""No-op: never bulk-defer uploads for a Client. Manual upload must stay free."""
_ = profile_id, until_ts, reason
return 0
def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int:
"""Remove copied global-quota error text from jobs whose Client is NOT blocked."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
blocked = blocked_profile_ids(settings)
cleared = 0
now = time.time()
for ch in db.list_shorts_channels(enabled=None):
pid = profile_id_for_channel(ch)
if pid in blocked:
continue
cid = str(ch.get("id") or "")
with db._lock:
conn = db._connect()
try:
cur = conn.execute(
"""
UPDATE shorts_jobs
SET error = '', updated_at = ?
WHERE channel_pk = ?
AND youtube_video_id = ''
AND status IN ('scheduled', 'recorded', 'failed')
AND (
error LIKE '%配额已用尽%'
OR error LIKE '%QUOTA_EXCEEDED%'
OR error LIKE '%429%'
)
""",
(now, cid),
)
cleared += int(cur.rowcount)
conn.commit()
finally:
conn.close()
return cleared
"""No-op: keep YouTube API error text on jobs for operator feedback."""
_ = cfg
return 0
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]:
"""Scan recent job errors; pause only the matching Client profile(s)."""
"""No-op: never auto-pause Clients from local counters or past 429s."""
_ = cfg
return {}
def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None:
"""Wipe legacy blocked_until / global pause so uploads are never locally gated."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
paused: dict[str, float] = {}
# Soft local budget hit
for row in quota_budgets_by_profile(settings):
pid = str(row["id"])
if row.get("blocked") and float(row.get("blocked_until") or 0) > time.time():
paused[pid] = float(row["blocked_until"])
continue
if int(row.get("used") or 0) >= int(row.get("limit") or 1):
paused[pid] = pause_uploads_until_reset(settings, profile_id=pid)
with db._lock:
conn = db._connect()
try:
rows = conn.execute(
"""
SELECT id, channel_pk, error, updated_at FROM shorts_jobs
WHERE error != ''
ORDER BY updated_at DESC
LIMIT 40
""",
).fetchall()
finally:
conn.close()
for row in rows:
err = str(row["error"] or "")
if not is_upload_quota_error(err):
continue
job = {"channel_pk": row["channel_pk"], "id": row["id"]}
pid = profile_id_for_job(job)
if pid in paused:
continue
until = pause_uploads_until_reset(settings, profile_id=pid)
paused[pid] = until
return paused
quota_map = _load_quota_map(settings)
changed = False
for pid, entry in list(quota_map.items()):
if float(entry.get("blocked_until") or 0) != 0:
entry = dict(entry)
entry["blocked_until"] = 0.0
quota_map[pid] = entry
changed = True
if changed or float(settings.get("shorts_yt_upload_blocked_until") or 0) > 0:
_save_quota_map(quota_map)
# Back-compat aliases used by older call sites (treat as profile A)

View File

@ -1,6 +1,7 @@
httpx[socks]==0.28.1
socksio==1.0.0
fastapi==0.115.6
uvicorn[standard]==0.34.0
httpx==0.28.1
pydantic==2.10.4
pydantic-settings==2.7.0
python-multipart==0.0.20

View File

@ -0,0 +1,33 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
from pathlib import Path
def test_delete_channel_cascades_jobs_and_clips(temp_db, tmp_path):
ch = temp_db.create_shorts_channel(name="gone", enabled=True)
clip = tmp_path / "a.mp4"
clip.write_bytes(b"fake")
job = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"])
temp_db.update_shorts_job(job["id"], status="scheduled", clip_path=str(clip), upload_at=1)
stats = temp_db.delete_shorts_channel(ch["id"])
assert stats["channel"] == 1
assert stats["jobs"] == 1
assert stats["clips"] == 1
assert temp_db.get_shorts_channel(ch["id"]) is None
assert temp_db.get_shorts_job(job["id"]) is None
assert not clip.exists()
def test_purge_orphan_shorts_jobs(temp_db, tmp_path):
clip = tmp_path / "orphan.mp4"
clip.write_bytes(b"x")
job = temp_db.create_shorts_job(session_id="", room_id="r2", channel_pk="missing-channel-id")
temp_db.update_shorts_job(job["id"], status="recorded", clip_path=str(clip))
stats = temp_db.purge_orphan_shorts_jobs()
assert stats["jobs"] == 1
assert stats["clips"] == 1
assert temp_db.get_shorts_job(job["id"]) is None
assert not clip.exists()

View File

@ -0,0 +1,81 @@
# -*- coding: utf-8 -*-
from app.shorts_socks import (
DEFAULT_SOCKS_PROFILE_ID,
merge_socks_profiles_patch,
resolve_upload_socks_proxy,
socks_proxy_url,
)
def test_socks_proxy_url_builds_socks5h():
url = socks_proxy_url(
{
"server": "185.124.61.35",
"port": 43676,
"username": "V0sI3BsI1bxgKRx",
"password": "QGwGeRTAa9YcVhM",
}
)
assert url.startswith("socks5h://")
assert "185.124.61.35:43676" in url
assert "V0sI3BsI1bxgKRx" in url
def test_resolve_off_by_default(temp_db):
cfg = temp_db.get_settings_map()
# seed defaults if missing
if "shorts_upload_socks_enabled" not in cfg:
temp_db.update_settings_map(
{
"shorts_upload_socks_enabled": False,
"shorts_upload_socks_profile_id": DEFAULT_SOCKS_PROFILE_ID,
"shorts_upload_socks_profiles": [
{
"id": DEFAULT_SOCKS_PROFILE_ID,
"label": "静态住宅 IP",
"type": "socks5",
"server": "185.124.61.35",
"port": 43676,
"username": "u",
"password": "p",
}
],
}
)
cfg = temp_db.get_settings_map()
assert resolve_upload_socks_proxy(cfg) == ""
temp_db.update_settings_map({"shorts_upload_socks_enabled": True})
url = resolve_upload_socks_proxy(temp_db.get_settings_map())
assert url.startswith("socks5h://")
def test_merge_keeps_password_when_masked(temp_db):
existing = {
"shorts_upload_socks_profiles": [
{
"id": "a1",
"label": "A",
"type": "socks5",
"server": "1.1.1.1",
"port": 1080,
"username": "u",
"password": "secret-pass",
}
]
}
merged = merge_socks_profiles_patch(
[
{
"id": "a1",
"label": "A2",
"type": "socks5",
"server": "1.1.1.1",
"port": 1080,
"username": "u",
"password": "***pass",
}
],
existing,
)
assert merged[0]["password"] == "secret-pass"
assert merged[0]["label"] == "A2"

View File

@ -45,6 +45,7 @@ def test_reclaim_stale_uploading(temp_db):
channel_pk=ch["id"],
push_date=day,
)
assert job is not None
temp_db.update_shorts_job(
job["id"],
status="uploading",
@ -52,7 +53,39 @@ def test_reclaim_stale_uploading(temp_db):
upload_at=time.time(),
started_at=time.time() - 500,
)
# Heartbeat uses updated_at — force it stale
with temp_db._lock:
conn = temp_db._connect()
try:
conn.execute(
"UPDATE shorts_jobs SET updated_at = ? WHERE id = ?",
(time.time() - 500, job["id"]),
)
conn.commit()
finally:
conn.close()
n = temp_db.reclaim_stale_shorts_uploads(max_age_sec=120)
assert n == 1
row = temp_db.get_shorts_job(job["id"])
assert row["status"] == "scheduled"
def test_create_shorts_job_dedupes_room_day(temp_db):
ch = temp_db.create_shorts_channel(name="D", enabled=True)
day = push_date_from_ts(time.time())
a = temp_db.create_shorts_job(session_id="", room_id="dup1", channel_pk=ch["id"], push_date=day)
b = temp_db.create_shorts_job(session_id="", room_id="dup1", channel_pk=ch["id"], push_date=day)
assert a is not None
assert b is None
def test_finalize_shorts_upload_once(temp_db):
ch = temp_db.create_shorts_channel(name="F", enabled=True)
job = temp_db.create_shorts_job(session_id="", room_id="fin1", channel_pk=ch["id"])
assert job is not None
temp_db.update_shorts_job(job["id"], status="uploading", clip_path="/tmp/x.mp4")
assert temp_db.finalize_shorts_upload(job["id"], youtube_video_id="vid1", youtube_url="http://y/1")
assert not temp_db.finalize_shorts_upload(job["id"], youtube_video_id="vid2", youtube_url="http://y/2")
row = temp_db.get_shorts_job(job["id"])
assert row["youtube_video_id"] == "vid1"
assert row["status"] == "uploaded"

View File

@ -6,7 +6,11 @@ import time
from app.shorts_upload import is_upload_quota_error
from app.shorts_yt_quota import (
YT_DAILY_UPLOAD_LIMIT_DEFAULT,
blocked_profile_ids,
clear_all_upload_self_blocks,
pause_uploads_until_reset,
profile_upload_blocked,
project_uploads_available,
reserve_yt_upload_slot,
yt_upload_budget,
)
@ -30,7 +34,16 @@ def test_yt_upload_budget_and_reserve(temp_db):
assert remaining2 == remaining - 1
def test_pause_uploads_defers_jobs(temp_db):
def test_never_self_blocks_uploads(temp_db):
"""Local counter / pause helpers must not gate uploads."""
cfg = temp_db.get_settings_map()
for _ in range(YT_DAILY_UPLOAD_LIMIT_DEFAULT + 5):
assert reserve_yt_upload_slot(cfg) is True
cfg = temp_db.get_settings_map()
assert project_uploads_available(cfg, profile_id="A") is True
assert profile_upload_blocked(cfg, profile_id="A") == (False, 0.0)
assert blocked_profile_ids(cfg) == set()
ch = temp_db.create_shorts_channel(name="Y", enabled=True)
job = temp_db.create_shorts_job(session_id="", room_id="r1", channel_pk=ch["id"])
temp_db.update_shorts_job(job["id"], status="scheduled", clip_path="/tmp/x.mp4", upload_at=time.time())
@ -38,9 +51,13 @@ def test_pause_uploads_defers_jobs(temp_db):
refreshed = temp_db.get_shorts_job(job["id"])
assert refreshed is not None
assert refreshed["status"] == "scheduled"
assert float(refreshed["upload_at"]) >= until
# Must NOT defer the job into the future as a self-pause
assert float(refreshed["upload_at"]) <= time.time() + 5
cfg = temp_db.get_settings_map()
assert float(cfg.get("shorts_yt_upload_blocked_until") or 0) >= until
assert float(cfg.get("shorts_yt_upload_blocked_until") or 0) == 0
assert until > time.time() # reset timestamp still returned for UI hint
clear_all_upload_self_blocks(cfg)
assert profile_upload_blocked(temp_db.get_settings_map(), profile_id="A") == (False, 0.0)
def test_pacific_day_from_ts():

View File

@ -351,13 +351,13 @@ export default function ShortsPage() {
async function removeChannel(id: string) {
const ok = await confirm({
title: "删除 Shorts 频道",
message: "确定删除该频道?已排程任务不会自动恢复。",
message: "确定删除该频道?将同时删除该频道下全部任务与本地成片素材。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" });
toast.push("频道已删除", "ok");
const r = await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" });
toast.push(`频道已删除(任务 ${r.jobs ?? 0} · 成片 ${r.clips ?? 0})`, "ok");
await load();
}
@ -372,7 +372,7 @@ export default function ShortsPage() {
try {
const r = await fetchJson("/api/shorts/reconcile", { method: "POST" });
toast.push(
`修复完成:丢失成片 ${r.missing_clips ?? 0} · 误标失败 ${r.false_failed ?? 0} · 卡死上传 ${r.stale_uploads ?? 0}`,
`修复完成:孤儿任务 ${r.orphan_jobs ?? 0} · 丢失成片 ${r.missing_clips ?? 0} · 误标失败 ${r.false_failed ?? 0} · 卡死上传 ${r.stale_uploads ?? 0}`,
"ok",
);
await load();
@ -882,23 +882,31 @@ export default function ShortsPage() {
</span>
</div>
<div className="grid gap-3 sm:grid-cols-2">
{(boardChannels.length ? boardChannels : channels.map((c) => ({
id: c.id,
name: c.name,
youtube_channel_id: c.youtube_channel_id,
enabled: c.enabled,
daily_min: Number(c.daily_min ?? 9),
daily_max: Number(c.daily_max ?? 9),
authorized: Boolean(c.authorized || c.has_refresh_token),
used: 0,
scheduled: 0,
uploaded: 0,
pending: 0,
gap: Number(c.daily_max ?? 9),
min_met: false,
max_met: false,
behind_pace: false,
}))).map((ch) => {
{[...(boardChannels.length
? boardChannels
: channels.map((c) => ({
id: c.id,
name: c.name,
youtube_channel_id: c.youtube_channel_id,
enabled: c.enabled,
daily_min: Number(c.daily_min ?? 9),
daily_max: Number(c.daily_max ?? 9),
authorized: Boolean(c.authorized || c.has_refresh_token),
used: 0,
scheduled: 0,
uploaded: 0,
pending: 0,
gap: Number(c.daily_max ?? 9),
min_met: false,
max_met: false,
behind_pace: false,
})))]
.sort((a, b) => {
const an = String(a.name || "").localeCompare(String(b.name || ""), "zh");
if (an !== 0) return an;
return String(a.id || "").localeCompare(String(b.id || ""));
})
.map((ch) => {
const pct = Math.min(100, Math.round((ch.used / Math.max(1, ch.daily_max)) * 100));
const minPct = Math.round((ch.daily_min / Math.max(1, ch.daily_max)) * 100);
const full = channels.find((x) => x.id === ch.id);

View File

@ -7,7 +7,7 @@ import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { fetchJson, fmtTs } from "@/lib/api";
type Settings = Record<string, number | boolean | string>;
type Settings = Record<string, any>;
const FIELDS: Array<{ key: string; label: string; hint: string; step?: number }> = [
{ key: "max_concurrency", label: "最大并发", hint: "同时检查的直播间数,建议 1–3", step: 1 },
@ -111,6 +111,11 @@ export default function SettingsPage() {
settings.shorts_oauth_redirect_uri || "https://dylive.nomadro.com/api/shorts/oauth/callback"
);
const profiles = Array.isArray(settings.shorts_oauth_profiles) ? settings.shorts_oauth_profiles : [];
body.shorts_upload_socks_enabled = Boolean(settings.shorts_upload_socks_enabled);
body.shorts_upload_socks_profile_id = String(settings.shorts_upload_socks_profile_id || "");
body.shorts_upload_socks_profiles = Array.isArray(settings.shorts_upload_socks_profiles)
? settings.shorts_upload_socks_profiles
: [];
const oauthProfiles = profiles.map((p: any) => ({
id: String(p.id || "").toUpperCase(),
label: String(p.label || ""),
@ -432,6 +437,176 @@ export default function SettingsPage() {
/>
</label>
</div>
<div className="space-y-3 rounded-xl border border-violet-500/20 bg-violet-500/5 p-3">
<div className="flex flex-wrap items-center justify-between gap-2">
<div>
<h4 className="text-xs font-medium text-slate-200">Shorts 上传 SOCKS5 代理</h4>
<p className="mt-1 text-[11px] leading-relaxed text-slate-500">
仅作用于 YouTube Shorts 上传(含 OAuth token 刷新),默认关闭。不影响抖音监控与其它业务。
</p>
</div>
<label className="inline-flex items-center gap-2 text-sm text-slate-200">
<input
type="checkbox"
checked={Boolean(settings.shorts_upload_socks_enabled)}
onChange={(e) =>
setSettings((prev) => ({ ...prev, shorts_upload_socks_enabled: e.target.checked }))
}
/>
启用 SOCKS 上传
</label>
</div>
{(() => {
const socksList = Array.isArray(settings.shorts_upload_socks_profiles)
? ([...(settings.shorts_upload_socks_profiles as any[])] as any[])
: [];
const selectedId = String(settings.shorts_upload_socks_profile_id || "");
const selected =
socksList.find((p) => String(p.id) === selectedId) || socksList[0] || null;
const setSocksList = (next: any[]) =>
setSettings((prev) => ({
...prev,
shorts_upload_socks_profiles: next,
shorts_upload_socks_profile_id:
next.some((p) => String(p.id) === String(prev.shorts_upload_socks_profile_id))
? prev.shorts_upload_socks_profile_id
: String(next[0]?.id || ""),
}));
const patchSelected = (patch: Record<string, unknown>) => {
if (!selected) return;
const next = socksList.map((p) =>
String(p.id) === String(selected.id) ? { ...p, ...patch } : p
);
setSocksList(next);
};
return (
<div className="space-y-3">
<div className="flex flex-wrap items-end gap-2">
<label className="block min-w-[12rem] flex-1 text-xs text-slate-400">
当前配置
<select
value={String(selected?.id || "")}
onChange={(e) =>
setSettings((prev) => ({
...prev,
shorts_upload_socks_profile_id: e.target.value,
}))
}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
{socksList.length === 0 ? <option value="">暂无配置</option> : null}
{socksList.map((p) => (
<option key={String(p.id)} value={String(p.id)}>
{String(p.label || p.server || p.id)}
</option>
))}
</select>
</label>
<button
type="button"
onClick={() => {
const id =
typeof crypto !== "undefined" && crypto.randomUUID
? crypto.randomUUID()
: `socks-${Date.now()}`;
const row = {
id,
label: `SOCKS ${socksList.length + 1}`,
type: "socks5",
server: "",
port: 1080,
username: "",
password: "",
};
setSocksList([...socksList, row]);
setSettings((prev) => ({ ...prev, shorts_upload_socks_profile_id: id }));
}}
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-xs text-slate-200 hover:bg-white/10"
>
新增配置
</button>
{selected ? (
<button
type="button"
onClick={() => {
if (socksList.length <= 1) {
setError("至少保留一套 SOCKS 配置");
return;
}
const next = socksList.filter((p) => String(p.id) !== String(selected.id));
setSocksList(next);
}}
className="rounded-lg border border-rose-500/30 bg-rose-500/10 px-3 py-2 text-xs text-rose-100"
>
删除当前
</button>
) : null}
</div>
{selected ? (
<div className="grid gap-2 md:grid-cols-2">
<label className="block text-xs text-slate-400">
名称
<input
value={String(selected.label || "")}
onChange={(e) => patchSelected({ label: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
类型
<select
value={String(selected.type || "socks5")}
onChange={(e) => patchSelected({ type: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 text-sm"
>
<option value="socks5">socks5</option>
<option value="socks5h">socks5h(DNS 走代理)</option>
</select>
</label>
<label className="block text-xs text-slate-400">
服务器
<input
value={String(selected.server || "")}
onChange={(e) => patchSelected({ server: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
placeholder="185.x.x.x"
/>
</label>
<label className="block text-xs text-slate-400">
端口
<input
type="number"
value={Number(selected.port || 0)}
onChange={(e) => patchSelected({ port: Number(e.target.value) })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
用户名
<input
value={String(selected.username || "")}
onChange={(e) => patchSelected({ username: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
</label>
<label className="block text-xs text-slate-400">
密码(*** 表示不修改)
<input
value={String(selected.password || "")}
onChange={(e) => patchSelected({ password: e.target.value })}
className="mt-1 w-full rounded-lg border border-white/10 bg-slate-900 px-3 py-2 font-mono text-sm"
/>
</label>
</div>
) : (
<p className="text-xs text-amber-200">暂无 SOCKS 配置,请点「新增配置」。</p>
)}
</div>
);
})()}
</div>
<div className="space-y-3">
<div>
<h4 className="text-xs font-medium text-slate-200">OAuth 配置档(A / B / C / D)</h4>

View File

@ -320,6 +320,15 @@ export default function ShortsPage() {
arr.push(ch);
buckets.set(key, arr);
}
// Keep card order stable inside each Client group (never sort by used/gap/behind)
for (const [k, arr] of buckets) {
arr.sort((a, b) => {
const an = String(a.name || "").localeCompare(String(b.name || ""), "zh");
if (an !== 0) return an;
return String(a.id || "").localeCompare(String(b.id || ""));
});
buckets.set(k, arr);
}
const order = ["A", "B", "C", "D", "_"];
const keys = [...order.filter((k) => buckets.has(k)), ...[...buckets.keys()].filter((k) => !order.includes(k))];
return keys.map((k) => ({
@ -489,13 +498,13 @@ export default function ShortsPage() {
async function removeChannel(id: string) {
const ok = await confirm({
title: "删除 Shorts 频道",
message: "确定删除该频道?已排程任务不会自动恢复。",
message: "确定删除该频道?将同时删除该频道下全部任务与本地成片素材。",
confirmLabel: "删除",
destructive: true,
});
if (!ok) return;
await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" });
toast.push("频道已删除", "ok");
const r = await fetchJson(`/api/shorts/channels/${id}`, { method: "DELETE" });
toast.push(`频道已删除(任务 ${r.jobs ?? 0} · 成片 ${r.clips ?? 0})`, "ok");
await load();
}
@ -510,7 +519,7 @@ export default function ShortsPage() {
try {
const r = await fetchJson("/api/shorts/reconcile", { method: "POST" });
toast.push(
`修复完成:丢失成片 ${r.missing_clips ?? 0} · 误标失败 ${r.false_failed ?? 0} · 卡死上传 ${r.stale_uploads ?? 0}`,
`修复完成:孤儿任务 ${r.orphan_jobs ?? 0} · 丢失成片 ${r.missing_clips ?? 0} · 误标失败 ${r.false_failed ?? 0} · 卡死上传 ${r.stale_uploads ?? 0}`,
"ok",
);
await load();
@ -948,17 +957,15 @@ export default function ShortsPage() {
{msg ? <div className="mb-3 text-sm text-teal-300">{msg}</div> : null}
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
{status?.upload_quota_blocked ? (
<div className="mb-3 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2.5 text-xs text-rose-50">
<p className="font-medium text-rose-100">部分 Client 的 YouTube 上传配额已用尽</p>
<p className="mt-1 text-rose-100/90">
已暂停:
{(status.upload_quota_blocked_profiles || []).length
? (status.upload_quota_blocked_profiles as string[]).map((p) => `Client ${p}`).join("、")
: "未知"}
。其他 Client 仍可正常上传。
{status.upload_quota_blocked_until ? (
<> 预计恢复:{fmtTs(status.upload_quota_blocked_until)}(北京)</>
{Array.isArray(status?.yt_quota_exhausted_hint) && (status.yt_quota_exhausted_hint as string[]).length ? (
<div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2.5 text-xs text-amber-50">
<p className="font-medium text-amber-100">部分 Client 本地计数已达参考上限(仅提示,不拦截上传)</p>
<p className="mt-1 text-amber-100/90">
提示:
{(status.yt_quota_exhausted_hint as string[]).map((p) => `Client ${p}`).join("、")}
。仍可点「立即上传」;以 YouTube 接口返回为准。
{status.yt_quota_reset_at ? (
<> YouTube 侧预计重置:{fmtTs(status.yt_quota_reset_at)}(北京)</>
) : null}
</p>
{Array.isArray(status.yt_quota_by_profile) ? (
@ -967,19 +974,19 @@ export default function ShortsPage() {
<span
key={row.id}
className={`rounded border px-2 py-0.5 text-[10px] ${
row.blocked
? "border-rose-400/40 bg-rose-500/20 text-rose-100"
row.exhausted_hint
? "border-amber-400/40 bg-amber-500/20 text-amber-100"
: "border-teal-400/30 bg-teal-500/10 text-teal-100"
}`}
>
Client {row.id} · {row.used}/{row.limit}
{row.blocked ? " · 已暂停" : ` · 剩 ${row.remaining}`}
{row.exhausted_hint ? " · 参考已满" : ` · 剩 ${row.remaining}`}
</span>
))}
</div>
) : null}
<p className="mt-1 text-[11px] text-rose-200/70">
配额按 OAuth Client A/B/C/D(不同 Google 项目)分别计算,互不影响。
<p className="mt-1 text-[11px] text-amber-200/70">
配额按 OAuth Client A/B/C/D(不同 Google 项目)分别计算,互不影响。本系统不自行暂停上传。
</p>
</div>
) : Array.isArray(status?.yt_quota_by_profile) ? (
@ -1000,7 +1007,7 @@ export default function ShortsPage() {
) : typeof status?.yt_upload_remaining === "number" && status.yt_upload_remaining <= 10 ? (
<div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50">
YouTube 上传配额即将用尽:今日 {status.yt_upload_used ?? 0}/{status.yt_upload_limit ?? 90} 次(太平洋日),剩余{" "}
{status.yt_upload_remaining} 次。
{status.yt_upload_remaining} 次(仅提示,不拦截)。
</div>
) : status?.last_error ? (
<div className="mb-3 rounded-xl border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">

44
scripts/_deploy.py Normal file
View File

@ -0,0 +1,44 @@
"""Standard deploy: server git pull dev + restart API + rebuild frontend + restart web."""
import paramiko, time
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REPO = "/opt/douyinWEB"
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
def run(cmd, timeout=300):
_s, out, err = c.exec_command(cmd, timeout=timeout)
o = out.read().decode("utf-8", "replace").strip()
e = err.read().decode("utf-8", "replace").strip()
return o, e
print("[git pull]")
o, e = run(f"cd {REPO} && git pull origin dev 2>&1", timeout=60)
print(o or e)
print("[git log]")
o, _ = run(f"cd {REPO} && git log --oneline -2")
print(o)
print("[restart api]")
c.exec_command("systemctl restart douyinweb-api >/dev/null 2>&1", timeout=5)
time.sleep(8)
o, _ = run("systemctl is-active douyinweb-api")
print("api:", o)
print("[npm build]")
o, _ = run(f"cd {REPO}/frontend && npm run build 2>&1 | tail -6", timeout=360)
print(o.encode("ascii", "replace").decode())
print("[restart web]")
c.exec_command("systemctl restart douyinweb-web >/dev/null 2>&1", timeout=5)
time.sleep(5)
o, _ = run("systemctl is-active douyinweb-web")
print("web:", o)
c.close()
print("DONE")

View File

@ -0,0 +1,77 @@
# -*- coding: utf-8 -*-
"""Deploy channel-cascade delete + purge orphan shorts jobs."""
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"backend/app/main.py",
"backend/app/shorts_pipeline.py",
"backend/app/shorts_schedule.py",
"frontend/src/app/shorts/page.tsx",
]
def run(c, cmd, timeout=420):
print("$", cmd[:200], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
text = "".join(buf)
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
print(clean[-3000:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(
c,
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
"systemctl reset-failed douyinweb-api || true; "
"systemctl start douyinweb-api; sleep 5; systemctl is-active douyinweb-api",
)
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
"\"from app import db; db.init_db(); r=db.purge_orphan_shorts_jobs(limit=2000); print('purged', r)\"",
timeout=120,
)
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=600) != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web --no-block; sleep 4; systemctl is-active douyinweb-api douyinweb-web")
c.close()
print("DONE")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,65 @@
# -*- coding: utf-8 -*-
"""Deploy stable Shorts channel card order."""
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"frontend/src/app/shorts/page.tsx",
]
def run(c, cmd, timeout=600):
print("$", cmd[:180], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
text = "".join(buf)
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
print(clean[-2000:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(
c,
"systemctl restart douyinweb-api; sleep 4; systemctl is-active douyinweb-api",
)
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=600) != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
c.close()
print("DONE")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,75 @@
# -*- coding: utf-8 -*-
"""Deploy duplicate-upload fix (lease + room-day dedupe + reclaim)."""
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/db.py",
"backend/app/main.py",
"backend/app/shorts_pipeline.py",
]
def run(c, cmd, timeout=420):
print("$", cmd[:200], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
text = "".join(buf)
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
print(clean[-2500:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(
c,
"systemctl kill -s SIGKILL douyinweb-api || true; sleep 1; "
"systemctl reset-failed douyinweb-api || true; "
"systemctl start douyinweb-api; sleep 5; systemctl is-active douyinweb-api",
)
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
"\"from app import db; db.init_db(); "
"print('deduped', db.dedupe_shorts_jobs_room_day()); "
"print('orphans', db.purge_orphan_shorts_jobs(limit=500))\"",
timeout=120,
)
run(c, "systemctl is-active douyinweb-api")
c.close()
print("DONE")
if __name__ == "__main__":
main()

View File

@ -0,0 +1,102 @@
# -*- coding: utf-8 -*-
"""Deploy Shorts SOCKS5 upload proxy support."""
import sys
import time
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
HOST = "107.173.30.245"
USER = "root"
PASSWORD = "Xiao4669805"
REMOTE = "/opt/douyinWEB"
LOCAL = Path(__file__).resolve().parents[1]
FILES = [
"backend/app/shorts_socks.py",
"backend/app/shorts_upload.py",
"backend/app/shorts_pipeline.py",
"backend/app/db.py",
"backend/app/models.py",
"backend/app/main.py",
"backend/requirements.txt",
"frontend/src/app/settings/page.tsx",
]
def run(c, cmd, timeout=600):
print("$", cmd[:200], flush=True)
chan = c.get_transport().open_session()
chan.settimeout(timeout)
chan.get_pty()
chan.exec_command(cmd)
buf = []
while True:
if chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
if chan.exit_status_ready() and not chan.recv_ready():
break
time.sleep(0.25)
while chan.recv_ready():
buf.append(chan.recv(65535).decode("utf-8", "replace"))
code = chan.recv_exit_status()
text = "".join(buf)
clean = "".join(ch for ch in text if ord(ch) < 128 or "\u4e00" <= ch <= "\u9fff")
print(clean[-2500:], flush=True)
return code
def main():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(HOST, 22, USER, PASSWORD, timeout=30, allow_agent=False, look_for_keys=False)
sftp = c.open_sftp()
for rel in FILES:
print("upload", rel, flush=True)
sftp.put(str(LOCAL / rel), f"{REMOTE}/{rel}")
sftp.close()
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/pip install -q 'httpx[socks]==0.28.1' socksio==1.0.0",
timeout=180,
)
run(
c,
"systemctl restart douyinweb-api; sleep 5; systemctl is-active douyinweb-api",
)
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python - <<'PY'\n"
"from app import db\n"
"from app.shorts_socks import DEFAULT_SOCKS_PROFILES, DEFAULT_SOCKS_PROFILE_ID, resolve_upload_socks_proxy\n"
"db.init_db()\n"
"cfg = db.get_settings_map()\n"
"patch = {}\n"
"if 'shorts_upload_socks_enabled' not in cfg:\n"
" patch['shorts_upload_socks_enabled'] = False\n"
"if not cfg.get('shorts_upload_socks_profile_id'):\n"
" patch['shorts_upload_socks_profile_id'] = DEFAULT_SOCKS_PROFILE_ID\n"
"profiles = cfg.get('shorts_upload_socks_profiles')\n"
"if not isinstance(profiles, list) or not profiles:\n"
" patch['shorts_upload_socks_profiles'] = DEFAULT_SOCKS_PROFILES\n"
"if patch:\n"
" db.update_settings_map(patch)\n"
"cfg = db.get_settings_map()\n"
"print('enabled', bool(cfg.get('shorts_upload_socks_enabled')))\n"
"print('profile_id', cfg.get('shorts_upload_socks_profile_id'))\n"
"print('profiles', len(cfg.get('shorts_upload_socks_profiles') or []))\n"
"print('proxy_when_off', repr(resolve_upload_socks_proxy(cfg)))\n"
"PY",
timeout=60,
)
if run(c, "cd /opt/douyinWEB/frontend && npm run build", timeout=600) != 0:
raise SystemExit(1)
run(c, "systemctl restart douyinweb-web; sleep 3; systemctl is-active douyinweb-api douyinweb-web")
c.close()
print("DONE")
if __name__ == "__main__":
main()

View File

@ -64,11 +64,12 @@ def main():
run(
c,
"cd /opt/douyinWEB/backend && .venv/bin/python -c "
"\"from app import db; from app.shorts_yt_quota import detect_and_block_from_recent_errors, yt_upload_budget; "
"db.init_db(); blocked, until = detect_and_block_from_recent_errors(); "
"lim, used, rem = yt_upload_budget(); "
"print('blocked', blocked, 'until', until); "
"print('budget', used, '/', lim, 'remaining', rem)\"",
"\"from app import db; from app.shorts_yt_quota import clear_all_upload_self_blocks, profile_upload_blocked, yt_upload_budget, blocked_profile_ids; "
"db.init_db(); clear_all_upload_self_blocks(); "
"print('blocked_ids', blocked_profile_ids()); "
"print('profile_A_blocked', profile_upload_blocked(profile_id='A')); "
"lim, used, rem = yt_upload_budget(profile_id='A'); "
"print('budget_A', used, '/', lim, 'remaining', rem)\"",
timeout=60,
)
run(