2018-04-24 19:34:03 +00:00
|
|
|
// import database from '../../realm';
|
|
|
|
// import reduxStore from '../../createStore';
|
|
|
|
// import normalizeMessage from '../helpers/normalizeMessage';
|
|
|
|
// import _buildMessage from '../helpers/buildMessage';
|
|
|
|
// import protectedFunction from '../helpers/protectedFunction';
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
const subscribe = (ddp, rid) => Promise.all([
|
|
|
|
ddp.subscribe('stream-room-messages', rid, false),
|
2018-09-28 18:57:29 +00:00
|
|
|
ddp.subscribe('stream-notify-room', `${ rid }/typing`, false),
|
|
|
|
ddp.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;
|
|
|
|
let logged;
|
|
|
|
let disconnected;
|
|
|
|
|
|
|
|
const stop = (ddp) => {
|
|
|
|
if (promises) {
|
|
|
|
promises.then(unsubscribe);
|
|
|
|
promises = false;
|
|
|
|
}
|
|
|
|
|
2018-05-07 20:43:26 +00:00
|
|
|
if (ddp) {
|
|
|
|
ddp.removeListener('logged', logged);
|
|
|
|
ddp.removeListener('disconnected', disconnected);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
logged = false;
|
|
|
|
disconnected = 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 {
|
|
|
|
await this.loadMissedMessages({ rid, t, lastOpen: timer });
|
|
|
|
timer = false;
|
|
|
|
loop();
|
|
|
|
} catch (e) {
|
|
|
|
loop(time);
|
|
|
|
}
|
|
|
|
}, 5000);
|
|
|
|
};
|
|
|
|
|
2018-05-07 20:43:26 +00:00
|
|
|
if (!this.ddp || !this.ddp.status) {
|
2018-04-24 19:34:03 +00:00
|
|
|
loop();
|
|
|
|
} else {
|
2018-05-07 20:43:26 +00:00
|
|
|
logged = this.ddp.on('logged', () => {
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = false;
|
2018-05-18 17:55:08 +00:00
|
|
|
// promises = subscribe(this.ddp, rid);
|
2018-05-07 20:43:26 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
disconnected = this.ddp.on('disconnected', () => {
|
|
|
|
if (this._login) {
|
|
|
|
loop();
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
try {
|
|
|
|
promises = subscribe(this.ddp, rid);
|
|
|
|
} catch (e) {
|
|
|
|
log('subscribeRoom', e);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return {
|
|
|
|
stop: () => stop(this.ddp)
|
|
|
|
};
|
|
|
|
}
|