mail/back/app/saveMessage.js
2023-03-17 13:31:27 +01:00

92 lines
3.8 KiB
JavaScript

const {
createRoom,
registerMessageInRoom,
createThread,
registerMessageInThread,
isRoomGroup,
findSpacesFromMessage,
hasSameMembersAsParent,
} = require("../db/saveMessageApp");
const { findRoomByOwner, getAddresseId } = require("../db/mail");
/**
* take object address and join mailbox and host to return mailbox@host
*/
function createAddress(elt) {
return `${elt.mailbox}@${elt.host}`;
}
async function registerMessageInApp(messageId, attrs) {
const isSeen = attrs.flags.includes("Seen") ? 1 : 0; // todo verify
const envelope = attrs.envelope;
await getAddresseId(createAddress(envelope.sender[0])).then(async (ownerId) => {
if (envelope.inReplyTo) {
await registerReplyMessage(envelope, messageId, isSeen);
} else {
await findRoomByOwner(ownerId).then(async (res) => {
if (res.length == 0) {
await createRoom(envelope.subject, ownerId, messageId).then(async (roomId) => {
await registerMessageInRoom(messageId, roomId, isSeen);
});
} else {
await registerMessageInRoom(messageId, res[0].room_id, isSeen);
}
});
}
});
}
async function registerReplyMessage(envelope, messageId, isSeen) {
const messageID = envelope.messageId;
await findSpacesFromMessage(messageId).then(async (spaces) => {
// todo sub thread will not be in index 0 so look in all indexes
if (spaces.length == 0) {
// no space, so is a transfer
// todo test if members of transferred message are included
} else if (spaces[0].thread_id) {
await registerMessageInThread(messageId, spaces[0].thread_id, isSeen);
// todo
// if (hasSameMembersAsParent(messageID, envelope.inReplyTo)) {
// // register new message in thread
// // possibly convert to room only if parent is channel
// } else {
// // todo create sub thread
// }
} else if (spaces[0].room_id) {
// message in room and not thread
await isRoomGroup(spaces[0].room_id).then(async (isGroup) => {
if (isGroup) {
const hasSameMembers = await hasSameMembersAsParent(messageID, envelope.inReplyTo);
if (hasSameMembers) {
await registerMessageInRoom(messageId, spaces[0].room_id, isSeen);
} else {
// group and not the same member as the reply
// some recipient has been removed create a thread
const isDm = 0; // todo
await createThread(space[0].room_id, envelope.subject, isSeen, isDm).then(async (threadId) => {
await registerMessageInThread(messageId, threadId, isSeen);
});
}
} else {
// reply from channel
// todo
// if (messageInRoom == 1) { // was new channel transform to group
// // register new message in group
// } else if (sender == owner) { // correction from the original sender
// // leave in the same channel
// } else { // user response to announcement
// // create new thread
// }
}
});
}
});
// `SELECT app_room_messages.room, app_room_messages.thread FROM app_room_messages INNER JOIN messages WHERE messages.messageID = '${envelope.inReplyTo}' AND app_room_messages.message = messages.id`;
}
module.exports = {
registerMessageInApp
};