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