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
|
|
|
|
|
|
|
// TODO: api fix
|
|
|
|
const types = {
|
|
|
|
c: 'channels', d: 'im', p: 'groups'
|
|
|
|
};
|
|
|
|
|
|
|
|
async function loadMessagesForRoomRest({ rid: roomId, latest, t }) {
|
|
|
|
const { token, id } = this.ddp._login;
|
|
|
|
const server = this.ddp.url.replace('ws', 'http');
|
|
|
|
const data = await get({ token, id, server }, `${ types[t] }.history`, { roomId, latest });
|
|
|
|
return data.messages;
|
|
|
|
}
|
|
|
|
|
|
|
|
async function loadMessagesForRoomDDP(...args) {
|
|
|
|
const [{ rid: roomId, latest }] = args;
|
|
|
|
try {
|
|
|
|
const data = await this.ddp.call('loadHistory', roomId, latest, 50);
|
|
|
|
if (!data || !data.messages.length) {
|
|
|
|
return [];
|
|
|
|
}
|
|
|
|
return data.messages;
|
|
|
|
} catch (e) {
|
|
|
|
console.warn('loadMessagesForRoomDDP', e);
|
|
|
|
return loadMessagesForRoomRest.call(this, ...args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async function loadMessagesForRoom(...args) {
|
|
|
|
const { database: db } = database;
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
return new Promise(async(resolve, reject) => {
|
|
|
|
try {
|
|
|
|
// eslint-disable-next-line
|
|
|
|
const data = (await (false && this.ddp.status ? loadMessagesForRoomDDP.call(this, ...args) : loadMessagesForRoomRest.call(this, ...args))).map(buildMessage);
|
2018-06-01 17:56:59 +00:00
|
|
|
if (data && data.length) {
|
2018-05-18 17:55:08 +00:00
|
|
|
InteractionManager.runAfterInteractions(() => {
|
2018-04-24 19:34:03 +00:00
|
|
|
db.write(() => data.forEach(message => db.create('messages', message, true)));
|
2018-05-18 17:55:08 +00:00
|
|
|
return resolve(data);
|
|
|
|
});
|
2018-06-01 17:56:59 +00:00
|
|
|
} else {
|
|
|
|
return resolve([]);
|
2018-05-18 17:55:08 +00:00
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
log('loadMessagesForRoom', e);
|
|
|
|
reject(e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|