Merge pull request #5793 from AJ0070/watch-fixes

fix: watch page state, handlers, resize observer and controls
This commit is contained in:
Isaac Connor authored and GitHub committed 2026-11-14 18:51:51 -05:00
commit 46930054bd
12 files changed
+780 -52

No files matched your search

+40
View File
@@ -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();
+99
View File
@@ -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();
+48
View File
@@ -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: '<button class="lightToggleBtn">'};
g.applyMonitorControllable();
assert.deepStrictEqual(requests, ['lightStatus']);
});
done();
+80
View File
@@ -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();
+68
View File
@@ -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();
+101
View File
@@ -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};
+113
View File
@@ -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);
+58
View File
@@ -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();
+101
View File
@@ -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();
+10
View File
@@ -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);
@@ -1453,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') {
@@ -1937,6 +1943,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 +1998,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 +2135,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 +2192,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;
+59 -51
View File
@@ -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;
@@ -680,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));
}
});
}
@@ -761,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) {
@@ -798,6 +793,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 +843,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);
@@ -913,12 +910,14 @@ 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
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');
@@ -978,6 +977,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();
@@ -1035,12 +1035,13 @@ function applyMonitorControllable() {
return;
}
if (currentMonitor.monitorControllable) {
const ptzShow = getCookie('ptzShow');
ptzToggle.classList.remove("disabled");
ptzToggle.disabled=false;
sidebarControls.html(currentMonitor.ptzControls);
if (ptzShow) {
// The buttons belong to this monitor's controls, so ask for their state now
lightStatusReq();
indicatorLightStatusReq();
if (ptzVisible) {
sidebarControls.show();
ptzToggle.classList.remove("btn-secondary");
ptzToggle.classList.add("btn-primary");
@@ -1058,6 +1059,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');
@@ -1121,9 +1128,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) {
@@ -1133,7 +1142,7 @@ function initPage() {
ayswModal.on('hidden.bs.modal', function() {
idleTimeoutTriggered = false;
streamCmdPlay(true);
if (cycle_was) cycleStart();
if (idleCycleWas) cycleStart();
});
ayswModal.modal('show');
})
@@ -1179,10 +1188,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"]');
@@ -1195,20 +1201,15 @@ function initPage() {
alert("No monitor found for id "+monitorId);
}
// Status-aware light toggle: initialise from the camera and re-query after
// each click so the button tracks the real state.
if ($j('.lightToggleBtn').length) {
lightStatusReq();
$j(document).on('click', '.lightToggleBtn', function() {
setTimeout(lightStatusReq, 800);
});
}
if ($j('.indicatorLightToggleBtn').length) {
indicatorLightStatusReq();
$j(document).on('click', '.indicatorLightToggleBtn', function() {
setTimeout(indicatorLightStatusReq, 800);
});
}
// Status-aware light toggle: re-query after each click so the button tracks
// the real state. Delegated, so it also covers a monitor switched to later;
// the initial query runs from applyMonitorControllable().
$j(document).on('click', '.lightToggleBtn', function() {
setTimeout(lightStatusReq, 800);
});
$j(document).on('click', '.indicatorLightToggleBtn', function() {
setTimeout(indicatorLightStatusReq, 800);
});
} // initPage
function watchFullscreen() {
@@ -1342,11 +1343,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();
@@ -1550,10 +1552,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 +1583,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).
+3 -1
View File
@@ -10,6 +10,7 @@
global $labels;
global $cycle;
global $player;
$control = $monitor->Control();
?>
//
// Import constants
@@ -20,6 +21,8 @@ var LIST_THUMBS = <?php echo ZM_WEB_LIST_THUMBS?'true':'false' ?>;
var streamMode = "<?php echo validJsStr($streamMode) ?>";
var showMode = "<?php echo ($showPtzControls && !empty($control))?"control":"events" ?>";
// Whether the PTZ panel starts shown: the request, the cookie or, with neither, shown
var ptzVisible = <?php echo $showPtzControls ? 'true' : 'false' ?>;
var cycle = <?php echo $cycle ? 'true' : 'false' ?>;
var player = '<?php echo validJsStr($player) ?>';
@@ -82,7 +85,6 @@ const imageRefreshTimeout = <?php echo 1000*ZM_WEB_REFRESH_IMAGE ?>;
const canStream = <?php echo canStream()?'true':'false' ?>;
var imageControlMode = '<?php
$control = $monitor->Control();
if ($control->CanMoveMap()) {
echo 'moveMap';
} else if ($control->CanMoveRel()) {