journey.mjs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { createApp, h, nextTick } from 'vue'
  4. import { createPinia, setActivePinia } from 'pinia'
  5. import PointDetailCard from '../../src/modules/cockpit/components/PointDetailCard.vue'
  6. import VideoMonitorEntry from '../../src/modules/cockpit/components/VideoMonitorEntry.vue'
  7. import VideoMonitorPanel from '../../src/modules/cockpit/components/VideoMonitorPanel.vue'
  8. import { useDetailStore } from '../../src/modules/cockpit/stores/detailStore.js'
  9. import { useVideoStore } from '../../src/modules/cockpit/stores/videoStore.js'
  10. import { useEnhancementDevicesStore } from '../../src/modules/cockpit/stores/enhancementDevicesStore.js'
  11. const code = 'CAM/01 空格'
  12. const device = { deviceCode: code, deviceName: '现场摄像机A', typeCode: '20', bound: true,
  13. capabilities: { live: true, records: false, playback: false, playbackControl: false, ptz: false, ptzStopGuaranteed: false }, unavailableReason: null }
  14. const envelope = (data, status = 200) => Response.json({ code: status, msg: status === 200 ? '操作成功' : '失败', data }, { status })
  15. const aggregate = { deviceCode: code, aggregateState: 'READY',
  16. archive: { state: 'SUCCESS', data: { deviceCode: code, deviceName: '现场摄像机A', deviceType: '20' } },
  17. metrics: { state: 'EMPTY', data: null }, warnings: { state: 'EMPTY', data: [] }, alarms: { state: 'EMPTY', data: [] },
  18. workOrders: { state: 'EMPTY', data: null }, timelines: { state: 'EMPTY', data: null }, latestImage: { state: 'EMPTY', data: null } }
  19. async function settle() { for (let i = 0; i < 4; i++) { await new Promise(setImmediate); await nextTick() } }
  20. async function mountJourney(overrides = {}) {
  21. const requests = []
  22. const config = { dataSource: 'real', api: { baseUrl: 'http://fixture.invalid/api/cockpit/v1', token: 'must-not-send' } }
  23. const fetchImpl = async (url, options = {}) => {
  24. const path = new URL(url).pathname
  25. const body = options.body ? JSON.parse(options.body) : null
  26. requests.push({ url: new URL(url), path, options, body })
  27. assert.equal(options.headers?.Authorization, undefined)
  28. if (path.endsWith('/detail-aggregate')) return envelope(aggregate)
  29. if (path.endsWith('/collection-records')) return overrides.records?.() || envelope({ deviceCode: code, state: 'EMPTY', recordView: { columns: [], rows: [] } })
  30. if (path.endsWith('/video/device')) {
  31. assert.equal(new URL(url).searchParams.get('deviceCode'), code)
  32. return envelope(overrides.device || device)
  33. }
  34. if (path.endsWith('/video/sessions/prepare')) {
  35. assert.deepEqual(body, { deviceCode: code })
  36. return overrides.prepare?.() || new Response(JSON.stringify({ code: 200, data: {
  37. deviceCode: code, deviceName: device.deviceName, sessionId: 'session-a', sessionToken: 'owner-a', mode: 'LIVE', status: 'PREPARED',
  38. } }), { status: 201, headers: { 'Content-Type': 'application/json' } })
  39. }
  40. if (path.endsWith('/video/sessions/session-a/live')) {
  41. assert.deepEqual(body, { sessionToken: 'owner-a' })
  42. return overrides.live?.() || envelope(livePayload({ native: true, url: 'https://media.invalid/live.mp4' }))
  43. }
  44. if (path.endsWith('/status')) return overrides.status?.() || envelope({ sessionId: 'session-a', deviceCode: code, mode: 'LIVE', status: 'STOPPED' })
  45. if (path.endsWith('/heartbeat')) return overrides.heartbeat?.() || envelope({ sessionId: 'session-a', status: 'ACTIVE' })
  46. if (path.endsWith('/stop')) return overrides.stop?.() || envelope({ sessionId: 'session-a', status: 'STOPPED' })
  47. throw new Error('Unexpected fixture request: ' + path)
  48. }
  49. const pinia = createPinia(); setActivePinia(pinia)
  50. const detail = useDetailStore(); detail.configure({ config, fetchImpl })
  51. const video = useVideoStore(); video.configure({ config, fetchImpl, ...(overrides.sessionOptions || {}) })
  52. await detail.openDevice(code)
  53. const host = document.createElement('main'); document.body.appendChild(host)
  54. const app = createApp({ render: () => h('div', [overrides.entryOnly
  55. ? h(VideoMonitorEntry, { deviceCode: code, monitorSource: overrides.monitorSource || 'enhancement' })
  56. : h(PointDetailCard), h(VideoMonitorPanel)]) })
  57. app.use(pinia).mount(host)
  58. await settle()
  59. return { host, requests, video, detail, config, fetchImpl, async dispose() { app.unmount(); await video.close(); host.remove() } }
  60. }
  61. const livePayload = (media) => ({ deviceCode: code, deviceName: device.deviceName, sessionId: 'session-a', mode: 'LIVE', status: 'ACTIVE', media })
  62. async function openMonitor(page) {
  63. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  64. page.host.querySelector('[data-video-open]').click(); await settle()
  65. return document.querySelector('[data-video-monitor]')
  66. }
  67. test('closing the originating main detail releases video even if another host retains the same device code', async () => {
  68. const page = await mountJourney()
  69. try {
  70. await useEnhancementDevicesStore().open({ code, name: device.deviceName }, {
  71. fetchDetail: async () => ({ state: 'success', data: aggregate }),
  72. })
  73. await openMonitor(page)
  74. page.host.querySelector('[data-detail-close]').click(); await settle()
  75. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false)
  76. const stops = page.requests.filter((request) => request.path.endsWith('/stop'))
  77. assert.equal(stops.length, 1)
  78. assert.deepEqual(stops[0].body, { sessionToken: 'owner-a' })
  79. } finally { await page.dispose() }
  80. })
  81. test('selection invalidation and same-code restoration in one turn still ends the old viewing session', async () => {
  82. const page = await mountJourney()
  83. try {
  84. await openMonitor(page)
  85. page.detail.closeDetail()
  86. const restored = page.detail.openDevice(code)
  87. await restored; await settle()
  88. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false, 'restoring selection must not resurrect its previous viewer')
  89. assert.equal(page.requests.filter((request) => request.path.endsWith('/prepare')).length, 1)
  90. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  91. } finally { await page.dispose() }
  92. })
  93. test('the underground host owns its own viewing source and a main-detail close does not stop it', async () => {
  94. const page = await mountJourney({ entryOnly: true })
  95. try {
  96. await useEnhancementDevicesStore().open({ code, name: device.deviceName }, {
  97. fetchDetail: async () => ({ state: 'success', data: aggregate }),
  98. })
  99. page.host.querySelector('[data-video-open]').click(); await settle()
  100. assert.equal(page.video.state.ownerSource, 'enhancement')
  101. assert.ok(document.querySelector('[data-video-monitor]'))
  102. await page.detail.closeDetail(); await settle()
  103. assert.ok(document.querySelector('[data-video-monitor]'), 'main detail close must not stop the enhancement-owned video')
  104. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 0)
  105. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  106. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false)
  107. } finally { await page.dispose() }
  108. })
  109. test('a successful HTTP envelope for another session cannot confirm cleanup of the current viewer', async () => {
  110. let wrong = true
  111. const page = await mountJourney({ stop: () => envelope({ sessionId: wrong ? 'someone-else' : 'session-a', status: 'STOPPED' }) })
  112. try {
  113. await openMonitor(page)
  114. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  115. assert.ok(page.host.querySelector('[data-video-entry]').textContent.includes('会话释放未确认'))
  116. assert.equal(page.host.querySelector('[data-video-open]').disabled, true)
  117. } finally { wrong = false; await page.dispose() }
  118. })
  119. class TestClock {
  120. now = 0; next = 1; jobs = new Map()
  121. setTimeout(fn, delay) { const id = this.next++; this.jobs.set(id, { fn, at: this.now + delay }); return id }
  122. clearTimeout(id) { this.jobs.delete(id) }
  123. setInterval(fn, delay) { const id = this.setTimeout(fn, delay); this.jobs.get(id).interval = delay; return id }
  124. clearInterval(id) { this.clearTimeout(id) }
  125. async advance(duration) {
  126. const end = this.now + duration
  127. while (true) {
  128. const due = Array.from(this.jobs).filter(([, job]) => job.at <= end).sort((a, b) => a[1].at - b[1].at)[0]
  129. if (!due) break
  130. const [id, job] = due; this.now = job.at
  131. if (job.interval) job.at += job.interval; else this.jobs.delete(id)
  132. job.fn(); await settle()
  133. }
  134. this.now = end; await settle()
  135. }
  136. }
  137. test('watching heartbeat preserves its session ownership and failure releases the viewer', async () => {
  138. const clock = new TestClock(); let wrong = false
  139. const page = await mountJourney({ sessionOptions: { timers: clock }, heartbeat: () => envelope({ sessionId: wrong ? 'other' : 'session-a', status: 'ACTIVE' }) })
  140. try {
  141. const dialog = await openMonitor(page)
  142. dialog.querySelector('video').dispatchEvent(new Event('playing')); await settle()
  143. await clock.advance(30000)
  144. const beat = page.requests.find((request) => request.path.endsWith('/heartbeat'))
  145. assert.deepEqual(beat.body, { sessionToken: 'owner-a' })
  146. wrong = true
  147. await clock.advance(30000)
  148. // Ticket 04: a dropped session is temporary, so the bounded retry runs before the terminal reason.
  149. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  150. await clock.advance(400000)
  151. // After the budget is spent the panel must show a terminal failure and drop the media.
  152. assert.ok(dialog.textContent.includes('播放失败') || dialog.textContent.includes('播放会话已断开'), dialog.textContent)
  153. assert.equal(dialog.querySelector('video'), null)
  154. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  155. } finally { await page.dispose() }
  156. })
  157. test('Escape closes the global modal and releases its viewing resource', async () => {
  158. const page = await mountJourney()
  159. try {
  160. await openMonitor(page)
  161. const key = new Event('keydown', { bubbles: true, cancelable: true }); key.key = 'Escape'
  162. document.dispatchEvent(key); await settle()
  163. assert.equal(document.querySelector('[data-video-monitor]'), null)
  164. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  165. } finally { await page.dispose() }
  166. })
  167. test('collection-record failure does not remove the latest-tab monitoring entry', async () => {
  168. const page = await mountJourney({ records: () => envelope({}, 503) })
  169. try {
  170. const dialog = await openMonitor(page)
  171. assert.ok(dialog.querySelector('video'))
  172. assert.ok(page.host.textContent.includes('其它分区不受影响'))
  173. } finally { await page.dispose() }
  174. })
  175. test('non-camera has no monitor button; unbound and unknown live capability stay disabled without starting', async () => {
  176. for (const camera of [
  177. { ...device, typeCode: '15', bound: false, capabilities: { live: false } },
  178. { ...device, bound: false, capabilities: { live: false }, unavailableReason: '尚未绑定视频' },
  179. { ...device, bound: true, capabilities: { live: false }, unavailableReason: '实时能力未确认' },
  180. ]) {
  181. const page = await mountJourney({ device: camera })
  182. try {
  183. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  184. const button = page.host.querySelector('[data-video-open]')
  185. if (camera.typeCode !== '20') assert.equal(button, null)
  186. else { assert.equal(button.disabled, true); assert.ok(page.host.textContent.includes(camera.unavailableReason)) }
  187. assert.equal(page.requests.some((request) => request.path.endsWith('/live')), false)
  188. } finally { await page.dispose() }
  189. }
  190. })
  191. test('a WebRTC-only media payload is now unsupported: it is refused, released and never presents playing', async () => {
  192. // After tech-stack unification the cockpit plays FLV only; a WebRTC-only response has no playable URL.
  193. const clock = new TestClock()
  194. // Make WebRTC constructible so a fallback would be caught here, not just fail for lack of the API.
  195. const rtc = []
  196. globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
  197. try {
  198. const page = await mountJourney({ sessionOptions: { timers: clock }, live: () => envelope(livePayload({ native: false, webrtc: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play' })) })
  199. try {
  200. const dialog = await openMonitor(page)
  201. assert.equal(dialog.querySelector('video'), null)
  202. // Unsupported media is a capability outcome, never a temporary outage: no retry is spent.
  203. assert.ok(dialog.textContent.includes('不支持'), dialog.textContent)
  204. assert.equal(dialog.textContent.includes('正在播放'), false)
  205. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1, 'an unsupported payload must not be retried')
  206. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  207. assert.equal(rtc.length, 0, 'a WebRTC-only payload must be refused, never attempted')
  208. assert.equal(page.video.state.media, null)
  209. } finally { await page.dispose() }
  210. } finally { delete globalThis.RTCPeerConnection }
  211. })
  212. test('HTTP 200 HTML live response is a visible failure and releases the prepared viewing resource', async () => {
  213. const page = await mountJourney({ live: () => new Response('<html>wrong route</html>', { headers: { 'Content-Type': 'text/html' } }) })
  214. try {
  215. const dialog = await openMonitor(page)
  216. assert.equal(dialog.querySelector('video'), null)
  217. assert.ok(dialog.textContent.includes('无效数据'))
  218. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  219. assert.equal(page.requests.filter((request) => request.path.endsWith('/prepare')).length, 1)
  220. } finally { await page.dispose() }
  221. })
  222. test('a live start exceeding 35 seconds exits visibly and releases a later owned response without opening video', async () => {
  223. const clock = new TestClock(); let respond
  224. const delayed = new Promise((resolve) => { respond = resolve })
  225. const page = await mountJourney({ live: () => delayed, sessionOptions: { timers: clock } })
  226. try {
  227. const dialog = await openMonitor(page)
  228. await clock.advance(35000)
  229. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  230. await clock.advance(400000)
  231. assert.ok(dialog.textContent.includes('视频建立超时'), dialog.textContent)
  232. assert.equal(dialog.querySelector('video'), null)
  233. respond(envelope(livePayload({ native: true, url: 'https://media.invalid/live.mp4' })))
  234. await settle()
  235. assert.equal(dialog.querySelector('video'), null)
  236. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  237. assert.ok(page.requests.filter((request) => request.path.endsWith('/live')).length >= 1)
  238. } finally { await page.dispose() }
  239. })
  240. test('player readiness has a bound independent of HTTP success and cleans its owned session', async () => {
  241. const clock = new TestClock()
  242. const page = await mountJourney({ sessionOptions: { timers: clock } })
  243. try {
  244. const dialog = await openMonitor(page)
  245. assert.ok(dialog.textContent.includes('等待视频画面'))
  246. await clock.advance(20000)
  247. // Ticket 04: an unreachable player is a temporary failure, so the retry state shows first.
  248. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  249. assert.equal(dialog.querySelector('video'), null)
  250. // Exhausting the bounded budget is what finally surfaces the terminal reason.
  251. await clock.advance(400000)
  252. assert.ok(dialog.textContent.includes('播放器就绪超时'), dialog.textContent)
  253. assert.equal(dialog.querySelector('video'), null)
  254. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  255. } finally { await page.dispose() }
  256. })
  257. test('hiding the page closes video and does not reopen it when visible again', async () => {
  258. const page = await mountJourney()
  259. try {
  260. await openMonitor(page)
  261. Object.defineProperty(document, 'hidden', { configurable: true, value: true })
  262. document.dispatchEvent(new Event('visibilitychange')); await settle()
  263. assert.equal(document.querySelector('[data-video-monitor]'), null)
  264. Object.defineProperty(document, 'hidden', { configurable: true, value: false })
  265. document.dispatchEvent(new Event('visibilitychange')); await settle()
  266. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1)
  267. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  268. } finally { delete document.hidden; await page.dispose() }
  269. })
  270. test('latest-tab entry plays the returned FLV through Jessibuca and only Jessibuca play establishes visible playback', async () => {
  271. // Tech-stack unification: the cockpit now decodes FLV with Jessibuca, not WebRTC signalling.
  272. const players = []
  273. const rtc = []
  274. globalThis.Jessibuca = class {
  275. constructor(options) { this.options = options; this.handlers = new Map(); players.push(this) }
  276. on(type, fn) { this.handlers.set(type, fn) }
  277. emit(type) { this.handlers.get(type)?.() }
  278. async play(url) { this.url = url; this.emit('play') }
  279. destroy() { this.destroyed = true }
  280. }
  281. globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
  282. try {
  283. // A competing WebRTC url proves the FLV field wins, not that WebRTC is merely unavailable.
  284. const page = await mountJourney({
  285. live: () => envelope(livePayload({ native: false,
  286. url: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play',
  287. flv: 'https://media.invalid/live.flv' })),
  288. })
  289. try {
  290. const dialog = await openMonitor(page)
  291. // The FLV stream is handed to Jessibuca, not turned into a native <video src>.
  292. assert.equal(players.length, 1)
  293. assert.equal(players[0].url, 'https://media.invalid/live.flv', 'must prefer the flv field over the competing url')
  294. assert.equal(page.video.state.media.kind, 'flv', 'media classification must be flv')
  295. assert.equal(rtc.length, 0, 'FLV playback must never construct RTCPeerConnection')
  296. assert.equal(dialog.querySelector('video'), null)
  297. assert.ok(dialog.textContent.includes('正在播放'), 'a Jessibuca play event establishes visible playback')
  298. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  299. assert.equal(players[0].destroyed, true)
  300. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  301. } finally { await page.dispose() }
  302. } finally { delete globalThis.Jessibuca; delete globalThis.RTCPeerConnection }
  303. })
  304. test('a native (non-FLV) direct URL is played by a <video> that actually carries its src', async () => {
  305. // Regression guard: the native branch must bind :src, otherwise MANUAL direct-URL devices never show.
  306. const page = await mountJourney({ live: () => envelope(livePayload({ native: true, url: 'https://media.invalid/direct.mp4' })) })
  307. try {
  308. const dialog = await openMonitor(page)
  309. const element = dialog.querySelector('video')
  310. assert.ok(element, 'native media must render a <video>')
  311. assert.equal(page.video.state.media.kind, 'native')
  312. // linkeDOM does not reflect a bound src onto attributes/props reliably; assert the component
  313. // chose the native branch with the direct URL, and that it renders a <video> (not the decoder div).
  314. assert.equal(page.video.state.media.url, 'https://media.invalid/direct.mp4')
  315. assert.equal(dialog.querySelector('[data-flv-decoder]'), null, 'native media must not use the Jessibuca decoder')
  316. assert.equal(page.video.state.media.kind, 'native')
  317. element.dispatchEvent(new Event('playing')); await settle()
  318. assert.ok(dialog.textContent.includes('正在播放'))
  319. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  320. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  321. } finally { await page.dispose() }
  322. })
  323. test('device detail latest tab opens its own anonymous live video even with no collection records, then closes it', async () => {
  324. const page = await mountJourney()
  325. try {
  326. const latest = page.host.querySelector('[data-equipment-tab="metrics"]')
  327. assert.ok(latest, 'existing device-detail latest tab must be visible')
  328. latest.click(); await settle()
  329. const open = page.host.querySelector('[data-video-open]')
  330. assert.ok(open, 'the monitor entry must be inside the latest tab')
  331. assert.equal(open.disabled, false)
  332. open.click(); await settle()
  333. const dialog = document.querySelector('[role="dialog"][data-video-monitor]')
  334. assert.ok(dialog)
  335. assert.ok(dialog.textContent.includes('现场摄像机A'))
  336. assert.ok(dialog.textContent.includes(code))
  337. assert.equal(dialog.textContent.includes('owner-a'), false)
  338. dialog.querySelector('video').dispatchEvent(new Event('playing'))
  339. await settle()
  340. assert.ok(dialog.textContent.includes('正在播放'))
  341. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  342. assert.equal(document.querySelector('[data-video-monitor]'), null)
  343. const stops = page.requests.filter((request) => request.path.endsWith('/stop'))
  344. assert.equal(stops.length, 1)
  345. assert.deepEqual(stops[0].body, { sessionToken: 'owner-a' })
  346. } finally { await page.dispose() }
  347. })
  348. test('a failed cleanup is visible at the entry and blocks another live request until cleanup succeeds', async () => {
  349. let cleanupFails = true
  350. const page = await mountJourney({ stop: () => cleanupFails
  351. ? envelope({ category: 'CLEANUP_UNCONFIRMED' }, 503)
  352. : envelope({ sessionId: 'session-a', status: 'STOPPED' }) })
  353. try {
  354. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  355. page.host.querySelector('[data-video-open]').click(); await settle()
  356. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  357. const entry = page.host.querySelector('[data-video-entry]')
  358. assert.ok(entry.textContent.includes('会话释放未确认'))
  359. assert.equal(entry.querySelector('[data-video-open]').disabled, true)
  360. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1)
  361. cleanupFails = false
  362. Array.from(entry.querySelectorAll('button')).find((button) => button.textContent === '重试清理').click(); await settle()
  363. assert.equal(page.host.querySelector('[data-video-open]').disabled, false)
  364. } finally { cleanupFails = false; await page.dispose() }
  365. })