aboutsummaryrefslogtreecommitdiff
path: root/modern/src/SocketController.js
diff options
context:
space:
mode:
authorAnton Tananaev <anton.tananaev@gmail.com>2020-03-22 23:07:16 -0700
committerGitHub <noreply@github.com>2020-03-22 23:07:16 -0700
commit48a726021f5d3c741749094891d529ccb3ba59b4 (patch)
tree8df80eca54f9dd39664f63365ffcc2ec248fb3df /modern/src/SocketController.js
parentf5165c8e897e8d9cf4219d943e2d34b61adb48b5 (diff)
parentba9cc86f667486a09edb323402c2d63ada5ea639 (diff)
downloadtrackermap-web-48a726021f5d3c741749094891d529ccb3ba59b4.tar.gz
trackermap-web-48a726021f5d3c741749094891d529ccb3ba59b4.tar.bz2
trackermap-web-48a726021f5d3c741749094891d529ccb3ba59b4.zip
Merge pull request #768 from traccar/modern
Create a new React web app
Diffstat (limited to 'modern/src/SocketController.js')
-rw-r--r--modern/src/SocketController.js61
1 files changed, 61 insertions, 0 deletions
diff --git a/modern/src/SocketController.js b/modern/src/SocketController.js
new file mode 100644
index 00000000..b89845f2
--- /dev/null
+++ b/modern/src/SocketController.js
@@ -0,0 +1,61 @@
+import { Component } from 'react';
+import { connect } from 'react-redux';
+import { updateDevices, updatePositions } from './actions';
+
+const displayNotifications = events => {
+ if ("Notification" in window) {
+ if (Notification.permission === "granted") {
+ for (const event of events) {
+ const notification = new Notification(`Event: ${event.type}`);
+ setTimeout(notification.close.bind(notification), 4 * 1000);
+ }
+ } else if (Notification.permission !== "denied") {
+ Notification.requestPermission(permission => {
+ if (permission === "granted") {
+ displayNotifications(events);
+ }
+ });
+ }
+ }
+};
+
+class SocketController extends Component {
+ connectSocket() {
+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
+ const socket = new WebSocket(protocol + '//' + window.location.host + '/api/socket');
+
+ socket.onclose = () => {
+ setTimeout(() => this.connectSocket(), 60 * 1000);
+ };
+
+ socket.onmessage = (event) => {
+ const data = JSON.parse(event.data);
+ if (data.devices) {
+ this.props.dispatch(updateDevices(data.devices));
+ }
+ if (data.positions) {
+ this.props.dispatch(updatePositions(data.positions));
+ }
+ if (data.events) {
+ displayNotifications(data.events);
+ }
+ }
+ }
+
+ componentDidMount() {
+ fetch('/api/devices').then(response => {
+ if (response.ok) {
+ response.json().then(devices => {
+ this.props.dispatch(updateDevices(devices));
+ });
+ }
+ this.connectSocket();
+ });
+ }
+
+ render() {
+ return null;
+ }
+}
+
+export default connect()(SocketController);