summaryrefslogtreecommitdiff
path: root/src/web/app/common/scripts/messaging-stream.js
blob: e6fc6f8bd0bd81c8065e2917df9c044b97da3d70 (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
const ReconnectingWebSocket = require('reconnecting-websocket');
const riot = require('riot');

class Connection {
	constructor(me, otherparty) {
		this.event = riot.observable();
		this.me = me;

		const host = CONFIG.api.url.replace('http', 'ws');
		this.socket = new ReconnectingWebSocket(`${host}/messaging?i=${me.token}&otherparty=${otherparty}`);
		this.socket.addEventListener('open', this.onOpen);
		this.socket.addEventListener('message', this.onMessage);
	}

	onOpen() {
		this.socket.send(JSON.stringify({
			i: this.me.token
		}));
	}

	onMessage(message) {
		try {
			const message = JSON.parse(message.data);
			if (message.type) this.event.trigger(message.type, message.body);
		} catch(e) {
			// noop
		}
	}

	close() {
		this.socket.removeEventListener('open', this.onOpen);
		this.socket.removeEventListener('message', this.onMessage);
	}
}

module.exports = Connection;