Files
relay/server/socket/socket.js

111 lines
3.0 KiB
JavaScript

const { Server } = require("socket.io");
const {
insertMessage,
getMessages,
insertContact,
getContacts,
} = require("../db/db");
const { verifyJwtToken } = require("../auth/jwt");
const console = require("node:console");
function initializeSocket(io) {
io.use((socket, next) => {
const token = socket.handshake.auth.token;
if (!token) {
console.log("(socket) Not logged in");
return next(new Error("Not logged in"));
}
try {
const { username, user_id } = verifyJwtToken(token);
if (!username || !user_id) {
console.log("Invalid token payload");
return next(new Error("Invalid token payload"));
}
socket.username = username;
socket.user_id = user_id;
console.log(
`socket id: ${socket.id}, username: ${username}, user_id: ${user_id}`,
);
next();
} catch (error) {
console.error("Token verification failed:", error.message);
next(new Error("Invalid token"));
}
});
io.on("connection", async (socket) => {
const username = socket.username;
if (!username) {
socket.on("disconnect", () => {
console.log(socket.id, " disconnected due to: invalid username/token");
});
return;
}
socket.join(username); // join username room
const sendContactList = async () => {
const contacts = await getContacts(username);
io.to(username).emit("contacts list", contacts);
console.log("sent on 'contacts list: ", contacts);
};
await sendContactList(username);
socket.on("chat message", async (msg) => {
const { message, recipient, timestamp } = msg;
const sender = username;
if (!message || recipient.length < 4 || !recipient) {
return;
}
const insertedMessage = await insertMessage(
username,
recipient,
message,
timestamp,
);
const message_id = insertedMessage.message_id;
console.log("received from chat message", msg);
io.to(username).to(recipient).emit("chat message", {
sender,
message,
recipient,
timestamp,
message_id,
});
console.log("sent on 'chat message' socket: ", {
sender,
message,
recipient,
timestamp,
message_id,
});
});
socket.on("historical", async (recipient) => {
const messages = await getMessages(username, recipient.recipient);
io.to(username).emit("historical", messages);
});
socket.on("add contact", (contactInf) => {
let { contact, read } = contactInf;
if (contact) {
if (contact.length < 4 || contact.length > 20) {
return;
}
}
insertContact(username, contact, read);
io.to(username).emit("contact", { contact, read });
console.log("sent on 'contact' socket: ", { contact, read });
});
socket.on("disconnect", (reason) => {
console.log(socket.id, " disconnected due to: ", reason);
});
});
}
module.exports = { initializeSocket };