2017-02-18 05:18:59 +01:00
|
|
|
const ReconnectingWebSocket = require('reconnecting-websocket');
|
|
|
|
const riot = require('riot');
|
|
|
|
|
|
|
|
module.exports = me => {
|
|
|
|
let state = 'initializing';
|
|
|
|
const stateEv = riot.observable();
|
|
|
|
const event = riot.observable();
|
2017-02-19 07:32:10 +01:00
|
|
|
const host = CONFIG.apiUrl.replace('http', 'ws');
|
2017-02-18 05:18:59 +01:00
|
|
|
const socket = new ReconnectingWebSocket(`${host}?i=${me.token}`);
|
|
|
|
|
|
|
|
socket.onopen = () => {
|
|
|
|
state = 'connected';
|
|
|
|
stateEv.trigger('connected');
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onclose = () => {
|
|
|
|
state = 'reconnecting';
|
|
|
|
stateEv.trigger('closed');
|
|
|
|
};
|
|
|
|
|
|
|
|
socket.onmessage = message => {
|
|
|
|
try {
|
2017-02-19 00:02:59 +01:00
|
|
|
const msg = JSON.parse(message.data);
|
|
|
|
if (msg.type) {
|
|
|
|
event.trigger(msg.type, msg.body);
|
2017-02-18 05:18:59 +01:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
// noop
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
event.on('i_updated', me.update);
|
|
|
|
|
|
|
|
return {
|
|
|
|
stateEv: stateEv,
|
|
|
|
getState: () => state,
|
|
|
|
event: event
|
|
|
|
};
|
|
|
|
};
|