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>
442 lines
20 KiB
Python
442 lines
20 KiB
Python
"""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)
|