2017-02-18 05:18:59 +01:00
|
|
|
const ReconnectingWebSocket = require('reconnecting-websocket');
|
2017-03-18 12:05:11 +01:00
|
|
|
import * as riot from 'riot';
|
|
|
|
import CONFIG from './config';
|
|
|
|
|
|
|
|
class Connection {
|
|
|
|
constructor(me) {
|
|
|
|
// BIND -----------------------------------
|
|
|
|
this.onOpen = this.onOpen.bind(this);
|
|
|
|
this.onClose = this.onClose.bind(this);
|
|
|
|
this.onMessage = this.onMessage.bind(this);
|
2017-03-20 06:49:24 +01:00
|
|
|
this.send = this.send.bind(this);
|
2017-03-18 12:05:11 +01:00
|
|
|
this.close = this.close.bind(this);
|
|
|
|
// ----------------------------------------
|
|
|
|
|
2017-03-20 06:49:24 +01:00
|
|
|
riot.observable(this);
|
|
|
|
|
2017-03-18 12:05:11 +01:00
|
|
|
this.state = 'initializing';
|
|
|
|
this.me = me;
|
2017-03-21 10:14:59 +01:00
|
|
|
this.buffer = [];
|
2017-03-18 12:05:11 +01:00
|
|
|
|
|
|
|
const host = CONFIG.apiUrl.replace('http', 'ws');
|
|
|
|
this.socket = new ReconnectingWebSocket(`${host}?i=${me.token}`);
|
|
|
|
this.socket.addEventListener('open', this.onOpen);
|
|
|
|
this.socket.addEventListener('close', this.onClose);
|
|
|
|
this.socket.addEventListener('message', this.onMessage);
|
|
|
|
|
2017-03-20 06:49:24 +01:00
|
|
|
this.on('i_updated', me.update);
|
2017-03-18 12:05:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
onOpen() {
|
|
|
|
this.state = 'connected';
|
2017-03-20 06:49:24 +01:00
|
|
|
this.trigger('_connected_');
|
2017-03-21 10:14:59 +01:00
|
|
|
|
|
|
|
// バッファーを処理
|
|
|
|
const _buffer = [].concat(this.buffer); // Shallow copy
|
|
|
|
this.buffer = []; // Clear buffer
|
|
|
|
_buffer.forEach(message => {
|
|
|
|
this.send(message); // Resend each buffered messages
|
|
|
|
});
|
2017-03-18 12:05:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
onClose() {
|
|
|
|
this.state = 'reconnecting';
|
2017-03-20 06:49:24 +01:00
|
|
|
this.trigger('_closed_');
|
2017-03-18 12:05:11 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
onMessage(message) {
|
2017-02-18 05:18:59 +01:00
|
|
|
try {
|
2017-02-19 00:02:59 +01:00
|
|
|
const msg = JSON.parse(message.data);
|
2017-03-20 06:49:24 +01:00
|
|
|
if (msg.type) this.trigger(msg.type, msg.body);
|
2017-03-18 12:05:11 +01:00
|
|
|
} catch(e) {
|
2017-02-18 05:18:59 +01:00
|
|
|
// noop
|
|
|
|
}
|
2017-03-18 12:05:11 +01:00
|
|
|
}
|
2017-02-18 05:18:59 +01:00
|
|
|
|
2017-03-20 05:54:59 +01:00
|
|
|
send(message) {
|
2017-03-21 10:14:59 +01:00
|
|
|
// まだ接続が確立されていなかったらバッファリングして次に接続した時に送信する
|
|
|
|
if (this.state != 'connected') {
|
|
|
|
this.buffer.push(message);
|
|
|
|
return;
|
|
|
|
};
|
|
|
|
|
2017-03-20 05:54:59 +01:00
|
|
|
this.socket.send(JSON.stringify(message));
|
|
|
|
}
|
|
|
|
|
2017-03-18 12:05:11 +01:00
|
|
|
close() {
|
|
|
|
this.socket.removeEventListener('open', this.onOpen);
|
|
|
|
this.socket.removeEventListener('message', this.onMessage);
|
|
|
|
}
|
|
|
|
}
|
2017-02-18 05:18:59 +01:00
|
|
|
|
2017-03-18 12:05:11 +01:00
|
|
|
export default Connection;
|