From d948524c743a82943a12a58a930411e18e0dfac4 Mon Sep 17 00:00:00 2001 From: alexa Date: Sun, 30 Jun 2024 01:30:28 +0200 Subject: [PATCH] work on message attachments --- src/features/database/mariaDbDatabase.ts | 5 +++++ src/features/messagingFeature.ts | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/src/features/database/mariaDbDatabase.ts b/src/features/database/mariaDbDatabase.ts index 0d97eaf..13c0a89 100644 --- a/src/features/database/mariaDbDatabase.ts +++ b/src/features/database/mariaDbDatabase.ts @@ -339,4 +339,9 @@ WHERE ur.userId = ?`, [userId]); const rows = await this.query("SELECT * FROM venel.attachments WHERE messageId = ? AND filename = ?", [messageId, name]); return rows[0] ?? null; } + + async getChannelByMessageId(messageId: Id) { + const rows = await this.query("SELECT * FROM venel.channels WHERE id IN (SELECT channelId FROM venel.messages WHERE id = ?)", [messageId]); + return rows[0] ?? null; + } } \ No newline at end of file diff --git a/src/features/messagingFeature.ts b/src/features/messagingFeature.ts index 09ddd0e..bfc1da4 100644 --- a/src/features/messagingFeature.ts +++ b/src/features/messagingFeature.ts @@ -4,6 +4,7 @@ import {MariaDbDatabase} from "./database/mariaDbDatabase"; import {MessagingEndpoints} from "./messaging/endpoints"; import fs from "fs"; import {CLI} from "../tooling/CLI"; +import {User} from "./database/models"; export class MessagingFeature { static enable(app: Application, db: MariaDbDatabase) { @@ -56,13 +57,27 @@ export class MessagingFeature { res.status(404).send("Attachment not found"); return; } + + const channel = await db.getChannelByMessageId(parseInt(messageId.toString())); + if (!channel) { + res.status(404).send("Channel not found"); + return; + } + + const user = req.user as User; + const invalid = await MessagingEndpoints.checkChannelAccess(db, user, channel.id); + if (invalid !== null) { + res.status(invalid.code).send(invalid.error); + return; + } + CLI.debug(`Sending attachment ${attachmentPath}`); const stat = fs.statSync(attachmentPath); const messageAttachment = await db.getMessageAttachment(parseInt(messageId.toString()), filename.toString()); res.setHeader("Content-Type", messageAttachment?.type ?? "application/octet-stream"); res.setHeader("Content-Length", stat.size); - const base64 = fs.readFileSync(attachmentPath).toString("base64"); - res.send(base64); + const stream = fs.createReadStream(attachmentPath); + stream.pipe(res); }); return app;