2018-04-24 19:34:03 +00:00
|
|
|
import { InteractionManager } from 'react-native';
|
2018-10-15 20:22:42 +00:00
|
|
|
import * as SDK from '@rocket.chat/sdk';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
2018-10-15 20:22:42 +00:00
|
|
|
async function loadMissedMessagesRest({ rid: roomId, lastOpen }) {
|
|
|
|
let lastUpdate;
|
|
|
|
if (lastOpen) {
|
|
|
|
lastUpdate = new Date(lastOpen).toISOString();
|
|
|
|
}
|
|
|
|
const { result } = await SDK.api.get('chat.syncMessages', { roomId, lastUpdate });
|
2018-09-28 18:57:29 +00:00
|
|
|
return result;
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function loadMissedMessagesDDP(...args) {
|
|
|
|
const [{ rid, lastOpen: lastUpdate }] = args;
|
|
|
|
|
|
|
|
try {
|
2018-10-15 20:22:42 +00:00
|
|
|
const result = await SDK.driver.asyncCall('messages/get', rid, { lastUpdate: new Date(lastUpdate) });
|
2018-09-28 18:57:29 +00:00
|
|
|
return result;
|
2018-04-24 19:34:03 +00:00
|
|
|
} catch (e) {
|
|
|
|
return loadMissedMessagesRest.call(this, ...args);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-09-28 18:57:29 +00:00
|
|
|
export default async function loadMissedMessages(...args) {
|
2018-04-24 19:34:03 +00:00
|
|
|
const { database: db } = database;
|
2018-05-18 17:55:08 +00:00
|
|
|
return new Promise(async(resolve, reject) => {
|
|
|
|
try {
|
2018-10-15 20:22:42 +00:00
|
|
|
const data = (await (SDK.driver.ddp ? loadMissedMessagesDDP.call(this, ...args) : loadMissedMessagesRest.call(this, ...args)));
|
2018-05-18 17:55:08 +00:00
|
|
|
|
|
|
|
if (data) {
|
2018-09-28 18:57:29 +00:00
|
|
|
if (data.updated && data.updated.length) {
|
|
|
|
const { updated } = data;
|
|
|
|
updated.forEach(buildMessage);
|
|
|
|
InteractionManager.runAfterInteractions(() => {
|
|
|
|
db.write(() => updated.forEach(message => db.create('messages', message, true)));
|
|
|
|
resolve(updated);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
if (data.deleted && data.deleted.length) {
|
|
|
|
const { deleted } = data;
|
|
|
|
InteractionManager.runAfterInteractions(() => {
|
|
|
|
db.write(() => {
|
|
|
|
deleted.forEach((m) => {
|
|
|
|
const message = database.objects('messages').filtered('_id = $0', m._id);
|
|
|
|
database.delete(message);
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
2018-05-18 17:55:08 +00:00
|
|
|
}
|
|
|
|
resolve([]);
|
|
|
|
} catch (e) {
|
|
|
|
log('loadMissedMessages', e);
|
|
|
|
reject(e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|