generated from lucien/api-template
add: added image attachments to messages
This commit is contained in:
parent
8f77a271e1
commit
fb90f1ef4f
10 changed files with 169 additions and 10 deletions
22
back/api/attachments.js
Normal file
22
back/api/attachments.js
Normal file
|
@ -0,0 +1,22 @@
|
||||||
|
const express = require('express');
|
||||||
|
const { getConnection, getAttachment } = require('../libs/mysql');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
|
||||||
|
const router = express.Router();
|
||||||
|
|
||||||
|
router.get('/:file_name', async (req, res) => {
|
||||||
|
const { file_name } = req.params;
|
||||||
|
|
||||||
|
const connection = await getConnection();
|
||||||
|
const attachment = await getAttachment(connection, file_name);
|
||||||
|
connection.end();
|
||||||
|
|
||||||
|
if (!attachment[0]) {
|
||||||
|
return res.status(404).send({ error: 'File not found' });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.sendFile(path.join(__dirname, `../data/attachments/${attachment[0].file_name}`), { headers: { 'Content-Type': 'image' } });
|
||||||
|
})
|
||||||
|
|
||||||
|
module.exports = router;
|
|
@ -11,14 +11,19 @@ const {
|
||||||
getUserByUsername,
|
getUserByUsername,
|
||||||
deleteChannelMessages,
|
deleteChannelMessages,
|
||||||
deleteChannel,
|
deleteChannel,
|
||||||
getMessageReplies
|
getMessageReplies,
|
||||||
|
addAttachment,
|
||||||
|
getMessageAttachments,
|
||||||
|
getUnusedAttachments,
|
||||||
|
deleteUnusedAttachments
|
||||||
} = require('../libs/mysql');
|
} = require('../libs/mysql');
|
||||||
const rateLimit = require("express-rate-limit");
|
const rateLimit = require("express-rate-limit");
|
||||||
const slowDown = require("express-slow-down");
|
const slowDown = require("express-slow-down");
|
||||||
const { checkAuth } = require('../libs/middlewares');
|
const { checkAuth } = require('../libs/middlewares');
|
||||||
const multer = require('multer');
|
const multer = require('multer');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
const upload = multer({ dest: 'data/attachements/' })
|
const upload = multer({ dest: 'data/attachments/' })
|
||||||
upload.limits = {
|
upload.limits = {
|
||||||
fileSize: 1024 * 1024 * 5,
|
fileSize: 1024 * 1024 * 5,
|
||||||
files: 1,
|
files: 1,
|
||||||
|
@ -104,6 +109,15 @@ router.post('/:name/delete', async (req, res) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
await deleteChannel(connection, channel[0].id);
|
await deleteChannel(connection, channel[0].id);
|
||||||
|
|
||||||
|
const attachments = await getUnusedAttachments(connection);
|
||||||
|
for (const attachment of attachments) {
|
||||||
|
if (fs.existsSync(`data/attachments/${attachment.file_name}`)) {
|
||||||
|
fs.unlinkSync(`data/attachments/${attachment.file_name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await deleteUnusedAttachments(connection);
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
req.sockets.emit({
|
req.sockets.emit({
|
||||||
|
@ -143,7 +157,7 @@ router.get('/:name/messages', async (req, res) => {
|
||||||
const messages = await getMessages(connection, channel[0].id, limit);
|
const messages = await getMessages(connection, channel[0].id, limit);
|
||||||
|
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
if (message.content.includes('@')) {
|
if (message.has_mentions) {
|
||||||
const mentions = await getMentions(connection, message.id);
|
const mentions = await getMentions(connection, message.id);
|
||||||
message.mentions = mentions;
|
message.mentions = mentions;
|
||||||
} else {
|
} else {
|
||||||
|
@ -157,18 +171,28 @@ router.get('/:name/messages', async (req, res) => {
|
||||||
else {
|
else {
|
||||||
message.replies = [];
|
message.replies = [];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (message.has_attachments) {
|
||||||
|
const attachments = await getMessageAttachments(connection, message.id);
|
||||||
|
message.attachments = attachments;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
message.attachments = [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
res.send(messages);
|
res.send(messages);
|
||||||
});
|
});
|
||||||
|
|
||||||
router.post('/:name/messages/send', speedLimiter, limiter, upload.single("attachement"), checkAuth, async (req, res) => {
|
router.post('/:name/messages/send', speedLimiter, limiter, upload.single("attachment"), checkAuth, async (req, res) => {
|
||||||
const { message } = req.body;
|
const { message } = req.body;
|
||||||
const name = req.params.name;
|
const name = req.params.name;
|
||||||
const user = req.user;
|
const user = req.user;
|
||||||
|
const attachement = req.file;
|
||||||
|
|
||||||
if (!message) {
|
if (!message) {
|
||||||
|
if (attachement) fs.unlinkSync(`data/attachements/${attachement.filename}`);
|
||||||
return res.status(400).send({ error: 'Missing parameters' });
|
return res.status(400).send({ error: 'Missing parameters' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -177,12 +201,17 @@ router.post('/:name/messages/send', speedLimiter, limiter, upload.single("attach
|
||||||
const channel = await getChannel(connection, name);
|
const channel = await getChannel(connection, name);
|
||||||
if (!channel[0]) {
|
if (!channel[0]) {
|
||||||
connection.end();
|
connection.end();
|
||||||
|
if (attachement) fs.unlinkSync(`data/attachements/${attachement.filename}`);
|
||||||
return res.send('No channel found');
|
return res.send('No channel found');
|
||||||
}
|
}
|
||||||
|
|
||||||
const sent_message = await addMessage(connection, channel[0].id, user.id, message.replace("\"", "'"));
|
const sent_message = await addMessage(connection, channel[0].id, user.id, message.replace("\"", "'"));
|
||||||
const message_id = sent_message.insertId;
|
const message_id = sent_message.insertId;
|
||||||
|
|
||||||
|
if (attachement) {
|
||||||
|
await addAttachment(connection, message_id, attachement.filename);
|
||||||
|
}
|
||||||
|
|
||||||
for (const word of message.split(' ')) {
|
for (const word of message.split(' ')) {
|
||||||
if (word.startsWith('@')) {
|
if (word.startsWith('@')) {
|
||||||
const username = word.substring(1);
|
const username = word.substring(1);
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const { getConnection, getLastMessages, getMentions } = require('../libs/mysql');
|
const { getConnection, getLastMessages, getMentions, getMessageAttachments } = require('../libs/mysql');
|
||||||
|
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
@ -15,6 +15,12 @@ router.get('/', async (req, res) => {
|
||||||
message.mentions = [];
|
message.mentions = [];
|
||||||
}
|
}
|
||||||
message.replies = [];
|
message.replies = [];
|
||||||
|
if (message.has_attachments) {
|
||||||
|
const attachments = await getMessageAttachments(connection, message.id);
|
||||||
|
message.attachments = attachments;
|
||||||
|
} else {
|
||||||
|
message.attachments = [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
|
@ -8,11 +8,14 @@ const {
|
||||||
getMentions,
|
getMentions,
|
||||||
getUserByUsername,
|
getUserByUsername,
|
||||||
addReply,
|
addReply,
|
||||||
getMessageReplies
|
getMessageReplies,
|
||||||
|
getUnusedAttachments,
|
||||||
|
deleteUnusedAttachments
|
||||||
} = require('../libs/mysql');
|
} = require('../libs/mysql');
|
||||||
const rateLimit = require("express-rate-limit");
|
const rateLimit = require("express-rate-limit");
|
||||||
const slowDown = require("express-slow-down");
|
const slowDown = require("express-slow-down");
|
||||||
const { checkAuth } = require('../libs/middlewares');
|
const { checkAuth } = require('../libs/middlewares');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
|
||||||
const limiter = rateLimit({
|
const limiter = rateLimit({
|
||||||
windowMs: 1 * 1000,
|
windowMs: 1 * 1000,
|
||||||
|
@ -132,6 +135,15 @@ router.post('/:message_id/delete', checkAuth, async (req, res) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
await deleteMessage(connection, message_id);
|
await deleteMessage(connection, message_id);
|
||||||
|
|
||||||
|
const attachments = await getUnusedAttachments(connection);
|
||||||
|
for (const attachment of attachments) {
|
||||||
|
if (fs.existsSync(`data/attachments/${attachment.file_name}`)) {
|
||||||
|
fs.unlinkSync(`data/attachments/${attachment.file_name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await deleteUnusedAttachments(connection);
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
req.sockets.emit({
|
req.sockets.emit({
|
||||||
|
|
|
@ -1,5 +1,5 @@
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const { getConnection, getUsers, getUserByUsername, getUserLastMessages, getMentions, deleteUser, deleteUserMessages, deleteUserMentions, setUserPfp } = require('../libs/mysql');
|
const { getConnection, getUsers, getUserByUsername, getUserLastMessages, getMentions, deleteUser, setUserPfp, getMessageAttachments, getUnusedAttachments, deleteUnusedAttachments } = require('../libs/mysql');
|
||||||
const { checkAuth } = require("../libs/middlewares")
|
const { checkAuth } = require("../libs/middlewares")
|
||||||
const path = require('path');
|
const path = require('path');
|
||||||
const fs = require('node:fs');
|
const fs = require('node:fs');
|
||||||
|
@ -38,6 +38,12 @@ router.get('/:username/lastmessages', async (req, res) => {
|
||||||
message.mentions = [];
|
message.mentions = [];
|
||||||
}
|
}
|
||||||
message.replies = [];
|
message.replies = [];
|
||||||
|
if (message.has_attachments) {
|
||||||
|
const attachments = await getMessageAttachments(connection, message.id);
|
||||||
|
message.attachments = attachments;
|
||||||
|
} else {
|
||||||
|
message.attachments = [];
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
@ -87,6 +93,14 @@ router.post('/:username/delete', checkAuth, async (req, res) => {
|
||||||
|
|
||||||
await deleteUser(connection, userToDelete[0].id);
|
await deleteUser(connection, userToDelete[0].id);
|
||||||
|
|
||||||
|
const attachments = await getUnusedAttachments(connection);
|
||||||
|
for (const attachment of attachments) {
|
||||||
|
if (fs.existsSync(`data/attachments/${attachment.file_name}`)) {
|
||||||
|
fs.unlinkSync(`data/attachments/${attachment.file_name}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
await deleteUnusedAttachments(connection);
|
||||||
|
|
||||||
connection.end();
|
connection.end();
|
||||||
|
|
||||||
req.sockets.emit({
|
req.sockets.emit({
|
||||||
|
|
|
@ -617,6 +617,20 @@ function deleteUnusedAttachments(connection) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getUnusedAttachments(connection) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
connection.query(
|
||||||
|
`SELECT * FROM attachments WHERE message_id IS NULL`,
|
||||||
|
(error, result) => {
|
||||||
|
if (error) {
|
||||||
|
reject(new Error(error));
|
||||||
|
}
|
||||||
|
resolve(result);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function getMessageAttachments(connection, message_id) {
|
function getMessageAttachments(connection, message_id) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
connection.query(
|
connection.query(
|
||||||
|
@ -632,6 +646,21 @@ function getMessageAttachments(connection, message_id) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getAttachment(connection, file_name) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
connection.query(
|
||||||
|
`SELECT * FROM attachments WHERE file_name = ?`,
|
||||||
|
[file_name],
|
||||||
|
(error, result) => {
|
||||||
|
if (error) {
|
||||||
|
reject(new Error(error));
|
||||||
|
}
|
||||||
|
resolve(result);
|
||||||
|
}
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getConnection,
|
getConnection,
|
||||||
|
|
||||||
|
@ -672,4 +701,10 @@ module.exports = {
|
||||||
getEmoji,
|
getEmoji,
|
||||||
getEmojiByName,
|
getEmojiByName,
|
||||||
searchEmojis,
|
searchEmojis,
|
||||||
|
|
||||||
|
addAttachment,
|
||||||
|
deleteUnusedAttachments,
|
||||||
|
getUnusedAttachments,
|
||||||
|
getMessageAttachments,
|
||||||
|
getAttachment,
|
||||||
};
|
};
|
||||||
|
|
|
@ -131,6 +131,13 @@ export default function MessageComponent({ message, user, channel }: {
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{message.has_attachments == true && (
|
||||||
|
<div className="message-attachments">
|
||||||
|
{message.attachments.map((attachment) => (
|
||||||
|
<img src={`/api/attachments/${attachment.file_name}`} alt="attachment" className="message-attachment" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
<div>
|
<div>
|
||||||
{message.content.toLocaleLowerCase().includes("gros cochon") && (
|
{message.content.toLocaleLowerCase().includes("gros cochon") && (
|
||||||
<img src="/pig.png" alt="Gros cochon" className="pig" />
|
<img src="/pig.png" alt="Gros cochon" className="pig" />
|
||||||
|
|
|
@ -23,8 +23,20 @@ export default function ChannelPage({socket}: {socket: WebSocket}) {
|
||||||
|
|
||||||
function handleSubmit(e: React.FormEvent) {
|
function handleSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
|
|
||||||
|
const formData = new FormData();
|
||||||
|
const fileInput = document.getElementById("attachment") as HTMLInputElement;
|
||||||
|
if (fileInput.files) {
|
||||||
|
formData.append("attachment", fileInput.files[0]);
|
||||||
|
}
|
||||||
|
formData.append("token", token);
|
||||||
|
formData.append("message", message);
|
||||||
axios
|
axios
|
||||||
.post(`/api/channels/${name}/messages/send`, { token, message})
|
.post(`/api/channels/${name}/messages/send`, formData, {
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "multipart/form-data",
|
||||||
|
}
|
||||||
|
})
|
||||||
.then(() => {
|
.then(() => {
|
||||||
setMessage("");
|
setMessage("");
|
||||||
setSearchedUsers([]);
|
setSearchedUsers([]);
|
||||||
|
@ -204,6 +216,7 @@ export default function ChannelPage({socket}: {socket: WebSocket}) {
|
||||||
onChange={(e) => setMessage(e.target.value)}
|
onChange={(e) => setMessage(e.target.value)}
|
||||||
ref={ref}
|
ref={ref}
|
||||||
/>
|
/>
|
||||||
|
<input type="file" name="attachment" id="attachment" />
|
||||||
<button type="submit">Send</button>
|
<button type="submit">Send</button>
|
||||||
{searchedUsers.length > 0 && (
|
{searchedUsers.length > 0 && (
|
||||||
<div className="mentions">
|
<div className="mentions">
|
||||||
|
|
|
@ -42,6 +42,17 @@
|
||||||
max-height: 1em;
|
max-height: 1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.message-attachments {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.message-attachment {
|
||||||
|
max-width: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
.message-replies {
|
.message-replies {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|
|
@ -25,17 +25,27 @@ export type Mention = {
|
||||||
|
|
||||||
export type Mentions = Mention[]
|
export type Mentions = Mention[]
|
||||||
|
|
||||||
|
export type Attachment = {
|
||||||
|
id: number
|
||||||
|
message_id: number
|
||||||
|
file_name: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export type Attachments = Attachment[]
|
||||||
|
|
||||||
export type Message = {
|
export type Message = {
|
||||||
id: number
|
id: number
|
||||||
user_id: number
|
user_id: number
|
||||||
username: string
|
username: string
|
||||||
content: string
|
content: string
|
||||||
date: number
|
date: number
|
||||||
channel_id: number
|
|
||||||
channel_name: string
|
channel_name: string
|
||||||
|
has_mentions: boolean
|
||||||
|
has_replies: boolean
|
||||||
|
has_attachments: boolean
|
||||||
mentions: Mentions
|
mentions: Mentions
|
||||||
replies: Messages
|
replies: Messages
|
||||||
has_replies: boolean
|
attachments: Attachments
|
||||||
}
|
}
|
||||||
|
|
||||||
export type Messages = Message[]
|
export type Messages = Message[]
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue