aboutsummaryrefslogtreecommitdiff
path: root/modern/src/SocketController.js
blob: b89845f2fd109402f3ee415feae0e926995f2d3f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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);