|
| 1 | +import express from "express"; |
| 2 | +import { connectDB } from "./utils/features.js"; |
| 3 | +import dotenv from "dotenv"; |
| 4 | +import { errorMiddleware } from "./middlewares/error.js"; |
| 5 | +import cookieParser from "cookie-parser"; |
| 6 | +import { Server } from "socket.io"; |
| 7 | +import { createServer } from "http"; |
| 8 | +import { v4 as uuid } from "uuid"; |
| 9 | +import cors from "cors"; |
| 10 | +import { v2 as cloudinary } from "cloudinary"; |
| 11 | +import { |
| 12 | + CHAT_JOINED, |
| 13 | + CHAT_LEAVED, |
| 14 | + NEW_MESSAGE, |
| 15 | + NEW_MESSAGE_ALERT, |
| 16 | + ONLINE_USERS, |
| 17 | + START_TYPING, |
| 18 | + STOP_TYPING, |
| 19 | +} from "./constants/events.js"; |
| 20 | +import { getSockets } from "./lib/helper.js"; |
| 21 | +import { Message } from "./models/message.js"; |
| 22 | +import { corsOptions } from "./constants/config.js"; |
| 23 | +import { socketAuthenticator } from "./middlewares/auth.js"; |
| 24 | + |
| 25 | +import userRoute from "./routes/user.js"; |
| 26 | +import chatRoute from "./routes/chat.js"; |
| 27 | +import adminRoute from "./routes/admin.js"; |
| 28 | + |
| 29 | +dotenv.config({ |
| 30 | + path: "./.env", |
| 31 | +}); |
| 32 | + |
| 33 | +const mongoURI = process.env.MONGO_URI; |
| 34 | +const port = process.env.PORT || 3000; |
| 35 | +const envMode = process.env.NODE_ENV.trim() || "PRODUCTION"; |
| 36 | +const adminSecretKey = process.env.ADMIN_SECRET_KEY || "adsasdsdfsdfsdfd"; |
| 37 | +const userSocketIDs = new Map(); |
| 38 | +const onlineUsers = new Set(); |
| 39 | + |
| 40 | +connectDB(mongoURI); |
| 41 | + |
| 42 | +cloudinary.config({ |
| 43 | + cloud_name: process.env.CLOUDINARY_CLOUD_NAME, |
| 44 | + api_key: process.env.CLOUDINARY_API_KEY, |
| 45 | + api_secret: process.env.CLOUDINARY_API_SECRET, |
| 46 | +}); |
| 47 | + |
| 48 | +const app = express(); |
| 49 | +const server = createServer(app); |
| 50 | +const io = new Server(server, { |
| 51 | + cors: corsOptions, |
| 52 | +}); |
| 53 | + |
| 54 | +app.set("io", io); |
| 55 | + |
| 56 | +// Using Middlewares Here |
| 57 | +app.use(express.json()); |
| 58 | +app.use(cookieParser()); |
| 59 | +app.use(cors(corsOptions)); |
| 60 | + |
| 61 | +app.use("/api/v1/user", userRoute); |
| 62 | +app.use("/api/v1/chat", chatRoute); |
| 63 | +app.use("/api/v1/admin", adminRoute); |
| 64 | + |
| 65 | +app.get("/", (req, res) => { |
| 66 | + res.send("Hello World"); |
| 67 | +}); |
| 68 | + |
| 69 | +//middleware for socket authentication |
| 70 | +io.use((socket, next) => { |
| 71 | + cookieParser()( |
| 72 | + //can read cookies). |
| 73 | + socket.request, |
| 74 | + socket.request.res, |
| 75 | + async (err) => await socketAuthenticator(err, socket, next) //method for authenticating socket connections |
| 76 | + ); |
| 77 | +}); |
| 78 | + |
| 79 | +io.on("connection", (socket) => { |
| 80 | + console.log("New client connected:", socket.id); |
| 81 | + const user = socket.user; |
| 82 | + userSocketIDs.set(user._id.toString(), socket.id); |
| 83 | + console.log(`User connected: ${user.name}`); |
| 84 | + |
| 85 | + socket.on(NEW_MESSAGE, async ({ chatId, members, message }) => { |
| 86 | + const messageForRealTime = { |
| 87 | + content: message, |
| 88 | + _id: uuid(), |
| 89 | + sender: { |
| 90 | + _id: user._id, |
| 91 | + name: user.name, |
| 92 | + }, |
| 93 | + chat: chatId, |
| 94 | + createdAt: new Date().toISOString(), |
| 95 | + }; |
| 96 | + |
| 97 | + const messageForDB = { |
| 98 | + content: message, |
| 99 | + sender: user._id, |
| 100 | + chat: chatId, |
| 101 | + }; |
| 102 | + |
| 103 | + const membersSocket = getSockets(members); |
| 104 | + io.to(membersSocket).emit(NEW_MESSAGE, { |
| 105 | + chatId, |
| 106 | + message: messageForRealTime, |
| 107 | + }); |
| 108 | + io.to(membersSocket).emit(NEW_MESSAGE_ALERT, { chatId }); |
| 109 | + |
| 110 | + try { |
| 111 | + await Message.create(messageForDB); |
| 112 | + } catch (error) { |
| 113 | + throw new Error(error); |
| 114 | + } |
| 115 | + }); |
| 116 | + |
| 117 | + socket.on(START_TYPING, ({ members, chatId }) => { |
| 118 | + const membersSockets = getSockets(members); |
| 119 | + socket.to(membersSockets).emit(START_TYPING, { chatId }); |
| 120 | + }); |
| 121 | + |
| 122 | + socket.on(STOP_TYPING, ({ members, chatId }) => { |
| 123 | + const membersSockets = getSockets(members); |
| 124 | + socket.to(membersSockets).emit(STOP_TYPING, { chatId }); |
| 125 | + }); |
| 126 | + |
| 127 | + socket.on(CHAT_JOINED, ({ userId, members }) => { |
| 128 | + onlineUsers.add(userId.toString()); |
| 129 | + |
| 130 | + const membersSocket = getSockets(members); |
| 131 | + io.to(membersSocket).emit(ONLINE_USERS, Array.from(onlineUsers)); |
| 132 | + }); |
| 133 | + |
| 134 | + socket.on(CHAT_LEAVED, ({ userId, members }) => { |
| 135 | + onlineUsers.delete(userId.toString()); |
| 136 | + |
| 137 | + const membersSocket = getSockets(members); |
| 138 | + io.to(membersSocket).emit(ONLINE_USERS, Array.from(onlineUsers)); |
| 139 | + }); |
| 140 | + |
| 141 | + socket.on("disconnect", () => { |
| 142 | + userSocketIDs.delete(user._id.toString()); |
| 143 | + onlineUsers.delete(user._id.toString()); |
| 144 | + socket.broadcast.emit(ONLINE_USERS, Array.from(onlineUsers)); |
| 145 | + }); |
| 146 | +}); |
| 147 | + |
| 148 | +app.use(errorMiddleware); |
| 149 | + |
| 150 | +server.listen(port, () => { |
| 151 | + console.log(`Server is running on port ${port} in ${envMode} Mode`); |
| 152 | +}); |
| 153 | + |
| 154 | +export { envMode, adminSecretKey, userSocketIDs }; |
0 commit comments