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-05-18 17:55:08 +00:00
|
|
|
|
2018-04-24 19:34:03 +00:00
|
|
|
import mergeSubscriptionsRooms, { merge } from './helpers/mergeSubscriptionsRooms';
|
|
|
|
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
|
|
|
|
|
|
|
const lastMessage = () => {
|
|
|
|
const message = database
|
|
|
|
.objects('subscriptions')
|
|
|
|
.sorted('roomUpdatedAt', true)[0];
|
2018-10-15 20:22:42 +00:00
|
|
|
return message && new Date(message.roomUpdatedAt).toISOString();
|
2018-04-24 19:34:03 +00:00
|
|
|
};
|
|
|
|
|
2018-10-23 21:39:48 +00:00
|
|
|
export default function() {
|
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-12-05 20:52:08 +00:00
|
|
|
const updatedSince = lastMessage();
|
|
|
|
const [subscriptionsResult, roomsResult] = await (updatedSince
|
|
|
|
? Promise.all([SDK.api.get('subscriptions.get', { updatedSince }), SDK.api.get('rooms.get', { updatedSince })])
|
|
|
|
: Promise.all([SDK.api.get('subscriptions.get'), SDK.api.get('rooms.get')])
|
|
|
|
);
|
|
|
|
const { subscriptions, rooms } = mergeSubscriptionsRooms(subscriptionsResult, roomsResult);
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
const data = rooms.map(room => ({ room, sub: database.objects('subscriptions').filtered('rid == $0', room._id) }));
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
InteractionManager.runAfterInteractions(() => {
|
|
|
|
db.write(() => {
|
|
|
|
subscriptions.forEach(subscription => db.create('subscriptions', subscription, true));
|
|
|
|
data.forEach(({ sub, room }) => sub[0] && merge(sub[0], room));
|
|
|
|
});
|
|
|
|
resolve(data);
|
2018-04-24 19:34:03 +00:00
|
|
|
});
|
2018-05-18 17:55:08 +00:00
|
|
|
} catch (e) {
|
|
|
|
log('getRooms', e);
|
|
|
|
reject(e);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
});
|
|
|
|
}
|