journey.mjs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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 VideoMonitorPanel from '../../src/modules/cockpit/components/VideoMonitorPanel.vue'
  7. import { useDetailStore } from '../../src/modules/cockpit/stores/detailStore.js'
  8. import { useVideoStore } from '../../src/modules/cockpit/stores/videoStore.js'
  9. const code = 'CAM/01 空格'
  10. const device = { deviceCode: code, deviceName: '现场摄像机A', typeCode: '20', bound: true,
  11. capabilities: { live: true, records: false, playback: false, playbackControl: false, ptz: false, ptzStopGuaranteed: false }, unavailableReason: null }
  12. const envelope = (data, status = 200) => Response.json({ code: status, msg: status === 200 ? '操作成功' : '失败', data }, { status })
  13. const aggregate = { deviceCode: code, aggregateState: 'READY',
  14. archive: { state: 'SUCCESS', data: { deviceCode: code, deviceName: '现场摄像机A', deviceType: '20' } },
  15. metrics: { state: 'EMPTY', data: null }, warnings: { state: 'EMPTY', data: [] }, alarms: { state: 'EMPTY', data: [] },
  16. workOrders: { state: 'EMPTY', data: null }, timelines: { state: 'EMPTY', data: null }, latestImage: { state: 'EMPTY', data: null } }
  17. async function settle() { for (let i = 0; i < 4; i++) { await new Promise(setImmediate); await nextTick() } }
  18. async function mountJourney(overrides = {}) {
  19. const requests = []
  20. const config = { dataSource: 'real', api: { baseUrl: 'http://fixture.invalid/api/cockpit/v1', token: 'must-not-send' } }
  21. const fetchImpl = async (url, options = {}) => {
  22. const path = new URL(url).pathname
  23. const body = options.body ? JSON.parse(options.body) : null
  24. requests.push({ url: new URL(url), path, options, body })
  25. assert.equal(options.headers?.Authorization, undefined)
  26. if (path.endsWith('/detail-aggregate')) return envelope(aggregate)
  27. if (path.endsWith('/collection-records')) return overrides.records?.() || envelope({ deviceCode: code, state: 'EMPTY', recordView: { columns: [], rows: [] } })
  28. if (path.endsWith('/video/device')) {
  29. assert.equal(new URL(url).searchParams.get('deviceCode'), code)
  30. return envelope(overrides.device || device)
  31. }
  32. if (path.endsWith('/video/live')) {
  33. assert.deepEqual(body, { deviceCode: code })
  34. return overrides.live?.() || envelope({ deviceCode: code, deviceName: device.deviceName,
  35. sessionId: 'session-a', sessionToken: 'owner-a', mode: 'LIVE', media: { native: true, url: 'https://media.invalid/live.mp4' } })
  36. }
  37. if (path.endsWith('/heartbeat')) return overrides.heartbeat?.() || envelope({ sessionId: 'session-a', status: 'ACTIVE' })
  38. if (path.endsWith('/stop')) return overrides.stop?.() || envelope({ sessionId: 'session-a', status: 'STOPPED' })
  39. throw new Error('Unexpected fixture request: ' + path)
  40. }
  41. const pinia = createPinia(); setActivePinia(pinia)
  42. const detail = useDetailStore(); detail.configure({ config, fetchImpl })
  43. const video = useVideoStore(); video.configure({ config, fetchImpl, ...(overrides.sessionOptions || {}) })
  44. await detail.openDevice(code)
  45. const host = document.createElement('main'); document.body.appendChild(host)
  46. const app = createApp({ render: () => h('div', [h(PointDetailCard), h(VideoMonitorPanel)]) })
  47. app.use(pinia).mount(host)
  48. await settle()
  49. return { host, requests, video, detail, async dispose() { app.unmount(); await video.close(); host.remove() } }
  50. }
  51. const livePayload = (media) => ({ deviceCode: code, deviceName: device.deviceName, sessionId: 'session-a', sessionToken: 'owner-a', mode: 'LIVE', media })
  52. async function openMonitor(page) {
  53. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  54. page.host.querySelector('[data-video-open]').click(); await settle()
  55. return document.querySelector('[data-video-monitor]')
  56. }
  57. test('a successful HTTP envelope for another session cannot confirm cleanup of the current viewer', async () => {
  58. let wrong = true
  59. const page = await mountJourney({ stop: () => envelope({ sessionId: wrong ? 'someone-else' : 'session-a', status: 'STOPPED' }) })
  60. try {
  61. await openMonitor(page)
  62. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  63. assert.ok(page.host.querySelector('[data-video-entry]').textContent.includes('会话释放未确认'))
  64. assert.equal(page.host.querySelector('[data-video-open]').disabled, true)
  65. } finally { wrong = false; await page.dispose() }
  66. })
  67. class TestClock {
  68. now = 0; next = 1; jobs = new Map()
  69. setTimeout(fn, delay) { const id = this.next++; this.jobs.set(id, { fn, at: this.now + delay }); return id }
  70. clearTimeout(id) { this.jobs.delete(id) }
  71. setInterval(fn, delay) { const id = this.setTimeout(fn, delay); this.jobs.get(id).interval = delay; return id }
  72. clearInterval(id) { this.clearTimeout(id) }
  73. async advance(duration) {
  74. const end = this.now + duration
  75. while (true) {
  76. const due = Array.from(this.jobs).filter(([, job]) => job.at <= end).sort((a, b) => a[1].at - b[1].at)[0]
  77. if (!due) break
  78. const [id, job] = due; this.now = job.at
  79. if (job.interval) job.at += job.interval; else this.jobs.delete(id)
  80. job.fn(); await settle()
  81. }
  82. this.now = end; await settle()
  83. }
  84. }
  85. test('watching heartbeat preserves its session ownership and failure releases the viewer', async () => {
  86. const clock = new TestClock(); let wrong = false
  87. const page = await mountJourney({ sessionOptions: { timers: clock }, heartbeat: () => envelope({ sessionId: wrong ? 'other' : 'session-a', status: 'ACTIVE' }) })
  88. try {
  89. const dialog = await openMonitor(page)
  90. dialog.querySelector('video').dispatchEvent(new Event('playing')); await settle()
  91. await clock.advance(30000)
  92. const beat = page.requests.find((request) => request.path.endsWith('/heartbeat'))
  93. assert.deepEqual(beat.body, { sessionToken: 'owner-a' })
  94. wrong = true
  95. await clock.advance(30000)
  96. assert.equal(dialog.querySelector('video'), null)
  97. assert.ok(dialog.textContent.includes('播放会话已断开'))
  98. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  99. } finally { await page.dispose() }
  100. })
  101. test('Escape closes the global modal and releases its viewing resource', async () => {
  102. const page = await mountJourney()
  103. try {
  104. await openMonitor(page)
  105. const key = new Event('keydown', { bubbles: true, cancelable: true }); key.key = 'Escape'
  106. document.dispatchEvent(key); await settle()
  107. assert.equal(document.querySelector('[data-video-monitor]'), null)
  108. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  109. } finally { await page.dispose() }
  110. })
  111. test('collection-record failure does not remove the latest-tab monitoring entry', async () => {
  112. const page = await mountJourney({ records: () => envelope({}, 503) })
  113. try {
  114. const dialog = await openMonitor(page)
  115. assert.ok(dialog.querySelector('video'))
  116. assert.ok(page.host.textContent.includes('其它分区不受影响'))
  117. } finally { await page.dispose() }
  118. })
  119. test('non-camera has no monitor button; unbound and unknown live capability stay disabled without starting', async () => {
  120. for (const camera of [
  121. { ...device, typeCode: '15', bound: false, capabilities: { live: false } },
  122. { ...device, bound: false, capabilities: { live: false }, unavailableReason: '尚未绑定视频' },
  123. { ...device, bound: true, capabilities: { live: false }, unavailableReason: '实时能力未确认' },
  124. ]) {
  125. const page = await mountJourney({ device: camera })
  126. try {
  127. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  128. const button = page.host.querySelector('[data-video-open]')
  129. if (camera.typeCode !== '20') assert.equal(button, null)
  130. else { assert.equal(button.disabled, true); assert.ok(page.host.textContent.includes(camera.unavailableReason)) }
  131. assert.equal(page.requests.some((request) => request.path.endsWith('/video/live')), false)
  132. } finally { await page.dispose() }
  133. }
  134. })
  135. test('unsupported returned media releases its owned session and never presents playing', async () => {
  136. const page = await mountJourney({ live: () => envelope(livePayload({ native: false, flv: 'https://media.invalid/live.flv' })) })
  137. try {
  138. const dialog = await openMonitor(page)
  139. assert.equal(dialog.querySelector('video'), null)
  140. assert.ok(dialog.textContent.includes('不支持'))
  141. assert.equal(dialog.textContent.includes('正在播放'), false)
  142. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  143. } finally { await page.dispose() }
  144. })
  145. test('HTTP 200 HTML is a visible failure with unconfirmed resources, not an active video', async () => {
  146. const page = await mountJourney({ live: () => new Response('<html>wrong route</html>', { headers: { 'Content-Type': 'text/html' } }) })
  147. try {
  148. const dialog = await openMonitor(page)
  149. assert.equal(dialog.querySelector('video'), null)
  150. assert.ok(dialog.textContent.includes('无效数据'))
  151. assert.ok(dialog.textContent.includes('未确认'))
  152. assert.equal(Array.from(dialog.querySelectorAll('button')).find((button) => button.textContent === '重新播放').disabled, true)
  153. } finally { await page.dispose() }
  154. })
  155. test('a live start exceeding 35 seconds exits visibly and releases a later owned response without opening video', async () => {
  156. const clock = new TestClock(); let respond
  157. const delayed = new Promise((resolve) => { respond = resolve })
  158. const page = await mountJourney({ live: () => delayed, sessionOptions: { timers: clock } })
  159. try {
  160. const dialog = await openMonitor(page)
  161. await clock.advance(35000)
  162. assert.ok(dialog.textContent.includes('视频建立超时'))
  163. assert.equal(dialog.querySelector('video'), null)
  164. respond(envelope(livePayload({ native: true, url: 'https://media.invalid/live.mp4' })))
  165. await settle()
  166. assert.equal(dialog.querySelector('video'), null)
  167. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  168. assert.equal(page.requests.filter((request) => request.path.endsWith('/video/live')).length, 1)
  169. } finally { await page.dispose() }
  170. })
  171. test('player readiness has a bound independent of HTTP success and cleans its owned session', async () => {
  172. const clock = new TestClock()
  173. const page = await mountJourney({ sessionOptions: { timers: clock } })
  174. try {
  175. const dialog = await openMonitor(page)
  176. assert.ok(dialog.textContent.includes('等待视频画面'))
  177. await clock.advance(20000)
  178. assert.ok(dialog.textContent.includes('播放器就绪超时'))
  179. assert.equal(dialog.querySelector('video'), null)
  180. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  181. } finally { await page.dispose() }
  182. })
  183. test('hiding the page closes video and does not reopen it when visible again', async () => {
  184. const page = await mountJourney()
  185. try {
  186. await openMonitor(page)
  187. Object.defineProperty(document, 'hidden', { configurable: true, value: true })
  188. document.dispatchEvent(new Event('visibilitychange')); await settle()
  189. assert.equal(document.querySelector('[data-video-monitor]'), null)
  190. Object.defineProperty(document, 'hidden', { configurable: true, value: false })
  191. document.dispatchEvent(new Event('visibilitychange')); await settle()
  192. assert.equal(page.requests.filter((request) => request.path.endsWith('/video/live')).length, 1)
  193. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  194. } finally { delete document.hidden; await page.dispose() }
  195. })
  196. test('latest-tab entry drives WebRTC signaling and only a video playing event establishes visible playback', async () => {
  197. const peers = [], signaling = []
  198. class Emitter {
  199. handlers = new Map()
  200. addEventListener(type, fn) { const group = this.handlers.get(type) || new Set(); group.add(fn); this.handlers.set(type, group) }
  201. removeEventListener(type, fn) { this.handlers.get(type)?.delete(fn) }
  202. emit(type, event = {}) { for (const fn of this.handlers.get(type) || []) fn(event) }
  203. }
  204. const track = new Emitter(); track.kind = 'video'; track.readyState = 'live'; track.stop = () => { track.readyState = 'ended' }
  205. class Peer extends Emitter {
  206. iceGatheringState = 'complete'; connectionState = 'new'; closed = false
  207. constructor(options) { super(); assert.deepEqual(options, { iceServers: [] }); peers.push(this) }
  208. addTransceiver() {}
  209. async createOffer() { return { type: 'offer', sdp: 'v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n' } }
  210. async setLocalDescription(offer) { this.localDescription = offer }
  211. async setRemoteDescription(answer) { this.remoteDescription = answer }
  212. getReceivers() { return [{ track }] }
  213. close() { this.closed = true }
  214. }
  215. const page = await mountJourney({
  216. live: () => envelope(livePayload({ native: false, webrtc: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play' })),
  217. sessionOptions: { playerOptions: { PeerConnection: Peer, fetchImpl: async (url, options) => {
  218. signaling.push({ url, options }); assert.equal(options.credentials, 'omit')
  219. return Response.json({ code: 0, type: 'answer', sdp: 'v=0\r\nm=video 9 UDP/TLS/RTP/SAVPF 96\r\n' })
  220. } } },
  221. })
  222. try {
  223. const dialog = await openMonitor(page)
  224. assert.equal(signaling.length, 1)
  225. assert.ok(signaling[0].options.body.startsWith('v=0'))
  226. assert.equal(dialog.textContent.includes('正在播放'), false)
  227. const stream = { getTracks: () => [track], addTrack() {} }
  228. peers[0].emit('track', { track, streams: [stream] })
  229. dialog.querySelector('video').dispatchEvent(new Event('playing')); await settle()
  230. assert.ok(dialog.textContent.includes('正在播放'))
  231. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  232. assert.equal(peers[0].closed, true)
  233. assert.equal(track.readyState, 'ended')
  234. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  235. } finally { await page.dispose() }
  236. })
  237. test('device detail latest tab opens its own anonymous live video even with no collection records, then closes it', async () => {
  238. const page = await mountJourney()
  239. try {
  240. const latest = page.host.querySelector('[data-equipment-tab="metrics"]')
  241. assert.ok(latest, 'existing device-detail latest tab must be visible')
  242. latest.click(); await settle()
  243. const open = page.host.querySelector('[data-video-open]')
  244. assert.ok(open, 'the monitor entry must be inside the latest tab')
  245. assert.equal(open.disabled, false)
  246. open.click(); await settle()
  247. const dialog = document.querySelector('[role="dialog"][data-video-monitor]')
  248. assert.ok(dialog)
  249. assert.ok(dialog.textContent.includes('现场摄像机A'))
  250. assert.ok(dialog.textContent.includes(code))
  251. assert.equal(dialog.textContent.includes('owner-a'), false)
  252. dialog.querySelector('video').dispatchEvent(new Event('playing'))
  253. await settle()
  254. assert.ok(dialog.textContent.includes('正在播放'))
  255. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  256. assert.equal(document.querySelector('[data-video-monitor]'), null)
  257. const stops = page.requests.filter((request) => request.path.endsWith('/stop'))
  258. assert.equal(stops.length, 1)
  259. assert.deepEqual(stops[0].body, { sessionToken: 'owner-a' })
  260. } finally { await page.dispose() }
  261. })
  262. test('a failed cleanup is visible at the entry and blocks another live request until cleanup succeeds', async () => {
  263. let cleanupFails = true
  264. const page = await mountJourney({ stop: () => cleanupFails
  265. ? envelope({ category: 'CLEANUP_UNCONFIRMED' }, 503)
  266. : envelope({ sessionId: 'session-a', status: 'STOPPED' }) })
  267. try {
  268. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  269. page.host.querySelector('[data-video-open]').click(); await settle()
  270. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  271. const entry = page.host.querySelector('[data-video-entry]')
  272. assert.ok(entry.textContent.includes('会话释放未确认'))
  273. assert.equal(entry.querySelector('[data-video-open]').disabled, true)
  274. assert.equal(page.requests.filter((request) => request.path.endsWith('/video/live')).length, 1)
  275. cleanupFails = false
  276. Array.from(entry.querySelectorAll('button')).find((button) => button.textContent === '重试清理').click(); await settle()
  277. assert.equal(page.host.querySelector('[data-video-open]').disabled, false)
  278. } finally { cleanupFails = false; await page.dispose() }
  279. })