视频接入接口

This commit is contained in:
mmc
2026-08-10 15:25:56 +08:00
parent 7d81362a88
commit a69190cbdc
4 changed files with 464 additions and 74 deletions

View File

@@ -1,104 +1,253 @@
import React, { useState } from 'react';
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Card as AntdCard, Tag, Button, Space, Typography, Row, Col, message
Card, Tag, Button, Space, Typography, Row, Col, Select, Table, Modal, message, Empty, Spin
} from 'antd';
import {
VideoCameraOutlined, PlayCircleOutlined, HistoryOutlined, SettingOutlined,
CameraOutlined, EyeOutlined
VideoCameraOutlined, DownloadOutlined, PlayCircleOutlined,
FolderOutlined, ReloadOutlined, EyeOutlined, DatabaseOutlined
} from '@ant-design/icons';
import axios from 'axios';
import flvjs from 'flv.js';
const { Title, Text } = Typography;
// ======================
// 视频管理(仅 admin 可见)
// 说明:当前为前端展示页,数据使用本地 mock 视频通道。
// 接入真实视频时,「实时预览」可跳转至监控页 /monitor(VideoMonitorPage),
// 或对接 WebRTC / 流媒体服务获取实时画面与回放地址。
// 真实数据对接 nodevideo(端口 9528,SRS 录制文件服务):
// POST /list body: { deviceId?, year?, month?, day? }
// 不传参 → 所有通道(deviceId);传 deviceId → 年份目录;逐级下钻 → 当天视频文件
// 返回 { code, path, directories:[], files:[{ fileName, size, sizeFormatted }] }
// GET /video/download?deviceId=&year=&month=&day=&fileName=
// 流式返回录制视频(SRS 多为 .flv,用 flv.js 播放)
// 说明:本机开发直连 http://localhost:9528;若部署到其它主机,请改为反向代理/相对路径。
// ======================
const MOCK_CHANNELS = [
{ id: 'CAM-01', name: '1区组件巡检摄像头', device: '巡检机器人-01', status: 'online', location: 'A排 1-12 组件', lastUpdate: '2026-08-10 12:58' },
{ id: 'CAM-02', name: '升压站全景摄像头', device: '固定球机', status: 'online', location: '升压站', lastUpdate: '2026-08-10 12:59' },
{ id: 'CAM-03', name: '无人机航拍通道', device: '无人机-01', status: 'offline', location: '全场', lastUpdate: '2026-08-09 18:20' },
{ id: 'CAM-04', name: '汇流箱热成像', device: '巡检机器人-02', status: 'online', location: 'B排汇流箱', lastUpdate: '2026-08-10 13:01' },
{ id: 'CAM-05', name: '逆变器舱监控', device: '固定枪机', status: 'online', location: '逆变器室', lastUpdate: '2026-08-10 13:00' },
{ id: 'CAM-06', name: '组件热斑巡检通道', device: '无人机-02', status: 'offline', location: 'C排组件', lastUpdate: '2026-08-09 17:45' },
];
const NODEVIDEO_BASE = 'http://1.95.137.212:30003';
const fetchList = async (body: Record<string, string> = {}) => {
const res = await axios.post(`${NODEVIDEO_BASE}/list`, body);
return res.data as { code: number; path: string; directories: string[]; files: { fileName: string; size: number; sizeFormatted: string }[]; error?: string };
};
const buildDownloadUrl = (p: { deviceId: string; year: string; month: string; day: string; fileName: string }) =>
`${NODEVIDEO_BASE}/video/download?deviceId=${encodeURIComponent(p.deviceId)}&year=${p.year}&month=${p.month}&day=${p.day}&fileName=${encodeURIComponent(p.fileName)}`;
const isFlv = (name: string) => name.toLowerCase().endsWith('.flv');
const VideoManagement = () => {
const navigate = useNavigate();
const [channels] = useState(MOCK_CHANNELS);
const [channels, setChannels] = useState<string[]>([]);
const [channel, setChannel] = useState<string | undefined>();
const [years, setYears] = useState<string[]>([]);
const [year, setYear] = useState<string | undefined>();
const [months, setMonths] = useState<string[]>([]);
const [month, setMonth] = useState<string | undefined>();
const [days, setDays] = useState<string[]>([]);
const [day, setDay] = useState<string | undefined>();
const [files, setFiles] = useState<{ fileName: string; size: number; sizeFormatted: string }[]>([]);
const [loading, setLoading] = useState(false);
const [preview, setPreview] = useState<{ url: string; fileName: string } | null>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const flvPlayerRef = useRef<any>(null);
const onlineCount = channels.filter((c) => c.status === 'online').length;
const handlePreview = (ch: any) => {
if (ch.status !== 'online') {
message.warning(`${ch.name} 当前离线,无法预览`);
return;
// 1. 加载通道列表(deviceId)
const loadChannels = async () => {
setLoading(true);
try {
const data = await fetchList({});
if (data.code === 200) {
setChannels(data.directories || []);
} else {
setChannels([]);
message.warning(data.error || '读取通道失败');
}
} catch (e) {
setChannels([]);
message.error('无法连接 nodevideo 服务(9528)');
} finally {
setLoading(false);
}
// 跳转至实时监控页,可携带通道信息
navigate('/monitor', { state: { channel: ch.id, name: ch.name } });
};
useEffect(() => { loadChannels(); }, []);
// 2. 选通道 → 加载年份
const onChannelChange = async (val: string) => {
setChannel(val);
setYear(undefined); setYears([]);
setMonth(undefined); setMonths([]);
setDay(undefined); setDays([]);
setFiles([]);
if (!val) return;
setLoading(true);
try {
const data = await fetchList({ deviceId: val });
setYears(data.code === 200 ? (data.directories || []) : []);
} catch { setYears([]); }
finally { setLoading(false); }
};
// 3. 选年份 → 加载月份
const onYearChange = async (val: string) => {
setYear(val);
setMonth(undefined); setMonths([]);
setDay(undefined); setDays([]);
setFiles([]);
if (!val || !channel) return;
setLoading(true);
try {
const data = await fetchList({ deviceId: channel, year: val });
setMonths(data.code === 200 ? (data.directories || []) : []);
} catch { setMonths([]); }
finally { setLoading(false); }
};
// 4. 选月份 → 加载日期
const onMonthChange = async (val: string) => {
setMonth(val);
setDay(undefined); setDays([]);
setFiles([]);
if (!val || !channel || !year) return;
setLoading(true);
try {
const data = await fetchList({ deviceId: channel, year, month: val });
setDays(data.code === 200 ? (data.directories || []) : []);
} catch { setDays([]); }
finally { setLoading(false); }
};
// 5. 选日期 → 加载当天视频文件
const onDayChange = async (val: string) => {
setDay(val);
setFiles([]);
if (!val || !channel || !year || !month) return;
setLoading(true);
try {
const data = await fetchList({ deviceId: channel, year, month, day: val });
setFiles(data.code === 200 ? (data.files || []) : []);
if (data.code !== 200) message.warning(data.error || '读取文件失败');
} catch { setFiles([]); message.error('读取文件失败'); }
finally { setLoading(false); }
};
// 预览:flv 用 flv.js,其余用原生 video
useEffect(() => {
if (!preview) return;
const video = videoRef.current;
if (!video) return;
if (isFlv(preview.fileName) && flvjs.isSupported()) {
const player = flvjs.createPlayer({ type: 'flv', url: preview.url, isLive: false });
player.attachMediaElement(video);
player.load();
player.play().catch(() => { /* 自动播放策略可能拦截,用户手动点击 */ });
flvPlayerRef.current = player;
}
return () => {
flvPlayerRef.current?.destroy();
flvPlayerRef.current = null;
};
}, [preview]);
const openPreview = (file: { fileName: string }) => {
if (!channel || !year || !month || !day) return;
setPreview({
url: buildDownloadUrl({ deviceId: channel, year, month, day, fileName: file.fileName }),
fileName: file.fileName,
});
};
const columns = [
{ title: '文件名', dataIndex: 'fileName', key: 'fileName', ellipsis: true },
{ title: '大小', dataIndex: 'sizeFormatted', key: 'sizeFormatted', width: 120 },
{
title: '操作', key: 'action', width: 160,
render: (_: any, rec: { fileName: string }) => (
<Space>
<Button size="small" type="link" icon={<PlayCircleOutlined />} onClick={() => openPreview(rec)}>预览</Button>
<a href={buildDownloadUrl({ deviceId: channel!, year: year!, month: month!, day: day!, fileName: rec.fileName })} target="_blank" rel="noreferrer">
<Button size="small" type="link" icon={<DownloadOutlined />}>下载</Button>
</a>
</Space>
),
},
];
return (
<div style={{ padding: '8px 0px', background: '#f5f7fa', minHeight: '100vh' }}>
<div style={{ marginBottom: 8 }}>
<Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.1vw, 18px)' }}>视频管理</Title>
<Text type="secondary" style={{ fontSize: 12 }}>视频通道总览与预览管理,仅超级管理员可查看 · 在线 {onlineCount}/{channels.length}</Text>
<Text type="secondary" style={{ fontSize: 12 }}>
录像通道与回放管理(对接 nodevideo :9528) · 共 {channels.length} 个通道
</Text>
</div>
<Row gutter={[8, 8]}>
{channels.map((ch) => {
const online = ch.status === 'online';
return (
<Col xs={24} sm={12} lg={8} xl={6} key={ch.id}>
<AntdCard
bordered={false}
style={{ borderRadius: 10, boxShadow: '0 2px 8px rgba(0,0,0,0.04)', overflow: 'hidden' }}
bodyStyle={{ padding: 12 }}
>
{/* 视频快照占位 */}
<div style={{
position: 'relative', height: 120, borderRadius: 8, marginBottom: 10,
background: online
? 'linear-gradient(135deg, #0b2545 0%, #134074 100%)'
: 'linear-gradient(135deg, #2b2b2b 0%, #4a4a4a 100%)',
display: 'flex', alignItems: 'center', justifyContent: 'center',
}}>
<CameraOutlined style={{ fontSize: 36, color: online ? 'rgba(255,255,255,0.85)' : 'rgba(255,255,255,0.35)' }} />
<div style={{
position: 'absolute', top: 8, left: 8,
padding: '0 8px', borderRadius: 10, fontSize: 10,
background: online ? 'rgba(82,196,26,0.9)' : 'rgba(0,0,0,0.45)',
color: '#fff',
}}>
{online ? '● 在线' : '○ 离线'}
</div>
<div style={{
position: 'absolute', bottom: 8, right: 8,
padding: '0 8px', borderRadius: 10, fontSize: 10,
background: 'rgba(0,0,0,0.45)', color: '#fff',
}}>{ch.id}</div>
</div>
<Card bordered={false} style={{ borderRadius: 10, marginBottom: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }} bodyStyle={{ padding: 12 }}>
<Row gutter={[8, 8]} align="middle">
<Col xs={24} sm={10} md={7}>
<Text style={{ fontSize: 12, color: '#666' }}>通道</Text>
<Select
size="small" style={{ width: '100%' }} placeholder="选择设备通道"
loading={loading && !channels.length}
value={channel} onChange={onChannelChange}
options={channels.map((c) => ({ value: c, label: c }))}
showSearch optionFilterProp="label"
/>
</Col>
<Col xs={8} sm={5} md={4}>
<Text style={{ fontSize: 12, color: '#666' }}>年</Text>
<Select size="small" style={{ width: '100%' }} placeholder="年" disabled={!channel}
value={year} onChange={onYearChange}
options={years.map((y) => ({ value: y, label: y }))} />
</Col>
<Col xs={8} sm={5} md={4}>
<Text style={{ fontSize: 12, color: '#666' }}>月</Text>
<Select size="small" style={{ width: '100%' }} placeholder="月" disabled={!year}
value={month} onChange={onMonthChange}
options={months.map((m) => ({ value: m, label: m }))} />
</Col>
<Col xs={8} sm={5} md={4}>
<Text style={{ fontSize: 12, color: '#666' }}>日</Text>
<Select size="small" style={{ width: '100%' }} placeholder="日" disabled={!month}
value={day} onChange={onDayChange}
options={days.map((d) => ({ value: d, label: d }))} />
</Col>
<Col xs={24} sm={4} md={5}>
<Button size="small" icon={<ReloadOutlined />} onClick={loadChannels} style={{ width: '100%' }}>刷新通道</Button>
</Col>
</Row>
</Card>
<div style={{ fontSize: 13, fontWeight: 600, color: '#262626', marginBottom: 4 }}>{ch.name}</div>
<Space size={4} style={{ fontSize: 11, color: '#8c8c8c', marginBottom: 8 }} wrap>
<VideoCameraOutlined />
<span>{ch.device}</span>
<Tag bordered={false} style={{ margin: 0, fontSize: 10 }} color={online ? 'green' : 'default'}>{ch.location}</Tag>
</Space>
<Card bordered={false} style={{ borderRadius: 10, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }} bodyStyle={{ padding: 4 }}>
{loading ? (
<div style={{ textAlign: 'center', padding: 40 }}><Spin /></div>
) : !channel ? (
<Empty description="请先选择视频通道" style={{ padding: 40 }} />
) : !day ? (
<Empty description="请选择 年 / 月 / 日 加载录像" image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ padding: 40 }} />
) : files.length === 0 ? (
<Empty description="该日暂无录像文件" style={{ padding: 40 }} />
) : (
<Table
size="small" rowKey="fileName" columns={columns} dataSource={files}
pagination={{ size: 'small', pageSize: 10, showTotal: (t) => `共 ${t} 个文件` }}
/>
)}
</Card>
<div style={{ display: 'flex', gap: 6, marginTop: 4 }}>
<Button size="small" type="primary" icon={<PlayCircleOutlined />} style={{ flex: 1 }} onClick={() => handlePreview(ch)}>预览</Button>
<Button size="small" icon={<HistoryOutlined />} disabled={!online} onClick={() => message.info(`${ch.name} 回放功能开发中`)}>回放</Button>
<Button size="small" icon={<SettingOutlined />} onClick={() => message.info(`${ch.name} 参数设置`)} />
</div>
</AntdCard>
</Col>
);
})}
</Row>
<Modal
open={!!preview} title={`预览 ${preview?.fileName || ''}`} footer={null}
onCancel={() => setPreview(null)} width={880} destroyOnClose
>
{preview && isFlv(preview.fileName) ? (
<video ref={videoRef} controls style={{ width: '100%', background: '#000', borderRadius: 8 }} />
) : preview && (
<video src={preview.url} controls style={{ width: '100%', background: '#000', borderRadius: 8 }} />
)}
<div style={{ marginTop: 8, color: '#888', fontSize: 12 }}>
若无法播放,请使用「下载」按钮获取文件后用本地播放器查看。
</div>
</Modal>
</div>
);
};