Merge pull request #5895 from AJ0070/map-fixes

fix: map popups, empty map, fit to monitors, DMS fields and empty locations
This commit is contained in:
Isaac Connor authored and GitHub committed 2026-11-14 18:44:51 -05:00
commit 29dab837ca
10 files changed
+498 -8

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.join(__dirname, '../..');
const src = fs.readFileSync(path.join(root, 'web/skins/classic/views/js/monitor.js'), 'utf8');
const dmsSrc = fs.readFileSync(path.join(root, 'web/js/dms.js'), 'utf8')
.replace('export default class', 'class')
.replace('export function', 'function')
.replace('export class', 'class');
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 extract(name) {
const start = src.indexOf('function ' + name + '(');
let depth = 0;
for (let i = src.indexOf('{', start); ; i++) {
if (src[i] === '{') depth++;
if (src[i] === '}' && !--depth) return src.slice(start, i + 1);
}
}
function page(lat, lng) {
const els = {
'newMonitor[Latitude]': {id: 'newMonitor[Latitude]', value: lat},
'newMonitor[Longitude]': {id: 'newMonitor[Longitude]', value: lng},
'LatitudeDMS': {id: 'LatitudeDMS', value: ''},
'LongitudeDMS': {id: 'LongitudeDMS', value: ''},
};
els.contentForm = {elements: {
'newMonitor[Latitude]': els['newMonitor[Latitude]'],
'newMonitor[Longitude]': els['newMonitor[Longitude]'],
}};
const view = {latlng: null};
const ctx = {
document: {getElementById: (id) => els[id]},
console,
L: {LatLng: function(a, b) {
this.lat = Number(a);
this.lng = Number(b);
}},
marker: {setLatLng(l) {
view.latlng = l;
}},
map: {setView() {}, invalidateSize() {}},
setTimeout: () => {},
navigator: {geolocation: {getCurrentPosition: (cb) => cb({coords: {latitude: -33.8688, longitude: 151.2093}})}},
};
vm.createContext(ctx);
const fns = ['ll2dms', 'dms2ll', 'updateMarker', 'updateLatitudeAndLongitude', 'getLocation'];
vm.runInContext(dmsSrc + fns.map(extract).join('\n') + ';this.api = {ll2dms, dms2ll, getLocation, parseDms}', ctx);
return {els, view, api: ctx.api};
}
test('Get Current Location refreshes the DMS fields', () => {
const p = page('', '');
p.api.getLocation();
assert.strictEqual(p.els.LatitudeDMS.value, '33°52′7.68″ S');
assert.strictEqual(p.els.LongitudeDMS.value, '151°12′33.48″ E');
assert.strictEqual(p.view.latlng.lat, -33.8688);
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
+89
View File
@@ -0,0 +1,89 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.join(__dirname, '../..');
const src = fs.readFileSync(path.join(root, 'web/skins/classic/views/js/monitor.js'), 'utf8');
const dmsSrc = fs.readFileSync(path.join(root, 'web/js/dms.js'), 'utf8')
.replace('export default class', 'class')
.replace('export function', 'function')
.replace('export class', 'class');
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 extract(name) {
const start = src.indexOf('function ' + name + '(');
let depth = 0;
for (let i = src.indexOf('{', start); ; i++) {
if (src[i] === '{') depth++;
if (src[i] === '}' && !--depth) return src.slice(start, i + 1);
}
}
function page(lat, lng) {
const els = {
'newMonitor[Latitude]': {id: 'newMonitor[Latitude]', value: lat},
'newMonitor[Longitude]': {id: 'newMonitor[Longitude]', value: lng},
'LatitudeDMS': {id: 'LatitudeDMS', value: ''},
'LongitudeDMS': {id: 'LongitudeDMS', value: ''},
};
els.contentForm = {elements: {
'newMonitor[Latitude]': els['newMonitor[Latitude]'],
'newMonitor[Longitude]': els['newMonitor[Longitude]'],
}};
const view = {latlng: null};
const ctx = {
document: {getElementById: (id) => els[id]},
console,
L: {LatLng: function(a, b) {
this.lat = Number(a);
this.lng = Number(b);
}},
marker: {setLatLng(l) {
view.latlng = l;
}},
map: {setView() {}, invalidateSize() {}},
setTimeout: () => {},
navigator: {geolocation: {getCurrentPosition: (cb) => cb({coords: {latitude: -33.8688, longitude: 151.2093}})}},
};
vm.createContext(ctx);
const fns = ['ll2dms', 'dms2ll', 'updateMarker', 'updateLatitudeAndLongitude', 'getLocation'];
vm.runInContext(dmsSrc + fns.map(extract).join('\n') + ';this.api = {ll2dms, dms2ll, getLocation, parseDms}', ctx);
return {els, view, api: ctx.api};
}
test('an empty or unparsable DMS field leaves the decimal value alone', () => {
const p = page('10', '20');
p.els.LatitudeDMS.value = '';
p.api.dms2ll(p.els.LatitudeDMS);
assert.strictEqual(p.els['newMonitor[Latitude]'].value, '10');
p.els.LongitudeDMS.value = 'abc';
p.api.dms2ll(p.els.LongitudeDMS);
assert.strictEqual(p.els['newMonitor[Longitude]'].value, '20');
assert.strictEqual(p.view.latlng, null);
});
test('a valid DMS value still sets the decimal value', () => {
const p = page('10', '20');
p.els.LatitudeDMS.value = '33°52′7.68″ S';
p.api.dms2ll(p.els.LatitudeDMS);
assert.strictEqual(p.els['newMonitor[Latitude]'].value, '-33.86880000');
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
+69
View File
@@ -0,0 +1,69 @@
'use strict';
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/events.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 extract(name) {
const start = src.indexOf('function ' + name + '(');
let depth = 0;
for (let i = src.indexOf('{', start); ; i++) {
if (src[i] === '{') depth++;
if (src[i] === '}' && !--depth) return src.slice(start, i + 1);
}
}
function location(lat, lng) {
const ctx = {
$j: {each: (arr, fn) => arr.forEach((v, i) => fn(i, v))},
canEdit: {}, yesString: 'Yes', archivedString: '', emailedString: '',
filterQuery: '', sortQuery: '', Date, String,
};
vm.createContext(ctx);
vm.runInContext(extract('processRows') + ';this.processRows = processRows', ctx);
const row = {
Id: 1, Archived: 'No', Emailed: 'No', Name: 'n', Monitor: 'm', Cause: 'c', Notes: '',
Frames: 1, AlarmFrames: 0, MaxScore: 0, DiskSpace: '', Storage: '', Length: 5,
Latitude: lat, Longitude: lng,
};
try {
ctx.processRows([row]);
} catch (e) {
if (row.Location === undefined) throw e;
}
return row.Location;
}
test('an event without coordinates shows an empty location', () => {
assert.strictEqual(location(null, null), '');
});
test('an event of a monitor without a location shows an empty location', () => {
assert.strictEqual(location('0.00000000', '0.00000000'), '');
});
test('an event with coordinates shows them', () => {
assert.strictEqual(location('48.13700000', '11.57500000'), '48.13700000, 11.57500000');
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
+84
View File
@@ -0,0 +1,84 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.join(__dirname, '../..');
let passed = 0;
let failed = 0;
async function test(name, fn) {
try {
await fn();
console.log(' ok ' + name);
passed++;
} catch (e) {
console.error(' FAIL ' + name);
console.error(' ' + (e.stack || e.message));
failed++;
}
}
async function scenario(monitors) {
const markers = [];
const els = {};
const el = (id) => els[id] || (els[id] = {style: {}, innerHTML: '', classList: {add() {}}});
const L = {
fit: null,
map: () => ({invalidateSize() {}, fitBounds(b) {
L.fit = b;
}}),
latLng: (a, b) => ({a, b}),
tileLayer: () => ({addTo() {}}),
icon: (o) => o,
marker: (ll, o) => {
const m = {ll, o, addTo() {
markers.push(m);
return m;
}, bindPopup(p) {
m.popup = p;
return m;
}};
return m;
},
};
const ctx = {
L, document: {getElementById: el}, console: {log() {}},
location: {port: '', protocol: 'http:', host: 'zm'},
ZM_OPT_GEOLOCATION_TILE_PROVIDER: 'x', ZM_OPT_GEOLOCATION_ACCESS_TOKEN: 't',
serverId: 0, thisUrl: 'index.php', zmAuth: {appendTo: (u) => u},
sin: Math.sin, cos: Math.cos, sqrt: Math.sqrt, atan2: Math.atan2,
deg2rad: (d) => d * Math.PI / 180,
};
vm.createContext(ctx);
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Server.js'), 'utf8'), ctx);
ctx.Servers = [new ctx.Server({Id: 0, Hostname: 'h', Protocol: 'http', PathToZMS: '/zms'})];
ctx.Servers[0].getFromApi = () => Promise.resolve({json: () => Promise.resolve({monitors})});
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Map.js'), 'utf8') + ';this.ZMMap = ZMMap', ctx);
new ctx.ZMMap().addMonitors();
await new Promise((r) => setTimeout(r, 20));
return {markers, els, L};
}
const mon = (o, events = '3') => ({
Monitor: Object.assign({Id: '1', Name: 'a', Latitude: '10.1', Longitude: '20.2', Width: 640, Height: 480, ServerId: null}, o),
Monitor_Status: {CaptureFPS: '5', Status: 'Connected'},
Event_Summary: {TotalEvents: events},
});
(async () => {
await test('the view is fitted to the monitor locations', async () => {
const r = await scenario([mon({Latitude: '48.1', Longitude: '11.5'}), mon({Id: '2', Latitude: '52.5', Longitude: '13.4'})]);
assert.strictEqual(JSON.stringify(r.L.fit), '[["48.1","11.5"],["52.5","13.4"]]');
});
await test('no fit when no monitor has a location', async () => {
const r = await scenario([mon({Latitude: null, Longitude: null})]);
assert.strictEqual(r.L.fit, null);
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
})();
+83
View File
@@ -0,0 +1,83 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.join(__dirname, '../..');
let passed = 0;
let failed = 0;
async function test(name, fn) {
try {
await fn();
console.log(' ok ' + name);
passed++;
} catch (e) {
console.error(' FAIL ' + name);
console.error(' ' + (e.stack || e.message));
failed++;
}
}
async function scenario(monitors) {
const markers = [];
const els = {};
const el = (id) => els[id] || (els[id] = {style: {}, innerHTML: '', classList: {add() {}}});
const L = {
fit: null,
map: () => ({invalidateSize() {}, fitBounds(b) {
L.fit = b;
}}),
latLng: (a, b) => ({a, b}),
tileLayer: () => ({addTo() {}}),
icon: (o) => o,
marker: (ll, o) => {
const m = {ll, o, addTo() {
markers.push(m);
return m;
}, bindPopup(p) {
m.popup = p;
return m;
}};
return m;
},
};
const ctx = {
L, document: {getElementById: el}, console: {log() {}},
location: {port: '', protocol: 'http:', host: 'zm'},
ZM_OPT_GEOLOCATION_TILE_PROVIDER: 'x', ZM_OPT_GEOLOCATION_ACCESS_TOKEN: 't',
serverId: 0, thisUrl: 'index.php', zmAuth: {appendTo: (u) => u},
sin: Math.sin, cos: Math.cos, sqrt: Math.sqrt, atan2: Math.atan2,
deg2rad: (d) => d * Math.PI / 180,
};
vm.createContext(ctx);
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Server.js'), 'utf8'), ctx);
ctx.Servers = [new ctx.Server({Id: 0, Hostname: 'h', Protocol: 'http', PathToZMS: '/zms'})];
ctx.Servers[0].getFromApi = () => Promise.resolve({json: () => Promise.resolve({monitors})});
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Map.js'), 'utf8') + ';this.ZMMap = ZMMap', ctx);
new ctx.ZMMap().addMonitors();
await new Promise((r) => setTimeout(r, 20));
return {markers, els, L};
}
const mon = (o, events = '3') => ({
Monitor: Object.assign({Id: '1', Name: 'a', Latitude: '10.1', Longitude: '20.2', Width: 640, Height: 480, ServerId: null}, o),
Monitor_Status: {CaptureFPS: '5', Status: 'Connected'},
Event_Summary: {TotalEvents: events},
});
(async () => {
await test('no located monitors shows 0% rather than NaN%', async () => {
const r = await scenario([mon({Latitude: null, Longitude: null})]);
assert.strictEqual(r.markers.length, 0);
for (const id of ['progress-connected', 'progress-disconnected', 'progress-error']) {
assert.strictEqual(r.els[id].innerHTML, '0.00%');
assert.strictEqual(r.els[id].style.width, '0.00%');
}
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
})();
+81
View File
@@ -0,0 +1,81 @@
'use strict';
const assert = require('assert');
const fs = require('fs');
const path = require('path');
const vm = require('vm');
const root = path.join(__dirname, '../..');
let passed = 0;
let failed = 0;
async function test(name, fn) {
try {
await fn();
console.log(' ok ' + name);
passed++;
} catch (e) {
console.error(' FAIL ' + name);
console.error(' ' + (e.stack || e.message));
failed++;
}
}
async function scenario(monitors) {
const markers = [];
const els = {};
const el = (id) => els[id] || (els[id] = {style: {}, innerHTML: '', classList: {add() {}}});
const L = {
fit: null,
map: () => ({invalidateSize() {}, fitBounds(b) {
L.fit = b;
}}),
latLng: (a, b) => ({a, b}),
tileLayer: () => ({addTo() {}}),
icon: (o) => o,
marker: (ll, o) => {
const m = {ll, o, addTo() {
markers.push(m);
return m;
}, bindPopup(p) {
m.popup = p;
return m;
}};
return m;
},
};
const ctx = {
L, document: {getElementById: el}, console: {log() {}},
location: {port: '', protocol: 'http:', host: 'zm'},
ZM_OPT_GEOLOCATION_TILE_PROVIDER: 'x', ZM_OPT_GEOLOCATION_ACCESS_TOKEN: 't',
serverId: 0, thisUrl: 'index.php', zmAuth: {appendTo: (u) => u},
sin: Math.sin, cos: Math.cos, sqrt: Math.sqrt, atan2: Math.atan2,
deg2rad: (d) => d * Math.PI / 180,
};
vm.createContext(ctx);
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Server.js'), 'utf8'), ctx);
ctx.Servers = [new ctx.Server({Id: 0, Hostname: 'h', Protocol: 'http', PathToZMS: '/zms'})];
ctx.Servers[0].getFromApi = () => Promise.resolve({json: () => Promise.resolve({monitors})});
vm.runInContext(fs.readFileSync(path.join(root, 'web/js/Map.js'), 'utf8') + ';this.ZMMap = ZMMap', ctx);
new ctx.ZMMap().addMonitors();
await new Promise((r) => setTimeout(r, 20));
return {markers, els, L};
}
const mon = (o, events = '3') => ({
Monitor: Object.assign({Id: '1', Name: 'a', Latitude: '10.1', Longitude: '20.2', Width: 640, Height: 480, ServerId: null}, o),
Monitor_Status: {CaptureFPS: '5', Status: 'Connected'},
Event_Summary: {TotalEvents: events},
});
(async () => {
await test('a monitor without a ServerId gets a usable stream url', async () => {
const r = await scenario([mon({})]);
assert.strictEqual(r.markers.length, 1);
assert.ok(!/undefined/.test(r.markers[0].popup), r.markers[0].popup);
assert.ok(/src="http:\/\/h\/zms\?/.test(r.markers[0].popup), r.markers[0].popup);
});
console.log('');
console.log(passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
})();
+7 -4
View File
@@ -88,6 +88,7 @@ var ZMMap = function() {
const div_error = document.getElementById("progress-error");
const pins = [];
const bounds = [];
for (let i=0, len = monitors.monitors.length; i<len; i++) {
const monitor = monitors.monitors[i].Monitor;
@@ -118,7 +119,7 @@ var ZMMap = function() {
}
const monitor_status = monitors["monitors"][i]["Monitor_Status"];
const event_summary = monitors["monitors"][i]["Event_Summary"];
const server = new Server(Servers[monitor.ServerId]);
const server = new Server(Servers[monitor.ServerId] || Servers[0]);
const id = monitor["Id"];
const fps = monitor_status["CaptureFPS"];
@@ -144,11 +145,13 @@ var ZMMap = function() {
.addTo(this.map).bindPopup(popup);
cant_error += 1;
}
bounds.push([monitor.Latitude, monitor.Longitude]);
total_cameras += 1;
} // end foreach monitor
const percent_connected = Number.parseFloat(((cant_connected*100)/total_cameras)).toFixed(2);
const percent_disconnected = Number.parseFloat(((cant_disconnected*100)/total_cameras)).toFixed(2);
const percent_error = Number.parseFloat(((cant_error*100)/total_cameras)).toFixed(2);
if (bounds.length) this.map.fitBounds(bounds, {maxZoom: 12});
const percent_connected = Number.parseFloat(total_cameras ? (cant_connected*100)/total_cameras : 0).toFixed(2);
const percent_disconnected = Number.parseFloat(total_cameras ? (cant_disconnected*100)/total_cameras : 0).toFixed(2);
const percent_error = Number.parseFloat(total_cameras ? (cant_error*100)/total_cameras : 0).toFixed(2);
div_connected.style.width = percent_connected+"%";
div_connected.innerHTML = percent_connected+"%";
+2 -2
View File
@@ -1431,7 +1431,7 @@ function getStat() {
// tdString = '<a href="?view=frames&amp;eid=' + eventData.Id + '">' + eventData[key] + '</a>';
// break;
case 'Location':
tdString = eventData.Latitude + ', ' + eventData.Longitude;
tdString = (parseFloat(eventData.Latitude) || parseFloat(eventData.Longitude)) ? eventData.Latitude + ', ' + eventData.Longitude : '';
break;
//case 'MonitorId':
// if (canView["Monitors"]) {
@@ -1961,7 +1961,7 @@ function initPage() {
zoomOffset: -1,
accessToken: ZM_OPT_GEOLOCATION_ACCESS_TOKEN,
}).addTo(map);
const marker = L.marker([eventData.Latitude, eventData.Longitude], {draggable: 'false'});
const marker = L.marker([eventData.Latitude, eventData.Longitude], {draggable: false});
marker.addTo(map);
map.invalidateSize();
} else {
+1 -1
View File
@@ -111,7 +111,7 @@ function processRows(rows) {
row.Frames = '<a href="?view=frames&amp;eid=' + eid + '">' + row.Frames + '</a>';
row.AlarmFrames = '<a href="?view=frames&amp;eid=' + eid + '">' + row.AlarmFrames + '</a>';
row.MaxScore = '<a href="?view=frame&amp;eid=' + eid + '&amp;fid=0">' + row.MaxScore + '</a>';
row.Location = row.Latitude+', '+row.Longitude;
row.Location = (parseFloat(row.Latitude) || parseFloat(row.Longitude)) ? row.Latitude+', '+row.Longitude : '';
row.DiskSpace = '<a href="?view=event&amp;eid=' + eid + filterQuery + sortQuery + '&amp;page=1">' + row.DiskSpace + '</a>';
row.Storage = '<a href="?view=event&amp;eid=' + eid + filterQuery + sortQuery + '&amp;page=1">' + row.Storage + '</a>';
+3 -1
View File
@@ -698,6 +698,7 @@ function dms2ll(input) {
const latitude = document.getElementById('newMonitor[Latitude]');
const longitude = document.getElementById('newMonitor[Longitude]');
const dms = parseDms(input.value);
if (isNaN(dms)) return;
if (input.id == 'LatitudeDMS') {
latitude.value = dms.toFixed(8);
@@ -840,7 +841,8 @@ function updateLatitudeAndLongitude(latitude, longitude) {
var form = document.getElementById('contentForm');
form.elements['newMonitor[Latitude]'].value = latitude;
form.elements['newMonitor[Longitude]'].value = longitude;
updateMarker(latitude, longitude);
ll2dms(form.elements['newMonitor[Latitude]']);
ll2dms(form.elements['newMonitor[Longitude]']);
}
function getLocation() {