(
data: BaseMessageWithRelations,
opts?: {
ignoreChecks?: boolean;
},
)
| 31 | } from './message'; |
| 32 | |
| 33 | export async function upsertMessage( |
| 34 | data: BaseMessageWithRelations, |
| 35 | opts?: { |
| 36 | ignoreChecks?: boolean; |
| 37 | }, |
| 38 | ) { |
| 39 | if (!opts?.ignoreChecks) { |
| 40 | const [ignoredAccount, userServerSettings] = await Promise.all([ |
| 41 | findIgnoredDiscordAccountById(data.authorId), |
| 42 | findUserServerSettingsById({ |
| 43 | userId: data.authorId, |
| 44 | serverId: data.serverId, |
| 45 | }), |
| 46 | ]); |
| 47 | if (ignoredAccount) { |
| 48 | throw new DBError( |
| 49 | CANNOT_UPSERT_MESSAGE_FOR_IGNORED_ACCOUNT_MESSAGE, |
| 50 | 'IGNORED_ACCOUNT', |
| 51 | ); |
| 52 | } |
| 53 | if (userServerSettings?.flags.messageIndexingDisabled) { |
| 54 | throw new DBError( |
| 55 | CANNOT_UPSERT_MESSAGE_FOR_USER_WITH_MESSAGE_INDEXING_DISABLED_MESSAGE, |
| 56 | 'MESSAGE_INDEXING_DISABLED', |
| 57 | ); |
| 58 | } |
| 59 | } |
| 60 | const { attachments, reactions, embeds, ...msg } = data; |
| 61 | const parsed = { |
| 62 | ...messageSchema.parse(msg), |
| 63 | embeds, |
| 64 | }; |
| 65 | |
| 66 | await db.insert(dbMessages).values(parsed).onDuplicateKeyUpdate({ |
| 67 | set: parsed, |
| 68 | }); |
| 69 | const updateAttachments = async () => { |
| 70 | const existingAttachments = await db |
| 71 | .select() |
| 72 | .from(dbAttachments) |
| 73 | .where(eq(dbAttachments.messageId, msg.id)); |
| 74 | const existingAttachmentIds = new Set(existingAttachments.map((a) => a.id)); |
| 75 | |
| 76 | if (!attachments) { |
| 77 | await db.delete(dbAttachments).where(eq(dbAttachments.messageId, msg.id)); |
| 78 | return; |
| 79 | } |
| 80 | for await (const attachment of attachments) { |
| 81 | if (!existingAttachmentIds.has(attachment.id)) { |
| 82 | void uploadFileFromUrl({ |
| 83 | url: attachment.url, |
| 84 | id: attachment.id, |
| 85 | contentType: attachment.contentType ?? undefined, |
| 86 | filename: attachment.filename, |
| 87 | }).then(async (uploaded) => { |
| 88 | if (!uploaded) return; |
| 89 | await db.insert(dbAttachments).values( |
| 90 | attachmentSchema.parse({ |
no test coverage detected