43 Commits

Author SHA1 Message Date
Linus Groh
cb0694b032 Release 2.4.0 2020-06-01 18:44:07 +01:00
Linus Groh
d0f2a99302 Upgrade dependencies 2020-06-01 18:39:01 +01:00
Linus Groh
c8b0ec8b9e Upgrade dependencies
This includes a major version bump of ESLint and Prettier, so also some
reformatting.
2020-05-16 13:58:48 +01:00
Linus Groh
906eb2a1b4 Fix typos causing the minAccuracy filter to work incorrectly 2020-05-16 13:50:57 +01:00
Linus Groh
005aab715f Improve wording in docs 2020-05-11 19:22:13 +01:00
Linus Groh
b76cbdc2e6 Add filters.minAccuracy config option
This allows us to ignore location points which do not meet the configured
accuracy requirement.

Closes #35.
2020-05-11 19:15:56 +01:00
Linus Groh
bb87ec01d4 Release 2.3.1 2020-05-09 15:50:52 +01:00
Linus Groh
c3e6b775f9 Re-format config.md 2020-05-09 15:50:01 +01:00
Linus Groh
a9998e8e3b Release 2.3.0 2020-05-09 15:45:19 +01:00
Linus Groh
2c4ead262a Add api.fetchOptions to allow customising fetch() behaviour
This allows sending custom HTTP headers or including cookies in the
request!
2020-05-09 15:40:50 +01:00
Linus Groh
6b1d35be51 Upgrade dependencies 2020-05-09 14:18:14 +01:00
Linus Groh
34cc4895b0 Upgrade dependencies 2020-04-02 19:45:43 +01:00
Linus Groh
57caacb548 Release 2.2.0 2020-03-18 17:56:11 +00:00
Linus Groh
9783b6f27d Upgrade dependencies 2020-03-18 17:55:43 +00:00
Linus Groh
b262ff602c Improve mobile layout further
- Reduce header paddings
- Align buttons/dropdowns
2020-03-18 17:50:49 +00:00
Linus Groh
458658865e Release 2.1.0 2020-03-18 00:35:24 +00:00
Linus Groh
e744e2c001 Make it usable on mobile
Closes #19
2020-03-18 00:28:11 +00:00
Linus Groh
feff6d5272 Upgrade dependencies 2020-03-14 16:17:31 +00:00
Linus Groh
7b88102c2b Merge pull request #28 from owntracks/dependabot/npm_and_yarn/acorn-5.7.4
Bump acorn from 5.7.3 to 5.7.4
2020-03-14 16:14:03 +00:00
dependabot[bot]
a2c7974f38 Bump acorn from 5.7.3 to 5.7.4
Bumps [acorn](https://github.com/acornjs/acorn) from 5.7.3 to 5.7.4.
- [Release notes](https://github.com/acornjs/acorn/releases)
- [Commits](https://github.com/acornjs/acorn/compare/5.7.3...5.7.4)

Signed-off-by: dependabot[bot] <support@github.com>
2020-03-14 09:44:52 +00:00
Linus Groh
b3fdf1eabe Improve verbose mode logging
- Support passing a log message function to `logging.log` for lazy
  evaluation
- Log results (or at least lengths) of all API functions
- Log merged config during initialisation
- Log distance calculation duration
2020-03-07 00:22:56 +00:00
Linus Groh
1482833e05 Fix a few parameter type definitions 2020-03-07 00:14:59 +00:00
Linus Groh
04fa3392f0 Fix typo in CHANGELOG.md 2020-03-03 14:05:08 +00:00
Linus Groh
a4334e5273 Fix manual installation instructions in README.md
`yarn install --production` does not actually install all dependencies
required for building - maybe we have to move some `devDependencies` to
`dependencies`, but for now this should do the trick.
2020-03-03 13:40:15 +00:00
Linus Groh
806526380d Replace default Leaflet marker with a custom one
Closes #2
2020-03-03 08:11:45 +00:00
Linus Groh
2e63f01438 Release 2.0.0 🎉 2020-03-01 21:16:59 +00:00
Linus Groh
fb97cd080f Release 2.0.0-beta.11 2020-03-01 21:11:33 +00:00
Linus Groh
f2d461d019 Merge pull request #20 from owntracks/clean-up-the-typing-mess
Clean up the typing mess
2020-03-01 20:59:36 +00:00
Linus Groh
798a0af97d Update function documentations 2020-03-01 20:56:28 +00:00
Linus Groh
3c92a77847 Fix typo in OTLocation.inregions comment 2020-03-01 20:55:52 +00:00
Linus Groh
b252a6580a Use TypeScript interface for websocket calllback 2020-03-01 20:53:38 +00:00
Linus Groh
9ce9933d11 Remove unused properties from Config interface 2020-03-01 20:34:21 +00:00
Linus Groh
f22db6301b Merge branch 'master' into clean-up-the-typing-mess 2020-03-01 20:33:00 +00:00
Linus Groh
3b18ab58ed Replace map initial center/zoom config with auto fitting
Closes #23
2020-03-01 20:28:15 +00:00
Linus Groh
bb81daaea4 Upgrade dependencies 2020-03-01 19:56:57 +00:00
Linus Groh
f491d63eb9 Mention Spanish translations in config docs 2020-02-09 11:07:35 +00:00
Linus Groh
e923fdc6c7 Merge pull request #25 from dtorner/patch-2
Create es.json
2020-02-09 11:00:30 +00:00
dtorner
b1ce1297ed Create es.json 2020-02-09 09:47:11 +01:00
Linus Groh
f4262efaa4 Change distance travelled label to title
See https://github.com/owntracks/frontend/issues/22#issuecomment-583698919
2020-02-08 11:50:48 +00:00
Linus Groh
a2109a5802 Fix humanReadableDistance JSDoc
That's what you get from copy & paste...
2020-02-07 21:51:39 +00:00
Linus Groh
a20fbf7e10 Remove all @typedef definitions 2020-01-24 21:02:24 +00:00
Linus Groh
d2eafd5a4a Merge branch 'master' into clean-up-the-typing-mess 2020-01-24 20:43:57 +00:00
Linus Groh
871f9f0cb2 Add index.d.ts 2019-12-15 20:59:57 +00:00
28 changed files with 3214 additions and 3059 deletions

View File

@@ -1,5 +1,51 @@
# Changelog
Dates are in UTC.
## 2.4.0 (2020-06-01)
- Add `filters.minAccuracy` config option - this allows ignoring location points which do
not meet the configured accuracy requirement ([#35](https://github.com/owntracks/frontend/issues/35))
- Upgrade dependencies
## 2.3.1 (2020-05-09)
- Fix linting issue in `config.md`
## 2.3.0 (2020-05-09)
- Add `api.fetchOptions` config option - this allows sending custom HTTP headers or including
cookies in the request
- Upgrade dependencies
## 2.2.0 (2020-03-18)
- Improve mobile layout further:
- Reduce header paddings
- Align buttons/dropdowns
- Upgrade dependencies
## 2.1.0 (2020-03-18)
- Replace default Leaflet marker with a custom one ([#2](https://github.com/owntracks/frontend/issues/2))
- Improve verbose mode logging
- Improve mobile usability ([#19](https://github.com/owntracks/frontend/issues/19))
- Upgrade dependencies
## 2.0.0 (2020-03-01)
Stable release of v2, finally! 🎉
_This is just a version bump, see all the beta releases below, especially the first one, for a list of changes._
## 2.0.0-beta.11 (2020-03-01)
- Add Spanish translations ([#25](https://github.com/owntracks/frontend/pull/25), [@dtorner](https://github.com/dtorner))
- Change "distance travelled" label to `title`
- Replace map initial center/zoom config with auto fitting ([#23](https://github.com/owntracks/frontend/issues/23))
- Enhance code type definitions using TypeScript features ([#20](https://github.com/owntracks/frontend/pull/20))
- Upgrade dependencies
## 2.0.0-beta.10 (2020-02-07)
- Add "distance travelled" feature

View File

@@ -77,7 +77,7 @@ directory as `docker-compose.yml`)
### Manually
- Run `yarn install --production` to install dependencies
- Run `yarn install` to install dependencies
- Run `yarn build` to compile and minify for production
- Copy the content of the `dist/` directory to your webroot

View File

@@ -6,7 +6,7 @@ COPY . ./
RUN yarn build
FROM nginx:1.17-alpine
LABEL version="2.0.0-beta.10"
LABEL version="2.4.0"
LABEL description="OwnTracks UI"
LABEL maintainer="Linus Groh <mail@linusgroh.de>"
ENV LISTEN_PORT=80 \

View File

@@ -24,14 +24,14 @@ window.owntracks.config = {};
- `api`
- [`baseUrl`](#apibaseurl)
- [`fetchOptions`](#apifetchoptions)
- [`endDateTime`](#enddatetime)
- `filters`
- [`minAccuracy`](#filtersminaccuracy)
- [`ignorePingLocation`](#ignorepinglocation)
- [`locale`](#locale)
- `map`
- [`attribution`](#mapattribution)
- `center`
- [`lat`](#mapcenterlat)
- [`lng`](#mapcenterlng)
- [`circle`](#mapcircle)
- [`circleMarker`](#mapcirclemarker)
- `controls`
@@ -59,7 +59,6 @@ window.owntracks.config = {};
- [`maxZoom`](#mapmaxzoom)
- [`polyline`](#mappolyline)
- [`url`](#mapurl)
- [`zoom`](#mapzoom)
- `onLocationChange`
- [`reloadHistory`](#onlocationchangereloadhistory)
- [`primaryColor`](#primarycolor)
@@ -80,16 +79,36 @@ Base URL for the recorder's HTTP and WebSocket API. Keep CORS in mind.
// API requests will be made to https://owntracks.example.com/api/0/...
window.owntracks.config = {
api: {
baseUrl: "https://owntracks.example.com"
}
baseUrl: "https://owntracks.example.com",
},
};
```
```js
// API requests will be made to https://example.com/owntracks/api/0/...
window.owntracks.config = {
api: {
baseUrl: "https://example.com/owntracks/"
}
baseUrl: "https://example.com/owntracks/",
},
};
```
### `api.fetchOptions`
Options for API requests (made with `fetch()`). See [`fetch()` docs on MDN] for details.
You can use this for example to send custom HTTP headers or to include cookies in the request.
- Type: [`Object`]
- Default: `{}`
- Example:
```js
// Include credentials (e.g. cookies)
window.owntracks.config = {
api: {
fetchOptions: {
credentials: "include",
},
},
};
```
@@ -103,7 +122,27 @@ Initial end date and time (browser timezone) for fetched data.
```js
// Data will be fetched up to 1970-01-01
window.owntracks.config = {
endDateTime: new Date(1970, 1, 1)
endDateTime: new Date(1970, 1, 1),
};
```
### `filters.minAccuracy`
Minimum accuracy in meters for location points to be rendered & included in the travelled distance.
This filter is disabled by default as accuracies can vary across devices an locations, but you're
encouraged to set it as it can be a simple way to remove outliers and vastly improve the travelled
distance calculation.
- Type: [`Number`] or `null`
- Default: `null`
- Example:
```js
// Don't include location points with an accuracy exceeding 100 meters
window.owntracks.config = {
filters: {
minAccuracy: 100,
},
};
```
@@ -118,15 +157,22 @@ Remove the `ping/ping` location from the fetched data. This is useful when using
```js
// Don't ignore ping/ping location. Not sure why you'd do this :)
window.owntracks.config = {
ignorePingLocation: false
ignorePingLocation: false,
};
```
### `locale`
The locale to use for the user interface, this affects the language and date/time
formats. Available languages are `de` (German), `en` (English). You can use formats
like `en-GB`, `en-US`, `de-DE`.
formats.
Available languages:
- `de` (German)
- `en` (English)
- `es` (Spanish)
You can use formats like `en-GB`, `en-US`, `de-DE`.
- Type: [`String`]
- Default: `"en"`
@@ -142,25 +188,11 @@ Attribution for map tiles.
// Make sure to add proper attribution!
window.owntracks.config = {
map: {
attribution: "Map tiles &copy; MyTileServerProvider"
}
attribution: "Map tiles &copy; MyTileServerProvider",
},
};
```
### `map.center.lat`
Initial map center latitude.
- Type: [`Number`]
- Default: `0`
### `map.center.lng`
Initial map center longitude.
- Type: [`Number`]
- Default: `0`
### `map.circle`
Location accuracy indicator configuation. `color` and `fillColor` default to
@@ -324,8 +356,8 @@ splitting into separate lines.
// Don't connect points with a distance of more than 1km
window.owntracks.config = {
map: {
maxPointDistance: 1000
}
maxPointDistance: 1000,
},
};
```
@@ -366,18 +398,11 @@ and [this Wikipedia article](https://en.wikipedia.org/wiki/Tiled_web_map).
window.owntracks.config = {
map: {
url:
"https://api.mapbox.com/v4/mapbox.dark/{z}/{x}/{y}@2x.png?access_token=xxxxxxxxxxxxxxxx"
}
"https://api.mapbox.com/v4/mapbox.dark/{z}/{x}/{y}@2x.png?access_token=xxxxxxxxxxxxxxxx",
},
};
```
### `map.zoom`
Initial map zoom level.
- Type: [`Number`]
- Default: `19`
### `onLocationChange.reloadHistory`
Whether to reload the location history (of selected date range) or not when a location
@@ -396,7 +421,7 @@ Primary color for the user interface (navigation bar and various map elements).
```js
// Set the UI's primary color to 'rebeccapurple'
window.owntracks.config = {
primaryColor: "rebeccapurple"
primaryColor: "rebeccapurple",
};
```
@@ -415,7 +440,7 @@ amount of data fetched after page load.
// Select the device 'phone' from user 'foo' by default
window.owntracks.config = {
selectedUser: "foo",
selectedDevice: "phone"
selectedDevice: "phone",
};
```
@@ -432,7 +457,7 @@ amount of data fetched after page load.
```js
// Select all devices from user 'foo' by default
window.owntracks.config = {
selectedUser: "foo"
selectedUser: "foo",
};
```
@@ -459,7 +484,7 @@ Initial start date and time (browser timezone) for fetched data.
startDateTime.setHours(0, 0, 0, 0);
startDateTime.setDate(1);
window.owntracks.config = {
startDateTime
startDateTime,
};
```
@@ -476,3 +501,4 @@ Whether to enable verbose mode or not.
[`object`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
[`string`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String
[css `<color>`]: https://developer.mozilla.org/en-US/docs/Web/CSS/color_value
[`fetch()` docs on mdn]: https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters

View File

@@ -1,6 +1,6 @@
{
"name": "owntracks-ui",
"version": "2.0.0-beta.10",
"version": "2.4.0",
"author": {
"name": "Linus Groh",
"email": "mail@linusgroh.de"
@@ -18,41 +18,43 @@
},
"dependencies": {
"clipboard-copy": "^3.1.0",
"core-js": "^3.6.4",
"core-js": "^3.6.5",
"deepmerge": "^4.2.2",
"leaflet": "^1.6.0",
"leaflet.heat": "^0.2.0",
"moment": "^2.24.0",
"moment": "^2.26.0",
"vue": "^2.6.11",
"vue-ctk-date-time-picker": "^2.4.0",
"vue-feather-icons": "^5.0.0",
"vue-i18n": "^8.15.3",
"vue-js-modal": "^1.3.31",
"vue-i18n": "^8.18.1",
"vue-js-modal": "^1.3.33",
"vue-mq": "^1.0.1",
"vue-outside-events": "^1.1.3",
"vue-router": "^3.1.5",
"vue2-leaflet": "^2.4.2",
"vuex": "^3.1.2"
"vue-router": "^3.3.2",
"vue2-leaflet": "^2.5.2",
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.1.2",
"@vue/cli-plugin-eslint": "^4.1.2",
"@vue/cli-plugin-unit-jest": "^4.1.2",
"@vue/cli-service": "^4.1.2",
"@vue/cli-plugin-babel": "~4.4.1",
"@vue/cli-plugin-eslint": "~4.4.1",
"@vue/cli-plugin-unit-jest": "~4.4.1",
"@vue/cli-service": "~4.4.1",
"@vue/eslint-config-prettier": "^6.0.0",
"@vue/test-utils": "1.0.0-beta.31",
"@vue/test-utils": "1.0.3",
"babel-core": "7.0.0-bridge.0",
"babel-eslint": "^10.0.3",
"babel-jest": "^25.1.0",
"cors-anywhere": "^0.4.1",
"eslint": "^6.8.0",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-vue": "^6.1.2",
"jest-fetch-mock": "^3.0.1",
"lint-staged": "^10.0.2",
"moment-locales-webpack-plugin": "^1.1.2",
"node-sass": "^4.13.1",
"babel-eslint": "^10.1.0",
"babel-jest": "^26.0.1",
"cors-anywhere": "^0.4.3",
"eslint": "^7.1.0",
"eslint-plugin-prettier": "^3.1.3",
"eslint-plugin-vue": "^6.2.2",
"jest-fetch-mock": "^3.0.3",
"lint-staged": "^10.2.7",
"moment-locales-webpack-plugin": "^1.2.0",
"node-sass": "^4.14.1",
"prettier": "^2.0.5",
"sass-loader": "^8.0.2",
"vue-cli-plugin-i18n": "^0.6.1",
"vue-cli-plugin-i18n": "~1.0.1",
"vue-template-compiler": "^2.6.11"
},
"license": "MIT",

View File

@@ -34,7 +34,7 @@ export default {
this.populateStateFromQuery(this.$route.query);
this.loadData();
// Update URL query params when relevant values changes
this.$store.subscribe(mutation => {
this.$store.subscribe((mutation) => {
if (
[
types.SET_SELECTED_USER,
@@ -73,7 +73,7 @@ export default {
selectedDevice: device,
} = this.$store.state;
const activeLayers = Object.keys(map.layers).filter(
key => map.layers[key] === true
(key) => map.layers[key] === true
);
const query = {
lat: map.center.lat,

View File

@@ -1,30 +1,23 @@
import config from "@/config";
import { log, logLevels } from "@/logging";
import { getApiUrl } from "@/util";
/** @typedef {import("./types").QueryParams} QueryParams */
/** @typedef {import("./types").User} User */
/** @typedef {import("./types").Device} Device */
/** @typedef {import("./types").LastLocation} LastLocation */
/** @typedef {import("./types").LocationHistory} LocationHistory */
/**
* Callback for new WebSocket location messages.
*
* @callback webSocketLocationCallback
*/
import { getApiUrl, getLocationHistoryCount } from "@/util";
/**
* Fetch an API resource.
*
* @param {String} path API resource path
* @param {QueryParams} [params] Query parameters
* @param {Object} [params] Query parameters
* @returns {Promise} Promise returned by the fetch function
*/
const fetchApi = (path, params = {}) => {
const url = getApiUrl(path);
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));
Object.keys(params).forEach((key) =>
url.searchParams.append(key, params[key])
);
log("HTTP", `GET ${url.href}`);
return fetch(url.href).catch(error => log("HTTP", error, logLevels.ERROR));
return fetch(url.href, config.api.fetchOptions).catch((error) =>
log("HTTP", error, logLevels.ERROR)
);
};
/**
@@ -36,38 +29,49 @@ export const getVersion = async () => {
const response = await fetchApi("/api/0/version");
const json = await response.json();
const version = json.version;
log("API", () => `[getVersion] ${version}`);
return version;
};
/**
* Get all users.
*
* @returns {Array.<User>} Array of usernames
* @returns {User[]} Array of usernames
*/
export const getUsers = async () => {
const response = await fetchApi("/api/0/list");
const json = await response.json();
const users = json.results;
log("API", () => `[getUsers] Fetched ${users.length} users`);
return users;
};
/**
* Get all devices for the provided users.
*
* @param {Array.<User>} users Array of usernames
* @returns {Object.<User, Array.<Device>>}
* @param {User[]} users Array of usernames
* @returns {{User: Device[]}}
* Object mapping each username to an array of device names
*/
export const getDevices = async users => {
export const getDevices = async (users) => {
const devices = {};
await Promise.all(
users.map(async user => {
users.map(async (user) => {
const response = await fetchApi(`/api/0/list`, { user });
const json = await response.json();
const userDevices = json.results;
devices[user] = userDevices;
})
);
log("API", () => {
const devicesCount = Object.keys(devices)
.map((user) => devices[user].length)
.reduce((a, b) => a + b, 0);
return (
`[getDevices] Fetched ${devicesCount} ` +
`devices for ${users.length} users`
);
});
return devices;
};
@@ -76,7 +80,7 @@ export const getDevices = async users => {
*
* @param {User} [user] Get last locations of all devices from this user
* @param {Device} [device] Get last location of specific device
* @returns {Array.<LastLocation>} Array of last location objects
* @returns {OTLocation[]} Array of last location objects
*/
export const getLastLocations = async (user, device) => {
const params = {};
@@ -88,7 +92,12 @@ export const getLastLocations = async (user, device) => {
}
const response = await fetchApi("/api/0/last", params);
const json = await response.json();
return json;
const lastLocations = json;
log(
"API",
() => `[getLastLocations] Fetched ${lastLocations.length} last locations`
);
return lastLocations;
};
/**
@@ -98,7 +107,7 @@ export const getLastLocations = async (user, device) => {
* @param {Device} device Device name
* @param {String} start Start date and time in UTC
* @param {String} end End date and time in UTC
* @returns {LocationHistory} Array of location history objects
* @returns {OTLocation[]} Array of location history objects
*/
export const getUserDeviceLocationHistory = async (
user,
@@ -114,26 +123,33 @@ export const getUserDeviceLocationHistory = async (
format: "json",
});
const json = await response.json();
return json.data;
const userDeviceLocationHistory = json.data;
log(
"API",
() =>
`[getUserDeviceLocationHistory] Fetched ` +
`${userDeviceLocationHistory.length} locations for ` +
`${user}/${device} from ${start} - ${end}`
);
return userDeviceLocationHistory;
};
/**
* Get the location history of multiple devices.
*
* @param {Object.<User, Array.<Device>>} devices
* @param {{User: Device[]}} devices
* Devices of which the history should be fetched
* @param {String} start Start date and time in UTC
* @param {String} end End date and time in UTC
* @returns {Object.<User, Object.<Device, LocationHistory>>}
* Array of location history objects
* @returns {LocationHistory} Location history
*/
export const getLocationHistory = async (devices, start, end) => {
const locationHistory = {};
await Promise.all(
Object.keys(devices).map(async user => {
Object.keys(devices).map(async (user) => {
locationHistory[user] = {};
await Promise.all(
devices[user].map(async device => {
devices[user].map(async (device) => {
locationHistory[user][device] = await getUserDeviceLocationHistory(
user,
device,
@@ -144,6 +160,13 @@ export const getLocationHistory = async (devices, start, end) => {
);
})
);
log("API", () => {
const locationHistoryCount = getLocationHistoryCount(locationHistory);
return (
"[getLocationHistory] Fetched " +
`${locationHistoryCount} locations in total`
);
});
return locationHistory;
};
@@ -151,9 +174,9 @@ export const getLocationHistory = async (devices, start, end) => {
* Connect to the WebSocket API, reconnect when necessary and handle received
* messages.
*
* @param {webSocketLocationCallback} [callback] Callback for location messages
* @param {WebSocketLocationCallback} [callback] Callback for location messages
*/
export const connectWebsocket = async callback => {
export const connectWebsocket = async (callback) => {
let url = getApiUrl("/ws/last");
url.protocol = url.protocol.replace("http", "ws");
url = url.href;
@@ -163,16 +186,17 @@ export const connectWebsocket = async callback => {
log("WS", "Connected");
ws.send("LAST");
};
ws.onclose = event => {
ws.onclose = (event) => {
log(
"WS",
`Disconnected unexpectedly (reason: ${event.reason ||
"unknown"}). Reconnecting in one second.`,
`Disconnected unexpectedly (reason: ${
event.reason || "unknown"
}). Reconnecting in one second.`,
logLevels.WARNING
);
setTimeout(connectWebsocket, 1000);
};
ws.onmessage = async msg => {
ws.onmessage = async (msg) => {
if (msg.data) {
try {
const data = JSON.parse(msg.data);

View File

@@ -1,7 +1,25 @@
<template>
<header>
<nav>
<header :class="$mq === 'sm' ? 'header-sm' : null">
<div v-if="$mq === 'sm'" class="header-item">
<button
class="button button-flat button-icon"
@click="showMobileNav = !showMobileNav"
>
<MenuIcon size="1x" aria-hidden="true" role="img" />
</button>
</div>
<nav
v-if="$mq === 'sm' ? showMobileNav : true"
class="header-item header-item-grow"
:class="$mq === 'sm' ? 'nav-sm' : null"
>
<div class="nav-item">
<CrosshairIcon
v-if="$mq === 'sm'"
size="1x"
aria-hidden="true"
role="img"
/>
<button
class="button button-outline"
:title="
@@ -46,7 +64,7 @@
:title="$t('Select start date')"
/>
</VueCtkDateTimePicker>
{{ $t("to") }}
<span>{{ $t("to") }}</span>
<VueCtkDateTimePicker
v-model="endDateTime"
:format="DATE_TIME_FORMAT"
@@ -97,16 +115,13 @@
</select>
</div>
</nav>
<nav class="nav-shrink">
<nav class="header-item header-item-right">
<div
class="nav-item"
v-if="$config.showDistanceTravelled && distanceTravelled"
class="nav-item"
:title="$t('Distance travelled')"
>
{{
$t("Distance travelled: {distance}", {
distance: humanReadableDistance(distanceTravelled),
})
}}
{{ humanReadableDistance(distanceTravelled) }}
</div>
<div class="nav-item">
<button
@@ -139,9 +154,11 @@ import moment from "moment";
import { mapActions, mapGetters, mapMutations, mapState } from "vuex";
import {
CalendarIcon,
CrosshairIcon,
DownloadIcon,
InfoIcon,
LayersIcon,
MenuIcon,
SmartphoneIcon,
UserIcon,
} from "vue-feather-icons";
@@ -156,9 +173,11 @@ import { humanReadableDistance } from "@/util";
export default {
components: {
CalendarIcon,
CrosshairIcon,
DownloadIcon,
InfoIcon,
LayersIcon,
MenuIcon,
SmartphoneIcon,
UserIcon,
VueCtkDateTimePicker,
@@ -173,6 +192,7 @@ export default {
{ layer: "points", label: this.$t("Show location history (points)") },
{ layer: "heatmap", label: this.$t("Show location heatmap") },
],
showMobileNav: false,
};
},
computed: {
@@ -202,9 +222,7 @@ export default {
},
set(value) {
this.setStartDateTime(
moment(value, DATE_TIME_FORMAT)
.utc()
.format(DATE_TIME_FORMAT)
moment(value, DATE_TIME_FORMAT).utc().format(DATE_TIME_FORMAT)
);
},
},

View File

@@ -0,0 +1,19 @@
/* eslint-disable max-len */
const svg = `
<svg
xmlns="http://www.w3.org/2000/svg"
width="691.429"
height="1007.429"
viewBox="0 0 182.94 266.549"
>
<path
d="M182.94 91.47c0 50.518-55.748 139.357-91.47 175.079C55.75 230.827 0 141.988 0 91.47 0 40.953 40.953 0 91.47 0c50.518 0 91.47 40.953 91.47 91.47z"
/>
</svg>
`;
/* eslint-enable */
export default L.divIcon({
className: "",
html: `<span class="pin">${svg}</span>`,
});

View File

@@ -94,7 +94,7 @@ export default {
this.parentContainer.addLayer(this, !this.visible);
this.$watch(
"latLng",
newVal => {
(newVal) => {
this.mapObject.setLatLngs(newVal);
},
{ deep: true }

View File

@@ -10,17 +10,17 @@ startDateTime.setHours(0, 0, 0, 0);
const DEFAULT_CONFIG = {
api: {
baseUrl: `${window.location.protocol}//${window.location.host}`,
fetchOptions: {},
},
endDateTime,
filters: {
minAccuracy: null,
},
ignorePingLocation: true,
locale: "en",
map: {
attribution:
'&copy; <a href="https://osm.org/copyright">OpenStreetMap</a> contributors',
center: {
lat: 0,
lng: 0,
},
circle: {
color: null,
fillColor: null,
@@ -65,7 +65,6 @@ const DEFAULT_CONFIG = {
fillColor: "transparent",
},
url: "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
zoom: 19,
},
onLocationChange: {
reloadHistory: false,

View File

@@ -7,7 +7,7 @@ Vue.use(VueI18n);
const locales = require.context("./locales", true, /[A-Za-z0-9-_,\s]+\.json$/i);
const messages = {};
locales.keys().forEach(key => {
locales.keys().forEach((key) => {
const matched = key.match(/([A-Za-z0-9-_]+)\./i);
if (matched && matched.length > 1) {
const locale = matched[1];

223
src/index.d.ts vendored Normal file
View File

@@ -0,0 +1,223 @@
/** Configuration object. */
interface Config {
api: {
baseUrl: string;
};
endDateTime: Date;
ignorePingLocation: boolean;
locale: string;
map: {
attribution: string;
circle: {
color: OptionalColor;
fillColor: OptionalColor;
fillOpacity: number;
};
circleMarker: {
color: OptionalColor;
fillColor: OptionalColor;
fillOpacity: number;
radius: number;
};
controls: {
scale: {
display: boolean;
imperial: boolean;
maxWidth: number;
metric: boolean;
position: string;
};
zoom: {
display: boolean;
position: string;
};
};
heatmap: {
blur: number;
gradient: { number: Color } | null;
max: number;
radius: number;
};
layers: {
heatmap: boolean;
last: boolean;
line: boolean;
points: boolean;
};
maxNativeZoom: number;
maxPointDistance: number | null;
maxZoom: number;
polyline: {
color: OptionalColor;
fillColor: OptionalColor;
};
url: string;
};
onLocationChange: {
reloadHistory: boolean;
};
primaryColor: Color;
selectedUser: User| null;
selectedDevice: Device| null;
startDateTime: Date;
verbose: boolean;
}
/** Vuex state. */
interface State {
isLoading: boolean;
frontendVersion: string;
recorderVersion: string;
users: User[];
devices: { User: Device[] };
lastLocations: OTLocation[];
locationHistory: LocationHistory;
selectedUser: User| null;
selectedDevice: Device| null;
startDateTime: string;
endDateTime: string;
map: {
center: {
lat: number;
lng: number;
};
layers: {
heatmap: boolean;
last: boolean;
line: boolean;
points: boolean;
};
zoom: number;
};
}
/**
* A location object as returned by the OwnTracks recorder.
* https://owntracks.org/booklet/tech/json/#_typelocation
*/
interface OTLocation {
_http: boolean;
/**
* In this case always "location"
* https://owntracks.org/booklet/tech/json/#types
*/
_type: string;
/** Accuracy in meters */
acc?: number;
/** Altitude above sea level in meters */
alt?: number;
/** Device battery level in percent */
batt?: number;
/**
* Battery status (iOS only)
*
* - `0` = unknown
* - `1` = unplugged
* - `2` = charging
* - `3` = full
*/
bs?: number;
/** Course over ground in degrees (iOS only) */
cog?: number;
/**
* Internet connectivity status (route to host) when the message is created
*
* - `"w"` = phone is connected to a WiFi connection
* - `"o"` = phone is offline
* - `"m"` = mobile data
*/
conn?: string;
/** Device name */
device?: Device;
/** Timestamp in a readable format */
disptst: string;
/** Base64-encoded face image (device icon) */
face?: string;
/**
* Geohash of the location
* https://en.wikipedia.org/wiki/Geohash
*/
ghash?: string;
/** Regions the device is currently in (e.g. `["Home", "Garage"]`). Might be empty. */
inregions?: string[];
/**
* No idea; some kind of timestamp as well - figure it out yourself. :)
* https://github.com/owntracks/recorder/blob/df009f791a845012e9cce24923e6203a079ca1ed/storage.c#L659
* https://github.com/owntracks/recorder/blob/df009f791a845012e9cce24923e6203a079ca1ed/storage.c#L704
*/
isorcv?: string;
/** ISO 8601 timestamp */
isotst?: string;
/** Latitude in degrees */
lat: number;
/** Longitude in degrees */
lon: number;
/** Friendly device name */
name?: string;
/**
* Trigger for the location report
*
* - `"p"` = ping issued randomly by background task
* - `"c"` = circular region enter/leave event
* - `"b"` = beacon region enter/leave event (iOS only)
* - `"r"` = response to a reportLocation cmd message
* - `"u"` = manual publish requested by the user
* - `"t"` = timer based publish in move move (iOS only)
* - `"v"` = updated by Settings/Privacy/Locations Services/System Services/Frequent Locations monitoring (iOS only)
*/
t?: string;
/** Tracker ID used to display the initials of a user */
tid?: string;
/**
* Original publish topic
* https://owntracks.org/booklet/tech/json/#topics
*/
topic?: string;
/** UNIX epoch timestamp of the location fix in seconds */
tst: number;
/** User */
username?: User;
/** Vertical accuracy of the alt element in meters */
vac?: number;
/** Velocity in km/h */
vel?: number;
}
/** URL query parameters (prior to any parsing so it's all strings). */
interface QueryParams {
/** Map center latitude */
lat?: string;
/** Map center longitude */
lng?: string;
/** Start date and time of selected time range */
start?: string;
/** End date and time of selected time range */
end?: string;
/** Selected user */
user?: string;
/** Selected device */
device?: string;
/** Comma-separated list of active layers */
layers?: string;
}
/** Callback for new WebSocket location messages. */
interface WebSocketLocationCallback { (): void }
/** Function for lazy evaluation of log messages. */
interface LogMessageFunction { (): string }
/** A CSS color. */
type Color = string;
/** A CSS color that will use `primaryColor` as fallback. */
type OptionalColor = Color | null;
/** A user's name. */
type User = string;
/** A device's name. */
type Device = string;
/** Multiple location histories mapped to user and devices. */
type LocationHistory = { User: { Device: OTLocation[] } };

View File

@@ -10,7 +10,7 @@
"Select user": "Benutzer auswählen",
"Show all": "Alle anzeigen",
"Select device": "Gerät auswählen",
"Distance travelled: {distance}": "Gereiste Entfernung: {distance}",
"Distance travelled": "Gereiste Entfernung",
"Download raw data": "Rohdaten herunterladen",
"Information": "Information",
"Show last known locations": "Zeige letzte bekannte Standorte",

View File

@@ -10,7 +10,7 @@
"Select user": "Select user",
"Show all": "Show all",
"Select device": "Select device",
"Distance travelled: {distance}": "Distance travelled: {distance}",
"Distance travelled": "Distance travelled",
"Download raw data": "Download raw data",
"Information": "Information",
"Show last known locations": "Show last known locations",

33
src/locales/es.json Normal file
View File

@@ -0,0 +1,33 @@
{
"Automatically center the map view and zoom in to relevant data": "Centrar automáticamente el zoom y la vista del mapa a los datos",
"Fit view": "Ajustar vista",
"Layer settings": "Configuración de capas",
"Show/hide layers": "Mostrar/ocultar capas",
"Now": "Ahora",
"Select start date": "Seleccionar fecha inicio",
"to": "hasta",
"Select end date": "Seleccionar fecha fin",
"Select user": "Seleccionar usuario",
"Show all": "Mostrar todos",
"Select device": "Seleccionar dispositivo",
"Distance travelled": "Distancia recorrida",
"Download raw data": "Descargar datos en crudo",
"Information": "Información",
"Show last known locations": "Mostrar última ubicación conocida",
"Show location history (line)": "Mostrar historial (línea)",
"Show location history (points)": "Mostrar historial (puntos)",
"Show location heatmap": "Mostra mapa de calor",
"Minify JSON": "Reducir JSON",
"Copy to clipboard": "Copiar al portapapeles",
"Download": "Descarga",
"OwnTracks website": "OwnTracks - Sitio web",
"OwnTracks documentation": "OwnTracks - documentación",
"OwnTracks on Twitter": "OwnTracks en Twitter",
"Loading data, please wait...": "Cargando datos, por favor, espera...",
"Image of {deviceName}": "Imágen de {deviceName}",
"Timestamp": "Fecha / Hora",
"Location": "Ubicación",
"Address": "Dirección",
"Battery": "Bateria",
"Speed": "Velocidad"
}

View File

@@ -20,6 +20,16 @@ const logColors = {
[logLevels.ERROR]: "#ad1515",
};
/**
* Log a message to the browser's console.
*
* Convenience wrapper for `console.{info,warn,error}` doing some formatting
* and taking the `verbose` config option into account.
*
* @param {String} label Log message label, useful for filtering
* @param {String|LogMessageFunction} message Log message
* @param {String} [level] Log level, use `logLevels` constants
*/
export const log = (label, message, level = logLevels.INFO) => {
if (!Object.keys(logLevels).includes(level)) {
log("WARNING", `invalid log level: ${level}`, logLevels.WARNING);
@@ -35,5 +45,9 @@ export const log = (label, message, level = logLevels.INFO) => {
padding: 3px;
`;
const logFunc = logFunctions[level];
logFunc(`%c${label}`, css, message);
logFunc(
`%c${label}`,
css,
typeof message === "function" ? message() : message
);
};

View File

@@ -1,22 +1,33 @@
import Vue from "vue";
import VueModal from "vue-js-modal";
import VueOutsideEvents from "vue-outside-events";
import VueMq from "vue-mq";
import App from "@/App.vue";
import config from "@/config";
import { log } from "@/logging";
import i18n from "@/i18n";
import router from "@/router";
import store from "@/store";
import VModal from "vue-js-modal";
import VOutsideEvents from "vue-outside-events";
Vue.use(VModal);
Vue.use(VOutsideEvents);
Vue.use(VueModal);
Vue.use(VueOutsideEvents);
Vue.use(VueMq, {
breakpoints: {
sm: 1300,
lg: Infinity,
},
});
Vue.config.productionTip = false;
log("CONFIG", config);
Vue.prototype.$config = config;
new Vue({
i18n,
router,
store,
render: h => h(App),
render: (h) => h(App),
}).$mount("#app");

View File

@@ -1,11 +1,12 @@
import * as types from "@/store/mutation-types";
import * as api from "@/api";
import config from "@/config";
import { distanceBetweenCoordinates, isIsoDateTime } from "@/util";
/** @typedef {import("./types").QueryParams} QueryParams */
/** @typedef {import("./types").User} User */
/** @typedef {import("./types").Device} Device */
import { log } from "@/logging";
import {
distanceBetweenCoordinates,
isIsoDateTime,
getLocationHistoryCount,
} from "@/util";
/**
* Populate the state from URL query parameters.
@@ -42,7 +43,7 @@ const populateStateFromQuery = ({ state, commit }, query) => {
}
if (query.layers) {
const activeLayers = query.layers.split(",");
Object.keys(state.map.layers).forEach(layer => {
Object.keys(state.map.layers).forEach((layer) => {
const visibility = activeLayers.includes(layer);
if (state.map.layers[layer] !== visibility) {
commit(types.SET_MAP_LAYER_VISIBILITY, { layer, visibility });
@@ -115,19 +116,25 @@ const getLastLocations = async ({ commit, state }) => {
// Remove ping/ping from the owntracks/recorder Docker image
// https://github.com/owntracks/frontend/issues/12
lastLocations = lastLocations.filter(
l => !(l.username === "ping" && l.device === "ping")
(l) => !(l.username === "ping" && l.device === "ping")
);
}
commit(types.SET_LAST_LOCATIONS, lastLocations);
};
const _getDistanceTravelled = locationHistory => {
const _getDistanceTravelled = (locationHistory) => {
const start = Date.now();
let distanceTravelled = 0;
Object.keys(locationHistory).forEach(user => {
Object.keys(locationHistory[user]).forEach(device => {
Object.keys(locationHistory).forEach((user) => {
Object.keys(locationHistory[user]).forEach((device) => {
let lastLatLng = null;
locationHistory[user][device].forEach(coordinate => {
const latLng = L.latLng(coordinate.lat, coordinate.lon);
locationHistory[user][device].forEach((location) => {
if (
config.filters.minAccuracy !== null &&
location.acc > config.filters.minAccuracy
)
return;
const latLng = L.latLng(location.lat, location.lon);
if (lastLatLng !== null) {
const distance = distanceBetweenCoordinates(lastLatLng, latLng);
if (
@@ -147,6 +154,15 @@ const _getDistanceTravelled = locationHistory => {
});
});
});
const end = Date.now();
log("DISTANCE", () => {
const locationHistoryCount = getLocationHistoryCount(locationHistory);
const duration = (end - start) / 1000;
return (
`[_getDistanceTravelled] Took ${duration} seconds to ` +
`calculate distance of ${locationHistoryCount} locations`
);
});
return distanceTravelled;
};

View File

@@ -3,25 +3,47 @@ import L from "leaflet";
import config from "@/config";
import { distanceBetweenCoordinates } from "@/util";
/** @typedef {import("./types").State} State */
/** @typedef {import("./types").MultiLocationHistory} MultiLocationHistory */
/** @typedef {import("./types").DatepickerConfig} DatepickerConfig */
/**
* Apply filters to the selected users' and devices' location histories.
*
* @param {State} state
* @param {LocationHistory} state.locationHistory
* Location history of selected users and devices
* @returns {LocationHistory} Filtered location history
*/
const filteredLocationHistory = (state) => {
const locationHistory = {};
Object.keys(state.locationHistory).forEach((user) => {
locationHistory[user] = {};
Object.keys(state.locationHistory[user]).forEach((device) => {
locationHistory[user][device] = [];
state.locationHistory[user][device].forEach((location) => {
if (
config.filters.minAccuracy !== null &&
location.acc > config.filters.minAccuracy
)
return;
locationHistory[user][device].push(location);
});
});
});
return locationHistory;
};
/**
* From the selected users' and devices' location histories, create an
* array of all coordinates.
*
* @param {State} state
* @param {MultiLocationHistory} state.locationHistory
* Location history of selected users and devices
* @returns {Array.<L.LatLng>} All coordinates
* @returns {L.LatLng[]} All coordinates
*/
const locationHistoryLatLngs = state => {
const filteredLocationHistoryLatLngs = (state) => {
const latLngs = [];
Object.keys(state.locationHistory).forEach(user => {
Object.keys(state.locationHistory[user]).forEach(device => {
state.locationHistory[user][device].forEach(coordinate => {
latLngs.push(L.latLng(coordinate.lat, coordinate.lon));
const locationHistory = filteredLocationHistory(state);
Object.keys(locationHistory).forEach((user) => {
Object.keys(locationHistory[user]).forEach((device) => {
locationHistory[user][device].forEach((location) => {
latLngs.push(L.latLng(location.lat, location.lon));
});
});
});
@@ -34,17 +56,16 @@ const locationHistoryLatLngs = state => {
* coordinates does not exceed `config.map.maxPointDistance`.
*
* @param {State} state
* @param {MultiLocationHistory} state.locationHistory
* Location history of selected users and devices
* @returns {Array.<Array.<L.LatLng>>} Groups of coherent coordinates
* @returns {L.LatLng[][]} Groups of coherent coordinates
*/
const locationHistoryLatLngGroups = state => {
const filteredLocationHistoryLatLngGroups = (state) => {
const groups = [];
Object.keys(state.locationHistory).forEach(user => {
Object.keys(state.locationHistory[user]).forEach(device => {
const locationHistory = filteredLocationHistory(state);
Object.keys(locationHistory).forEach((user) => {
Object.keys(locationHistory[user]).forEach((device) => {
let latLngs = [];
state.locationHistory[user][device].forEach(coordinate => {
const latLng = L.latLng(coordinate.lat, coordinate.lon);
locationHistory[user][device].forEach((location) => {
const latLng = L.latLng(location.lat, location.lon);
// Skip if group splitting is disabled or this is the first
// coordinate in the current group
if (
@@ -72,6 +93,7 @@ const locationHistoryLatLngGroups = state => {
};
export default {
locationHistoryLatLngs,
locationHistoryLatLngGroups,
filteredLocationHistory,
filteredLocationHistoryLatLngs,
filteredLocationHistoryLatLngGroups,
};

View File

@@ -23,8 +23,11 @@ export default new Vuex.Store({
startDateTime: config.startDateTime.toISOString().slice(0, 19),
endDateTime: config.endDateTime.toISOString().slice(0, 19),
map: {
center: config.map.center,
zoom: config.map.zoom,
center: {
lat: 0,
lng: 0,
},
zoom: 19,
layers: config.map.layers,
},
distanceTravelled: null,

View File

@@ -11,6 +11,7 @@
--color-primary-text: #fff;
--drop-shadow: drop-shadow(0 10px 10px rgb(0, 0, 0, 0.2));
--dropdown-arrow: url("data:image/svg+xml;utf8,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2225%22%20height%3D%2210%22%3E%3Cpath%20fill%3D%22%23333%22%20fill-opacity%3D%221%22%20stroke%3D%22none%22%20d%3D%22M0%2C0%20L0%2C0%20L1%2C0%20L1%2C6%20L7%2C6%20L7%2C7%20L0%2C7%20z%22%20transform%3D%22rotate(-45%205%200)%22%20%2F%3E%3C%2Fsvg%3E");
--pin-width: 32px;
}
html, body {
@@ -105,30 +106,106 @@ pre {
color: var(--color-primary-text);
background: var(--color-primary);
nav {
&.header-sm {
padding: 10px;
.header-item:not(.nav-sm) .nav-item:not(:first-child) {
margin-left: 10px;
}
}
.header-item {
display: flex;
flex: 1;
align-items: center;
&:not(:first-child) {
margin-left: 20px;
}
&.nav-shrink {
flex: 0 1 auto;
&-grow {
flex: 1;
}
.nav-item:not(:first-child) {
margin-left: 20px;
&-right {
margin-left: auto !important;
}
.feather {
font-size: 20px;
margin-right: 10px;
}
.button-icon .feather {
.nav-item {
&:not(:first-child) {
margin-left: 20px;
}
> span {
margin: 0 5px;
}
.feather {
margin-right: 10px;
}
.button-icon .feather {
margin: 0;
}
}
&.nav-sm {
background: var(--color-primary);
border-top: 1px solid rgba(0, 0, 0, 0.2);
bottom: 0;
display: block;
left: 0;
margin: 0;
overflow-x: auto;
padding: 20px;
position: absolute;
right: 0;
top: 56px;
z-index: 1;
.nav-item {
align-items: center;
display: flex;
flex-wrap: wrap;
margin-left: auto;
margin-right: auto;
max-width: 400px;
&:not(:first-child) {
margin-top: 20px;
}
> .button,
> .dropdown,
> .date-time-picker {
flex: 1;
}
> .dropdown .dropdown-button,
> .date-time-picker .dropdown-button {
width: 100%;
}
> .date-time-picker {
margin-left: 0;
margin-right: 0;
}
> span {
flex-basis: 100%;
margin: 0;
}
// THIS IS TERRIBLE (but it works for now)
> :not(:nth-child(1)):not(:nth-child(2)) {
display: block;
margin-left: 30px;
margin-top: 5px;
}
}
}
}
}
@@ -172,8 +249,8 @@ pre {
overflow: hidden;
padding: 8px 16px;
text-overflow: ellipsis;
white-space: nowrap;
transition: box-shadow 0.2s;
white-space: nowrap;
&:focus {
outline: none;

View File

@@ -6,5 +6,14 @@
box-shadow: none !important;
filter: var(--drop-shadow);
margin-top: 5px;
@media screen and (max-width: 415px) {
// Fix buttons being off screen
.datepicker-buttons-container {
bottom: 0;
position: absolute;
width: 100%;
}
}
}
}

View File

@@ -4,7 +4,7 @@
.leaflet-popup {
filter: var(--drop-shadow);
margin-bottom: 25px;
margin-bottom: calc(var(--pin-width) * 1.5 + 20px);
.leaflet-popup-content-wrapper {
border-radius: 3px;
@@ -44,4 +44,38 @@
color: var(--color-primary);
}
}
.leaflet-marker-icon {
width: 0 !important;
height: 0 !important;
margin: 0 !important;
.pin {
display: block;
margin-left: calc(-1 * var(--pin-width) / 2);
margin-top: calc(-1 * var(--pin-width) * 1.5);
position: relative;
width: var(--pin-width);
&::before {
background: var(--color-background);
border-radius: 100%;
content: "";
position: absolute;
width: calc(var(--pin-width) / 2);
height: calc(var(--pin-width) / 2);
top: calc(var(--pin-width) / 4);
left: calc(var(--pin-width) / 4);
}
svg {
height: auto;
width: 100%;
path {
fill: var(--color-primary);
}
}
}
}
}

View File

@@ -1,57 +0,0 @@
/* eslint max-len: 0 */
/**
* A coordinate with latitude and longitude.
*
* @typedef Coordinate
* @type {(Object|L.LatLng)}
* @property {Number} lat Latitude
* @property {Number} lng Longitude
*/
/**
* Vuex state.
*
* @typedef {Object.<String, *>} State
*/
/**
* URL query parameter object.
*
* @typedef {Object.<String, *>} QueryParams
*/
/**
* @typedef {Object} DatepickerConfig
* @property {Function} DatepickerConfig.customPredictor Custom predictor function
*/
/**
* A user's name.
*
* @typedef {String} User
*/
/**
* A device's name.
*
* @typedef {String} Device
*/
/**
* A last location object.
*
* @typedef {Object.<String, *>} LastLocation
*/
/**
* An array of location history objects
*
* @typedef {Array.<Object.<String, *>>} LocationHistory
*/
/**
* Multiple arrays of location history objects mapped to user and devices.
*
* @typedef {Object.<User, Object.<Device, LocationHistory>>} MultiLocationHistory
*/

View File

@@ -3,8 +3,6 @@ import moment from "moment";
import config from "@/config";
import { DATE_TIME_FORMAT, EARTH_RADIUS_IN_KM } from "@/constants";
/** @typedef {import("./types").Coordinate} Coordinate */
/**
* Get a complete URL for any API resource, taking the
* base URL configuration into account.
@@ -12,7 +10,7 @@ import { DATE_TIME_FORMAT, EARTH_RADIUS_IN_KM } from "@/constants";
* @param {String} path Path to the API resource
* @returns {URL} Final API URL
*/
export const getApiUrl = path => {
export const getApiUrl = (path) => {
const normalizedBaseUrl = config.api.baseUrl.endsWith("/")
? config.api.baseUrl.slice(1)
: config.api.baseUrl;
@@ -26,7 +24,7 @@ export const getApiUrl = path => {
* @param {String} s Input value to be tested
* @returns {Boolean} Whether the input matches the expected format
*/
export const isIsoDateTime = s => moment(s, DATE_TIME_FORMAT, true).isValid();
export const isIsoDateTime = (s) => moment(s, DATE_TIME_FORMAT, true).isValid();
/**
* Convert degrees to radians.
@@ -34,7 +32,7 @@ export const isIsoDateTime = s => moment(s, DATE_TIME_FORMAT, true).isValid();
* @param {Number} degrees Angle in degrees
* @returns {Number} Angle in radians
*/
export const degreesToRadians = degrees => (degrees * Math.PI) / 180;
export const degreesToRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* Calculate the distance between two coordinates. Uses the haversine formula,
@@ -91,9 +89,9 @@ export const download = (text, filename, mimeType = "text/plain") => {
* ft / mi.
*
* @param {Number} distance Distance in meters
* @param {String} [mimeType] Formatted string including unit
* @returns {String} Formatted string including unit
*/
export const humanReadableDistance = distance => {
export const humanReadableDistance = (distance) => {
let unit = "m";
if (Math.abs(distance) >= 1000) {
distance = distance / 1000;
@@ -103,3 +101,18 @@ export const humanReadableDistance = distance => {
maximumFractionDigits: 1,
})} ${unit}`;
};
/**
* Get the total number of locations from a nested location history.
*
* @param {LocationHistory} locationHistory Location history
* @returns {Number} Total number of locations
*/
export const getLocationHistoryCount = (locationHistory) =>
Object.keys(locationHistory)
.map((user) =>
Object.keys(locationHistory[user])
.map((device) => locationHistory[user][device].length)
.reduce((a, b) => a + b, 0)
)
.reduce((a, b) => a + b, 0);

View File

@@ -37,6 +37,7 @@
v-for="l in lastLocations"
:key="`${l.topic}-marker`"
:lat-lng="[l.lat, l.lon]"
:icon="markerIcon"
>
<LDeviceLocationPopup
:user="l.username"
@@ -55,7 +56,7 @@
<template v-if="map.layers.line">
<LPolyline
v-for="(group, i) in locationHistoryLatLngGroups"
v-for="(group, i) in filteredLocationHistoryLatLngGroups"
:key="i"
:lat-lngs="group"
v-bind="polyline"
@@ -63,7 +64,7 @@
</template>
<template v-if="map.layers.points">
<template v-for="(userDevices, user) in locationHistory">
<template v-for="(userDevices, user) in filteredLocationHistory">
<template v-for="(deviceLocations, device) in userDevices">
<LCircleMarker
v-for="(l, n) in deviceLocationsWithNameAndFace(
@@ -94,8 +95,8 @@
<template v-if="map.layers.heatmap">
<LHeatmap
v-if="locationHistoryLatLngs.length"
:lat-lng="locationHistoryLatLngs"
v-if="filteredLocationHistoryLatLngs.length"
:lat-lng="filteredLocationHistoryLatLngs"
:max="heatmap.max"
:radius="heatmap.radius"
:blur="heatmap.blur"
@@ -119,22 +120,11 @@ import {
LPolyline,
} from "vue2-leaflet";
import "leaflet/dist/leaflet.css";
import markerIcon from "leaflet/dist/images/marker-icon.png";
import markerIcon2x from "leaflet/dist/images/marker-icon-2x.png";
import markerShadow from "leaflet/dist/images/marker-shadow.png";
import * as types from "@/store/mutation-types";
import LCustomMarker from "@/components/LCustomMarker";
import LHeatmap from "@/components/LHeatmap";
import LDeviceLocationPopup from "@/components/LDeviceLocationPopup";
// See https://github.com/KoRiGaN/Vue2Leaflet/issues/28#issuecomment-299038157
delete L.Icon.Default.prototype._getIconUrl;
L.Icon.Default.mergeOptions({
iconUrl: markerIcon,
iconRetinaUrl: markerIcon2x,
shadowUrl: markerShadow,
});
export default {
components: {
LMap,
@@ -154,6 +144,7 @@ export default {
center: this.$store.state.map.center,
controls: this.$config.map.controls,
heatmap: this.$config.map.heatmap,
markerIcon: LCustomMarker,
maxZoom: this.$config.map.maxZoom,
maxNativeZoom: this.$config.map.maxNativeZoom,
url: this.$config.map.url,
@@ -180,8 +171,12 @@ export default {
});
},
computed: {
...mapGetters(["locationHistoryLatLngs", "locationHistoryLatLngGroups"]),
...mapState(["lastLocations", "locationHistory", "map"]),
...mapGetters([
"filteredLocationHistory",
"filteredLocationHistoryLatLngs",
"filteredLocationHistoryLatLngGroups",
]),
...mapState(["lastLocations", "map"]),
},
methods: {
...mapMutations({
@@ -196,13 +191,13 @@ export default {
(this.map.layers.line ||
this.map.layers.points ||
this.map.layers.heatmap) &&
this.locationHistoryLatLngs.length > 0
this.filteredLocationHistoryLatLngs.length > 0
) {
this.$refs.map.mapObject.fitBounds(
new L.LatLngBounds(this.locationHistoryLatLngs)
new L.LatLngBounds(this.filteredLocationHistoryLatLngs)
);
} else if (this.map.layers.last && this.lastLocations.length > 0) {
const locations = this.lastLocations.map(l => L.latLng(l.lat, l.lon));
const locations = this.lastLocations.map((l) => L.latLng(l.lat, l.lon));
this.$refs.map.mapObject.fitBounds(new L.LatLngBounds(locations), {
maxZoom: this.maxNativeZoom,
});
@@ -215,22 +210,30 @@ export default {
*
* @param {User} user Username
* @param {Device} device Device name
* @param {LocationHistory} deviceLocations Device name
* @returns {LocationHistory} Updated location history
* @param {OTLocation[]} deviceLocations Device name
* @returns {OTLocation[]} Updated locations
*/
deviceLocationsWithNameAndFace(user, device, deviceLocations) {
const lastLocation = this.lastLocations.find(
l => l.username === user && l.device === device
(l) => l.username === user && l.device === device
);
if (!lastLocation) {
return deviceLocations;
}
return deviceLocations.map(l => ({
return deviceLocations.map((l) => ({
...l,
name: lastLocation.name,
face: lastLocation.face,
}));
},
},
watch: {
lastLocations() {
this.fitView();
},
filteredLocationHistory() {
this.fitView();
},
},
};
</script>

5200
yarn.lock

File diff suppressed because it is too large Load Diff