feat: XLive 直播平台初始版本
多用户网页直播平台:OBS/FFmpeg 鉴权 RTMP 推流到 SRS,HLS 低延迟播放; Fastify 5 + Prisma + PostgreSQL + Redis 后端,Vue 3 前端,Docker Compose 部署。
This commit is contained in:
1 parent
5ef949fe07
commit
463dbb1566
73 files changed
+9593
No files matched your search
@@ -0,0 +1,7 @@
|
||||
node_modules
|
||||
**/node_modules
|
||||
**/dist
|
||||
.git
|
||||
.env
|
||||
coverage
|
||||
uploads/*
|
||||
@@ -0,0 +1,17 @@
|
||||
APP_ENV=development
|
||||
APP_PORT=3000
|
||||
PUBLIC_URL=http://localhost
|
||||
DATABASE_URL=postgresql://xlive:xlive_dev_password@postgres:5432/xlive?schema=public
|
||||
REDIS_URL=redis://redis:6379
|
||||
JWT_SECRET=replace-with-at-least-32-random-characters
|
||||
CONFIG_ENCRYPTION_KEY=replace-with-32-byte-base64-key
|
||||
COOKIE_SECURE=false
|
||||
ADMIN_USERNAME=admin
|
||||
ADMIN_PASSWORD=ChangeMe123!
|
||||
ADMIN_EMAIL=admin@example.com
|
||||
SRS_API_URL=http://srs:1985
|
||||
SRS_HOOK_SECRET=replace-with-a-random-hook-secret
|
||||
RTMP_PUBLIC_URL=rtmp://localhost/live
|
||||
HLS_PUBLIC_URL=http://localhost/live
|
||||
UPLOAD_DIR=/app/uploads
|
||||
LIVE_DIR=/app/live
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
node_modules/
|
||||
dist/
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
uploads/*
|
||||
!uploads/.gitkeep
|
||||
coverage/
|
||||
*.log
|
||||
.idea/
|
||||
.vscode/
|
||||
apps/api/prisma/dev.db
|
||||
infra/nginx/certs/
|
||||
|
||||
# 本地临时文件与数据库备份,绝不提交
|
||||
.tmp-*
|
||||
*.dump
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 itxiaohui
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,210 @@
|
||||
# XLive
|
||||
|
||||
[](LICENSE)
|
||||
[](package.json)
|
||||
[](docker-compose.yml)
|
||||
|
||||
一个可部署的多用户网页直播平台。主播使用 OBS / FFmpeg 通过鉴权 RTMP 推送到 SRS,SRS 输出低延迟 HLS,浏览器通过 hls.js 播放;业务状态由 SRS HTTP Hooks 自动驱动,不依赖主播手动点击「开始直播」。
|
||||
|
||||
**XLive** is a self-hostable multi-user live-streaming platform. Streamers push RTMP (authenticated by stream key) to SRS via OBS/FFmpeg; SRS produces low-latency HLS played back in the browser with hls.js. Room state is fully driven by SRS HTTP Hooks — no manual "go live" needed.
|
||||
|
||||
## ✨ 功能特性
|
||||
|
||||
- 邮箱/手机号注册模式、Argon2id 密码、HttpOnly Cookie Access/Refresh Token、登录失败锁定
|
||||
- 邮箱与短信一次性验证码:5 分钟 TTL、60 秒冷却、IP 限流、Hash 存储、失败次数限制
|
||||
- 用户资料、直播间、公开/私有房间、唯一房间号、分类、搜索、直播记录与可播放回放
|
||||
- OBS Stream Key 显示/复制/立即轮换;数据库中 Hash 鉴权 + AES-256-GCM 加密备份
|
||||
- SRS RTMP 鉴权、HLS 输出、开播/停播/录制 Webhook、自动强制断流、禁播
|
||||
- 实时聊天与画面弹幕,回放时按原直播时间轴同步重放弹幕
|
||||
- Redis ZSET 心跳在线人数,刷新/断网后自动过期;LiveSession 峰值与采样统计
|
||||
- HLS.js 播放、原生 HLS 回退、自动播放降级、断线重连、离线状态
|
||||
- USER / ADMIN / SUPER_ADMIN 后端 RBAC
|
||||
- 管理后台:指标、系统资源、用户、房间、分类、日志、站点/注册/SMTP/SMS 等配置
|
||||
- SMTP 连接验证和真实测试邮件;阿里云 Dysmsapi 真实签名请求与测试短信
|
||||
- 站点名称、Logo、暗色 Logo、Favicon、SEO、备案、页脚动态配置;浅色/深色/跟随系统
|
||||
- requestId、统一错误结构、日志敏感字段脱敏、参数校验、限流
|
||||
- PostgreSQL 迁移、首次超级管理员初始化、Docker Compose、Nginx、Swagger
|
||||
|
||||
## 🏗 技术架构
|
||||
|
||||
```text
|
||||
OBS / FFmpeg --RTMP--> SRS --HTTP Hooks--> Fastify API
|
||||
|
|
||||
+--HLS--> Nginx --> hls.js --> Browser
|
||||
|
||||
Vue 3 + TypeScript + Pinia + Naive UI
|
||||
Fastify 5 + Prisma + PostgreSQL 16 + Redis 7
|
||||
SRS 6 + Nginx + Docker Compose
|
||||
```
|
||||
|
||||
推流名称与密钥分离。OBS 中显示的 Stream Key 形式为 `room_10001?token=<secret>`;SRS 实际流名是 `room_10001`,因此公开的 HLS URL 不包含密钥。
|
||||
|
||||
## 📁 目录结构
|
||||
|
||||
```text
|
||||
apps/api 后端、Prisma 模型/迁移、测试、Swagger
|
||||
apps/web Vue SPA 与管理后台
|
||||
infra/srs SRS 配置
|
||||
infra/nginx 入口代理、HLS MIME/缓存、上传文件
|
||||
scripts RTMP 全链路测试脚本
|
||||
docs/ API 文档
|
||||
docker-compose.yml 生产/完整部署编排
|
||||
docker-compose.dev.yml 本地开发热更新覆盖层
|
||||
```
|
||||
|
||||
## 🚀 快速开始
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Docker Desktop 4.x 或 Docker Engine 25+(含 Docker Compose v2)
|
||||
- 本地开发可选 Node.js 22+
|
||||
- OBS Studio,或用项目脚本自动拉取 FFmpeg 容器
|
||||
|
||||
### 启动
|
||||
|
||||
1. 克隆仓库并复制环境变量模板:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/itxiaohui66/xlive.git
|
||||
cd xlive
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
2. 修改 `.env`,至少替换以下值(生产环境请使用密码管理器生成随机值):
|
||||
|
||||
- `JWT_SECRET`、`CONFIG_ENCRYPTION_KEY`、`SRS_HOOK_SECRET`
|
||||
- `ADMIN_PASSWORD`
|
||||
- `POSTGRES_PASSWORD`(如不使用模板中的开发默认值)
|
||||
|
||||
3. 构建并启动:
|
||||
|
||||
```bash
|
||||
docker compose up -d --build
|
||||
docker compose ps
|
||||
```
|
||||
|
||||
数据库迁移与首次管理员创建由 API 容器自动完成。初始化只在用户名/邮箱不存在时创建管理员,不会在重启时覆盖密码。
|
||||
|
||||
- 网站:<http://localhost>
|
||||
- Swagger:<http://localhost/api/docs>
|
||||
- 健康检查:<http://localhost/health>
|
||||
- RTMP:`rtmp://localhost/live`
|
||||
|
||||
默认开发管理员取自 `.env` 的 `ADMIN_USERNAME` / `ADMIN_PASSWORD`。首次登录后请立即更换密码。
|
||||
|
||||
## 🛠 本地开发
|
||||
|
||||
基础设施使用 Docker,前后端热更新:
|
||||
|
||||
```bash
|
||||
docker compose up -d postgres redis srs
|
||||
npm install
|
||||
$env:DATABASE_URL="postgresql://xlive:xlive_dev_password@localhost:5432/xlive?schema=public"
|
||||
$env:REDIS_URL="redis://localhost:6379"
|
||||
npm run dev
|
||||
```
|
||||
|
||||
也可使用 `docker compose -f docker-compose.yml -f docker-compose.dev.yml up --build`。提交数据库变更前运行 `npx prisma migrate dev --schema apps/api/prisma/schema.prisma --name <name>`。
|
||||
|
||||
## 🎥 OBS 与真实直播测试
|
||||
|
||||
1. 注册并登录,进入「我的直播间」,创建直播间。
|
||||
2. 在推流设置复制 RTMP Server 和完整 Stream Key。
|
||||
3. OBS → 设置 → 直播 → 自定义:Server 填 `rtmp://localhost/live`,Stream Key 填页面值。
|
||||
4. 视频编码使用 H.264、音频 AAC,建议关键帧间隔 2 秒。
|
||||
5. 开始推流后,SRS 鉴权成功并回调 API,房间自动变为 LIVE,公开房间出现在首页。
|
||||
6. 停止推流后,房间自动 OFFLINE,SRS 将本场直播录制为 FLV 回放,并生成带时间轴弹幕的直播记录。
|
||||
|
||||
无本机 FFmpeg 时,在 PowerShell 执行:
|
||||
|
||||
```powershell
|
||||
.\scripts\rtmp-smoke.ps1 -StreamKey 'room_10001?token=从页面复制的密钥' -Seconds 60
|
||||
```
|
||||
|
||||
打开 `http://localhost/room/10001` 验证画面。另一个终端可观察:
|
||||
|
||||
```bash
|
||||
docker compose logs -f srs api
|
||||
```
|
||||
|
||||
## ⚙️ 配置说明
|
||||
|
||||
所有运行配置通过 `.env` 注入(模板见 `.env.example`),关键项:
|
||||
|
||||
| 变量 | 说明 |
|
||||
|---|---|
|
||||
| `DATABASE_URL` / `REDIS_URL` | PostgreSQL / Redis 连接串 |
|
||||
| `JWT_SECRET` / `CONFIG_ENCRYPTION_KEY` | Token 签名与敏感配置加密密钥 |
|
||||
| `ADMIN_USERNAME` / `ADMIN_PASSWORD` / `ADMIN_EMAIL` | 首次启动创建的超管账号 |
|
||||
| `SRS_API_URL` / `SRS_HOOK_SECRET` | SRS HTTP API 地址与 Webhook 鉴权 |
|
||||
| `RTMP_PUBLIC_URL` / `HLS_PUBLIC_URL` | 对外推流/播放地址 |
|
||||
| `UPLOAD_DIR` / `LIVE_DIR` | 上传文件与直播切片目录 |
|
||||
|
||||
> ⚠️ **永远不要把真实的 `.env` 提交到仓库**。它已被 `.gitignore` 排除;`.env.example` 只含占位符模板。
|
||||
|
||||
SMTP 与阿里云短信配置在管理后台「系统设置」中完成:SMTP 填写 Host、Port、用户名、密码、加密方式(NONE/SSL/STARTTLS);短信填写 AccessKey、签名与模板编号,密码/Secret 使用 AES-256-GCM 加密保存,接口仅返回 `********`。建议使用仅授予 `dysms:SendSms` 的 RAM 子账号。
|
||||
|
||||
## 🌐 生产部署与 HTTPS
|
||||
|
||||
1. 使用独立 PostgreSQL/Redis 凭据,Redis 不暴露公网。
|
||||
2. 将域名写入 Nginx `server_name`,把 `.env` 的 `PUBLIC_URL`、`RTMP_PUBLIC_URL`、`HLS_PUBLIC_URL` 改为真实域名。
|
||||
3. 用 Certbot/Let's Encrypt 申请证书,将证书只读挂载到 `/etc/nginx/certs`,启用 443 server 并将 80 重定向至 HTTPS。
|
||||
4. 页面、API、HLS 必须统一 HTTPS;聊天室使用 WSS。RTMP 可继续使用 `rtmp://`(或在专用入口配置 RTMPS),不会产生浏览器 Mixed Content。
|
||||
5. 设置 `COOKIE_SECURE=true`,限制防火墙只开放 80/443/1935。SRS API 1985 不应暴露公网。
|
||||
6. 反向代理已为 HLS 配置正确 MIME、无缓存、CORS;上传限制为 10 MB。
|
||||
|
||||
## 💾 数据库、备份与升级
|
||||
|
||||
备份:
|
||||
|
||||
```bash
|
||||
docker compose exec -T postgres pg_dump -U xlive -Fc xlive > xlive.dump
|
||||
```
|
||||
|
||||
恢复到空库前先停止 API,并验证备份。升级时先备份,再拉取代码并运行 `docker compose up -d --build`;API 启动会执行尚未应用的 Prisma migration。不要删除已经在生产使用的 migration。
|
||||
|
||||
## 🧪 测试
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
npm test
|
||||
docker compose config --quiet
|
||||
```
|
||||
|
||||
测试覆盖密码策略/Argon2id、敏感配置加密,以及 SRS 无效密钥与停播 Webhook。完整直播验证使用上述 `rtmp-smoke.ps1`,它生成动态测试源并真实经过 RTMP → SRS → HLS → 浏览器,不使用静态视频冒充。
|
||||
|
||||
## 📚 API 与错误格式
|
||||
|
||||
运行后 Swagger/OpenAPI 位于 `/api/docs`。主要端点见 [API 文档](docs/API.md)。错误统一返回:
|
||||
|
||||
```json
|
||||
{"code":"ROOM_NOT_FOUND","message":"直播间不存在","requestId":"2cb…"}
|
||||
```
|
||||
|
||||
数据库异常、堆栈、内部地址和密钥不会直接返回。
|
||||
|
||||
## ❓ 常见问题
|
||||
|
||||
- **Docker CLI 存在但无法连接**:先启动 Docker Desktop;Windows 可检查 `dockerDesktopLinuxEngine`。Docker Desktop 自身崩溃时查看 `%LOCALAPPDATA%\Docker\log\host\com.docker.backend.exe.log`。
|
||||
- **推流被拒绝**:确认复制了完整 Stream Key、用户/房间未禁播,查看 `docker compose logs api srs`。
|
||||
- **有推流但播放器 404**:等待首个 HLS 分片(通常 2–4 秒),确认编码是 H.264 + AAC,并检查挂载的 `srs_hls` volume。
|
||||
- **自动播放失败**:浏览器要求首次自动播放静音;页面会提示用户点击播放。
|
||||
- **SMTP/SMS 未配置**:系统检测应显示「未配置」,不是「正常」;测试接口不会伪造成功。
|
||||
|
||||
## 🔒 安全
|
||||
|
||||
- 真实 `.env`、数据库备份、上传内容与证书均被 `.gitignore` 排除,请勿强行提交。
|
||||
- 发现安全漏洞请通过私密渠道联系维护者,不要在公开 Issue 中披露细节。
|
||||
- 部署后请立即修改默认管理员密码,并定期备份数据库。
|
||||
|
||||
## 👤 作者
|
||||
|
||||
- 作者:**itxiaohui**
|
||||
- 网站:<http://www.itxiaohui.top>
|
||||
- 作者社区:<http://www.itky.cc>
|
||||
|
||||
有问题或建议欢迎到社区交流,或在本仓库提交 Issue / Pull Request。
|
||||
|
||||
## 📄 许可证
|
||||
|
||||
[MIT](LICENSE) © 2026 itxiaohui
|
||||
@@ -0,0 +1,28 @@
|
||||
FROM node:22-alpine AS base
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache openssl libc6-compat
|
||||
COPY package*.json ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
RUN npm ci
|
||||
COPY apps/api apps/api
|
||||
|
||||
FROM base AS dev
|
||||
CMD ["npm", "run", "dev", "-w", "@xlive/api"]
|
||||
|
||||
FROM base AS build
|
||||
RUN npm run build -w @xlive/api
|
||||
|
||||
FROM node:22-alpine AS production
|
||||
WORKDIR /app
|
||||
RUN apk add --no-cache openssl wget ffmpeg su-exec && addgroup -S app && adduser -S app -G app
|
||||
COPY package*.json ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
RUN npm ci --omit=dev --workspace=@xlive/api --include-workspace-root=false
|
||||
COPY --from=build /app/apps/api/dist apps/api/dist
|
||||
COPY --from=build /app/apps/api/prisma apps/api/prisma
|
||||
COPY --from=build /app/node_modules/.prisma node_modules/.prisma
|
||||
RUN mkdir -p /app/uploads /app/live && chown -R app:app /app
|
||||
# 回放目录由 SRS(root)写入,启动时放开目录写权限,再以 app 用户运行服务
|
||||
CMD ["sh", "-c", "mkdir -p /app/live/replays && chmod -R a+rwX /app/live/replays 2>/dev/null || true; exec su-exec app sh -c 'npx prisma migrate deploy --schema apps/api/prisma/schema.prisma && node apps/api/dist/seed.js && node apps/api/dist/server.js'"]
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"name": "@xlive/api",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch src/server.ts",
|
||||
"build": "prisma generate && tsc -p tsconfig.json",
|
||||
"start": "node dist/server.js",
|
||||
"db:migrate": "prisma migrate deploy",
|
||||
"db:seed": "tsx src/seed.ts",
|
||||
"test": "vitest run --coverage",
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aws-sdk/client-ses": "^3.888.0",
|
||||
"@fastify/cookie": "^11.0.2",
|
||||
"@fastify/cors": "^11.1.0",
|
||||
"@fastify/helmet": "^13.0.2",
|
||||
"@fastify/jwt": "^10.0.0",
|
||||
"@fastify/multipart": "^9.2.1",
|
||||
"@fastify/rate-limit": "^10.3.0",
|
||||
"@fastify/swagger": "^9.5.1",
|
||||
"@fastify/swagger-ui": "^5.2.3",
|
||||
"@fastify/websocket": "^11.2.0",
|
||||
"@prisma/client": "^6.16.2",
|
||||
"@scalar/fastify-api-reference": "^1.34.6",
|
||||
"@types/node": "^24.3.3",
|
||||
"argon2": "^0.44.0",
|
||||
"fastify": "^5.6.0",
|
||||
"nodemailer": "^7.0.6",
|
||||
"os-utils": "^0.0.14",
|
||||
"pino": "^9.9.4",
|
||||
"prisma": "^6.16.2",
|
||||
"prom-client": "^15.1.3",
|
||||
"redis": "^5.8.2",
|
||||
"systeminformation": "^5.27.7",
|
||||
"uuid": "^11.1.0",
|
||||
"ws": "^8.18.3",
|
||||
"zod": "^4.1.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/nodemailer": "^7.0.1",
|
||||
"@types/ws": "^8.18.1",
|
||||
"@vitest/coverage-v8": "^3.2.4",
|
||||
"tsx": "^4.20.5",
|
||||
"typescript": "^5.9.2",
|
||||
"vitest": "^3.2.4"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
-- CreateSchema
|
||||
CREATE SCHEMA IF NOT EXISTS "public";
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "UserStatus" AS ENUM ('ACTIVE', 'DISABLED', 'DELETED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RoleName" AS ENUM ('USER', 'ADMIN', 'SUPER_ADMIN');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "RoomVisibility" AS ENUM ('PUBLIC', 'PRIVATE');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "StreamStatus" AS ENUM ('OFFLINE', 'LIVE', 'BANNED');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CodePurpose" AS ENUM ('REGISTER', 'LOGIN', 'RESET_PASSWORD');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "CodeChannel" AS ENUM ('EMAIL', 'SMS');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "BanType" AS ENUM ('LOGIN', 'CHAT', 'STREAM');
|
||||
|
||||
-- CreateEnum
|
||||
CREATE TYPE "AdminResult" AS ENUM ('SUCCESS', 'FAILURE');
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "users" (
|
||||
"id" UUID NOT NULL,
|
||||
"username" VARCHAR(32) NOT NULL,
|
||||
"nickname" VARCHAR(64) NOT NULL,
|
||||
"avatar" VARCHAR(500),
|
||||
"bio" VARCHAR(500),
|
||||
"email" VARCHAR(254),
|
||||
"phone" VARCHAR(32),
|
||||
"password_hash" TEXT NOT NULL,
|
||||
"status" "UserStatus" NOT NULL DEFAULT 'ACTIVE',
|
||||
"can_stream" BOOLEAN NOT NULL DEFAULT true,
|
||||
"register_ip" VARCHAR(64),
|
||||
"last_login_ip" VARCHAR(64),
|
||||
"last_login_at" TIMESTAMP(3),
|
||||
"failed_login_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"locked_until" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "roles" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"name" "RoleName" NOT NULL,
|
||||
"description" TEXT,
|
||||
|
||||
CONSTRAINT "roles_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "user_roles" (
|
||||
"user_id" UUID NOT NULL,
|
||||
"role_id" INTEGER NOT NULL,
|
||||
|
||||
CONSTRAINT "user_roles_pkey" PRIMARY KEY ("user_id","role_id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "rooms" (
|
||||
"id" UUID NOT NULL,
|
||||
"owner_id" UUID NOT NULL,
|
||||
"room_number" SERIAL NOT NULL,
|
||||
"title" VARCHAR(120) NOT NULL,
|
||||
"description" VARCHAR(1000),
|
||||
"cover" VARCHAR(500),
|
||||
"announcement" VARCHAR(1000),
|
||||
"visibility" "RoomVisibility" NOT NULL DEFAULT 'PUBLIC',
|
||||
"stream_status" "StreamStatus" NOT NULL DEFAULT 'OFFLINE',
|
||||
"viewer_count" INTEGER NOT NULL DEFAULT 0,
|
||||
"show_viewer_count" BOOLEAN NOT NULL DEFAULT true,
|
||||
"featured" BOOLEAN NOT NULL DEFAULT false,
|
||||
"live_banned" BOOLEAN NOT NULL DEFAULT false,
|
||||
"last_live_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"category_id" INTEGER,
|
||||
|
||||
CONSTRAINT "rooms_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "stream_keys" (
|
||||
"id" UUID NOT NULL,
|
||||
"room_id" UUID NOT NULL,
|
||||
"key_hash" VARCHAR(64) NOT NULL,
|
||||
"key_cipher" TEXT NOT NULL,
|
||||
"key_hint" VARCHAR(12) NOT NULL,
|
||||
"version" INTEGER NOT NULL DEFAULT 1,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"rotated_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "stream_keys_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "live_sessions" (
|
||||
"id" UUID NOT NULL,
|
||||
"room_id" UUID NOT NULL,
|
||||
"stream_name" VARCHAR(128) NOT NULL,
|
||||
"srs_client_id" VARCHAR(64),
|
||||
"started_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"ended_at" TIMESTAMP(3),
|
||||
"duration_seconds" INTEGER,
|
||||
"peak_viewers" INTEGER NOT NULL DEFAULT 0,
|
||||
"viewer_seconds" BIGINT NOT NULL DEFAULT 0,
|
||||
"viewer_samples" INTEGER NOT NULL DEFAULT 0,
|
||||
"total_views" INTEGER NOT NULL DEFAULT 0,
|
||||
|
||||
CONSTRAINT "live_sessions_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "categories" (
|
||||
"id" SERIAL NOT NULL,
|
||||
"name" VARCHAR(64) NOT NULL,
|
||||
"slug" VARCHAR(64) NOT NULL,
|
||||
"icon" VARCHAR(128),
|
||||
"sort" INTEGER NOT NULL DEFAULT 0,
|
||||
"enabled" BOOLEAN NOT NULL DEFAULT true,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "categories_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "verification_codes" (
|
||||
"id" UUID NOT NULL,
|
||||
"channel" "CodeChannel" NOT NULL,
|
||||
"target_hash" VARCHAR(64) NOT NULL,
|
||||
"code_hash" VARCHAR(64) NOT NULL,
|
||||
"purpose" "CodePurpose" NOT NULL,
|
||||
"attempts" INTEGER NOT NULL DEFAULT 0,
|
||||
"max_attempts" INTEGER NOT NULL DEFAULT 5,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"used_at" TIMESTAMP(3),
|
||||
"ip" VARCHAR(64),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "verification_codes_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "system_settings" (
|
||||
"key" VARCHAR(128) NOT NULL,
|
||||
"value" TEXT NOT NULL,
|
||||
"group" VARCHAR(64) NOT NULL,
|
||||
"sensitive" BOOLEAN NOT NULL DEFAULT false,
|
||||
"description" TEXT,
|
||||
"updated_at" TIMESTAMP(3) NOT NULL,
|
||||
"updated_by" UUID,
|
||||
|
||||
CONSTRAINT "system_settings_pkey" PRIMARY KEY ("key")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "refresh_tokens" (
|
||||
"id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"token_hash" VARCHAR(64) NOT NULL,
|
||||
"expires_at" TIMESTAMP(3) NOT NULL,
|
||||
"revoked_at" TIMESTAMP(3),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"ip" VARCHAR(64),
|
||||
|
||||
CONSTRAINT "refresh_tokens_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "admin_logs" (
|
||||
"id" BIGSERIAL NOT NULL,
|
||||
"admin_id" UUID NOT NULL,
|
||||
"action" VARCHAR(128) NOT NULL,
|
||||
"target_type" VARCHAR(64),
|
||||
"target_id" VARCHAR(128),
|
||||
"details" JSONB,
|
||||
"result" "AdminResult" NOT NULL,
|
||||
"ip" VARCHAR(64),
|
||||
"request_id" VARCHAR(64),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "admin_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "login_logs" (
|
||||
"id" BIGSERIAL NOT NULL,
|
||||
"user_id" UUID,
|
||||
"account" VARCHAR(254) NOT NULL,
|
||||
"success" BOOLEAN NOT NULL,
|
||||
"reason" VARCHAR(128),
|
||||
"ip" VARCHAR(64),
|
||||
"user_agent" VARCHAR(500),
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "login_logs_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "chat_messages" (
|
||||
"id" UUID NOT NULL,
|
||||
"room_id" UUID NOT NULL,
|
||||
"user_id" UUID,
|
||||
"nickname" VARCHAR(64) NOT NULL,
|
||||
"avatar" VARCHAR(500),
|
||||
"content" VARCHAR(500) NOT NULL,
|
||||
"deleted_at" TIMESTAMP(3),
|
||||
"deleted_by" UUID,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "chat_messages_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "bans" (
|
||||
"id" UUID NOT NULL,
|
||||
"user_id" UUID NOT NULL,
|
||||
"type" "BanType" NOT NULL,
|
||||
"reason" VARCHAR(500),
|
||||
"expires_at" TIMESTAMP(3),
|
||||
"created_by" UUID NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"revoked_at" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "bans_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_username_key" ON "users"("username");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "users_phone_key" ON "users"("phone");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "users_created_at_idx" ON "users"("created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "roles_name_key" ON "roles"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "rooms_room_number_key" ON "rooms"("room_number");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "rooms_stream_status_visibility_idx" ON "rooms"("stream_status", "visibility");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "rooms_owner_id_idx" ON "rooms"("owner_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "rooms_category_id_idx" ON "rooms"("category_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "stream_keys_room_id_key" ON "stream_keys"("room_id");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "stream_keys_key_hash_key" ON "stream_keys"("key_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "live_sessions_room_id_started_at_idx" ON "live_sessions"("room_id", "started_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "live_sessions_ended_at_idx" ON "live_sessions"("ended_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "categories_name_key" ON "categories"("name");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "categories_slug_key" ON "categories"("slug");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "categories_enabled_sort_idx" ON "categories"("enabled", "sort");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "verification_codes_target_hash_purpose_expires_at_idx" ON "verification_codes"("target_hash", "purpose", "expires_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "system_settings_group_idx" ON "system_settings"("group");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "refresh_tokens_token_hash_key" ON "refresh_tokens"("token_hash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "refresh_tokens_user_id_expires_at_idx" ON "refresh_tokens"("user_id", "expires_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "admin_logs_admin_id_created_at_idx" ON "admin_logs"("admin_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "admin_logs_action_created_at_idx" ON "admin_logs"("action", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "login_logs_account_created_at_idx" ON "login_logs"("account", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "login_logs_ip_created_at_idx" ON "login_logs"("ip", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "chat_messages_room_id_created_at_idx" ON "chat_messages"("room_id", "created_at");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "bans_user_id_type_expires_at_idx" ON "bans"("user_id", "type", "expires_at");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_roles" ADD CONSTRAINT "user_roles_role_id_fkey" FOREIGN KEY ("role_id") REFERENCES "roles"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "rooms" ADD CONSTRAINT "rooms_owner_id_fkey" FOREIGN KEY ("owner_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "rooms" ADD CONSTRAINT "rooms_category_id_fkey" FOREIGN KEY ("category_id") REFERENCES "categories"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "stream_keys" ADD CONSTRAINT "stream_keys_room_id_fkey" FOREIGN KEY ("room_id") REFERENCES "rooms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "live_sessions" ADD CONSTRAINT "live_sessions_room_id_fkey" FOREIGN KEY ("room_id") REFERENCES "rooms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "refresh_tokens" ADD CONSTRAINT "refresh_tokens_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "admin_logs" ADD CONSTRAINT "admin_logs_admin_id_fkey" FOREIGN KEY ("admin_id") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "login_logs" ADD CONSTRAINT "login_logs_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "chat_messages" ADD CONSTRAINT "chat_messages_room_id_fkey" FOREIGN KEY ("room_id") REFERENCES "rooms"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "chat_messages" ADD CONSTRAINT "chat_messages_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "bans" ADD CONSTRAINT "bans_user_id_fkey" FOREIGN KEY ("user_id") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "bans" ADD CONSTRAINT "bans_created_by_fkey" FOREIGN KEY ("created_by") REFERENCES "users"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- Add replay metadata to completed live sessions.
|
||||
ALTER TABLE "live_sessions"
|
||||
ADD COLUMN "recording_url" VARCHAR(500),
|
||||
ADD COLUMN "recording_size" BIGINT;
|
||||
|
||||
-- Associate chat messages with their live session so they can be replayed as timed danmaku.
|
||||
ALTER TABLE "chat_messages"
|
||||
ADD COLUMN "session_id" UUID,
|
||||
ADD COLUMN "offset_seconds" DOUBLE PRECISION;
|
||||
|
||||
CREATE INDEX "chat_messages_session_id_offset_seconds_idx"
|
||||
ON "chat_messages"("session_id", "offset_seconds");
|
||||
|
||||
ALTER TABLE "chat_messages"
|
||||
ADD CONSTRAINT "chat_messages_session_id_fkey"
|
||||
FOREIGN KEY ("session_id") REFERENCES "live_sessions"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,26 @@
|
||||
-- Track uploaded files (avatars, covers) so admins can manage them.
|
||||
CREATE TABLE "uploads" (
|
||||
"id" UUID NOT NULL,
|
||||
"filename" VARCHAR(255) NOT NULL,
|
||||
"original_name" VARCHAR(255),
|
||||
"mime_type" VARCHAR(64) NOT NULL,
|
||||
"size" INTEGER NOT NULL,
|
||||
"uploader_id" UUID,
|
||||
"url" VARCHAR(500) NOT NULL,
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
CONSTRAINT "uploads_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "uploads_created_at_idx" ON "uploads"("created_at");
|
||||
|
||||
ALTER TABLE "uploads"
|
||||
ADD CONSTRAINT "uploads_uploader_id_fkey"
|
||||
FOREIGN KEY ("uploader_id") REFERENCES "users"("id")
|
||||
ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
-- Per-room choice whether live sessions generate a replay, captured per session at publish time.
|
||||
ALTER TABLE "rooms"
|
||||
ADD COLUMN "record_replay" BOOLEAN NOT NULL DEFAULT true;
|
||||
|
||||
ALTER TABLE "live_sessions"
|
||||
ADD COLUMN "record_enabled" BOOLEAN NOT NULL DEFAULT true;
|
||||
@@ -0,0 +1,21 @@
|
||||
-- 站内信 / 开播申请:用户向管理员申请开播权限,管理员审批。
|
||||
CREATE TABLE "notices" (
|
||||
"id" UUID NOT NULL,
|
||||
"from_id" UUID NOT NULL,
|
||||
"content" VARCHAR(1000) NOT NULL,
|
||||
"status" VARCHAR(16) NOT NULL DEFAULT 'PENDING',
|
||||
"created_at" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"handled_at" TIMESTAMP(3),
|
||||
"handled_by" UUID,
|
||||
CONSTRAINT "notices_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
CREATE INDEX "notices_status_created_at_idx" ON "notices"("status", "created_at");
|
||||
|
||||
ALTER TABLE "notices"
|
||||
ADD CONSTRAINT "notices_from_id_fkey"
|
||||
FOREIGN KEY ("from_id") REFERENCES "users"("id")
|
||||
ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- 新注册用户默认无开播权限,需向管理员申请并由管理员批准。
|
||||
ALTER TABLE "users" ALTER COLUMN "can_stream" SET DEFAULT false;
|
||||
@@ -0,0 +1 @@
|
||||
provider = "postgresql"
|
||||
@@ -0,0 +1,332 @@
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum UserStatus {
|
||||
ACTIVE
|
||||
DISABLED
|
||||
DELETED
|
||||
}
|
||||
|
||||
enum RoleName {
|
||||
USER
|
||||
ADMIN
|
||||
SUPER_ADMIN
|
||||
}
|
||||
|
||||
enum RoomVisibility {
|
||||
PUBLIC
|
||||
PRIVATE
|
||||
}
|
||||
|
||||
enum StreamStatus {
|
||||
OFFLINE
|
||||
LIVE
|
||||
BANNED
|
||||
}
|
||||
|
||||
enum CodePurpose {
|
||||
REGISTER
|
||||
LOGIN
|
||||
RESET_PASSWORD
|
||||
}
|
||||
|
||||
enum CodeChannel {
|
||||
EMAIL
|
||||
SMS
|
||||
}
|
||||
|
||||
enum BanType {
|
||||
LOGIN
|
||||
CHAT
|
||||
STREAM
|
||||
}
|
||||
|
||||
enum AdminResult {
|
||||
SUCCESS
|
||||
FAILURE
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
username String @unique @db.VarChar(32)
|
||||
nickname String @db.VarChar(64)
|
||||
avatar String? @db.VarChar(500)
|
||||
bio String? @db.VarChar(500)
|
||||
email String? @unique @db.VarChar(254)
|
||||
phone String? @unique @db.VarChar(32)
|
||||
passwordHash String @map("password_hash")
|
||||
status UserStatus @default(ACTIVE)
|
||||
canStream Boolean @default(false) @map("can_stream")
|
||||
registerIp String? @map("register_ip") @db.VarChar(64)
|
||||
lastLoginIp String? @map("last_login_ip") @db.VarChar(64)
|
||||
lastLoginAt DateTime? @map("last_login_at")
|
||||
failedLoginCount Int @default(0) @map("failed_login_count")
|
||||
lockedUntil DateTime? @map("locked_until")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
roles UserRole[]
|
||||
rooms Room[]
|
||||
refreshTokens RefreshToken[]
|
||||
chatMessages ChatMessage[]
|
||||
bans Ban[] @relation("BannedUser")
|
||||
bansIssued Ban[] @relation("IssuedBy")
|
||||
adminLogs AdminLog[]
|
||||
loginLogs LoginLog[]
|
||||
uploads Upload[]
|
||||
sentNotices Notice[] @relation("NoticeFrom")
|
||||
|
||||
@@index([createdAt])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
model Role {
|
||||
id Int @id @default(autoincrement())
|
||||
name RoleName @unique
|
||||
description String?
|
||||
users UserRole[]
|
||||
|
||||
@@map("roles")
|
||||
}
|
||||
|
||||
model UserRole {
|
||||
userId String @map("user_id") @db.Uuid
|
||||
roleId Int @map("role_id")
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
role Role @relation(fields: [roleId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@id([userId, roleId])
|
||||
@@map("user_roles")
|
||||
}
|
||||
|
||||
model Room {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
ownerId String @map("owner_id") @db.Uuid
|
||||
roomNumber Int @unique @default(autoincrement()) @map("room_number")
|
||||
title String @db.VarChar(120)
|
||||
description String? @db.VarChar(1000)
|
||||
cover String? @db.VarChar(500)
|
||||
announcement String? @db.VarChar(1000)
|
||||
visibility RoomVisibility @default(PUBLIC)
|
||||
streamStatus StreamStatus @default(OFFLINE) @map("stream_status")
|
||||
viewerCount Int @default(0) @map("viewer_count")
|
||||
showViewerCount Boolean @default(true) @map("show_viewer_count")
|
||||
featured Boolean @default(false)
|
||||
liveBanned Boolean @default(false) @map("live_banned")
|
||||
recordReplay Boolean @default(true) @map("record_replay")
|
||||
lastLiveAt DateTime? @map("last_live_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
owner User @relation(fields: [ownerId], references: [id], onDelete: Restrict)
|
||||
categoryId Int? @map("category_id")
|
||||
category Category? @relation(fields: [categoryId], references: [id], onDelete: SetNull)
|
||||
streamKey StreamKey?
|
||||
sessions LiveSession[]
|
||||
chatMessages ChatMessage[]
|
||||
|
||||
@@index([streamStatus, visibility])
|
||||
@@index([ownerId])
|
||||
@@index([categoryId])
|
||||
@@map("rooms")
|
||||
}
|
||||
|
||||
model StreamKey {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roomId String @unique @map("room_id") @db.Uuid
|
||||
keyHash String @unique @map("key_hash") @db.VarChar(64)
|
||||
keyCipher String @map("key_cipher")
|
||||
keyHint String @map("key_hint") @db.VarChar(12)
|
||||
version Int @default(1)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
rotatedAt DateTime? @map("rotated_at")
|
||||
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@map("stream_keys")
|
||||
}
|
||||
|
||||
model LiveSession {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roomId String @map("room_id") @db.Uuid
|
||||
streamName String @map("stream_name") @db.VarChar(128)
|
||||
srsClientId String? @map("srs_client_id") @db.VarChar(64)
|
||||
startedAt DateTime @default(now()) @map("started_at")
|
||||
endedAt DateTime? @map("ended_at")
|
||||
durationSeconds Int? @map("duration_seconds")
|
||||
peakViewers Int @default(0) @map("peak_viewers")
|
||||
viewerSeconds BigInt @default(0) @map("viewer_seconds")
|
||||
viewerSamples Int @default(0) @map("viewer_samples")
|
||||
totalViews Int @default(0) @map("total_views")
|
||||
recordingUrl String? @map("recording_url") @db.VarChar(500)
|
||||
recordingSize BigInt? @map("recording_size")
|
||||
recordEnabled Boolean @default(true) @map("record_enabled")
|
||||
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
chatMessages ChatMessage[]
|
||||
|
||||
@@index([roomId, startedAt])
|
||||
@@index([endedAt])
|
||||
@@map("live_sessions")
|
||||
}
|
||||
|
||||
model Notice {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
fromId String @map("from_id") @db.Uuid
|
||||
from User @relation("NoticeFrom", fields: [fromId], references: [id], onDelete: Cascade)
|
||||
content String @db.VarChar(1000)
|
||||
status String @default("PENDING") @db.VarChar(16)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
handledAt DateTime? @map("handled_at")
|
||||
handledBy String? @map("handled_by") @db.Uuid
|
||||
|
||||
@@index([status, createdAt])
|
||||
@@map("notices")
|
||||
}
|
||||
|
||||
model Upload {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
filename String @db.VarChar(255)
|
||||
originalName String? @map("original_name") @db.VarChar(255)
|
||||
mimeType String @map("mime_type") @db.VarChar(64)
|
||||
size Int
|
||||
uploaderId String? @map("uploader_id") @db.Uuid
|
||||
uploader User? @relation(fields: [uploaderId], references: [id], onDelete: SetNull)
|
||||
url String @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([createdAt])
|
||||
@@map("uploads")
|
||||
}
|
||||
|
||||
model Category {
|
||||
id Int @id @default(autoincrement())
|
||||
name String @unique @db.VarChar(64)
|
||||
slug String @unique @db.VarChar(64)
|
||||
icon String? @db.VarChar(128)
|
||||
sort Int @default(0)
|
||||
enabled Boolean @default(true)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
rooms Room[]
|
||||
|
||||
@@index([enabled, sort])
|
||||
@@map("categories")
|
||||
}
|
||||
|
||||
model VerificationCode {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
channel CodeChannel
|
||||
targetHash String @map("target_hash") @db.VarChar(64)
|
||||
codeHash String @map("code_hash") @db.VarChar(64)
|
||||
purpose CodePurpose
|
||||
attempts Int @default(0)
|
||||
maxAttempts Int @default(5) @map("max_attempts")
|
||||
expiresAt DateTime @map("expires_at")
|
||||
usedAt DateTime? @map("used_at")
|
||||
ip String? @db.VarChar(64)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
|
||||
@@index([targetHash, purpose, expiresAt])
|
||||
@@map("verification_codes")
|
||||
}
|
||||
|
||||
model SystemSetting {
|
||||
key String @id @db.VarChar(128)
|
||||
value String
|
||||
group String @db.VarChar(64)
|
||||
sensitive Boolean @default(false)
|
||||
description String?
|
||||
updatedAt DateTime @updatedAt @map("updated_at")
|
||||
updatedBy String? @map("updated_by") @db.Uuid
|
||||
|
||||
@@index([group])
|
||||
@@map("system_settings")
|
||||
}
|
||||
|
||||
model RefreshToken {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
tokenHash String @unique @map("token_hash") @db.VarChar(64)
|
||||
expiresAt DateTime @map("expires_at")
|
||||
revokedAt DateTime? @map("revoked_at")
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
ip String? @db.VarChar(64)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([userId, expiresAt])
|
||||
@@map("refresh_tokens")
|
||||
}
|
||||
|
||||
model AdminLog {
|
||||
id BigInt @id @default(autoincrement())
|
||||
adminId String @map("admin_id") @db.Uuid
|
||||
action String @db.VarChar(128)
|
||||
targetType String? @map("target_type") @db.VarChar(64)
|
||||
targetId String? @map("target_id") @db.VarChar(128)
|
||||
details Json?
|
||||
result AdminResult
|
||||
ip String? @db.VarChar(64)
|
||||
requestId String? @map("request_id") @db.VarChar(64)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
admin User @relation(fields: [adminId], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([adminId, createdAt])
|
||||
@@index([action, createdAt])
|
||||
@@map("admin_logs")
|
||||
}
|
||||
|
||||
model LoginLog {
|
||||
id BigInt @id @default(autoincrement())
|
||||
userId String? @map("user_id") @db.Uuid
|
||||
account String @db.VarChar(254)
|
||||
success Boolean
|
||||
reason String? @db.VarChar(128)
|
||||
ip String? @db.VarChar(64)
|
||||
userAgent String? @map("user_agent") @db.VarChar(500)
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([account, createdAt])
|
||||
@@index([ip, createdAt])
|
||||
@@map("login_logs")
|
||||
}
|
||||
|
||||
model ChatMessage {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
roomId String @map("room_id") @db.Uuid
|
||||
userId String? @map("user_id") @db.Uuid
|
||||
sessionId String? @map("session_id") @db.Uuid
|
||||
offsetSeconds Float? @map("offset_seconds")
|
||||
nickname String @db.VarChar(64)
|
||||
avatar String? @db.VarChar(500)
|
||||
content String @db.VarChar(500)
|
||||
deletedAt DateTime? @map("deleted_at")
|
||||
deletedBy String? @map("deleted_by") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
room Room @relation(fields: [roomId], references: [id], onDelete: Cascade)
|
||||
user User? @relation(fields: [userId], references: [id], onDelete: SetNull)
|
||||
session LiveSession? @relation(fields: [sessionId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([roomId, createdAt])
|
||||
@@index([sessionId, offsetSeconds])
|
||||
@@map("chat_messages")
|
||||
}
|
||||
|
||||
model Ban {
|
||||
id String @id @default(uuid()) @db.Uuid
|
||||
userId String @map("user_id") @db.Uuid
|
||||
type BanType
|
||||
reason String? @db.VarChar(500)
|
||||
expiresAt DateTime? @map("expires_at")
|
||||
createdBy String @map("created_by") @db.Uuid
|
||||
createdAt DateTime @default(now()) @map("created_at")
|
||||
revokedAt DateTime? @map("revoked_at")
|
||||
user User @relation("BannedUser", fields: [userId], references: [id], onDelete: Cascade)
|
||||
issuer User @relation("IssuedBy", fields: [createdBy], references: [id], onDelete: Restrict)
|
||||
|
||||
@@index([userId, type, expiresAt])
|
||||
@@map("bans")
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import Fastify from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import cors from '@fastify/cors';
|
||||
import helmet from '@fastify/helmet';
|
||||
import jwt from '@fastify/jwt';
|
||||
import rateLimit from '@fastify/rate-limit';
|
||||
import swagger from '@fastify/swagger';
|
||||
import swaggerUi from '@fastify/swagger-ui';
|
||||
import websocket from '@fastify/websocket';
|
||||
import multipart from '@fastify/multipart';
|
||||
import { createClient } from 'redis';
|
||||
import { ZodError } from 'zod';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import type { AppConfig } from './config.js';
|
||||
import { AppError } from './lib/errors.js';
|
||||
import { SettingsService } from './modules/settings.service.js';
|
||||
import { MessagingService } from './modules/messaging.service.js';
|
||||
import { VerificationService } from './modules/verification.service.js';
|
||||
import { TranscoderService } from './modules/transcoder.service.js';
|
||||
import { authRoutes } from './modules/auth.routes.js';
|
||||
import { roomRoutes } from './modules/rooms.routes.js';
|
||||
import { mediaRoutes } from './modules/media.routes.js';
|
||||
import { adminRoutes } from './modules/admin.routes.js';
|
||||
import { chatRoutes } from './modules/chat.routes.js';
|
||||
import { uploadRoutes } from './modules/uploads.routes.js';
|
||||
|
||||
export async function buildApp(config: AppConfig, db: PrismaClient) {
|
||||
const app = Fastify({
|
||||
logger: { level: config.APP_ENV === 'production' ? 'info' : 'debug', redact: ['req.headers.authorization', 'req.headers.cookie', '*.password', '*.token', '*.accessKeySecret', '*.streamKey'] },
|
||||
genReqId: req => String(req.headers['x-request-id'] ?? crypto.randomUUID())
|
||||
});
|
||||
const redis = createClient({ url: config.REDIS_URL });
|
||||
redis.on('error', error => app.log.error({ err: error }, 'Redis connection error'));
|
||||
await redis.connect();
|
||||
const settings = new SettingsService(db, config);
|
||||
const messaging = new MessagingService(settings);
|
||||
const verification = new VerificationService(db, redis, messaging);
|
||||
const transcoder = new TranscoderService(settings);
|
||||
|
||||
await app.register(cookie);
|
||||
await app.register(cors, { origin: config.APP_ENV === 'development' ? true : false, credentials: true });
|
||||
await app.register(helmet, { contentSecurityPolicy: false });
|
||||
await app.register(jwt, { secret: config.JWT_SECRET, cookie: { cookieName: 'xlive_access', signed: false } });
|
||||
await app.register(rateLimit, { max: 300, timeWindow: '1 minute', keyGenerator: request => request.ip });
|
||||
await app.register(websocket);
|
||||
await app.register(multipart, { limits: { fileSize: 5 * 1024 * 1024, files: 1 } });
|
||||
await app.register(swagger, { openapi: { info: { title: 'XLive API', version: '1.0.0', description: 'XLive 多用户直播平台 REST API' }, tags: [{ name: 'auth' }, { name: 'rooms' }, { name: 'admin' }] } });
|
||||
await app.register(swaggerUi, { routePrefix: '/api/docs' });
|
||||
|
||||
app.addHook('onSend', async (request, reply, payload) => { reply.header('x-request-id', request.id); return payload; });
|
||||
app.setErrorHandler((error, request, reply) => {
|
||||
if (error instanceof ZodError) return reply.code(422).send({ code: 'VALIDATION_ERROR', message: '请求参数不正确', details: error.issues.map(i => ({ path: i.path.join('.'), message: i.message })), requestId: request.id });
|
||||
if (error instanceof AppError) return reply.code(error.status).send({ code: error.code, message: error.message, requestId: request.id });
|
||||
if ((error as { code?: string }).code === 'P2002') return reply.code(409).send({ code: 'DUPLICATE_RESOURCE', message: '数据已存在', requestId: request.id });
|
||||
if ((error as { statusCode?: number }).statusCode && (error as { statusCode: number }).statusCode < 500) return reply.code((error as { statusCode: number }).statusCode).send({ code: 'BAD_REQUEST', message: '请求格式不正确', requestId: request.id });
|
||||
request.log.error({ err: error }, 'Unhandled request error');
|
||||
return reply.code(500).send({ code: 'INTERNAL_ERROR', message: '服务器内部错误', requestId: request.id });
|
||||
});
|
||||
|
||||
app.get('/health', async (_request, reply) => {
|
||||
try { await db.$queryRaw`SELECT 1`; await redis.ping(); return { status: 'ok', components: { application: 'up', database: 'up', redis: 'up' } }; }
|
||||
catch { return reply.code(503).send({ status: 'degraded' }); }
|
||||
});
|
||||
app.get('/api/settings/public', async () => ({ data: await settings.publicSettings() }));
|
||||
|
||||
await authRoutes(app, { db, config, settings, verification });
|
||||
await roomRoutes(app, { db, redis, config, settings, transcoder });
|
||||
await mediaRoutes(app, { db, config, settings, transcoder });
|
||||
await chatRoutes(app, db);
|
||||
await uploadRoutes(app, { db, config });
|
||||
await adminRoutes(app, { db, redis, config, settings, messaging });
|
||||
|
||||
app.addHook('onClose', async () => { await redis.quit(); });
|
||||
return app;
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { z } from 'zod';
|
||||
|
||||
const schema = z.object({
|
||||
APP_ENV: z.enum(['development', 'test', 'production']).default('development'),
|
||||
APP_PORT: z.coerce.number().int().min(1).max(65535).default(3000),
|
||||
DATABASE_URL: z.string().min(1),
|
||||
REDIS_URL: z.string().min(1),
|
||||
JWT_SECRET: z.string().min(32),
|
||||
CONFIG_ENCRYPTION_KEY: z.string().min(16),
|
||||
COOKIE_SECURE: z.string().default('false').transform(v => v === 'true'),
|
||||
ADMIN_USERNAME: z.string().min(3).default('admin'),
|
||||
ADMIN_PASSWORD: z.string().min(8),
|
||||
ADMIN_EMAIL: z.string().email(),
|
||||
SRS_API_URL: z.string().url().default('http://srs:1985'),
|
||||
SRS_HOOK_SECRET: z.string().min(12),
|
||||
RTMP_PUBLIC_URL: z.string().default(''),
|
||||
RTMP_PORT: z.coerce.number().int().min(1).max(65535).default(1935),
|
||||
HLS_PUBLIC_URL: z.string().default('http://localhost/live'),
|
||||
UPLOAD_DIR: z.string().default('./uploads'),
|
||||
LIVE_DIR: z.string().default('./live')
|
||||
});
|
||||
|
||||
export type AppConfig = z.infer<typeof schema>;
|
||||
export const loadConfig = (): AppConfig => schema.parse(process.env);
|
||||
@@ -0,0 +1,31 @@
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify';
|
||||
import type { RoleName } from '@prisma/client';
|
||||
import { AppError } from './errors.js';
|
||||
|
||||
type TokenPayload = { sub: string; roles: RoleName[]; type: 'access' };
|
||||
|
||||
export async function authenticate(request: FastifyRequest): Promise<void> {
|
||||
try {
|
||||
const payload = await request.jwtVerify<TokenPayload>();
|
||||
if (payload.type !== 'access') throw new Error('wrong token type');
|
||||
request.auth = { userId: payload.sub, roles: payload.roles };
|
||||
} catch { throw new AppError('UNAUTHORIZED', '请先登录', 401); }
|
||||
}
|
||||
|
||||
export const requireRoles = (...roles: RoleName[]) => async (request: FastifyRequest) => {
|
||||
await authenticate(request);
|
||||
if (!roles.some(role => request.auth!.roles.includes(role))) throw new AppError('FORBIDDEN', '没有执行此操作的权限', 403);
|
||||
};
|
||||
|
||||
export function setAccessCookie(reply: FastifyReply, token: string, secure: boolean) {
|
||||
reply.setCookie('xlive_access', token, { httpOnly: true, secure, sameSite: 'lax', path: '/', maxAge: 15 * 60 });
|
||||
}
|
||||
|
||||
export function setRefreshCookie(reply: FastifyReply, token: string, secure: boolean) {
|
||||
reply.setCookie('xlive_refresh', token, { httpOnly: true, secure, sameSite: 'strict', path: '/api/auth', maxAge: 30 * 24 * 3600 });
|
||||
}
|
||||
|
||||
export function clearAuthCookies(reply: FastifyReply) {
|
||||
reply.clearCookie('xlive_access', { path: '/' });
|
||||
reply.clearCookie('xlive_refresh', { path: '/api/auth' });
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { decrypt, encrypt, sha256 } from './crypto.js';
|
||||
describe('secret protection',()=>{it('uses authenticated encryption',()=>{const secret='unit-test-key-that-is-long-enough',plain='smtp-password';const cipher=encrypt(plain,secret);expect(cipher).not.toContain(plain);expect(decrypt(cipher,secret)).toBe(plain)});it('hashes deterministically',()=>expect(sha256('a')).toBe(sha256('a')))});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
||||
|
||||
export const sha256 = (value: string) => createHash('sha256').update(value).digest('hex');
|
||||
export const randomToken = (bytes = 32) => randomBytes(bytes).toString('base64url');
|
||||
export const randomCode = () => String(Math.floor(100000 + Math.random() * 900000));
|
||||
|
||||
const deriveKey = (secret: string) => createHash('sha256').update(secret).digest();
|
||||
|
||||
export function encrypt(value: string, secret: string): string {
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', deriveKey(secret), iv);
|
||||
const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
|
||||
return ['v1', iv.toString('base64url'), cipher.getAuthTag().toString('base64url'), encrypted.toString('base64url')].join('.');
|
||||
}
|
||||
|
||||
export function decrypt(value: string, secret: string): string {
|
||||
const [version, iv, tag, payload] = value.split('.');
|
||||
if (version !== 'v1' || !iv || !tag || !payload) throw new Error('Invalid encrypted value');
|
||||
const decipher = createDecipheriv('aes-256-gcm', deriveKey(secret), Buffer.from(iv, 'base64url'));
|
||||
decipher.setAuthTag(Buffer.from(tag, 'base64url'));
|
||||
return Buffer.concat([decipher.update(Buffer.from(payload, 'base64url')), decipher.final()]).toString('utf8');
|
||||
}
|
||||
|
||||
export const safeEqual = (a: string, b: string) => {
|
||||
const aa = Buffer.from(a); const bb = Buffer.from(b);
|
||||
return aa.length === bb.length && timingSafeEqual(aa, bb);
|
||||
};
|
||||
|
||||
export const hmacSha1Base64 = (key: string, value: string) => createHmac('sha1', key).update(value).digest('base64');
|
||||
@@ -0,0 +1,5 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
|
||||
export const prisma = new PrismaClient({
|
||||
log: process.env.APP_ENV === 'development' ? ['warn', 'error'] : ['error']
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
export class AppError extends Error {
|
||||
constructor(public code: string, message: string, public status = 400) { super(message); }
|
||||
}
|
||||
|
||||
export function assert(condition: unknown, code: string, message: string, status = 400): asserts condition {
|
||||
if (!condition) throw new AppError(code, message, status);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { defaultPasswordPolicy, hashPassword, validatePassword, verifyPassword } from './password.js';
|
||||
|
||||
describe('password policy and hashing', () => {
|
||||
it('accepts a compliant password', () => expect(() => validatePassword('ValidPass123', defaultPasswordPolicy)).not.toThrow());
|
||||
it.each(['short', 'alllowercase1', 'ALLUPPERCASE1', 'NoNumbersHere'])('rejects non-compliant password %s', value => expect(() => validatePassword(value, defaultPasswordPolicy)).toThrow());
|
||||
it('uses salted Argon2id hashes', async () => { const a=await hashPassword('ValidPass123'); const b=await hashPassword('ValidPass123'); expect(a).not.toBe(b); expect(a).toContain('argon2id'); expect(await verifyPassword(a,'ValidPass123')).toBe(true); });
|
||||
});
|
||||
@@ -0,0 +1,22 @@
|
||||
import argon2 from 'argon2';
|
||||
import { AppError } from './errors.js';
|
||||
|
||||
export type PasswordPolicy = {
|
||||
minLength: number; maxLength: number; uppercase: boolean; lowercase: boolean; number: boolean; special: boolean;
|
||||
};
|
||||
|
||||
export const defaultPasswordPolicy: PasswordPolicy = { minLength: 8, maxLength: 64, uppercase: true, lowercase: true, number: true, special: false };
|
||||
|
||||
export function validatePassword(password: string, policy: PasswordPolicy): void {
|
||||
const failures: string[] = [];
|
||||
if (password.length < policy.minLength) failures.push(`至少 ${policy.minLength} 位`);
|
||||
if (password.length > policy.maxLength) failures.push(`最多 ${policy.maxLength} 位`);
|
||||
if (policy.uppercase && !/[A-Z]/.test(password)) failures.push('包含大写字母');
|
||||
if (policy.lowercase && !/[a-z]/.test(password)) failures.push('包含小写字母');
|
||||
if (policy.number && !/\d/.test(password)) failures.push('包含数字');
|
||||
if (policy.special && !/[^A-Za-z0-9]/.test(password)) failures.push('包含特殊字符');
|
||||
if (failures.length) throw new AppError('PASSWORD_POLICY_VIOLATION', `密码必须${failures.join('、')}`);
|
||||
}
|
||||
|
||||
export const hashPassword = (password: string) => argon2.hash(password, { type: argon2.argon2id, memoryCost: 19456, timeCost: 2, parallelism: 1 });
|
||||
export const verifyPassword = (hash: string, password: string) => argon2.verify(hash, password);
|
||||
@@ -0,0 +1,11 @@
|
||||
export interface RedisLike {
|
||||
ping(): Promise<string>;
|
||||
info(section?: string): Promise<string>;
|
||||
exists(key: string): Promise<number>;
|
||||
incr(key: string): Promise<number>;
|
||||
expire(key: string, seconds: number): Promise<number>;
|
||||
set(key: string, value: string, options?: { EX?: number }): Promise<string | null>;
|
||||
zAdd(key: string, members: { score: number; value: string }): Promise<number>;
|
||||
zRemRangeByScore(key: string, min: number, max: number): Promise<number>;
|
||||
zCard(key: string): Promise<number>;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { createReadStream } from 'node:fs';
|
||||
import { unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { RedisLike } from '../lib/redis.js';
|
||||
import { z } from 'zod';
|
||||
import si from 'systeminformation';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
import type { MessagingService } from './messaging.service.js';
|
||||
import { requireRoles } from '../lib/auth.js';
|
||||
import { assert } from '../lib/errors.js';
|
||||
import { stopSrsStream } from './rooms.routes.js';
|
||||
import { hashPassword, validatePassword } from '../lib/password.js';
|
||||
|
||||
const admin = requireRoles('ADMIN', 'SUPER_ADMIN'); const superAdmin = requireRoles('SUPER_ADMIN');
|
||||
const log = (db: PrismaClient, request: { auth?: { userId: string }; ip: string; id: string }, action: string, targetType?: string, targetId?: string, details?: object) => db.adminLog.create({ data: { adminId: request.auth!.userId, action, targetType, targetId, details, result: 'SUCCESS', ip: request.ip, requestId: request.id } });
|
||||
|
||||
export async function adminRoutes(app: FastifyInstance, deps: { db: PrismaClient; redis: RedisLike; config: AppConfig; settings: SettingsService; messaging: MessagingService }) {
|
||||
const { db, redis, config, settings, messaging } = deps;
|
||||
app.get('/api/admin/dashboard', { preHandler: admin }, async () => {
|
||||
const start = new Date(); start.setHours(0, 0, 0, 0);
|
||||
const [users, todayUsers, live, rooms, todaySessions, viewers, cpu, memory, fs] = await Promise.all([db.user.count(), db.user.count({ where: { createdAt: { gte: start } } }), db.room.count({ where: { streamStatus: 'LIVE' } }), db.room.count(), db.liveSession.count({ where: { startedAt: { gte: start } } }), db.room.aggregate({ _sum: { viewerCount: true } }), si.currentLoad(), si.mem(), si.fsSize()]);
|
||||
const dbVersion = await db.$queryRaw<Array<{ version: string }>>`SELECT version()`; const redisInfo = await redis.info('server'); const redisVersion = /redis_version:([^\r\n]+)/.exec(redisInfo)?.[1] ?? 'unknown'; let mediaVersion='unavailable'; try { const response=await fetch(`${config.SRS_API_URL}/api/v1/versions`); if(response.ok){const body=await response.json() as {data?:{major?:number;minor?:number;revision?:number}};mediaVersion=body.data?`${body.data.major}.${body.data.minor}.${body.data.revision}`:'connected';} } catch {}
|
||||
return { data: { metrics: { users, todayUsers, live, rooms, todaySessions, viewers: viewers._sum.viewerCount ?? 0 }, system: { node: process.version, postgres: dbVersion[0]?.version, redis: redisVersion, mediaServer: mediaVersion, platform: `${process.platform} ${process.arch}`, uptimeSeconds: Math.floor(process.uptime()), cpuUsage: Math.round(cpu.currentLoad * 10) / 10, memory: { total: memory.total, used: memory.active, free: memory.available }, disks: fs.map(x => ({ mount: x.mount, size: x.size, used: x.used, use: x.use })) } } };
|
||||
});
|
||||
|
||||
app.get('/api/admin/health', { preHandler: admin }, async () => {
|
||||
const result: Record<string, { status: string; detail?: string }> = { application: { status: '正常' } };
|
||||
try { await db.$queryRaw`SELECT 1`; result.database={status:'正常'}; } catch { result.database={status:'异常'}; }
|
||||
try { await redis.ping(); result.redis={status:'正常'}; } catch { result.redis={status:'异常'}; }
|
||||
try { const r=await fetch(`${config.SRS_API_URL}/api/v1/versions`); result.mediaServer={status:r.ok?'正常':'异常'}; } catch { result.mediaServer={status:'异常'}; }
|
||||
const all=await settings.all(false); result.smtp={status:all['smtp.host']?'已配置':'未配置'}; result.sms={status:all['sms.accessKeyId']?'已配置':'未配置'};
|
||||
return { data: result };
|
||||
});
|
||||
|
||||
app.get('/api/admin/users', { preHandler: admin }, async request => { const q = z.object({ search: z.string().optional(), page: z.coerce.number().default(1), limit: z.coerce.number().max(100).default(20) }).parse(request.query); const where = q.search ? { OR: [{ username: { contains: q.search, mode: 'insensitive' as const } }, { nickname: { contains: q.search, mode: 'insensitive' as const } }, { email: { contains: q.search, mode: 'insensitive' as const } }] } : {}; const [items, total] = await Promise.all([db.user.findMany({ where, select: { id: true, username: true, nickname: true, avatar: true, email: true, phone: true, status: true, canStream: true, registerIp: true, createdAt: true, lastLoginIp: true, lastLoginAt: true, roles: { select: { role: { select: { name: true } } } }, bans: { where: { revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] }, select: { id: true, type: true, reason: true, expiresAt: true } } }, skip: (q.page - 1) * q.limit, take: q.limit, orderBy: { createdAt: 'desc' } }), db.user.count({ where })]); return { data: items.map(u => ({ ...u, phone: u.phone ? `${u.phone.slice(0, 3)}****${u.phone.slice(-4)}` : null })), meta: { total } }; });
|
||||
app.delete('/api/admin/users/:id', { preHandler: superAdmin }, async request => { const { id }=z.object({id:z.string().uuid()}).parse(request.params); assert(id!==request.auth!.userId,'CANNOT_DELETE_SELF','不能删除当前登录账号',409); await db.$transaction([db.refreshToken.updateMany({where:{userId:id},data:{revokedAt:new Date()}}),db.user.update({where:{id},data:{status:'DELETED',email:null,phone:null,canStream:false}})]); await log(db,request,'DELETE_USER','USER',id); return {data:{deleted:true}}; });
|
||||
app.patch('/api/admin/users/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const input = z.object({ status: z.enum(['ACTIVE', 'DISABLED']).optional(), canStream: z.boolean().optional(), nickname: z.string().min(1).max(64).optional() }).parse(request.body); const user = await db.user.update({ where: { id }, data: input }); if (input.canStream === false) { const rooms = await db.room.findMany({ where: { ownerId: id, streamStatus: 'LIVE' } }); await Promise.all(rooms.map(r => stopSrsStream(config, `room_${r.roomNumber}`))); } await log(db, request, 'UPDATE_USER', 'USER', id, input); return { data: user }; });
|
||||
app.post('/api/admin/users/:id/reset-password', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const { password } = z.object({ password: z.string() }).parse(request.body); validatePassword(password, await settings.passwordPolicy()); await db.$transaction([db.user.update({ where: { id }, data: { passwordHash: await hashPassword(password) } }), db.refreshToken.updateMany({ where: { userId: id }, data: { revokedAt: new Date() } })]); await log(db, request, 'RESET_USER_PASSWORD', 'USER', id); return { data: { reset: true } }; });
|
||||
app.post('/api/admin/users/:id/chat-ban', { preHandler: admin }, async request => { const {id}=z.object({id:z.string().uuid()}).parse(request.params); const input=z.object({minutes:z.number().int().min(1).max(525600).default(60),reason:z.string().max(500).optional()}).parse(request.body); const ban=await db.ban.create({data:{userId:id,type:'CHAT',reason:input.reason,expiresAt:new Date(Date.now()+input.minutes*60000),createdBy:request.auth!.userId}}); await log(db,request,'MUTE_USER','USER',id,{minutes:input.minutes}); return {data:ban}; });
|
||||
app.delete('/api/admin/bans/:id', { preHandler: admin }, async request => { const {id}=z.object({id:z.string().uuid()}).parse(request.params); const ban=await db.ban.update({where:{id},data:{revokedAt:new Date()}}); await log(db,request,'REVOKE_BAN','BAN',id); return {data:ban}; });
|
||||
|
||||
app.get('/api/admin/rooms', { preHandler: admin }, async () => ({ data: await db.room.findMany({ include: { owner: { select: { id: true, username: true, nickname: true, avatar: true } }, category: true }, orderBy: { updatedAt: 'desc' } }) }));
|
||||
app.patch('/api/admin/rooms/:roomNumber', { preHandler: admin }, async request => { const {roomNumber}=z.object({roomNumber:z.coerce.number()}).parse(request.params); const input=z.object({featured:z.boolean().optional(),visibility:z.enum(['PUBLIC','PRIVATE']).optional(),title:z.string().min(1).max(120).optional()}).parse(request.body); const room=await db.room.update({where:{roomNumber},data:input}); await log(db,request,'UPDATE_ROOM','ROOM',String(roomNumber),input); return {data:room}; });
|
||||
app.delete('/api/admin/rooms/:roomNumber', { preHandler: admin }, async request => { const {roomNumber}=z.object({roomNumber:z.coerce.number()}).parse(request.params); const room=await db.room.findUnique({where:{roomNumber}}); assert(room,'ROOM_NOT_FOUND','直播间不存在',404); if(room.streamStatus==='LIVE')await stopSrsStream(config,`room_${roomNumber}`); await db.room.delete({where:{id:room.id}}); await log(db,request,'DELETE_ROOM','ROOM',String(roomNumber)); return {data:{deleted:true}}; });
|
||||
app.get('/api/admin/sessions', { preHandler: admin }, async () => ({ data: await db.liveSession.findMany({ take: 200, orderBy: { startedAt: 'desc' }, select: { id: true, startedAt: true, endedAt: true, durationSeconds: true, peakViewers: true, totalViews: true, recordingUrl: true, room: { select: { roomNumber: true, title: true, owner: { select: { nickname: true } } } } } }) }));
|
||||
app.get('/api/admin/messages', { preHandler: admin }, async () => ({ data: await db.chatMessage.findMany({ take: 200, orderBy: { createdAt: 'desc' }, include: { room: { select: { roomNumber: true, title: true } } } }) }));
|
||||
app.get('/api/admin/notices', { preHandler: admin }, async () => ({ data: await db.notice.findMany({ take: 200, orderBy: { createdAt: 'desc' }, include: { from: { select: { id: true, username: true, nickname: true } } } }) }));
|
||||
app.post('/api/admin/notices/:id/approve', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const notice = await db.notice.findUnique({ where: { id } }); assert(notice, 'NOTICE_NOT_FOUND', '申请不存在', 404); assert(notice.status === 'PENDING', 'NOTICE_ALREADY_HANDLED', '该申请已处理'); await db.$transaction([db.notice.update({ where: { id }, data: { status: 'APPROVED', handledAt: new Date(), handledBy: request.auth!.userId } }), db.user.update({ where: { id: notice.fromId }, data: { canStream: true } })]); await log(db, request, 'APPROVE_STREAM_PERMISSION', 'NOTICE', id); return { data: { approved: true } }; });
|
||||
app.post('/api/admin/notices/:id/reject', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const notice = await db.notice.findUnique({ where: { id } }); assert(notice, 'NOTICE_NOT_FOUND', '申请不存在', 404); assert(notice.status === 'PENDING', 'NOTICE_ALREADY_HANDLED', '该申请已处理'); await db.notice.update({ where: { id }, data: { status: 'REJECTED', handledAt: new Date(), handledBy: request.auth!.userId } }); await log(db, request, 'REJECT_STREAM_PERMISSION', 'NOTICE', id); return { data: { rejected: true } }; });
|
||||
app.get('/api/admin/files', { preHandler: admin }, async request => { const q = z.object({ page: z.coerce.number().default(1), limit: z.coerce.number().max(100).default(100) }).parse(request.query); const [items, total] = await Promise.all([db.upload.findMany({ include: { uploader: { select: { id: true, nickname: true } } }, skip: (q.page - 1) * q.limit, take: q.limit, orderBy: { createdAt: 'desc' } }), db.upload.count()]); return { data: items, meta: { total } }; });
|
||||
app.delete('/api/admin/files/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const file = await db.upload.findUnique({ where: { id } }); assert(file, 'FILE_NOT_FOUND', '文件不存在', 404); await unlink(join(config.UPLOAD_DIR, file.filename)).catch(error => request.log.error({ err: error }, 'delete upload file failed')); await db.upload.delete({ where: { id } }); await log(db, request, 'DELETE_UPLOAD', 'UPLOAD', id, { filename: file.filename }); return { data: { deleted: true } }; });
|
||||
app.get('/api/admin/files/:id/download', { preHandler: admin }, async (request, reply) => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const file = await db.upload.findUnique({ where: { id } }); assert(file, 'FILE_NOT_FOUND', '文件不存在', 404); const name = (file.originalName ?? file.filename).replace(/["\\\r\n]/g, '_'); reply.header('content-disposition', `attachment; filename*=UTF-8''${encodeURIComponent(name)}`).type(file.mimeType); return reply.send(createReadStream(join(config.UPLOAD_DIR, file.filename))); });
|
||||
app.get('/api/admin/replays', { preHandler: admin }, async request => { const q = z.object({ page: z.coerce.number().default(1), limit: z.coerce.number().max(100).default(100) }).parse(request.query); const [items, total] = await Promise.all([db.liveSession.findMany({ where: { recordingUrl: { not: null } }, skip: (q.page - 1) * q.limit, take: q.limit, orderBy: { startedAt: 'desc' }, select: { id: true, startedAt: true, endedAt: true, durationSeconds: true, peakViewers: true, totalViews: true, recordingUrl: true, recordingSize: true, room: { select: { roomNumber: true, title: true, owner: { select: { nickname: true } } } } } }), db.liveSession.count({ where: { recordingUrl: { not: null } } })]); return { data: items.map(s => ({ ...s, recordingSize: s.recordingSize?.toString() ?? null })), meta: { total } }; });
|
||||
app.delete('/api/admin/replays/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const session = await db.liveSession.findUnique({ where: { id } }); assert(session?.recordingUrl, 'REPLAY_NOT_FOUND', '该场次没有回放', 404); const fileName = session.recordingUrl.split(/[\\/]/).pop(); if (fileName && /^room_\d+\.\d+\.flv$/.test(fileName)) await unlink(join(config.LIVE_DIR, 'replays', fileName)).catch(error => request.log.error({ err: error }, 'delete replay file failed')); await db.liveSession.update({ where: { id }, data: { recordingUrl: null, recordingSize: null } }); await log(db, request, 'DELETE_REPLAY', 'SESSION', id, { file: fileName }); return { data: { deleted: true } }; });
|
||||
app.get('/api/admin/replays/:id/download', { preHandler: admin }, async (request, reply) => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); const session = await db.liveSession.findUnique({ where: { id } }); assert(session?.recordingUrl, 'REPLAY_NOT_FOUND', '该场次没有回放', 404); const fileName = session.recordingUrl.split(/[\\/]/).pop(); assert(fileName && /^room_\d+\.\d+\.flv$/.test(fileName), 'RECORDING_PATH_INVALID', '回放文件路径无效', 422); reply.header('content-disposition', `attachment; filename="${fileName}"`).type('video/x-flv'); return reply.send(createReadStream(join(config.LIVE_DIR, 'replays', fileName))); });
|
||||
app.post('/api/admin/rooms/:roomNumber/stop', { preHandler: admin }, async request => { const { roomNumber } = z.object({ roomNumber: z.coerce.number() }).parse(request.params); const room = await db.room.findUnique({ where: { roomNumber } }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404); const stopped = await stopSrsStream(config, `room_${roomNumber}`); await db.room.update({ where: { id: room.id }, data: { streamStatus: 'OFFLINE', viewerCount: 0 } }); await log(db, request, 'FORCE_STOP_STREAM', 'ROOM', String(roomNumber), { stopped }); return { data: { stopped } }; });
|
||||
app.post('/api/admin/rooms/:roomNumber/ban', { preHandler: admin }, async request => { const { roomNumber } = z.object({ roomNumber: z.coerce.number() }).parse(request.params); const room = await db.room.update({ where: { roomNumber }, data: { liveBanned: true, streamStatus: 'BANNED' } }); await stopSrsStream(config, `room_${roomNumber}`); await log(db, request, 'BAN_ROOM_STREAM', 'ROOM', String(roomNumber)); return { data: room }; });
|
||||
app.post('/api/admin/rooms/:roomNumber/unban', { preHandler: admin }, async request => { const { roomNumber } = z.object({ roomNumber: z.coerce.number() }).parse(request.params); const room = await db.room.update({ where: { roomNumber }, data: { liveBanned: false, streamStatus: 'OFFLINE' } }); await log(db, request, 'UNBAN_ROOM_STREAM', 'ROOM', String(roomNumber)); return { data: room }; });
|
||||
|
||||
app.get('/api/admin/categories', { preHandler: admin }, async () => ({ data: await db.category.findMany({ orderBy: [{ sort: 'asc' }, { id: 'asc' }] }) }));
|
||||
app.post('/api/admin/categories', { preHandler: admin }, async (request, reply) => { const input = z.object({ name: z.string().min(1).max(64), slug: z.string().regex(/^[a-z0-9-]+$/), icon: z.string().max(128).optional(), sort: z.number().int().default(0), enabled: z.boolean().default(true) }).parse(request.body); const item = await db.category.create({ data: input }); await log(db, request, 'CREATE_CATEGORY', 'CATEGORY', String(item.id)); reply.code(201).send({ data: item }); });
|
||||
app.patch('/api/admin/categories/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.coerce.number() }).parse(request.params); const input = z.object({ name: z.string().min(1).max(64), slug: z.string().regex(/^[a-z0-9-]+$/), icon: z.string().max(128).nullable(), sort: z.number().int(), enabled: z.boolean() }).partial().parse(request.body); const item = await db.category.update({ where: { id }, data: input }); await log(db, request, 'UPDATE_CATEGORY', 'CATEGORY', String(id)); return { data: item }; });
|
||||
app.delete('/api/admin/categories/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.coerce.number() }).parse(request.params); assert(await db.room.count({ where: { categoryId: id } }) === 0, 'CATEGORY_IN_USE', '该分类下仍有直播间,不能删除', 409); await db.category.delete({ where: { id } }); await log(db, request, 'DELETE_CATEGORY', 'CATEGORY', String(id)); return { data: { deleted: true } }; });
|
||||
|
||||
app.get('/api/admin/settings', { preHandler: admin }, async () => ({ data: await settings.all(false) }));
|
||||
app.put('/api/admin/settings', { preHandler: superAdmin }, async request => { const { values } = z.object({ values: z.record(z.string(), z.unknown()) }).parse(request.body); await settings.setMany(values, request.auth!.userId); await log(db, request, 'UPDATE_SETTINGS', 'SYSTEM', 'settings', { keys: Object.keys(values) }); return { data: await settings.all(false) }; });
|
||||
app.post('/api/admin/settings/smtp/test', { preHandler: superAdmin }, async request => { const { email } = z.object({ email: z.string().email() }).parse(request.body); const info = await messaging.sendEmail(email, 'XLive SMTP 测试', '如果您收到此邮件,说明 XLive SMTP 配置有效。'); await log(db, request, 'TEST_SMTP', 'SYSTEM', 'smtp', { accepted: info.accepted }); return { data: { sent: true, accepted: info.accepted } }; });
|
||||
app.post('/api/admin/settings/sms/test', { preHandler: superAdmin }, async request => { const { phone } = z.object({ phone: z.string().regex(/^\+?\d{7,15}$/) }).parse(request.body); const code = String(Math.floor(100000 + Math.random() * 900000)); const result = await messaging.sendSmsForPurpose(phone, 'REGISTER', code); await log(db, request, 'TEST_SMS', 'SYSTEM', 'sms', { requestId: result.RequestId }); return { data: { sent: true, requestId: result.RequestId } }; });
|
||||
app.get('/api/admin/logs', { preHandler: admin }, async () => ({ data: (await db.adminLog.findMany({ take: 200, orderBy: { createdAt: 'desc' }, include: { admin: { select: { username: true, nickname: true } } } })).map(item => ({ ...item, id: item.id.toString() })) }));
|
||||
app.get('/api/admin/admins', { preHandler: superAdmin }, async () => ({ data: await db.user.findMany({ where: { roles: { some: { role: { name: { in: ['ADMIN','SUPER_ADMIN'] } } } } }, select: { id:true,username:true,nickname:true,email:true,status:true,createdAt:true,roles:{select:{role:{select:{name:true}}}} }, orderBy:{createdAt:'asc'} }) }));
|
||||
app.patch('/api/admin/admins/:id/role', { preHandler: superAdmin }, async request => { const {id}=z.object({id:z.string().uuid()}).parse(request.params); const {role}=z.object({role:z.enum(['ADMIN','SUPER_ADMIN'])}).parse(request.body); assert(id!==request.auth!.userId,'CANNOT_CHANGE_SELF_ROLE','不能修改当前登录账号的角色',409); const target=await db.user.findUnique({where:{id}}); assert(target,'USER_NOT_FOUND','用户不存在',404); await db.$transaction(async tx=>{const selectedRole=await tx.role.findUniqueOrThrow({where:{name:role}}); await tx.userRole.deleteMany({where:{userId:id,role:{name:{in:['ADMIN','SUPER_ADMIN']}}}}); await tx.userRole.create({data:{userId:id,roleId:selectedRole.id}})}); await log(db,request,'CHANGE_ADMIN_ROLE','USER',id,{role}); return {data:{updated:true}}; });
|
||||
app.delete('/api/admin/messages/:id', { preHandler: admin }, async request => { const { id } = z.object({ id: z.string().uuid() }).parse(request.params); await db.chatMessage.update({ where: { id }, data: { deletedAt: new Date(), deletedBy: request.auth!.userId } }); await log(db, request, 'DELETE_CHAT_MESSAGE', 'CHAT_MESSAGE', id); return { data: { deleted: true } }; });
|
||||
app.post('/api/admin/admins', { preHandler: superAdmin }, async (request, reply) => { const input = z.object({ username: z.string().min(3).max(32), nickname: z.string().min(1).max(64), email: z.string().email(), password: z.string(), role: z.enum(['ADMIN', 'SUPER_ADMIN']).default('ADMIN') }).parse(request.body); validatePassword(input.password, await settings.passwordPolicy()); const user = await db.user.create({ data: { username: input.username, nickname: input.nickname, email: input.email.toLowerCase(), passwordHash: await hashPassword(input.password), roles: { create: { role: { connect: { name: input.role } } } } } }); await log(db, request, 'CREATE_ADMIN', 'USER', user.id, { role: input.role }); reply.code(201).send({ data: { id: user.id } }); });
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient, RoleName } from '@prisma/client';
|
||||
import { z } from 'zod';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
import type { VerificationService } from './verification.service.js';
|
||||
import { AppError, assert } from '../lib/errors.js';
|
||||
import { hashPassword, validatePassword, verifyPassword } from '../lib/password.js';
|
||||
import { clearAuthCookies, authenticate, setAccessCookie, setRefreshCookie } from '../lib/auth.js';
|
||||
import { randomToken, sha256 } from '../lib/crypto.js';
|
||||
|
||||
const registerSchema = z.object({ username: z.string().min(3).max(32).regex(/^[a-zA-Z0-9_]+$/), nickname: z.string().min(1).max(64), email: z.string().email().optional(), phone: z.string().regex(/^\+?\d{7,15}$/).optional(), password: z.string().min(1), emailCode: z.string().length(6).optional(), smsCode: z.string().length(6).optional() });
|
||||
const loginSchema = z.object({ account: z.string().min(1).max(254), password: z.string().min(1).max(128) });
|
||||
|
||||
function safeUser(user: { id: string; username: string; nickname: string; avatar: string | null; email: string | null; phone: string | null; status: string; canStream: boolean; createdAt: Date; roles: { role: { name: RoleName } }[] }) {
|
||||
return { id: user.id, username: user.username, nickname: user.nickname, avatar: user.avatar, email: user.email, phone: user.phone ? `${user.phone.slice(0, 3)}****${user.phone.slice(-4)}` : null, status: user.status, canStream: user.canStream, createdAt: user.createdAt, roles: user.roles.map(r => r.role.name) };
|
||||
}
|
||||
|
||||
export async function authRoutes(app: FastifyInstance, deps: { db: PrismaClient; config: AppConfig; settings: SettingsService; verification: VerificationService }) {
|
||||
const { db, config, settings, verification } = deps;
|
||||
|
||||
app.post('/api/auth/register', async (request, reply) => {
|
||||
const input = registerSchema.parse(request.body); const options = await settings.all(false);
|
||||
const emailEnabled = Boolean(options['auth.register.email']); const smsEnabled = Boolean(options['auth.register.sms']);
|
||||
assert(emailEnabled || smsEnabled, 'REGISTRATION_DISABLED', '网站暂未开放注册', 403);
|
||||
assert(!input.email || emailEnabled, 'EMAIL_REGISTRATION_DISABLED', '未开放邮箱注册');
|
||||
assert(!input.phone || smsEnabled, 'SMS_REGISTRATION_DISABLED', '未开放手机号注册');
|
||||
const rule = String(options['auth.register.rule'] ?? 'ANY');
|
||||
if (emailEnabled && smsEnabled && rule === 'ALL') assert(input.email && input.phone, 'CONTACT_REQUIRED', '邮箱和手机号均为必填项');
|
||||
else assert((emailEnabled && input.email) || (smsEnabled && input.phone), 'CONTACT_REQUIRED', '请填写可用的邮箱或手机号');
|
||||
if (options['auth.register.requireVerification']) {
|
||||
if (rule === 'ALL') { assert(input.emailCode && input.smsCode, 'VERIFICATION_CODE_REQUIRED', '请输入邮箱和短信验证码'); await verification.verify('EMAIL', input.email!, 'REGISTER', input.emailCode); await verification.verify('SMS', input.phone!, 'REGISTER', input.smsCode); }
|
||||
else if (input.email && input.emailCode) await verification.verify('EMAIL', input.email, 'REGISTER', input.emailCode);
|
||||
else if (input.phone && input.smsCode) await verification.verify('SMS', input.phone, 'REGISTER', input.smsCode);
|
||||
else throw new AppError('VERIFICATION_CODE_REQUIRED', '请至少完成一种验证码验证');
|
||||
}
|
||||
validatePassword(input.password, await settings.passwordPolicy());
|
||||
const existing = await db.user.findFirst({ where: { OR: [{ username: input.username }, ...(input.email ? [{ email: input.email.toLowerCase() }] : []), ...(input.phone ? [{ phone: input.phone }] : [])] } });
|
||||
assert(!existing, 'ACCOUNT_EXISTS', '用户名、邮箱或手机号已被使用', 409);
|
||||
const canStream = await settings.get<boolean>('live.newUserCanStream', false);
|
||||
const user = await db.user.create({ data: { username: input.username, nickname: input.nickname, email: input.email?.toLowerCase(), phone: input.phone, passwordHash: await hashPassword(input.password), canStream, registerIp: request.ip, roles: { create: { role: { connect: { name: 'USER' } } } } }, include: { roles: { include: { role: true } } } });
|
||||
reply.code(201).send({ data: safeUser(user) });
|
||||
});
|
||||
|
||||
app.post('/api/auth/login', async (request, reply) => {
|
||||
const input = loginSchema.parse(request.body); const now = new Date();
|
||||
const user = await db.user.findFirst({ where: { OR: [{ username: input.account }, { email: input.account.toLowerCase() }, { phone: input.account }] }, include: { roles: { include: { role: true } } } });
|
||||
const fail = async (reason: string) => {
|
||||
await db.loginLog.create({ data: { userId: user?.id, account: input.account, success: false, reason, ip: request.ip, userAgent: request.headers['user-agent'] } });
|
||||
throw new AppError('INVALID_CREDENTIALS', '账号或密码错误', 401);
|
||||
};
|
||||
if (!user || !(await verifyPassword(user.passwordHash, input.password))) {
|
||||
if (user) { const max = await settings.get<number>('security.loginMaxFailures', 5); const lockMinutes = await settings.get<number>('security.loginLockMinutes', 15); const count = user.failedLoginCount + 1; await db.user.update({ where: { id: user.id }, data: { failedLoginCount: count >= max ? 0 : count, lockedUntil: count >= max ? new Date(Date.now() + lockMinutes * 60_000) : undefined } }); }
|
||||
return fail('BAD_PASSWORD');
|
||||
}
|
||||
if (user.status !== 'ACTIVE') throw new AppError('ACCOUNT_DISABLED', '账号已被禁用', 403);
|
||||
if (user.lockedUntil && user.lockedUntil > now) throw new AppError('ACCOUNT_TEMPORARILY_LOCKED', `账号暂时锁定至 ${user.lockedUntil.toISOString()}`, 423);
|
||||
const roles = user.roles.map(r => r.role.name);
|
||||
const access = await reply.jwtSign({ sub: user.id, roles, type: 'access' }, { expiresIn: '15m' }); const refresh = randomToken(48);
|
||||
await db.$transaction([db.refreshToken.create({ data: { userId: user.id, tokenHash: sha256(refresh), expiresAt: new Date(Date.now() + 30 * 86400_000), ip: request.ip } }), db.user.update({ where: { id: user.id }, data: { failedLoginCount: 0, lockedUntil: null, lastLoginAt: now, lastLoginIp: request.ip } }), db.loginLog.create({ data: { userId: user.id, account: input.account, success: true, ip: request.ip, userAgent: request.headers['user-agent'] } })]);
|
||||
setAccessCookie(reply, access, config.COOKIE_SECURE); setRefreshCookie(reply, refresh, config.COOKIE_SECURE);
|
||||
return { data: safeUser(user) };
|
||||
});
|
||||
|
||||
app.post('/api/auth/refresh', async (request, reply) => {
|
||||
const token = request.cookies.xlive_refresh; assert(token, 'REFRESH_REQUIRED', '登录状态已过期', 401);
|
||||
const record = await db.refreshToken.findUnique({ where: { tokenHash: sha256(token) }, include: { user: { include: { roles: { include: { role: true } } } } } });
|
||||
assert(record && !record.revokedAt && record.expiresAt > new Date() && record.user.status === 'ACTIVE', 'REFRESH_INVALID', '登录状态已过期', 401);
|
||||
const roles = record.user.roles.map(r => r.role.name); const access = await reply.jwtSign({ sub: record.userId, roles, type: 'access' }, { expiresIn: '15m' });
|
||||
setAccessCookie(reply, access, config.COOKIE_SECURE); return { data: { refreshed: true } };
|
||||
});
|
||||
|
||||
app.post('/api/auth/logout', async (request, reply) => { const token = request.cookies.xlive_refresh; if (token) await db.refreshToken.updateMany({ where: { tokenHash: sha256(token) }, data: { revokedAt: new Date() } }); clearAuthCookies(reply); return { data: { loggedOut: true } }; });
|
||||
app.get('/api/users/me', { preHandler: authenticate }, async request => { const user = await db.user.findUniqueOrThrow({ where: { id: request.auth!.userId }, include: { roles: { include: { role: true } } } }); return { data: safeUser(user) }; });
|
||||
app.patch('/api/users/me', { preHandler: authenticate }, async request => { const input = z.object({ nickname: z.string().min(1).max(64).optional(), bio: z.string().max(500).optional(), avatar: z.string().max(500).refine(v => v === '' || /^https?:\/\/\S+$/.test(v) || v.startsWith('/uploads/'), '头像必须是有效的图片链接').optional() }).parse(request.body); const user = await db.user.update({ where: { id: request.auth!.userId }, data: { ...input, avatar: input.avatar === '' ? null : input.avatar }, include: { roles: { include: { role: true } } } }); return { data: safeUser(user) }; });
|
||||
app.post('/api/auth/change-password', { preHandler: authenticate }, async request => { const input = z.object({ currentPassword: z.string(), newPassword: z.string() }).parse(request.body); const user = await db.user.findUniqueOrThrow({ where: { id: request.auth!.userId } }); assert(await verifyPassword(user.passwordHash, input.currentPassword), 'CURRENT_PASSWORD_INVALID', '当前密码不正确'); validatePassword(input.newPassword, await settings.passwordPolicy()); await db.$transaction([db.user.update({ where: { id: user.id }, data: { passwordHash: await hashPassword(input.newPassword) } }), db.refreshToken.updateMany({ where: { userId: user.id }, data: { revokedAt: new Date() } })]); return { data: { changed: true } }; });
|
||||
app.get('/api/auth/captcha', async () => ({ data: await verification.createCaptcha() }));
|
||||
app.post('/api/auth/email/send-code', async request => { const input = z.object({ email: z.string().email(), purpose: z.enum(['REGISTER', 'LOGIN', 'RESET_PASSWORD']).default('REGISTER'), captchaId: z.string().min(8), captchaText: z.string().min(4).max(8) }).parse(request.body); await verification.requireCaptcha(input.captchaId, input.captchaText); return { data: await verification.send('EMAIL', input.email, input.purpose, request.ip) }; });
|
||||
app.post('/api/auth/sms/send-code', async request => { const input = z.object({ phone: z.string().regex(/^\+?\d{7,15}$/), purpose: z.enum(['REGISTER', 'LOGIN', 'RESET_PASSWORD']).default('REGISTER'), captchaId: z.string().min(8), captchaText: z.string().min(4).max(8) }).parse(request.body); await verification.requireCaptcha(input.captchaId, input.captchaText); return { data: await verification.send('SMS', input.phone, input.purpose, request.ip) }; });
|
||||
app.post('/api/auth/reset-password', async request => { const input = z.object({ channel: z.enum(['EMAIL', 'SMS']), target: z.string(), code: z.string().length(6), newPassword: z.string() }).parse(request.body); await verification.verify(input.channel, input.target, 'RESET_PASSWORD', input.code); validatePassword(input.newPassword, await settings.passwordPolicy()); const where = input.channel === 'EMAIL' ? { email: input.target.toLowerCase() } : { phone: input.target }; const user = await db.user.findFirst({ where }); assert(user, 'ACCOUNT_NOT_FOUND', '账号不存在', 404); await db.$transaction([db.user.update({ where: { id: user.id }, data: { passwordHash: await hashPassword(input.newPassword) } }), db.refreshToken.updateMany({ where: { userId: user.id }, data: { revokedAt: new Date() } })]); return { data: { reset: true } }; });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import Fastify from 'fastify';
|
||||
import cookie from '@fastify/cookie';
|
||||
import jwt from '@fastify/jwt';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { hashPassword } from '../lib/password.js';
|
||||
import { authRoutes } from './auth.routes.js';
|
||||
import { roomRoutes } from './rooms.routes.js';
|
||||
import { SettingsService } from './settings.service.js';
|
||||
|
||||
const config={JWT_SECRET:'test-secret-test-secret-test-secret-123',COOKIE_SECURE:false,CONFIG_ENCRYPTION_KEY:'settings-test-key',RTMP_PUBLIC_URL:'rtmp://localhost/live',HLS_PUBLIC_URL:'http://localhost/live',SRS_API_URL:'http://srs:1985'} as never;
|
||||
const user=(passwordHash:string)=>({id:'1d3ba0bb-5560-4184-9267-4a7ad9012a50',username:'alice',nickname:'Alice',avatar:null,email:'alice@example.com',phone:null,status:'ACTIVE',canStream:true,createdAt:new Date(),failedLoginCount:0,lockedUntil:null,passwordHash,roles:[{role:{name:'USER'}}]});
|
||||
|
||||
describe('authentication routes',()=>{
|
||||
it('registers a valid user',async()=>{const created=user('hash');const db={user:{findFirst:vi.fn().mockResolvedValue(null),create:vi.fn().mockResolvedValue(created)}} as never;const settings={all:vi.fn().mockResolvedValue({'auth.register.email':true,'auth.register.sms':false,'auth.register.requireVerification':false}),passwordPolicy:vi.fn().mockResolvedValue({minLength:8,maxLength:64,uppercase:true,lowercase:true,number:true,special:false}),get:vi.fn().mockResolvedValue(true)} as never;const app=Fastify();await app.register(cookie);await app.register(jwt,{secret:(config as any).JWT_SECRET,cookie:{cookieName:'xlive_access',signed:false}});await authRoutes(app,{db,config,settings,verification:{} as never});const r=await app.inject({method:'POST',url:'/api/auth/register',payload:{username:'alice',nickname:'Alice',email:'alice@example.com',password:'ValidPass123'}});expect(r.statusCode).toBe(201);expect((db as any).user.create).toHaveBeenCalled()});
|
||||
it('logs in and issues HttpOnly cookies',async()=>{const u=user(await hashPassword('ValidPass123'));const db={user:{findFirst:vi.fn().mockResolvedValue(u),update:vi.fn().mockResolvedValue(u)},refreshToken:{create:vi.fn().mockResolvedValue({})},loginLog:{create:vi.fn().mockResolvedValue({})},$transaction:vi.fn(async(items:Promise<unknown>[])=>Promise.all(items))} as never;const settings={get:vi.fn()} as never;const app=Fastify();await app.register(cookie);await app.register(jwt,{secret:(config as any).JWT_SECRET,cookie:{cookieName:'xlive_access',signed:false}});await authRoutes(app,{db,config,settings,verification:{} as never});const r=await app.inject({method:'POST',url:'/api/auth/login',payload:{account:'alice',password:'ValidPass123'}});expect(r.statusCode).toBe(200);expect(String(r.headers['set-cookie'])).toContain('HttpOnly')});
|
||||
});
|
||||
|
||||
describe('room discovery',()=>{it('always filters normal listings to public rooms',async()=>{const db={room:{findMany:vi.fn().mockResolvedValue([]),count:vi.fn().mockResolvedValue(0)},category:{findMany:vi.fn()}} as never;const app=Fastify();await app.register(cookie);await roomRoutes(app,{db,redis:{} as never,config,settings:{} as never});const r=await app.inject({method:'GET',url:'/api/rooms?search=secret'});expect(r.statusCode).toBe(200);expect((db as any).room.findMany.mock.calls[0][0].where.visibility).toBe('PUBLIC')})});
|
||||
|
||||
describe('system settings',()=>{it('never returns sensitive plaintext to admin lists',async()=>{const db={systemSetting:{findMany:vi.fn().mockResolvedValue([{key:'smtp.password',value:'encrypted-value',group:'smtp',sensitive:true}])}} as never;const service=new SettingsService(db,config);const all=await service.all(false);expect(all['smtp.password']).toBe('********')})});
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient, RoleName } from '@prisma/client';
|
||||
import type { WebSocket } from 'ws';
|
||||
import { z } from 'zod';
|
||||
|
||||
type Client = { socket: WebSocket; userId: string | null; nickname: string; avatar: string | null; roles: RoleName[] };
|
||||
const rooms = new Map<number, Set<Client>>();
|
||||
|
||||
export async function chatRoutes(app: FastifyInstance, db: PrismaClient) {
|
||||
app.get('/api/rooms/:roomNumber/chat', { websocket: true }, async (socket, request) => {
|
||||
const roomNumber = Number((request.params as { roomNumber: string }).roomNumber);
|
||||
const room = await db.room.findUnique({ where: { roomNumber } });
|
||||
if (!room) { socket.send(JSON.stringify({ type: 'error', message: '直播间不存在' })); socket.close(1008); return; }
|
||||
|
||||
let user: { id: string; nickname: string; avatar: string | null; status: string } | null = null;
|
||||
let roles: RoleName[] = [];
|
||||
try {
|
||||
const token = await request.jwtVerify<{ sub: string; roles: RoleName[] }>();
|
||||
roles = token.roles;
|
||||
const [account, ban] = await Promise.all([
|
||||
db.user.findUnique({ where: { id: token.sub }, select: { id: true, nickname: true, avatar: true, status: true } }),
|
||||
db.ban.findFirst({ where: { userId: token.sub, type: 'CHAT', revokedAt: null, OR: [{ expiresAt: null }, { expiresAt: { gt: new Date() } }] } })
|
||||
]);
|
||||
if (!account || account.status !== 'ACTIVE' || ban) { socket.send(JSON.stringify({ type: 'error', message: ban ? '您已被禁言' : '账号当前无法参与聊天' })); socket.close(1008); return; }
|
||||
user = account;
|
||||
} catch { /* 游客可接收聊天和弹幕,但不能发送。 */ }
|
||||
|
||||
const client: Client = { socket, userId: user?.id ?? null, nickname: user?.nickname ?? '游客', avatar: user?.avatar ?? null, roles };
|
||||
if (!rooms.has(roomNumber)) rooms.set(roomNumber, new Set()); rooms.get(roomNumber)!.add(client);
|
||||
const history = await db.chatMessage.findMany({ where: { roomId: room.id, deletedAt: null }, orderBy: { createdAt: 'desc' }, take: 50 });
|
||||
socket.send(JSON.stringify({ type: 'history', messages: history.reverse() }));
|
||||
socket.on('message', async raw => {
|
||||
if (!user) { socket.send(JSON.stringify({ type: 'error', message: '请先登录后参与聊天' })); return; }
|
||||
try {
|
||||
const { content } = z.object({ content: z.string().trim().min(1).max(500) }).parse(JSON.parse(raw.toString()));
|
||||
const session = await db.liveSession.findFirst({ where: { roomId: room.id, endedAt: null }, orderBy: { startedAt: 'desc' } });
|
||||
const message = await db.chatMessage.create({ data: { roomId: room.id, userId: user.id, nickname: user.nickname, avatar: user.avatar, content, sessionId: session?.id, offsetSeconds: session ? Math.max(0, (Date.now() - session.startedAt.getTime()) / 1000) : null } });
|
||||
const event = JSON.stringify({ type: 'message', message });
|
||||
for (const peer of rooms.get(roomNumber) ?? []) if (peer.socket.readyState === peer.socket.OPEN) peer.socket.send(event);
|
||||
} catch { socket.send(JSON.stringify({ type: 'error', message: '消息格式不正确或发送失败' })); }
|
||||
});
|
||||
socket.on('close', () => { rooms.get(roomNumber)?.delete(client); if (!rooms.get(roomNumber)?.size) rooms.delete(roomNumber); });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import Fastify from 'fastify';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { mediaRoutes } from './media.routes.js';
|
||||
const config={SRS_HOOK_SECRET:'test-hook-secret',SRS_API_URL:'http://srs:1985'} as never;
|
||||
function mockDb(){const session={id:'s1',startedAt:new Date(Date.now()-5000)};return {room:{findUnique:vi.fn().mockResolvedValue({id:'r1',roomNumber:10001,liveBanned:false,owner:{status:'ACTIVE',canStream:true},streamKey:{keyHash:'73475cb40a568e8da8a045ced110137e159f890ac4da883b6b17dc651b3a8049'}}),count:vi.fn().mockResolvedValue(0),update:vi.fn()},liveSession:{updateMany:vi.fn(),create:vi.fn(),findFirst:vi.fn().mockResolvedValue(session),update:vi.fn()},$transaction:vi.fn(async(arg:unknown)=>typeof arg==='function'?(arg as (tx:unknown)=>unknown)({room:{update:vi.fn()},liveSession:{updateMany:vi.fn(),create:vi.fn()}}):Promise.all(arg as Promise<unknown>[]))} as never}
|
||||
describe('SRS webhooks',()=>{it('rejects invalid stream keys',async()=>{const app=Fastify();await mediaRoutes(app,{db:mockDb(),config});const r=await app.inject({method:'POST',url:'/api/media/hooks?secret=test-hook-secret',payload:{action:'on_publish',app:'live',stream:'room_10001',param:'?token=wrong'}});expect(r.statusCode).toBe(403)});it('records unpublish and marks a room offline',async()=>{const db=mockDb() as any,app=Fastify();await mediaRoutes(app,{db,config});const r=await app.inject({method:'POST',url:'/api/media/hooks?secret=test-hook-secret',payload:{action:'on_unpublish',app:'live',stream:'room_10001'}});expect(r.statusCode).toBe(200);expect(db.room.update).toHaveBeenCalled()})});
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { stat, unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import { z } from 'zod';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { assert } from '../lib/errors.js';
|
||||
import { sha256, safeEqual } from '../lib/crypto.js';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
import type { TranscoderService } from './transcoder.service.js';
|
||||
|
||||
const hookSchema = z.object({ action: z.string(), client_id: z.union([z.string(), z.number()]).optional(), ip: z.string().optional(), vhost: z.string().optional(), app: z.string(), stream: z.string(), param: z.string().optional(), file: z.string().optional(), duration: z.coerce.number().optional(), cwd: z.string().optional() });
|
||||
|
||||
export async function mediaRoutes(app: FastifyInstance, deps: { db: PrismaClient; config: AppConfig; settings?: SettingsService; transcoder?: TranscoderService }) {
|
||||
const { db, config, settings, transcoder } = deps;
|
||||
app.post('/api/media/hooks', async (request, reply) => {
|
||||
const secret = (request.query as { secret?: string }).secret ?? ''; assert(safeEqual(secret, config.SRS_HOOK_SECRET), 'HOOK_UNAUTHORIZED', '无效的媒体服务器签名', 401);
|
||||
const hook = hookSchema.parse(request.body); const match = /^room_(\d+)$/.exec(hook.stream); assert(match, 'STREAM_NAME_INVALID', '无效的流名称', 403); const roomNumber = Number(match[1]);
|
||||
const room = await db.room.findUnique({ where: { roomNumber }, include: { owner: true, streamKey: true } }); assert(room && room.streamKey, 'STREAM_NOT_FOUND', '推流目标不存在', 403);
|
||||
if (hook.action === 'on_publish') {
|
||||
const params = new URLSearchParams((hook.param ?? '').replace(/^\?/, '')); const token = params.get('token') ?? '';
|
||||
assert(token && safeEqual(sha256(token), room.streamKey.keyHash), 'STREAM_KEY_INVALID', 'Stream Key 无效', 403);
|
||||
assert(room.owner.status === 'ACTIVE' && room.owner.canStream && !room.liveBanned, 'STREAM_PERMISSION_DENIED', '账号或直播间已被禁止直播', 403);
|
||||
const active = await db.room.count({ where: { streamStatus: 'LIVE' } }); const maximum = settings ? await settings.get<number>('live.maxConcurrent', 100) : 100;
|
||||
assert(room.streamStatus === 'LIVE' || active < maximum, 'STREAM_CAPACITY_REACHED', '平台同时直播数量已达到上限', 503);
|
||||
await db.$transaction(async tx => {
|
||||
await tx.liveSession.updateMany({ where: { roomId: room.id, endedAt: null }, data: { endedAt: new Date() } });
|
||||
await tx.liveSession.create({ data: { roomId: room.id, streamName: hook.stream, srsClientId: hook.client_id ? String(hook.client_id) : null, recordEnabled: room.recordReplay } });
|
||||
await tx.room.update({ where: { id: room.id }, data: { streamStatus: 'LIVE', lastLiveAt: new Date(), viewerCount: 0 } });
|
||||
});
|
||||
if (transcoder) void transcoder.onPublish(hook.stream).catch(error => request.log.error({ err: error }, 'transcoder onPublish failed'));
|
||||
}
|
||||
if (hook.action === 'on_unpublish') {
|
||||
if (transcoder) transcoder.onUnpublish(hook.stream);
|
||||
const session = await db.liveSession.findFirst({ where: { roomId: room.id, endedAt: null }, orderBy: { startedAt: 'desc' } }); const endedAt = new Date();
|
||||
await db.$transaction([db.room.update({ where: { id: room.id }, data: { streamStatus: room.liveBanned ? 'BANNED' : 'OFFLINE', viewerCount: 0 } }), ...(session ? [db.liveSession.update({ where: { id: session.id }, data: { endedAt, durationSeconds: Math.max(0, Math.floor((endedAt.getTime() - session.startedAt.getTime()) / 1000)) } })] : [])]);
|
||||
}
|
||||
if (hook.action === 'on_dvr' && hook.file) {
|
||||
const fileName = hook.file.split(/[\\/]/).pop();
|
||||
assert(fileName && /^room_\d+\.\d+\.flv$/.test(fileName), 'RECORDING_PATH_INVALID', '回放文件路径无效', 422);
|
||||
const session = await db.liveSession.findFirst({ where: { roomId: room.id }, orderBy: { startedAt: 'desc' } });
|
||||
if (session && !session.recordEnabled) {
|
||||
unlink(join(config.LIVE_DIR, 'replays', fileName)).catch(error => request.log.error({ err: error }, 'delete replay file failed'));
|
||||
} else if (session) {
|
||||
const size = await stat(join(config.LIVE_DIR, 'replays', fileName)).then(s => s.size).catch(() => null);
|
||||
await db.liveSession.update({ where: { id: session.id }, data: { recordingUrl: `/live/replays/${fileName}`, ...(size != null ? { recordingSize: size } : {}), ...(hook.duration && !session.durationSeconds ? { durationSeconds: Math.round(hook.duration) } : {}) } });
|
||||
}
|
||||
}
|
||||
reply.type('application/json').send(0);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import nodemailer from 'nodemailer';
|
||||
import type { CodePurpose } from '@prisma/client';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
import { AppError } from '../lib/errors.js';
|
||||
import { hmacSha1Base64 } from '../lib/crypto.js';
|
||||
|
||||
type SmtpConfig = { host: string; port: number; username: string; password: string; encryption: 'NONE' | 'SSL' | 'STARTTLS'; fromEmail: string; fromName: string };
|
||||
type SmsConfig = { accessKeyId: string; accessKeySecret: string; signName: string; regionId?: string; registerTemplateId: string; loginTemplateId: string; resetTemplateId: string };
|
||||
|
||||
export class MessagingService {
|
||||
constructor(private settings: SettingsService) {}
|
||||
|
||||
private async smtp(): Promise<SmtpConfig> {
|
||||
const all = await this.settings.all(true);
|
||||
const c = {
|
||||
host: String(all['smtp.host'] ?? ''), port: Number(all['smtp.port'] ?? 587), username: String(all['smtp.username'] ?? ''),
|
||||
password: String(all['smtp.password'] ?? ''), encryption: String(all['smtp.encryption'] ?? 'STARTTLS') as SmtpConfig['encryption'],
|
||||
fromEmail: String(all['smtp.fromEmail'] ?? ''), fromName: String(all['smtp.fromName'] ?? all['site.name'] ?? 'XLive')
|
||||
};
|
||||
if (!c.host || !c.fromEmail) throw new AppError('SMTP_NOT_CONFIGURED', 'SMTP 尚未配置');
|
||||
return c;
|
||||
}
|
||||
|
||||
async sendEmail(to: string, subject: string, text: string) {
|
||||
const c = await this.smtp();
|
||||
const transport = nodemailer.createTransport({ host: c.host, port: c.port, secure: c.encryption === 'SSL', requireTLS: c.encryption === 'STARTTLS', auth: c.username ? { user: c.username, pass: c.password } : undefined, connectionTimeout: 10_000 });
|
||||
try {
|
||||
await transport.verify();
|
||||
return await transport.sendMail({ from: { address: c.fromEmail, name: c.fromName }, to, subject, text });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '未知错误';
|
||||
throw new AppError('SMTP_SEND_FAILED', `邮件发送失败:${message}`, 502);
|
||||
}
|
||||
}
|
||||
|
||||
async sendSms(phone: string, templateId: string, code: string) {
|
||||
const all = await this.settings.all(true);
|
||||
const c: SmsConfig = { accessKeyId: String(all['sms.accessKeyId'] ?? ''), accessKeySecret: String(all['sms.accessKeySecret'] ?? ''), signName: String(all['sms.signName'] ?? ''), regionId: String(all['sms.regionId'] ?? 'cn-hangzhou'), registerTemplateId: String(all['sms.registerTemplateId'] ?? ''), loginTemplateId: String(all['sms.loginTemplateId'] ?? ''), resetTemplateId: String(all['sms.resetTemplateId'] ?? '') };
|
||||
if (!c.accessKeyId || !c.accessKeySecret || !c.signName || !templateId) throw new AppError('SMS_NOT_CONFIGURED', '阿里云短信尚未完整配置');
|
||||
const params: Record<string, string> = {
|
||||
AccessKeyId: c.accessKeyId, Action: 'SendSms', Format: 'JSON', PhoneNumbers: phone, RegionId: c.regionId ?? 'cn-hangzhou',
|
||||
SignName: c.signName, SignatureMethod: 'HMAC-SHA1', SignatureNonce: crypto.randomUUID(), SignatureVersion: '1.0',
|
||||
TemplateCode: templateId, TemplateParam: JSON.stringify({ code }), Timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'), Version: '2017-05-25'
|
||||
};
|
||||
const percent = (s: string) => encodeURIComponent(s).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
|
||||
const canonical = Object.keys(params).sort().map(k => `${percent(k)}=${percent(params[k]!)}`).join('&');
|
||||
params.Signature = hmacSha1Base64(`${c.accessKeySecret}&`, `GET&%2F&${percent(canonical)}`);
|
||||
const response = await fetch(`https://dysmsapi.aliyuncs.com/?${new URLSearchParams(params)}`);
|
||||
const body = await response.json() as { Code?: string; Message?: string; RequestId?: string };
|
||||
if (!response.ok || body.Code !== 'OK') throw new AppError('SMS_SEND_FAILED', `短信发送失败:${body.Message ?? body.Code ?? response.statusText}`, 502);
|
||||
return body;
|
||||
}
|
||||
|
||||
async sendSmsForPurpose(phone: string, purpose: CodePurpose, code: string) {
|
||||
const key = purpose === 'REGISTER' ? 'sms.registerTemplateId' : purpose === 'LOGIN' ? 'sms.loginTemplateId' : 'sms.resetTemplateId';
|
||||
return this.sendSms(phone, await this.settings.get<string>(key, ''), code);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import type { RedisLike } from '../lib/redis.js';
|
||||
import { z } from 'zod';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
import { qualitySlug, type QualitySetting, type TranscoderService } from './transcoder.service.js';
|
||||
import { authenticate } from '../lib/auth.js';
|
||||
import { AppError, assert } from '../lib/errors.js';
|
||||
import { decrypt, encrypt, randomToken, sha256 } from '../lib/crypto.js';
|
||||
|
||||
const roomInclude = { owner: { select: { id: true, username: true, nickname: true, avatar: true } }, category: true } as const;
|
||||
const flvUrl = (path: string, flvHost: string) => flvHost ? `//${flvHost.replace(/^https?:\/\//, '').replace(/\/+$/, '')}${path}` : path;
|
||||
const qualitiesFor = (n: number, configs: QualitySetting[], src: { width: number; height: number } | undefined, flvHost: string) => [{ label: '原画', flv: flvUrl(`/live/room_${n}.flv`, flvHost), hls: `/live/room_${n}.m3u8` }, ...configs.filter(q => q.enabled !== false).filter(q => !src || (q.width < src.width && q.height < src.height)).map(q => ({ label: q.label, flv: flvUrl(`/transcode/live/room_${n}_${qualitySlug(q.label)}.flv`, flvHost), hls: `/live/room_${n}_${qualitySlug(q.label)}.m3u8` }))];
|
||||
const roomInput = z.object({ title: z.string().min(1).max(120), description: z.string().max(1000).optional(), cover: z.string().max(500).optional(), announcement: z.string().max(1000).optional(), categoryId: z.number().int().positive().nullable().optional(), visibility: z.enum(['PUBLIC', 'PRIVATE']).default('PUBLIC'), showViewerCount: z.boolean().default(true), recordReplay: z.boolean().optional() });
|
||||
|
||||
export async function roomRoutes(app: FastifyInstance, deps: { db: PrismaClient; redis: RedisLike; config: AppConfig; settings: SettingsService; transcoder: TranscoderService }) {
|
||||
const { db, redis, config, settings, transcoder } = deps;
|
||||
|
||||
app.get('/api/rooms', async request => {
|
||||
const q = z.object({ category: z.string().optional(), search: z.string().max(100).optional(), status: z.enum(['LIVE', 'OFFLINE']).optional(), page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(50).default(20) }).parse(request.query);
|
||||
const where = { visibility: 'PUBLIC' as const, ...(q.status ? { streamStatus: q.status } : {}), ...(q.category ? { category: { slug: q.category, enabled: true } } : {}), ...(q.search ? { OR: [{ title: { contains: q.search, mode: 'insensitive' as const } }, { owner: { nickname: { contains: q.search, mode: 'insensitive' as const } } }] } : {}) };
|
||||
const [items, total] = await Promise.all([db.room.findMany({ where, include: roomInclude, orderBy: [{ featured: 'desc' }, { streamStatus: 'desc' }, { viewerCount: 'desc' }, { lastLiveAt: 'desc' }], skip: (q.page - 1) * q.limit, take: q.limit }), db.room.count({ where })]);
|
||||
return { data: items, meta: { page: q.page, limit: q.limit, total } };
|
||||
});
|
||||
|
||||
app.get('/api/rooms/:roomNumber', async request => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params);
|
||||
const room = await db.room.findUnique({ where: { roomNumber }, include: roomInclude }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404);
|
||||
if (!(await settings.get<boolean>('auth.guestViewing', true)) && !request.cookies.xlive_access) throw new AppError('LOGIN_REQUIRED', '登录后才能观看直播', 401);
|
||||
const [protocol, flvHost, transcodeQualities] = await Promise.all([settings.get<'FLV' | 'HLS'>('live.playback.protocol', 'FLV'), settings.get<string>('live.playback.flvHost', ''), settings.get<QualitySetting[]>('live.transcode.qualities', [])]);
|
||||
const qualities = qualitiesFor(room.roomNumber, transcodeQualities, transcoder.probeOf(`room_${room.roomNumber}`), flvHost);
|
||||
return { data: { ...room, playback: room.streamStatus === 'LIVE' ? { ...qualities[0]!, qualities, protocol } : null } };
|
||||
});
|
||||
|
||||
app.get('/api/categories', async () => ({ data: await db.category.findMany({ where: { enabled: true }, orderBy: [{ sort: 'asc' }, { id: 'asc' }] }) }));
|
||||
|
||||
app.post('/api/rooms', { preHandler: authenticate }, async (request, reply) => {
|
||||
const input = roomInput.parse(request.body); const user = await db.user.findUniqueOrThrow({ where: { id: request.auth!.userId } });
|
||||
assert(user.canStream && user.status === 'ACTIVE', 'STREAM_PERMISSION_DENIED', '当前账号没有直播权限', 403); assert(await settings.get<boolean>('live.allowRegisteredUsers', true), 'STREAM_CREATION_DISABLED', '平台暂未开放创建直播间', 403);
|
||||
const max = await settings.get<number>('live.maxPerUser', 1); assert(await db.room.count({ where: { ownerId: user.id } }) < max, 'ROOM_LIMIT_REACHED', `每个用户最多可创建 ${max} 个直播间`, 409);
|
||||
const rawKey = randomToken(32); const room = await db.room.create({ data: { ...input, ownerId: user.id, streamKey: { create: { keyHash: sha256(rawKey), keyCipher: encrypt(rawKey, config.CONFIG_ENCRYPTION_KEY), keyHint: rawKey.slice(-6) } } }, include: roomInclude });
|
||||
reply.code(201).send({ data: room });
|
||||
});
|
||||
|
||||
app.get('/api/users/me/rooms', { preHandler: authenticate }, async request => ({ data: await db.room.findMany({ where: { ownerId: request.auth!.userId }, include: { ...roomInclude, sessions: { orderBy: { startedAt: 'desc' }, take: 20, select: { id: true, startedAt: true, endedAt: true, durationSeconds: true, peakViewers: true, totalViews: true, recordingUrl: true } } } }) }));
|
||||
|
||||
app.get('/api/rooms/:roomNumber/replays', async request => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params);
|
||||
const room = await db.room.findUnique({ where: { roomNumber } }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404);
|
||||
const sessions = await db.liveSession.findMany({ where: { roomId: room.id, endedAt: { not: null }, recordingUrl: { not: null } }, orderBy: { startedAt: 'desc' }, take: 50, select: { id: true, startedAt: true, endedAt: true, durationSeconds: true, peakViewers: true, totalViews: true, recordingUrl: true } });
|
||||
return { data: sessions };
|
||||
});
|
||||
|
||||
app.get('/api/replays', async request => {
|
||||
const q = z.object({ page: z.coerce.number().int().min(1).default(1), limit: z.coerce.number().int().min(1).max(50).default(20) }).parse(request.query);
|
||||
const where = { endedAt: { not: null }, recordingUrl: { not: null }, room: { visibility: 'PUBLIC' as const } };
|
||||
const [items, total] = await Promise.all([db.liveSession.findMany({ where, select: { id: true, startedAt: true, endedAt: true, durationSeconds: true, peakViewers: true, totalViews: true, recordingUrl: true, room: { select: { roomNumber: true, title: true, cover: true } } }, orderBy: { startedAt: 'desc' }, skip: (q.page - 1) * q.limit, take: q.limit }), db.liveSession.count({ where })]);
|
||||
return { data: items, meta: { page: q.page, limit: q.limit, total } };
|
||||
});
|
||||
|
||||
app.post('/api/notices/stream-permission', { preHandler: authenticate }, async (request, reply) => {
|
||||
const input = z.object({ content: z.string().max(1000).optional() }).parse(request.body);
|
||||
const user = await db.user.findUniqueOrThrow({ where: { id: request.auth!.userId } });
|
||||
assert(!user.canStream, 'STREAM_PERMISSION_GRANTED', '您已拥有开播权限');
|
||||
const pending = await db.notice.findFirst({ where: { fromId: user.id, status: 'PENDING' } });
|
||||
assert(!pending, 'APPLICATION_PENDING', '已有待审核的申请,请耐心等待');
|
||||
const notice = await db.notice.create({ data: { fromId: user.id, content: input.content?.trim() || '申请开播权限' } });
|
||||
reply.code(201).send({ data: notice });
|
||||
});
|
||||
|
||||
app.get('/api/notices/stream-permission', { preHandler: authenticate }, async request => ({ data: await db.notice.findFirst({ where: { fromId: request.auth!.userId }, orderBy: { createdAt: 'desc' } }) }));
|
||||
|
||||
app.get('/api/replays/:sessionId/danmaku', async request => {
|
||||
const { sessionId } = z.object({ sessionId: z.string().uuid() }).parse(request.params);
|
||||
const session = await db.liveSession.findUnique({ where: { id: sessionId }, select: { id: true, recordingUrl: true } }); assert(session?.recordingUrl, 'REPLAY_NOT_FOUND', '直播回放不存在', 404);
|
||||
const messages = await db.chatMessage.findMany({ where: { sessionId, deletedAt: null, offsetSeconds: { not: null } }, orderBy: { offsetSeconds: 'asc' }, select: { id: true, nickname: true, avatar: true, content: true, createdAt: true, offsetSeconds: true } });
|
||||
return { data: messages };
|
||||
});
|
||||
|
||||
app.patch('/api/rooms/:roomNumber', { preHandler: authenticate }, async request => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params); const room = await db.room.findUnique({ where: { roomNumber } }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404); assert(room.ownerId === request.auth!.userId || request.auth!.roles.some(r => r !== 'USER'), 'FORBIDDEN', '无权修改此直播间', 403);
|
||||
return { data: await db.room.update({ where: { id: room.id }, data: roomInput.partial().parse(request.body), include: roomInclude }) };
|
||||
});
|
||||
|
||||
app.get('/api/rooms/:roomNumber/stream', { preHandler: authenticate }, async request => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params); const room = await db.room.findUnique({ where: { roomNumber }, include: { streamKey: true } }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404); assert(room.ownerId === request.auth!.userId, 'FORBIDDEN', '只能查看自己的推流信息', 403); assert(room.streamKey, 'STREAM_KEY_MISSING', '推流密钥不存在', 500);
|
||||
const key = decrypt(room.streamKey.keyCipher, config.CONFIG_ENCRYPTION_KEY); const [protocol, flvHost] = await Promise.all([settings.get<'FLV' | 'HLS'>('live.playback.protocol', 'FLV'), settings.get<string>('live.playback.flvHost', '')]);
|
||||
const server = config.RTMP_PUBLIC_URL || `rtmp://${request.hostname}:${config.RTMP_PORT}/live`;
|
||||
return { data: { server, streamKey: `room_${room.roomNumber}?token=${key}`, keyHint: room.streamKey.keyHint, playback: protocol === 'FLV' ? flvUrl(`/live/room_${room.roomNumber}.flv`, flvHost) : `/live/room_${room.roomNumber}.m3u8` } };
|
||||
});
|
||||
|
||||
app.post('/api/rooms/:roomNumber/stream/rotate', { preHandler: authenticate }, async request => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params); const room = await db.room.findUnique({ where: { roomNumber }, include: { streamKey: true } }); assert(room && room.streamKey, 'ROOM_NOT_FOUND', '直播间不存在', 404); assert(room.ownerId === request.auth!.userId, 'FORBIDDEN', '只能重置自己的推流密钥', 403);
|
||||
const raw = randomToken(32); await db.streamKey.update({ where: { roomId: room.id }, data: { keyHash: sha256(raw), keyCipher: encrypt(raw, config.CONFIG_ENCRYPTION_KEY), keyHint: raw.slice(-6), version: { increment: 1 }, rotatedAt: new Date() } });
|
||||
if (room.streamStatus === 'LIVE') await stopSrsStream(config, `room_${roomNumber}`); return { data: { streamKey: `room_${roomNumber}?token=${raw}` } };
|
||||
});
|
||||
|
||||
app.post('/api/rooms/:roomNumber/viewers/heartbeat', async (request, reply) => {
|
||||
const { roomNumber } = z.object({ roomNumber: z.coerce.number().int() }).parse(request.params); const room = await db.room.findUnique({ where: { roomNumber } }); assert(room, 'ROOM_NOT_FOUND', '直播间不存在', 404);
|
||||
let viewer = request.cookies.xlive_viewer; if (!viewer) { viewer = randomToken(18); reply.setCookie('xlive_viewer', viewer, { httpOnly: true, sameSite: 'lax', path: '/', maxAge: 86400 }); }
|
||||
const key = `viewers:${room.id}`; const now = Date.now(); await redis.zAdd(key, { score: now + 45_000, value: viewer }); await redis.zRemRangeByScore(key, 0, now); await redis.expire(key, 120); const count = await redis.zCard(key);
|
||||
await db.room.update({ where: { id: room.id }, data: { viewerCount: count } }); const session = await db.liveSession.findFirst({ where: { roomId: room.id, endedAt: null }, orderBy: { startedAt: 'desc' } }); if (session) await db.liveSession.update({ where: { id: session.id }, data: { peakViewers: Math.max(session.peakViewers, count), viewerSeconds: { increment: BigInt(count * 15) }, viewerSamples: { increment: 1 } } });
|
||||
return { data: { viewerCount: room.showViewerCount ? count : null } };
|
||||
});
|
||||
}
|
||||
|
||||
export async function stopSrsStream(config: AppConfig, streamName: string) {
|
||||
const response = await fetch(`${config.SRS_API_URL}/api/v1/streams?count=100`); if (!response.ok) return false;
|
||||
const body = await response.json() as { streams?: Array<{ name: string; publish?: { cid?: number } }> }; const stream = body.streams?.find(s => s.name === streamName); const cid = stream?.publish?.cid; if (!cid) return false;
|
||||
const stopped = await fetch(`${config.SRS_API_URL}/api/v1/clients/${cid}`, { method: 'DELETE' }); return stopped.ok;
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { decrypt, encrypt } from '../lib/crypto.js';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { defaultPasswordPolicy, type PasswordPolicy } from '../lib/password.js';
|
||||
|
||||
export const publicDefaults: Record<string, unknown> = {
|
||||
'site.name': 'XLive', 'site.subtitle': '看见每一种热爱', 'site.description': '轻量、开放的多用户直播平台',
|
||||
'site.keywords': '直播,视频,互动', 'site.logo': '', 'site.darkLogo': '', 'site.favicon': '',
|
||||
'site.footer': '让连接实时发生', 'site.copyright': '© 2026 XLive', 'site.icp.text': '', 'site.icp.url': '',
|
||||
'site.userAgreement': `欢迎使用 XLive 直播平台!
|
||||
|
||||
一、服务说明
|
||||
XLive 是一个多用户直播与互动平台。您在注册和使用本平台前,请仔细阅读本协议的全部内容。注册成功即视为您已充分理解并同意本协议。
|
||||
|
||||
二、账号注册
|
||||
1. 您需年满 18 周岁,或已获得监护人同意方可注册使用本平台。
|
||||
2. 注册时请提供真实、准确的信息,并妥善保管账号密码,因保管不善造成的损失由您自行承担。
|
||||
3. 不得恶意批量注册账号。
|
||||
|
||||
三、用户行为规范
|
||||
1. 禁止发布违反法律法规的内容,包括但不限于:危害国家安全、暴力恐怖、色情低俗、赌博诈骗、侵犯他人隐私与知识产权的内容。
|
||||
2. 禁止在直播、弹幕与聊天中辱骂、骚扰或人身攻击其他用户。
|
||||
3. 禁止利用平台漏洞进行攻击、盗取数据、刷量作弊等行为。
|
||||
|
||||
四、内容与知识产权
|
||||
您发布的直播与内容,授权平台在提供服务所需的范围内存储、分发与展示。您保证所发布内容不侵犯任何第三方合法权益。
|
||||
|
||||
五、隐私保护
|
||||
平台将按照相关法律法规保护您的个人信息,未经您同意不向第三方披露,法律法规另有规定的除外。
|
||||
|
||||
六、责任与免责
|
||||
1. 因您的行为导致的后果由您自行承担。
|
||||
2. 平台有权对违规账号采取警告、禁言、封禁等措施,并配合有关部门调查。
|
||||
3. 因不可抗力、网络故障等导致服务中断的,平台不承担责任。
|
||||
|
||||
七、协议变更
|
||||
平台有权更新本协议,更新后将公布最新版本,继续使用平台即视为接受新协议。
|
||||
|
||||
如有疑问,请联系平台管理员。`,
|
||||
'site.police.text': '', 'site.police.url': '', 'auth.guestViewing': true,
|
||||
'auth.register.email': true, 'auth.register.sms': false, 'auth.register.rule': 'ANY', 'auth.register.requireVerification': false,
|
||||
'password.policy': defaultPasswordPolicy,
|
||||
'live.allowRegisteredUsers': true, 'live.newUserCanStream': false, 'live.maxConcurrent': 100,
|
||||
'live.maxPerUser': 1, 'live.maxBitrateKbps': 8000, 'live.maxFps': 60, 'live.codecs': ['H264', 'AAC'], 'live.showPlayerLatency': false,
|
||||
'live.playback.protocol': 'FLV', 'live.playback.flvHost': '',
|
||||
'live.transcode.qualities': [
|
||||
{ label: '2.5K', width: 2560, height: 1440, bitrate: 5000, fps: 30, enabled: true },
|
||||
{ label: '4K', width: 3840, height: 2160, bitrate: 8000, fps: 30, enabled: true },
|
||||
{ label: '1080P', width: 1920, height: 1080, bitrate: 3000, fps: 30, enabled: true },
|
||||
{ label: '720P', width: 1280, height: 720, bitrate: 1500, fps: 30, enabled: true },
|
||||
{ label: '480P', width: 854, height: 480, bitrate: 800, fps: 25, enabled: true }
|
||||
],
|
||||
'security.loginMaxFailures': 5, 'security.loginLockMinutes': 15
|
||||
};
|
||||
|
||||
export class SettingsService {
|
||||
private cache = new Map<string, unknown>();
|
||||
private loadedAt = 0;
|
||||
constructor(private db: PrismaClient, private config: AppConfig) {}
|
||||
|
||||
async all(includeSensitive = false) {
|
||||
const rows = await this.db.systemSetting.findMany({ orderBy: [{ group: 'asc' }, { key: 'asc' }] });
|
||||
const merged = new Map(Object.entries(publicDefaults));
|
||||
for (const row of rows) {
|
||||
if (row.sensitive && !includeSensitive) { merged.set(row.key, row.value ? '********' : ''); continue; }
|
||||
const raw = row.sensitive && row.value ? decrypt(row.value, this.config.CONFIG_ENCRYPTION_KEY) : row.value;
|
||||
try { merged.set(row.key, JSON.parse(raw)); } catch { merged.set(row.key, raw); }
|
||||
}
|
||||
return Object.fromEntries(merged);
|
||||
}
|
||||
|
||||
async publicSettings() {
|
||||
const all = await this.all(false);
|
||||
return Object.fromEntries(Object.entries(all).filter(([key]) => key.startsWith('site.') || ['auth.guestViewing', 'auth.register.email', 'auth.register.sms', 'auth.register.rule', 'password.policy', 'live.showPlayerLatency'].includes(key)));
|
||||
}
|
||||
|
||||
async get<T>(key: string, fallback?: T): Promise<T> {
|
||||
if (Date.now() - this.loadedAt > 30_000) { this.cache.clear(); this.loadedAt = Date.now(); }
|
||||
if (this.cache.has(key)) return this.cache.get(key) as T;
|
||||
const row = await this.db.systemSetting.findUnique({ where: { key } });
|
||||
let value: unknown = publicDefaults[key] ?? fallback;
|
||||
if (row) {
|
||||
const raw = row.sensitive && row.value ? decrypt(row.value, this.config.CONFIG_ENCRYPTION_KEY) : row.value;
|
||||
try { value = JSON.parse(raw); } catch { value = raw; }
|
||||
}
|
||||
this.cache.set(key, value); return value as T;
|
||||
}
|
||||
|
||||
passwordPolicy() { return this.get<PasswordPolicy>('password.policy', defaultPasswordPolicy); }
|
||||
|
||||
async setMany(values: Record<string, unknown>, updatedBy: string, sensitiveKeys: string[] = []) {
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
const sensitive = sensitiveKeys.includes(key) || ['smtp.password', 'sms.accessKeySecret'].includes(key);
|
||||
if (sensitive && (value === '' || value === '********')) continue;
|
||||
const raw = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
await this.db.systemSetting.upsert({ where: { key }, update: { value: sensitive ? encrypt(raw, this.config.CONFIG_ENCRYPTION_KEY) : raw, sensitive, updatedBy }, create: { key, value: sensitive ? encrypt(raw, this.config.CONFIG_ENCRYPTION_KEY) : raw, group: key.split('.')[0]!, sensitive, updatedBy } });
|
||||
}
|
||||
this.cache.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import type { SettingsService } from './settings.service.js';
|
||||
|
||||
export type QualitySetting = { label: string; width: number; height: number; bitrate: number; fps: number; enabled?: boolean };
|
||||
export const qualitySlug = (label: string) => label.replace(/[^A-Za-z0-9]/g, '');
|
||||
|
||||
export class TranscoderService {
|
||||
private procs = new Map<string, ChildProcess[]>();
|
||||
private probes = new Map<string, { width: number; height: number }>();
|
||||
constructor(private settings: SettingsService) {}
|
||||
|
||||
probeOf(stream: string) { return this.probes.get(stream); }
|
||||
|
||||
async onPublish(stream: string) {
|
||||
this.onUnpublish(stream);
|
||||
const qualities = (await this.settings.get<QualitySetting[]>('live.transcode.qualities', [])).filter(q => q.enabled !== false && q.width > 0 && q.height > 0 && q.bitrate > 0 && q.fps > 0);
|
||||
if (!qualities.length) return;
|
||||
const src = await this.probe(stream);
|
||||
if (!src) return;
|
||||
const targets = qualities.filter(q => q.width < src.width && q.height < src.height);
|
||||
if (!targets.length) return;
|
||||
const procs = targets.map(q => {
|
||||
const proc = spawn('ffmpeg', ['-hide_banner', '-loglevel', 'error', '-i', `rtmp://srs:1935/live/${stream}`, '-c:v', 'libx264', '-preset', 'ultrafast', '-tune', 'zerolatency', '-b:v', `${q.bitrate}k`, '-maxrate', `${Math.round(q.bitrate * 1.2)}k`, '-bufsize', `${q.bitrate * 2}k`, '-vf', `scale=${q.width}:${q.height}`, '-r', String(q.fps), '-g', String(q.fps * 2), '-sc_threshold', '0', '-c:a', 'aac', '-b:a', '128k', '-ar', '48000', '-ac', '2', '-f', 'flv', `rtmp://srs2:1936/live/${stream}_${qualitySlug(q.label)}`], { stdio: 'ignore' });
|
||||
proc.on('error', () => {}); proc.on('exit', () => { this.procs.set(stream, (this.procs.get(stream) ?? []).filter(p => p !== proc)); });
|
||||
return proc;
|
||||
});
|
||||
this.procs.set(stream, procs);
|
||||
}
|
||||
|
||||
onUnpublish(stream: string) {
|
||||
const procs = this.procs.get(stream) ?? []; this.procs.delete(stream);
|
||||
for (const proc of procs) proc.kill('SIGKILL');
|
||||
}
|
||||
|
||||
private probe(stream: string): Promise<{ width: number; height: number } | null> {
|
||||
return new Promise(resolve => {
|
||||
const proc = spawn('ffprobe', ['-v', 'error', '-analyzeduration', '3M', '-probesize', '3M', '-select_streams', 'v:0', '-show_entries', 'stream=width,height', '-of', 'csv=p=0', `rtmp://srs:1935/live/${stream}`], { stdio: ['ignore', 'pipe', 'ignore'] });
|
||||
let out = ''; const timer = setTimeout(() => proc.kill('SIGKILL'), 10_000);
|
||||
proc.stdout.on('data', (chunk: Buffer) => { out += chunk.toString(); });
|
||||
proc.on('error', () => { clearTimeout(timer); resolve(null); });
|
||||
proc.on('exit', () => {
|
||||
clearTimeout(timer);
|
||||
const match = /(\d+),(\d+)/.exec(out);
|
||||
const info = match ? { width: Number(match[1]), height: Number(match[2]) } : null;
|
||||
if (info) this.probes.set(stream, info);
|
||||
resolve(info);
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import type { FastifyInstance } from 'fastify';
|
||||
import type { PrismaClient } from '@prisma/client';
|
||||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { AppConfig } from '../config.js';
|
||||
import { authenticate } from '../lib/auth.js';
|
||||
import { AppError } from '../lib/errors.js';
|
||||
import { randomToken } from '../lib/crypto.js';
|
||||
|
||||
function detectedExtension(buffer: Buffer): 'jpg' | 'png' | 'webp' | null {
|
||||
if (buffer.length > 3 && buffer[0] === 0xff && buffer[1] === 0xd8 && buffer[2] === 0xff) return 'jpg';
|
||||
if (buffer.length > 8 && buffer.subarray(0, 8).equals(Buffer.from([137,80,78,71,13,10,26,10]))) return 'png';
|
||||
if (buffer.length > 12 && buffer.toString('ascii',0,4)==='RIFF' && buffer.toString('ascii',8,12)==='WEBP') return 'webp';
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function uploadRoutes(app: FastifyInstance, deps: { db: PrismaClient; config: AppConfig }) {
|
||||
const { db, config } = deps;
|
||||
app.post('/api/uploads/images', { preHandler: authenticate }, async request => {
|
||||
const file = await request.file({ limits: { fileSize: 5 * 1024 * 1024, files: 1 } });
|
||||
if (!file) throw new AppError('FILE_REQUIRED', '请选择图片文件');
|
||||
const buffer = await file.toBuffer(); const extension = detectedExtension(buffer);
|
||||
if (!extension || !['image/jpeg','image/png','image/webp'].includes(file.mimetype)) throw new AppError('INVALID_IMAGE', '仅支持 JPG、PNG、WebP 图片');
|
||||
await mkdir(config.UPLOAD_DIR, { recursive: true }); const name = `${randomToken(20)}.${extension}`; await writeFile(join(config.UPLOAD_DIR, name), buffer, { flag: 'wx' });
|
||||
const upload = await db.upload.create({ data: { filename: name, originalName: file.filename?.slice(0, 255), mimeType: file.mimetype, size: buffer.length, uploaderId: request.auth!.userId, url: `/uploads/${name}` } });
|
||||
return { data: { id: upload.id, url: upload.url } };
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import type { PrismaClient, CodeChannel, CodePurpose } from '@prisma/client';
|
||||
import type { RedisLike } from '../lib/redis.js';
|
||||
import { randomCode, randomToken, sha256, safeEqual } from '../lib/crypto.js';
|
||||
import { AppError, assert } from '../lib/errors.js';
|
||||
import type { MessagingService } from './messaging.service.js';
|
||||
|
||||
// 图形验证码:本地生成 SVG 图片(英文字母),答案哈希后存入 Redis,一次性使用
|
||||
const CAPTCHA_LETTERS = 'ABCDEFGHJKLMNPQRSTUVWXYZ';
|
||||
const captchaKey = (id: string, text: string) => `captcha:${sha256(`${id}:${text}`)}`;
|
||||
function renderCaptchaSvg(text: string) {
|
||||
const colors = ['#c0392b', '#1f618d', '#1e8449', '#6c3483', '#b9770e', '#21618c'];
|
||||
const chars = text.split('').map((ch, i) => {
|
||||
const x = 16 + i * 24, y = 28 + Math.floor(Math.random() * 6 - 3), rotate = Math.floor(Math.random() * 36 - 18), size = 24 + Math.floor(Math.random() * 8);
|
||||
return `<text x="${x}" y="${y}" font-size="${size}" font-weight="bold" font-family="Arial,Helvetica,sans-serif" fill="${colors[Math.floor(Math.random() * colors.length)]}" transform="rotate(${rotate} ${x} ${y})">${ch}</text>`;
|
||||
}).join('');
|
||||
const noise = Array.from({ length: 5 }, () => `<line x1="${Math.floor(Math.random() * 120)}" y1="${Math.floor(Math.random() * 44)}" x2="${Math.floor(Math.random() * 120)}" y2="${Math.floor(Math.random() * 44)}" stroke="#9aa5b1" stroke-width="1"/>`).join('');
|
||||
const dots = Array.from({ length: 40 }, () => `<circle cx="${Math.floor(Math.random() * 120)}" cy="${Math.floor(Math.random() * 44)}" r="1" fill="#9aa5b1"/>`).join('');
|
||||
return `<svg xmlns="http://www.w3.org/2000/svg" width="120" height="44" viewBox="0 0 120 44"><rect width="120" height="44" fill="#eef1f5"/>${noise}${dots}${chars}</svg>`;
|
||||
}
|
||||
|
||||
export class VerificationService {
|
||||
constructor(private db: PrismaClient, private redis: RedisLike, private messaging: MessagingService) {}
|
||||
async send(channel: CodeChannel, target: string, purpose: CodePurpose, ip: string) {
|
||||
const normalized = target.trim().toLowerCase(); const targetHash = sha256(normalized);
|
||||
const cooldown = `verify:cooldown:${channel}:${targetHash}`; const ipRate = `verify:ip:${ip}`;
|
||||
assert(!(await this.redis.exists(cooldown)), 'CODE_TOO_FREQUENT', '请在 60 秒后重试', 429);
|
||||
const count = await this.redis.incr(ipRate); if (count === 1) await this.redis.expire(ipRate, 3600);
|
||||
assert(count <= 20, 'IP_RATE_LIMITED', '此 IP 发送过于频繁,请稍后重试', 429);
|
||||
const code = randomCode();
|
||||
await this.db.verificationCode.create({ data: { channel, targetHash, codeHash: sha256(`${targetHash}:${code}`), purpose, expiresAt: new Date(Date.now() + 5 * 60_000), ip } });
|
||||
if (channel === 'EMAIL') await this.messaging.sendEmail(normalized, 'XLive 验证码', `您的验证码为 ${code},5 分钟内有效。请勿将验证码告知他人。`);
|
||||
else await this.messaging.sendSmsForPurpose(normalized, purpose, code);
|
||||
await this.redis.set(cooldown, '1', { EX: 60 });
|
||||
return { expiresIn: 300, retryAfter: 60 };
|
||||
}
|
||||
|
||||
async createCaptcha() {
|
||||
const id = randomToken(12);
|
||||
const text = Array.from({ length: 4 }, () => CAPTCHA_LETTERS[Math.floor(Math.random() * CAPTCHA_LETTERS.length)]).join('');
|
||||
await this.redis.set(captchaKey(id, text), '1', { EX: 300 });
|
||||
return { captchaId: id, image: `data:image/svg+xml;base64,${Buffer.from(renderCaptchaSvg(text)).toString('base64')}` };
|
||||
}
|
||||
|
||||
async requireCaptcha(captchaId: string, captchaText: string) {
|
||||
const key = captchaKey(captchaId, captchaText.trim().toUpperCase());
|
||||
assert(await this.redis.exists(key), 'CAPTCHA_INVALID', '图形验证码不正确或已过期,请重新输入');
|
||||
await this.redis.expire(key, 1); // 一次性使用,立即失效
|
||||
}
|
||||
|
||||
async verify(channel: CodeChannel, target: string, purpose: CodePurpose, code: string) {
|
||||
const targetHash = sha256(target.trim().toLowerCase());
|
||||
const record = await this.db.verificationCode.findFirst({ where: { channel, targetHash, purpose, usedAt: null, expiresAt: { gt: new Date() }, attempts: { lt: 5 } }, orderBy: { createdAt: 'desc' } });
|
||||
if (!record) throw new AppError('CODE_INVALID_OR_EXPIRED', '验证码无效或已过期');
|
||||
const valid = safeEqual(record.codeHash, sha256(`${targetHash}:${code}`));
|
||||
await this.db.verificationCode.update({ where: { id: record.id }, data: valid ? { usedAt: new Date() } : { attempts: { increment: 1 } } });
|
||||
if (!valid) throw new AppError('CODE_INVALID', '验证码不正确');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { PrismaClient } from '@prisma/client';
|
||||
import { hashPassword } from './lib/password.js';
|
||||
|
||||
const db = new PrismaClient();
|
||||
for (const role of ['USER', 'ADMIN', 'SUPER_ADMIN'] as const) await db.role.upsert({ where: { name: role }, update: {}, create: { name: role, description: role } });
|
||||
const categories = [['游戏', 'games', 'game-controller'], ['聊天', 'chat', 'chatbubbles'], ['音乐', 'music', 'musical-notes'], ['学习', 'study', 'book'], ['户外', 'outdoors', 'bicycle'], ['体育', 'sports', 'football'], ['其他', 'other', 'apps']] as const;
|
||||
for (const [name, slug, icon] of categories) await db.category.upsert({ where: { slug }, update: {}, create: { name, slug, icon } });
|
||||
const username = process.env.ADMIN_USERNAME ?? 'admin'; const email = process.env.ADMIN_EMAIL ?? 'admin@example.com'; const password = process.env.ADMIN_PASSWORD;
|
||||
if (!password) throw new Error('ADMIN_PASSWORD is required for first startup');
|
||||
const existing = await db.user.findFirst({ where: { OR: [{ username }, { email }] } });
|
||||
if (!existing) await db.user.create({ data: { username, nickname: '超级管理员', email, passwordHash: await hashPassword(password), roles: { create: { role: { connect: { name: 'SUPER_ADMIN' } } } } } });
|
||||
await db.$disconnect();
|
||||
@@ -0,0 +1,9 @@
|
||||
import { loadConfig } from './config.js';
|
||||
import { prisma } from './lib/db.js';
|
||||
import { buildApp } from './app.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const app = await buildApp(config, prisma);
|
||||
const stop = async () => { await app.close(); await prisma.$disconnect(); process.exit(0); };
|
||||
process.on('SIGINT', stop); process.on('SIGTERM', stop);
|
||||
await app.listen({ host: '0.0.0.0', port: config.APP_PORT });
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
import type { RoleName } from '@prisma/client';
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
auth?: { userId: string; roles: RoleName[] };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2023",
|
||||
"module": "NodeNext",
|
||||
"moduleResolution": "NodeNext",
|
||||
"outDir": "dist",
|
||||
"rootDir": "src",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"resolveJsonModule": true
|
||||
},
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/**/*.test.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
FROM node:22-alpine AS base
|
||||
WORKDIR /app
|
||||
COPY package*.json ./
|
||||
COPY apps/api/package.json apps/api/package.json
|
||||
COPY apps/web/package.json apps/web/package.json
|
||||
RUN npm ci
|
||||
COPY apps/web apps/web
|
||||
FROM base AS dev
|
||||
CMD ["npm", "run", "dev", "-w", "@xlive/web", "--", "--host", "0.0.0.0"]
|
||||
FROM base AS build
|
||||
RUN npm run build -w @xlive/web
|
||||
FROM nginx:1.27-alpine AS production
|
||||
COPY --from=build /app/apps/web/dist /usr/share/nginx/html
|
||||
COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf
|
||||
@@ -0,0 +1 @@
|
||||
<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"/><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover"/><meta name="description" content="多用户实时直播平台"/><title>直播平台</title></head><body><div id="app"></div><script type="module" src="/src/main.ts"></script></body></html>
|
||||
@@ -0,0 +1 @@
|
||||
server { listen 80; server_name _; root /usr/share/nginx/html; index index.html; location / { try_files $uri $uri/ /index.html; } location ~* \.(js|css|png|jpg|jpeg|webp|svg|ico|woff2)$ { expires 7d; add_header Cache-Control "public, immutable"; } }
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "@xlive/web",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"test": "vitest run",
|
||||
"lint": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vicons/ionicons5": "^0.13.0",
|
||||
"hls.js": "^1.6.13",
|
||||
"mpegts.js": "^1.8.2",
|
||||
"naive-ui": "^2.42.0",
|
||||
"pinia": "^3.0.3",
|
||||
"vue": "^3.5.21",
|
||||
"vue-router": "^4.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^6.0.1",
|
||||
"@vue/test-utils": "^2.4.6",
|
||||
"jsdom": "^26.1.0",
|
||||
"typescript": "^5.9.2",
|
||||
"vite": "^7.1.5",
|
||||
"vitest": "^3.2.4",
|
||||
"vue-tsc": "^3.0.6"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref, watchEffect } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { NConfigProvider, NDialogProvider, NMessageProvider, NModal, NCard, NInput, NButton, darkTheme, zhCN, dateZhCN } from 'naive-ui';
|
||||
import { useAppStore } from './stores/app';
|
||||
const store=useAppStore(),router=useRouter(); const enterOpen=ref(false),roomNumber=ref('');
|
||||
const mode=ref(localStorage.getItem('theme')??'system'); const systemDark=matchMedia('(prefers-color-scheme: dark)'); const tick=ref(systemDark.matches); systemDark.addEventListener('change',e=>tick.value=e.matches);
|
||||
const dark=computed(()=>mode.value==='dark'||(mode.value==='system'&&tick.value));
|
||||
watchEffect(()=>{document.documentElement.dataset.theme=dark.value?'dark':'light'; localStorage.setItem('theme',mode.value)});
|
||||
onMounted(()=>store.bootstrap());
|
||||
function enter(){if(/^\d+$/.test(roomNumber.value)){enterOpen.value=false;router.push(`/room/${roomNumber.value}`)}}
|
||||
</script>
|
||||
<template><NConfigProvider :theme="dark?darkTheme:null" :locale="zhCN" :date-locale="dateZhCN"><NDialogProvider><NMessageProvider>
|
||||
<div class="shell"><header class="header"><router-link class="brand" to="/"><img v-if="store.settings[dark?'site.darkLogo':'site.logo']" :src="String(store.settings[dark?'site.darkLogo':'site.logo'])"><span>{{store.settings['site.name']}}</span></router-link>
|
||||
<nav><router-link to="/">首页</router-link><router-link to="/categories">分类</router-link><router-link to="/replays">回放</router-link><button class="text-button" @click="enterOpen=true">进入房间</button></nav>
|
||||
<div class="header-actions"><select v-model="mode" class="theme-select" aria-label="主题"><option value="system">跟随系统</option><option value="light">浅色</option><option value="dark">深色</option></select>
|
||||
<template v-if="store.user"><router-link to="/me/room">我的直播间</router-link><router-link v-if="store.isAdmin" to="/admin">管理后台</router-link><router-link to="/me">{{store.user.nickname}}</router-link><button class="text-button" @click="store.logout();router.push('/')">退出</button></template>
|
||||
<template v-else><router-link to="/login">登录</router-link><router-link class="primary-link" to="/register">注册</router-link></template></div></header>
|
||||
<main><router-view/></main><footer><span>{{store.settings['site.copyright']}}</span><span>{{store.settings['site.footer']}}</span><a v-if="store.settings['site.icp.text']" :href="String(store.settings['site.icp.url']||'#')">{{store.settings['site.icp.text']}}</a></footer></div>
|
||||
<NModal v-model:show="enterOpen"><NCard title="进入直播间" closable @close="enterOpen=false" style="width:min(420px,92vw)"><NInput v-model:value="roomNumber" placeholder="请输入房间号,如 10001" @keyup.enter="enter"/><NButton type="primary" block class="modal-button" @click="enter">进入直播间</NButton></NCard></NModal>
|
||||
</NMessageProvider></NDialogProvider></NConfigProvider></template>
|
||||
@@ -0,0 +1,23 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { api } from './api';
|
||||
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
describe('API client', () => {
|
||||
it('returns typed JSON data', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ok: true } }), { status: 200, headers: { 'content-type': 'application/json' } })));
|
||||
await expect(api<{ data: { ok: boolean } }>('/api/test')).resolves.toEqual({ data: { ok: true } });
|
||||
});
|
||||
|
||||
it('surfaces safe API errors', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ code: 'ROOM_NOT_FOUND', message: '直播间不存在' }), { status: 404, headers: { 'content-type': 'application/json' } })));
|
||||
await expect(api('/api/rooms/0')).rejects.toMatchObject({ code: 'ROOM_NOT_FOUND' });
|
||||
});
|
||||
|
||||
it('does not send a JSON content type with an empty DELETE body', async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { deleted: true } }), { status: 200, headers: { 'content-type': 'application/json' } }));
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
await api('/api/test', { method: 'DELETE' });
|
||||
expect(fetchMock.mock.calls[0]?.[1]).toMatchObject({ body: undefined, headers: {} });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
export type ApiError = { code: string; message: string; requestId?: string };
|
||||
export async function api<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const requestBody = init.body ?? (init.method === 'POST' ? '{}' : undefined);
|
||||
const response = await fetch(path, { ...init, body: requestBody, credentials: 'include', headers: { ...(requestBody !== undefined && !(requestBody instanceof FormData) ? { 'content-type': 'application/json' } : {}), ...init.headers } });
|
||||
if (response.status === 401 && path !== '/api/auth/refresh') { const refreshed = await fetch('/api/auth/refresh', { method: 'POST', credentials: 'include' }); if (refreshed.ok) return api<T>(path, init); }
|
||||
const body = await response.json().catch(() => ({ code: 'NETWORK_ERROR', message: '服务返回了无法解析的响应' }));
|
||||
if (!response.ok) throw body as ApiError; return body as T;
|
||||
}
|
||||
Vendored
+2
@@ -0,0 +1,2 @@
|
||||
/// <reference types="vite/client" />
|
||||
declare module '*.vue' { import type { DefineComponent } from 'vue'; const component: DefineComponent; export default component; }
|
||||
@@ -0,0 +1,6 @@
|
||||
import { createApp } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import App from './App.vue';
|
||||
import router from './router';
|
||||
import './style.css';
|
||||
createApp(App).use(createPinia()).use(router).mount('#app');
|
||||
@@ -0,0 +1,13 @@
|
||||
import { createRouter, createWebHistory } from 'vue-router';
|
||||
import HomeView from './views/HomeView.vue';
|
||||
import AuthView from './views/AuthView.vue';
|
||||
import RoomView from './views/RoomView.vue';
|
||||
import MyRoomView from './views/MyRoomView.vue';
|
||||
import ReplaysView from './views/ReplaysView.vue';
|
||||
import ProfileView from './views/ProfileView.vue';
|
||||
import AdminView from './views/AdminView.vue';
|
||||
export default createRouter({ history:createWebHistory(), routes:[
|
||||
{path:'/',component:HomeView},{path:'/categories/:slug?',component:HomeView},{path:'/search',component:HomeView},{path:'/replays',component:ReplaysView},{path:'/room/:roomNumber',component:RoomView},
|
||||
{path:'/login',component:AuthView,props:{mode:'login'}},{path:'/register',component:AuthView,props:{mode:'register'}},{path:'/forgot-password',component:AuthView,props:{mode:'forgot'}},
|
||||
{path:'/me',component:ProfileView},{path:'/me/security',component:ProfileView},{path:'/me/room',component:MyRoomView},{path:'/me/stream',component:MyRoomView},{path:'/me/sessions',component:MyRoomView},{path:'/admin/:section?',component:AdminView}
|
||||
]});
|
||||
@@ -0,0 +1,12 @@
|
||||
import { defineStore } from 'pinia';
|
||||
import { computed, ref } from 'vue';
|
||||
import { api } from '../api';
|
||||
type User = { id:string; username:string; nickname:string; avatar?:string; email?:string; roles:string[]; canStream:boolean };
|
||||
export const useAppStore = defineStore('app', () => {
|
||||
const settings = ref<Record<string, unknown>>({ 'site.name': 'XLive' }); const user = ref<User | null>(null); const loaded = ref(false);
|
||||
const isAdmin = computed(() => user.value?.roles.some(r => r === 'ADMIN' || r === 'SUPER_ADMIN') ?? false);
|
||||
async function bootstrap() { try { settings.value = (await api<{data:Record<string,unknown>}>('/api/settings/public')).data; document.title = String(settings.value['site.name'] ?? 'XLive'); const favicon = String(settings.value['site.favicon'] ?? ''); if (favicon) { let el = document.querySelector<HTMLLinkElement>('link[rel="icon"]'); if (!el) { el = document.createElement('link'); el.rel='icon'; document.head.append(el); } el.href=favicon; } try { user.value = (await api<{data:User}>('/api/users/me')).data; } catch { user.value=null; } } finally { loaded.value=true; } }
|
||||
async function login(account:string,password:string){ user.value=(await api<{data:User}>('/api/auth/login',{method:'POST',body:JSON.stringify({account,password})})).data; }
|
||||
async function logout(){ await api('/api/auth/logout',{method:'POST'}); user.value=null; }
|
||||
return { settings,user,loaded,isAdmin,bootstrap,login,logout };
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
:root{font-family:Inter,"PingFang SC","Microsoft YaHei",sans-serif;color:#18181b;background:#f7f7f8;line-height:1.5;font-synthesis:none;--bg:#f7f7f8;--surface:#fff;--surface-2:#f1f2f4;--border:#e4e4e7;--text:#18181b;--muted:#71717a;--accent:#ff5b47;--accent-hover:#e94b39;--shadow:0 8px 30px rgba(24,24,27,.07)}
|
||||
:root[data-theme=dark]{color:#f4f4f5;background:#101114;--bg:#101114;--surface:#18191d;--surface-2:#23242a;--border:#303137;--text:#f4f4f5;--muted:#a1a1aa;--shadow:0 8px 30px rgba(0,0,0,.25)}
|
||||
*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text)}a{color:inherit;text-decoration:none}button,input,select,textarea{font:inherit}.shell{min-height:100vh;display:flex;flex-direction:column}.header{height:64px;padding:0 max(24px,calc((100vw - 1320px)/2));display:flex;align-items:center;gap:36px;background:var(--surface);border-bottom:1px solid var(--border);position:sticky;top:0;z-index:20}.brand{font-weight:750;font-size:21px;display:flex;align-items:center;gap:9px}.brand img{width:34px;height:34px;object-fit:contain}.header nav,.header-actions{display:flex;align-items:center;gap:22px}.header-actions{margin-left:auto;font-size:14px}.header a.router-link-active{color:var(--accent)}.text-button{border:0;background:none;color:inherit;cursor:pointer;padding:0}.primary-link,.primary-button{background:var(--accent)!important;color:#fff!important;padding:8px 16px;border-radius:7px}.primary-link:hover,.primary-button:hover{background:var(--accent-hover)!important}.theme-select{border:1px solid var(--border);background:var(--surface);color:var(--text);border-radius:6px;padding:6px 8px}main{width:min(1320px,calc(100% - 48px));margin:0 auto;flex:1;padding:34px 0 60px}footer{padding:24px max(24px,calc((100vw - 1320px)/2));border-top:1px solid var(--border);color:var(--muted);display:flex;gap:20px;font-size:13px;background:var(--surface)}h1,h2,h3,p{margin-top:0}.hero{background:var(--surface);border:1px solid var(--border);padding:42px;border-radius:12px;display:flex;justify-content:space-between;align-items:center}.hero h1{font-size:34px;margin-bottom:10px}.hero p{color:var(--muted);max-width:650px}.section-head{display:flex;align-items:center;justify-content:space-between;margin:34px 0 18px}.section-head h2{margin:0}.search{display:flex;gap:10px;max-width:440px;width:100%}.captcha-img{width:120px;height:44px;border:1px solid var(--border);border-radius:7px;cursor:pointer;flex-shrink:0}.auth-wrap .search .input{flex:1;min-width:0}.grid{display:grid;grid-template-columns:repeat(4,1fr);gap:20px}.room-card{background:var(--surface);border:1px solid var(--border);border-radius:10px;overflow:hidden;transition:.18s}.room-card:hover{transform:translateY(-2px);box-shadow:var(--shadow)}.cover{aspect-ratio:16/9;background:var(--surface-2);position:relative;overflow:hidden}.cover img{width:100%;height:100%;object-fit:cover}.live-badge{position:absolute;top:10px;left:10px;background:#ef4444;color:#fff;border-radius:4px;padding:3px 7px;font-size:12px}.replay-badge{position:absolute;top:10px;left:10px;background:#7c3aed;color:#fff;border-radius:4px;padding:3px 7px;font-size:12px}.viewer{position:absolute;right:10px;bottom:8px;color:#fff;background:rgba(0,0,0,.65);padding:2px 6px;border-radius:4px;font-size:12px}.card-body{padding:14px}.card-title{font-weight:650;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.card-meta{display:flex;justify-content:space-between;color:var(--muted);font-size:13px;margin-top:8px}.panel{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:24px}.auth-wrap{max-width:440px;margin:50px auto}.auth-wrap h1{text-align:center}.modal-mask{position:fixed;inset:0;background:rgba(0,0,0,.55);display:grid;place-items:center;z-index:50}.modal-card{background:var(--surface);border:1px solid var(--border);border-radius:12px;padding:22px;width:min(560px,92vw);display:grid;gap:14px}.agreement-box{height:320px;overflow:auto;border:1px solid var(--border);border-radius:8px;padding:14px;background:var(--surface-2);white-space:pre-wrap;font-size:13px;color:var(--muted)}.form{display:grid;gap:16px}.form label{display:grid;gap:7px;color:var(--muted);font-size:14px}.input{border:1px solid var(--border);background:var(--surface);color:var(--text);padding:10px 12px;border-radius:7px;outline:none}.input:focus{border-color:var(--accent)}.button{border:0;background:var(--surface-2);color:var(--text);padding:10px 15px;border-radius:7px;cursor:pointer}.button:disabled{opacity:.5;cursor:not-allowed}.qblock{display:grid;gap:8px;color:var(--muted);font-size:14px;border-top:1px solid var(--border);padding-top:14px}.qrow{display:flex;align-items:center;gap:6px;flex-wrap:wrap}.qrow .input{padding:6px 8px;font-size:13px}.error{color:#ef4444;font-size:14px}.success{color:#22c55e}.muted{color:var(--muted)}.room-layout{display:grid;grid-template-columns:minmax(0,1fr) 340px;gap:20px}.player{aspect-ratio:16/9;background:#050505;display:grid;place-items:center;position:relative}.player video{width:100%;height:100%;background:#000;cursor:pointer}.player-top{position:absolute;top:10px;right:10px;display:flex;gap:8px;z-index:3}.player-top .chip{background:rgba(0,0,0,.55);color:#fff;border-radius:4px;padding:3px 8px;font-size:12px;font-variant-numeric:tabular-nums}.player-bar{position:absolute;left:0;right:0;bottom:0;display:flex;align-items:center;gap:10px;padding:12px 14px;background:linear-gradient(to top,rgba(0,0,0,.78),transparent);opacity:0;transition:opacity .2s;z-index:3}.playLine truncated
|
||||
@media(max-width:1000px){.grid{grid-template-columns:repeat(2,1fr)}.room-layout{grid-template-columns:1fr}.metric-grid{grid-template-columns:repeat(2,1fr)}.sidebar-layout{grid-template-columns:1fr}.sidebar{flex-direction:row;overflow:auto}.sidebar a{white-space:nowrap}}
|
||||
@media(max-width:640px){.header{padding:10px 16px;height:auto;gap:12px;flex-wrap:wrap}.header-actions{gap:10px}.theme-select{width:90px}.brand{font-size:18px}.header nav{order:3;width:100%;display:flex;justify-content:space-around;border-top:1px solid var(--border);padding-top:9px}main{width:calc(100% - 28px);padding-top:20px}.hero{padding:25px}.hero h1{font-size:26px}.grid{grid-template-columns:1fr;gap:14px}.two-col{grid-template-columns:1fr}.metric-grid{grid-template-columns:1fr 1fr}.panel{padding:17px}footer{flex-direction:column;gap:6px}}
|
||||
|
||||
/* Admin workspace */
|
||||
.admin-layout{align-items:start}.sidebar-title{padding:12px}.admin-content{min-width:0}.admin-toolbar{display:flex;align-items:flex-start;justify-content:space-between;gap:18px;margin-bottom:18px}.admin-toolbar h1{margin-bottom:4px}.admin-toolbar p{margin-bottom:0}.admin-two-col{display:grid;grid-template-columns:1fr 1fr;gap:20px;margin-top:20px}.health-list{display:grid;gap:12px}.health-list>div{display:flex;justify-content:space-between;border-bottom:1px solid var(--border);padding-bottom:10px}.status-dot{color:#f59e0b}.status-ok{color:#22c55e}.list-toolbar{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:14px}.list-toolbar .input{width:min(360px,100%)}.table-wrap{overflow:auto}.table-link{color:var(--accent)}.small{padding:6px 9px;font-size:12px}.danger{color:#ef4444;background:rgba(239,68,68,.1)}.tag{display:inline-block;padding:2px 7px;border-radius:999px;background:var(--surface-2);font-size:12px}.tag-ok{color:#16a34a;background:rgba(34,197,94,.1)}.category-layout{grid-template-columns:minmax(280px,360px) minmax(0,1fr);margin-top:0}.settings-panel{max-width:780px}.readonly-note{padding:12px 14px;margin-bottom:18px;background:#fff7ed;color:#c2410c;border-radius:7px}.qrow .input{width:100px}.admin-content .data-table td{vertical-align:top}
|
||||
|
||||
/* Live danmaku and replay */
|
||||
.streamer h2{margin:0}.live-return{margin-left:auto}.danmaku-layer{position:absolute;inset:0;overflow:hidden;pointer-events:none;z-index:2}.danmaku-item{position:absolute;left:100%;white-space:nowrap;font-size:16px;font-weight:600;text-shadow:0 1px 3px #000,0 0 2px #000;animation-name:danmaku-run;animation-timing-function:linear;animation-fill-mode:forwards}.danmaku-item b{font-size:12px;opacity:.85}.danmaku-paused .danmaku-item{animation-play-state:paused}@keyframes danmaku-run{from{transform:translateX(0)}to{transform:translateX(calc(-100vw - 100%))}}.danmaku-toggle{width:auto;border-radius:14px;padding:0 11px;font-size:13px}.danmaku-toggle.off{opacity:.5;text-decoration:line-through}.replay-chip{background:#7c3aed!important}.replay-progress{flex:1;min-width:80px;accent-color:var(--accent)}.time-label{color:#fff;font-size:12px;font-variant-numeric:tabular-nums}.replay-progress+.time-label{margin-right:auto}.replay-list{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.replay-card{display:flex;align-items:center;text-align:left;gap:12px;padding:12px;border:1px solid var(--border);border-radius:8px;background:var(--surface);color:var(--text);cursor:pointer}.replay-card:hover,.replay-card.active{border-color:var(--accent);background:rgba(255,91,71,.06)}.replay-card span:last-child{min-width:0}.replay-card small{display:block;color:var(--muted);margin-top:3px}.replay-icon{display:grid;place-items:center;width:34px;height:34px;border-radius:50%;background:var(--accent);color:#fff;flex-shrink:0}.replay-section,.room-layout section>.panel:not(.streamer){margin-top:20px}.section-head.compact{margin:0 0 14px}.section-head.compact>div{display:flex;align-items:center;gap:12px}.section-head.compact h2,.section-head.compact h3{margin:0}.chat>h3{display:flex;justify-content:space-between}.chat .search{margin-top:14px}.chat .search .input{min-width:0}.chat .search .button{flex-shrink:0}.chat-list{height:400px;overflow:auto;scrollbar-width:thin}.chat-list p{overflow-wrap:anywhere}
|
||||
|
||||
@media(max-width:1000px){.admin-two-col{grid-template-columns:1fr}.category-layout{grid-template-columns:1fr}.replay-list{grid-template-columns:1fr 1fr}}
|
||||
@media(max-width:640px){.admin-toolbar{align-items:center}.admin-toolbar p{display:none}.replay-list{grid-template-columns:1fr}.vol{display:none}.time-label{display:none}.player-bar{gap:6px;padding:8px}.danmaku-item{font-size:14px}}
|
||||
@@ -0,0 +1,173 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue';
|
||||
import { useRoute, useRouter } from 'vue-router';
|
||||
import { api } from '../api';
|
||||
import { useAppStore } from '../stores/app';
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const store = useAppStore();
|
||||
const section = computed(() => String(route.params.section ?? 'dashboard'));
|
||||
const isSuperAdmin = computed(() => store.user?.roles.includes('SUPER_ADMIN') ?? false);
|
||||
const error = ref('');
|
||||
const notice = ref('');
|
||||
const loading = ref(false);
|
||||
const busy = ref(false);
|
||||
const data = ref<any>([]);
|
||||
const health = ref<Record<string, { status: string }>>({});
|
||||
const search = ref('');
|
||||
const settings = reactive<Record<string, any>>({});
|
||||
const test = reactive({ email: '', phone: '' });
|
||||
const categoryForm = reactive({ id: 0, name: '', slug: '', icon: '', sort: 0, enabled: true });
|
||||
const adminForm = reactive({ username: '', nickname: '', email: '', password: '', role: 'ADMIN' });
|
||||
const allNav = [['dashboard', '仪表盘'], ['users', '用户管理'], ['notices', '开播申请'], ['rooms', '直播管理'], ['sessions', '直播记录'], ['replays', '回放管理'], ['categories', '分类管理'], ['messages', '消息管理'], ['files', '文件管理'], ['logs', '系统日志'], ['basic', '基础设置'], ['register', '注册设置'], ['smtp', '邮件设置'], ['sms', '短信设置'], ['password', '密码策略'], ['live', '直播设置'], ['security', '安全设置'], ['admins', '管理员管理']];
|
||||
const nav = computed(() => allNav.filter(item => item[0] !== 'admins' || isSuperAdmin.value));
|
||||
const settingSections = ['basic', 'register', 'smtp', 'sms', 'password', 'live', 'security'];
|
||||
const filteredData = computed(() => {
|
||||
const rows = Array.isArray(data.value) ? data.value : [];
|
||||
const query = search.value.trim().toLowerCase();
|
||||
return query ? rows.filter((row: any) => JSON.stringify(row).toLowerCase().includes(query)) : rows;
|
||||
});
|
||||
|
||||
function messageOf(value: unknown) { return value instanceof Error ? value.message : '操作失败,请稍后再试'; }
|
||||
function flash(message: string) {
|
||||
notice.value = message;
|
||||
window.setTimeout(() => { if (notice.value === message) notice.value = ''; }, 3500);
|
||||
}
|
||||
async function load() {
|
||||
loading.value = true; error.value = ''; search.value = '';
|
||||
try {
|
||||
if (section.value === 'dashboard') {
|
||||
const [dashboard, status] = await Promise.all([
|
||||
api<{ data: Record<string, any> }>('/api/admin/dashboard'),
|
||||
api<{ data: Record<string, { status: string }> }>('/api/admin/health')
|
||||
]);
|
||||
data.value = dashboard.data; health.value = status.data;
|
||||
} else if (['users', 'notices', 'rooms', 'sessions', 'replays', 'messages', 'files', 'categories', 'logs', 'admins'].includes(section.value)) {
|
||||
data.value = (await api<{ data: any[] }>(`/api/admin/${section.value}${section.value === 'users' ? '?limit=100' : ''}`)).data;
|
||||
} else if (settingSections.includes(section.value)) {
|
||||
Object.assign(settings, (await api<{ data: Record<string, unknown> }>('/api/admin/settings')).data);
|
||||
} else await router.replace('/admin/dashboard');
|
||||
} catch (value) { error.value = messageOf(value); }
|
||||
finally { loading.value = false; }
|
||||
}
|
||||
async function action(path: string, method = 'POST', body?: object, success = '操作成功') {
|
||||
busy.value = true; error.value = '';
|
||||
try {
|
||||
await api(path, { method, body: body ? JSON.stringify(body) : undefined });
|
||||
flash(success); await load(); return true;
|
||||
} catch (value) { error.value = messageOf(value); return false; }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
async function confirmAction(message: string, path: string, method = 'POST', body?: object, success?: string) {
|
||||
if (window.confirm(message)) await action(path, method, body, success);
|
||||
}
|
||||
async function saveSettings() {
|
||||
if (!isSuperAdmin.value) return;
|
||||
busy.value = true; error.value = '';
|
||||
try {
|
||||
const result = await api<{ data: Record<string, unknown> }>('/api/admin/settings', { method: 'PUT', body: JSON.stringify({ values: settings }) });
|
||||
Object.assign(settings, result.data); flash('设置已保存,将在 30 秒缓存窗口内全站生效');
|
||||
} catch (value) { error.value = messageOf(value); }
|
||||
finally { busy.value = false; }
|
||||
}
|
||||
async function testService(type: 'smtp' | 'sms') {
|
||||
await action(`/api/admin/settings/${type}/test`, 'POST', type === 'smtp' ? { email: test.email } : { phone: test.phone }, type === 'smtp' ? '测试邮件已发送' : '测试短信已发送');
|
||||
}
|
||||
async function resetPassword(user: any) {
|
||||
const password = window.prompt(`为 ${user.nickname} 设置新密码(需满足当前密码策略)`);
|
||||
if (password) await action(`/api/admin/users/${user.id}/reset-password`, 'POST', { password }, '密码已重置,该用户的其他登录会话已退出');
|
||||
}
|
||||
async function muteUser(user: any) {
|
||||
const raw = window.prompt(`禁言 ${user.nickname} 多少分钟?`, '60'); if (!raw) return;
|
||||
const minutes = Number(raw);
|
||||
if (Number.isInteger(minutes) && minutes > 0) await action(`/api/admin/users/${user.id}/chat-ban`, 'POST', { minutes }, `已禁言 ${minutes} 分钟`);
|
||||
else error.value = '请输入有效的禁言分钟数';
|
||||
}
|
||||
async function renameUser(user: any) {
|
||||
const nickname = window.prompt('输入新的用户昵称', user.nickname); if (!nickname || nickname === user.nickname) return;
|
||||
await action(`/api/admin/users/${user.id}`, 'PATCH', { nickname }, '用户昵称已更新');
|
||||
}
|
||||
function editCategory(category: any) { Object.assign(categoryForm, { id: category.id, name: category.name, slug: category.slug, icon: category.icon ?? '', sort: category.sort, enabled: category.enabled }); }
|
||||
function clearCategory() { Object.assign(categoryForm, { id: 0, name: '', slug: '', icon: '', sort: 0, enabled: true }); }
|
||||
async function saveCategory() {
|
||||
const body = { name: categoryForm.name.trim(), slug: categoryForm.slug.trim(), icon: categoryForm.icon.trim() || undefined, sort: categoryForm.sort, enabled: categoryForm.enabled };
|
||||
const ok = categoryForm.id ? await action(`/api/admin/categories/${categoryForm.id}`, 'PATCH', body, '分类已更新') : await action('/api/admin/categories', 'POST', body, '分类已创建');
|
||||
if (ok) clearCategory();
|
||||
}
|
||||
async function createAdmin() {
|
||||
const ok = await action('/api/admin/admins', 'POST', { ...adminForm }, '管理员已创建');
|
||||
if (ok) Object.assign(adminForm, { username: '', nickname: '', email: '', password: '', role: 'ADMIN' });
|
||||
}
|
||||
function formatDuration(value?: number) {
|
||||
if (value == null) return '-'; const hours = Math.floor(value / 3600), minutes = Math.floor(value % 3600 / 60), seconds = value % 60;
|
||||
return [hours ? `${hours}时` : '', minutes ? `${minutes}分` : '', `${seconds}秒`].join('');
|
||||
}
|
||||
function formatBytes(value?: number | string | null) {
|
||||
if (value == null) return '-'; const bytes = Number(value); if (!bytes) return '0 B';
|
||||
const units = ['B', 'KB', 'MB', 'GB']; const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
|
||||
return `${(bytes / 1024 ** i).toFixed(i ? 1 : 0)} ${units[i]}`;
|
||||
}
|
||||
|
||||
onMounted(async () => { if (!store.user) await store.bootstrap(); if (!store.isAdmin) { await router.replace('/login'); return; } await load(); });
|
||||
watch(section, async () => { if (section.value === 'admins' && !isSuperAdmin.value) { await router.replace('/admin/dashboard'); return; } await load(); });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="sidebar-layout admin-layout">
|
||||
<aside class="panel sidebar">
|
||||
<strong class="sidebar-title">管理后台</strong>
|
||||
<router-link v-for="item in nav" :key="item[0]" :to="`/admin/${item[0]}`">{{ item[1] }}</router-link>
|
||||
</aside>
|
||||
<section class="admin-content">
|
||||
<div class="admin-toolbar">
|
||||
<div><h1>{{ nav.find(item => item[0] === section)?.[1] }}</h1><p class="muted">所有操作均直接连接后台服务。</p></div>
|
||||
<button class="button" :disabled="loading" @click="load">{{ loading ? '加载中…' : '刷新数据' }}</button>
|
||||
</div>
|
||||
<p v-if="error" class="panel error">{{ error }}</p><p v-if="notice" class="panel success">{{ notice }}</p>
|
||||
<div v-if="loading" class="panel empty">正在读取后台数据…</div>
|
||||
|
||||
<template v-else-if="section === 'dashboard' && data.metrics">
|
||||
<div class="metric-grid"><div v-for="(value,key) in data.metrics" :key="key" class="metric"><span class="muted">{{ ({users:'用户总数',todayUsers:'今日新增',live:'正在直播',rooms:'房间总数',todaySessions:'今日直播',viewers:'在线观众'} as any)[key] ?? key }}</span><h2>{{ value }}</h2></div></div>
|
||||
<div class="admin-two-col">
|
||||
<div class="panel"><h2>服务健康</h2><div class="health-list"><div v-for="(value,key) in health" :key="key"><span>{{ ({application:'应用服务',database:'数据库',redis:'Redis',mediaServer:'媒体服务',smtp:'邮件服务',sms:'短信服务'} as any)[key] ?? key }}</span><span class="status-dot" :class="{'status-ok':value.status === '正常' || value.status === '已配置'}">{{ value.status }}</span></div></div></div>
|
||||
<div class="panel"><h2>运行环境</h2><p>Node {{ data.system.node }} · {{ data.system.platform }}</p><p>运行 {{ formatDuration(data.system.uptimeSeconds) }}</p><p>CPU {{ data.system.cpuUsage }}% · 内存 {{ Math.round(data.system.memory.used/1024/1024) }} / {{ Math.round(data.system.memory.total/1024/1024) }} MB</p><p class="muted">PostgreSQL {{ data.system.postgres }}<br>Redis {{ data.system.redis }} · 媒体服务器 {{ data.system.mediaServer }}</p></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="['users','notices','rooms','sessions','replays','messages','files','logs'].includes(section)">
|
||||
<div class="panel"><div class="list-toolbar"><input v-model="search" class="input" placeholder="搜索当前列表"><span class="muted">共 {{ filteredData.length }} 条</span></div><div class="table-wrap">
|
||||
<table v-if="section === 'users'" class="data-table"><thead><tr><th>用户</th><th>邮箱 / 手机</th><th>状态</th><th>直播</th><th>注册 / 登录</th><th>操作</th></tr></thead><tbody><tr v-for="user in filteredData" :key="user.id"><td><strong>{{ user.nickname }}</strong><br><small>{{ user.username }} · {{ user.roles.map((role:any)=>role.role.name).join(', ') }}</small></td><td>{{ user.email || '-' }}<br>{{ user.phone || '-' }}</td><td><span class="tag" :class="{'tag-ok':user.status==='ACTIVE'}">{{ user.status }}</span><br><small v-if="user.bans?.length" class="error">已禁言至 {{ user.bans[0].expiresAt?new Date(user.bans[0].expiresAt).toLocaleString():'永久' }}</small></td><td>{{ user.canStream ? '允许' : '禁止' }}</td><td><small>{{ new Date(user.createdAt).toLocaleString() }}<br>{{ user.lastLoginAt ? new Date(user.lastLoginAt).toLocaleString() : '从未登录' }}</small></td><td><div class="actions"><button class="button small" :disabled="busy" @click="action(`/api/admin/users/${user.id}`,'PATCH',{status:user.status==='ACTIVE'?'DISABLED':'ACTIVE'})">{{ user.status==='ACTIVE'?'禁用':'启用' }}</button><button class="button small" @click="action(`/api/admin/users/${user.id}`,'PATCH',{canStream:!user.canStream})">{{ user.canStream?'禁播':'恢复直播' }}</button><button v-if="user.bans?.length" class="button small" @click="action(`/api/admin/bans/${user.bans[0].id}`,'DELETE',undefined,'禁言已解除')">解除禁言</button><button v-else class="button small" @click="muteUser(user)">禁言</button><button class="button small" @click="renameUser(user)">改昵称</button><button class="button small" @click="resetPassword(user)">重置密码</button><button v-if="isSuperAdmin && user.id !== store.user?.id" class="button small danger" @click="confirmAction(`确认删除用户 ${user.nickname}?`,`/api/admin/users/${user.id}`,'DELETE',undefined,'用户已删除')">删除</button></div></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'notices'" class="data-table"><thead><tr><th>申请人</th><th>申请内容</th><th>时间</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="n in filteredData" :key="n.id"><td>{{ n.from.nickname }}<br><small>{{ n.from.username }}</small></td><td>{{ n.content }}</td><td>{{ new Date(n.createdAt).toLocaleString() }}</td><td><span class="tag" :class="{'tag-ok':n.status==='APPROVED'}">{{ ({PENDING:'待审核',APPROVED:'已批准',REJECTED:'已拒绝'} as any)[n.status] ?? n.status }}</span></td><td><div class="actions"><button v-if="n.status==='PENDING'" class="button small" @click="action(`/api/admin/notices/${n.id}/approve`,'POST',undefined,'已批准开播权限')">批准开播</button><button v-if="n.status==='PENDING'" class="button small danger" @click="confirmAction('确认拒绝该申请?',`/api/admin/notices/${n.id}/reject`,'POST',undefined,'已拒绝申请')">拒绝</button></div></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'rooms'" class="data-table"><thead><tr><th>房间</th><th>主播</th><th>可见性</th><th>状态</th><th>观看</th><th>操作</th></tr></thead><tbody><tr v-for="room in filteredData" :key="room.id"><td><router-link class="table-link" :to="`/room/${room.roomNumber}`">{{ room.roomNumber }} · {{ room.title }}</router-link><br><small v-if="room.featured" class="success">首页推荐</small></td><td>{{ room.owner.nickname }}</td><td>{{ room.visibility }}</td><td><span class="tag" :class="{'tag-ok':room.streamStatus==='LIVE'}">{{ room.streamStatus }}</span></td><td>{{ room.viewerCount }}</td><td><div class="actions"><button class="button small" @click="action(`/api/admin/rooms/${room.roomNumber}`,'PATCH',{featured:!room.featured},room.featured?'已取消推荐':'已设为推荐')">{{ room.featured?'取消推荐':'推荐' }}</button><button class="button small" @click="action(`/api/admin/rooms/${room.roomNumber}`,'PATCH',{visibility:room.visibility==='PUBLIC'?'PRIVATE':'PUBLIC'})">设为{{ room.visibility==='PUBLIC'?'私密':'公开' }}</button><button class="button small" :disabled="room.streamStatus!=='LIVE'" @click="confirmAction('确认强制断开这场直播?',`/api/admin/rooms/${room.roomNumber}/stop`)">断流</button><button class="button small" @click="confirmAction('确认更改该房间的直播权限?',`/api/admin/rooms/${room.roomNumber}/${room.liveBanned?'unban':'ban'}`)">{{ room.liveBanned?'恢复':'封禁' }}</button><button class="button small danger" @click="confirmAction('删除房间后直播记录和聊天消息也会删除,确认继续?',`/api/admin/rooms/${room.roomNumber}`,'DELETE',undefined,'直播间已删除')">删除</button></div></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'sessions'" class="data-table"><thead><tr><th>房间</th><th>主播</th><th>开始</th><th>结束</th><th>时长</th><th>峰值 / 浏览</th><th>回放</th></tr></thead><tbody><tr v-for="session in filteredData" :key="session.id"><td>{{ session.room.roomNumber }} · {{ session.room.title }}</td><td>{{ session.room.owner.nickname }}</td><td>{{ new Date(session.startedAt).toLocaleString() }}</td><td>{{ session.endedAt?new Date(session.endedAt).toLocaleString():'直播中' }}</td><td>{{ formatDuration(session.durationSeconds) }}</td><td>{{ session.peakViewers }} / {{ session.totalViews }}</td><td><a v-if="session.recordingUrl" class="table-link" :href="session.recordingUrl" target="_blank">打开回放</a><span v-else class="muted">未生成</span></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'messages'" class="data-table"><thead><tr><th>房间</th><th>用户</th><th>内容</th><th>时间</th><th>操作</th></tr></thead><tbody><tr v-for="message in filteredData" :key="message.id"><td>{{ message.room.roomNumber }}</td><td>{{ message.nickname }}</td><td :class="{muted:message.deletedAt}">{{ message.deletedAt?'[已删除]':message.content }}</td><td>{{ new Date(message.createdAt).toLocaleString() }}</td><td><button v-if="!message.deletedAt" class="button small danger" @click="confirmAction('确认删除这条消息?',`/api/admin/messages/${message.id}`,'DELETE')">删除</button></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'replays'" class="data-table"><thead><tr><th>房间</th><th>主播</th><th>开始</th><th>时长</th><th>大小</th><th>操作</th></tr></thead><tbody><tr v-for="session in filteredData" :key="session.id"><td>{{ session.room.roomNumber }} · {{ session.room.title }}</td><td>{{ session.room.owner.nickname }}</td><td>{{ new Date(session.startedAt).toLocaleString() }}</td><td>{{ formatDuration(session.durationSeconds) }}</td><td>{{ formatBytes(session.recordingSize) }}</td><td><div class="actions"><a class="button small" :href="`/api/admin/replays/${session.id}/download`">下载</a><a v-if="session.recordingUrl" class="button small" :href="session.recordingUrl" target="_blank">打开</a><button class="button small danger" @click="confirmAction('确认删除该回放?删除后观众将无法观看。',`/api/admin/replays/${session.id}`,'DELETE',undefined,'回放已删除')">删除</button></div></td></tr></tbody></table>
|
||||
<table v-else-if="section === 'files'" class="data-table"><thead><tr><th>文件</th><th>上传者</th><th>大小</th><th>时间</th><th>操作</th></tr></thead><tbody><tr v-for="file in filteredData" :key="file.id"><td><div class="file-cell"><img v-if="file.mimeType?.startsWith('image/')" class="file-thumb" :src="file.url" :alt="file.originalName||file.filename"><div><a class="table-link" :href="file.url" target="_blank">{{ file.originalName || file.filename }}</a><br><small class="muted">{{ file.mimeType }} · {{ file.url }}</small></div></div></td><td>{{ file.uploader?.nickname || '-' }}</td><td>{{ formatBytes(file.size) }}</td><td>{{ new Date(file.createdAt).toLocaleString() }}</td><td><div class="actions"><a class="button small" :href="`/api/admin/files/${file.id}/download`">下载</a><button class="button small danger" @click="confirmAction('确认删除该文件?使用它的头像/封面将失效。',`/api/admin/files/${file.id}`,'DELETE',undefined,'文件已删除')">删除</button></div></td></tr></tbody></table>
|
||||
<table v-else class="data-table"><thead><tr><th>时间</th><th>管理员</th><th>操作</th><th>对象</th><th>结果</th><th>IP</th></tr></thead><tbody><tr v-for="log in filteredData" :key="log.id"><td>{{ new Date(log.createdAt).toLocaleString() }}</td><td>{{ log.admin.nickname }}</td><td>{{ log.action }}</td><td>{{ log.targetType || '-' }} {{ log.targetId || '' }}</td><td>{{ log.result }}</td><td>{{ log.ip || '-' }}</td></tr></tbody></table>
|
||||
</div></div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="section === 'categories'"><div class="admin-two-col category-layout">
|
||||
<form class="panel form" @submit.prevent="saveCategory"><h2>{{ categoryForm.id?'编辑分类':'新增分类' }}</h2><label>名称<input v-model="categoryForm.name" class="input" required maxlength="64"></label><label>英文标识<input v-model="categoryForm.slug" class="input" required pattern="[a-z0-9-]+" placeholder="例如 technology"></label><label>图标标识<input v-model="categoryForm.icon" class="input"></label><label>排序<input v-model.number="categoryForm.sort" type="number" class="input"></label><label><span><input v-model="categoryForm.enabled" type="checkbox"> 启用</span></label><div class="actions"><button class="button primary-button" :disabled="busy">{{ categoryForm.id?'保存修改':'创建分类' }}</button><button v-if="categoryForm.id" type="button" class="button" @click="clearCategory">取消</button></div></form>
|
||||
<div class="panel table-wrap"><table class="data-table"><thead><tr><th>分类</th><th>标识</th><th>排序</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="category in data" :key="category.id"><td>{{ category.name }}</td><td>{{ category.slug }}</td><td>{{ category.sort }}</td><td>{{ category.enabled?'启用':'禁用' }}</td><td><div class="actions"><button class="button small" @click="editCategory(category)">编辑</button><button class="button small" @click="action(`/api/admin/categories/${category.id}`,'PATCH',{enabled:!category.enabled})">{{ category.enabled?'停用':'启用' }}</button><button class="button small danger" @click="confirmAction('确认删除该分类?',`/api/admin/categories/${category.id}`,'DELETE')">删除</button></div></td></tr></tbody></table></div>
|
||||
</div></template>
|
||||
|
||||
<template v-else-if="section === 'admins'"><div class="admin-two-col category-layout">
|
||||
<form class="panel form" @submit.prevent="createAdmin"><h2>新增管理员</h2><label>用户名<input v-model="adminForm.username" class="input" minlength="3" required></label><label>昵称<input v-model="adminForm.nickname" class="input" required></label><label>邮箱<input v-model="adminForm.email" type="email" class="input" required></label><label>初始密码<input v-model="adminForm.password" type="password" class="input" required></label><label>角色<select v-model="adminForm.role" class="input"><option value="ADMIN">管理员</option><option value="SUPER_ADMIN">超级管理员</option></select></label><button class="button primary-button" :disabled="busy">创建管理员</button></form>
|
||||
<div class="panel table-wrap"><table class="data-table"><thead><tr><th>管理员</th><th>邮箱</th><th>角色</th><th>状态</th><th>操作</th></tr></thead><tbody><tr v-for="user in data" :key="user.id"><td>{{ user.nickname }}<br><small>{{ user.username }}</small></td><td>{{ user.email }}</td><td>{{ user.roles.map((role:any)=>role.role.name).join(', ') }}</td><td>{{ user.status }}</td><td><div v-if="user.id!==store.user?.id" class="actions"><button class="button small" @click="action(`/api/admin/users/${user.id}`,'PATCH',{status:user.status==='ACTIVE'?'DISABLED':'ACTIVE'})">{{ user.status==='ACTIVE'?'禁用':'启用' }}</button><button class="button small" @click="action(`/api/admin/admins/${user.id}/role`,'PATCH',{role:user.roles.some((item:any)=>item.role.name==='SUPER_ADMIN')?'ADMIN':'SUPER_ADMIN'},'管理员角色已更新')">设为{{ user.roles.some((item:any)=>item.role.name==='SUPER_ADMIN')?'管理员':'超级管理员' }}</button></div><span v-else class="muted">当前账号</span></td></tr></tbody></table></div>
|
||||
</div></template>
|
||||
|
||||
<template v-else-if="settingSections.includes(section)"><div class="panel settings-panel"><div v-if="!isSuperAdmin" class="readonly-note">当前账号可以查看设置,但只有超级管理员可以修改。</div><form class="form" @submit.prevent="saveSettings">
|
||||
<template v-if="section === 'basic'"><label>站点名称<input v-model="settings['site.name']" class="input"></label><label>站点副标题<input v-model="settings['site.subtitle']" class="input"></label><label>站点描述<textarea v-model="settings['site.description']" class="input"></textarea></label><label>搜索关键词<input v-model="settings['site.keywords']" class="input"></label><label>Logo URL<input v-model="settings['site.logo']" class="input"></label><label>Dark Logo URL<input v-model="settings['site.darkLogo']" class="input"></label><label>Favicon URL<input v-model="settings['site.favicon']" class="input"></label><label>ICP备案文字<input v-model="settings['site.icp.text']" class="input"></label><label>ICP备案链接<input v-model="settings['site.icp.url']" class="input"></label><label>公安备案文字<input v-model="settings['site.police.text']" class="input"></label><label>公安备案链接<input v-model="settings['site.police.url']" class="input"></label><label>页脚文字<input v-model="settings['site.footer']" class="input"></label><label>版权信息<input v-model="settings['site.copyright']" class="input"></label><label>用户协议<textarea v-model="settings['site.userAgreement']" class="input" rows="10"></textarea><small>注册时弹窗展示,需滚动到底部才能勾选同意。</small></label></template>
|
||||
<template v-else-if="section === 'register'"><label><span><input v-model="settings['auth.register.email']" type="checkbox"> 邮箱注册</span></label><label><span><input v-model="settings['auth.register.sms']" type="checkbox"> 手机号注册</span></label><label>验证规则<select v-model="settings['auth.register.rule']" class="input"><option value="ANY">任意一种</option><option value="ALL">两者都必须</option></select></label><label><span><input v-model="settings['auth.register.requireVerification']" type="checkbox"> 注册必须验证码</span></label></template>
|
||||
<template v-else-if="section === 'smtp'"><label>SMTP Host<input v-model="settings['smtp.host']" class="input"></label><label>Port<input v-model.number="settings['smtp.port']" type="number" class="input"></label><label>Username<input v-model="settings['smtp.username']" class="input"></label><label>Password<input v-model="settings['smtp.password']" type="password" class="input" placeholder="留空保持不变"></label><label>Encryption<select v-model="settings['smtp.encryption']" class="input"><option>NONE</option><option>SSL</option><option>STARTTLS</option></select></label><label>发件人邮箱<input v-model="settings['smtp.fromEmail']" class="input"></label><label>发件人名称<input v-model="settings['smtp.fromName']" class="input"></label><label>测试收件箱<div class="search"><input v-model="test.email" type="email" class="input"><button type="button" class="button" :disabled="!isSuperAdmin||!test.email" @click="testService('smtp')">发送测试邮件</button></div></label></template>
|
||||
<template v-else-if="section === 'sms'"><label>AccessKey ID<input v-model="settings['sms.accessKeyId']" class="input"></label><label>AccessKey Secret<input v-model="settings['sms.accessKeySecret']" type="password" class="input" placeholder="留空保持不变"></label><label>短信签名<input v-model="settings['sms.signName']" class="input"></label><label>注册模板 ID<input v-model="settings['sms.registerTemplateId']" class="input"></label><label>登录模板 ID<input v-model="settings['sms.loginTemplateId']" class="input"></label><label>找回密码模板 ID<input v-model="settings['sms.resetTemplateId']" class="input"></label><label>测试手机号<div class="search"><input v-model="test.phone" class="input"><button type="button" class="button" :disabled="!isSuperAdmin||!test.phone" @click="testService('sms')">发送测试短信</button></div></label></template>
|
||||
<template v-else-if="section === 'password'"><label>最小长度<input v-model.number="settings['password.policy'].minLength" type="number" min="8" max="128" class="input"></label><label>最大长度<input v-model.number="settings['password.policy'].maxLength" type="number" min="8" max="256" class="input"></label><label><span><input v-model="settings['password.policy'].uppercase" type="checkbox"> 必须包含大写字母</span></label><label><span><input v-model="settings['password.policy'].lowercase" type="checkbox"> 必须包含小写字母</span></label><label><span><input v-model="settings['password.policy'].number" type="checkbox"> 必须包含数字</span></label><label><span><input v-model="settings['password.policy'].special" type="checkbox"> 必须包含特殊字符</span></label></template>
|
||||
<template v-else-if="section === 'live'"><label><span><input v-model="settings['live.allowRegisteredUsers']" type="checkbox"> 允许注册用户创建直播间</span></label><label><span><input v-model="settings['live.newUserCanStream']" type="checkbox"> 新用户默认允许直播</span></label><label>最大同时直播数<input v-model.number="settings['live.maxConcurrent']" type="number" min="1" class="input"></label><label>单用户最大直播间数<input v-model.number="settings['live.maxPerUser']" type="number" min="1" class="input"></label><label>最大码率 Kbps<input v-model.number="settings['live.maxBitrateKbps']" type="number" min="1" class="input"></label><label>最大 FPS<input v-model.number="settings['live.maxFps']" type="number" min="1" class="input"></label><label><span><input v-model="settings['live.showPlayerLatency']" type="checkbox"> 播放器显示直播延迟</span></label><label>播放协议<select v-model="settings['live.playback.protocol']" class="input"><option value="FLV">FLV(低延迟,直连源站)</option><option value="HLS">HLS(走 CDN 加速)</option></select></label><label>FLV 直连播放域名<input v-model="settings['live.playback.flvHost']" class="input" placeholder="如 live.example.com,留空则跟随当前访问域名"></label><div class="qblock"><span>转码清晰度列表</span><div v-for="(quality,index) in settings['live.transcode.qualities']" :key="index" class="qrow"><input v-model="quality.label" class="input" placeholder="名称"><input v-model.number="quality.width" type="number" min="1" class="input" placeholder="宽"><span>×</span><input v-model.number="quality.height" type="number" min="1" class="input" placeholder="高"><input v-model.number="quality.bitrate" type="number" min="1" class="input" placeholder="码率"><input v-model.number="quality.fps" type="number" min="1" class="input" placeholder="帧率"><label><span><input v-model="quality.enabled" type="checkbox">启用</span></label><button type="button" class="button" @click="settings['live.transcode.qualities'].splice(index,1)">删除</button></div><button type="button" class="button" @click="settings['live.transcode.qualities'].push({label:'1080P',width:1920,height:1080,bitrate:3000,fps:30,enabled:true})">+ 添加清晰度</button></div></template>
|
||||
<template v-else><label><span><input v-model="settings['auth.guestViewing']" type="checkbox"> 允许游客观看</span></label><label>登录失败锁定阈值<input v-model.number="settings['security.loginMaxFailures']" type="number" min="1" class="input"></label><label>锁定分钟数<input v-model.number="settings['security.loginLockMinutes']" type="number" min="1" class="input"></label></template>
|
||||
<button class="button primary-button" :disabled="busy||!isSuperAdmin">{{ busy?'保存中…':isSuperAdmin?'保存设置':'仅超级管理员可保存' }}</button>
|
||||
</form></div></template>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,16 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'; import { useRouter } from 'vue-router'; import { useAppStore } from '../stores/app'; import { api } from '../api';
|
||||
const props=defineProps<{mode:'login'|'register'|'forgot'}>(),store=useAppStore(),router=useRouter(),busy=ref(false),error=ref(''),message=ref('');
|
||||
const form=reactive({account:'',username:'',nickname:'',email:'',phone:'',password:'',emailCode:'',smsCode:'',captchaText:'',newPassword:''}); const title=computed(()=>props.mode==='login'?'登录':props.mode==='register'?'创建账号':'找回密码');
|
||||
const captcha=reactive({id:'',image:''});
|
||||
const emailEnabled=computed(()=>store.settings['auth.register.email']!==false);
|
||||
const smsEnabled=computed(()=>store.settings['auth.register.sms']===true);
|
||||
const agreementOpen=ref(false),agreed=ref(false),scrolledToBottom=ref(false); const agreementText=computed(()=>String(store.settings['site.userAgreement']||''));
|
||||
async function loadCaptcha(){try{const res=await api<{data:{captchaId:string,image:string}}>('/api/auth/captcha');captcha.id=res.data.captchaId;captcha.image=res.data.image}catch(e){error.value=(e as {message:string}).message}}
|
||||
onMounted(()=>{if(props.mode!=='login')loadCaptcha();if(!store.loaded)void store.bootstrap()});
|
||||
function onAgreementScroll(e:Event){const el=e.target as HTMLDivElement;scrolledToBottom.value=el.scrollTop+el.clientHeight>=el.scrollHeight-8}
|
||||
function confirmAgreement(){agreed.value=true;agreementOpen.value=false;void submit()}
|
||||
async function submit(){if(props.mode==='register'&&!agreed.value){agreementOpen.value=true;return}busy.value=true;error.value='';try{if(props.mode==='login'){await store.login(form.account,form.password);router.push('/')}else if(props.mode==='register'){await api('/api/auth/register',{method:'POST',body:JSON.stringify({username:form.username,nickname:form.nickname,email:form.email||undefined,phone:form.phone||undefined,password:form.password,emailCode:form.emailCode||undefined,smsCode:form.smsCode||undefined})});message.value='注册成功,请登录';setTimeout(()=>router.push('/login'),800)}else{await api('/api/auth/reset-password',{method:'POST',body:JSON.stringify({channel:'EMAIL',target:form.email,code:form.emailCode,newPassword:form.newPassword})});message.value='密码已重置';}}catch(e){error.value=(e as {message:string}).message}finally{busy.value=false}}
|
||||
async function sendCode(channel:'EMAIL'|'SMS'){error.value='';message.value='';if(!form.captchaText){error.value='请先输入图形验证码';return}try{const target=channel==='EMAIL'?form.email:form.phone;await api(channel==='EMAIL'?'/api/auth/email/send-code':'/api/auth/sms/send-code',{method:'POST',body:JSON.stringify({[channel==='EMAIL'?'email':'phone']:target,purpose:props.mode==='forgot'?'RESET_PASSWORD':'REGISTER',captchaId:captcha.id,captchaText:form.captchaText})});message.value=channel==='EMAIL'?'验证码已发送,请检查邮箱':'验证码已发送,请检查短信'}catch(e){error.value=(e as {message:string}).message;loadCaptcha();form.captchaText=''}}
|
||||
</script>
|
||||
<template><div class="auth-wrap panel"><h1>{{title}}</h1><form class="form" @submit.prevent="submit"><template v-if="mode==='login'"><label>账号<input v-model="form.account" class="input" autocomplete="username" required placeholder="用户名 / 邮箱 / 手机号"></label><label>密码<input v-model="form.password" class="input" type="password" autocomplete="current-password" required></label></template><template v-else-if="mode==='register'"><label>用户名<input v-model="form.username" class="input" required minlength="3"></label><label>昵称<input v-model="form.nickname" class="input" required></label><label v-if="emailEnabled">邮箱<input v-model="form.email" class="input" type="email"></label><label v-if="smsEnabled">手机号<input v-model="form.phone" class="input"></label><label>密码<input v-model="form.password" class="input" type="password" required><small>密码规则由平台管理员统一配置,服务端会再次校验。</small></label><label>图形验证码<div class="search"><img class="captcha-img" :src="captcha.image" alt="图形验证码" title="点击刷新" @click="loadCaptcha"><input v-model="form.captchaText" class="input" placeholder="输入图片中的英文字母" autocomplete="off"></div></label><label v-if="emailEnabled">邮箱验证码<div class="search"><input v-model="form.emailCode" class="input"><button type="button" class="button" @click="sendCode('EMAIL')">发送</button></div></label><label v-if="smsEnabled">手机验证码<div class="search"><input v-model="form.smsCode" class="input"><button type="button" class="button" @click="sendCode('SMS')">发送</button></div></label></template><template v-else><label>邮箱<input v-model="form.email" class="input" type="email" required></label><label>图形验证码<div class="search"><img class="captcha-img" :src="captcha.image" alt="图形验证码" title="点击刷新" @click="loadCaptcha"><input v-model="form.captchaText" class="input" placeholder="输入图片中的英文字母" autocomplete="off"></div></label><label>验证码<div class="search"><input v-model="form.emailCode" class="input" required><button type="button" class="button" @click="sendCode('EMAIL')">发送</button></div></label><label>新密码<input v-model="form.newPassword" type="password" class="input" required></label></template><p v-if="error" class="error">{{error}}</p><p v-if="message" class="success">{{message}}</p><button class="button primary-button" :disabled="busy">{{busy?'请稍候…':title}}</button><div><router-link v-if="mode==='login'" to="/forgot-password" class="muted">忘记密码</router-link><router-link v-if="mode!=='login'" to="/login" class="muted"> 返回登录</router-link></div></form><div v-if="agreementOpen" class="modal-mask" @click.self="agreementOpen=false"><div class="modal-card"><h3>用户协议</h3><div class="agreement-box" @scroll="onAgreementScroll">{{agreementText}}</div><p v-if="!scrolledToBottom" class="muted">请阅读协议内容并滚动到底部</p><label><span><input v-model="agreed" type="checkbox" :disabled="!scrolledToBottom"> 我已阅读并同意《用户协议》</span></label><div class="actions"><button type="button" class="button" @click="agreementOpen=false">取消</button><button type="button" class="button primary-button" :disabled="!agreed" @click="confirmAgreement">同意并继续注册</button></div></div></div></div></template>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, watch } from 'vue'; import { useRoute, useRouter } from 'vue-router'; import { api } from '../api';
|
||||
type Room={roomNumber:number;title:string;cover?:string;streamStatus:string;viewerCount:number;owner:{nickname:string;avatar?:string};category?:{name:string;slug:string}}; type Category={id:number;name:string;slug:string};
|
||||
const route=useRoute(),router=useRouter(),rooms=ref<Room[]>([]),categories=ref<Category[]>([]),loading=ref(true),search=ref(String(route.query.q??'')),error=ref('');
|
||||
async function load(){loading.value=true;error.value='';try{const params=new URLSearchParams({status:'LIVE'});const slug=String(route.params.slug??'');if(slug)params.set('category',slug);if(route.path==='/search'&&route.query.q)params.set('search',String(route.query.q));rooms.value=(await api<{data:Room[]}>(`/api/rooms?${params}`)).data;categories.value=(await api<{data:Category[]}>('/api/categories')).data}catch(e){error.value=(e as {message:string}).message}finally{loading.value=false}}
|
||||
function doSearch(){router.push({path:'/search',query:{q:search.value}})} onMounted(load);watch(()=>route.fullPath,load);
|
||||
</script>
|
||||
<template><section class="hero"><div><h1>此刻,正在发生</h1><p>发现真实、即时的内容,或创建自己的直播间,通过 OBS 即刻开播。</p><div class="search"><input v-model="search" class="input" placeholder="搜索直播标题、主播" @keyup.enter="doSearch"><button class="button primary-button" @click="doSearch">搜索</button></div></div><button class="button" @click="$router.push('/me/room')">我要开播</button></section>
|
||||
<div class="section-head"><h2>{{route.path==='/search'?`“${route.query.q??''}” 的结果`:'正在直播'}}</h2><div><router-link v-for="c in categories" :key="c.id" :to="`/categories/${c.slug}`" style="margin-left:16px" class="muted">{{c.name}}</router-link></div></div>
|
||||
<p v-if="error" class="error">{{error}}</p><p v-else-if="loading" class="muted">正在加载直播间…</p><div v-else-if="rooms.length" class="grid"><router-link v-for="room in rooms" :key="room.roomNumber" :to="`/room/${room.roomNumber}`" class="room-card"><div class="cover"><img v-if="room.cover" :src="room.cover" :alt="room.title"><span class="live-badge">直播中</span><span class="viewer">{{room.viewerCount}} 人</span></div><div class="card-body"><div class="card-title">{{room.title}}</div><div class="card-meta"><span>{{room.owner.nickname}}</span><span>{{room.category?.name??'未分类'}}</span></div></div></router-link></div><div v-else class="panel muted">暂时没有符合条件的直播,稍后再来看看。</div></template>
|
||||
@@ -0,0 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, reactive, ref } from 'vue'; import { api } from '../api'; import { useAppStore } from '../stores/app';
|
||||
type Room={roomNumber:number;title:string;description?:string;announcement?:string;cover?:string;visibility:'PUBLIC'|'PRIVATE';showViewerCount:boolean;recordReplay?:boolean;streamStatus:string;sessions:{id:string;startedAt:string;endedAt?:string;durationSeconds?:number;peakViewers:number;recordingUrl?:string}[]};
|
||||
const store=useAppStore(),rooms=ref<Room[]>([]),error=ref(''),saved=ref(''),key=ref<{server:string;streamKey:string;playback:string}|null>(null),showKey=ref(false); const current=computed(()=>rooms.value[0]); const form=reactive({title:'我的直播间',description:'',announcement:'',cover:'',visibility:'PUBLIC',showViewerCount:true,recordReplay:true});
|
||||
const coverInput=ref<HTMLInputElement>(),applyContent=ref(''),applyStatus=ref<{status:string;createdAt?:string}|null>(null);
|
||||
async function load(){try{rooms.value=(await api<{data:Room[]}>('/api/users/me/rooms')).data;if(current.value)Object.assign(form,current.value)}catch(e){error.value=(e as {message:string}).message}}
|
||||
async function loadApply(){if(!store.user||store.user.canStream)return;try{applyStatus.value=(await api<{data:{status:string}|null}>('/api/notices/stream-permission')).data}catch(e){error.value=(e as {message:string}).message}}
|
||||
async function applyStream(){try{await api('/api/notices/stream-permission',{method:'POST',body:JSON.stringify({content:applyContent.value})});saved.value='申请已提交,请等待管理员审核';await loadApply()}catch(e){error.value=(e as {message:string}).message}}
|
||||
async function save(){try{if(current.value)await api(`/api/rooms/${current.value.roomNumber}`,{method:'PATCH',body:JSON.stringify(form)});else await api('/api/rooms',{method:'POST',body:JSON.stringify(form)});saved.value='已保存';await load()}catch(e){error.value=(e as {message:string}).message}}
|
||||
async function uploadCover(e:Event){const file=(e.target as HTMLInputElement).files?.[0];if(!file)return;try{const fd=new FormData();fd.append('file',file);const res=await api<{data:{url:string}}>('/api/uploads/images',{method:'POST',body:fd});form.cover=res.data.url;saved.value='封面已上传,点击"保存直播设置"生效'}catch(err){error.value=(err as {message:string}).message}}
|
||||
async function loadKey(){if(!current.value)return;key.value=(await api<{data:{server:string;streamKey:string;playback:string}}>(`/api/rooms/${current.value.roomNumber}/stream`)).data}
|
||||
async function rotate(){if(!current.value||!confirm('重新生成后,旧推流密钥将立即失效,OBS 中需要重新配置。确定继续?'))return;const r=await api<{data:{streamKey:string}}>(`/api/rooms/${current.value.roomNumber}/stream/rotate`,{method:'POST'});if(key.value)key.value.streamKey=r.data.streamKey;showKey.value=true}
|
||||
async function copy(v:string){await navigator.clipboard.writeText(v);saved.value='已复制'} onMounted(async()=>{if(!store.user)await store.bootstrap();await loadApply();await load();if(current.value)await loadKey()});
|
||||
</script>
|
||||
<template><div class="sidebar-layout"><aside class="panel sidebar"><router-link to="/me/room">直播设置</router-link><router-link to="/me/stream">推流设置</router-link><router-link to="/me/sessions">直播记录</router-link></aside><section><div v-if="store.user&&!store.user.canStream" class="panel"><h2>开播权限</h2><template v-if="applyStatus?.status==='PENDING'"><p class="success">申请已提交,等待管理员审核中</p></template><template v-else><p class="muted">您当前没有开播权限。向管理员提交申请,批准后即可创建直播间并推流。</p><textarea v-model="applyContent" class="input" rows="3" maxlength="1000" placeholder="申请理由(可选)"></textarea><button type="button" class="button primary-button" @click="applyStream">提交开播申请</button><p v-if="applyStatus?.status==='REJECTED'" class="error">上次申请未通过,可重新提交</p></template></div><div class="panel" style="margin-top:20px"><h1>我的直播间</h1><p v-if="current" class="muted">房间号 {{current.roomNumber}} · {{current.streamStatus}}</p><form class="form" @submit.prevent="save"><label>直播标题<input v-model="form.title" class="input" required maxlength="120"></label><label>封面<div class="search"><input v-model="form.cover" class="input" placeholder="图片 URL,或点击上传(JPG / PNG / WebP,推荐 16:9)"><button type="button" class="button" @click="coverInput?.click()">上传</button></div><img v-if="form.cover" class="cover-preview" :src="form.cover" alt="封面预览"><input ref="coverInput" type="file" accept="image/jpeg,image/png,image/webp" hidden @change="uploadCover"></label><label>直播简介<textarea v-model="form.description" class="input" rows="3"></textarea></label><label>直播公告<textarea v-model="form.announcement" class="input" rows="3"></textarea></label><label>可见性<select v-model="form.visibility" class="input"><option value="PUBLIC">公开</option><option value="PRIVATE">私有(仅可通过房间号进入)</option></select></label><label><span><input v-model="form.showViewerCount" type="checkbox"> 显示在线人数</span></label><label><span><input v-model="form.recordReplay" type="checkbox"> 生成直播回放</span><small>在开播前设置,对下一场直播生效。关闭后本场直播结束不保留回放。</small></label><p v-if="error" class="error">{{error}}</p><p v-if="saved" class="success">{{saved}}</p><button class="button primary-button">{{current?'保存直播设置':'创建直播间'}}</button></form></div>
|
||||
<div v-if="current&&key" class="panel" style="margin-top:20px"><h2>OBS 推流设置</h2><p class="muted">推流真正接入 SRS 后,直播状态才会自动变为 LIVE。</p><div class="form"><label>RTMP Server<div class="search"><input :value="key.server" readonly class="input"><button type="button" class="button" @click="copy(key.server)">复制</button></div></label><label>Stream Key<input :value="showKey?key.streamKey:'••••••••••••••••••••'" readonly class="input"></label><div><button type="button" class="button" @click="showKey=!showKey">{{showKey?'隐藏':'显示'}}</button> <button type="button" class="button" @click="copy(key.streamKey)">复制</button> <button type="button" class="button" @click="rotate">重新生成</button></div></div></div>
|
||||
<div v-if="current?.sessions?.length" class="panel" style="margin-top:20px"><h2>直播记录</h2><table class="data-table"><thead><tr><th>开始</th><th>结束</th><th>时长</th><th>峰值在线</th><th>回放</th></tr></thead><tbody><tr v-for="s in current.sessions" :key="s.id"><td>{{new Date(s.startedAt).toLocaleString()}}</td><td>{{s.endedAt?new Date(s.endedAt).toLocaleString():'直播中'}}</td><td>{{s.durationSeconds??'-'}} 秒</td><td>{{s.peakViewers}}</td><td><router-link v-if="s.recordingUrl" class="table-link" :to="`/room/${current.roomNumber}`">观看</router-link><span v-else class="muted">未生成</span></td></tr></tbody></table></div></section></div></template>
|
||||
@@ -0,0 +1,10 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'; import { api } from '../api'; import { useAppStore } from '../stores/app';
|
||||
const store=useAppStore(),error=ref(''),message=ref('');const profile=reactive({nickname:'',bio:'',avatar:''}),password=reactive({currentPassword:'',newPassword:''});
|
||||
const avatarInput=ref<HTMLInputElement>();
|
||||
onMounted(async()=>{if(!store.user)await store.bootstrap();if(store.user)Object.assign(profile,{nickname:store.user.nickname,avatar:store.user.avatar??''})});
|
||||
async function save(){try{await api('/api/users/me',{method:'PATCH',body:JSON.stringify(profile)});message.value='资料已更新';await store.bootstrap()}catch(e){error.value=(e as {message:string}).message}}
|
||||
async function uploadAvatar(e:Event){const file=(e.target as HTMLInputElement).files?.[0];if(!file)return;try{const fd=new FormData();fd.append('file',file);const res=await api<{data:{url:string}}>('/api/uploads/images',{method:'POST',body:fd});profile.avatar=res.data.url;message.value='头像已上传,点击"保存资料"生效'}catch(err){error.value=(err as {message:string}).message}}
|
||||
async function change(){try{await api('/api/auth/change-password',{method:'POST',body:JSON.stringify(password)});message.value='密码已修改,请重新登录'}catch(e){error.value=(e as {message:string}).message}}
|
||||
</script>
|
||||
<template><div class="sidebar-layout"><aside class="panel sidebar"><router-link to="/me">账号信息</router-link><router-link to="/me/security">安全设置</router-link><router-link to="/me/room">我的直播间</router-link></aside><section><div class="panel"><h1>个人中心</h1><form class="form" @submit.prevent="save"><label>昵称<input v-model="profile.nickname" class="input"></label><label>头像<div class="search"><input v-model="profile.avatar" class="input" placeholder="图片 URL,或点击上传"><button type="button" class="button" @click="avatarInput?.click()">上传</button></div><img v-if="profile.avatar" class="avatar-preview" :src="profile.avatar" alt="头像预览"><input ref="avatarInput" type="file" accept="image/jpeg,image/png,image/webp" hidden @change="uploadAvatar"></label><label>个人简介<textarea v-model="profile.bio" class="input"></textarea></label><button class="button primary-button">保存资料</button></form></div><div class="panel" style="margin-top:20px"><h2>修改密码</h2><form class="form" @submit.prevent="change"><label>当前密码<input v-model="password.currentPassword" type="password" class="input"></label><label>新密码<input v-model="password.newPassword" type="password" class="input"></label><button class="button">修改密码</button></form><p v-if="error" class="error">{{error}}</p><p v-if="message" class="success">{{message}}</p></div></section></div></template>
|
||||
@@ -0,0 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'; import { api } from '../api';
|
||||
type Replay={id:string;startedAt:string;endedAt:string;durationSeconds?:number;peakViewers:number;recordingUrl:string;room:{roomNumber:number;title:string;cover?:string}};
|
||||
const items=ref<Replay[]>([]),error=ref(''),page=ref(1),total=ref(0),loading=ref(false);
|
||||
async function load(){loading.value=true;try{const res=await api<{data:Replay[];meta:{total:number}}>(`/api/replays?page=${page.value}`);items.value.push(...res.data);total.value=res.meta.total}catch(e){error.value=(e as Error).message}finally{loading.value=false}}
|
||||
function fmt(v:string){return new Date(v).toLocaleString()}
|
||||
onMounted(load);
|
||||
</script>
|
||||
<template><div><div class="section-head"><h2>直播回放</h2><span class="muted">共 {{ total }} 场</span></div><p v-if="error" class="error">{{ error }}</p><div class="grid"><router-link v-for="r in items" :key="r.id" :to="`/room/${r.room.roomNumber}?replay=${r.id}`" class="room-card"><div class="cover"><img v-if="r.room.cover" :src="r.room.cover" :alt="r.room.title"><span class="replay-badge">回放</span></div><div class="card-body"><div class="card-title">{{ r.room.title }} · {{ fmt(r.startedAt) }}</div><div class="card-meta"><span>{{ r.durationSeconds??'-' }} 秒</span><span>{{ r.peakViewers }} 人在线</span></div></div></router-link></div><div v-if="!items.length&&!loading" class="panel empty">还没有直播回放</div><div v-if="items.length<total" class="empty"><button class="button" :disabled="loading" @click="page++;load()">{{ loading?'加载中…':'加载更多' }}</button></div></div></template>
|
||||
@@ -0,0 +1,98 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue';
|
||||
import { useRoute } from 'vue-router';
|
||||
import Hls from 'hls.js';
|
||||
import mpegts from 'mpegts.js';
|
||||
import { api } from '../api';
|
||||
import { useAppStore } from '../stores/app';
|
||||
|
||||
type Quality = { label: string; flv?: string; hls: string };
|
||||
type Room = { roomNumber:number; title:string; description?:string; cover?:string; announcement?:string; streamStatus:'LIVE'|'OFFLINE'|'BANNED'; viewerCount:number; showViewerCount:boolean; owner:{nickname:string;avatar?:string}; category?:{name:string}; playback?:{hls:string;flv?:string;qualities?:Quality[];protocol?:'FLV'|'HLS'} };
|
||||
type ChatMessage = { id:string; nickname:string; avatar?:string; content:string; createdAt:string; offsetSeconds?:number|null };
|
||||
type Replay = { id:string; startedAt:string; endedAt:string; durationSeconds?:number; peakViewers:number; totalViews:number; recordingUrl:string };
|
||||
type Bullet = { key:number; content:string; nickname:string; lane:number; color:string; duration:number };
|
||||
|
||||
const route=useRoute(),app=useAppStore();
|
||||
const room=ref<Room|null>(null),replays=ref<Replay[]>([]),selectedReplay=ref<Replay|null>(null),error=ref('');
|
||||
const video=ref<HTMLVideoElement>(),box=ref<HTMLDivElement>(),status=ref(''),count=ref(0),messages=ref<ChatMessage[]>([]),chatText=ref(''),chatStatus=ref('连接中…');
|
||||
const playing=ref(true),muted=ref(true),fps=ref('--'),latency=ref('--'),quality=ref<Quality|null>(null),qOpen=ref(false),danmakuEnabled=ref(true),bullets=ref<Bullet[]>([]),replayDanmaku=ref<ChatMessage[]>([]),currentTime=ref(0),duration=ref(0);
|
||||
const isReplay=computed(()=>selectedReplay.value!==null),hasVideo=computed(()=>room.value?.streamStatus==='LIVE'||isReplay.value);
|
||||
let hls:Hls|null=null,flv:ReturnType<typeof mpegts.createPlayer>|null=null,heartbeatTimer=0,statsTimer=0,lastFrames=0,ws:WebSocket|null=null,bulletKey=0,nextDanmaku=0;
|
||||
|
||||
function cleanupPlayer(){clearInterval(statsTimer);lastFrames=0;fps.value='--';latency.value='--';hls?.destroy();hls=null;flv?.destroy();flv=null;if(video.value){video.value.removeAttribute('src');video.value.load()}}
|
||||
async function load(){
|
||||
cleanupPlayer();selectedReplay.value=null;error.value='';
|
||||
try{
|
||||
room.value=(await api<{data:Room}>(`/api/rooms/${route.params.roomNumber}`)).data;count.value=room.value.viewerCount;
|
||||
replays.value=(await api<{data:Replay[]}>(`/api/rooms/${route.params.roomNumber}/replays`)).data;
|
||||
const replayId=String(route.query.replay??'');const target=replayId?replays.value.find(r=>r.id===replayId):null;
|
||||
if(target){await selectReplay(target)}else if(room.value.streamStatus==='LIVE'&&room.value.playback){await nextTick();playLive(room.value.playback)}
|
||||
}catch(value){error.value=(value as Error).message}
|
||||
}
|
||||
function playLive(playback:{hls:string;flv?:string;qualities?:Quality[];protocol?:'FLV'|'HLS'}){quality.value=playback.qualities?.[0]??{label:'原画',flv:playback.flv,hls:playback.hls};startQuality(quality.value)}
|
||||
function startQuality(item:Quality){
|
||||
if(!video.value)return;cleanupPlayer();quality.value=item;
|
||||
if(room.value?.playback?.protocol==='HLS'){if(Hls.isSupported())startHls(item.hls);else if(video.value.canPlayType('application/vnd.apple.mpegurl'))video.value.src=item.hls}
|
||||
else if(item.flv&&mpegts.isSupported()){
|
||||
flv=mpegts.createPlayer({type:'flv',isLive:true,url:item.flv,enableStashBuffer:false});flv.attachMediaElement(video.value);flv.load();flv.play();
|
||||
flv.on(mpegts.Events.ERROR,()=>{flv?.destroy();flv=null;startHls(item.hls)});
|
||||
}else if(Hls.isSupported())startHls(item.hls);else if(video.value.canPlayType('application/vnd.apple.mpegurl'))video.value.src=item.hls;
|
||||
video.value.play().catch(()=>status.value='点击播放按钮开始观看');statsTimer=window.setInterval(sampleStats,1000);
|
||||
}
|
||||
function startHls(url:string){
|
||||
if(!video.value)return;hls=new Hls({liveSyncDurationCount:1,maxLiveSyncPlaybackRate:1.25});hls.loadSource(url);hls.attachMedia(video.value);
|
||||
hls.on(Hls.Events.MANIFEST_PARSED,()=>video.value?.play().catch(()=>status.value='点击播放按钮开始观看'));
|
||||
hls.on(Hls.Events.ERROR,(_event,detail)=>{if(detail.fatal){status.value='直播连接中断,正在重连…';if(detail.type===Hls.ErrorTypes.NETWORK_ERROR)hls?.startLoad();else hls?.recoverMediaError()}});
|
||||
}
|
||||
async function selectReplay(replay:Replay){
|
||||
cleanupPlayer();selectedReplay.value=replay;qOpen.value=false;status.value='';bullets.value=[];currentTime.value=0;duration.value=replay.durationSeconds??0;
|
||||
replayDanmaku.value=(await api<{data:ChatMessage[]}>(`/api/replays/${replay.id}/danmaku`)).data;nextDanmaku=0;
|
||||
await nextTick();if(!video.value)return;
|
||||
if(mpegts.isSupported()){flv=mpegts.createPlayer({type:'flv',isLive:false,url:replay.recordingUrl,enableWorker:true,lazyLoad:true});flv.attachMediaElement(video.value);flv.load();flv.play()}else video.value.src=replay.recordingUrl;
|
||||
video.value.play().catch(()=>status.value='点击播放按钮观看回放');
|
||||
}
|
||||
async function returnToLive(){cleanupPlayer();selectedReplay.value=null;replayDanmaku.value=[];bullets.value=[];await nextTick();if(room.value?.streamStatus==='LIVE'&&room.value.playback)playLive(room.value.playback)}
|
||||
function switchQuality(item:Quality){if(item.label===quality.value?.label)return;qOpen.value=false;startQuality(item)}
|
||||
function togglePlay(){const element=video.value;if(!element)return;element.paused?element.play().catch(()=>status.value='点击播放按钮开始观看'):element.pause()}
|
||||
function toggleMute(){if(video.value)video.value.muted=!video.value.muted}
|
||||
function setVolume(event:Event){const element=video.value;if(!element)return;element.volume=Number((event.target as HTMLInputElement).value);element.muted=element.volume===0}
|
||||
function seek(event:Event){if(!video.value)return;video.value.currentTime=Number((event.target as HTMLInputElement).value);resetReplayCursor()}
|
||||
function toggleFullscreen(){if(!box.value)return;document.fullscreenElement?document.exitFullscreen().catch(()=>{}):box.value.requestFullscreen().catch(()=>{})}
|
||||
function sampleStats(){const element=video.value;if(!element)return;const stats=element.getVideoPlaybackQuality?.();if(stats){fps.value=String(stats.totalVideoFrames-lastFrames);lastFrames=stats.totalVideoFrames}if(hls&&hls.latency>0)latency.value=`${Math.round(hls.latency*1000)}ms`;else if(flv&&!isReplay.value){const end=element.buffered.length?element.buffered.end(element.buffered.length-1):0;if(end>element.currentTime)latency.value=`${Math.round((end-element.currentTime)*1000+300)}ms`}}
|
||||
function formatTime(value:number){if(!Number.isFinite(value))return'00:00';const h=Math.floor(value/3600),m=Math.floor(value%3600/60),s=Math.floor(value%60);return h?`${h}:${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`:`${String(m).padStart(2,'0')}:${String(s).padStart(2,'0')}`}
|
||||
function pushBullet(message:ChatMessage){if(!danmakuEnabled.value)return;const key=++bulletKey;const colors=['#fff','#ffe36e','#7ee7ff','#ff9cce','#a7ff9b'];bullets.value.push({key,content:message.content,nickname:message.nickname,lane:key%6,color:colors[key%colors.length]!,duration:8+(key%4)});window.setTimeout(()=>bullets.value=bullets.value.filter(item=>item.key!==key),13000)}
|
||||
function resetReplayCursor(){const time=video.value?.currentTime??0;bullets.value=[];nextDanmaku=replayDanmaku.value.findIndex(item=>(item.offsetSeconds??0)>=time);if(nextDanmaku<0)nextDanmaku=replayDanmaku.value.length}
|
||||
function onTimeUpdate(){const element=video.value;if(!element)return;currentTime.value=element.currentTime;duration.value=Number.isFinite(element.duration)?element.duration:(selectedReplay.value?.durationSeconds??0);if(!isReplay.value)return;while(nextDanmaku<replayDanmaku.value.length&&(replayDanmaku.value[nextDanmaku]!.offsetSeconds??0)<=element.currentTime+.15){const item=replayDanmaku.value[nextDanmaku++]!;if((item.offsetSeconds??0)>=element.currentTime-1)pushBullet(item)}}
|
||||
async function heartbeat(){try{const result=await api<{data:{viewerCount:number|null}}>(`/api/rooms/${route.params.roomNumber}/viewers/heartbeat`,{method:'POST'});if(result.data.viewerCount!==null)count.value=result.data.viewerCount}catch{}}
|
||||
function connectChat(){
|
||||
ws?.close();const protocol=location.protocol==='https:'?'wss:':'ws:';ws=new WebSocket(`${protocol}//${location.host}/api/rooms/${route.params.roomNumber}/chat`);
|
||||
ws.onopen=()=>chatStatus.value=app.user?'已连接':'只读浏览';ws.onclose=()=>chatStatus.value='连接已断开';
|
||||
ws.onmessage=event=>{const payload=JSON.parse(event.data);if(payload.type==='history')messages.value=payload.messages;if(payload.type==='message'){messages.value.push(payload.message);if(!isReplay.value)pushBullet(payload.message)}if(payload.type==='error')chatStatus.value=payload.message};
|
||||
}
|
||||
function sendChat(){if(!app.user){chatStatus.value='请先登录后参与聊天';return}const content=chatText.value.trim();if(!content||ws?.readyState!==WebSocket.OPEN)return;ws.send(JSON.stringify({content}));chatText.value=''}
|
||||
onMounted(async()=>{await load();heartbeat();connectChat();heartbeatTimer=window.setInterval(heartbeat,15000)});
|
||||
onBeforeUnmount(()=>{clearInterval(heartbeatTimer);cleanupPlayer();ws?.close()});
|
||||
watch(()=>route.params.roomNumber,async()=>{await load();connectChat()});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<p v-if="error" class="panel error">{{error}}</p>
|
||||
<div v-else-if="room" class="room-layout">
|
||||
<section>
|
||||
<div class="panel streamer"><img class="avatar" :src="room.owner.avatar||''"><div><h2>{{room.title}}</h2><div class="muted">{{room.owner.nickname}} · {{room.category?.name??'未分类'}} · {{count}} 人在线</div></div><button v-if="isReplay" class="button live-return" @click="returnToLive">返回直播</button></div>
|
||||
<div ref="box" class="player" :class="{'danmaku-paused':!playing}">
|
||||
<video v-if="hasVideo" ref="video" playsinline muted autoplay @click="togglePlay" @dblclick="toggleFullscreen" @play="playing=true" @pause="playing=false" @volumechange="muted=video?.muted??true" @timeupdate="onTimeUpdate" @seeking="resetReplayCursor"></video>
|
||||
<div v-else class="offline"><h2>{{room.streamStatus==='BANNED'?'直播间已暂停':'主播暂未开播'}}</h2><p>{{replays.length?'可以在下方观看往期回放。':'可以先收藏房间,稍后再来。'}}</p></div>
|
||||
<div v-if="hasVideo&&danmakuEnabled" class="danmaku-layer"><span v-for="item in bullets" :key="item.key" class="danmaku-item" :style="{top:`${8+item.lane*13}%`,color:item.color,animationDuration:`${item.duration}s`}"><b>{{item.nickname}}</b> {{item.content}}</span></div>
|
||||
<div v-if="hasVideo" class="player-top"><span v-if="isReplay" class="chip replay-chip">回放</span><template v-else><span class="chip">帧率 {{fps}}</span><span v-if="app.settings['live.showPlayerLatency']" class="chip">延迟 {{latency}}</span></template></div>
|
||||
<div v-if="hasVideo" class="player-bar" :class="{visible:!playing}"><button class="pbtn" title="播放/暂停" @click="togglePlay"><svg viewBox="0 0 24 24" fill="currentColor"><path :d="playing?'M6 5h4v14H6zM14 5h4v14h-4z':'M8 5v14l11-7z'"/></svg></button><button class="pbtn" :title="muted?'取消静音':'静音'" @click="toggleMute"><svg viewBox="0 0 24 24" fill="currentColor"><path :d="muted?'M3 9v6h4l5 5V4L7 9H3zm12.6 3l2.1-2.1-1.4-1.4-2.1 2.1-2.1-2.1-1.4 1.4 2.1 2.1-2.1 2.1 1.4 1.4 2.1-2.1 2.1 2.1 1.4-1.4z':'M3 9v6h4l5 5V4L7 9H3zm13.5 3a4.5 4.5 0 00-2.5-4.03v8.06a4.5 4.5 0 002.5-4.03z'"/></svg></button><input class="vol" type="range" min="0" max="1" step="0.05" value="1" @input="setVolume"><template v-if="isReplay"><span class="time-label">{{formatTime(currentTime)}}</span><input class="replay-progress" type="range" min="0" :max="duration||1" step="0.1" :value="currentTime" @input="seek"><span class="time-label">{{formatTime(duration)}}</span></template><button class="pbtn danmaku-toggle" :class="{off:!danmakuEnabled}" :title="danmakuEnabled?'关闭弹幕':'开启弹幕'" @click="danmakuEnabled=!danmakuEnabled">弹</button><button v-if="!isReplay" class="pbtn qbtn" title="清晰度" @click="qOpen=!qOpen">{{quality?.label}}<svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 10l5 5 5-5z"/></svg></button><button class="pbtn" title="全屏" @click="toggleFullscreen"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"/></svg></button></div>
|
||||
<div v-if="qOpen&&!isReplay" class="qmenu"><button v-for="item in room.playback?.qualities??[]" :key="item.label" :class="{active:item.label===quality?.label}" @click="switchQuality(item)">{{item.label}}</button></div>
|
||||
<button v-if="hasVideo&&!playing" class="big-play" title="播放" @click="togglePlay"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg></button><span v-if="status" class="live-badge">{{status}}</span>
|
||||
</div>
|
||||
<div v-if="replays.length" class="panel replay-section"><div class="section-head compact"><div><h3>直播回放</h3><span class="muted">共 {{replays.length}} 场</span></div></div><div class="replay-list"><button v-for="item in replays" :key="item.id" class="replay-card" :class="{active:item.id===selectedReplay?.id}" @click="selectReplay(item)"><span class="replay-icon">▶</span><span><strong>{{new Date(item.startedAt).toLocaleString()}}</strong><small>{{formatTime(item.durationSeconds??0)}} · 峰值 {{item.peakViewers}} 人</small></span></button></div></div>
|
||||
<div class="panel room-description"><h3>直播简介</h3><p class="muted">{{room.description||'主播还没有填写直播简介。'}}</p><h3>直播公告</h3><p class="muted">{{room.announcement||'暂无公告'}}</p></div>
|
||||
</section>
|
||||
<aside class="panel chat"><h3>聊天室 <small class="muted">{{chatStatus}}</small></h3><div class="chat-list"><p v-for="message in messages" :key="message.id"><strong>{{message.nickname}}</strong> <span>{{message.content}}</span><br><small class="muted">{{new Date(message.createdAt).toLocaleTimeString()}}</small></p></div><p v-if="!app.user" class="muted"><router-link class="table-link" to="/login">登录</router-link> 后即可参与聊天</p><div class="search"><input v-model="chatText" class="input" maxlength="500" :placeholder="app.user?'发送聊天与弹幕…':'登录后发送消息'" :disabled="!app.user" @keyup.enter="sendChat"><button class="button" :disabled="!app.user" @click="sendChat">发送</button></div></aside>
|
||||
</div>
|
||||
<p v-else class="muted">正在进入直播间…</p>
|
||||
</template>
|
||||
@@ -0,0 +1 @@
|
||||
{"compilerOptions":{"target":"ES2022","module":"ESNext","moduleResolution":"Bundler","strict":true,"noEmit":true,"jsx":"preserve","lib":["ES2022","DOM","DOM.Iterable"],"types":["vite/client"],"noUncheckedIndexedAccess":true},"include":["src/**/*.ts","src/**/*.vue"]}
|
||||
@@ -0,0 +1 @@
|
||||
{"files":[],"references":[{"path":"./tsconfig.app.json"},{"path":"./tsconfig.node.json"}]}
|
||||
@@ -0,0 +1 @@
|
||||
{"compilerOptions":{"composite":true,"module":"ESNext","moduleResolution":"Bundler"},"include":["vite.config.ts"]}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { defineConfig } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
export default defineConfig({ plugins: [vue()], server: { proxy: { '/api': 'http://localhost:3000', '/health': 'http://localhost:3000' } } });
|
||||
@@ -0,0 +1,15 @@
|
||||
services:
|
||||
api:
|
||||
build:
|
||||
target: dev
|
||||
command: npm run dev -w @xlive/api
|
||||
volumes:
|
||||
- ./apps/api/src:/app/apps/api/src
|
||||
- ./apps/api/prisma:/app/apps/api/prisma
|
||||
web:
|
||||
build:
|
||||
target: dev
|
||||
command: npm run dev -w @xlive/web -- --host 0.0.0.0
|
||||
volumes:
|
||||
- ./apps/web/src:/app/apps/web/src
|
||||
ports: ["5173:5173"]
|
||||
@@ -0,0 +1,95 @@
|
||||
name: xlive
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-alpine
|
||||
environment:
|
||||
POSTGRES_DB: xlive
|
||||
POSTGRES_USER: xlive
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-xlive_dev_password}
|
||||
volumes: [postgres_data:/var/lib/postgresql/data]
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U xlive -d xlive"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
redis:
|
||||
image: redis:7-alpine
|
||||
command: redis-server --appendonly yes
|
||||
volumes: [redis_data:/data]
|
||||
healthcheck:
|
||||
test: ["CMD", "redis-cli", "ping"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
srs:
|
||||
image: ossrs/srs:6
|
||||
command: ["sh", "-c", "sed \"s|__HOOK_SECRET__|$${SRS_HOOK_SECRET}|g\" /usr/local/srs/conf/xlive.template.conf > /tmp/xlive.conf && exec ./objs/srs -c /tmp/xlive.conf"]
|
||||
environment:
|
||||
SRS_HOOK_SECRET: ${SRS_HOOK_SECRET}
|
||||
volumes:
|
||||
- ./infra/srs/srs.conf:/usr/local/srs/conf/xlive.template.conf:ro
|
||||
- srs_hls:/usr/local/srs/objs/nginx/html/live
|
||||
ports:
|
||||
- "1935:1935"
|
||||
expose: ["1985", "8080"]
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
srs2:
|
||||
image: ossrs/srs:6
|
||||
command: ["sh", "-c", "exec ./objs/srs -c /usr/local/srs/conf/srs2.conf"]
|
||||
volumes:
|
||||
- ./infra/srs/srs2.conf:/usr/local/srs/conf/srs2.conf:ro
|
||||
- srs_hls:/usr/local/srs/objs/nginx/html/live
|
||||
expose: ["1936", "8081"]
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
restart: unless-stopped
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/api/Dockerfile
|
||||
env_file: [.env]
|
||||
environment:
|
||||
DATABASE_URL: postgresql://xlive:${POSTGRES_PASSWORD:-xlive_dev_password}@postgres:5432/xlive?schema=public
|
||||
REDIS_URL: redis://redis:6379
|
||||
APP_PORT: 3000
|
||||
UPLOAD_DIR: /app/uploads
|
||||
LIVE_DIR: /app/live
|
||||
volumes: [uploads:/app/uploads, srs_hls:/app/live]
|
||||
expose: ["3000"]
|
||||
depends_on:
|
||||
postgres: {condition: service_healthy}
|
||||
redis: {condition: service_healthy}
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-qO-", "http://localhost:3000/health"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
restart: unless-stopped
|
||||
web:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: apps/web/Dockerfile
|
||||
expose: ["80"]
|
||||
restart: unless-stopped
|
||||
nginx:
|
||||
image: nginx:1.27-alpine
|
||||
ports: ["80:80", "443:443"]
|
||||
volumes:
|
||||
- ./infra/nginx/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||
- ./infra/nginx/conf.d:/etc/nginx/conf.d:ro
|
||||
- ./infra/nginx/certs:/etc/nginx/certs:ro
|
||||
- uploads:/var/www/uploads:ro
|
||||
- srs_hls:/var/www/live:ro
|
||||
depends_on: [web, api, srs]
|
||||
restart: unless-stopped
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
uploads:
|
||||
srs_hls:
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
# XLive REST API
|
||||
|
||||
完整、可交互的 OpenAPI UI 运行于 `/api/docs`。所有 JSON API 使用 `/api` 前缀;认证信息放在 HttpOnly Cookie 中。
|
||||
|
||||
## 认证与用户
|
||||
|
||||
| Method | Path | 说明 |
|
||||
|---|---|---|
|
||||
| POST | `/api/auth/register` | 按后台注册模式创建账号 |
|
||||
| POST | `/api/auth/login` | 登录并设置 Access/Refresh Cookie |
|
||||
| POST | `/api/auth/refresh` | 轮换短期 Access Token |
|
||||
| POST | `/api/auth/logout` | 撤销 Refresh Token |
|
||||
| GET | `/api/auth/captcha` | 生成图形验证码图片(发码前需通过校验) |
|
||||
| POST | `/api/auth/email/send-code` | 真实发送邮箱验证码(需 captchaId + captchaText) |
|
||||
| POST | `/api/auth/sms/send-code` | 真实发送阿里云短信验证码(需 captchaId + captchaText) |
|
||||
| POST | `/api/auth/reset-password` | 验证码重置密码并撤销会话 |
|
||||
| POST | `/api/auth/change-password` | 当前用户修改密码 |
|
||||
| GET/PATCH | `/api/users/me` | 当前用户资料 |
|
||||
| POST | `/api/uploads/images` | 登录用户上传图片(JPG/PNG/WebP,≤5MB),用于头像/封面 |
|
||||
|
||||
## 直播间
|
||||
|
||||
| Method | Path | 说明 |
|
||||
|---|---|---|
|
||||
| GET/POST | `/api/rooms` | 公开列表 / 创建房间 |
|
||||
| GET/PATCH | `/api/rooms/{roomNumber}` | 房间详情 / 主播修改 |
|
||||
| GET | `/api/users/me/rooms` | 主播房间和近期 Session |
|
||||
| GET | `/api/rooms/{roomNumber}/stream` | 仅房主读取推流参数 |
|
||||
| POST | `/api/rooms/{roomNumber}/stream/rotate` | 立即轮换密钥并断开旧流 |
|
||||
| POST | `/api/rooms/{roomNumber}/viewers/heartbeat` | 45 秒 TTL 观看心跳 |
|
||||
| GET | `/api/categories` | 启用的公开分类 |
|
||||
|
||||
## 媒体服务器
|
||||
|
||||
`POST /api/media/hooks?secret=...` 仅供内部 SRS 调用,公网 Nginx 明确返回 404。支持 `on_publish`、`on_unpublish` 和 `on_dvr`。`on_publish` 校验流名、Token Hash、用户状态和直播权限;非 2xx 响应使 SRS 拒绝推流。`on_dvr` 将录制文件关联到直播场次;若该房间关闭了「生成直播回放」(`record_replay`),录制文件会被立即删除且不产生回放。
|
||||
|
||||
`GET /api/rooms/:roomNumber/replays` 返回房间的可用回放;`GET /api/replays/:sessionId/danmaku` 返回按直播时间偏移排序的回放弹幕。
|
||||
|
||||
## 管理后台
|
||||
|
||||
`/api/admin/**` 需要 ADMIN 或 SUPER_ADMIN;设置、管理员创建和外部服务测试仅 SUPER_ADMIN。
|
||||
|
||||
- `GET /api/admin/dashboard|users|rooms|categories|logs`
|
||||
- `PATCH /api/admin/users/{id}`
|
||||
- `POST /api/admin/users/{id}/reset-password`
|
||||
- `POST /api/admin/rooms/{roomNumber}/stop|ban|unban`
|
||||
- `POST/PATCH/DELETE /api/admin/categories`
|
||||
- `GET /api/admin/files`、`DELETE /api/admin/files/{id}`、`GET /api/admin/files/{id}/download`(上传文件管理)
|
||||
- `GET /api/admin/replays`、`DELETE /api/admin/replays/{id}`、`GET /api/admin/replays/{id}/download`(回放管理)
|
||||
- `GET/PUT /api/admin/settings`
|
||||
- `POST /api/admin/settings/smtp/test|sms/test`
|
||||
- `POST /api/admin/admins`
|
||||
|
||||
## 状态码
|
||||
|
||||
- `400` 业务参数不满足规则
|
||||
- `401` 未登录、Token/Hook 签名无效
|
||||
- `403` RBAC、账号或直播权限拒绝
|
||||
- `404` 资源不存在
|
||||
- `409` 唯一约束或资源状态冲突
|
||||
- `422` Zod 参数校验失败
|
||||
- `423` 登录失败次数过多导致临时锁定
|
||||
- `429` 发送频率或接口速率限制
|
||||
- `502` SMTP/SMS 上游真实调用失败
|
||||
@@ -0,0 +1,49 @@
|
||||
upstream xlive_api { server api:3000; keepalive 32; }
|
||||
upstream xlive_web { server web:80; keepalive 16; }
|
||||
server {
|
||||
listen 80;
|
||||
server_name _;
|
||||
location /api/media/hooks { return 404; }
|
||||
location /api/ {
|
||||
proxy_pass http://xlive_api;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_set_header X-Request-ID $request_id;
|
||||
proxy_set_header Upgrade $http_upgrade;
|
||||
proxy_set_header Connection $connection_upgrade;
|
||||
}
|
||||
location = /health { proxy_pass http://xlive_api/health; proxy_set_header X-Request-ID $request_id; }
|
||||
location ~ ^/live/.*\.flv$ {
|
||||
proxy_pass http://srs:8080;
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
add_header Cache-Control "no-cache, no-store" always;
|
||||
add_header Access-Control-Allow-Origin "*" always;
|
||||
}
|
||||
location ~ ^/transcode/live/.*\.flv$ {
|
||||
rewrite ^/transcode/live/(.*)$ /live/$1 break;
|
||||
proxy_pass http://srs2:8081;
|
||||
proxy_http_version 1.1;
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
proxy_read_timeout 300s;
|
||||
add_header Cache-Control "no-cache, no-store" always;
|
||||
add_header Access-Control-Allow-Origin "*" always;
|
||||
}
|
||||
location /live/ {
|
||||
alias /var/www/live/;
|
||||
add_header Access-Control-Allow-Origin "*" always;
|
||||
add_header Cache-Control "no-cache, no-store" always;
|
||||
types { application/vnd.apple.mpegurl m3u8; video/mp2t ts; video/mp4 m4s mp4; }
|
||||
try_files $uri =404;
|
||||
}
|
||||
location /uploads/ { alias /var/www/uploads/; expires 7d; add_header X-Content-Type-Options nosniff; }
|
||||
location / { proxy_pass http://xlive_web; proxy_set_header Host $host; }
|
||||
}
|
||||
|
||||
# Production: obtain a certificate with certbot, then enable TLS here and redirect HTTP.
|
||||
@@ -0,0 +1,20 @@
|
||||
user nginx;
|
||||
worker_processes auto;
|
||||
error_log /var/log/nginx/error.log warn;
|
||||
pid /var/run/nginx.pid;
|
||||
events { worker_connections 2048; }
|
||||
http {
|
||||
include /etc/nginx/mime.types;
|
||||
default_type application/octet-stream;
|
||||
log_format main '$remote_addr - $request_id [$time_local] "$request" $status $body_bytes_sent';
|
||||
access_log /var/log/nginx/access.log main;
|
||||
sendfile on;
|
||||
tcp_nopush on;
|
||||
keepalive_timeout 65;
|
||||
client_max_body_size 10m;
|
||||
server_tokens off;
|
||||
gzip on;
|
||||
gzip_types text/plain text/css application/json application/javascript application/vnd.apple.mpegurl;
|
||||
map $http_upgrade $connection_upgrade { default upgrade; '' close; }
|
||||
include /etc/nginx/conf.d/*.conf;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
listen 1935;
|
||||
max_connections 1000;
|
||||
daemon off;
|
||||
srs_log_tank console;
|
||||
|
||||
http_api {
|
||||
enabled on;
|
||||
listen 1985;
|
||||
}
|
||||
|
||||
http_server {
|
||||
enabled on;
|
||||
listen 8080;
|
||||
dir ./objs/nginx/html;
|
||||
}
|
||||
|
||||
vhost __defaultVhost__ {
|
||||
tcp_nodelay on;
|
||||
min_latency on;
|
||||
play {
|
||||
gop_cache off;
|
||||
queue_length 10;
|
||||
mw_latency 100;
|
||||
}
|
||||
publish {
|
||||
mr off;
|
||||
}
|
||||
hls {
|
||||
enabled on;
|
||||
hls_path ./objs/nginx/html;
|
||||
hls_fragment 1;
|
||||
hls_window 6;
|
||||
hls_cleanup on;
|
||||
hls_dispose 30;
|
||||
hls_m3u8_file live/[stream].m3u8;
|
||||
hls_ts_file live/[stream]-[seq].ts;
|
||||
}
|
||||
dvr {
|
||||
enabled on;
|
||||
dvr_path ./objs/nginx/html/[app]/replays/[stream].[timestamp].flv;
|
||||
dvr_plan session;
|
||||
}
|
||||
http_remux {
|
||||
enabled on;
|
||||
mount [vhost]/[app]/[stream].flv;
|
||||
}
|
||||
http_hooks {
|
||||
enabled on;
|
||||
on_publish http://api:3000/api/media/hooks?secret=__HOOK_SECRET__;
|
||||
on_unpublish http://api:3000/api/media/hooks?secret=__HOOK_SECRET__;
|
||||
on_dvr http://api:3000/api/media/hooks?secret=__HOOK_SECRET__;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
listen 1936;
|
||||
max_connections 1000;
|
||||
daemon off;
|
||||
srs_log_tank console;
|
||||
|
||||
http_server {
|
||||
enabled on;
|
||||
listen 8081;
|
||||
dir ./objs/nginx/html;
|
||||
}
|
||||
|
||||
vhost __defaultVhost__ {
|
||||
tcp_nodelay on;
|
||||
min_latency on;
|
||||
play {
|
||||
gop_cache off;
|
||||
queue_length 10;
|
||||
mw_latency 100;
|
||||
}
|
||||
publish {
|
||||
mr off;
|
||||
}
|
||||
hls {
|
||||
enabled on;
|
||||
hls_path ./objs/nginx/html;
|
||||
hls_fragment 1;
|
||||
hls_window 6;
|
||||
hls_cleanup on;
|
||||
hls_dispose 30;
|
||||
hls_m3u8_file live/[stream].m3u8;
|
||||
hls_ts_file live/[stream]-[seq].ts;
|
||||
}
|
||||
http_remux {
|
||||
enabled on;
|
||||
mount [vhost]/[app]/[stream].flv;
|
||||
}
|
||||
}
|
||||
Generated
+6704
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "xlive",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"workspaces": ["apps/*"],
|
||||
"scripts": {
|
||||
"dev": "concurrently -n api,web -c blue,green \"npm run dev -w @xlive/api\" \"npm run dev -w @xlive/web\"",
|
||||
"build": "npm run build -w @xlive/api && npm run build -w @xlive/web",
|
||||
"test": "npm run test -w @xlive/api && npm run test -w @xlive/web",
|
||||
"lint": "npm run lint -ws --if-present"
|
||||
},
|
||||
"devDependencies": {"concurrently": "^9.2.1"},
|
||||
"engines": {"node": ">=22"}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
param(
|
||||
[Parameter(Mandatory=$true)][string]$StreamKey,
|
||||
[int]$Seconds = 30
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
if ($StreamKey -notmatch '^room_\d+\?token=') { throw 'StreamKey 必须是主播中心显示的完整值:room_房间号?token=密钥' }
|
||||
Write-Host "推送 ${Seconds} 秒测试画面到 rtmp://localhost/live"
|
||||
docker run --rm --network host jrottenberg/ffmpeg:6.1-alpine `
|
||||
-re -f lavfi -i "testsrc2=size=1280x720:rate=30" `
|
||||
-f lavfi -i "sine=frequency=1000:sample_rate=44100" `
|
||||
-t $Seconds -c:v libx264 -preset veryfast -tune zerolatency -g 60 `
|
||||
-c:a aac -b:a 128k -f flv "rtmp://host.docker.internal/live/$StreamKey"
|
||||
Write-Host '推流结束。检查直播间是否自动回到 OFFLINE,并确认直播记录。'
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
Reference in new issue
Block a user