Skip to content

Commit

Permalink
work on message attachments
Browse files Browse the repository at this point in the history
  • Loading branch information
targoninc-alex committed Jun 29, 2024
1 parent 889f3a1 commit d948524
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
5 changes: 5 additions & 0 deletions src/features/database/mariaDbDatabase.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
}
19 changes: 17 additions & 2 deletions src/features/messagingFeature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit d948524

Please sign in to comment.