Initial commit: LiveStream Platform

Backend: FastAPI + SQLAlchemy + SQLite
Frontend: React + Vite + Ant Design (serif Anthropic theme)
Media server: MediaMTX with edge node support
Load balancing: round-robin / weighted / least-conn
Multicast detection with automatic fallback
Transcoding support via FFmpeg (configurable quality)
hls.js player with line & quality switching
Admin panel with password auth
Windows compatible scripts
This commit is contained in:
admin committed 2026-08-07 15:02:07 +08:00
commit 2e4594fa77
43 files changed
+2196

No files matched your search

+52
View File
@@ -0,0 +1,52 @@
import { useState, useEffect } from 'react'
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom'
import { ConfigProvider } from 'antd'
import theme from './theme/anthropic'
import AdminLayout from './admin/AdminLayout'
import LoginPage from './admin/LoginPage'
import Dashboard from './admin/pages/Dashboard'
import StreamList from './admin/pages/StreamList'
import StreamForm from './admin/pages/StreamForm'
import NodeManager from './admin/pages/NodeManager'
import SettingsPage from './admin/pages/Settings'
import WatchPage from './viewer/pages/WatchPage'
import { verifyToken, getToken } from './api/auth'
function AdminGuard({ children }: { children: React.ReactNode }) {
const [authed, setAuthed] = useState<boolean | null>(null)
useEffect(() => {
const token = getToken()
if (!token) { setAuthed(false); return }
verifyToken().then(setAuthed)
}, [])
if (authed === null) return null
if (!authed) return <Navigate to="/admin/login" replace />
return <>{children}</>
}
export default function App() {
return (
<ConfigProvider theme={theme}>
<BrowserRouter>
<Routes>
<Route path="/watch/:id" element={<WatchPage />} />
<Route path="/admin/login" element={<LoginPage />} />
<Route path="/admin" element={
<AdminGuard>
<AdminLayout />
</AdminGuard>
}>
<Route index element={<Dashboard />} />
<Route path="streams" element={<StreamList />} />
<Route path="streams/new" element={<StreamForm />} />
<Route path="nodes" element={<NodeManager />} />
<Route path="settings" element={<SettingsPage />} />
</Route>
<Route path="/" element={<Navigate to="/admin" replace />} />
</Routes>
</BrowserRouter>
</ConfigProvider>
)
}
+93
View File
@@ -0,0 +1,93 @@
import { useState } from 'react'
import { Outlet, useNavigate, useLocation, Link } from 'react-router-dom'
import { Layout, Menu, Button, Typography } from 'antd'
import {
DashboardOutlined,
VideoCameraOutlined,
PlusOutlined,
CloudServerOutlined,
SettingOutlined,
LogoutOutlined,
} from '@ant-design/icons'
import { clearToken } from '../api/client'
const { Sider, Content, Header } = Layout
const { Text } = Typography
const menuItems = [
{ key: '/admin', icon: <DashboardOutlined />, label: 'Dashboard' },
{ key: '/admin/streams', icon: <VideoCameraOutlined />, label: 'Streams' },
{ key: '/admin/streams/new', icon: <PlusOutlined />, label: 'New Stream' },
{ key: '/admin/nodes', icon: <CloudServerOutlined />, label: 'Edge Nodes' },
{ key: '/admin/settings', icon: <SettingOutlined />, label: 'Settings' },
]
export default function AdminLayout() {
const [collapsed, setCollapsed] = useState(false)
const navigate = useNavigate()
const location = useLocation()
const selectedKey = menuItems.find(
(item) => location.pathname === item.key || (location.pathname === '/' && item.key === '/admin')
)?.key || '/admin'
const handleLogout = () => {
clearToken()
navigate('/admin/login')
}
return (
<Layout style={{ minHeight: '100vh' }}>
<Sider
collapsible
collapsed={collapsed}
onCollapse={setCollapsed}
width={220}
style={{
borderRight: '1px solid #E8E4DD',
background: '#FFFFFF',
}}
>
<div style={{
height: 56,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
borderBottom: '1px solid #E8E4DD',
}}>
<Text strong style={{ fontSize: collapsed ? 14 : 18, letterSpacing: -0.5 }}>
{collapsed ? 'LS' : 'LiveStream'}
</Text>
</div>
<Menu
mode="inline"
selectedKeys={[selectedKey]}
items={menuItems}
onClick={({ key }) => navigate(key)}
style={{ border: 'none', marginTop: 8 }}
/>
</Sider>
<Layout>
<Header style={{
background: '#FFFFFF',
borderBottom: '1px solid #E8E4DD',
display: 'flex',
justifyContent: 'flex-end',
alignItems: 'center',
padding: '0 32px',
}}>
<Button
type="text"
icon={<LogoutOutlined />}
onClick={handleLogout}
>
Logout
</Button>
</Header>
<Content style={{ padding: 32, overflow: 'auto' }}>
<Outlet />
</Content>
</Layout>
</Layout>
)
}
+61
View File
@@ -0,0 +1,61 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Card, Form, Input, Button, Typography, message, Space } from 'antd'
import { LockOutlined } from '@ant-design/icons'
import { login } from '../api/auth'
const { Title, Text } = Typography
export default function LoginPage() {
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleSubmit = async (values: { password: string }) => {
setLoading(true)
try {
await login(values.password)
message.success('Welcome back')
navigate('/admin')
} catch {
message.error('Invalid password')
} finally {
setLoading(false)
}
}
return (
<div style={{
minHeight: '100vh',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: '#FAF8F5',
}}>
<Card style={{ width: 400, boxShadow: '0 2px 16px rgba(0,0,0,0.04)' }}>
<Space direction="vertical" size="large" style={{ width: '100%' }}>
<div style={{ textAlign: 'center' }}>
<Title level={2} style={{ marginBottom: 4 }}>LiveStream</Title>
<Text type="secondary">Admin Panel</Text>
</div>
<Form onFinish={handleSubmit} layout="vertical">
<Form.Item
name="password"
rules={[{ required: true, message: 'Enter your password' }]}
>
<Input.Password
prefix={<LockOutlined />}
placeholder="Password"
size="large"
/>
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={loading} block size="large">
Sign In
</Button>
</Form.Item>
</Form>
</Space>
</Card>
</div>
)
}
+96
View File
@@ -0,0 +1,96 @@
import { useState, useEffect } from 'react'
import { Row, Col, Card, Statistic, Typography, Table, Tag, Space } from 'antd'
import { VideoCameraOutlined, EyeOutlined, CloudServerOutlined, SignalFilled } from '@ant-design/icons'
import { fetchStreams, type StreamInfo } from '../../api/streams'
const { Title } = Typography
export default function Dashboard() {
const [streams, setStreams] = useState<StreamInfo[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
loadData()
const timer = setInterval(loadData, 10000)
return () => clearInterval(timer)
}, [])
async function loadData() {
try {
const data = await fetchStreams()
setStreams(data)
} catch { /* ignore */ }
setLoading(false)
}
const liveCount = streams.filter((s) => s.status === 'live').length
const pendingCount = streams.filter((s) => s.status === 'pending').length
const endedCount = streams.filter((s) => s.status === 'ended').length
const statusMap: Record<string, { color: string; label: string }> = {
pending: { color: 'blue', label: 'Pending' },
live: { color: 'green', label: 'Live' },
ended: { color: 'default', label: 'Ended' },
cancelled: { color: 'red', label: 'Cancelled' },
}
const recentColumns = [
{ title: 'Title', dataIndex: 'title', key: 'title', ellipsis: true },
{
title: 'Status', dataIndex: 'status', key: 'status',
render: (status: string) => {
const s = statusMap[status] || { color: 'default', label: status }
return <Tag color={s.color}>{s.label}</Tag>
},
},
{ title: 'Created', dataIndex: 'created_at', key: 'created_at', render: (v: string) => v?.slice(0, 16) },
]
return (
<div>
<Title level={3} style={{ marginBottom: 24 }}>Dashboard</Title>
<Row gutter={[24, 24]}>
<Col xs={24} sm={8}>
<Card>
<Statistic
title="Live Streams"
value={liveCount}
prefix={<SignalFilled style={{ color: '#52c41a' }} />}
loading={loading}
/>
</Card>
</Col>
<Col xs={24} sm={8}>
<Card>
<Statistic
title="Pending"
value={pendingCount}
prefix={<VideoCameraOutlined style={{ color: '#1677ff' }} />}
loading={loading}
/>
</Card>
</Col>
<Col xs={24} sm={8}>
<Card>
<Statistic
title="Total Streams"
value={streams.length}
prefix={<EyeOutlined />}
loading={loading}
/>
</Card>
</Col>
</Row>
<Card title="Recent Streams" style={{ marginTop: 24 }}>
<Table
dataSource={streams.slice(0, 10)}
columns={recentColumns}
rowKey="id"
loading={loading}
pagination={false}
size="middle"
/>
</Card>
</div>
)
}
+144
View File
@@ -0,0 +1,144 @@
import { useState, useEffect } from 'react'
import {
Card, Table, InputNumber, Switch, Typography, message, Space, Tag, Statistic, Row, Col, Button,
} from 'antd'
import { CheckCircleOutlined, CloseCircleOutlined, ReloadOutlined } from '@ant-design/icons'
import api from '../../api/client'
const { Title, Text } = Typography
interface NodeInfo {
id: string
name: string
host: string
hls_port: number
api_port: number
weight: number
enabled: boolean
}
interface StrategyInfo {
strategy: string
multicast_enabled: boolean
multicast_available: boolean
}
export default function NodeManager() {
const [nodes, setNodes] = useState<NodeInfo[]>([])
const [strategy, setStrategy] = useState<StrategyInfo | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => { loadData() }, [])
async function loadData() {
setLoading(true)
try {
const [nodesRes, strategyRes] = await Promise.all([
api.get('/nodes'),
api.get('/nodes/strategy'),
])
setNodes(nodesRes.data)
setStrategy(strategyRes.data)
} catch { message.error('Failed to load') }
setLoading(false)
}
async function updateWeight(nodeId: string, weight: number) {
try {
await api.put(`/nodes/${nodeId}`, { weight })
message.success('Updated')
} catch { message.error('Failed') }
}
async function toggleNode(nodeId: string, enabled: boolean) {
const node = nodes.find((n) => n.id === nodeId)
if (!node) return
try {
await api.put(`/nodes/${nodeId}`, { weight: node.weight, enabled })
setNodes((prev) => prev.map((n) => (n.id === nodeId ? { ...n, enabled } : n)))
message.success('Updated')
} catch { message.error('Failed') }
}
const columns = [
{ title: 'Name', dataIndex: 'name', key: 'name' },
{ title: 'Host', dataIndex: 'host', key: 'host' },
{ title: 'HLS Port', dataIndex: 'hls_port', key: 'hls_port', width: 100 },
{ title: 'API Port', dataIndex: 'api_port', key: 'api_port', width: 100 },
{
title: 'Weight', dataIndex: 'weight', key: 'weight', width: 140,
render: (_: number, record: NodeInfo) => (
<InputNumber
min={0}
max={1000}
value={record.weight}
onChange={(val) => {
const v = val || 0
setNodes((prev) => prev.map((n) => (n.id === record.id ? { ...n, weight: v } : n)))
updateWeight(record.id, v)
}}
size="small"
style={{ width: 90 }}
/>
),
},
{
title: 'Enabled', dataIndex: 'enabled', key: 'enabled', width: 90,
render: (_: any, record: NodeInfo) => (
<Switch
checked={record.enabled}
onChange={(val) => toggleNode(record.id, val)}
size="small"
/>
),
},
{
title: 'Health', key: 'health', width: 100,
render: () => <Tag icon={<CheckCircleOutlined />} color="success">Online</Tag>,
},
]
return (
<div>
<Title level={3} style={{ marginBottom: 24 }}>Edge Nodes</Title>
{strategy && (
<Row gutter={[24, 24]} style={{ marginBottom: 24 }}>
<Col xs={24} sm={8}>
<Card>
<Statistic title="Strategy" value={strategy.strategy} />
</Card>
</Col>
<Col xs={24} sm={8}>
<Card>
<Statistic
title="Multicast"
value={strategy.multicast_available ? 'Available' : 'Unavailable'}
valueStyle={{ color: strategy.multicast_available ? '#52c41a' : '#999' }}
/>
</Card>
</Col>
<Col xs={24} sm={8}>
<Card>
<Statistic title="Edge Nodes" value={nodes.length} />
</Card>
</Col>
</Row>
)}
<Card
title="Node List"
extra={<Button icon={<ReloadOutlined />} onClick={loadData}>Refresh</Button>}
>
<Table
dataSource={nodes}
columns={columns}
rowKey="id"
loading={loading}
pagination={false}
size="middle"
/>
</Card>
</div>
)
}
+84
View File
@@ -0,0 +1,84 @@
import { useState, useEffect } from 'react'
import {
Card, Select, Switch, Typography, message, Space, Descriptions, Button,
} from 'antd'
import api from '../../api/client'
const { Title } = Typography
const strategies = [
{ value: 'round-robin', label: 'Round Robin' },
{ value: 'weighted', label: 'Weighted' },
{ value: 'least-conn', label: 'Least Connections' },
]
export default function SettingsPage() {
const [strategy, setStrategy] = useState('weighted')
const [multicastEnabled, setMulticastEnabled] = useState(true)
const [multicastAvailable, setMulticastAvailable] = useState(false)
const [saving, setSaving] = useState(false)
useEffect(() => {
loadSettings()
}, [])
async function loadSettings() {
try {
const { data } = await api.get('/nodes/strategy')
setStrategy(data.strategy)
setMulticastEnabled(data.multicast_enabled)
setMulticastAvailable(data.multicast_available)
} catch { /* ignore */ }
}
async function saveStrategy(val: string) {
setSaving(true)
try {
await api.put(`/nodes/strategy?strategy=${val}&multicast_enabled=${multicastEnabled}`)
setStrategy(val)
message.success('Strategy updated')
} catch { message.error('Failed') }
setSaving(false)
}
async function toggleMulticast(val: boolean) {
setMulticastEnabled(val)
try {
await api.put(`/nodes/strategy?strategy=${strategy}&multicast_enabled=${val}`)
message.success('Multicast setting updated')
} catch { message.error('Failed') }
}
return (
<div style={{ maxWidth: 720 }}>
<Title level={3} style={{ marginBottom: 24 }}>Settings</Title>
<Card title="Load Balancing" style={{ marginBottom: 24 }}>
<Descriptions column={1} labelStyle={{ width: 180 }}>
<Descriptions.Item label="Strategy">
<Select
value={strategy}
onChange={saveStrategy}
options={strategies}
loading={saving}
style={{ width: 240 }}
/>
</Descriptions.Item>
</Descriptions>
</Card>
<Card title="Multicast">
<Descriptions column={1} labelStyle={{ width: 180 }}>
<Descriptions.Item label="Enable Multicast">
<Switch checked={multicastEnabled} onChange={toggleMulticast} />
</Descriptions.Item>
<Descriptions.Item label="Network Status">
<span style={{ color: multicastAvailable ? '#52c41a' : '#999' }}>
{multicastAvailable ? 'Available' : 'Unavailable (fallback to unicast)'}
</span>
</Descriptions.Item>
</Descriptions>
</Card>
</div>
)
}
+128
View File
@@ -0,0 +1,128 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import {
Card, Form, Input, Button, DatePicker, Typography, message, Space, Alert, Divider,
} from 'antd'
import { CopyOutlined, ArrowLeftOutlined } from '@ant-design/icons'
import { createStream } from '../../api/streams'
const { Title, Text } = Typography
const { TextArea } = Input
export default function StreamForm() {
const [loading, setLoading] = useState(false)
const [result, setResult] = useState<{ rtmp_url: string; stream_key: string } | null>(null)
const navigate = useNavigate()
const handleSubmit = async (values: any) => {
setLoading(true)
try {
const res = await createStream({
title: values.title,
description: values.description,
cover_url: values.cover_url,
scheduled_at: values.scheduled_at?.toISOString(),
})
setResult({ rtmp_url: res.rtmp_url, stream_key: res.stream_key })
message.success('Stream created')
} catch {
message.error('Failed to create stream')
}
setLoading(false)
}
if (result) {
return (
<div style={{ maxWidth: 640 }}>
<Title level={3} style={{ marginBottom: 24 }}>Stream Created</Title>
<Alert
type="success"
message="Your stream is ready"
description={
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
<div>
<Text strong>Stream Key (UUID):</Text>
<div style={{
marginTop: 8, padding: 12,
background: '#F5F2EE', borderRadius: 6,
fontFamily: 'monospace', fontSize: 14,
wordBreak: 'break-all',
}}>
{result.stream_key}
</div>
</div>
<div>
<Text strong>RTMP Push URL:</Text>
<div style={{
marginTop: 8, padding: 12,
background: '#F5F2EE', borderRadius: 6,
fontFamily: 'monospace', fontSize: 14,
wordBreak: 'break-all',
}}>
{result.rtmp_url}
</div>
</div>
</Space>
}
showIcon
style={{ marginBottom: 24 }}
/>
<Space>
<Button
icon={<CopyOutlined />}
onClick={() => {
navigator.clipboard.writeText(
`Stream Key: ${result.stream_key}\nRTMP URL: ${result.rtmp_url}`
)
message.success('Copied to clipboard')
}}
>
Copy All
</Button>
<Button type="primary" onClick={() => navigate('/admin/streams')}>
Back to Streams
</Button>
</Space>
</div>
)
}
return (
<div style={{ maxWidth: 640 }}>
<Button
type="text"
icon={<ArrowLeftOutlined />}
onClick={() => navigate('/admin/streams')}
style={{ marginBottom: 16 }}
>
Back
</Button>
<Card>
<Title level={3} style={{ marginBottom: 24 }}>New Stream</Title>
<Form layout="vertical" onFinish={handleSubmit}>
<Form.Item
name="title"
label="Title"
rules={[{ required: true, message: 'Enter a title' }]}
>
<Input placeholder="Stream title" size="large" />
</Form.Item>
<Form.Item name="description" label="Description">
<TextArea rows={3} placeholder="Stream description (optional)" />
</Form.Item>
<Form.Item name="cover_url" label="Cover Image URL">
<Input placeholder="https://..." />
</Form.Item>
<Form.Item name="scheduled_at" label="Scheduled Time">
<DatePicker showTime style={{ width: '100%' }} size="large" />
</Form.Item>
<Form.Item>
<Button type="primary" htmlType="submit" loading={loading} size="large" block>
Create Stream
</Button>
</Form.Item>
</Form>
</Card>
</div>
)
}
+123
View File
@@ -0,0 +1,123 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import {
Table, Button, Tag, Space, Modal, Typography, message, Tooltip, Popconfirm,
} from 'antd'
import { PlusOutlined, PlayCircleOutlined, StopOutlined, DeleteOutlined, LinkOutlined } from '@ant-design/icons'
import { fetchStreams, deleteStream, goLive, endStream, type StreamInfo } from '../../api/streams'
const { Title, Text } = Typography
const statusMap: Record<string, { color: string; label: string }> = {
pending: { color: 'blue', label: 'Pending' },
live: { color: 'green', label: 'Live' },
ended: { color: 'default', label: 'Ended' },
cancelled: { color: 'red', label: 'Cancelled' },
}
export default function StreamList() {
const [streams, setStreams] = useState<StreamInfo[]>([])
const [loading, setLoading] = useState(true)
const navigate = useNavigate()
useEffect(() => { loadData() }, [])
async function loadData() {
setLoading(true)
try {
const data = await fetchStreams()
setStreams(data)
} catch { message.error('Failed to load streams') }
setLoading(false)
}
async function handleDelete(id: number) {
try {
await deleteStream(id)
message.success('Stream deleted')
loadData()
} catch { message.error('Delete failed') }
}
async function handleGoLive(id: number) {
try {
await goLive(id)
message.success('Stream is now live')
loadData()
} catch { message.error('Failed to set live') }
}
async function handleEnd(id: number) {
try {
await endStream(id)
message.success('Stream ended')
loadData()
} catch { message.error('Failed to end') }
}
const columns = [
{ title: 'ID', dataIndex: 'id', key: 'id', width: 80 },
{ title: 'Title', dataIndex: 'title', key: 'title', ellipsis: true },
{
title: 'Status', dataIndex: 'status', key: 'status', width: 110,
render: (s: string) => {
const info = statusMap[s] || { color: 'default', label: s }
return <Tag color={info.color}>{info.label}</Tag>
},
},
{ title: 'Created', dataIndex: 'created_at', key: 'created_at', render: (v: string) => v?.slice(0, 16), width: 170 },
{
title: 'Actions', key: 'actions', width: 280,
render: (_: any, record: StreamInfo) => (
<Space size="small">
<Button
size="small"
icon={<LinkOutlined />}
onClick={() => {
navigator.clipboard.writeText(record.stream_key)
message.success('Stream key copied')
}}
>
Copy Key
</Button>
{record.status !== 'live' ? (
<Tooltip title="Mark as live">
<Button size="small" type="primary" icon={<PlayCircleOutlined />}
onClick={() => handleGoLive(record.id)} ghost />
</Tooltip>
) : (
<Tooltip title="End stream">
<Button size="small" icon={<StopOutlined />}
onClick={() => handleEnd(record.id)} danger />
</Tooltip>
)}
<Button size="small" onClick={() => window.open(`/watch/${record.id}`, '_blank')}>
Watch
</Button>
<Popconfirm title="Delete this stream?" onConfirm={() => handleDelete(record.id)}>
<Button size="small" icon={<DeleteOutlined />} danger />
</Popconfirm>
</Space>
),
},
]
return (
<div>
<div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 24 }}>
<Title level={3} style={{ margin: 0 }}>Streams</Title>
<Button type="primary" icon={<PlusOutlined />} onClick={() => navigate('/admin/streams/new')}>
New Stream
</Button>
</div>
<Table
dataSource={streams}
columns={columns}
rowKey="id"
loading={loading}
pagination={{ pageSize: 15 }}
size="middle"
/>
</div>
)
}
+18
View File
@@ -0,0 +1,18 @@
import api, { setToken, getToken } from './client'
export async function login(password: string): Promise<string> {
const { data } = await api.post(`/auth/login?password=${encodeURIComponent(password)}`)
setToken(data.token)
return data.token
}
export async function verifyToken(): Promise<boolean> {
const token = getToken()
if (!token) return false
try {
await api.post(`/auth/verify?token=${encodeURIComponent(token)}`)
return true
} catch {
return false
}
}
+30
View File
@@ -0,0 +1,30 @@
import axios from 'axios'
const api = axios.create({
baseURL: '/api',
timeout: 15000,
})
const TOKEN_KEY = 'livestream_admin_token'
api.interceptors.request.use((config) => {
const token = localStorage.getItem(TOKEN_KEY)
if (token) {
config.headers.Authorization = `Bearer ${token}`
}
return config
})
export function setToken(token: string) {
localStorage.setItem(TOKEN_KEY, token)
}
export function getToken(): string | null {
return localStorage.getItem(TOKEN_KEY)
}
export function clearToken() {
localStorage.removeItem(TOKEN_KEY)
}
export default api
+92
View File
@@ -0,0 +1,92 @@
import api from './client'
export interface StreamInfo {
id: number
title: string
description?: string
cover_url?: string
stream_key: string
status: string
scheduled_at?: string
started_at?: string
ended_at?: string
multicast_enabled: boolean
created_at: string
}
export interface StreamCreateReq {
title: string
description?: string
cover_url?: string
scheduled_at?: string
}
export interface WatchInfo {
stream_id: number
title: string
status: string
multicast_available: boolean
lines: LineInfo[]
qualities: QualityInfo[]
}
export interface LineInfo {
node_id: string
node_name: string
weight: number
type: string
url: string
unicast_fallback?: string
qualities: QualityUrl[]
}
export interface QualityUrl {
label: string
width: number
height: number
url: string
}
export interface QualityInfo {
label: string
width: number
height: number
}
export async function fetchStreams(): Promise<StreamInfo[]> {
const { data } = await api.get('/streams')
return data
}
export async function createStream(req: StreamCreateReq): Promise<{
id: number; stream_key: string; rtmp_url: string; status: string
}> {
const { data } = await api.post('/streams', req)
return data
}
export async function getStream(streamId: number): Promise<StreamInfo> {
const { data } = await api.get(`/streams/${streamId}`)
return data
}
export async function updateStream(streamId: number, req: Partial<StreamCreateReq>): Promise<void> {
await api.put(`/streams/${streamId}`, req)
}
export async function deleteStream(streamId: number): Promise<void> {
await api.delete(`/streams/${streamId}`)
}
export async function goLive(streamId: number): Promise<void> {
await api.post(`/streams/${streamId}/go-live`)
}
export async function endStream(streamId: number): Promise<void> {
await api.post(`/streams/${streamId}/end`)
}
export async function getWatchUrls(streamId: number): Promise<WatchInfo> {
const { data } = await api.get(`/streams/${streamId}/watch`)
return data
}
+8
View File
@@ -0,0 +1,8 @@
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; }
html, body, #root { height: 100%; }
body {
font-family: "Source Serif 4", "Noto Serif SC", Georgia, "Times New Roman", serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
background: #FAF8F5;
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './global.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
)
+62
View File
@@ -0,0 +1,62 @@
import type { ThemeConfig } from 'antd'
const theme: ThemeConfig = {
token: {
fontFamily: `"Source Serif 4", "Noto Serif SC", Georgia, "Times New Roman", serif`,
fontSize: 15,
colorPrimary: '#D97757',
colorSuccess: '#6B9E7A',
colorWarning: '#D4A24E',
colorError: '#C15C5C',
colorInfo: '#7B93A8',
colorTextBase: '#1A1A16',
colorBgBase: '#FAF8F5',
colorBgContainer: '#FFFFFF',
colorBgLayout: '#FAF8F5',
colorBorder: '#E8E4DD',
colorBorderSecondary: '#F0EDE7',
borderRadius: 6,
wireframe: false,
},
components: {
Layout: {
headerBg: '#FFFFFF',
headerHeight: 56,
headerPadding: '0 32px',
siderBg: '#FFFFFF',
bodyBg: '#FAF8F5',
},
Menu: {
itemBg: 'transparent',
itemSelectedBg: '#F5F2EE',
itemSelectedColor: '#1A1A16',
itemActiveBg: '#F5F2EE',
},
Card: {
paddingLG: 24,
borderRadiusLG: 8,
},
Button: {
borderRadius: 6,
fontWeight: 500,
},
Input: {
borderRadius: 6,
},
Select: {
borderRadius: 6,
},
Table: {
headerBg: '#FAF8F5',
rowHoverBg: '#F5F2EE',
},
Modal: {
borderRadiusLG: 10,
},
Tag: {
borderRadiusSM: 4,
},
},
}
export default theme
+207
View File
@@ -0,0 +1,207 @@
import { useState, useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import {
Layout, Card, Select, Button, Typography, Space, Tag, Spin, Skeleton, Empty, message,
} from 'antd'
import { ArrowLeftOutlined, WifiOutlined, SignalFilled } from '@ant-design/icons'
import Hls from 'hls.js'
import { getWatchUrls, type WatchInfo, type LineInfo } from '../../api/streams'
const { Header, Content } = Layout
const { Title, Text } = Typography
export default function WatchPage() {
const { id } = useParams<{ id: string }>()
const videoRef = useRef<HTMLVideoElement>(null)
const [info, setInfo] = useState<WatchInfo | null>(null)
const [loading, setLoading] = useState(true)
const [activeLine, setActiveLine] = useState<string>('')
const [activeQuality, setActiveQuality] = useState<string>('')
const [hls, setHls] = useState<Hls | null>(null)
useEffect(() => {
if (!id) return
loadInfo()
const timer = setInterval(loadInfo, 15000)
return () => {
clearInterval(timer)
if (hls) { hls.destroy() }
}
}, [id])
async function loadInfo() {
if (!id) return
try {
const data = await getWatchUrls(parseInt(id))
setInfo(data)
if (!activeLine && data.lines.length > 0) {
const best = autoSelectLine(data.lines)
setActiveLine(best.node_id)
if (data.qualities.length > 0) {
setActiveQuality(data.qualities[0].label)
}
}
} catch { /* stream not ready */ }
setLoading(false)
}
function autoSelectLine(lines: LineInfo[]): LineInfo {
const enabled = lines.filter((l) => l.weight > 0)
if (enabled.length === 0) return lines[0]
const total = enabled.reduce((s, l) => s + l.weight, 0)
let r = Math.random() * total
for (const line of enabled) {
r -= line.weight
if (r <= 0) return line
}
return enabled[enabled.length - 1]
}
useEffect(() => {
if (!info || !activeLine || !videoRef.current) return
const line = info.lines.find((l) => l.node_id === activeLine)
if (!line) return
const quality = activeQuality
? line.qualities.find((q) => q.label === activeQuality)
: line.qualities[0]
if (!quality) return
if (hls) {
hls.destroy()
}
const url = quality.url
if (Hls.isSupported()) {
const hlsInstance = new Hls({
enableWorker: false,
lowLatencyMode: false,
})
hlsInstance.loadSource(url)
hlsInstance.attachMedia(videoRef.current!)
hlsInstance.on(Hls.Events.MANIFEST_PARSED, () => {
videoRef.current?.play().catch(() => {})
})
hlsInstance.on(Hls.Events.ERROR, (_event, data) => {
if (data.fatal) {
message.warning('Playback error, trying fallback...')
if (line.unicast_fallback) {
const fbUrl = activeQuality
? line.unicast_fallback.replace('index.m3u8', `${activeQuality}/index.m3u8`)
: line.unicast_fallback
hlsInstance.loadSource(fbUrl)
}
}
})
setHls(hlsInstance)
} else if (videoRef.current!.canPlayType('application/vnd.apple.mpegurl')) {
videoRef.current!.src = url
}
}, [activeLine, activeQuality, info])
if (loading) {
return (
<div style={{ minHeight: '100vh', background: '#000' }}>
<Skeleton active />
</div>
)
}
if (!info) {
return (
<div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', background: '#FAF8F5' }}>
<Empty description="Stream not found" />
</div>
)
}
return (
<Layout style={{ minHeight: '100vh', background: '#1A1A16' }}>
<Header style={{
background: 'rgba(26,26,22,0.95)',
borderBottom: '1px solid rgba(255,255,255,0.08)',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
padding: '0 24px',
height: 56,
}}>
<Space>
<Button type="text" icon={<ArrowLeftOutlined />} style={{ color: '#fff' }}
onClick={() => window.close()}>
Back
</Button>
<div>
<Title level={5} style={{ color: '#fff', margin: 0 }}>
{info.title}
</Title>
<Tag color={info.status === 'live' ? 'green' : 'default'} style={{ marginLeft: 8 }}>
{info.status === 'live' ? 'LIVE' : info.status}
</Tag>
</div>
</Space>
<Space size="middle">
<div style={{ color: '#aaa', fontSize: 13 }}>
<SignalFilled style={{ color: info.multicast_available ? '#52c41a' : '#666', marginRight: 4 }} />
{info.multicast_available ? 'Multicast' : 'Unicast'}
</div>
<Select
value={activeQuality}
onChange={setActiveQuality}
style={{ width: 100 }}
size="small"
options={info.qualities.map((q) => ({ value: q.label, label: q.label }))}
popupMatchSelectWidth={false}
/>
<Select
value={activeLine}
onChange={setActiveLine}
style={{ width: 140 }}
size="small"
options={info.lines.map((l) => ({
value: l.node_id,
label: `${l.node_name} (${l.weight})`,
}))}
popupMatchSelectWidth={false}
prefix={<WifiOutlined />}
/>
</Space>
</Header>
<Content style={{
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
padding: 24,
maxHeight: 'calc(100vh - 56px)',
}}>
<div style={{ width: '100%', maxWidth: 1280, aspectRatio: '16/9', background: '#000', position: 'relative' }}>
<video
ref={videoRef}
controls
autoPlay
playsInline
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
/>
{info.status !== 'live' && (
<div style={{
position: 'absolute',
inset: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
background: 'rgba(0,0,0,0.7)',
}}>
<Space direction="vertical" align="center">
<Spin size="large" />
<Text style={{ color: '#fff' }}>Waiting for stream to start...</Text>
</Space>
</div>
)}
</div>
</Content>
</Layout>
)
}