2018-04-24 19:34:03 +00:00
|
|
|
import Random from 'react-native-meteor/lib/Random';
|
|
|
|
|
2018-05-18 17:55:08 +00:00
|
|
|
import messagesStatus from '../../constants/messagesStatus';
|
2018-04-24 19:34:03 +00:00
|
|
|
import buildMessage from '../methods/helpers/buildMessage';
|
|
|
|
import { post } from './helpers/rest';
|
|
|
|
import database from '../realm';
|
|
|
|
import reduxStore from '../createStore';
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../utils/log';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
|
|
|
export const getMessage = (rid, msg = {}) => {
|
|
|
|
const _id = Random.id();
|
|
|
|
const message = {
|
|
|
|
_id,
|
|
|
|
rid,
|
|
|
|
msg,
|
|
|
|
ts: new Date(),
|
|
|
|
_updatedAt: new Date(),
|
|
|
|
status: messagesStatus.TEMP,
|
|
|
|
u: {
|
|
|
|
_id: reduxStore.getState().login.user.id || '1',
|
|
|
|
username: reduxStore.getState().login.user.username
|
|
|
|
}
|
|
|
|
};
|
2018-05-23 13:39:18 +00:00
|
|
|
try {
|
|
|
|
database.write(() => {
|
|
|
|
database.create('messages', message, true);
|
|
|
|
});
|
|
|
|
} catch (error) {
|
|
|
|
console.warn('getMessage', error);
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
return message;
|
|
|
|
};
|
|
|
|
|
|
|
|
function sendMessageByRest(message) {
|
|
|
|
const { token, id } = this.ddp._login;
|
|
|
|
const server = this.ddp.url.replace('ws', 'http');
|
|
|
|
const { _id, rid, msg } = message;
|
|
|
|
return post({ token, id, server }, 'chat.sendMessage', { message: { _id, rid, msg } });
|
|
|
|
}
|
|
|
|
|
|
|
|
function sendMessageByDDP(message) {
|
|
|
|
const { _id, rid, msg } = message;
|
|
|
|
return this.ddp.call('sendMessage', { _id, rid, msg });
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function _sendMessageCall(message) {
|
|
|
|
try {
|
|
|
|
// eslint-disable-next-line
|
2018-07-18 20:34:59 +00:00
|
|
|
const data = await (this.ddp.status ? sendMessageByDDP.call(this, message) : sendMessageByRest.call(this, message));
|
2018-04-24 19:34:03 +00:00
|
|
|
return data;
|
|
|
|
} catch (e) {
|
|
|
|
database.write(() => {
|
|
|
|
message.status = messagesStatus.ERROR;
|
|
|
|
database.create('messages', message, true);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default async function(rid, msg) {
|
|
|
|
const { database: db } = database;
|
|
|
|
try {
|
|
|
|
const message = getMessage(rid, msg);
|
|
|
|
const room = db.objects('subscriptions').filtered('rid == $0', rid);
|
|
|
|
|
|
|
|
db.write(() => {
|
|
|
|
room.lastMessage = message;
|
|
|
|
});
|
|
|
|
|
|
|
|
const ret = await _sendMessageCall.call(this, message);
|
|
|
|
// TODO: maybe I have created a bug in the future here <3
|
|
|
|
db.write(() => {
|
|
|
|
db.create('messages', buildMessage({ ...message, ...ret }), true);
|
|
|
|
});
|
|
|
|
} catch (e) {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('sendMessage', e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
}
|