Wire Taro social pages to social_svc (Centrifugo + live RTMP), drop multi-channel chat chrome, and add weapp WXSS sanitize/deploy helpers. Co-authored-by: Cursor <cursoragent@cursor.com>
157 lines
4.1 KiB
Python
157 lines
4.1 KiB
Python
"""游民社区原生音视频厅 — SRS RTMP 推流 + HTTP-FLV 拉流 + 房间信令。
|
||
|
||
微信小程序:LivePusher(pushUrl) + LivePlayer(playUrl)
|
||
门户 H5:仍可用 MiroTalk;本模块给 weapp 原生厅发流地址。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import hashlib
|
||
import hmac
|
||
import os
|
||
import re
|
||
import threading
|
||
import time
|
||
from typing import Any
|
||
|
||
from social_svc.config import (
|
||
LIVE_HTTP_PLAY_BASE,
|
||
LIVE_MAX_PEERS,
|
||
LIVE_PEER_TTL_SEC,
|
||
LIVE_RTMP_PUSH_BASE,
|
||
LIVE_STREAM_SECRET,
|
||
)
|
||
|
||
_lock = threading.RLock()
|
||
# room_id -> { peer_id: peer_dict }
|
||
_rooms: dict[str, dict[str, dict[str, Any]]] = {}
|
||
|
||
|
||
def _safe(s: str, n: int = 48) -> str:
|
||
t = re.sub(r"[^a-zA-Z0-9_-]+", "", (s or "").strip())[:n]
|
||
return t or "x"
|
||
|
||
|
||
def _sig(stream: str, exp: int) -> str:
|
||
raw = f"{stream}:{exp}".encode("utf-8")
|
||
return hmac.new(LIVE_STREAM_SECRET.encode("utf-8"), raw, hashlib.sha256).hexdigest()[:16]
|
||
|
||
|
||
def stream_name(room_id: str, peer_id: str) -> str:
|
||
return f"{_safe(room_id, 24)}_{_safe(peer_id, 24)}"
|
||
|
||
|
||
def build_urls(room_id: str, peer_id: str) -> dict[str, str]:
|
||
stream = stream_name(room_id, peer_id)
|
||
exp = int(time.time()) + 3600 * 6
|
||
token = _sig(stream, exp)
|
||
# 微信 LivePusher:RTMP url 勿带 query,否则真机常推流失败→本地黑屏
|
||
push = f"{LIVE_RTMP_PUSH_BASE.rstrip('/')}/{stream}"
|
||
# HTTP-FLV 拉流可带 token(nginx/SRS 忽略未知参数)
|
||
play = f"{LIVE_HTTP_PLAY_BASE.rstrip('/')}/{stream}.flv?e={exp}&k={token}"
|
||
return {"stream": stream, "pushUrl": push, "playUrl": play}
|
||
|
||
|
||
def _purge(room_id: str) -> None:
|
||
now = time.time()
|
||
room = _rooms.get(room_id) or {}
|
||
dead = [pid for pid, p in room.items() if now - float(p.get("seen", 0)) > LIVE_PEER_TTL_SEC]
|
||
for pid in dead:
|
||
room.pop(pid, None)
|
||
if not room:
|
||
_rooms.pop(room_id, None)
|
||
|
||
|
||
def list_peers(room_id: str) -> list[dict[str, Any]]:
|
||
with _lock:
|
||
_purge(room_id)
|
||
room = _rooms.get(room_id) or {}
|
||
return [
|
||
{
|
||
"peerId": p["peerId"],
|
||
"nick": p["nick"],
|
||
"playUrl": p["playUrl"],
|
||
"stream": p["stream"],
|
||
"seen": p["seen"],
|
||
}
|
||
for p in room.values()
|
||
]
|
||
|
||
|
||
def join_room(room_id: str, guest_id: str, nick: str) -> dict[str, Any]:
|
||
rid = _safe(room_id, 40)
|
||
gid = _safe(guest_id, 40)
|
||
name = (nick or "游民").strip()[:32] or "游民"
|
||
with _lock:
|
||
_purge(rid)
|
||
room = _rooms.setdefault(rid, {})
|
||
if gid not in room and len(room) >= LIVE_MAX_PEERS:
|
||
raise ValueError(f"厅已满(最多 {LIVE_MAX_PEERS} 人)")
|
||
urls = build_urls(rid, gid)
|
||
peer = {
|
||
"peerId": gid,
|
||
"nick": name,
|
||
"stream": urls["stream"],
|
||
"pushUrl": urls["pushUrl"],
|
||
"playUrl": urls["playUrl"],
|
||
"seen": time.time(),
|
||
"joinedAt": time.time(),
|
||
}
|
||
room[gid] = peer
|
||
peers = [
|
||
{
|
||
"peerId": p["peerId"],
|
||
"nick": p["nick"],
|
||
"playUrl": p["playUrl"],
|
||
"stream": p["stream"],
|
||
}
|
||
for pid, p in room.items()
|
||
if pid != gid
|
||
]
|
||
return {
|
||
"ok": True,
|
||
"roomId": rid,
|
||
"peerId": gid,
|
||
"nick": name,
|
||
"pushUrl": urls["pushUrl"],
|
||
"playUrl": urls["playUrl"],
|
||
"stream": urls["stream"],
|
||
"peers": peers,
|
||
"maxPeers": LIVE_MAX_PEERS,
|
||
"channelId": f"live-{rid}",
|
||
"engine": "srs-rtmp-flv",
|
||
}
|
||
|
||
|
||
def heartbeat(room_id: str, guest_id: str) -> dict[str, Any]:
|
||
rid = _safe(room_id, 40)
|
||
gid = _safe(guest_id, 40)
|
||
with _lock:
|
||
_purge(rid)
|
||
room = _rooms.get(rid) or {}
|
||
me = room.get(gid)
|
||
if not me:
|
||
raise ValueError("未在厅内,请重新进入")
|
||
me["seen"] = time.time()
|
||
peers = [
|
||
{
|
||
"peerId": p["peerId"],
|
||
"nick": p["nick"],
|
||
"playUrl": p["playUrl"],
|
||
"stream": p["stream"],
|
||
}
|
||
for pid, p in room.items()
|
||
if pid != gid
|
||
]
|
||
return {"ok": True, "roomId": rid, "peers": peers, "peerCount": len(peers) + 1}
|
||
|
||
|
||
def leave_room(room_id: str, guest_id: str) -> dict[str, Any]:
|
||
rid = _safe(room_id, 40)
|
||
gid = _safe(guest_id, 40)
|
||
with _lock:
|
||
room = _rooms.get(rid) or {}
|
||
room.pop(gid, None)
|
||
if not room:
|
||
_rooms.pop(rid, None)
|
||
return {"ok": True, "roomId": rid}
|