设备管理 tab重构 加上 flv预览 试试看 但是说 这个不建议预览 只要 下载

This commit is contained in:
mmc
2026-08-12 09:23:47 +08:00
parent a69190cbdc
commit 3c932c41fd
6 changed files with 588 additions and 524 deletions

View File

@@ -17,9 +17,9 @@ import CameraManagement from './CameraManagement';
export default function DeviceManagementPage() {
const [activeTab, setActiveTab] = useState('all');
const [allOrgOptions, setAllOrgOptions] = useState([]);
const [allSiteOptions, setAllSiteOptions] = useState([]);
const [allUserOptions, setAllUserOptions] = useState([]);
const [allOrgOptions, setAllOrgOptions] = useState<any[]>([]);
const [allSiteOptions, setAllSiteOptions] = useState<any[]>([]);
const [allUserOptions, setAllUserOptions] = useState<any[]>([]);
const [dataRefreshKey, setDataRefreshKey] = useState(0);
// 初始化时获取全量数据用于列表匹配
@@ -85,13 +85,14 @@ export default function DeviceManagementPage() {
activeKey={activeTab}
onChange={setActiveTab}
style={{ marginBottom: 0 }}
>
<Tabs.TabPane key="all" tab="设备管理" />
<Tabs.TabPane key="drone" tab="无人机管理" />
<Tabs.TabPane key="smart" tab="智能装备" />
<Tabs.TabPane key="camera" tab="摄像头管理" />
<Tabs.TabPane key="serialGenerate" tab="机器人生成" />
</Tabs>
items={[
{ key: 'all', label: '设备管理' },
{ key: 'drone', label: '无人机管理' },
{ key: 'smart', label: '智能装备' },
{ key: 'camera', label: '摄像头管理' },
{ key: 'serialGenerate', label: '机器人生成' },
]}
/>
{renderTabContent()}
</div >

View File

@@ -0,0 +1,231 @@
import React, { useEffect, useRef, useState } from 'react';
import flvjs from 'flv.js';
import { Spin, Alert, Button, Space } from 'antd';
import { DownloadOutlined, ReloadOutlined } from '@ant-design/icons';
interface FlvPlayerProps {
url: string;
fileName: string;
}
const isFlv = (name: string) => name.toLowerCase().endsWith('.flv');
const FlvPlayer: React.FC<FlvPlayerProps> = ({ url, fileName }) => {
const videoRef = useRef<HTMLVideoElement>(null);
const flvPlayerRef = useRef<flvjs.Player | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [retryCount, setRetryCount] = useState(0);
const [mediaReady, setMediaReady] = useState(false);
useEffect(() => {
const video = videoRef.current;
if (!video) return;
if (flvPlayerRef.current) {
flvPlayerRef.current.destroy();
flvPlayerRef.current = null;
}
video.removeAttribute('src');
video.load();
setLoading(true);
setError(null);
setMediaReady(false);
let timeoutId: ReturnType<typeof setTimeout> | null = null;
let canPlayThroughHandler: (() => void) | null = null;
let stalledHandler: (() => void) | null = null;
let videoErrorHandler: ((e: Event) => void) | null = null;
const initTimer = setTimeout(() => {
if (isFlv(fileName)) {
if (!flvjs.isSupported()) {
setError('当前浏览器不支持 FLV MSE播放,请下载文件查看');
setLoading(false);
return;
}
try {
const player = flvjs.createPlayer({
type: 'flv',
url,
isLive: false,
cors: true,
enableWorker: true,
enableStashBuffer: true,
stashInitialSize: 4 * 1024 * 1024, // 4MB 适配4K
lazyLoad: true, // ✅关键:大文件点播不能false,否则一次性全部下载立刻关闭MSE
lazyLoadMaxDuration: 120,
retryCount: 3,
retryDelay: 1200,
});
player.attachMediaElement(video);
// ✅ canplaythrough:足够数据可以连贯播放,真正就绪
canPlayThroughHandler = () => {
console.log('✅ canplaythrough 媒体就绪');
if (timeoutId) clearTimeout(timeoutId);
setLoading(false);
setMediaReady(true);
};
stalledHandler = () => {
console.warn('⚠️ video stalled 缓冲区卡顿');
};
videoErrorHandler = (ev) => {
const v = ev.target as HTMLVideoElement;
console.error('❌ video element error', ev, v.error);
if (v.error?.code === 3) {
setError('视频编码不受浏览器MSE支持,请下载文件本地播放');
setLoading(false);
if (timeoutId) clearTimeout(timeoutId);
} else if (v.error?.code === 4) {
setError('媒体源不支持');
setLoading(false);
if (timeoutId) clearTimeout(timeoutId);
}
};
video.addEventListener('canplaythrough', canPlayThroughHandler);
video.addEventListener('stalled', stalledHandler);
video.addEventListener('error', videoErrorHandler);
player.on(flvjs.Events.METADATA_ARRIVED, (meta) => {
console.log('📦 METADATA_ARRIVED', meta);
});
player.on(flvjs.Events.MEDIA_INFO, (info) => {
console.log('📺 MEDIA_INFO', info);
});
player.on(flvjs.Events.LOADING_COMPLETE, () => {
console.log('✅ flv 文件全部加载完成');
});
player.on(flvjs.Events.ERROR, (err) => {
console.error('❌ flv error', err);
let msg = 'FLV播放异常,建议下载文件本地播放';
if (err === flvjs.ErrorTypes.NETWORK_ERROR) {
msg = '网络错误,请检查视频地址';
} else if (err === flvjs.ErrorTypes.MEDIA_ERROR) {
msg = '媒体解码错误,该FLV文件可能不兼容浏览器MSE';
}
setError(msg);
setLoading(false);
if (timeoutId) clearTimeout(timeoutId);
});
timeoutId = setTimeout(() => {
// 15s超时:还没就绪,判定异常
if (!mediaReady) {
setError('加载超时,浏览器MSE解析失败,请下载文件本地播放');
setLoading(false);
}
}, 15000);
player.load();
flvPlayerRef.current = player;
console.log('🚀 flv player created');
} catch (err) {
console.error('❌ create player exception', err);
setError('播放器初始化失败,请重试');
setLoading(false);
}
} else {
// mp4原生
video.src = url;
video.load();
canPlayThroughHandler = () => {
if (timeoutId) clearTimeout(timeoutId);
setLoading(false);
setMediaReady(true);
};
videoErrorHandler = () => {
if (timeoutId) clearTimeout(timeoutId);
setError('视频加载失败,请检查地址或下载');
setLoading(false);
};
video.addEventListener('canplaythrough', canPlayThroughHandler);
video.addEventListener('error', videoErrorHandler);
timeoutId = setTimeout(() => {
if (!mediaReady) console.warn('⏰原生视频加载慢');
}, 15000);
}
}, 200);
return () => {
clearTimeout(initTimer);
if (timeoutId) clearTimeout(timeoutId);
if (flvPlayerRef.current) {
flvPlayerRef.current.destroy();
flvPlayerRef.current = null;
}
if (video) {
if (canPlayThroughHandler) video.removeEventListener('canplaythrough', canPlayThroughHandler);
if (stalledHandler) video.removeEventListener('stalled', stalledHandler);
if (videoErrorHandler) video.removeEventListener('error', videoErrorHandler);
}
};
}, [url, fileName, retryCount, mediaReady]);
const handleRetry = () => setRetryCount(p => p + 1);
const handleManualPlay = async () => {
const v = videoRef.current;
if (!v) return;
try {
await v.play();
} catch (e) {
console.warn('手动播放失败', e);
}
};
if (error) {
return (
<div style={{ textAlign: 'center', padding: 30 }}>
<Alert message="播放失败" description={error} type="error" showIcon style={{ marginBottom: 16 }} />
<Space>
<Button icon={<ReloadOutlined />} onClick={handleRetry}>重试</Button>
<Button type="primary" icon={<DownloadOutlined />} onClick={() => window.open(url, '_blank')}>
下载视频
</Button>
</Space>
</div>
);
}
return (
<div>
{loading && (
<div style={{ textAlign: 'center', padding: 40 }}>
<Spin tip="视频加载中..." />
</div>
)}
{mediaReady && (
<Button onClick={handleManualPlay} style={{ marginBottom: 8 }}>
点击手动播放视频
</Button>
)}
<video
ref={videoRef}
controls
style={{
width: '100%',
background: '#000',
borderRadius: 8,
maxHeight: '70vh',
display: loading ? 'none' : 'block',
}}
playsInline
/>
<div style={{ marginTop: 8, color: '#888', fontSize: 12 }}>
{isFlv(fileName) && <span>💡 FLV 使用 flv.js(MSE)解码,部分特殊编码FLV浏览器无法渲染,建议下载本地播放</span>}
{!isFlv(fileName) && <span>💡 非FLV使用浏览器原生播放</span>}
</div>
</div>
);
};
export default FlvPlayer;

View File

@@ -1,42 +1,46 @@
import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import {
Card, Tag, Button, Space, Typography, Row, Col, Select, Table, Modal, message, Empty, Spin
Card, Button, Space, Typography, Row, Col, Select, Table, Modal, message, Empty, Spin
} from 'antd';
import {
VideoCameraOutlined, DownloadOutlined, PlayCircleOutlined,
FolderOutlined, ReloadOutlined, EyeOutlined, DatabaseOutlined
DownloadOutlined, PlayCircleOutlined, ReloadOutlined
} from '@ant-design/icons';
import axios from 'axios';
import flvjs from 'flv.js';
import FlvPlayer from './FlvPlayer';
const { Title, Text } = Typography;
// ======================
// 视频管理(仅 admin 可见)
// 真实数据对接 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 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 };
return res.data;
};
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 buildDownloadUrl = (p: {
deviceId: string;
year: string;
month: string;
day: string;
fileName: string;
download?: boolean;
}) => {
const params = new URLSearchParams({
deviceId: p.deviceId,
year: p.year,
month: p.month,
day: p.day,
fileName: p.fileName,
});
if (p.download) params.append('download', 'true');
return `${NODEVIDEO_BASE}/video/download?${params.toString()}`;
};
const isFlv = (name: string) => name.toLowerCase().endsWith('.flv');
const isMp4 = (name: string) => name.toLowerCase().endsWith('.mp4');
const VideoManagement = () => {
const navigate = useNavigate();
const [channels, setChannels] = useState<string[]>([]);
const [channel, setChannel] = useState<string | undefined>();
const [years, setYears] = useState<string[]>([]);
@@ -48,10 +52,12 @@ const VideoManagement = () => {
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 [playerError, setPlayerError] = useState<string | null>(null);
const videoRef = useRef<HTMLVideoElement>(null);
const flvPlayerRef = useRef<any>(null);
// 1. 加载通道列表(deviceId)
// 加载通道列表
const loadChannels = async () => {
setLoading(true);
try {
@@ -64,7 +70,7 @@ const VideoManagement = () => {
}
} catch (e) {
setChannels([]);
message.error('无法连接 nodevideo 服务(9528)');
message.error('无法连接视频服务');
} finally {
setLoading(false);
}
@@ -72,7 +78,7 @@ const VideoManagement = () => {
useEffect(() => { loadChannels(); }, []);
// 2. 选通道 → 加载年份
// 通道变更
const onChannelChange = async (val: string) => {
setChannel(val);
setYear(undefined); setYears([]);
@@ -88,7 +94,7 @@ const VideoManagement = () => {
finally { setLoading(false); }
};
// 3. 选年份 → 加载月份
// 年份变更
const onYearChange = async (val: string) => {
setYear(val);
setMonth(undefined); setMonths([]);
@@ -103,7 +109,7 @@ const VideoManagement = () => {
finally { setLoading(false); }
};
// 4. 选月份 → 加载日期
// 月份变更
const onMonthChange = async (val: string) => {
setMonth(val);
setDay(undefined); setDays([]);
@@ -117,7 +123,7 @@ const VideoManagement = () => {
finally { setLoading(false); }
};
// 5. 选日期 → 加载当天视频文件
// 日期变更
const onDayChange = async (val: string) => {
setDay(val);
setFiles([]);
@@ -131,26 +137,13 @@ const VideoManagement = () => {
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;
if (!channel || !year || !month || !day) {
message.warning('请先选择完整的时间路径');
return;
}
setPreview({
url: buildDownloadUrl({ deviceId: channel, year, month, day, fileName: file.fileName }),
fileName: file.fileName,
@@ -163,12 +156,21 @@ const VideoManagement = () => {
{
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>
<a
href={buildDownloadUrl({
deviceId: channel!,
year: year!,
month: month!,
day: day!,
fileName: rec.fileName,
download: true
})}
target="_blank"
rel="noreferrer"
>
<Button size="small" type="link" icon={<DownloadOutlined />}>下载</Button>
</a>
),
},
];
@@ -178,11 +180,11 @@ const VideoManagement = () => {
<div style={{ marginBottom: 8 }}>
<Title level={4} style={{ margin: 0, fontSize: 'clamp(14px, 1.1vw, 18px)' }}>视频管理</Title>
<Text type="secondary" style={{ fontSize: 12 }}>
录像通道与回放管理(对接 nodevideo :9528) · 共 {channels.length} 个通道
录像通道与回放管理 · 共 {channels.length} 个通道
</Text>
</div>
<Card bordered={false} style={{ borderRadius: 10, marginBottom: 8, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }} bodyStyle={{ padding: 12 }}>
<Card bordered={false} style={{ borderRadius: 10, marginBottom: 8 }} bodyStyle={{ padding: 12 }}>
<Row gutter={[8, 8]} align="middle">
<Col xs={24} sm={10} md={7}>
<Text style={{ fontSize: 12, color: '#666' }}>通道</Text>
@@ -196,29 +198,33 @@ const VideoManagement = () => {
</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 }))} />
<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 }))} />
<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>
<Select
size="small" style={{ width: '100%' }} placeholder="日"
disabled={!month} value={day} onChange={onDayChange}
options={days.map((d) => ({ value: d, label: d }))}
/>
</Col>
</Row>
</Card>
<Card bordered={false} style={{ borderRadius: 10, boxShadow: '0 2px 8px rgba(0,0,0,0.04)' }} bodyStyle={{ padding: 4 }}>
<Card bordered={false} style={{ borderRadius: 10 }} bodyStyle={{ padding: 4 }}>
{loading ? (
<div style={{ textAlign: 'center', padding: 40 }}><Spin /></div>
) : !channel ? (
@@ -236,17 +242,15 @@ const VideoManagement = () => {
</Card>
<Modal
open={!!preview} title={`预览 ${preview?.fileName || ''}`} footer={null}
onCancel={() => setPreview(null)} width={880} destroyOnClose
open={!!preview}
title={`预览: ${preview?.fileName || ''}`}
footer={null}
onCancel={() => setPreview(null)}
width={880}
destroyOnClose
key={preview?.fileName || 'preview'}
>
{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>
{preview && <FlvPlayer url={preview.url} fileName={preview.fileName} />}
</Modal>
</div>
);