2018-04-24 19:34:03 +00:00
|
|
|
import { InteractionManager } from 'react-native';
|
|
|
|
|
|
|
|
import { get } from './helpers/rest';
|
|
|
|
import buildMessage from './helpers/buildMessage';
|
|
|
|
import database from '../realm';
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
async function loadMissedMessagesRest({ rid: roomId, lastOpen: lastUpdate }) {
|
|
|
|
const { token, id } = this.ddp._login;
|
|
|
|
const server = this.ddp.url.replace('ws', 'http');
|
|
|
|
const { result } = await get({ token, id, server }, 'chat.syncMessages', { roomId, lastUpdate });
|
|
|
|
// TODO: api fix
|
2018-09-26 13:56:36 +00:00
|
|
|
if (!result) {
|
|
|
|
return [];
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
return result.updated || result.messages;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loadMissedMessagesDDP(...args) {
|
|
|
|
const [{ rid, lastOpen: lastUpdate }] = args;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const data = await this.ddp.call('messages/get', rid, { lastUpdate: new Date(lastUpdate) });
|
|
|
|
return data.updated || data.messages;
|
|
|
|
} catch (e) {
|
|
|
|
return loadMissedMessagesRest.call(this, ...args);
|
|
|
|
}
|
|
|
|
|
|
|
|
// }
|
|
|
|
// if (cb) {
|
|
|
|
// cb({ end: data && data.messages.length < 20 });
|
|
|
|
// }
|
|
|
|
// return data.message;
|
|
|
|
// }, (err) => {
|
|
|
|
// if (err) {
|
|
|
|
// if (cb) {
|
|
|
|
// cb({ end: true });
|
|
|
|
// }
|
|
|
|
// return Promise.reject(err);
|
|
|
|
// }
|
|
|
|
// });
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async function(...args) {
|
|
|
|
const { database: db } = database;
|
2018-05-18 17:55:08 +00:00
|
|
|
return new Promise(async(resolve, reject) => {
|
|
|
|
try {
|
|
|
|
// eslint-disable-next-line
|
2018-07-18 20:34:59 +00:00
|
|
|
const data = (await (this.ddp.status ? loadMissedMessagesDDP.call(this, ...args) : loadMissedMessagesRest.call(this, ...args)));
|
2018-05-18 17:55:08 +00:00
|
|
|
|
|
|
|
if (data) {
|
|
|
|
data.forEach(buildMessage);
|
|
|
|
return InteractionManager.runAfterInteractions(() => {
|
2018-04-24 19:34:03 +00:00
|
|
|
db.write(() => data.forEach(message => db.create('messages', message, true)));
|
|
|
|
resolve(data);
|
2018-05-18 17:55:08 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
resolve([]);
|
|
|
|
} catch (e) {
|
|
|
|
log('loadMissedMessages', e);
|
|
|
|
reject(e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|