2018-10-15 20:22:42 +00:00
|
|
|
import * as SDK from '@rocket.chat/sdk';
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-10-15 20:22:42 +00:00
|
|
|
const subscribe = rid => Promise.all([
|
|
|
|
SDK.driver.subscribe('stream-room-messages', rid, false),
|
|
|
|
SDK.driver.subscribe('stream-notify-room', `${ rid }/typing`, false),
|
|
|
|
SDK.driver.subscribe('stream-notify-room', `${ rid }/deleteMessage`, false)
|
2018-04-24 19:34:03 +00:00
|
|
|
]);
|
2018-09-25 19:28:42 +00:00
|
|
|
const unsubscribe = subscriptions => subscriptions.forEach(sub => sub.unsubscribe().catch((e) => {
|
|
|
|
log('unsubscribeRoom', e);
|
|
|
|
}));
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
let timer = null;
|
|
|
|
let promises;
|
|
|
|
|
2018-10-15 20:22:42 +00:00
|
|
|
const stop = () => {
|
2018-04-24 19:34:03 +00:00
|
|
|
if (promises) {
|
|
|
|
promises.then(unsubscribe);
|
|
|
|
promises = false;
|
|
|
|
}
|
|
|
|
|
|
|
|
clearTimeout(timer);
|
|
|
|
};
|
|
|
|
|
|
|
|
export default async function subscribeRoom({ rid, t }) {
|
|
|
|
if (promises) {
|
|
|
|
promises.then(unsubscribe);
|
|
|
|
promises = false;
|
|
|
|
}
|
|
|
|
const loop = (time = new Date()) => {
|
|
|
|
if (timer) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
timer = setTimeout(async() => {
|
|
|
|
try {
|
2018-10-15 20:22:42 +00:00
|
|
|
await this.loadMissedMessages({ rid, t });
|
2018-04-24 19:34:03 +00:00
|
|
|
timer = false;
|
|
|
|
loop();
|
|
|
|
} catch (e) {
|
|
|
|
loop(time);
|
|
|
|
}
|
|
|
|
}, 5000);
|
|
|
|
};
|
|
|
|
|
2018-10-15 20:22:42 +00:00
|
|
|
if (!SDK.driver.ddp && SDK.driver.userId) {
|
2018-04-24 19:34:03 +00:00
|
|
|
loop();
|
|
|
|
} else {
|
2018-10-15 20:22:42 +00:00
|
|
|
SDK.driver.on('logged', () => {
|
2018-05-07 20:43:26 +00:00
|
|
|
clearTimeout(timer);
|
|
|
|
timer = false;
|
|
|
|
});
|
|
|
|
|
2018-10-15 20:22:42 +00:00
|
|
|
SDK.driver.on('disconnected', () => {
|
|
|
|
if (SDK.driver.userId) {
|
2018-05-07 20:43:26 +00:00
|
|
|
loop();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
try {
|
2018-10-15 20:22:42 +00:00
|
|
|
promises = subscribe(rid);
|
2018-05-18 17:55: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
|
|
|
};
|
|
|
|
}
|