import { selectVideoMedia, VideoRequestError } from './videoApi.js' const WINDOW = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/ const MAX_SPAN_MS = 7 * 24 * 60 * 60 * 1000 const UTC8_OFFSET_MS = 8 * 60 * 60 * 1000 /** Today 00:00 to now, expressed as UTC+8 wall-clock text regardless of the machine zone. */ export function defaultHistoryWindow(now = () => Date.now()) { const shifted = new Date(now() + UTC8_OFFSET_MS) const pad = (value) => String(value).padStart(2, '0') const day = `${shifted.getUTCFullYear()}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}` const clock = `${pad(shifted.getUTCHours())}:${pad(shifted.getUTCMinutes())}:${pad(shifted.getUTCSeconds())}` return { startTime: `${day} 00:00:00`, endTime: `${day} ${clock}` } } /** Parses a UTC+8 wall-clock string into a comparable instant, or null when malformed. */ function instant(text) { const match = WINDOW.exec(typeof text === 'string' ? text : '') if (!match) return null const [, year, month, day, hour, minute, second] = match.map(Number) const value = Date.UTC(year, month - 1, day, hour, minute, second) const back = new Date(value) // Reject impossible calendar values instead of letting Date silently roll them over. if (back.getUTCFullYear() !== year || back.getUTCMonth() !== month - 1 || back.getUTCDate() !== day || back.getUTCHours() !== hour || back.getUTCMinutes() !== minute || back.getUTCSeconds() !== second) return null return value } /** The query window contract: real UTC+8 instants, ordered, and at most seven days apart. */ function validate(from, to) { const start = instant(from), end = instant(to) if (start === null || end === null || end <= start || end - start > MAX_SPAN_MS) throw new VideoRequestError('INVALID_REQUEST', '录像时间格式为 yyyy-MM-dd HH:mm:ss,结束时间须晚于开始时间且范围不超过 7 天') return { start, end } } /** A seek is only meaningful inside the recording the viewer chose, not the whole day. */ function insideWindow(owned, seconds) { const span = owned.span if (!span || !Number.isFinite(seconds) || seconds < 0 || seconds > span.seconds) return false return true } /** Only explicitly confirmed controls are enabled; anything unreported stays unconfirmed. */ function normalizeControls(reported) { const source = reported && typeof reported === 'object' ? reported : {} return { pause: source.pause === true, resume: source.resume === true, speed: source.speed === true, seek: source.seek === true } } /** * History browsing and controlled playback for one anonymous viewer. * Records are only ever shown from what the device/NVR returned; playback starts only on an explicit choice. */ export function createVideoPlaybackSession(api, update, timers = globalThis) { const cleanupMessage = '回放释放未确认,等待服务端回收' let disposed = false, current = null, identity = null, records = [], generation = 0 const publish = (patch) => { if (!disposed) update(patch) } const reset = () => { current = null; identity = null; records = []; publish({ media: null, records: [], empty: false, error: '', cleanupError: '' }) } async function query(deviceCode, startTime, endTime) { // An illegal window is refused locally and surfaced, never sent to the server. try { validate(startTime, endTime) } catch (error) { records = [] publish({ phase: 'failed', records: [], empty: false, error: error?.message || '录像时间范围不合法' }) return [] } records = [] publish({ phase: 'querying', records: [], empty: false, error: '', cleanupError: '', window: { startTime, endTime } }) let reply try { reply = await api.records(deviceCode, startTime, endTime) } catch (error) { publish({ phase: 'failed', records: [], empty: false, error: error?.message || '录像查询失败' }) return [] } if (disposed) return [] const list = Array.isArray(reply?.records) ? reply.records : [] records = list // An empty list is an answer; a failure is not. Never retry either automatically. publish({ phase: 'listed', records: list, empty: list.length === 0, error: '' }) return list } async function play(deviceCode, startTime, endTime) { try { validate(startTime, endTime) } catch (error) { publish({ phase: 'failed', media: null, error: error?.message || '录像时间范围不合法' }) return false } // The previous stream of whichever mode must end before this one replaces it. await stop() if (disposed) return false const version = ++generation publish({ phase: 'starting', media: null, records, error: '', cleanupError: '' }) let started try { started = await api.playback(deviceCode, startTime, endTime) } catch (error) { if (disposed || version !== generation) return false // An occupied channel is reported as such and never releases the existing viewer. const occupied = error?.category === 'PLAYBACK_OCCUPIED' publish({ phase: 'failed', media: null, error: occupied ? '此通道已有录像回放,请结束后重试' : (error?.message || '录像回放启动失败') }) return false } if (disposed || version !== generation) { await release(started) return false } let media try { media = selectVideoMedia(started.media) } catch (error) { await release(started) if (version === generation) publish({ phase: 'failed', media: null, error: error?.message || '回放媒体不可用' }) return false } identity = { sessionId: started.sessionId, sessionToken: started.sessionToken, deviceCode, mode: 'PLAYBACK', // The chosen span bounds every seek; it is never the query window from the input fields. span: { start: instant(startTime), end: instant(endTime), seconds: (instant(endTime) - instant(startTime)) / 1000 }, // A device that reported confirmed controls keeps them; the default confirms nothing. controls: normalizeControls(started.controls) } current = identity // durationSeconds lets the panel bound the seek input to the chosen recording, not the day. publish({ phase: 'playing', media, window: { startTime, endTime }, durationSeconds: identity.span.seconds, controls: identity.controls }) return true } /** * Only a control the device confirmed may be sent; everything else is refused locally. * `seconds` is the offset inside the chosen recording, required for seek. */ async function control(key, seconds) { const owned = current const match = /^(pause|resume|seek|speed-(0\.25|0\.5|1|2|4))$/.exec(String(key)) if (!owned || !match) return false const granted = owned.controls || {} const action = match[2] ? 'speed' : match[1] const allowed = action === 'speed' ? granted.speed : granted[action] if (allowed !== true) return false // The control API takes an action plus its value; a rate key carries the rate as its value. if (action === 'seek' && !insideWindow(owned, seconds)) { publish({ error: '跳转位置必须是所选时段内的秒数' }) return false } const value = action === 'speed' ? Number(match[2]) : action === 'seek' ? seconds : undefined try { await api.control(owned, action, value) // A previous rejection must not linger after a control the server accepted. publish({ error: '' }) return true } catch (error) { publish({ error: error?.message || '回放控制失败' }) return false } } async function release(session) { if (!session) return true try { const result = await api.stop(session) if (result?.sessionId !== session.sessionId || !['STOPPED', 'FAILED'].includes(result?.status)) throw new Error('unconfirmed') return true } catch { publish({ cleanupError: cleanupMessage }) return false } } async function stop() { ++generation const owned = identity identity = null; current = null // A released session must not carry its capabilities or duration into the next one. publish({ media: null, phase: 'idle', controls: {}, durationSeconds: 0 }) const clean = await release(owned) if (!clean) publish({ phase: 'failed', error: cleanupMessage }) return clean } /** Player callbacks: a playback failure belongs to the history surface, never the live one. */ const ready = () => { if (!disposed && current) publish({ error: '' }) } const fail = (error) => { if (disposed) return const message = typeof error === 'string' ? error : error?.message publish({ error: message || '历史录像画面播放失败' }) } async function dispose() { await stop(); disposed = true } return { query, play, control, stop, dispose, ready, fail, records: () => records, current: () => current } }