From 6943a18a9cae21798a312ca468faa75fd3e547c9 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:20:37 +0530 Subject: [PATCH 01/10] fix: keep watch page restore state when stopPage runs twice refs #5792 --- tests/js/watch-stoppage-state.test.js | 113 ++++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 6 ++ 2 files changed, 119 insertions(+) create mode 100644 tests/js/watch-stoppage-state.test.js diff --git a/tests/js/watch-stoppage-state.test.js b/tests/js/watch-stoppage-state.test.js new file mode 100644 index 0000000000..e34e1acc7a --- /dev/null +++ b/tests/js/watch-stoppage-state.test.js @@ -0,0 +1,113 @@ +'use strict'; + +// stopPage() runs from the hidden-tab timer, 'freeze' and 'pagehide', so it can +// run twice for one hide. The second run found the stream already stopped and +// the cycle already paused, and overwrote prevStateStarted with 'stopped' and +// prevStateCycle with false, so startPage() restored neither. + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const src = fs.readFileSync( + path.join(__dirname, '../../web/skins/classic/views/js/watch.js'), 'utf8'); + +let passed = 0; +let failed = 0; +function test(name, fn) { + try { + fn(); + console.log(' ok ' + name); + passed++; + } catch (e) { + console.error(' FAIL ' + name); + console.error(' ' + (e.stack || e.message)); + failed++; + } +} + +function makeChainable() { + const proxy = new Proxy(function() {}, { + get: (target, prop) => { + if (prop === 'then') return undefined; + if (prop === 'val') return () => '10'; + if (prop === 'text') return () => ''; + return proxy; + }, + apply: () => proxy, + }); + return proxy; +} + +function loadWatch() { + const globals = { + $j: makeChainable(), + $: makeChainable(), + console: {log() {}, warn() {}, error() {}, debug() {}}, + document: { + getElementById: () => null, + querySelector: () => null, + querySelectorAll: () => [], + addEventListener: () => {}, + createElement: () => ({}), + }, + setInterval: () => 1, + clearInterval: () => {}, + setTimeout: () => 0, + clearTimeout: () => 0, + Object, Array, JSON, + monitorData: [{id: 1}, {id: 2}], + ZM_WEB_VIEWING_TIMEOUT: 0, + addEventListener: () => {}, + }; + const sandbox = new Proxy(globals, { + has: () => true, + get: (target, prop) => (prop === Symbol.unscopables ? undefined : target[prop]), + }); + globals.window = sandbox; + vm.createContext(sandbox); + vm.runInContext(src, sandbox, {filename: 'watch.js'}); + globals.whenAuthFresh = (cb) => cb(); + globals.monitorsSetScale = () => {}; + globals.onPlay = () => {}; + const ms = { + started: true, zmsState: null, element: {}, isActive: true, + currentChannelStream: 'default', starts: 0, + stop() { + this.started = false; + }, + start() { + this.starts++; + this.started = true; + }, + }; + globals.monitorStream = ms; + return {globals, ms}; +} + +console.log('watch.js stopPage/startPage'); + +test('a second stopPage keeps the state startPage restores', () => { + const {globals, ms} = loadWatch(); + globals.cycle = true; + globals.stopPage(); + globals.stopPage(); + globals.startPage(); + assert.strictEqual(ms.starts, 1, 'stream was not restarted'); + assert.strictEqual(globals.cycle, true, 'cycle was not resumed'); +}); + +test('stopPage after a restore stops again', () => { + const {globals, ms} = loadWatch(); + globals.stopPage(); + globals.startPage(); + assert.strictEqual(ms.starts, 1); + globals.stopPage(); + assert.strictEqual(ms.started, false); + globals.startPage(); + assert.strictEqual(ms.starts, 2); +}); + +console.log('\n' + passed + ' passed, ' + failed + ' failed'); +process.exit(failed ? 1 : 0); diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 61c438c06f..58e5c47f1c 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -1550,10 +1550,15 @@ window.addEventListener('pageshow', () => { }, 100); }); +var pageStopped = false; function stopPage() { // Avoid calling stopPage() twice, as stopPage() can be called asynchronously from different places. // For example, if 'freeze' is triggered earlier than 15 seconds after visibilityState === "hidden" TimerHideShow = clearTimeout(TimerHideShow); + // A second call would see the stream already stopped and the cycle already + // paused, and overwrite the state startPage() needs to restore. + if (pageStopped) return; + pageStopped = true; prevStateCycle = cycle; if (prevStateCycle) cycleStop(); if (monitorStream) { @@ -1576,6 +1581,7 @@ function stopPage() { function startPage() { // Always clear it because the return to visibility might happen before timeout TimerHideShow = clearTimeout(TimerHideShow); + pageStopped = false; // The stream src still carries the auth hash from before we were hidden. If // we were away long enough for it to expire, get a fresh one before starting // anything, otherwise zms 403s the reconnect (auth-helpers.js). From 06496ce62caa3723278314c2ad056767fcc295c8 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:23:01 +0530 Subject: [PATCH 02/10] test: add a shared watch.js sandbox for tests/js refs #5792 --- tests/js/watch-sandbox.js | 101 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 tests/js/watch-sandbox.js diff --git a/tests/js/watch-sandbox.js b/tests/js/watch-sandbox.js new file mode 100644 index 0000000000..865d75dffd --- /dev/null +++ b/tests/js/watch-sandbox.js @@ -0,0 +1,101 @@ +'use strict'; + +// Loads watch.js into a vm context for the tests. Unknown globals resolve to +// undefined; pass overrides for the ones a test cares about. + +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); + +const src = fs.readFileSync( + path.join(__dirname, '../../web/skins/classic/views/js/watch.js'), 'utf8'); + +function makeChainable() { + const proxy = new Proxy(function() {}, { + get: (target, prop) => { + if (prop === 'then') return undefined; + if (prop === 'val') return () => '10'; + if (prop === 'text') return () => ''; + return proxy; + }, + apply: () => proxy, + }); + return proxy; +} + +// A jQuery-like wrapper that keeps real handler lists, so tests can count how +// many times a handler would fire. +function makeHandlerSet() { + const handlers = {}; + const obj = { + handlers, + length: 1, + on(evt, fn) { + (handlers[evt] = handlers[evt] || []).push(fn); + return obj; + }, + off(evt, fn) { + if (!handlers[evt]) return obj; + handlers[evt] = fn ? handlers[evt].filter((f) => f !== fn) : []; + return obj; + }, + prop: () => obj, attr: () => obj, addClass: () => obj, removeClass: () => obj, + hasClass: () => false, hide: () => obj, show: () => obj, html: () => obj, + is: () => false, + }; + return obj; +} + +function loadWatch(overrides = {}) { + const globals = Object.assign({ + $j: makeChainable(), + $: makeChainable(), + console: {log() {}, warn() {}, error() {}, debug() {}}, + document: { + getElementById: () => null, + querySelector: () => null, + querySelectorAll: () => [], + addEventListener: () => {}, + createElement: () => ({}), + }, + setInterval: () => 1, + clearInterval: () => {}, + setTimeout: () => 0, + clearTimeout: () => 0, + Object, Array, JSON, Set, parseInt, parseFloat, String, Number, + monitorData: [{id: 1}, {id: 2}], + ZM_WEB_VIEWING_TIMEOUT: 0, + addEventListener: () => {}, + }, overrides); + const sandbox = new Proxy(globals, { + has: () => true, + get: (target, prop) => (prop === Symbol.unscopables ? undefined : target[prop]), + }); + globals.window = sandbox; + vm.createContext(sandbox); + vm.runInContext(src, sandbox, {filename: 'watch.js'}); + return globals; +} + +function runner() { + const state = {passed: 0, failed: 0}; + return { + test(name, fn) { + try { + fn(); + console.log(' ok ' + name); + state.passed++; + } catch (e) { + console.error(' FAIL ' + name); + console.error(' ' + (e.stack || e.message)); + state.failed++; + } + }, + done() { + console.log('\n' + state.passed + ' passed, ' + state.failed + ' failed'); + process.exit(state.failed ? 1 : 0); + }, + }; +} + +module.exports = {loadWatch, makeChainable, makeHandlerSet, runner}; From 7d198fa252de2689a7e89cc4a17952065976bd4e Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:23:38 +0530 Subject: [PATCH 03/10] fix: bind the watch alarm, settings and edit buttons once across monitor switches refs #5792 --- tests/js/watch-switch-handlers.test.js | 58 ++++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 7 +++- 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 tests/js/watch-switch-handlers.test.js diff --git a/tests/js/watch-switch-handlers.test.js b/tests/js/watch-switch-handlers.test.js new file mode 100644 index 0000000000..6b5b271e42 --- /dev/null +++ b/tests/js/watch-switch-handlers.test.js @@ -0,0 +1,58 @@ +'use strict'; + +// streamStart() runs for every monitor switch, but the alarm buttons live in +// the page header and are not replaced, so each switch added another click +// handler and one click sent the command once per switch. + +const assert = require('assert'); +const {loadWatch, makeHandlerSet, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +function setup() { + const g = loadWatch(); + g.enableAlmBtn = makeHandlerSet(); + g.forceAlmBtn = makeHandlerSet(); + g.analyseBtn = makeHandlerSet(); + g.canEdit = {Monitors: true}; + g.MonitorStream = function() { + this.setButton = () => {}; + this.setup_onclick = this.setup_onmove = this.setup_onpause = () => {}; + this.setup_onplay = this.setup_onalarm = this.manageAvailablePlayers = () => {}; + this.setBottomElement = () => {}; + }; + g.getCookie = () => null; + g.setChannelStream = g.streamCmdPlay = g.manageStreamQualityVisibility = () => {}; + g.panZoomEnabled = true; + g.monitorData = [{id: 1}, {id: 2}]; + g.monIdx = 0; + return g; +} + +console.log('watch.js handlers across monitor switches'); + +test('alarm buttons keep a single click handler after repeated streamStart', () => { + const g = setup(); + g.streamStart(); + g.streamStart(); + g.streamStart(); + assert.strictEqual(g.enableAlmBtn.handlers.click.length, 1); + assert.strictEqual(g.forceAlmBtn.handlers.click.length, 1); +}); + +test('settings button keeps a single click handler after repeated streamPrepareStart', () => { + const g = setup(); + g.settingsBtn = makeHandlerSet(); + const editBtn = makeHandlerSet(); + g.$j = (sel) => (sel === '#editBtn' ? editBtn : g.settingsBtn); + g.bindButton = (sel, action, data, fn) => g.$j(sel).on(action, fn); + g.getSettingsModal = () => {}; + g.canView = {Control: true, Events: false}; + g.history = {length: 2}; + g.currentMonitor = {monitorType: 'Local'}; + g.streamPrepareStart(g.currentMonitor); + g.streamPrepareStart(g.currentMonitor); + assert.strictEqual(g.settingsBtn.handlers.click.length, 1); + assert.strictEqual(editBtn.handlers.click.length, 1); +}); + +done(); diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 58e5c47f1c..1a1a7c3772 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -798,6 +798,7 @@ function streamPrepareStart(monitor=null) { settingsBtn.prop('disabled', false); getSettingsModal(); // Manage the SETTINGS button + settingsBtn.off('click'); bindButton('#settingsBtn', 'click', null, function onSettingsClick(evt) { evt.preventDefault(); $j('#settingsModal').modal('show'); @@ -847,6 +848,7 @@ function streamPrepareStart(monitor=null) { } // Manage the generate Edit button + $j('#editBtn').off('click'); bindButton('#editBtn', 'click', null, function onEditClick(evt) { evt.preventDefault(); window.location.assign("?view=monitor&mid="+monitorId); @@ -917,8 +919,9 @@ function streamStart(monitor = null) { monitorStream.setButton('analyseBtn', analyseBtn); if (canEdit.Monitors) { // Will be enabled by streamStatus ajax - enableAlmBtn.on('click', cmdAlarm); - forceAlmBtn.on('click', cmdForce); + // streamStart() runs for every monitor switch and the buttons are not replaced + enableAlmBtn.off('click', cmdAlarm).on('click', cmdAlarm); + forceAlmBtn.off('click', cmdForce).on('click', cmdForce); } else { forceAlmBtn.prop('title', forceAlmBtn.prop('title') + ': disabled because cannot edit Monitors'); enableAlmBtn.prop('title', enableAlmBtn.prop('title') + ': disabled because cannot edit Monitors'); From 61e2e8c08efc02e7328710b00330951c2b15ae09 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:24:18 +0530 Subject: [PATCH 04/10] fix: keep the watch ResizeObserver on the current stream element refs #5792 --- tests/js/watch-observe-stream.test.js | 80 +++++++++++++++++++++++++++ web/js/MonitorStream.js | 8 +++ web/skins/classic/views/js/watch.js | 12 ++-- 3 files changed, 96 insertions(+), 4 deletions(-) create mode 100644 tests/js/watch-observe-stream.test.js diff --git a/tests/js/watch-observe-stream.test.js b/tests/js/watch-observe-stream.test.js new file mode 100644 index 0000000000..9b4da03b72 --- /dev/null +++ b/tests/js/watch-observe-stream.test.js @@ -0,0 +1,80 @@ +'use strict'; + +// The watch page's ResizeObserver was attached once to the stream element that +// existed at load. A monitor switch replaces the element's HTML and the go2rtc, +// rtsp2web and janus players replace the element itself, after which resizes +// were no longer noticed and the stream was not rescaled. + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const {loadWatch, makeChainable, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +console.log('watch.js ResizeObserver'); + +test('observeStreamElements observes whatever stream elements exist now', () => { + let els = [{id: 'liveStream1'}, {id: 'monitorStatus1'}]; + const g = loadWatch({ + document: { + getElementById: () => null, querySelector: () => null, + querySelectorAll: () => els, addEventListener: () => {}, + createElement: () => ({}), + }, + }); + const seen = []; + g.observer = {observe: (el) => seen.push(el.id)}; + g.observeStreamElements(); + els = [{id: 'liveStream2'}, {id: 'monitorStatus2'}]; + g.observeStreamElements(); + assert.deepStrictEqual(seen, + ['liveStream1', 'monitorStatus1', 'liveStream2', 'monitorStatus2']); +}); + +test('observeStreamElements does nothing before the observer exists', () => { + const g = loadWatch(); + g.observeStreamElements(); +}); + +test('MonitorStream tells the page when it replaces its element', () => { + const src = fs.readFileSync( + path.join(__dirname, '../../web/js/MonitorStream.js'), 'utf8'); + const el = {nodeName: 'IMG', src: '', setAttribute() {}, getAttribute: () => null}; + let calls = 0; + const globals = { + Object, Math, Array, JSON, Set, Map, Date, parseInt, String, Number, + $j: makeChainable(), $: makeChainable(), + console: {log() {}, warn() {}, error() {}, debug() {}}, + currentView: 'watch', getCookie: () => 'true', + replaceDOMElement: () => el, generateUUID: () => 'u', + observeStreamElements: () => calls++, + zmAuth: {hash: '', applyTo: (u) => u, appendTo: (u) => u}, + document: {getElementById: () => null, createElement: () => ({})}, + setInterval: () => 1, clearInterval() {}, setTimeout: () => 0, clearTimeout() {}, + statusRefreshTimeout: 1000, + manageEventListener: {addEventListener: () => 1, removeEventListener: () => null}, + hideAudioMotion() {}, + streamSessionActive: () => true, + jQuery: {ajaxQueue: () => ({})}, + }; + const sandbox = new Proxy(globals, { + has: () => true, + get: (target, prop) => (prop === Symbol.unscopables ? undefined : target[prop]), + }); + globals.window = sandbox; + vm.createContext(sandbox); + vm.runInContext(src, sandbox, {filename: 'MonitorStream.js'}); + const m = new globals.MonitorStream({ + id: 5, name: 't', connKey: '1', url: 'i', url_to_zms: '/zms?x=1&mode=single', + width: 640, height: 480, + }); + m.getElement = () => el; + m.destroyVolumeSlider = () => {}; + m.updateStreamInfo = () => {}; + m.streamListenerBind = () => 1; + m.select_zms(); + assert.strictEqual(calls, 1); +}); + +done(); diff --git a/web/js/MonitorStream.js b/web/js/MonitorStream.js index 2ef90573a0..2caac18fa8 100644 --- a/web/js/MonitorStream.js +++ b/web/js/MonitorStream.js @@ -320,6 +320,10 @@ function MonitorStream(monitorData) { } return this.element; }; + // Lets a page that watches the stream element for resizes (watch) follow a replaced one + this.observeElement = function() { + if (typeof observeStreamElements === 'function') observeStreamElements(); + }; this.getFrame = function() { if (this.frame) return this.frame; this.frame = document.getElementById('imageFeed'+this.id); @@ -1937,6 +1941,7 @@ function MonitorStream(monitorData) { const url = go2rtcApiUrl(ZM_GO2RTC_PATH); const stream = this.element = replaceDOMElement(this.getElement(), 'video-stream'); + this.observeElement(); stream.srcObject = null; stream.background = true; // We do not use the document hiding/showing analysis from "video-rtc.js", because we have our own analysis //stream.muted = this.muted; @@ -1991,6 +1996,7 @@ function MonitorStream(monitorData) { if (ZM_RTSP2WEB_PATH) { this.playbackSessionId = generateUUID(); const stream = this.element = replaceDOMElement(this.getElement(), 'video'); + this.observeElement(); stream.srcObject = null; stream.setAttribute("autoplay", ""); stream.setAttribute("muted", this.muted); @@ -2127,6 +2133,7 @@ function MonitorStream(monitorData) { this.playbackSessionId = generateUUID(); let server; const stream = this.element = replaceDOMElement(this.getElement(), 'video'); + this.observeElement(); stream.srcObject = null; stream.setAttribute("autoplay", ""); stream.setAttribute("muted", this.muted); @@ -2183,6 +2190,7 @@ function MonitorStream(monitorData) { this.playbackSessionId = generateUUID(); const playbackSessionId = this.playbackSessionId; const stream = this.element = replaceDOMElement(this.getElement(), 'img'); + this.observeElement(); stream.srcObject = null; if (!stream) return; diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 1a1a7c3772..4f45c8e316 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -981,6 +981,7 @@ function streamReStart(oldId, newId) { applyMonitorControllable(); //manageChannelStream(); streamPrepareStart(currentMonitor); + observeStreamElements(); // IgorA100 ToDo: This isn't a duplicate initialization. We initialize different objects (in the first case, ".zoompan" is the default, in the second, ".imageFeed"), // but PanZoom wasn't fully implemented in panzoom.js for the second ".imageFeed" initialization line. zmPanZoom.init(); @@ -1061,6 +1062,12 @@ function applyMonitorControllable() { changeObjectClass(); } +// Registering an observer on the current stream and status elements; observing one twice is a no-op +function observeStreamElements() { + if (!observer) return; + document.querySelectorAll('[id ^= "liveStream"], .monitorStatus').forEach((el) => observer.observe(el)); +} + function initPage() { // +++ Support of old ZoomPan algorithm var useOldZoomPan = getCookie('zmUseOldZoomPan'); @@ -1182,10 +1189,7 @@ function initPage() { updateScale = true; }); - // Registering an observer on an element - $j('[id ^= "liveStream"], .monitorStatus').each(function() { - observer.observe(this); - }); + observeStreamElements(); // Event listener for double click //var elStream = document.querySelectorAll('[id ^= "liveStream"], [id ^= "evtStream"]'); From 22c3008ed37580c86662465635d70a624ac78e12 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:24:47 +0530 Subject: [PATCH 05/10] fix: track the cycle state per idle timeout in the watch modal handler refs #5792 --- tests/js/watch-idle-cycle.test.js | 99 +++++++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 7 +- 2 files changed, 104 insertions(+), 2 deletions(-) create mode 100644 tests/js/watch-idle-cycle.test.js diff --git a/tests/js/watch-idle-cycle.test.js b/tests/js/watch-idle-cycle.test.js new file mode 100644 index 0000000000..2ce9adcd0d --- /dev/null +++ b/tests/js/watch-idle-cycle.test.js @@ -0,0 +1,99 @@ +'use strict'; + +// The "are you still watching" modal is built once and its hidden handler was +// created with the cycle state of the first idle timeout. Later timeouts reused +// that stale value, so the cycle was resumed or left paused wrongly. + +const assert = require('assert'); +const {loadWatch, makeChainable, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +function setup() { + const chain = makeChainable(); + const timeouts = []; + const modal = { + length: 1, handlers: {}, + on(evt, fn) { + this.handlers[evt] = fn; + return this; + }, + modal() {}, + }; + let modalBuilt = false; + const doc = { + getElementById: (id) => (id === 'use-old-zoom-pan' ? {} : null), + referrer: '', querySelector: () => null, querySelectorAll: () => [], + addEventListener() {}, createElement: () => ({}), + }; + const $j = Object.assign((sel) => { + if (sel === '#AYSWModal') return modalBuilt ? modal : {length: 0}; + return chain; + }, { + getJSON: () => { + const p = {done: (fn) => { + fn({html: ''}); return p; + }, fail: () => p}; + return p; + }, + }); + const g = loadWatch({ + $j, document: doc, ZM_WEB_VIEWING_TIMEOUT: 5, + setTimeout: (fn) => timeouts.push(fn), + monitorData: [{id: 1}, {id: 2}], + ResizeObserver: function() { + this.observe = () => {}; + }, + }); + g.getCookie = () => null; + g.zmAuth = {hash: ''}; + g.lightStatusReq = g.indicatorLightStatusReq = () => {}; + g.zmPanZoom = {init() {}}; + g.bindButton = () => {}; + g.changeObjectClass = g.applyMonitorControllable = g.streamPrepareStart = () => {}; + g.insertModalHtml = () => { + modalBuilt = true; + return modal; + }; + g.streamCmdStop = g.streamCmdPlay = () => {}; + g.monitorId = 1; + g.cycleStarts = 0; + g.cycleStart = () => { + g.cycleStarts++; + }; + g.cyclePause = () => { + g.cycle = false; + }; + g.cycle = false; + g.panZoomEnabled = true; + return {g, timeouts, modal}; +} + +console.log('watch.js idle timeout and the cycle'); + +test('each idle timeout resumes the cycle only if it was running then', () => { + const {g, timeouts, modal} = setup(); + g.initPage(); + + // First idle timeout: not cycling. + timeouts[timeouts.length - 1](); + modal.handlers['hidden.bs.modal'](); + assert.strictEqual(g.cycleStarts, 0); + + // The user starts cycling, then goes idle again. + g.cycle = true; + timeouts[timeouts.length - 1](); + modal.handlers['hidden.bs.modal'](); + assert.strictEqual(g.cycleStarts, 1, 'cycle was not resumed'); +}); + +test('a timeout re-armed under the open modal keeps the original cycle state', () => { + const {g, timeouts, modal} = setup(); + g.initPage(); + g.cycle = true; + timeouts[timeouts.length - 1](); + timeouts[timeouts.length - 1](); + modal.handlers['hidden.bs.modal'](); + assert.strictEqual(g.cycleStarts, 1); +}); + +done(); diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 4f45c8e316..c9abc90737 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -9,6 +9,7 @@ var sidebarControls = $j('#ptzControls'); var wrapperMonitor = $j('#wrapperMonitor'); var filterQuery = '&filter[Query][terms][0][attr]=MonitorId&filter[Query][terms][0][op]=%3d&filter[Query][terms][0][val]='+monitorId; var analyse_frames = false; +var idleCycleWas = false; /* Cycle was running when the idle timeout fired */ var idleTimeoutTriggered = false; /* Timer ZM_WEB_VIEWING_TIMEOUT has been triggered */ var monitorStream = false; /* Stream is not started */ var currentMonitor; @@ -1131,9 +1132,11 @@ function initPage() { document.onkeydown = resetTimer; function stopPlayback() { + // Mouse movement under the open modal re-arms the timer, and that second + // run sees the cycle already paused. + if (!idleTimeoutTriggered) idleCycleWas = cycle; idleTimeoutTriggered = true; streamCmdStop(); - const cycle_was = cycle; cyclePause(); let ayswModal = $j('#AYSWModal'); if (!ayswModal.length) { @@ -1143,7 +1146,7 @@ function initPage() { ayswModal.on('hidden.bs.modal', function() { idleTimeoutTriggered = false; streamCmdPlay(true); - if (cycle_was) cycleStart(); + if (idleCycleWas) cycleStart(); }); ayswModal.modal('show'); }) From 98d23ebd3c0560d7ef932f493ab82538f4227637 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:24:59 +0530 Subject: [PATCH 06/10] fix: start the watch PTZ panel in the state watch.php rendered refs #5792 --- tests/js/watch-ptz-default.test.js | 68 +++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 9 ++-- web/skins/classic/views/js/watch.js.php | 2 + 3 files changed, 74 insertions(+), 5 deletions(-) create mode 100644 tests/js/watch-ptz-default.test.js diff --git a/tests/js/watch-ptz-default.test.js b/tests/js/watch-ptz-default.test.js new file mode 100644 index 0000000000..025f15a5a3 --- /dev/null +++ b/tests/js/watch-ptz-default.test.js @@ -0,0 +1,68 @@ +'use strict'; + +// watch.php shows the PTZ panel by default (no cookie) and honours ?ptzShow=, +// but applyMonitorControllable() decided from the cookie alone, so a first +// visit rendered the panel and then hid it. + +const assert = require('assert'); +const {loadWatch, makeHandlerSet, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +function setup(ptzVisible, controllable) { + const classes = new Set(['btn-secondary']); + const toggle = { + disabled: false, + classList: { + add: (c) => classes.add(c), remove: (c) => classes.delete(c), + }, + }; + const g = loadWatch({ + document: { + getElementById: (id) => (id === 'ptzToggle' ? toggle : null), + querySelector: () => null, querySelectorAll: () => [], + addEventListener() {}, createElement: () => ({}), + }, + }); + const calls = []; + g.sidebarControls = Object.assign(makeHandlerSet(), { + show: () => calls.push('show'), hide: () => calls.push('hide'), + html: () => calls.push('html'), + }); + g.getCookie = () => null; + g.changeObjectClass = () => {}; + g.lightStatusReq = g.indicatorLightStatusReq = () => {}; + g.ptzVisible = ptzVisible; + g.currentMonitor = {monitorControllable: controllable, ptzControls: ''}; + return {g, calls, classes}; +} + +console.log('watch.js PTZ panel initial state'); + +test('with no cookie the panel follows the server side default', () => { + const {g, calls, classes} = setup(true, true); + g.applyMonitorControllable(); + assert.ok(calls.includes('show')); + assert.ok(!calls.includes('hide')); + assert.ok(classes.has('btn-primary')); +}); + +test('a hidden state stays hidden', () => { + const {g, calls} = setup(false, true); + g.applyMonitorControllable(); + assert.ok(calls.includes('hide')); + assert.ok(!calls.includes('show')); +}); + +test('toggling keeps the state for the next monitor', () => { + const {g, calls} = setup(true, true); + g.sidebarControls.is = () => true; + g.setCookie = () => {}; + g.monitorsSetScale = () => {}; + g.ptzToggle(); + assert.strictEqual(g.ptzVisible, false); + calls.length = 0; + g.applyMonitorControllable(); + assert.ok(calls.includes('hide')); +}); + +done(); diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index c9abc90737..b5248ba321 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -1040,12 +1040,10 @@ function applyMonitorControllable() { return; } if (currentMonitor.monitorControllable) { - const ptzShow = getCookie('ptzShow'); - ptzToggle.classList.remove("disabled"); ptzToggle.disabled=false; sidebarControls.html(currentMonitor.ptzControls); - if (ptzShow) { + if (ptzVisible) { sidebarControls.show(); ptzToggle.classList.remove("btn-secondary"); ptzToggle.classList.add("btn-primary"); @@ -1352,11 +1350,12 @@ function ptzToggle(e) { const button = $j('#ptzToggle'); if (sidebarControls.is(":visible")) { sidebarControls.hide(); - setCookie('ptzShow', false); + ptzVisible = false; } else { sidebarControls.show(); - setCookie('ptzShow', true); + ptzVisible = true; } + setCookie('ptzShow', ptzVisible); button.toggleClass('btn-secondary'); button.toggleClass('btn-primary'); changeObjectClass(); diff --git a/web/skins/classic/views/js/watch.js.php b/web/skins/classic/views/js/watch.js.php index 086bda1686..cabfee5a3f 100644 --- a/web/skins/classic/views/js/watch.js.php +++ b/web/skins/classic/views/js/watch.js.php @@ -20,6 +20,8 @@ var LIST_THUMBS = ; var streamMode = ""; var showMode = ""; +// Whether the PTZ panel starts shown: the request, the cookie or, with neither, shown +var ptzVisible = ; var cycle = ; var player = ''; From 7f3f64be6e13ba300db57897e7d76bb095b07690 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:25:20 +0530 Subject: [PATCH 07/10] fix: show the zoom readout when zoomed and register the zoom-out button under its real key refs #5792 --- tests/js/watch-zoom-readout.test.js | 101 ++++++++++++++++++++++++++++ web/js/MonitorStream.js | 2 + web/skins/classic/views/js/watch.js | 3 +- 3 files changed, 105 insertions(+), 1 deletion(-) create mode 100644 tests/js/watch-zoom-readout.test.js diff --git a/tests/js/watch-zoom-readout.test.js b/tests/js/watch-zoom-readout.test.js new file mode 100644 index 0000000000..1970457a42 --- /dev/null +++ b/tests/js/watch-zoom-readout.test.js @@ -0,0 +1,101 @@ +'use strict'; + +// The zoom readout is rendered hidden and the status handler only ever added +// the hidden class, so "Zoom: Nx" never appeared. The zoom-out button state was +// keyed 'zoomOutBtn' in MonitorStream but registered as 'zoomOutButton' with a +// selector missing its '#', so it was never updated either. + +const assert = require('assert'); +const fs = require('fs'); +const path = require('path'); +const vm = require('vm'); +const {loadWatch, makeChainable, makeHandlerSet, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +const src = fs.readFileSync( + path.join(__dirname, '../../web/js/MonitorStream.js'), 'utf8'); + +function statusReply(zoom) { + const classes = {}; + const buttonStates = []; + const jq = (sel) => ({ + length: 1, text() { + return ''; + }, + removeClass(c) { + classes[sel] = 'removed ' + c; + }, + addClass(c) { + classes[sel] = 'added ' + c; + }, + hasClass: () => false, + }); + const globals = { + Object, Math, Array, JSON, Set, Map, Date, parseInt, String, Number, + $j: Object.assign(jq, {ajaxSetup() {}}), $: makeChainable(), + console: {log() {}, warn() {}, error() {}, debug() {}}, + currentView: 'watch', getCookie: () => 'true', + zmAuth: {update: () => false}, canEdit: {Monitors: false}, + STATE_IDLE: 0, secsToTime: () => '', stateStrings: [], + ZM_WEB_SOUND_ON_ALARM: 0, ZM_WEB_POPUP_ON_ALARM: 0, + setButtonState: (id, state) => buttonStates.push(id + ':' + state), + setTimeout: () => 0, clearTimeout() {}, setInterval: () => 0, + clearInterval() {}, statusRefreshTimeout: 1000, + }; + const sandbox = new Proxy(globals, { + has: () => true, + get: (target, prop) => (prop === Symbol.unscopables ? undefined : target[prop]), + }); + globals.window = sandbox; + vm.createContext(sandbox); + vm.runInContext(src, sandbox, {filename: 'MonitorStream.js'}); + const m = new globals.MonitorStream({ + id: 7, name: 't', connKey: '1', url: 'i', url_to_zms: 'z', width: 640, height: 480, + }); + m.getElement = () => ({}); + m.started = true; + m.streamCmdTimer = 1; + m.setButton('zoomOutBtn', {}); + m.getStreamCmdResponse({result: 'Ok', status: { + fps: 5, analysisfps: 1, capturefps: 5, level: 0, state: 0, delay: 0, zoom, + }}); + return {classes, buttonStates}; +} + +console.log('zoom readout and zoom-out button'); + +test('the readout is shown when zoomed in and hidden at 1.0', () => { + assert.strictEqual(statusReply('2.0').classes['#zoom7'], 'removed hidden'); + assert.strictEqual(statusReply('1.0').classes['#zoom7'], 'added hidden'); +}); + +test('the zoom-out button state follows the zoom', () => { + assert.deepStrictEqual(statusReply('2.0').buttonStates, ['zoomOutBtn:inactive']); + assert.deepStrictEqual(statusReply('1.0').buttonStates, ['zoomOutBtn:unavail']); +}); + +test('watch registers the zoom-out button under the key MonitorStream reads', () => { + const g = loadWatch(); + g.enableAlmBtn = g.forceAlmBtn = g.analyseBtn = makeHandlerSet(); + g.canEdit = {Monitors: false}; + const keys = []; + g.MonitorStream = function() { + this.setButton = (name) => keys.push(name); + this.setup_onclick = this.setup_onmove = this.setup_onpause = () => {}; + this.setup_onplay = this.setup_onalarm = this.manageAvailablePlayers = () => {}; + this.setBottomElement = () => {}; + }; + g.getCookie = () => null; + g.setChannelStream = g.streamCmdPlay = g.manageStreamQualityVisibility = () => {}; + g.monitorData = [{id: 1}]; + g.monIdx = 0; + g.panZoomEnabled = false; + g.streamStart(); + assert.ok(keys.includes('zoomOutBtn')); + keys.length = 0; + g.panZoomEnabled = true; + g.streamStart(); + assert.ok(!keys.includes('zoomOutBtn'), 'the button is hidden with the new ZoomPan'); +}); + +done(); diff --git a/web/js/MonitorStream.js b/web/js/MonitorStream.js index 2caac18fa8..bbd613d5be 100644 --- a/web/js/MonitorStream.js +++ b/web/js/MonitorStream.js @@ -1457,6 +1457,8 @@ function MonitorStream(monitorData) { $j('#zoomValue'+this.id).text(this.status.zoom); if (this.status.zoom == '1.0') { $j('#zoom'+this.id).addClass('hidden'); + } else { + $j('#zoom'+this.id).removeClass('hidden'); } if ('zoomOutBtn' in this.buttons) { if (this.status.zoom == '1.0') { diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index b5248ba321..08df8fa839 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -916,7 +916,8 @@ function streamStart(monitor = null) { monitorStream.setButton('enableAlarmButton', enableAlmBtn); monitorStream.setButton('forceAlarmButton', forceAlmBtn); - monitorStream.setButton('zoomOutButton', $j('zoomOutBtn')); + // Only the old ZoomPan uses the button; setButtonState() would unhide it + if (!panZoomEnabled) monitorStream.setButton('zoomOutBtn', $j('#zoomOutBtn')); monitorStream.setButton('analyseBtn', analyseBtn); if (canEdit.Monitors) { // Will be enabled by streamStatus ajax From 57216fc8af826bf77b7cbe7d276cf5ee682c2068 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:25:33 +0530 Subject: [PATCH 08/10] fix: call console.error in changeControl and drop the dead preset modal cache branch refs #5792 --- tests/js/watch-control-typos.test.js | 40 ++++++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 40 ++++++++++++---------------- 2 files changed, 57 insertions(+), 23 deletions(-) create mode 100644 tests/js/watch-control-typos.test.js diff --git a/tests/js/watch-control-typos.test.js b/tests/js/watch-control-typos.test.js new file mode 100644 index 0000000000..c40be7aeec --- /dev/null +++ b/tests/js/watch-control-typos.test.js @@ -0,0 +1,40 @@ +'use strict'; + +// changeControl() called console.err() when a control reply named an element +// the page does not have, which throws and abandoned the remaining controls. + +const assert = require('assert'); +const {loadWatch, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +console.log('watch.js changeControl'); + +test('an unknown control in the reply does not throw and later ones are applied', () => { + const set = []; + const errors = []; + const g = loadWatch({ + console: {log() {}, warn() {}, error: (m) => errors.push(m), debug() {}}, + }); + g.monitorUrl = 'index.php'; + g.monitorId = 1; + g.zmAuth = {appendTo: (u) => u}; + g.$j = Object.assign((sel) => ({ + length: sel === '#newContrast' ? 1 : 0, + val: (v) => set.push(['val', sel, v]), attr() {}, + }), { + getJSON: () => { + const p = {done: (fn) => { + fn({result: 'Ok', controls: [ + {control: 'brightness', value: 1}, {control: 'contrast', value: 2}, + ]}); + return p; + }, fail: () => p}; + return p; + }, + }); + g.changeControl({target: {name: 'newBrightness', value: '1'}}); + assert.strictEqual(errors.length, 1); + assert.deepStrictEqual(set, [['val', '#newContrast', 2]]); +}); + +done(); diff --git a/web/skins/classic/views/js/watch.js b/web/skins/classic/views/js/watch.js index 08df8fa839..efedd3d431 100644 --- a/web/skins/classic/views/js/watch.js +++ b/web/skins/classic/views/js/watch.js @@ -681,7 +681,7 @@ function changeControl(e) { element.val(control.value); element.attr('title', control.value); } else { - console.err('Element not found for #new'+control.control.charAt(0).toUpperCase() + control.control.slice(1)); + console.error('Element not found for #new'+control.control.charAt(0).toUpperCase() + control.control.slice(1)); } }); } @@ -762,28 +762,22 @@ function refresh_events_table() { function controlSetClicked() { console.log("Clicked"); - const modal = $j('#ctrlPresetModal'); - if (!modal.lenth) { - console.log('loading'); - // Load the PTZ Preset modal into the DOM - $j.getJSON(zmAuth.appendTo(monitorUrl + '?request=modal&modal=controlpreset&mid=' + monitorId)) - .done(function(data) { - insertModalHtml('ctrlPresetModal', data.html); - updatePresetLabels(); - // Manage the Preset Select box - $j('#preset').change(updatePresetLabels); - // Manage the Save button - $j('#cPresetSubmitModal').click(function(evt) { - evt.preventDefault(); - $j('#ctrlPresetForm').submit(); - }); - $j('#ctrlPresetModal').modal('show'); - }) - .fail(logAjaxFail); - } else { - console.log('not loading'); - modal.modal('show'); - } + // Always reload: the modal is rendered for one monitor and the page can switch monitors. + // Load the PTZ Preset modal into the DOM + $j.getJSON(zmAuth.appendTo(monitorUrl + '?request=modal&modal=controlpreset&mid=' + monitorId)) + .done(function(data) { + insertModalHtml('ctrlPresetModal', data.html); + updatePresetLabels(); + // Manage the Preset Select box + $j('#preset').change(updatePresetLabels); + // Manage the Save button + $j('#cPresetSubmitModal').click(function(evt) { + evt.preventDefault(); + $j('#ctrlPresetForm').submit(); + }); + $j('#ctrlPresetModal').modal('show'); + }) + .fail(logAjaxFail); } function streamPrepareStart(monitor=null) { From 5284e4d94f90c65fba6258a8d0ba4fa1d15960cf Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 18:25:47 +0530 Subject: [PATCH 09/10] fix: query the light toggle state for each monitor the watch page switches to refs #5792 --- tests/js/watch-light-toggle.test.js | 48 +++++++++++++++++++++++++++++ web/skins/classic/views/js/watch.js | 26 ++++++++-------- 2 files changed, 60 insertions(+), 14 deletions(-) create mode 100644 tests/js/watch-light-toggle.test.js diff --git a/tests/js/watch-light-toggle.test.js b/tests/js/watch-light-toggle.test.js new file mode 100644 index 0000000000..5848c25246 --- /dev/null +++ b/tests/js/watch-light-toggle.test.js @@ -0,0 +1,48 @@ +'use strict'; + +// The camera light state was queried only at page load, and only if the first +// monitor had a light button. Switching to a monitor that has one never asked +// the camera, so the button showed no state. + +const assert = require('assert'); +const {loadWatch, makeHandlerSet, runner} = require('./watch-sandbox'); +const {test, done} = runner(); + +console.log('watch.js light toggle'); + +test('applying a controllable monitor queries the light state of its buttons', () => { + const requests = []; + let lightButtons = 0; + const toggle = {disabled: false, classList: {add() {}, remove() {}}}; + const g = loadWatch({ + document: { + getElementById: (id) => (id === 'ptzToggle' ? toggle : null), + querySelector: () => null, querySelectorAll: () => [], + addEventListener() {}, createElement: () => ({}), + }, + }); + g.sidebarControls = Object.assign(makeHandlerSet(), { + html: (h) => { + if (h) lightButtons = 1; + }, + }); + g.$j = Object.assign((sel) => ({ + length: (sel === '.lightToggleBtn') ? lightButtons : 0, + }), { + getJSON: (url, data) => { + requests.push(data && data.control); + const p = {done: () => p, fail: () => p}; + return p; + }, + }); + g.zmAuth = {hash: ''}; + g.monitorUrl = 'index.php'; + g.monitorId = 2; + g.ptzVisible = true; + g.changeObjectClass = () => {}; + g.currentMonitor = {monitorControllable: true, ptzControls: '