From 3423b18e2740db1a4ebf60b8e3c86ca7f462c40b Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 1/7] fix: use the default server for map popups of monitors without a ServerId refs #5894 --- tests/js/map-single-server.test.js | 81 ++++++++++++++++++++++++++++++ web/js/Map.js | 2 +- 2 files changed, 82 insertions(+), 1 deletion(-) create mode 100644 tests/js/map-single-server.test.js diff --git a/tests/js/map-single-server.test.js b/tests/js/map-single-server.test.js new file mode 100644 index 0000000000..bd5f7e9998 --- /dev/null +++ b/tests/js/map-single-server.test.js @@ -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); +})(); diff --git a/web/js/Map.js b/web/js/Map.js index bf04587018..46620321cc 100644 --- a/web/js/Map.js +++ b/web/js/Map.js @@ -118,7 +118,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"]; From afdbe9db6a8bbbc780c94d3fd6757ef966d36bd3 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 2/7] fix: show 0% instead of NaN% on the map view when no monitor has a location refs #5894 --- tests/js/map-no-located-monitors.test.js | 83 ++++++++++++++++++++++++ web/js/Map.js | 6 +- 2 files changed, 86 insertions(+), 3 deletions(-) create mode 100644 tests/js/map-no-located-monitors.test.js diff --git a/tests/js/map-no-located-monitors.test.js b/tests/js/map-no-located-monitors.test.js new file mode 100644 index 0000000000..dfcd99ce10 --- /dev/null +++ b/tests/js/map-no-located-monitors.test.js @@ -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); +})(); diff --git a/web/js/Map.js b/web/js/Map.js index 46620321cc..9687030182 100644 --- a/web/js/Map.js +++ b/web/js/Map.js @@ -146,9 +146,9 @@ var ZMMap = function() { } 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); + 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+"%"; From 5d4067909d1d240e9617cce3652eadc4bf47f5c7 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 3/7] fix: update the DMS fields after Get Current Location refs #5894 --- tests/js/dms-getlocation.test.js | 79 +++++++++++++++++++++++++++ web/skins/classic/views/js/monitor.js | 3 +- 2 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 tests/js/dms-getlocation.test.js diff --git a/tests/js/dms-getlocation.test.js b/tests/js/dms-getlocation.test.js new file mode 100644 index 0000000000..4797a7376f --- /dev/null +++ b/tests/js/dms-getlocation.test.js @@ -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); diff --git a/web/skins/classic/views/js/monitor.js b/web/skins/classic/views/js/monitor.js index 26e34111c5..9a8e30321a 100644 --- a/web/skins/classic/views/js/monitor.js +++ b/web/skins/classic/views/js/monitor.js @@ -840,7 +840,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() { From fc9ce4f00adc39e62ad78e36a26f4d987891d413 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 4/7] fix: keep the decimal coordinate when the DMS field is empty or invalid refs #5894 --- tests/js/dms-invalid-input.test.js | 89 +++++++++++++++++++++++++++ web/skins/classic/views/js/monitor.js | 1 + 2 files changed, 90 insertions(+) create mode 100644 tests/js/dms-invalid-input.test.js diff --git a/tests/js/dms-invalid-input.test.js b/tests/js/dms-invalid-input.test.js new file mode 100644 index 0000000000..34a16ea6d9 --- /dev/null +++ b/tests/js/dms-invalid-input.test.js @@ -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); diff --git a/web/skins/classic/views/js/monitor.js b/web/skins/classic/views/js/monitor.js index 9a8e30321a..6ad3e4936a 100644 --- a/web/skins/classic/views/js/monitor.js +++ b/web/skins/classic/views/js/monitor.js @@ -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); From 101a577f6774dc71c7b8b25fa4b41f8bfb1d5a2a Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 5/7] fix: leave the event Location empty when there are no coordinates refs #5894 --- tests/js/events-location-column.test.js | 69 +++++++++++++++++++++++++ web/skins/classic/views/js/event.js | 2 +- web/skins/classic/views/js/events.js | 2 +- 3 files changed, 71 insertions(+), 2 deletions(-) create mode 100644 tests/js/events-location-column.test.js diff --git a/tests/js/events-location-column.test.js b/tests/js/events-location-column.test.js new file mode 100644 index 0000000000..7ec101ab59 --- /dev/null +++ b/tests/js/events-location-column.test.js @@ -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); diff --git a/web/skins/classic/views/js/event.js b/web/skins/classic/views/js/event.js index 7673489335..ad1c298522 100644 --- a/web/skins/classic/views/js/event.js +++ b/web/skins/classic/views/js/event.js @@ -1431,7 +1431,7 @@ function getStat() { // tdString = '' + eventData[key] + ''; // 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"]) { diff --git a/web/skins/classic/views/js/events.js b/web/skins/classic/views/js/events.js index 175ed593fa..abde294a98 100644 --- a/web/skins/classic/views/js/events.js +++ b/web/skins/classic/views/js/events.js @@ -111,7 +111,7 @@ function processRows(rows) { row.Frames = '' + row.Frames + ''; row.AlarmFrames = '' + row.AlarmFrames + ''; row.MaxScore = '' + row.MaxScore + ''; - row.Location = row.Latitude+', '+row.Longitude; + row.Location = (parseFloat(row.Latitude) || parseFloat(row.Longitude)) ? row.Latitude+', '+row.Longitude : ''; row.DiskSpace = '' + row.DiskSpace + ''; row.Storage = '' + row.Storage + ''; From ef08774253da8c83afb0d22c1815d6a8a8e94165 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:46:18 +0530 Subject: [PATCH 6/7] fix: make the event page location marker non-draggable refs #5894 --- web/skins/classic/views/js/event.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/web/skins/classic/views/js/event.js b/web/skins/classic/views/js/event.js index ad1c298522..7e0da1680a 100644 --- a/web/skins/classic/views/js/event.js +++ b/web/skins/classic/views/js/event.js @@ -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 { From 9ac91480a92269996877848f84cfb371430243d1 Mon Sep 17 00:00:00 2001 From: Jash Date: Sat, 14 Nov 2026 22:47:37 +0530 Subject: [PATCH 7/7] fix: fit the map view to the located monitors refs #5894 --- tests/js/map-fit-bounds.test.js | 84 +++++++++++++++++++++++++++++++++ web/js/Map.js | 3 ++ 2 files changed, 87 insertions(+) create mode 100644 tests/js/map-fit-bounds.test.js diff --git a/tests/js/map-fit-bounds.test.js b/tests/js/map-fit-bounds.test.js new file mode 100644 index 0000000000..9dc7bb7930 --- /dev/null +++ b/tests/js/map-fit-bounds.test.js @@ -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); +})(); diff --git a/web/js/Map.js b/web/js/Map.js index 9687030182..055900178f 100644 --- a/web/js/Map.js +++ b/web/js/Map.js @@ -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