2017-12-20 19:20:06 +00:00
|
|
|
import EJSON from 'ejson';
|
2018-04-24 19:34:03 +00:00
|
|
|
import { AppState } from 'react-native';
|
2018-05-18 17:55:08 +00:00
|
|
|
|
2018-04-24 19:34:03 +00:00
|
|
|
import debounce from '../utils/debounce';
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
// import { AppState, NativeModules } from 'react-native';
|
|
|
|
// const { WebSocketModule, BlobManager } = NativeModules;
|
|
|
|
|
|
|
|
// class WS extends WebSocket {
|
|
|
|
// _close(code?: number, reason?: string): void {
|
|
|
|
// if (Platform.OS === 'android') {
|
|
|
|
// WebSocketModule.close(code, reason, this._socketId);
|
|
|
|
// } else {
|
|
|
|
// WebSocketModule.close(this._socketId);
|
|
|
|
// }
|
|
|
|
//
|
|
|
|
// if (BlobManager.isAvailable && this._binaryType === 'blob') {
|
|
|
|
// BlobManager.removeWebSocketHandler(this._socketId);
|
|
|
|
// }
|
|
|
|
// }
|
|
|
|
// }
|
2017-12-20 19:20:06 +00:00
|
|
|
|
|
|
|
class EventEmitter {
|
|
|
|
constructor() {
|
|
|
|
this.events = {};
|
|
|
|
}
|
|
|
|
on(event, listener) {
|
|
|
|
if (typeof this.events[event] !== 'object') {
|
|
|
|
this.events[event] = [];
|
|
|
|
}
|
|
|
|
this.events[event].push(listener);
|
2018-04-24 19:34:03 +00:00
|
|
|
return listener;
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
removeListener(event, listener) {
|
|
|
|
if (typeof this.events[event] === 'object') {
|
|
|
|
const idx = this.events[event].indexOf(listener);
|
|
|
|
if (idx > -1) {
|
|
|
|
this.events[event].splice(idx, 1);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
emit(event, ...args) {
|
|
|
|
if (typeof this.events[event] === 'object') {
|
|
|
|
this.events[event].forEach((listener) => {
|
|
|
|
try {
|
|
|
|
listener.apply(this, args);
|
|
|
|
} catch (e) {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('EventEmitter.emit', e);
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
once(event, listener) {
|
|
|
|
this.on(event, function g(...args) {
|
|
|
|
this.removeListener(event, g);
|
|
|
|
listener.apply(this, args);
|
|
|
|
});
|
2018-04-24 19:34:03 +00:00
|
|
|
return listener;
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2017-12-20 19:20:06 +00:00
|
|
|
export default class Socket extends EventEmitter {
|
2018-04-24 19:34:03 +00:00
|
|
|
constructor(url, login) {
|
2017-12-20 19:20:06 +00:00
|
|
|
super();
|
2018-04-24 19:34:03 +00:00
|
|
|
this.state = 'active';
|
|
|
|
this.lastping = new Date();
|
|
|
|
this._login = login;
|
|
|
|
this.url = url;// .replace(/^http/, 'ws');
|
2017-12-20 19:20:06 +00:00
|
|
|
this.id = 0;
|
|
|
|
this.subscriptions = {};
|
|
|
|
this.ddp = new EventEmitter();
|
2018-04-24 19:34:03 +00:00
|
|
|
this._logged = false;
|
|
|
|
const waitTimeout = () => setTimeout(async() => {
|
|
|
|
// this.connection.ping();
|
|
|
|
this.send({ msg: 'ping' });
|
|
|
|
this.timeout = setTimeout(() => this.reconnect(), 1000);
|
|
|
|
}, 40000);
|
|
|
|
const handlePing = () => {
|
|
|
|
this.lastping = new Date();
|
|
|
|
this.send({ msg: 'pong' }, true);
|
|
|
|
if (this.timeout) {
|
|
|
|
clearTimeout(this.timeout);
|
|
|
|
}
|
|
|
|
this.timeout = waitTimeout();
|
|
|
|
};
|
|
|
|
const handlePong = () => {
|
|
|
|
this.lastping = new Date();
|
|
|
|
if (this.timeout) {
|
|
|
|
clearTimeout(this.timeout);
|
|
|
|
}
|
|
|
|
this.timeout = waitTimeout();
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
AppState.addEventListener('change', (nextAppState) => {
|
|
|
|
if (this.state && this.state.match(/inactive/) && nextAppState === 'active') {
|
|
|
|
try {
|
|
|
|
this.send({ msg: 'ping' }, true);
|
|
|
|
// this.connection.ping();
|
|
|
|
} catch (e) {
|
|
|
|
this.reconnect();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if (this.state && this.state.match(/background/) && nextAppState === 'active') {
|
|
|
|
this.emit('background');
|
|
|
|
}
|
|
|
|
this.state = nextAppState;
|
|
|
|
});
|
|
|
|
|
|
|
|
this.on('pong', handlePong);
|
|
|
|
this.on('ping', handlePing);
|
|
|
|
|
2018-01-16 18:32:30 +00:00
|
|
|
this.on('result', data => this.ddp.emit(data.id, { id: data.id, result: data.result, error: data.error }));
|
2017-12-20 19:20:06 +00:00
|
|
|
this.on('ready', data => this.ddp.emit(data.subs[0], data));
|
2018-04-24 19:34:03 +00:00
|
|
|
// this.on('error', () => this.reconnect());
|
|
|
|
this.on('disconnected', debounce(() => this.reconnect(), 300));
|
|
|
|
this.on('logged', () => this._logged = true);
|
|
|
|
|
|
|
|
this.on('logged', () => {
|
|
|
|
Object.keys(this.subscriptions || {}).forEach((key) => {
|
|
|
|
const { name, params } = this.subscriptions[key];
|
|
|
|
this.subscriptions[key].unsubscribe();
|
|
|
|
this.subscribe(name, ...params);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
this.on('open', async() => {
|
|
|
|
this._logged = false;
|
|
|
|
this.send({ msg: 'connect', version: '1', support: ['1', 'pre2', 'pre1'] });
|
|
|
|
});
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
try {
|
|
|
|
this._connect();
|
|
|
|
} catch (e) {
|
|
|
|
log('ddp.constructor._connect', e);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
check() {
|
|
|
|
if (!this.lastping) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
if ((Math.abs(this.lastping.getTime() - new Date().getTime()) / 1000) > 50) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
async login(params) {
|
|
|
|
try {
|
|
|
|
this.emit('login', params);
|
|
|
|
const result = await this.call('login', params);
|
|
|
|
this._login = { resume: result.token, ...result };
|
|
|
|
this._logged = true;
|
|
|
|
this.emit('logged', result);
|
|
|
|
return result;
|
|
|
|
} catch (err) {
|
|
|
|
const error = { ...err };
|
|
|
|
if (/user not found/i.test(error.reason)) {
|
|
|
|
error.error = 1;
|
|
|
|
error.reason = 'User or Password incorrect';
|
|
|
|
error.message = 'User or Password incorrect';
|
|
|
|
}
|
|
|
|
this.emit('logginError', error);
|
|
|
|
return Promise.reject(error);
|
|
|
|
}
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
async send(obj, ignore) {
|
|
|
|
console.log('send');
|
2017-12-20 19:20:06 +00:00
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this.id += 1;
|
2018-04-24 19:34:03 +00:00
|
|
|
const id = obj.id || `ddp-react-native-${ this.id }`;
|
|
|
|
// console.log('send', { ...obj, id });
|
2017-12-20 19:20:06 +00:00
|
|
|
this.connection.send(EJSON.stringify({ ...obj, id }));
|
2018-04-24 19:34:03 +00:00
|
|
|
if (ignore) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
const cancel = this.ddp.once('disconnected', reject);
|
|
|
|
this.ddp.once(id, (data) => {
|
|
|
|
// console.log(data);
|
|
|
|
this.ddp.removeListener(id, cancel);
|
|
|
|
return (data.error ? reject(data.error) : resolve({ id, ...data }));
|
|
|
|
});
|
2017-12-20 19:20:06 +00:00
|
|
|
});
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
get status() {
|
|
|
|
return this.connection && this.connection.readyState === 1 && this.check() && !!this._logged;
|
|
|
|
}
|
|
|
|
_close() {
|
|
|
|
try {
|
|
|
|
// this.connection && this.connection.readyState > 1 && this.connection.close && this.connection.close(300, 'disconnect');
|
|
|
|
if (this.connection && this.connection.close) {
|
|
|
|
this.connection.close(300, 'disconnect');
|
|
|
|
delete this.connection;
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
// console.log(e);
|
|
|
|
}
|
|
|
|
}
|
2017-12-20 19:20:06 +00:00
|
|
|
_connect() {
|
2018-04-24 19:34:03 +00:00
|
|
|
return new Promise((resolve) => {
|
|
|
|
this.lastping = new Date();
|
|
|
|
this._close();
|
|
|
|
clearInterval(this.reconnect_timeout);
|
|
|
|
this.reconnect_timeout = setInterval(() => (!this.connection || this.connection.readyState > 1 || !this.check()) && this.reconnect(), 5000);
|
|
|
|
this.connection = new WebSocket(`${ this.url }/websocket`, null);
|
2017-12-20 19:20:06 +00:00
|
|
|
|
2018-04-24 19:34:03 +00:00
|
|
|
this.connection.onopen = () => {
|
|
|
|
this.emit('open');
|
|
|
|
resolve();
|
|
|
|
this.ddp.emit('open');
|
|
|
|
return this._login && this.login(this._login);
|
|
|
|
};
|
|
|
|
this.connection.onclose = debounce((e) => { console.log('aer'); this.emit('disconnected', e); }, 300);
|
|
|
|
this.connection.onmessage = (e) => {
|
|
|
|
try {
|
|
|
|
// console.log('received', e.data, e.target.readyState);
|
|
|
|
const data = EJSON.parse(e.data);
|
|
|
|
this.emit(data.msg, data);
|
|
|
|
return data.collection && this.emit(data.collection, data);
|
|
|
|
} catch (err) {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('EJSON parse', err);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
});
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
logout() {
|
2018-04-24 19:34:03 +00:00
|
|
|
this._login = null;
|
2017-12-20 19:20:06 +00:00
|
|
|
return this.call('logout').then(() => this.subscriptions = {});
|
|
|
|
}
|
|
|
|
disconnect() {
|
2018-04-24 19:34:03 +00:00
|
|
|
this._close();
|
2018-05-07 20:43:26 +00:00
|
|
|
this._login = null;
|
|
|
|
this.subscriptions = {};
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
async reconnect() {
|
|
|
|
if (this._timer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
delete this.connection;
|
|
|
|
this._logged = false;
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
this._timer = setTimeout(async() => {
|
2018-04-24 19:34:03 +00:00
|
|
|
delete this._timer;
|
2018-05-18 17:55:08 +00:00
|
|
|
try {
|
|
|
|
await this._connect();
|
|
|
|
} catch (e) {
|
|
|
|
log('ddp.reconnect._connect', e);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
}, 1000);
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
call(method, ...params) {
|
|
|
|
return this.send({
|
|
|
|
msg: 'method', method, params
|
2018-04-24 19:34:03 +00:00
|
|
|
}).then(data => data.result || data.subs).catch((err) => {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('DDP call Error', err);
|
2018-04-24 19:34:03 +00:00
|
|
|
return Promise.reject(err);
|
|
|
|
});
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
unsubscribe(id) {
|
|
|
|
if (!this.subscriptions[id]) {
|
2018-01-16 18:32:30 +00:00
|
|
|
return Promise.reject(id);
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
delete this.subscriptions[id];
|
|
|
|
return this.send({
|
|
|
|
msg: 'unsub',
|
|
|
|
id
|
2018-04-24 19:34:03 +00:00
|
|
|
}).then(data => data.result || data.subs).catch((err) => {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('DDP unsubscribe Error', err);
|
2018-04-24 19:34:03 +00:00
|
|
|
return Promise.reject(err);
|
|
|
|
});
|
2017-12-20 19:20:06 +00:00
|
|
|
}
|
|
|
|
subscribe(name, ...params) {
|
2018-04-24 19:34:03 +00:00
|
|
|
console.log(name, params);
|
2017-12-20 19:20:06 +00:00
|
|
|
return this.send({
|
|
|
|
msg: 'sub', name, params
|
2018-01-16 18:32:30 +00:00
|
|
|
}).then(({ id }) => {
|
2018-01-15 18:44:20 +00:00
|
|
|
const args = {
|
2018-04-24 19:34:03 +00:00
|
|
|
id,
|
2017-12-20 19:20:06 +00:00
|
|
|
name,
|
|
|
|
params,
|
2018-01-15 18:44:20 +00:00
|
|
|
unsubscribe: () => this.unsubscribe(id)
|
2017-12-20 19:20:06 +00:00
|
|
|
};
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-01-15 18:44:20 +00:00
|
|
|
this.subscriptions[id] = args;
|
2018-04-24 19:34:03 +00:00
|
|
|
// console.log(args);
|
2018-01-15 18:44:20 +00:00
|
|
|
return args;
|
2018-04-24 19:34:03 +00:00
|
|
|
}).catch((err) => {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('DDP subscribe Error', err);
|
2018-04-24 19:34:03 +00:00
|
|
|
return Promise.reject(err);
|
2017-12-20 19:20:06 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|