2021-06-15 20:13:42 +00:00
|
|
|
import { sanitizedRaw } from '@nozbe/watermelondb/RawRecord';
|
|
|
|
|
|
|
|
import database from '../database';
|
|
|
|
import { getMessageById } from '../database/services/Message';
|
|
|
|
import { getThreadById } from '../database/services/Thread';
|
|
|
|
import log from '../../utils/log';
|
|
|
|
import { Encryption } from '../encryption';
|
2021-10-01 18:12:19 +00:00
|
|
|
import getSingleMessage from './getSingleMessage';
|
2022-03-29 18:53:27 +00:00
|
|
|
import { IMessage, IThread, TThreadModel } from '../../definitions';
|
2021-06-15 20:13:42 +00:00
|
|
|
|
2022-03-29 18:53:27 +00:00
|
|
|
const buildThreadName = (thread: IThread | IMessage): string | undefined => thread.msg || thread?.attachments?.[0]?.title;
|
2021-06-15 20:13:42 +00:00
|
|
|
|
2022-03-29 18:53:27 +00:00
|
|
|
const getThreadName = async (rid: string, tmid: string, messageId: string): Promise<string | undefined> => {
|
|
|
|
let tmsg: string | undefined;
|
2021-06-15 20:13:42 +00:00
|
|
|
try {
|
|
|
|
const db = database.active;
|
|
|
|
const threadCollection = db.get('threads');
|
|
|
|
const messageRecord = await getMessageById(messageId);
|
|
|
|
const threadRecord = await getThreadById(tmid);
|
|
|
|
if (threadRecord) {
|
|
|
|
tmsg = buildThreadName(threadRecord);
|
2022-03-29 18:53:27 +00:00
|
|
|
await db.write(async () => {
|
2021-10-01 18:12:19 +00:00
|
|
|
await messageRecord?.update(m => {
|
2021-06-15 20:13:42 +00:00
|
|
|
m.tmsg = tmsg;
|
|
|
|
});
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
let thread = await getSingleMessage(tmid);
|
|
|
|
thread = await Encryption.decryptMessage(thread);
|
|
|
|
tmsg = buildThreadName(thread);
|
2022-03-29 18:53:27 +00:00
|
|
|
await db.write(async () => {
|
2021-06-15 20:13:42 +00:00
|
|
|
await db.batch(
|
2022-03-29 18:53:27 +00:00
|
|
|
threadCollection?.prepareCreate((t: TThreadModel) => {
|
2021-06-15 20:13:42 +00:00
|
|
|
t._raw = sanitizedRaw({ id: thread._id }, threadCollection.schema);
|
2022-03-29 18:53:27 +00:00
|
|
|
if (t.subscription) t.subscription.id = rid;
|
2021-06-15 20:13:42 +00:00
|
|
|
Object.assign(t, thread);
|
|
|
|
}),
|
2021-10-01 18:12:19 +00:00
|
|
|
messageRecord?.prepareUpdate(m => {
|
2021-06-15 20:13:42 +00:00
|
|
|
m.tmsg = tmsg;
|
|
|
|
})
|
|
|
|
);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
log(e);
|
|
|
|
}
|
|
|
|
return tmsg;
|
|
|
|
};
|
|
|
|
|
|
|
|
export default getThreadName;
|