2018-05-18 17:55:08 +00:00
|
|
|
import messagesStatus from '../../constants/messagesStatus';
|
2018-09-25 19:28:42 +00:00
|
|
|
import buildMessage from './helpers/buildMessage';
|
2018-04-24 19:34:03 +00:00
|
|
|
import database from '../realm';
|
|
|
|
import reduxStore from '../createStore';
|
2018-05-18 17:55:08 +00:00
|
|
|
import log from '../../utils/log';
|
2018-12-05 20:52:08 +00:00
|
|
|
import random from '../../utils/random';
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2019-04-17 17:01:03 +00:00
|
|
|
export const getMessage = (rid, msg = '', tmid) => {
|
2018-12-05 20:52:08 +00:00
|
|
|
const _id = random(17);
|
2018-04-24 19:34:03 +00:00
|
|
|
const message = {
|
|
|
|
_id,
|
|
|
|
rid,
|
|
|
|
msg,
|
2019-04-17 17:01:03 +00:00
|
|
|
tmid,
|
2018-04-24 19:34:03 +00:00
|
|
|
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;
|
|
|
|
};
|
|
|
|
|
2018-12-05 20:52:08 +00:00
|
|
|
export async function sendMessageCall(message) {
|
2019-04-17 17:01:03 +00:00
|
|
|
const {
|
|
|
|
_id, rid, msg, tmid
|
|
|
|
} = message;
|
2018-12-21 10:55:35 +00:00
|
|
|
// RC 0.60.0
|
2019-04-17 17:01:03 +00:00
|
|
|
const data = await this.sdk.post('chat.sendMessage', {
|
|
|
|
message: {
|
|
|
|
_id, rid, msg, tmid
|
|
|
|
}
|
|
|
|
});
|
2018-11-16 11:06:29 +00:00
|
|
|
return data;
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
|
2019-04-17 17:01:03 +00:00
|
|
|
export default async function(rid, msg, tmid) {
|
2018-04-24 19:34:03 +00:00
|
|
|
try {
|
2019-04-17 17:01:03 +00:00
|
|
|
const message = getMessage(rid, msg, tmid);
|
2019-04-08 12:35:28 +00:00
|
|
|
const [room] = database.objects('subscriptions').filtered('rid == $0', rid);
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2019-04-17 17:01:03 +00:00
|
|
|
if (room) {
|
|
|
|
database.write(() => {
|
|
|
|
room.draftMessage = null;
|
|
|
|
});
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
|
2018-11-16 11:06:29 +00:00
|
|
|
try {
|
2018-12-05 20:52:08 +00:00
|
|
|
const ret = await sendMessageCall.call(this, message);
|
2019-02-07 15:48:10 +00:00
|
|
|
database.write(() => {
|
|
|
|
database.create('messages', buildMessage({ ...message, ...ret }), true);
|
2018-11-16 11:06:29 +00:00
|
|
|
});
|
|
|
|
} catch (e) {
|
|
|
|
database.write(() => {
|
|
|
|
message.status = messagesStatus.ERROR;
|
|
|
|
database.create('messages', message, true);
|
|
|
|
});
|
|
|
|
}
|
2018-04-24 19:34:03 +00:00
|
|
|
} catch (e) {
|
2018-05-18 17:55:08 +00:00
|
|
|
log('sendMessage', e);
|
2018-04-24 19:34:03 +00:00
|
|
|
}
|
|
|
|
}
|