2017-02-18 09:51:11 +02:00
|
|
|
const ReconnectingWebSocket = require('reconnecting-websocket');
|
2017-03-18 13:05:11 +02:00
|
|
|
import * as riot from 'riot';
|
|
|
|
import CONFIG from './config';
|
2017-02-18 09:51:11 +02:00
|
|
|
|
|
|
|
class Connection {
|
|
|
|
constructor(me, otherparty) {
|
2017-02-19 01:09:38 +02:00
|
|
|
// BIND -----------------------------------
|
|
|
|
this.onOpen = this.onOpen.bind(this);
|
|
|
|
this.onMessage = this.onMessage.bind(this);
|
|
|
|
this.close = this.close.bind(this);
|
|
|
|
// ----------------------------------------
|
|
|
|
|
2017-02-18 09:51:11 +02:00
|
|
|
this.event = riot.observable();
|
|
|
|
this.me = me;
|
|
|
|
|
2017-02-19 08:32:10 +02:00
|
|
|
const host = CONFIG.apiUrl.replace('http', 'ws');
|
2017-02-18 09:51:11 +02:00
|
|
|
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 {
|
2017-02-19 01:09:38 +02:00
|
|
|
const msg = JSON.parse(message.data);
|
|
|
|
if (msg.type) this.event.trigger(msg.type, msg.body);
|
2017-02-18 09:51:11 +02:00
|
|
|
} catch(e) {
|
|
|
|
// noop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
close() {
|
|
|
|
this.socket.removeEventListener('open', this.onOpen);
|
|
|
|
this.socket.removeEventListener('message', this.onMessage);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-03-18 13:05:11 +02:00
|
|
|
export default Connection;
|