add: improved the frontend and the backend by adding websockets

This commit is contained in:
Lukian 2025-04-07 22:46:04 +02:00
parent ecf7b61aca
commit fbf7821320
18 changed files with 255 additions and 65 deletions

View file

@ -11,6 +11,16 @@ router.get('/', async (req, res) => {
res.send(channels); res.send(channels);
}); });
const sockets = new Set();
router.ws('/', function(ws, req) {
sockets.add(ws);
ws.on('close', () => {
sockets.delete(ws);
});
});
router.get('/:name', async (req, res) => { router.get('/:name', async (req, res) => {
const name = req.params.name; const name = req.params.name;
const connection = await getConnection(); const connection = await getConnection();
@ -23,6 +33,22 @@ router.get('/:name', async (req, res) => {
} }
}); });
const channelSockets = new Map();
router.ws('/:name', function(ws, req) {
const name = req.params.name;
if (!channelSockets.has(name)) {
channelSockets.set(name, new Set());
}
channelSockets.get(name).add(ws);
ws.on('close', () => {
channelSockets.get(name).delete(ws);
});
});
router.get('/:name/messages', async (req, res) => { router.get('/:name/messages', async (req, res) => {
const name = req.params.name; const name = req.params.name;
const connection = await getConnection(); const connection = await getConnection();
@ -78,6 +104,23 @@ router.post('/:name/messages/send', async (req, res) => {
} }
connection.end(); connection.end();
if (sockets.size > 0) {
for (const client of sockets) {
if (client.readyState === 1) {
client.send('new_message');
}
}
}
if (channelSockets.has(name)) {
for (const client of channelSockets.get(name)) {
if (client.readyState === 1) {
client.send('new_message');
}
}
}
res.send({ message: 'Message sent' }); res.send({ message: 'Message sent' });
}); });
@ -113,6 +156,23 @@ router.post('/:name/messages/delete', async (req, res) => {
await deleteMessage(connection, message_id); await deleteMessage(connection, message_id);
await deleMentions(connection, message_id); await deleMentions(connection, message_id);
connection.end(); connection.end();
if (sockets.size > 0) {
for (const client of sockets) {
if (client.readyState === 1) {
client.send('delete_message');
}
}
}
if (channelSockets.has(name)) {
for (const client of channelSockets.get(name)) {
if (client.readyState === 1) {
client.send('delete_message');
}
}
}
res.send({ message: 'Message deleted' }); res.send({ message: 'Message deleted' });
}); });
@ -140,6 +200,15 @@ router.post('/add', async (req, res) => {
await addChannel(connection, name, description, user.id); await addChannel(connection, name, description, user.id);
connection.end(); connection.end();
if (sockets.size > 0) {
for (const client of sockets) {
if (client.readyState === 1) {
client.send('new_channel');
}
}
}
res.send({ message: 'Channel added' }); res.send({ message: 'Channel added' });
}); });

View file

@ -1,5 +1,4 @@
const express = require('express'); const express = require('express');
const jwt = require('jsonwebtoken');
const { getConnection, getLastMessages, getMentions } = require('../libs/mysql'); const { getConnection, getLastMessages, getMentions } = require('../libs/mysql');
const router = express.Router(); const router = express.Router();

13
back/api/newchannels.js Normal file
View file

@ -0,0 +1,13 @@
const express = require('express');
const { getConnection, getNewChannels } = require('../libs/mysql');
const router = express.Router();
router.get('/', async (req, res) => {
const connection = await getConnection();
const channels = await getNewChannels(connection);
connection.end();
res.send(channels);
});
module.exports = router;

View file

@ -7,6 +7,7 @@ const cors = require("cors");
require("dotenv").config(); require("dotenv").config();
const app = express(); const app = express();
var expressWs = require('express-ws')(app);
const port = config.port || 3000; const port = config.port || 3000;
app.use(express.json()); app.use(express.json());

View file

@ -110,7 +110,7 @@ function getActiveChannels(connection) {
FROM messages FROM messages
JOIN channels ON messages.channel_id = channels.id JOIN channels ON messages.channel_id = channels.id
JOIN users ON messages.user_id = users.id JOIN users ON messages.user_id = users.id
WHERE date > (SELECT max(date) FROM messages) - 7 * 24 * 60 * 60 WHERE date > (SELECT max(date) FROM messages) - 3 * 24 * 60 * 60
GROUP BY channel_id GROUP BY channel_id
ORDER BY count(*) DESC ORDER BY count(*) DESC
LIMIT 5;`, LIMIT 5;`,
@ -124,6 +124,23 @@ function getActiveChannels(connection) {
}); });
} }
function getNewChannels(connection) {
return new Promise((resolve, reject) => {
connection.query(
`SELECT channels.id, name, description, owner_id, username AS owner_username
FROM channels
JOIN users ON channels.owner_id = users.id
ORDER BY channels.id DESC LIMIT 5`,
(error, result) => {
if (error) {
reject(new Error(error));
}
resolve(result);
}
);
});
}
function searchChannels(connection, search) { function searchChannels(connection, search) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
connection.query( connection.query(
@ -319,6 +336,7 @@ module.exports = {
getUserLastMessages, getUserLastMessages,
getChannels, getChannels,
getActiveChannels, getActiveChannels,
getNewChannels,
searchChannels, searchChannels,
getChannel, getChannel,
addChannel, addChannel,

View file

@ -16,6 +16,7 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"express-ws": "^5.0.2",
"fs": "^0.0.1-security", "fs": "^0.0.1-security",
"https": "^1.0.0", "https": "^1.0.0",
"jsonwebtoken": "^9.0.2", "jsonwebtoken": "^9.0.2",

View file

@ -1387,6 +1387,18 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/node": {
"version": "22.14.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.14.0.tgz",
"integrity": "sha512-Kmpl+z84ILoG+3T/zQFyAJsU6EPTmOCj8/2+83fSN6djd6I4o7uOuGIH6vq3PrjY5BGitSbFuMN18j3iknubbA==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true,
"dependencies": {
"undici-types": "~6.21.0"
}
},
"node_modules/@types/react": { "node_modules/@types/react": {
"version": "19.0.12", "version": "19.0.12",
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.0.12.tgz", "resolved": "https://registry.npmjs.org/@types/react/-/react-19.0.12.tgz",
@ -3400,6 +3412,15 @@
"typescript": ">=4.8.4 <5.9.0" "typescript": ">=4.8.4 <5.9.0"
} }
}, },
"node_modules/undici-types": {
"version": "6.21.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz",
"integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==",
"dev": true,
"license": "MIT",
"optional": true,
"peer": true
},
"node_modules/update-browserslist-db": { "node_modules/update-browserslist-db": {
"version": "1.1.3", "version": "1.1.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz", "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.3.tgz",

View file

@ -19,6 +19,8 @@ export default function MessageComponent({ message, user, channel, deleteMessage
if (mention) { if (mention) {
return <span><Link key={index} to={`/u/${mention.username}`}>{word}</Link> </span>; return <span><Link key={index} to={`/u/${mention.username}`}>{word}</Link> </span>;
} }
} else if (word.startsWith("https://") || word.startsWith("http://")) {
return <span><Link to={word}>{word}</Link> </span>
} }
return <span key={index}>{word} </span>; return <span key={index}>{word} </span>;
})} })}

View file

@ -1,5 +1,6 @@
html { html {
background: linear-gradient(#FFE0E3, #f59ebb); background: linear-gradient(#FFE0E3, #f59ebb);
min-height: 100vh;
} }
.cat { .cat {

View file

@ -71,15 +71,17 @@ export default function ChannelPage() {
}, [name]); }, [name]);
useEffect(() => { useEffect(() => {
const id = setInterval(() => { const socket = new WebSocket(`/api/channels/${name}`);
socket.addEventListener('message', function (event) {
if (event.data === "new_message" || event.data === "delete_message") {
axios axios
.get(`/api/channels/${name}/messages`).then((res) => { .get(`/api/channels/${name}/messages`).then((res) => {
setMessages(res.data) setMessages(res.data)
}) })
}, 2000) }
});
return () => { clearInterval(id) } }, [name])
}, [])
useEffect(() => { useEffect(() => {
const words = message.toString().split(" "); const words = message.toString().split(" ");
@ -102,7 +104,14 @@ export default function ChannelPage() {
if (!channel || !messages) { if (!channel || !messages) {
return <div>Loading...</div>; return (
<div className="channel-page">
<TopBar user={user} />
<div className="channel">
<p>Loading...</p>
</div>
</div>
)
} }
return ( return (

View file

@ -34,22 +34,40 @@ export default function ChannelsPage() {
}, []) }, [])
useEffect(() => { useEffect(() => {
const id = setInterval(() => { const socket = new WebSocket("/api/channels");
axios
.get("/api/channels").then((res) => {
setChannels(res.data)
}
)
}, 2000)
return () => { clearInterval(id) } socket.addEventListener('message', function (event) {
if (event.data === "new_channel") {
axios
.get("/api/channels")
.then((res) => {
setChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
}
});
}, []) }, [])
if (!channels) {
return (
<div className="channels-page">
<TopBar user={user} />
<div className="channels-page-channels">
<h2>Channels</h2>
<p>Loading...</p>
</div>
</div>
)
}
return ( return (
<div className="channels-page"> <div className="channels-page">
<TopBar user={user} /> <TopBar user={user} />
<div className="channels-page-channels"> <div className="channels-page-channels">
<h2>Channels</h2> <h2>Channels</h2>
<Link to="/create-channel">Create channel</Link>
<input <input
type="text" type="text"
placeholder="Search channels" placeholder="Search channels"
@ -57,7 +75,7 @@ export default function ChannelsPage() {
onChange={(e) => setSearch(e.target.value)} onChange={(e) => setSearch(e.target.value)}
/> />
<ul> <ul>
{channels?.filter((channel) => channel.name.toLowerCase().includes(search.toLowerCase())).map((channel) => ( {channels?.sort().filter((channel) => channel.name.toLowerCase().includes(search.toLowerCase())).map((channel) => (
<li key={channel.id}> <li key={channel.id}>
<Link to={`/c/${channel.name}`}>{channel.name}</Link> <Link to={`/c/${channel.name}`}>{channel.name}</Link>
</li> </li>

View file

@ -31,7 +31,7 @@ export default function CreateChannel() {
axios axios
.post("/api/channels/add", { name, description, token }) .post("/api/channels/add", { name, description, token })
.then(() => { .then(() => {
navigate("/"); navigate(`/c/${name}`);
}) })
.catch((err) => { .catch((err) => {
console.error(err.response.data.message); console.error(err.response.data.message);

View file

@ -12,6 +12,7 @@ export default function Home() {
const [channels, setChannels] = useState<RecentChannels>(); const [channels, setChannels] = useState<RecentChannels>();
const [messages , setMessages] = useState<Messages>(); const [messages , setMessages] = useState<Messages>();
const [searchedChannels, setSearchedChannels] = useState<Channels>([]); const [searchedChannels, setSearchedChannels] = useState<Channels>([]);
const [newChannels, setNewChannels] = useState<Channels>([]);
const [search, setSearch] = useState<string>(""); const [search, setSearch] = useState<string>("");
useEffect(() => { useEffect(() => {
@ -45,27 +46,60 @@ export default function Home() {
}) })
.catch((err) => { .catch((err) => {
console.error(err.response) console.error(err.response)
} })
)
axios
.get("/api/newchannels")
.then((res) => {
setNewChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
}, []) }, [])
useEffect(() => { useEffect(() => {
const id = setInterval(() => { const socket = new WebSocket("/api/channels");
axios
.get("/api/activechannels").then((res) => {
setChannels(res.data)
}
)
socket.addEventListener('message', function (event) {
if (event.data === "new_message" || event.data === "delete_message") {
axios axios
.get("/api/lastmessages").then((res) => { .get("/api/lastmessages")
.then((res) => {
setMessages(res.data) setMessages(res.data)
})
.catch((err) => {
console.error(err.response)
})
axios
.get("/api/activechannels")
.then((res) => {
setChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
} else if (event.data === "new_channel") {
axios
.get("/api/activechannels")
.then((res) => {
setChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
axios
.get("/api/newchannels")
.then((res) => {
setNewChannels(res.data)
})
.catch((err) => {
console.error(err.response)
})
} }
) });
}, 2000)
return () => { clearInterval(id) }
}, []) }, [])
useEffect(() => { useEffect(() => {
@ -125,6 +159,16 @@ export default function Home() {
))} ))}
</ul> </ul>
</div> </div>
<div className="channels-new">
<h3>Last created channels</h3>
<ul>
{newChannels?.map((channel) => (
<li key={channel.id}>
<Link to={`/c/${channel.name}`}>{channel.name}</Link>
</li>
))}
</ul>
</div>
<div className="channels-search"> <div className="channels-search">
<h3>Search channels</h3> <h3>Search channels</h3>
<input <input

View file

@ -34,17 +34,6 @@ export default function UserPage() {
}); });
}, [username]); }, [username]);
useEffect(() => {
const id = setInterval(() => {
axios
.get(`/api/users/${username}/lastmessages`).then((res) => {
setMessages(res.data)
})
}, 2000)
return () => { clearInterval(id) }
}, [username])
if (!pageUser) { if (!pageUser) {
return <div>Loading...</div>; return <div>Loading...</div>;
} }
@ -55,6 +44,7 @@ export default function UserPage() {
<div className="user"> <div className="user">
<h2>{pageUser.username}</h2> <h2>{pageUser.username}</h2>
{pageUser.admin ? <p>Admin</p> : <p>User</p>} {pageUser.admin ? <p>Admin</p> : <p>User</p>}
</div>
<div className="user-messages"> <div className="user-messages">
<h2>Last messages</h2> <h2>Last messages</h2>
<div className="messages-list"> <div className="messages-list">
@ -70,6 +60,5 @@ export default function UserPage() {
</div> </div>
</div> </div>
</div> </div>
</div>
); );
} }

View file

@ -4,7 +4,6 @@
justify-content: start; justify-content: start;
align-items: center; align-items: center;
width: 100%; width: 100%;
min-height: 100vh;
gap: 20px; gap: 20px;
} }

View file

@ -4,7 +4,6 @@
justify-content: start; justify-content: start;
align-items: center; align-items: center;
width: 100%; width: 100%;
min-height: 100vh;
gap: 20px; gap: 20px;
} }
@ -13,4 +12,8 @@
border: 1px solid #270722; border: 1px solid #270722;
padding: 10px; padding: 10px;
background-color: #fff6fd; background-color: #fff6fd;
display: flex;
flex-direction: column;
align-items: start;
gap: 10px;
} }

View file

@ -4,7 +4,6 @@
justify-content: start; justify-content: start;
align-items: center; align-items: center;
width: 100%; width: 100%;
min-height: 100vh;
gap: 20px; gap: 20px;
} }
@ -18,8 +17,12 @@
} }
.user-messages { .user-messages {
width: 97%;
border: 1px solid #270722; border: 1px solid #270722;
padding: 10px; padding: 10px;
display: flex;
flex-direction: column;
background-color: #fff6fd;
} }
.messages-list { .messages-list {