2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-12-05 20:52:08 +00:00
|
|
|
const unsubscribe = subscriptions => subscriptions.forEach(sub => sub.unsubscribe().catch(() => console.log('unsubscribeRoom')));
|
2019-02-12 16:14:11 +00:00
|
|
|
const removeListener = listener => listener.stop();
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
let promises;
|
2019-02-07 15:48:10 +00:00
|
|
|
let timer = null;
|
2019-02-12 16:14:11 +00:00
|
|
|
let connectedListener;
|
|
|
|
let disconnectedListener;
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2019-02-07 15:48:10 +00:00
|
|
|
export default function subscribeRoom({ rid }) {
|
2018-04-24 19:34:03 +00:00
|
|
|
if (promises) {
|
|
|
|
promises.then(unsubscribe);
|
|
|
|
promises = false;
|
|
|
|
}
|
2019-02-07 15:48:10 +00:00
|
|
|
const loop = () => {
|
2018-04-24 19:34:03 +00:00
|
|
|
if (timer) {
|
|
|
|
return;
|
|
|
|
}
|
2019-02-12 16:14:11 +00:00
|
|
|
timer = setTimeout(() => {
|
2018-04-24 19:34:03 +00:00
|
|
|
try {
|
2019-02-07 15:48:10 +00:00
|
|
|
clearTimeout(timer);
|
2018-04-24 19:34:03 +00:00
|
|
|
timer = false;
|
2019-02-12 16:14:11 +00:00
|
|
|
this.loadMissedMessages({ rid });
|
|
|
|
loop();
|
2018-04-24 19:34:03 +00:00
|
|
|
} catch (e) {
|
2019-02-07 15:48:10 +00:00
|
|
|
loop();
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
}, 5000);
|
|
|
|
};
|
|
|
|
|
2019-02-12 16:14:11 +00:00
|
|
|
const handleConnected = () => {
|
|
|
|
this.loadMissedMessages({ rid });
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = false;
|
|
|
|
};
|
|
|
|
|
|
|
|
const handleDisconnected = () => {
|
2019-02-07 15:48:10 +00:00
|
|
|
if (this.sdk.userId) {
|
2019-02-12 16:14:11 +00:00
|
|
|
loop();
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
const stop = () => {
|
|
|
|
if (promises) {
|
|
|
|
promises.then(unsubscribe);
|
|
|
|
promises = false;
|
|
|
|
}
|
|
|
|
if (connectedListener) {
|
|
|
|
connectedListener.then(removeListener);
|
|
|
|
connectedListener = false;
|
|
|
|
}
|
|
|
|
if (disconnectedListener) {
|
|
|
|
disconnectedListener.then(removeListener);
|
|
|
|
disconnectedListener = false;
|
2019-02-07 15:48:10 +00:00
|
|
|
}
|
2018-12-05 20:52:08 +00:00
|
|
|
clearTimeout(timer);
|
2019-02-12 16:14:11 +00:00
|
|
|
};
|
2018-05-07 20:43:26 +00:00
|
|
|
|
2019-02-12 16:14:11 +00:00
|
|
|
connectedListener = this.sdk.onStreamData('connected', handleConnected);
|
|
|
|
disconnectedListener = this.sdk.onStreamData('close', handleDisconnected);
|
2018-12-05 20:52:08 +00:00
|
|
|
|
|
|
|
try {
|
2019-02-07 15:48:10 +00:00
|
|
|
promises = this.sdk.subscribeRoom(rid);
|
2018-12-05 20:52:08 +00:00
|
|
|
} catch (e) {
|
|
|
|
log('subscribeRoom', e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
2018-10-15 20:22:42 +00:00
|
|
|
stop: () => stop()
|
2018-04-24 19:34:03 +00:00
|
|
|
};
|
|
|
|
}
|