Add Xposed LiveCam control console and document it in README.

Pairs Android devices over WSS for TikTok/YouTube preview and go-live from monitored Douyin sources; also spreads TikTok uploads across the Beijing day with per-channel claim cooldown.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Eric 2026-10-29 17:28:47 +08:00
parent 5df8a23f00
commit ada3de5c52
14 changed files with 1134 additions and 30 deletions

View File

@ -4,6 +4,8 @@
可选旁路:**Shorts**(在播随机/开播入队 → 短成片 → YouTube Shorts 上传)。**默认关闭**,失败不影响监控 / 封面 / Webhook / 场次。 可选旁路:**Shorts**(在播随机/开播入队 → 短成片 → YouTube Shorts 上传)。**默认关闭**,失败不影响监控 / 封面 / Webhook / 场次。
可选旁路:**Xposed 直播控制台**(`/xposed`):网站配对已装 LiveCam / LSPosed 的 Android 真机,把监控上游推到手机 TikTok / YouTube 预览与开播。独立 `xposed_*` 表,失败不影响监控 / Shorts / 上传。详见 [docs/XPOSED_CONTROL.md](docs/XPOSED_CONTROL.md)。
控制台默认开启 **站点登录**(Cookie 会话);可选 `DY_API_KEY` 保护写操作。 控制台默认开启 **站点登录**(Cookie 会话);可选 `DY_API_KEY` 保护写操作。
## Windows 客户端(本地独立运行) ## Windows 客户端(本地独立运行)
@ -217,6 +219,7 @@ DY_NEKO_NAT1TO1=<国内边缘公网IP> # 改后清 nat1to1 缓存
| PocketBase 管理 | `${PUBLIC_BASE}/_/` | | PocketBase 管理 | `${PUBLIC_BASE}/_/` |
| Shorts | `${PUBLIC_BASE}/shorts` | | Shorts | `${PUBLIC_BASE}/shorts` |
| YouTube | `${PUBLIC_BASE}/youtube` | | YouTube | `${PUBLIC_BASE}/youtube` |
| Xposed 直播控制 | `${PUBLIC_BASE}/xposed` |
| 运维 | `${PUBLIC_BASE}/ops` | | 运维 | `${PUBLIC_BASE}/ops` |
| Web 分析 | `${PUBLIC_BASE}/web` | | Web 分析 | `${PUBLIC_BASE}/web` |
| Netdata(可选,需登录) | `${PUBLIC_BASE}/netdata/`(反代 `127.0.0.1:19999`,见 [运维与 Netdata](#运维与-netdata)) | | Netdata(可选,需登录) | `${PUBLIC_BASE}/netdata/`(反代 `127.0.0.1:19999`,见 [运维与 Netdata](#运维与-netdata)) |
@ -321,6 +324,20 @@ Windows 上可用 `python scripts\_deploy.py`(需自行配置 SSH 目标,**
- `DY_AUTH_ENABLED=false` 时跳过会话校验(本地调试) - `DY_AUTH_ENABLED=false` 时跳过会话校验(本地调试)
- 可选 `DY_API_KEY`:写操作需 `X-API-Key` / `Authorization`(GET 免检) - 可选 `DY_API_KEY`:写操作需 `X-API-Key` / `Authorization`(GET 免检)
- 会话放行:`/api/auth/login`、`/api/auth/status`、`/api/shorts/oauth/callback` - 会话放行:`/api/auth/login`、`/api/auth/status`、`/api/shorts/oauth/callback`
- 设备侧放行(手机凭证,非站点会话):`/api/xposed/device/enroll`、`/source`、`/source-status`、`/ws`
### Xposed 直播控制台(LiveCam)
入口:抖音子导航 **直播间** 右侧 **Xposed**(`/xposed`)。专题说明与验收记录见 [XPOSED_CONTROL.md](docs/XPOSED_CONTROL.md)。
- **配对**:管理员在网站生成一次性配对码(约 10 分钟);手机 LiveCam 填写站点 HTTPS 地址与配对码,凭证存 Android Keystore,不保存站点密码
- **上游**:从监控房间列表选源,或输入 `https://live.douyin.com/房间号`;站点解析 FLV/HLS 后仅下发当前分配地址,Cookie 不进宿主 App
- **操作**:打开/关闭目标 App、进入预览、自动开播、结束直播、暂停/恢复、截图、点击接管;开播/结束可一次性排期(浏览器时区录入,北京时间展示)
- **平台**:同一时刻一台手机只控 TikTok 或 YouTube;换平台前先结束并关闭原 App;平台自动化驱动隔离维护
- **权限**:只读用户可看状态/截图;配对、下发命令需写权限。APK:`GET /api/xposed/apk`(管理员)
- **数据**:`xposed_devices` / `xposed_pair_codes` / `xposed_commands`,与监控、YouTube/TikTok 上传表隔离
- **部署**:`scripts/deploy_xposed_control.py`(`DY_DEPLOY_HOST` / `USER` / `PASSWORD`);上线前备份代码与 `.next`
- **验证**:`python -m pytest tests/test_xposed_control.py -q`
### 监控核心 ### 监控核心
@ -548,6 +565,7 @@ Studio 里长时间停在 **Processing will begin shortly / Pending**,优先
| `/slots` | 开播时段规律:24h→6×4h,日/周热力 | | `/slots` | 开播时段规律:24h→6×4h,日/周热力 |
| `/sessions` | 场次列表 + 图表;`platform` 可筛抖音 / youtube / shorts | | `/sessions` | 场次列表 + 图表;`platform` 可筛抖音 / youtube / shorts |
| `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 | | `/rooms` | 批量管理;预检;重检;批量标签;快捷收藏/拉黑 |
| `/xposed` | Xposed / LiveCam:设备配对、上游分配、预览开播、截图接管 |
| `/anchors` | 主播画像与下次开播启发式 | | `/anchors` | 主播画像与下次开播启发式 |
| `/covers` | 截图库(有图墙 / 缺图表) | | `/covers` | 截图库(有图墙 / 缺图表) |
| `/events` | SSE 时间线;场次详情;导出 | | `/events` | SSE 时间线;场次详情;导出 |
@ -581,14 +599,14 @@ Studio 里长时间停在 **Processing will begin shortly / Pending**,优先
``` ```
douyinWEB/ douyinWEB/
backend/app/ FastAPI(auth / monitor / cover / shorts_* / yt_long_* / youtube_relay_* / youtube_neko / host_metrics / clip_retention …) backend/app/ FastAPI(auth / monitor / cover / shorts_* / yt_long_* / youtube_relay_* / youtube_neko / xposed_control / host_metrics / clip_retention …)
backend/tests/ pytest(Shorts / live / reconcile 等) backend/tests/ pytest(Shorts / live / reconcile / xposed 等)
backend/data/ SQLite、封面/成片缓存 backend/data/ SQLite、封面/成片缓存、xposed APK
frontend/src/ Next.js 控制台(Web) frontend/src/ Next.js 控制台(Web;含 `/xposed`)
desktop/ Windows Electron 客户端(本机 PB+API+UI) desktop/ Windows Electron 客户端(本机 PB+API+UI)
youtube-svc/ YouTube.js sidecar(InnerTube) youtube-svc/ YouTube.js sidecar(InnerTube)
pb/ PocketBase 数据与 migrations pb/ PocketBase 数据与 migrations
docs/ 专题文档(Shorts、物理机部署、YPP 创收 / AdSense API 调研等);全局 SOCKS5 方案见 README docs/ 专题文档(Xposed、Shorts、物理机部署、YPP 等);全局 SOCKS5 方案见 README
scripts/ 本地启动与 VPS 增量部署 scripts/ 本地启动与 VPS 增量部署
``` ```
@ -652,6 +670,7 @@ cd youtube-svc && npm install
| POST | `/api/sessions/reconcile-stale` | 对账僵尸场次 | | POST | `/api/sessions/reconcile-stale` | 对账僵尸场次 |
| POST | `/api/rooms/quick` | 收藏 / 取消 / 拉黑 | | POST | `/api/rooms/quick` | 收藏 / 取消 / 拉黑 |
| GET | `/api/events/stream` | SSE | | GET | `/api/events/stream` | SSE |
| GET/POST | `/api/xposed/*` | Xposed 设备配对 / 命令 / 截图 / APK(设备 enroll/ws 免站点会话) |
完整文档:线上 `/docs` 或本地 `8000/docs`。 完整文档:线上 `/docs` 或本地 `8000/docs`。
@ -955,19 +974,19 @@ git remote -v # 查看当前 origin
|------|------| |------|------|
| `main` | 稳定快照;可不直接部署 | | `main` | 稳定快照;可不直接部署 |
| `dev` | 日常合入参考 | | `dev` | 日常合入参考 |
| `test1` | 当前生产跟踪 / 已验证功能 | | `test1` / `test2` / `test3` | 历史生产跟踪与已验证轮次 |
| `test2` | 下一轮开发(从 `test1` 拉出) | | `test4` | 当前开发线(含 Xposed 直播控制台等) |
**推荐发布流程**: **推荐发布流程**:
``` ```
本地 commit → push 到 origin(test1 / test2) 本地 commit → push 到 origin(test3 / test4)
→ SSH 到目标机:cd ${APP_DIR} && git fetch && git reset --hard origin/<branch> → SSH 到目标机:cd ${APP_DIR} && git fetch && git reset --hard origin/<branch>
→ systemctl restart douyinweb-api → systemctl restart douyinweb-api
→ cd frontend && npm run build && systemctl restart douyinweb-web → cd frontend && npm run build && systemctl restart douyinweb-web
``` ```
双端同步可用:`python scripts/_deploy_git_pull_both.py`(跟踪 **`test2`**;两台海外 VPS:dylive + dy.live)。 双端同步可用:`python scripts/_deploy_git_pull_both.py`(跟踪部署分支;两台海外 VPS:dylive + dy.live)。
**禁止**: **禁止**:

View File

@ -10,6 +10,10 @@ from .config import settings
# OAuth redirect + SSE + static covers — never block # OAuth redirect + SSE + static covers — never block
_PUBLIC_PATHS = { _PUBLIC_PATHS = {
"/api/xposed/device/enroll",
"/api/xposed/device/source",
"/api/xposed/device/source-status",
"/api/xposed/device/ws",
"/api/shorts/oauth/callback", "/api/shorts/oauth/callback",
"/api/tiktok/oauth/callback/", "/api/tiktok/oauth/callback/",
"/api/tiktok/oauth/callback", "/api/tiktok/oauth/callback",

View File

@ -668,8 +668,9 @@ def _seed_defaults(conn: sqlite3.Connection) -> None:
"tiktok_live_sample_batch": 1, "tiktok_live_sample_batch": 1,
"tiktok_sample_any_live": True, "tiktok_sample_any_live": True,
"tiktok_upload_spread": True, "tiktok_upload_spread": True,
"tiktok_upload_min_gap_sec": 720, # Any-account gap / same-account gap — keep uploads sparse across Beijing day
"tiktok_channel_min_gap_sec": 2400, "tiktok_upload_min_gap_sec": 900,
"tiktok_channel_min_gap_sec": 5400,
"tiktok_delete_clip_after_upload": True, "tiktok_delete_clip_after_upload": True,
# TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default # TikTok upload SOCKS profiles (pool); each account opts in via socks_enabled=0 by default
"tiktok_upload_socks_profiles": [], "tiktok_upload_socks_profiles": [],

View File

@ -275,6 +275,8 @@ async def lifespan(_: FastAPI):
app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan) app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)
from .xposed_control import router as xposed_router
app.include_router(xposed_router)
_DESKTOP_LIGHT = str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"} _DESKTOP_LIGHT = str(os.environ.get("DY_DESKTOP_LIGHT") or "").strip().lower() in {"1", "true", "yes"}

View File

@ -26,6 +26,10 @@ _PUBLIC_API_PREFIXES = (
"/api/tiktok/oauth/callback/", "/api/tiktok/oauth/callback/",
) )
_PUBLIC_API_EXACT = { _PUBLIC_API_EXACT = {
"/api/xposed/device/enroll",
"/api/xposed/device/source",
"/api/xposed/device/source-status",
"/api/xposed/device/ws",
"/api/health", "/api/health",
"/api/ping", "/api/ping",
"/api/shorts/oauth/callback", "/api/shorts/oauth/callback",

View File

@ -695,11 +695,25 @@ def defer_tiktok_job_to_next_day(job_id: str, *, stagger_sec: float = 60) -> Non
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.""" """Claim next due scheduled upload, skipping accounts already at daily_max published today.
Also enforces per-channel cooldown so a backlog of past-due upload_at cannot
dump many videos in one burst.
"""
now = time.time() now = time.time()
today = push_date_from_ts(now) today = push_date_from_ts(now)
# Try a few candidates: defer over-quota rows then pick the next. try:
for i in range(8): from . import db as _db
from .tiktok_schedule import channel_upload_cooldown_left, pick_upload_at
cfg = _db.get_settings_map()
except Exception:
cfg = {}
channel_upload_cooldown_left = None # type: ignore
pick_upload_at = None # type: ignore
# Try a few candidates: defer over-quota / cooling rows then pick the next.
for i in range(12):
with _lock: with _lock:
conn = _connect() conn = _connect()
try: try:
@ -729,6 +743,26 @@ def claim_due_tiktok_upload() -> dict[str, Any] | None:
if ch_pk and channel_at_daily_upload_max(ch_pk, today): if ch_pk and channel_at_daily_upload_max(ch_pk, today):
defer_tiktok_job_to_next_day(jid, stagger_sec=60 + i * 90) defer_tiktok_job_to_next_day(jid, stagger_sec=60 + i * 90)
continue continue
if ch_pk and channel_upload_cooldown_left is not None:
try:
left = float(channel_upload_cooldown_left(ch_pk, cfg=cfg) or 0)
except Exception:
left = 0.0
if left > 5:
# Push this job (and avoid busy-looping the same row) into a later random slot
if pick_upload_at is not None:
try:
new_at = float(pick_upload_at(channel_pk=ch_pk, cfg=cfg))
update_tiktok_job(
jid,
upload_at=max(now + left + 30.0, new_at),
error=f"频道冷却中,约 {int(left // 60)} 分钟后再传",
)
except Exception:
update_tiktok_job(jid, upload_at=now + left + 60.0)
else:
update_tiktok_job(jid, upload_at=now + left + 60.0)
continue
with _lock: with _lock:
conn = _connect() conn = _connect()
try: try:

View File

@ -1,5 +1,5 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""TikTok upload scheduling — Beijing day staggered slots.""" """TikTok upload scheduling — Beijing day random stagger (anti burst)."""
from __future__ import annotations from __future__ import annotations
import random import random
@ -36,36 +36,82 @@ def _occupied_slots(push_date: str) -> list[tuple[float, str]]:
def pick_upload_at(*, channel_pk: str, push_date: str = "", cfg: dict[str, Any] | None = None) -> float: def pick_upload_at(*, channel_pk: str, push_date: str = "", cfg: dict[str, Any] | None = None) -> float:
"""Pick a random upload time within the Beijing calendar day.
Not "soon after now" clustering — spread across remaining daytime so two
accounts never dump a backlog in one burst.
"""
settings = cfg or db.get_settings_map() settings = cfg or db.get_settings_map()
now = time.time() now = time.time()
day = push_date or push_date_from_ts(now) day = push_date or push_date_from_ts(now)
day_end = _day_end_ts(day) day_start, day_end = beijing_day_bounds(day)
latest = day_end - 45 latest = day_end - 90.0
if not settings.get("tiktok_upload_spread", True): if not settings.get("tiktok_upload_spread", True):
return min(now + random.uniform(20, 120), latest) return float(min(now + random.uniform(120, 900), latest))
global_min = max(300.0, float(settings.get("tiktok_upload_min_gap_sec") or 720))
channel_min = max(global_min, float(settings.get("tiktok_channel_min_gap_sec") or 2400)) # Global gap between ANY account; per-channel gap keeps each account sparse across 24h.
earliest = now + random.uniform(180, 1500) global_min = max(600.0, float(settings.get("tiktok_upload_min_gap_sec") or 900))
if earliest >= latest: channel_min = max(global_min, float(settings.get("tiktok_channel_min_gap_sec") or 5400))
earliest = now + random.uniform(30, max(90.0, global_min * 0.4))
# Prefer random point in the remaining Beijing day (not just next 25 minutes).
earliest = max(now + random.uniform(300, 1200), day_start + 60)
if earliest >= latest - 60:
# Near day end → spill into tomorrow with random morning/afternoon offset
next_day = push_date_from_ts(day_end + 10)
n_start, n_end = beijing_day_bounds(next_day)
earliest = n_start + random.uniform(3600, 6 * 3600)
latest = n_end - 90
day = next_day
slots = _occupied_slots(day) slots = _occupied_slots(day)
def conflicts(ts: float) -> bool: def conflicts(ts: float) -> bool:
for other_ts, other_ch in slots: for other_ts, other_ch in slots:
gap = abs(ts - other_ts) gap = abs(ts - other_ts)
if gap < global_min * 0.9: if gap < global_min * 0.85:
return True return True
if other_ch == channel_pk and gap < channel_min * 0.9: if other_ch and other_ch == channel_pk and gap < channel_min * 0.85:
return True return True
return False return False
window_end = max(earliest + 60, latest) lo = float(earliest)
for _ in range(48): hi = float(max(lo + 60.0, latest))
cand = random.uniform(earliest, window_end) for _ in range(96):
cand = random.uniform(lo, hi)
if not conflicts(cand): if not conflicts(cand):
return float(min(cand, latest)) return float(min(cand, latest))
last_ts = max((s[0] for s in slots), default=now)
return float(min(max(earliest, last_ts + global_min), latest)) # Fallback: push after last occupied slot with channel gap jitter
last_ch = max((s[0] for s in slots if s[1] == channel_pk), default=now)
last_any = max((s[0] for s in slots), default=now)
base = max(lo, last_ch + channel_min, last_any + global_min)
return float(min(base + random.uniform(60, 900), latest))
def channel_upload_cooldown_left(channel_pk: str, *, cfg: dict[str, Any] | None = None) -> float:
"""Seconds until this channel may start another upload (0 = free)."""
pk = str(channel_pk or "").strip()
if not pk:
return 0.0
settings = cfg or db.get_settings_map()
channel_min = max(600.0, float(settings.get("tiktok_channel_min_gap_sec") or 5400))
now = time.time()
day = push_date_from_ts(now)
# Recent success / in-flight
last = 0.0
data = tiktok_db.list_tiktok_jobs(push_date=day, limit=200, offset=0)
for j in data.get("jobs") or []:
if str(j.get("channel_pk") or "") != pk:
continue
st = str(j.get("status") or "")
if st == "uploading":
last = max(last, float(j.get("updated_at") or 0), float(j.get("upload_at") or 0))
elif st in {"uploaded", "done"}:
last = max(last, float(j.get("finished_at") or j.get("updated_at") or 0))
if last <= 0:
return 0.0
left = (last + channel_min) - now
return float(max(0.0, left))
def schedule_board(limit: int = 24) -> dict[str, Any]: def schedule_board(limit: int = 24) -> dict[str, Any]:

View File

@ -0,0 +1,441 @@
"""LiveCam device control. Site sessions manage devices; device tokens never grant site access."""
from __future__ import annotations
import asyncio
import base64
import hashlib
import json
import re
import secrets
import time
import threading
import uuid
from contextlib import contextmanager
from fastapi import APIRouter, HTTPException, Request, Response, WebSocket, WebSocketDisconnect
from fastapi.responses import FileResponse
from pydantic import BaseModel, Field
from . import db, douyin
from .authz import assert_write_access, session_role_from_request
from .session_auth import session_user_from_request
router = APIRouter(prefix="/api/xposed", tags=["xposed"])
PLATFORMS = {"tiktok", "youtube"}
ACTIONS = {"apply_source", "open_app", "close_app", "prepare", "start_live", "stop_live", "pause_media", "resume_media", "audio", "snapshot", "tap", "back"}
_clients: dict[str, WebSocket] = {}
_source_cache: dict[str, tuple[float, dict]] = {}
_source_locks: dict[str, asyncio.Lock] = {}
_source_status_cache: dict[str, tuple[float, dict]] = {}
_source_status_locks: dict[str, asyncio.Lock] = {}
_schema_path = ""
_schema_lock = threading.Lock()
@contextmanager
def store():
# Independent additive tables: no changes to monitoring/YouTube/TikTok data.
global _schema_path
current_path = str(db.settings.sqlite_path)
if _schema_path != current_path:
with _schema_lock:
if _schema_path != current_path:
with db._lock:
conn = db._connect()
try:
conn.executescript("""
CREATE TABLE IF NOT EXISTS xposed_devices (
id TEXT PRIMARY KEY, name TEXT NOT NULL, token_hash TEXT NOT NULL,
created_at REAL NOT NULL, last_seen REAL NOT NULL DEFAULT 0,
revoked INTEGER NOT NULL DEFAULT 0, config TEXT NOT NULL DEFAULT '{}',
revision INTEGER NOT NULL DEFAULT 0, telemetry TEXT NOT NULL DEFAULT '{}',
screenshot TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS xposed_pair_codes (
hash TEXT PRIMARY KEY, name TEXT NOT NULL, expires_at REAL NOT NULL
);
CREATE TABLE IF NOT EXISTS xposed_commands (
id TEXT PRIMARY KEY, device_id TEXT NOT NULL, action TEXT NOT NULL,
payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'queued',
created_at REAL NOT NULL, not_before REAL NOT NULL, expires_at REAL NOT NULL,
sent_at REAL NOT NULL DEFAULT 0, finished_at REAL NOT NULL DEFAULT 0,
result TEXT NOT NULL DEFAULT '{}', actor TEXT NOT NULL DEFAULT ''
);
CREATE INDEX IF NOT EXISTS idx_xposed_commands_device ON xposed_commands(device_id, created_at);
""")
conn.commit()
finally:
conn.close()
_schema_path = current_path
with db._lock:
conn = db._connect()
try:
yield conn
conn.commit()
finally:
conn.close()
def digest(value: str) -> str:
return hashlib.sha256(value.encode()).hexdigest()
def admin(request: Request, *, write: bool = False) -> str:
user = session_user_from_request(request)
if not user:
raise HTTPException(401, "请登录")
if write:
assert_write_access(request)
return user
def authenticate(device_id: str, token: str) -> dict:
with store() as c:
row = c.execute("SELECT * FROM xposed_devices WHERE id=? AND revoked=0", (device_id,)).fetchone()
if not token or not row or not secrets.compare_digest(row["token_hash"], digest(token)):
raise HTTPException(401, "设备凭证失效")
return dict(row)
def device_auth(request: Request) -> dict:
return authenticate(request.headers.get("x-device-id", ""), request.headers.get("authorization", "").removeprefix("Bearer "))
def clean_source(value: str) -> str:
value = value.strip()
if re.fullmatch(r"\d{5,25}", value):
return f"https://live.douyin.com/{value}"
if re.fullmatch(r"https://live\.douyin\.com/\d{5,25}/?", value):
return value.rstrip("/")
raise HTTPException(422, "请选择直播间或输入 live.douyin.com 房间地址")
def public_device(row) -> dict:
d = dict(row)
for key in ("token_hash", "screenshot"):
d.pop(key, None)
d["config"] = json.loads(d["config"])
d["telemetry"] = json.loads(d["telemetry"])
d["online"] = d["id"] in _clients and time.time() - d["last_seen"] < 35
return d
class PairCode(BaseModel):
name: str = Field(min_length=1, max_length=80)
class Enroll(BaseModel):
code: str = Field(min_length=8, max_length=40)
model: str = Field(default="Android", max_length=120)
@router.post("/pair-codes")
def pair_code(body: PairCode, request: Request):
admin(request, write=True)
code = secrets.token_hex(6).upper()
expiry = time.time() + 600
with store() as c:
c.execute("DELETE FROM xposed_pair_codes WHERE expires_at<?", (time.time(),))
c.execute("INSERT INTO xposed_pair_codes VALUES (?,?,?)", (digest(code), body.name, expiry))
return {"code": code, "expires_at": expiry}
@router.post("/device/enroll")
def enroll(body: Enroll, request: Request):
# 48-bit one-use code, ten-minute lifetime; no administrator password on device.
code_hash = digest(body.code.strip().upper())
device_id, token = uuid.uuid4().hex, secrets.token_urlsafe(40)
with store() as c:
row = c.execute("SELECT * FROM xposed_pair_codes WHERE hash=? AND expires_at>?", (code_hash, time.time())).fetchone()
if not row:
raise HTTPException(401, "配对码无效或已过期")
c.execute("DELETE FROM xposed_pair_codes WHERE hash=?", (code_hash,))
c.execute("INSERT INTO xposed_devices(id,name,token_hash,created_at,telemetry) VALUES(?,?,?,?,?)",
(device_id, row["name"], digest(token), time.time(), json.dumps({"model": body.model})))
return {"device_id": device_id, "token": token}
@router.get("/devices")
def devices(request: Request):
admin(request)
with store() as c:
rows = c.execute("SELECT * FROM xposed_devices ORDER BY created_at DESC").fetchall()
return {"devices": [public_device(r) for r in rows], "can_write": session_role_from_request(request) != "readonly", "server_time": time.time()}
@router.get("/apk")
def apk(request: Request):
admin(request)
from .config import settings
path = settings.data_dir / "xposed" / "livecam.apk"
if not path.is_file():
raise HTTPException(404, "APK 尚未发布")
return FileResponse(path, media_type="application/vnd.android.package-archive", filename="LiveCam-control.apk", headers={"Cache-Control": "no-store"})
@router.delete("/devices/{device_id}")
async def revoke(device_id: str, request: Request):
admin(request, write=True)
with store() as c:
c.execute("UPDATE xposed_devices SET revoked=1 WHERE id=?", (device_id,))
c.execute("UPDATE xposed_commands SET status='cancelled',finished_at=? WHERE device_id=? AND status='queued'", (time.time(), device_id))
ws = _clients.get(device_id)
if ws:
await ws.close(code=4001)
return {"ok": True}
@router.get("/sources")
def sources(request: Request, q: str = ""):
admin(request)
rooms = db.list_rooms(q=q[:100], enabled=True, limit=2000)["rooms"]
return {"sources": [{"id": r["id"], "url": r["url"], "name": r.get("last_anchor") or r.get("note") or r["room_id"],
"room_id": r["room_id"], "status": r.get("last_status"), "checked_at": r.get("last_checked_at")} for r in rooms
if not db.is_blacklisted(r["room_id"], r["url"])]}
async def resolve_source(source: str) -> dict:
source = clean_source(source)
async with _source_locks.setdefault(source, asyncio.Lock()):
cached = _source_cache.get(source)
if cached and time.time() - cached[0] < 30:
return cached[1]
cfg = await asyncio.to_thread(db.get_settings_map)
result = await douyin.check_room(source, cookie=str(cfg.get("dy_cookie") or ""), proxy=str(cfg.get("http_proxy") or "").strip() or None)
if not result.get("ok") or not result.get("is_live") or not result.get("stream_candidates"):
raise HTTPException(409, "上游离线或解析暂不可用,请稍后重试")
reply = {"source": source, "title": result.get("title", ""), "anchor": result.get("anchor_name", ""),
"candidates": result["stream_candidates"], "resolved_at": time.time()}
if len(_source_cache) >= 256:
oldest = min(_source_cache, key=lambda k: _source_cache[k][0])
_source_cache.pop(oldest, None)
_source_cache[source] = (time.time(), reply)
return reply
@router.get("/device/source")
async def device_source(request: Request):
device = await asyncio.to_thread(device_auth, request)
config = json.loads(device["config"])
if not config.get("source"):
raise HTTPException(409, "尚未分配上游源")
return await resolve_source(config["source"])
@router.get("/device/source-status")
async def device_source_status(request: Request):
"""Fresh room evidence, independent of playback URL caches and command automation."""
device = await asyncio.to_thread(device_auth, request)
config = json.loads(device["config"])
source = clean_source(config.get("source", ""))
async with _source_status_locks.setdefault(source, asyncio.Lock()):
cached = _source_status_cache.get(source)
if cached and time.time() - cached[0] < 8:
evidence = cached[1]
else:
cfg = await asyncio.to_thread(db.get_settings_map)
result = await douyin.check_room(source, cookie=str(cfg.get("dy_cookie") or ""),
proxy=str(cfg.get("http_proxy") or "").strip() or None)
code = result.get("status_code")
state = "live" if result.get("ok") is True and code == 2 else (
"ended" if result.get("ok") is True and code == 4 else "unknown")
evidence = {"state": state, "room_status": code, "checked_at": time.time()}
if len(_source_status_cache) >= 256:
_source_status_cache.pop(min(_source_status_cache, key=lambda k: _source_status_cache[k][0]), None)
_source_status_cache[source] = (time.time(), evidence)
return {**evidence, "source": source, "revision": device["revision"]}
class Command(BaseModel):
action: str = Field(max_length=32)
payload: dict = Field(default_factory=dict)
not_before: float = 0
request_id: str = Field(default_factory=lambda: uuid.uuid4().hex, min_length=8, max_length=80, pattern=r"^[a-zA-Z0-9_-]+$")
def validate_payload(action: str, payload: dict) -> dict:
if action not in ACTIONS:
raise HTTPException(422, "不支持的操作")
if action == "apply_source":
platform = payload.get("platform")
if platform not in PLATFORMS:
raise HTTPException(422, "请选择 TikTok 或 YouTube")
return {"platform": platform, "source": clean_source(str(payload.get("source", ""))),
"audio": payload.get("audio", True) is True, "rotation": int(payload.get("rotation", 0)) if payload.get("rotation", 0) in (0,90,180,270) else 0,
"mirror": payload.get("mirror", False) is True}
if action == "audio":
return {"enabled": payload.get("enabled") is True}
if action == "tap":
try:
x, y = float(payload["x"]), float(payload["y"])
except (KeyError, ValueError, TypeError):
raise HTTPException(422, "坐标无效")
if not (0 <= x <= 1 and 0 <= y <= 1):
raise HTTPException(422, "坐标必须在屏幕范围内")
return {"x": x, "y": y}
return {}
@router.post("/devices/{device_id}/commands")
def create_command(device_id: str, body: Command, request: Request):
actor = admin(request, write=True)
payload = validate_payload(body.action, body.payload)
now = time.time()
when = max(now, body.not_before)
if when > now + 7 * 86400:
raise HTTPException(422, "最多提前七天排期")
if body.action in {"apply_source", "tap", "audio", "snapshot", "back"} and when > now + 5:
raise HTTPException(422, "此操作不支持排期")
with store() as c:
existing = c.execute("SELECT id,device_id FROM xposed_commands WHERE id=?", (body.request_id,)).fetchone()
if existing:
if existing["device_id"] != device_id:
raise HTTPException(409, "请求标识冲突")
return {"id": existing["id"], "duplicate": True}
device = c.execute("SELECT * FROM xposed_devices WHERE id=? AND revoked=0", (device_id,)).fetchone()
if not device:
raise HTTPException(404, "设备不存在或已撤销")
if body.action != "apply_source" and not json.loads(device["config"]).get("platform"):
raise HTTPException(409, "请先分配平台与上游源")
c.execute("INSERT INTO xposed_commands(id,device_id,action,payload,created_at,not_before,expires_at,actor) VALUES(?,?,?,?,?,?,?,?)",
(body.request_id, device_id, body.action, json.dumps(payload), now, when, when + 120, actor))
return {"id": body.request_id, "status": "queued", "not_before": when}
@router.get("/devices/{device_id}/commands")
def commands(device_id: str, request: Request):
admin(request)
with store() as c:
rows = c.execute("SELECT * FROM xposed_commands WHERE device_id=? ORDER BY created_at DESC LIMIT 60", (device_id,)).fetchall()
return {"commands": [dict(r, payload=json.loads(r["payload"]), result=json.loads(r["result"])) for r in rows]}
@router.delete("/devices/{device_id}/commands/{command_id}")
def cancel(device_id: str, command_id: str, request: Request):
admin(request, write=True)
with store() as c:
cur = c.execute("UPDATE xposed_commands SET status='cancelled',finished_at=? WHERE id=? AND device_id=? AND status='queued'", (time.time(), command_id, device_id))
if not cur.rowcount:
raise HTTPException(409, "命令已开始或已结束,不能撤回")
return {"ok": True}
@router.get("/devices/{device_id}/screenshot")
def screenshot(device_id: str, request: Request):
admin(request)
with store() as c:
row = c.execute("SELECT screenshot FROM xposed_devices WHERE id=?", (device_id,)).fetchone()
if not row or not row["screenshot"]:
raise HTTPException(404, "尚无截图")
return Response(base64.b64decode(row["screenshot"]), media_type="image/jpeg", headers={"Cache-Control": "no-store"})
def next_command(device_id: str) -> dict | None:
now = time.time()
with store() as c:
c.execute("UPDATE xposed_commands SET status='expired',finished_at=? WHERE device_id=? AND status='queued' AND expires_at<?", (now, device_id, now))
c.execute("UPDATE xposed_commands SET status='uncertain',finished_at=?,result=? WHERE device_id=? AND status='sent' AND sent_at<?",
(now, '{"message":"执行超时,需核对设备现场;未自动重发"}', device_id, now-180))
if c.execute("SELECT 1 FROM xposed_commands WHERE device_id=? AND status='sent'", (device_id,)).fetchone():
return None
row = c.execute("SELECT * FROM xposed_commands WHERE device_id=? AND status='queued' AND not_before<=? ORDER BY not_before,created_at LIMIT 1", (device_id, now)).fetchone()
if not row:
return None
payload = json.loads(row["payload"])
if row["action"] == "apply_source":
c.execute("UPDATE xposed_devices SET config=?, revision=revision+1 WHERE id=?", (json.dumps(payload), device_id))
elif row["action"] == "audio":
device = c.execute("SELECT config FROM xposed_devices WHERE id=?", (device_id,)).fetchone()
config = json.loads(device["config"])
config["audio"] = payload["enabled"]
c.execute("UPDATE xposed_devices SET config=?,revision=revision+1 WHERE id=?", (json.dumps(config), device_id))
device = c.execute("SELECT config,revision FROM xposed_devices WHERE id=?", (device_id,)).fetchone()
c.execute("UPDATE xposed_commands SET status='sent',sent_at=? WHERE id=? AND status='queued'", (now, row["id"]))
return {"type": "command", "id": row["id"], "action": row["action"], "payload": payload,
"config": json.loads(device["config"]), "revision": device["revision"], "expires_at": row["expires_at"]}
def heartbeat(device_id: str, data: dict):
allowed = {"model", "app_version", "accessibility", "page", "package", "automation", "media", "battery", "temperature", "message", "revision", "uptime", "screenshot_at", "source_guard"}
telemetry = {k: v for k, v in data.items() if k in allowed}
encoded = json.dumps(telemetry, ensure_ascii=False)
if len(encoded) > 32000:
raise ValueError("heartbeat too large")
with store() as c:
c.execute("UPDATE xposed_devices SET telemetry=?,last_seen=? WHERE id=?", (encoded, time.time(), device_id))
def acknowledge(device_id: str, data: dict):
result = {"message": str(data.get("message", ""))[:500], "page": str(data.get("page", ""))[:40]}
# Don't store screenshots or stream credentials in the command history.
status = data.get("status") if data.get("status") in {"succeeded", "failed", "uncertain"} else "failed"
with store() as c:
row = c.execute("SELECT status FROM xposed_commands WHERE id=? AND device_id=?", (data.get("id"), device_id)).fetchone()
if not row or row["status"] not in {"sent", "uncertain"}:
return
c.execute("UPDATE xposed_commands SET status=?,result=?,finished_at=? WHERE id=? AND device_id=?",
(status, json.dumps(result, ensure_ascii=False), time.time(), data.get("id"), device_id))
image = data.get("screenshot", "")
if isinstance(image, str) and len(image) < 1800000 and image:
try:
raw = base64.b64decode(image, validate=True)
if raw.startswith(b"\xff\xd8"):
c.execute("UPDATE xposed_devices SET screenshot=? WHERE id=?", (image, device_id))
except ValueError:
pass
@router.websocket("/device/ws")
async def device_socket(ws: WebSocket):
device_id = ws.headers.get("x-device-id", "")
try:
await asyncio.to_thread(authenticate, device_id, ws.headers.get("authorization", "").removeprefix("Bearer "))
except HTTPException:
await ws.close(code=4401)
return
await ws.accept()
with store() as c:
c.execute("UPDATE xposed_devices SET last_seen=? WHERE id=?", (time.time(), device_id))
previous = _clients.get(device_id)
_clients[device_id] = ws
if previous:
await previous.close(code=4000)
await ws.send_json({"type": "connected", "server_time": time.time()})
async def reader():
while True:
data = json.loads(await ws.receive_text())
if not isinstance(data, dict):
raise ValueError("invalid message")
if data.get("type") == "heartbeat":
await asyncio.to_thread(heartbeat, device_id, data.get("data", {}))
elif data.get("type") == "ack":
await asyncio.to_thread(acknowledge, device_id, data)
await ws.send_json({"type": "ack_received", "id": data.get("id")})
async def writer():
while True:
# Re-check revocation, including after API process restart.
with store() as c:
row = c.execute("SELECT revoked,last_seen FROM xposed_devices WHERE id=?", (device_id,)).fetchone()
if not row or row["revoked"] or (row["last_seen"] and time.time()-row["last_seen"] > 60):
await ws.close(code=4001)
return
command = await asyncio.to_thread(next_command, device_id)
if command:
await ws.send_json(command)
await asyncio.sleep(1)
tasks = [asyncio.create_task(reader()), asyncio.create_task(writer())]
try:
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
for task in done:
task.result()
except (WebSocketDisconnect, RuntimeError, ValueError):
pass
finally:
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
if _clients.get(device_id) is ws:
_clients.pop(device_id, None)

View File

@ -0,0 +1,156 @@
import time
import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from app import xposed_control as control
from app.session_auth import SESSION_COOKIE, SessionAuthMiddleware, create_session_token
@pytest.fixture()
def client(temp_db):
app = FastAPI()
app.include_router(control.router)
app.add_middleware(SessionAuthMiddleware)
with TestClient(app) as client:
client.cookies.set(SESSION_COOKIE, create_session_token("test-admin"))
yield client
control._clients.clear()
def paired(client):
code = client.post("/api/xposed/pair-codes", json={"name": "Test phone"}).json()["code"]
response = client.post("/api/xposed/device/enroll", json={"code": code, "model": "test"})
assert response.status_code == 200
return code, response.json()
def queue(client, device, action, payload=None, when=0, request_id=None):
body = {"action": action, "payload": payload or {}, "not_before": when}
if request_id:
body["request_id"] = request_id
return client.post(f"/api/xposed/devices/{device['device_id']}/commands", json=body)
def test_pairing_is_one_use_and_device_credentials_are_not_exposed(client):
code, device = paired(client)
assert client.post("/api/xposed/device/enroll", json={"code": code}).status_code == 401
listing = client.get("/api/xposed/devices")
assert "token_hash" not in listing.text and device["token"] not in listing.text
client.cookies.clear()
assert client.get("/api/xposed/devices", headers={"Authorization": "Bearer " + device["token"]}).status_code == 401
with pytest.raises(Exception):
control.authenticate(device["device_id"], "wrong-token")
def test_readonly_cannot_pair_or_send_commands(client):
_, device = paired(client)
client.cookies.set(SESSION_COOKIE, create_session_token("reader", role="readonly"))
assert client.get("/api/xposed/devices").status_code == 200
assert client.post("/api/xposed/pair-codes", json={"name": "bad"}).status_code == 403
assert queue(client, device, "open_app").status_code == 403
def test_queue_deduplicates_and_never_replays_sent_ui_action(client):
_, device = paired(client)
config = {"platform": "tiktok", "source": "375743009479"}
first = queue(client, device, "apply_source", config, request_id="stable-request-id")
assert first.status_code == 200
assert queue(client, device, "apply_source", config, request_id="stable-request-id").json()["duplicate"]
command = control.next_command(device["device_id"])
assert command["config"]["source"] == "https://live.douyin.com/375743009479"
assert control.next_command(device["device_id"]) is None
control.acknowledge(device["device_id"], {"id": command["id"], "status": "succeeded", "message": "applied"})
assert control.next_command(device["device_id"]) is None
assert len(client.get(f"/api/xposed/devices/{device['device_id']}/commands").json()["commands"]) == 1
def test_expired_command_not_delivered_and_schedule_does_not_apply_early(client):
_, device = paired(client)
queue(client, device, "apply_source", {"platform": "youtube", "source": "375743009479"})
cmd = control.next_command(device["device_id"])
control.acknowledge(device["device_id"], {"id": cmd["id"], "status": "succeeded"})
queue(client, device, "start_live", when=time.time()+3600)
assert control.next_command(device["device_id"]) is None
queue(client, device, "open_app", request_id="expired-command")
with control.store() as c:
c.execute("UPDATE xposed_commands SET expires_at=? WHERE id='expired-command'", (time.time()-1,))
assert control.next_command(device["device_id"]) is None
statuses = {c["id"]: c["status"] for c in client.get(f"/api/xposed/devices/{device['device_id']}/commands").json()["commands"]}
assert statuses["expired-command"] == "expired"
def test_device_cannot_ack_another_devices_command_and_revocation_invalidates_token(client):
_, a = paired(client)
_, b = paired(client)
queue(client, a, "apply_source", {"platform": "tiktok", "source": "375743009479"}, request_id="device-a-command")
control.next_command(a["device_id"])
control.acknowledge(b["device_id"], {"id": "device-a-command", "status": "succeeded"})
assert client.get(f"/api/xposed/devices/{a['device_id']}/commands").json()["commands"][0]["status"] == "sent"
assert client.delete(f"/api/xposed/devices/{a['device_id']}").status_code == 200
with pytest.raises(Exception):
control.authenticate(a["device_id"], a["token"])
def test_source_validation_prevents_arbitrary_server_fetch_and_shell_commands(client):
_, d = paired(client)
for source in ("http://127.0.0.1/admin", "https://live.douyin.com.evil.example/123456", "file:///etc/passwd"):
assert queue(client, d, "apply_source", {"platform": "youtube", "source": source}).status_code == 422
assert queue(client, d, "shell", {"cmd": "id"}).status_code == 422
def test_websocket_dispatch_and_ack_with_device_only_credentials(client):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "youtube", "source": "375743009479"})
client.cookies.clear()
headers = {"X-Device-ID": d["device_id"], "Authorization": "Bearer " + d["token"]}
with client.websocket_connect("/api/xposed/device/ws", headers=headers) as ws:
assert ws.receive_json()["type"] == "connected"
cmd = ws.receive_json()
assert cmd["action"] == "apply_source"
ws.send_json({"type": "heartbeat", "data": {"page": "PREVIEW", "model": "test", "media": {"active": True}}})
ws.send_json({"type": "ack", "id": cmd["id"], "status": "succeeded", "message": "ok"})
assert ws.receive_json()["type"] == "ack_received"
# A following command is only sent after the acknowledgement is persisted.
client.cookies.set(SESSION_COOKIE, create_session_token("test-admin"))
queue(client, d, "open_app")
assert ws.receive_json()["action"] == "open_app"
def test_sent_timeout_is_uncertain_and_late_ack_can_reconcile(client):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "youtube", "source": "375743009479"}, request_id="timeout-command")
control.next_command(d["device_id"])
with control.store() as c:
c.execute("UPDATE xposed_commands SET sent_at=? WHERE id=?", (time.time()-181, "timeout-command"))
assert control.next_command(d["device_id"]) is None
history_url = f"/api/xposed/devices/{d['device_id']}/commands"
assert client.get(history_url).json()["commands"][0]["status"] == "uncertain"
control.acknowledge(d["device_id"], {"id": "timeout-command", "status": "succeeded"})
assert client.get(history_url).json()["commands"][0]["status"] == "succeeded"
assert control.next_command(d["device_id"]) is None
def test_source_endpoint_uses_only_device_assignment_and_keeps_site_cookie_private(client, monkeypatch):
_, d = paired(client)
queue(client, d, "apply_source", {"platform": "tiktok", "source": "375743009479"})
control.next_command(d["device_id"])
control._source_cache.clear()
calls = []
async def check_room(source, *, cookie, proxy):
calls.append((source, cookie, proxy))
return {"ok": True, "is_live": True, "stream_candidates": [{"url": "https://media.example/live.flv"}]}
monkeypatch.setattr(control.db, "get_settings_map", lambda: {"dy_cookie": "private-site-cookie", "http_proxy": "http://proxy.example:8080"})
monkeypatch.setattr(control.douyin, "check_room", check_room)
client.cookies.clear()
headers = {"X-Device-ID": d["device_id"], "Authorization": "Bearer " + d["token"]}
response = client.get("/api/xposed/device/source?source=https://evil.example", headers=headers)
assert response.status_code == 200
assert response.json()["source"] == "https://live.douyin.com/375743009479"
assert calls == [("https://live.douyin.com/375743009479", "private-site-cookie", "http://proxy.example:8080")]
assert "private-site-cookie" not in response.text and "proxy.example" not in response.text
assert client.get("/api/xposed/device/source").status_code == 401
control._source_cache.clear()

View File

@ -0,0 +1,33 @@
import asyncio
from unittest.mock import AsyncMock, patch
import pytest
from app import xposed_control as x
@pytest.mark.parametrize("result,expected", [
({"ok": True, "status_code": 2}, "live"),
({"ok": True, "status_code": 4}, "ended"),
({"ok": False, "is_live": False, "status": "error", "risk": True}, "unknown"),
({"ok": True, "is_live": False}, "unknown"),
({"ok": True, "status_code": 0}, "unknown"),
])
def test_source_status_requires_explicit_ended_room(result, expected):
x._source_status_cache.clear()
x._source_status_locks.clear()
device = {"config": '{"source":"https://live.douyin.com/375743009479"}', "revision": 9}
with patch.object(x, "device_auth", return_value=device), \
patch.object(x.db, "get_settings_map", return_value={}), \
patch.object(x.douyin, "check_room", new=AsyncMock(return_value=result)):
reply = asyncio.run(x.device_source_status(None))
assert reply["state"] == expected
assert reply["revision"] == 9
assert reply["source"] == "https://live.douyin.com/375743009479"
assert reply["checked_at"] > 0
def test_device_status_is_exempt_from_site_session_only():
from app import auth, session_auth
for module in [auth, session_auth]:
values = [v for v in vars(module).values() if isinstance(v, (set, list, tuple))]
assert any("/api/xposed/device/source-status" in v for v in values)

58
docs/XPOSED_CONTROL.md Normal file
View File

@ -0,0 +1,58 @@
# Xposed 直播控制台
## 本次交付与验收状态(2026-10-29)
- 已部署到 `https://dylive.nomadro.com/xposed`,导航位于“抖音 → 直播间”右侧。公网登录、设备列表、上游列表、APK 下载及未登录访问拦截均已验证。
- LiveCam `2.8.0 / 276` 已构建并安装到测试手机,LiveCam 无障碍服务已绑定。Android 单元测试、Debug APK 构建、Lint 均通过;新增后端控制测试 9 项通过;前端生产构建通过。
- 本轮 USB 真机已完成配对,网站设备名 `USB test phone`。真实心跳、源分配、截图、两平台预览及实际开播/结束通过;TikTok 47.5.3、YouTube 21.43.523 均收到 LIVE / ENDED 回执。重复开播保护、暂停/恢复、关闭后切换平台并回归 TikTok 已执行。
- TikTok native 音频替换计数增长,YouTube Java PCM 消费超过 381 万字节;这些是注入链路证据,独立观众端听音、画质、延迟及长时间稳定性仍待验收。Android 单元测试现为 26 项通过。
- 原测试房间 `375743009479` 在 TikTok 测试时可用,YouTube 测试时已暂不可解析;后续选用站内在线源 `104107619390` 完成两平台交叉回归。
- 平台自动化驱动独立维护;TikTok 的版本资源 ID、Surface 重绑、手势兜底不作用于 YouTube。网站继续使用通用设备协议。
- 服务器切换前备份位于 `/opt/douyinweb-xposed-backup-20261029-113333`,包含被替换文件、原前端构建与数据库一致性快照。既有监控和 TikTok/YouTube 业务改动予以保留。
- 全量旧后端测试未全部通过:已观察到 `test_resolve_off_by_default`、`test_pick_soft_assign_when_quota_full` 失败;新增控制模块测试独立通过,不能据此宣称整个项目测试全绿。
真机验收顺序:配对与心跳 → 分配上游 → 打开目标 App → 预览检查视频/音频 → 截图及回执 → 实际开播与独立观众端核对 → 结束直播 → 断网重连与长时间运行。分别记录 TikTok、YouTube 的 App 版本及结果。
入口:抖音 → 直播间右侧 **Xposed**(`/xposed`)。服务端使用独立 `xposed_*` 表,不更改原监控和 YouTube/TikTok 上传数据。
## 首次连接
1. 以管理员登录网站,在 Xposed 页面下载 LiveCam APK,安装到已配置 Xposed/LSPosed 的 Android 真机。
2. 模块作用域选择目标 TikTok 或 YouTube 和 LiveCam。安装/升级后重启目标 App 以重新加载 Hook。
3. 网站填写设备名并生成配对码;打开手机 LiveCam → “Xposed 直播控制台”,填写 HTTPS 站点地址和配对码,配对连接。
4. 启用 LiveCam 无障碍服务,允许通知及设备厂商要求的后台运行权限。首次登录目标账号、直播资格与直播选项由操作者核对。
5. 网站选中在线设备,选择 TikTok 或 YouTube,选择监控上游源或输入 `https://live.douyin.com/房间号`,点击“应用到手机”。
6. 点击“打开应用”“进入预览”,观察状态、截图和媒体信息。自动开播会等待预览、持续视频输出与音频注入活动;提交一次后等待结果,不自动重复点击。
配对码有效十分钟且只能使用一次。手机保存设备专用凭证,不保存网站管理员密码;凭证用 Android Keystore 加密。手机主动建立 WSS 连接,不需要公网 ADB。关闭控制连接时,现有媒体和直播保持原状态。
## 操作与回执
- 可分配/切换上游、配置素材音频、旋转/镜像、打开/关闭 App、进入预览、自动开播、结束直播、暂停/恢复媒体。
- 截图按需获取;开启“点击接管”后,点击截图可操作当前配置的目标 App,操作后更新截图。
- 开播/结束支持一次性排期,界面时间输入使用当前浏览器时区,记录按北京时间显示;到点后两分钟未执行会过期。
- 每设备串行执行。网站保存排队/发送/完成状态;手机在执行前持久化命令标识、保存完成回执,并在重连时重传未确认回执。
- 已发送但结果未知的操作标记“待核对”,不会自动重放 UI 动作。取消只对尚未开始的排队操作有效。
- 撤销设备立即断开其控制连接,凭证失效;重新接入需要新配对码。撤销本身不代替结束直播。
## 上游与媒体
网站提供监控房间列表,按站点 Cookie/代理解析当前 FLV/HLS 候选地址,设备只获取当前分配源。播放地址短缓存,断流时重新请求;站点 Cookie 不传给宿主 App。
手机在现有 Media3 链路内硬件解码,沿用 TikTok 的方向与 ByteAudio/native 路径,以及 YouTube 的相机格式与 PCM 适配。平台专有媒体策略保持隔离。一台手机同一时刻控制一个平台;同时开播使用不同设备。切换平台前先结束并关闭原 App。
## 当前边界
- 自动操作以当前 App 中英文可访问控件为依据。未知页面、账号验证和直播资格问题停止自动操作,支持截图接管;其它语言/版本需要单独验收。
- “直播中”表示 App 页面强证据,不能替代独立观众端画质、声音、延迟和平台公开在播验证。
- 没有实现自动填充身份验证、验证码、平台限制绕过或无人值守登录。
- Android 11+ 支持无障碍截图;Android 9/10 仍可执行基础操作。后台启动/重启恢复依赖手机系统的后台权限,Root 用于明确目标包名的启动/关闭兜底。
- 长时间热稳定、App 升级回归、多设备并行和网络故障恢复需要在实际机型上验收,不能仅凭 API 或 APK 构建通过认定完成。
## 部署与维护
`scripts/deploy_xposed_control.py` 使用 `DY_DEPLOY_HOST / DY_DEPLOY_USER / DY_DEPLOY_PASSWORD` 环境变量。脚本基于服务器现有代码进行定点补丁,在独立目录构建服务器前端,构建通过后才切换;上线前备份原代码、原 `.next` 和 SQLite 一致性快照。
APK 发布到后端 `settings.data_dir/xposed/livecam.apk`,管理员登录后从 `/api/xposed/apk` 下载。只读用户可看状态和截图,不能生成配对码或下发命令。
验证命令:`python -m pytest tests/test_xposed_control.py -q`;前端 `npm run build`;LiveCam `gradlew :app:testDebugUnitTest :app:assembleDebug :app:lintDebug`。

View File

@ -0,0 +1,175 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import { Shell } from "@/components/Shell";
import { useToast } from "@/components/Toast";
import { useConfirm } from "@/components/ConfirmDialog";
import { fetchJson, fmtTs } from "@/lib/api";
type Config = { platform?: string; source?: string; audio?: boolean; rotation?: number; mirror?: boolean };
type Device = { id: string; name: string; online: boolean; revoked: number; last_seen: number; revision: number; config: Config; telemetry: Record<string, any> };
type Source = { id: string; url: string; name: string; room_id: string; status: string };
type Command = { id: string; action: string; status: string; created_at: number; not_before: number; result: { message?: string } };
const ACTIONS: Record<string, string> = { apply_source: "分配上游", open_app: "打开应用", close_app: "关闭应用", prepare: "进入预览", start_live: "自动开播", stop_live: "结束直播", pause_media: "暂停媒体", resume_media: "恢复媒体", audio: "素材音频", snapshot: "刷新截图", tap: "远程点击", back: "返回" };
const STATES: Record<string, string> = { queued: "排队", sent: "执行中", succeeded: "成功", failed: "失败", uncertain: "待核对", cancelled: "已取消", expired: "已过期" };
const PAGES: Record<string, string> = { LIVE: "直播中", PREVIEW: "直播预览", HOME: "主页", NEEDS_ATTENTION: "需要接管", OTHER: "待识别", DISCONNECTED: "无障碍未连接" };
const inputClass = "mt-1 w-full rounded-xl border border-white/10 bg-slate-950 px-3 py-2.5 text-sm text-slate-100";
export default function XposedPage() {
const toast = useToast();
const confirm = useConfirm();
const [devices, setDevices] = useState<Device[]>([]);
const [sources, setSources] = useState<Source[]>([]);
const [selected, setSelected] = useState("");
const selectedRef = useRef("");
const [canWrite, setCanWrite] = useState(false);
const [commands, setCommands] = useState<Command[]>([]);
const [error, setError] = useState("");
const [busy, setBusy] = useState(false);
const [pairName, setPairName] = useState("直播手机 1");
const [pairCode, setPairCode] = useState<{ code: string; expires_at: number } | null>(null);
const [config, setConfig] = useState<Config>({ platform: "tiktok", source: "https://live.douyin.com/375743009479", audio: true, rotation: 0, mirror: false });
const [filter, setFilter] = useState("");
const [schedule, setSchedule] = useState("");
const [image, setImage] = useState("");
const [manual, setManual] = useState(false);
const imageRef = useRef("");
const lastImage = useRef("");
const selectedDevice = devices.find(d => d.id === selected);
const load = useCallback(async () => {
try {
const response = await fetchJson("/api/xposed/devices");
setDevices(response.devices || []);
setCanWrite(response.can_write === true);
const id = selectedRef.current;
if (id) {
const history = await fetchJson(`/api/xposed/devices/${id}/commands`);
setCommands(history.commands || []);
const snapshot = (history.commands || []).find((c: Command) => ["snapshot", "tap", "back"].includes(c.action) && c.status === "succeeded");
if (snapshot && snapshot.id !== lastImage.current) {
lastImage.current = snapshot.id;
const result = await fetch(`/api/xposed/devices/${id}/screenshot`, { credentials: "include", cache: "no-store" });
if (result.ok && selectedRef.current === id) {
const url = URL.createObjectURL(await result.blob());
if (imageRef.current) URL.revokeObjectURL(imageRef.current);
imageRef.current = url;
setImage(url);
}
}
}
setError("");
} catch (e) { setError((e as Error).message); }
}, []);
useEffect(() => {
let alive = true;
let timer: ReturnType<typeof setTimeout>;
const poll = async () => {
if (!document.hidden) await load();
if (alive) timer = setTimeout(poll, 2500);
};
void poll();
void fetchJson("/api/xposed/sources").then(r => setSources(r.sources || [])).catch(e => setError(e.message));
return () => { alive = false; clearTimeout(timer); if (imageRef.current) URL.revokeObjectURL(imageRef.current); };
}, [load]);
function choose(device: Device) {
setSelected(device.id); selectedRef.current = device.id;
setConfig({ platform: "tiktok", audio: true, rotation: 0, mirror: false, ...device.config });
setCommands([]); setImage(""); setManual(false); lastImage.current = "";
if (imageRef.current) URL.revokeObjectURL(imageRef.current);
imageRef.current = "";
void load();
}
async function send(action: string, payload: Record<string, any> = {}, scheduled = false) {
if (!selected || busy) return;
setBusy(true);
try {
const when = scheduled && schedule ? new Date(schedule).getTime() / 1000 : 0;
if (scheduled && (!Number.isFinite(when) || when <= Date.now() / 1000)) throw new Error("请选择未来的排期时间");
await fetchJson(`/api/xposed/devices/${selected}/commands`, { method: "POST", body: JSON.stringify({ action, payload, not_before: when, request_id: crypto.randomUUID() }) });
toast.push(scheduled ? "操作已排期" : "操作已提交,等待设备回执", "ok");
await load();
} catch (e) { toast.push((e as Error).message, "err"); }
finally { setBusy(false); }
}
async function createPairCode() {
setBusy(true);
try { setPairCode(await fetchJson("/api/xposed/pair-codes", { method: "POST", body: JSON.stringify({ name: pairName }) })); }
catch (e) { toast.push((e as Error).message, "err"); }
finally { setBusy(false); }
}
const t = selectedDevice?.telemetry || {};
const media = t.media || {};
const visibleSources = sources.filter(s => `${s.name} ${s.room_id}`.toLowerCase().includes(filter.toLowerCase()));
const pending = commands.filter(c => ["queued", "sent"].includes(c.status)).length;
const controlsDisabled = busy || !canWrite || !selectedDevice?.online || !!selectedDevice?.revoked;
return <Shell>
<div className="mb-6 flex flex-wrap items-start justify-between gap-4">
<div><h1 className="font-display text-2xl font-semibold text-white">📱 Xposed 直播控制台</h1><p className="mt-2 text-sm text-slate-400">抖音上游源 → LiveCam → TikTok / YouTube · 手机主动连接,操作实时回执</p></div>
<div className="rounded-full border border-teal-400/20 bg-teal-400/5 px-4 py-2 text-sm text-teal-200">{devices.filter(d => d.online).length} 在线 / {devices.filter(d => !d.revoked).length} 设备</div>
</div>
{error && <div role="alert" className="mb-4 rounded-xl bg-rose-500/10 p-3 text-sm text-rose-300">{error}</div>}
<div className="grid gap-5 xl:grid-cols-[280px_1fr]">
<aside className="space-y-4">
<section className="rounded-2xl border border-white/10 bg-black/20 p-4">
<h2 className="mb-3 font-medium text-slate-200">设备</h2>
{!devices.length && <p className="text-sm leading-6 text-slate-400">先生成配对码,再在手机 LiveCam 中填写站点地址和配对码。</p>}
<div className="space-y-2">{devices.map(d => <button key={d.id} onClick={() => choose(d)} className={`w-full rounded-xl border p-3 text-left ${selected === d.id ? "border-teal-400/40 bg-teal-500/10" : "border-white/5 bg-white/5"}`}>
<div className="flex items-center justify-between gap-2"><span className="truncate text-sm text-white">{d.name}</span><span className={`text-xs ${d.online ? "text-emerald-300" : "text-slate-500"}`}>{d.revoked ? "已撤销" : d.online ? "在线" : "离线"}</span></div>
<div className="mt-2 text-xs text-slate-400">{d.telemetry.model || "Android"} · {d.config.platform || "未分配"}</div>
<div className="mt-1 text-xs text-slate-500">{d.last_seen ? fmtTs(d.last_seen) : "尚未连接"}</div>
</button>)}</div>
</section>
<section className="rounded-2xl border border-white/10 bg-black/20 p-4">
<h2 className="font-medium">连接新设备</h2>
<label className="mt-3 block text-xs text-slate-400">设备名称<input className={inputClass} value={pairName} maxLength={80} onChange={e => setPairName(e.target.value)} /></label>
<button disabled={!canWrite || busy || !pairName.trim()} onClick={createPairCode} className="mt-3 w-full rounded-xl bg-teal-500 px-3 py-2 text-sm font-medium text-slate-950 disabled:opacity-40">生成一次性配对码</button>
{pairCode && <div className="mt-4 rounded-xl bg-slate-950 p-3"><div className="text-center font-mono text-lg tracking-widest text-teal-200 select-all">{pairCode.code}</div><p className="mt-2 text-xs text-slate-400">有效至 {fmtTs(pairCode.expires_at)} · 使用一次失效</p></div>}
<a href="/api/xposed/apk" className="mt-3 block text-sm text-teal-300 underline">下载 LiveCam APK</a>
<p className="mt-3 break-all text-xs leading-5 text-slate-500">手机站点地址:{typeof window !== "undefined" ? window.location.origin : "https://dylive.nomadro.com"}<br />安装后启用 Xposed 作用域与 LiveCam 无障碍服务,再连接控制台。</p>
</section>
</aside>
<main className="min-w-0 space-y-5">
{!selectedDevice ? <div className="rounded-2xl border border-dashed border-white/15 p-12 text-center text-slate-400">选择一台设备,分配平台和上游直播源。</div> : <>
<div className="grid gap-3 sm:grid-cols-4">{[["应用页面", t.accessibility ? PAGES[t.page] || t.page || "待识别" : "无障碍未连接"], ["媒体", media.playing ? "播放中" : media.active ? "正在连接" : "未接入"], ["电池 / 温度", `${t.battery ?? "—"}% / ${t.temperature ?? "—"}°C`], ["任务", `${pending} 个待完成`]].map(([label, value]) => <div key={label} className="rounded-xl border border-white/10 bg-white/5 p-4"><div className="text-xs text-slate-500">{label}</div><div className="mt-2 truncate text-sm font-medium text-slate-100">{value}</div></div>)}</div>
<section className="rounded-2xl border border-white/10 bg-black/20 p-5">
<div className="mb-4 flex justify-between"><h2 className="font-medium text-white">平台与上游源</h2><span className="text-xs text-slate-500">配置 v{selectedDevice.revision} · 手机已应用 v{t.revision ?? "—"}</span></div>
<div className="grid gap-4 md:grid-cols-2">
<label className="text-xs text-slate-400">目标平台<select className={inputClass} value={config.platform} onChange={e => setConfig({ ...config, platform: e.target.value })}><option value="tiktok">TikTok</option><option value="youtube">YouTube</option></select></label>
<label className="text-xs text-slate-400">上游房间地址<input className={inputClass} value={config.source || ""} placeholder="https://live.douyin.com/375743009479" onChange={e => setConfig({ ...config, source: e.target.value })} /></label>
<label className="text-xs text-slate-400">搜索监控源<input className={inputClass} value={filter} placeholder="主播名称或房间号" onChange={e => setFilter(e.target.value)} /></label>
<label className="text-xs text-slate-400">从监控列表选源<select className={inputClass} value={sources.some(s => s.url === config.source) ? config.source : ""} onChange={e => e.target.value && setConfig({ ...config, source: e.target.value })}><option value="">请选择({visibleSources.length} 个)</option>{visibleSources.map(s => <option key={s.id} value={s.url}>{s.status === "live" ? "🔴" : "⚪"} {s.name} · {s.room_id}</option>)}</select></label>
</div>
<div className="mt-4 flex flex-wrap items-center gap-5 text-sm text-slate-300">
<label className="flex items-center gap-2"><input type="checkbox" checked={config.audio !== false} onChange={e => setConfig({ ...config, audio: e.target.checked })} />素材音频</label>
<label className="flex items-center gap-2"><input type="checkbox" checked={config.mirror === true} onChange={e => setConfig({ ...config, mirror: e.target.checked })} />镜像</label>
<label>额外旋转 <select className="rounded-lg bg-slate-950 p-2" value={config.rotation || 0} onChange={e => setConfig({ ...config, rotation: Number(e.target.value) })}>{[0,90,180,270].map(v => <option key={v} value={v}>{v}°</option>)}</select></label>
<button disabled={controlsDisabled || !config.source} onClick={() => send("apply_source", config)} className="ml-auto rounded-xl bg-teal-500 px-5 py-2.5 font-medium text-slate-950 disabled:opacity-40">应用到手机</button>
</div>
<p className="mt-3 text-xs text-slate-500">应用配置会切换媒体源;切换目标平台前应先结束当前直播。首次使用请在手机确认登录账号、频道和直播资格。</p>
</section>
<section className="rounded-2xl border border-white/10 bg-black/20 p-5">
<h2 className="mb-4 font-medium text-white">直播操作</h2>
<div className="flex flex-wrap gap-2">{["open_app","prepare","start_live","stop_live","snapshot","pause_media","resume_media","back","close_app"].map(action => <button disabled={controlsDisabled || !selectedDevice.config.platform} key={action} onClick={() => send(action)} className={`rounded-xl border px-4 py-2.5 text-sm disabled:opacity-35 ${action === "start_live" ? "border-emerald-400/30 bg-emerald-500/15 text-emerald-200" : action === "stop_live" ? "border-rose-400/30 bg-rose-500/15 text-rose-200" : "border-white/10 bg-white/5 text-slate-200"}`}>{ACTIONS[action]}</button>)}</div>
<div className="mt-4 flex flex-wrap items-end gap-3 border-t border-white/5 pt-4"><label className="text-xs text-slate-400">定时操作(本机时区)<input type="datetime-local" className={inputClass} value={schedule} onChange={e => setSchedule(e.target.value)} /></label><button disabled={!canWrite || busy || !schedule || !selectedDevice.config.platform} onClick={() => send("start_live", {}, true)} className="rounded-xl border border-white/10 px-4 py-2.5 text-sm disabled:opacity-35">定时开播</button><button disabled={!canWrite || busy || !schedule || !selectedDevice.config.platform} onClick={() => send("stop_live", {}, true)} className="rounded-xl border border-white/10 px-4 py-2.5 text-sm disabled:opacity-35">定时结束</button></div>
<p className="mt-3 text-xs leading-5 text-slate-500">自动开播先进入预览并检查媒体;未知页面或账号验证会停下等待接管。排期到点后两分钟未执行即过期。</p>
{t.message && <p className="mt-3 rounded-lg bg-white/5 p-3 text-sm text-amber-200">{t.message}</p>}
</section>
<div className="grid gap-5 lg:grid-cols-[minmax(240px,340px)_1fr]">
<section className="rounded-2xl border border-white/10 bg-black/20 p-4"><div className="mb-3 flex items-center justify-between"><h2 className="font-medium">手机画面</h2><label className="flex items-center gap-2 text-xs text-slate-400"><input type="checkbox" disabled={controlsDisabled} checked={manual} onChange={e => setManual(e.target.checked)} />点击接管</label></div>
{image ? <img src={image} alt="手机最近一次截图" className={`mx-auto max-h-[620px] w-auto max-w-full rounded-lg ${manual ? "cursor-crosshair" : ""}`} onClick={e => { if (!manual || controlsDisabled) return; const rect = e.currentTarget.getBoundingClientRect(); void send("tap", { x: (e.clientX-rect.left)/rect.width, y: (e.clientY-rect.top)/rect.height }); }} /> : <div className="flex h-64 items-center justify-center rounded-lg bg-slate-950 px-5 text-center text-sm text-slate-500">点击“刷新截图”查看手机。需要启用 LiveCam 无障碍服务。</div>}
<p className="mt-3 text-xs text-slate-500">截图按需获取;开启点击接管后可操作当前直播 App。</p>
</section>
<section className="min-w-0 rounded-2xl border border-white/10 bg-black/20 p-4"><h2 className="mb-3 font-medium">执行记录</h2><div className="max-h-[670px] space-y-2 overflow-auto">{!commands.length && <p className="text-sm text-slate-500">暂无操作</p>}{commands.map(c => <div key={c.id} className="rounded-xl border border-white/5 bg-white/[0.025] p-3"><div className="flex items-center justify-between gap-3"><span className="text-sm text-slate-200">{ACTIONS[c.action] || c.action}</span><span className={`text-xs ${c.status === "succeeded" ? "text-emerald-300" : ["failed","uncertain"].includes(c.status) ? "text-amber-300" : "text-slate-400"}`}>{STATES[c.status] || c.status}</span></div><div className="mt-1 text-xs text-slate-500">{fmtTs(c.not_before)} {c.not_before > c.created_at + 5 ? "· 排期" : ""}</div>{c.result.message && <p className="mt-2 break-words text-xs text-slate-400">{c.result.message}</p>}{c.status === "queued" && canWrite && <button onClick={async () => { try { await fetchJson(`/api/xposed/devices/${selected}/commands/${c.id}`, { method: "DELETE" }); await load(); } catch(e) { toast.push((e as Error).message,"err"); } }} className="mt-2 text-xs text-rose-300">取消排队</button>}</div>)}</div></section>
</div>
{canWrite && !selectedDevice.revoked && <button className="text-xs text-rose-300/70 underline" onClick={async () => { if (!await confirm({ title: "撤销设备连接", message: "该设备的控制凭证将失效,重新连接需要新的配对码。", destructive: true })) return; try { await fetchJson(`/api/xposed/devices/${selected}`, { method: "DELETE" }); await load(); } catch(e) { toast.push((e as Error).message,"err"); } }}>撤销此设备</button>}
</>}
</main>
</div>
</Shell>;
}

View File

@ -17,6 +17,7 @@ export const MAIN_NAV: NavItem[] = [
export const OVERVIEW_TABS: NavItem[] = [ export const OVERVIEW_TABS: NavItem[] = [
{ href: "/", label: "概览", emoji: "📡" }, { href: "/", label: "概览", emoji: "📡" },
{ href: "/rooms", label: "直播间", emoji: "🏠" }, { href: "/rooms", label: "直播间", emoji: "🏠" },
{ href: "/xposed", label: "Xposed", emoji: "📱" },
{ href: "/slots", label: "时段", emoji: "🕐" }, { href: "/slots", label: "时段", emoji: "🕐" },
{ href: "/sessions", label: "场次", emoji: "🎬" }, { href: "/sessions", label: "场次", emoji: "🎬" },
{ href: "/anchors", label: "主播", emoji: "👤" }, { href: "/anchors", label: "主播", emoji: "👤" },

View File

@ -0,0 +1,130 @@
"""Deploy only Xposed files, preserving remote changes and live runtime data.
Credentials are supplied through DY_DEPLOY_HOST/USER/PASSWORD, never written to code.
Frontend is built in a staging directory and switched only after a successful build.
"""
from __future__ import annotations
import json
import os
from pathlib import Path
import shlex
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(__file__).resolve().parents[1]
REMOTE = "/opt/douyinWEB"
STAMP = time.strftime("%Y%m%d-%H%M%S")
STAGE = f"/opt/douyinweb-xposed-stage-{STAMP}"
BACKUP = f"/opt/douyinweb-xposed-backup-{STAMP}"
def run(client, command, timeout=900):
_, stdout, stderr = client.exec_command(command, timeout=timeout)
# Read stdout/stderr concurrently to avoid a full SSH pipe on a long Next build.
channel = stdout.channel
start = time.monotonic()
while not channel.exit_status_ready() or channel.recv_ready() or channel.recv_stderr_ready():
if channel.recv_ready():
print(channel.recv(32768).decode("utf-8", "replace"), end="", flush=True)
if channel.recv_stderr_ready():
print(channel.recv_stderr(32768).decode("utf-8", "replace"), end="", flush=True)
if time.monotonic()-start > timeout:
raise TimeoutError("Remote command timeout; inspect stage before retrying")
time.sleep(0.15)
code = channel.recv_exit_status()
if code:
raise RuntimeError(f"Remote command exited {code}")
def main():
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(os.environ["DY_DEPLOY_HOST"], username=os.environ.get("DY_DEPLOY_USER", "root"),
password=os.environ["DY_DEPLOY_PASSWORD"], timeout=25, allow_agent=False, look_for_keys=False)
print("Backup:", BACKUP, "Stage:", STAGE, flush=True)
run(client, f"mkdir -p {shlex.quote(STAGE)}/backend/app {shlex.quote(STAGE)}/frontend/src/app/xposed {shlex.quote(STAGE)}/frontend/src/lib {shlex.quote(BACKUP)}")
sftp = client.open_sftp()
# Patch the live versions rather than copying local main/auth/nav files over remote work.
original = {}
for rel in ("backend/app/main.py", "backend/app/session_auth.py", "backend/app/auth.py", "frontend/src/lib/shellNav.ts"):
with sftp.open(f"{REMOTE}/{rel}", "rb") as f:
original[rel] = f.read()
contents = {k: v.decode("utf-8") for k, v in original.items()}
entry = contents["backend/app/main.py"]
if "app.include_router(xposed_router)" not in entry:
marker = 'app = FastAPI(title="Douyin Live Monitor", version="0.2.0", lifespan=lifespan)'
if entry.count(marker) != 1:
raise RuntimeError("Unexpected live FastAPI entrypoint; refusing blind replacement")
contents["backend/app/main.py"] = entry.replace(marker, marker + "\nfrom .xposed_control import router as xposed_router\napp.include_router(xposed_router)", 1)
for rel, marker in (("backend/app/session_auth.py", "_PUBLIC_API_EXACT = {"), ("backend/app/auth.py", "_PUBLIC_PATHS = {")):
if '"/api/xposed/device/enroll"' not in contents[rel]:
if contents[rel].count(marker) != 1:
raise RuntimeError("Unexpected auth middleware")
contents[rel] = contents[rel].replace(marker, marker + '\n "/api/xposed/device/enroll",\n "/api/xposed/device/source",\n "/api/xposed/device/ws",', 1)
nav = contents["frontend/src/lib/shellNav.ts"]
if 'href: "/xposed"' not in nav:
marker = ' { href: "/rooms", label: "直播间", emoji: "🏠" },'
if nav.count(marker) != 1:
raise RuntimeError("Unexpected live navigation")
contents["frontend/src/lib/shellNav.ts"] = nav.replace(marker, marker + '\n { href: "/xposed", label: "Xposed", emoji: "📱" },', 1)
for rel, value in contents.items():
with sftp.open(f"{STAGE}/{rel}", "wb") as f:
f.write(value.encode("utf-8"))
sftp.put(str(ROOT / "backend/app/xposed_control.py"), f"{STAGE}/backend/app/xposed_control.py")
sftp.put(str(ROOT / "frontend/src/app/xposed/page.tsx"), f"{STAGE}/frontend/src/app/xposed/page.tsx")
# Build a copy of the SERVER frontend so unrelated live UI fixes are preserved.
remote_script = f"""
set -eu
cp -a {REMOTE}/frontend/package.json {REMOTE}/frontend/package-lock.json {REMOTE}/frontend/next.config.mjs {REMOTE}/frontend/tsconfig.json {REMOTE}/frontend/tailwind.config.js {REMOTE}/frontend/postcss.config.js {STAGE}/frontend/
cp -a {REMOTE}/frontend/public {STAGE}/frontend/
cp -a {REMOTE}/frontend/src {STAGE}/frontend/server-src
cp -a {STAGE}/frontend/src/app/xposed {STAGE}/frontend/server-src/app/
cp -a {STAGE}/frontend/src/lib/shellNav.ts {STAGE}/frontend/server-src/lib/shellNav.ts
mv {STAGE}/frontend/src {STAGE}/frontend/patch-src
mv {STAGE}/frontend/server-src {STAGE}/frontend/src
ln -s {REMOTE}/frontend/node_modules {STAGE}/frontend/node_modules
cd {STAGE}/frontend
NEXT_TELEMETRY_DISABLED=1 NODE_OPTIONS=--max-old-space-size=1536 npm run build
"""
with sftp.open(f"{STAGE}/build.sh", "w") as f: f.write(remote_script)
sftp.close()
run(client, f"bash {STAGE}/build.sh")
# Exact remote backup of code and a consistent SQLite backup before additive schema writes.
commit_script = f"""
import pathlib, shutil, sqlite3, sys
root=pathlib.Path({REMOTE!r}); stage=pathlib.Path({STAGE!r}); backup=pathlib.Path({BACKUP!r})
sys.path.insert(0,str(root/'backend'))
from app.config import settings
source=sqlite3.connect(str(settings.sqlite_path)); target=sqlite3.connect(str(backup/'monitor.db'))
source.backup(target); target.close(); source.close()
files={list(contents)!r}+['backend/app/xposed_control.py','frontend/src/app/xposed/page.tsx']
for rel in files:
src=root/rel; dst=backup/rel; dst.parent.mkdir(parents=True,exist_ok=True)
if src.exists(): shutil.copy2(src,dst)
src.parent.mkdir(parents=True,exist_ok=True)
shutil.copy2(stage/rel,src.with_name(src.name+'.xposed-new'))
src.with_name(src.name+'.xposed-new').replace(src)
shutil.move(str(root/'frontend/.next'),str(backup/'frontend.next'))
shutil.move(str(stage/'frontend/.next'),str(root/'frontend/.next'))
print('Backups saved; Xposed code installed')
"""
sftp = client.open_sftp()
with sftp.open(f"{STAGE}/commit.py", "w") as f: f.write(commit_script)
sftp.close()
# Python env file is read from backend working directory.
run(client, f"cd {REMOTE}/backend && .venv/bin/python {STAGE}/commit.py")
run(client, f"cd {REMOTE}/backend && .venv/bin/python -m py_compile app/xposed_control.py app/main.py app/session_auth.py app/auth.py")
run(client, "systemctl restart douyinweb-api douyinweb-web && systemctl is-active douyinweb-api douyinweb-web")
client.close()
print("Deployed; validate HTTPS before removing stage/backup.")
if __name__ == "__main__":
main()