journey.mjs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. import assert from 'node:assert/strict'
  2. import test from 'node:test'
  3. import { createApp, h, nextTick, shallowRef } 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 VideoPlayer from '../../src/modules/cockpit/components/VideoPlayer.vue'
  9. import { useDetailStore } from '../../src/modules/cockpit/stores/detailStore.js'
  10. import { useVideoStore } from '../../src/modules/cockpit/stores/videoStore.js'
  11. import { useEnhancementDevicesStore } from '../../src/modules/cockpit/stores/enhancementDevicesStore.js'
  12. const code = 'CAM/01 空格'
  13. const device = { deviceCode: code, deviceName: '现场摄像机A', typeCode: '20', bound: true,
  14. capabilities: { live: true, records: false, playback: false, playbackControl: false, ptz: false, ptzStopGuaranteed: false }, unavailableReason: null }
  15. const envelope = (data, status = 200) => Response.json({ code: status, msg: status === 200 ? '操作成功' : '失败', data }, { status })
  16. const aggregate = { deviceCode: code, aggregateState: 'READY',
  17. archive: { state: 'SUCCESS', data: { deviceCode: code, deviceName: '现场摄像机A', deviceType: '20' } },
  18. metrics: { state: 'EMPTY', data: null }, warnings: { state: 'EMPTY', data: [] }, alarms: { state: 'EMPTY', data: [] },
  19. workOrders: { state: 'EMPTY', data: null }, timelines: { state: 'EMPTY', data: null }, latestImage: { state: 'EMPTY', data: null } }
  20. async function settle() { for (let i = 0; i < 4; i++) { await new Promise(setImmediate); await nextTick() } }
  21. async function mountJourney(overrides = {}) {
  22. const requests = []
  23. const config = { dataSource: 'real', api: { baseUrl: 'http://fixture.invalid/api/cockpit/v1', token: 'must-not-send' } }
  24. const fetchImpl = async (url, options = {}) => {
  25. const path = new URL(url).pathname
  26. const body = options.body ? JSON.parse(options.body) : null
  27. requests.push({ url: new URL(url), path, options, body })
  28. assert.equal(options.headers?.Authorization, undefined)
  29. if (path.endsWith('/detail-aggregate')) return envelope(overrides.aggregate || aggregate)
  30. if (path.endsWith('/collection-records')) return overrides.records?.() || envelope({ deviceCode: code, state: 'EMPTY', recordView: { columns: [], rows: [] } })
  31. if (path.endsWith('/video/device')) {
  32. assert.equal(new URL(url).searchParams.get('deviceCode'), code)
  33. return envelope(overrides.device || device)
  34. }
  35. if (path.endsWith('/video/sessions/prepare')) {
  36. assert.deepEqual(body, { deviceCode: code })
  37. return overrides.prepare?.() || new Response(JSON.stringify({ code: 200, data: {
  38. deviceCode: code, deviceName: device.deviceName, sessionId: 'session-a', sessionToken: 'owner-a', mode: 'LIVE', status: 'PREPARED',
  39. } }), { status: 201, headers: { 'Content-Type': 'application/json' } })
  40. }
  41. if (path.endsWith('/video/sessions/session-a/live')) {
  42. assert.deepEqual(body, { sessionToken: 'owner-a' })
  43. return overrides.live?.() || envelope(livePayload({ native: true, url: 'https://media.invalid/live.mp4' }))
  44. }
  45. if (path.endsWith('/status')) return overrides.status?.() || envelope({ sessionId: 'session-a', deviceCode: code, mode: 'LIVE', status: 'STOPPED' })
  46. if (path.endsWith('/heartbeat')) return overrides.heartbeat?.() || envelope({ sessionId: 'session-a', status: 'ACTIVE' })
  47. if (path.endsWith('/stop')) return overrides.stop?.() || envelope({ sessionId: 'session-a', status: 'STOPPED' })
  48. throw new Error('Unexpected fixture request: ' + path)
  49. }
  50. const pinia = createPinia(); setActivePinia(pinia)
  51. const detail = useDetailStore(); detail.configure({ config, fetchImpl })
  52. const video = useVideoStore(); video.configure({ config, fetchImpl, ...(overrides.sessionOptions || {}) })
  53. await detail.openDevice(code)
  54. const host = document.createElement('main'); document.body.appendChild(host)
  55. const app = createApp({ render: () => h('div', [overrides.entryOnly
  56. ? h(VideoMonitorEntry, { deviceCode: code, monitorSource: overrides.monitorSource || 'enhancement' })
  57. : h(PointDetailCard), h(VideoMonitorPanel)]) })
  58. app.use(pinia).mount(host)
  59. await settle()
  60. return { host, requests, video, detail, config, fetchImpl, async dispose() { app.unmount(); await video.close(); host.remove() } }
  61. }
  62. const livePayload = (media) => ({ deviceCode: code, deviceName: device.deviceName, sessionId: 'session-a', mode: 'LIVE', status: 'ACTIVE', media })
  63. async function openMonitor(page) {
  64. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  65. page.host.querySelector('[data-video-open]').click(); await settle()
  66. return document.querySelector('[data-video-monitor]')
  67. }
  68. test('closing the originating main detail releases video even if another host retains the same device code', async () => {
  69. const page = await mountJourney()
  70. try {
  71. await useEnhancementDevicesStore().open({ code, name: device.deviceName }, {
  72. fetchDetail: async () => ({ state: 'success', data: aggregate }),
  73. })
  74. await openMonitor(page)
  75. page.host.querySelector('[data-detail-close]').click(); await settle()
  76. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false)
  77. const stops = page.requests.filter((request) => request.path.endsWith('/stop'))
  78. assert.equal(stops.length, 1)
  79. assert.deepEqual(stops[0].body, { sessionToken: 'owner-a' })
  80. } finally { await page.dispose() }
  81. })
  82. test('selection invalidation and same-code restoration in one turn still ends the old viewing session', async () => {
  83. const page = await mountJourney()
  84. try {
  85. await openMonitor(page)
  86. page.detail.closeDetail()
  87. const restored = page.detail.openDevice(code)
  88. await restored; await settle()
  89. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false, 'restoring selection must not resurrect its previous viewer')
  90. assert.equal(page.requests.filter((request) => request.path.endsWith('/prepare')).length, 1)
  91. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  92. } finally { await page.dispose() }
  93. })
  94. test('the underground host owns its own viewing source and a main-detail close does not stop it', async () => {
  95. const page = await mountJourney({ entryOnly: true })
  96. try {
  97. await useEnhancementDevicesStore().open({ code, name: device.deviceName }, {
  98. fetchDetail: async () => ({ state: 'success', data: aggregate }),
  99. })
  100. page.host.querySelector('[data-video-open]').click(); await settle()
  101. assert.equal(page.video.state.ownerSource, 'enhancement')
  102. assert.ok(document.querySelector('[data-video-monitor]'))
  103. await page.detail.closeDetail(); await settle()
  104. assert.ok(document.querySelector('[data-video-monitor]'), 'main detail close must not stop the enhancement-owned video')
  105. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 0)
  106. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  107. assert.equal(Boolean(document.querySelector('[data-video-monitor]')), false)
  108. } finally { await page.dispose() }
  109. })
  110. test('a successful HTTP envelope for another session cannot confirm cleanup of the current viewer', async () => {
  111. let wrong = true
  112. const page = await mountJourney({ stop: () => envelope({ sessionId: wrong ? 'someone-else' : 'session-a', status: 'STOPPED' }) })
  113. try {
  114. await openMonitor(page)
  115. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  116. assert.ok(page.host.querySelector('[data-video-entry]').textContent.includes('会话释放未确认'))
  117. assert.equal(page.host.querySelector('[data-video-open]').disabled, true)
  118. } finally { wrong = false; await page.dispose() }
  119. })
  120. class TestClock {
  121. now = 0; next = 1; jobs = new Map()
  122. setTimeout(fn, delay) { const id = this.next++; this.jobs.set(id, { fn, at: this.now + delay }); return id }
  123. clearTimeout(id) { this.jobs.delete(id) }
  124. setInterval(fn, delay) { const id = this.setTimeout(fn, delay); this.jobs.get(id).interval = delay; return id }
  125. clearInterval(id) { this.clearTimeout(id) }
  126. async advance(duration) {
  127. const end = this.now + duration
  128. while (true) {
  129. const due = Array.from(this.jobs).filter(([, job]) => job.at <= end).sort((a, b) => a[1].at - b[1].at)[0]
  130. if (!due) break
  131. const [id, job] = due; this.now = job.at
  132. if (job.interval) job.at += job.interval; else this.jobs.delete(id)
  133. job.fn(); await settle()
  134. }
  135. this.now = end; await settle()
  136. }
  137. }
  138. test('watching heartbeat preserves its session ownership and failure releases the viewer', async () => {
  139. const clock = new TestClock(); let wrong = false
  140. const page = await mountJourney({ sessionOptions: { timers: clock }, heartbeat: () => envelope({ sessionId: wrong ? 'other' : 'session-a', status: 'ACTIVE' }) })
  141. try {
  142. const dialog = await openMonitor(page)
  143. dialog.querySelector('video').dispatchEvent(new Event('playing')); await settle()
  144. await clock.advance(30000)
  145. const beat = page.requests.find((request) => request.path.endsWith('/heartbeat'))
  146. assert.deepEqual(beat.body, { sessionToken: 'owner-a' })
  147. wrong = true
  148. await clock.advance(30000)
  149. // Ticket 04: a dropped session is temporary, so the bounded retry runs before the terminal reason.
  150. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  151. await clock.advance(400000)
  152. // After the budget is spent the panel must show a terminal failure and drop the media.
  153. assert.ok(dialog.textContent.includes('播放失败') || dialog.textContent.includes('播放会话已断开'), dialog.textContent)
  154. assert.equal(dialog.querySelector('video'), null)
  155. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  156. } finally { await page.dispose() }
  157. })
  158. test('Escape closes the global modal and releases its viewing resource', async () => {
  159. const page = await mountJourney()
  160. try {
  161. await openMonitor(page)
  162. const key = new Event('keydown', { bubbles: true, cancelable: true }); key.key = 'Escape'
  163. document.dispatchEvent(key); await settle()
  164. assert.equal(document.querySelector('[data-video-monitor]'), null)
  165. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  166. } finally { await page.dispose() }
  167. })
  168. test('collection-record failure does not remove the latest-tab monitoring entry', async () => {
  169. const page = await mountJourney({ records: () => envelope({}, 503) })
  170. try {
  171. const dialog = await openMonitor(page)
  172. assert.ok(dialog.querySelector('video'))
  173. assert.ok(page.host.querySelector('[data-video-metrics-note]'))
  174. assert.equal(page.host.querySelector('[data-metrics-failed]'), null, '摄像机不渲染采集记录失败提示')
  175. } finally { await page.dispose() }
  176. })
  177. test('摄像机指标不可用用监控入口承接,传感器不可用仍如实提示', async () => {
  178. for (const camera of [true, false]) {
  179. const archive = { ...aggregate, archive: { state: 'SUCCESS', data: { deviceCode: code, deviceName: camera ? '摄像机' : '压力传感器', deviceType: camera ? '20' : '15' } } }
  180. const page = await mountJourney({ aggregate: archive,
  181. device: camera ? device : { ...device, typeCode: '15', bound: false, capabilities: { live: false } },
  182. records: () => envelope({ deviceCode: code, state: 'UNAVAILABLE', recordView: { columns: [], rows: [] } }) })
  183. try {
  184. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  185. if (camera) {
  186. assert.ok(page.host.querySelector('[data-video-metrics-note]'))
  187. assert.equal(page.host.querySelector('[data-metrics-unavailable]'), null)
  188. assert.equal(page.host.querySelector('[data-video-open]').getAttribute('aria-label'), '监控面板入口')
  189. } else {
  190. assert.ok(page.host.querySelector('[data-metrics-unavailable]'))
  191. assert.equal(page.host.querySelector('[data-video-metrics-note]'), null)
  192. assert.equal(page.host.querySelector('[data-video-open]'), null)
  193. }
  194. } finally { await page.dispose() }
  195. }
  196. })
  197. test('non-camera has no monitor button; unbound and unknown live capability stay disabled without starting', async () => {
  198. for (const camera of [
  199. { ...device, typeCode: '15', bound: false, capabilities: { live: false } },
  200. { ...device, bound: false, capabilities: { live: false }, unavailableReason: '尚未绑定视频' },
  201. { ...device, bound: true, capabilities: { live: false }, unavailableReason: '实时能力未确认' },
  202. ]) {
  203. const page = await mountJourney({ device: camera })
  204. try {
  205. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  206. const button = page.host.querySelector('[data-video-open]')
  207. if (camera.typeCode !== '20') assert.equal(button, null)
  208. else { assert.equal(button.disabled, true); assert.ok(page.host.textContent.includes(camera.unavailableReason)) }
  209. assert.equal(page.requests.some((request) => request.path.endsWith('/live')), false)
  210. } finally { await page.dispose() }
  211. }
  212. })
  213. test('a WebRTC-only media payload is now unsupported: it is refused, released and never presents playing', async () => {
  214. // After tech-stack unification the cockpit plays FLV only; a WebRTC-only response has no playable URL.
  215. const clock = new TestClock()
  216. // Make WebRTC constructible so a fallback would be caught here, not just fail for lack of the API.
  217. const rtc = []
  218. globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
  219. try {
  220. 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' })) })
  221. try {
  222. const dialog = await openMonitor(page)
  223. assert.equal(dialog.querySelector('video'), null)
  224. // Unsupported media is a capability outcome, never a temporary outage: no retry is spent.
  225. assert.ok(dialog.textContent.includes('不支持'), dialog.textContent)
  226. assert.equal(dialog.textContent.includes('正在播放'), false)
  227. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1, 'an unsupported payload must not be retried')
  228. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  229. assert.equal(rtc.length, 0, 'a WebRTC-only payload must be refused, never attempted')
  230. assert.equal(page.video.state.media, null)
  231. } finally { await page.dispose() }
  232. } finally { delete globalThis.RTCPeerConnection }
  233. })
  234. test('HTTP 200 HTML live response is a visible failure and releases the prepared viewing resource', async () => {
  235. const page = await mountJourney({ live: () => new Response('<html>wrong route</html>', { headers: { 'Content-Type': 'text/html' } }) })
  236. try {
  237. const dialog = await openMonitor(page)
  238. assert.equal(dialog.querySelector('video'), null)
  239. assert.ok(dialog.textContent.includes('无效数据'))
  240. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  241. assert.equal(page.requests.filter((request) => request.path.endsWith('/prepare')).length, 1)
  242. } finally { await page.dispose() }
  243. })
  244. test('a live start exceeding 35 seconds exits visibly and releases a later owned response without opening video', async () => {
  245. const clock = new TestClock(); let respond
  246. const delayed = new Promise((resolve) => { respond = resolve })
  247. const page = await mountJourney({ live: () => delayed, sessionOptions: { timers: clock } })
  248. try {
  249. const dialog = await openMonitor(page)
  250. await clock.advance(35000)
  251. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  252. await clock.advance(400000)
  253. assert.ok(dialog.textContent.includes('视频建立超时'), dialog.textContent)
  254. assert.equal(dialog.querySelector('video'), null)
  255. respond(envelope(livePayload({ native: true, url: 'https://media.invalid/live.mp4' })))
  256. await settle()
  257. assert.equal(dialog.querySelector('video'), null)
  258. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  259. assert.ok(page.requests.filter((request) => request.path.endsWith('/live')).length >= 1)
  260. } finally { await page.dispose() }
  261. })
  262. test('player readiness has a bound independent of HTTP success and cleans its owned session', async () => {
  263. const clock = new TestClock()
  264. const page = await mountJourney({ sessionOptions: { timers: clock } })
  265. try {
  266. const dialog = await openMonitor(page)
  267. assert.ok(dialog.textContent.includes('等待视频画面'))
  268. await clock.advance(20000)
  269. // Ticket 04: an unreachable player is a temporary failure, so the retry state shows first.
  270. assert.ok(dialog.textContent.includes('自动重连'), dialog.textContent)
  271. assert.equal(dialog.querySelector('video'), null)
  272. // Exhausting the bounded budget is what finally surfaces the terminal reason.
  273. await clock.advance(400000)
  274. assert.ok(dialog.textContent.includes('播放器就绪超时'), dialog.textContent)
  275. assert.equal(dialog.querySelector('video'), null)
  276. assert.ok(page.requests.filter((request) => request.path.endsWith('/stop')).length >= 1)
  277. } finally { await page.dispose() }
  278. })
  279. test('hiding the page closes video and does not reopen it when visible again', async () => {
  280. const page = await mountJourney()
  281. try {
  282. await openMonitor(page)
  283. Object.defineProperty(document, 'hidden', { configurable: true, value: true })
  284. document.dispatchEvent(new Event('visibilitychange')); await settle()
  285. assert.equal(document.querySelector('[data-video-monitor]'), null)
  286. Object.defineProperty(document, 'hidden', { configurable: true, value: false })
  287. document.dispatchEvent(new Event('visibilitychange')); await settle()
  288. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1)
  289. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  290. } finally { delete document.hidden; await page.dispose() }
  291. })
  292. test('latest-tab entry plays the returned FLV through Jessibuca and only Jessibuca play establishes visible playback', async () => {
  293. // Tech-stack unification: the cockpit now decodes FLV with Jessibuca, not WebRTC signalling.
  294. const players = []
  295. const rtc = []
  296. globalThis.Jessibuca = class {
  297. constructor(options) { this.options = options; this.handlers = new Map(); players.push(this) }
  298. on(type, fn) { this.handlers.set(type, fn) }
  299. emit(type) { this.handlers.get(type)?.() }
  300. async play(url) { this.url = url; this.emit('play') }
  301. mute() {}
  302. setVolume() {}
  303. audioResume() {}
  304. destroy() { this.destroyed = true }
  305. }
  306. globalThis.RTCPeerConnection = class { constructor(...args) { rtc.push(args) } }
  307. try {
  308. // A competing WebRTC url proves the FLV field wins, not that WebRTC is merely unavailable.
  309. const page = await mountJourney({
  310. live: () => envelope(livePayload({ native: false,
  311. url: 'http://media.invalid/index/api/webrtc?app=rtp&stream=cam&type=play',
  312. flv: 'https://media.invalid/live.flv' })),
  313. })
  314. try {
  315. const dialog = await openMonitor(page)
  316. // The FLV stream is handed to Jessibuca, not turned into a native <video src>.
  317. assert.equal(players.length, 1)
  318. assert.equal(players[0].url, 'https://media.invalid/live.flv', 'must prefer the flv field over the competing url')
  319. assert.equal(page.video.state.media.kind, 'flv', 'media classification must be flv')
  320. assert.equal(rtc.length, 0, 'FLV playback must never construct RTCPeerConnection')
  321. assert.equal(dialog.querySelector('video'), null)
  322. assert.ok(dialog.textContent.includes('正在播放'), 'a Jessibuca play event establishes visible playback')
  323. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  324. assert.equal(players[0].destroyed, true)
  325. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  326. } finally { await page.dispose() }
  327. } finally { delete globalThis.Jessibuca; delete globalThis.RTCPeerConnection }
  328. })
  329. test('FLV调音和全屏只改变呈现,不重连不发送设备命令', async () => {
  330. const players = []
  331. globalThis.Jessibuca = class {
  332. constructor(options) { this.options = options; this.handlers = new Map(); this.volumes = []; this.mutes = 0; this.resumes = 0; players.push(this) }
  333. on(type, fn) { this.handlers.set(type, fn) }
  334. async play(url) { this.url = url; this.handlers.get('play')?.() }
  335. mute() { this.mutes++ }
  336. setVolume(value) { this.volumes.push(value) }
  337. audioResume() { this.resumes++ }
  338. destroy() { this.destroyed = true }
  339. }
  340. let page
  341. try {
  342. page = await mountJourney({ live: () => envelope(livePayload({ flv: 'https://media.invalid/live.flv', native: false })) })
  343. const dialog = await openMonitor(page)
  344. assert.equal(players.length, 1)
  345. assert.equal(players[0].options.hasAudio, true, '静音不能关闭音频解码')
  346. assert.ok(players[0].mutes > 0, '默认静音')
  347. const before = page.requests.length
  348. dialog.querySelector('[data-video-mute]').click(); await settle()
  349. assert.equal(players[0].volumes.at(-1), 0.5)
  350. assert.ok(players[0].resumes > 0)
  351. const slider = dialog.querySelector('[data-video-volume]')
  352. slider.value = '25'; slider.dispatchEvent(new Event('input')); await settle()
  353. assert.equal(players[0].volumes.at(-1), 0.25)
  354. const surface = dialog.querySelector('[data-video-surface]')
  355. let entered = null
  356. surface.requestFullscreen = async function () { entered = this }
  357. dialog.querySelector('[data-video-fullscreen]').click(); await settle()
  358. assert.equal(entered, surface, '全屏目标包含画面与工具条,非video选择器')
  359. const full = dialog.querySelector('[data-video-fullscreen]')
  360. const first = surface.querySelector('button')
  361. const activeDescriptor = Object.getOwnPropertyDescriptor(document, 'activeElement')
  362. const fullscreenDescriptor = Object.getOwnPropertyDescriptor(document, 'fullscreenElement')
  363. let focused = null
  364. try {
  365. Object.defineProperty(document, 'fullscreenElement', { configurable: true, value: surface })
  366. Object.defineProperty(document, 'activeElement', { configurable: true, value: full })
  367. first.focus = () => { focused = first }
  368. const key = new Event('keydown', { bubbles: true, cancelable: true }); key.key = 'Tab'
  369. document.dispatchEvent(key)
  370. assert.equal(focused, first, '全屏焦点循环留在画面工具条内')
  371. } finally {
  372. if (activeDescriptor) Object.defineProperty(document, 'activeElement', activeDescriptor)
  373. else delete document.activeElement
  374. if (fullscreenDescriptor) Object.defineProperty(document, 'fullscreenElement', fullscreenDescriptor)
  375. else delete document.fullscreenElement
  376. }
  377. surface.requestFullscreen = async () => { throw new Error('全屏权限被拒绝') }
  378. dialog.querySelector('[data-video-fullscreen]').click(); await settle()
  379. assert.ok(dialog.querySelector('[data-video-presentation-error]').textContent.includes('全屏权限被拒绝'))
  380. assert.equal(page.requests.length, before)
  381. assert.equal(players.length, 1, '调音和全屏不重建播放器')
  382. assert.equal(page.video.state.phase, 'playing', '全屏失败不停止观看')
  383. } finally { await page?.dispose(); delete globalThis.Jessibuca }
  384. })
  385. test('旧解码器迟到回调与异步销毁不能破坏重新打开的画面', async () => {
  386. const players = []; let finishOldDestroy
  387. globalThis.Jessibuca = class {
  388. constructor(options) { this.options = options; this.handlers = new Map(); players.push(this) }
  389. on(type, fn) { this.handlers.set(type, fn) }
  390. async play() { this.options.container.appendChild(document.createElement('canvas')); this.handlers.get('play')?.() }
  391. mute() {}
  392. audioResume() {}
  393. setVolume() {}
  394. destroy() {
  395. if (this === players[0]) return new Promise(resolve => { finishOldDestroy = () => { this.options.container.innerHTML = ''; resolve() } })
  396. this.options.container.innerHTML = ''
  397. }
  398. }
  399. let page
  400. try {
  401. page = await mountJourney({ live: () => envelope(livePayload({ native: false, flv: 'https://media.invalid/live.flv' })) })
  402. let dialog = await openMonitor(page)
  403. const old = players[0]
  404. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  405. dialog = await openMonitor(page)
  406. assert.equal(players.length, 2)
  407. assert.notEqual(players[1].options.container, old.options.container)
  408. old.handlers.get('error')?.(); old.handlers.get('play')?.(); finishOldDestroy(); await settle()
  409. assert.ok(dialog.querySelector('[data-flv-decoder] canvas'))
  410. assert.equal(page.video.state.phase, 'playing')
  411. assert.equal(page.video.state.error, '')
  412. assert.equal(old.options.container.isConnected, false)
  413. } finally { finishOldDestroy?.(); await page?.dispose(); delete globalThis.Jessibuca }
  414. })
  415. test('播放器源由原生切到FLV会显式释放已脱离DOM的旧原生元素', async () => {
  416. const media = shallowRef({ kind: 'native', url: 'https://media.invalid/native.mp4' })
  417. const host = document.createElement('div'); document.body.appendChild(host)
  418. globalThis.Jessibuca = class { on() {} mute() {} audioResume() {} setVolume() {} async play() {} destroy() {} }
  419. const app = createApp({ render: () => h(VideoPlayer, { media: media.value }) })
  420. try {
  421. app.mount(host); await settle()
  422. const old = host.querySelector('video')
  423. assert.equal(old.getAttribute('src'), 'https://media.invalid/native.mp4')
  424. let paused = 0, unloaded = 0
  425. old.pause = () => { paused++ }; old.load = () => { unloaded++ }
  426. media.value = { kind: 'flv', url: 'ws://media.invalid/live.flv' }; await settle()
  427. assert.equal(old.isConnected, false)
  428. assert.equal(paused, 1)
  429. assert.equal(unloaded, 1)
  430. assert.equal(old.getAttribute('src'), null)
  431. assert.ok(host.querySelector('[data-flv-decoder]'))
  432. } finally { app.unmount(); host.remove(); delete globalThis.Jessibuca }
  433. })
  434. test('a native (non-FLV) direct URL is played by a <video> that actually carries its src', async () => {
  435. // Regression guard: the native branch must bind :src, otherwise MANUAL direct-URL devices never show.
  436. const page = await mountJourney({ live: () => envelope(livePayload({ native: true, url: 'https://media.invalid/direct.mp4' })) })
  437. try {
  438. const dialog = await openMonitor(page)
  439. const element = dialog.querySelector('video')
  440. assert.ok(element, 'native media must render a <video>')
  441. assert.equal(page.video.state.media.kind, 'native')
  442. assert.equal(element.getAttribute('src'), 'https://media.invalid/direct.mp4', 'mounted startup must not clear the native source')
  443. assert.equal(page.video.state.media.url, 'https://media.invalid/direct.mp4')
  444. assert.equal(dialog.querySelector('[data-flv-decoder]'), null, 'native media must not use the Jessibuca decoder')
  445. assert.equal(page.video.state.media.kind, 'native')
  446. element.dispatchEvent(new Event('playing')); await settle()
  447. assert.ok(dialog.textContent.includes('正在播放'))
  448. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  449. assert.equal(page.requests.filter((request) => request.path.endsWith('/stop')).length, 1)
  450. } finally { await page.dispose() }
  451. })
  452. test('device detail latest tab opens its own anonymous live video even with no collection records, then closes it', async () => {
  453. const page = await mountJourney()
  454. try {
  455. const latest = page.host.querySelector('[data-equipment-tab="metrics"]')
  456. assert.ok(latest, 'existing device-detail latest tab must be visible')
  457. latest.click(); await settle()
  458. const open = page.host.querySelector('[data-video-open]')
  459. assert.ok(open, 'the monitor entry must be inside the latest tab')
  460. assert.equal(open.disabled, false)
  461. open.click(); await settle()
  462. const dialog = document.querySelector('[role="dialog"][data-video-monitor]')
  463. assert.ok(dialog)
  464. assert.ok(dialog.textContent.includes('现场摄像机A'))
  465. assert.ok(dialog.textContent.includes(code))
  466. assert.equal(dialog.textContent.includes('owner-a'), false)
  467. dialog.querySelector('video').dispatchEvent(new Event('playing'))
  468. await settle()
  469. assert.ok(dialog.textContent.includes('正在播放'))
  470. dialog.querySelector('[aria-label="关闭监控"]').click(); await settle()
  471. assert.equal(document.querySelector('[data-video-monitor]'), null)
  472. const stops = page.requests.filter((request) => request.path.endsWith('/stop'))
  473. assert.equal(stops.length, 1)
  474. assert.deepEqual(stops[0].body, { sessionToken: 'owner-a' })
  475. } finally { await page.dispose() }
  476. })
  477. test('a failed cleanup is visible at the entry and blocks another live request until cleanup succeeds', async () => {
  478. let cleanupFails = true
  479. const page = await mountJourney({ stop: () => cleanupFails
  480. ? envelope({ category: 'CLEANUP_UNCONFIRMED' }, 503)
  481. : envelope({ sessionId: 'session-a', status: 'STOPPED' }) })
  482. try {
  483. page.host.querySelector('[data-equipment-tab="metrics"]').click(); await settle()
  484. page.host.querySelector('[data-video-open]').click(); await settle()
  485. document.querySelector('[aria-label="关闭监控"]').click(); await settle()
  486. const entry = page.host.querySelector('[data-video-entry]')
  487. assert.ok(entry.textContent.includes('会话释放未确认'))
  488. assert.equal(entry.querySelector('[data-video-open]').disabled, true)
  489. assert.equal(page.requests.filter((request) => request.path.endsWith('/live')).length, 1)
  490. cleanupFails = false
  491. Array.from(entry.querySelectorAll('button')).find((button) => button.textContent === '重试清理').click(); await settle()
  492. assert.equal(page.host.querySelector('[data-video-open]').disabled, false)
  493. } finally { cleanupFails = false; await page.dispose() }
  494. })