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/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/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/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/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/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..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' + 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"]) { @@ -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 { 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 + ''; diff --git a/web/skins/classic/views/js/monitor.js b/web/skins/classic/views/js/monitor.js index 26e34111c5..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); @@ -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() {