Spaces:
Runtime error
Runtime error
File size: 4,217 Bytes
c13f601 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 |
import express from "express";
import bodyParser from "body-parser";
import { getDB } from "./db.js";
import { lucia } from "./auth.js";
import { generateId, verifyRequestOrigin } from "lucia";
import { loginSchema, signUpSchema } from "./schemas.js";
import bcrypt from "bcrypt";
import dotenv from "dotenv";
import cors from "cors";
import mutler from "multer";
import { Server, Socket } from "socket.io";
import http from "http";
import path from "path";
import { authCookieMiddleware, isAuthAPIMiddleware, isAuthSocketMiddleware, login_handler, signup_handler } from "./authHandler.js";
import {
getMyChats,
getLastMessage,
getUnseenCount,
searchContacts,
addMessage,
markMessageSeen,
getAllMessages,
getContact,
} from "./chatHandler.js";
dotenv.config();
const __dirname = path.resolve();
var db = getDB();
var app = express();
const server = http.createServer(app);
const allowedOrigins = process.env.ALLOWED_ORIGINS || 'http://localhost:3001'
const allowed_origins = allowedOrigins.split(",").map(item => item.trim());
app.use(cors({
credentials: true,
// origin: true,
origin: allowed_origins,
}));
// parse application/json
app.use(bodyParser.json());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// app.use(express.urlencoded());
app.use(mutler().array(""));
// The entire build/web directory is statically served.
app.use(express.static(path.join(__dirname, "../client/build")));
app.use(authCookieMiddleware);
// http://localhost:3000/session
app.get("/session", (req, res) => {
if (!res.locals.user) {
return res.status(403).send();
}
return res.status(200).send(res.locals.user);
})
app.post("/signup", signup_handler);
app.post("/login", login_handler);
app.get("/test", (req,res)=>{
console.log(req);
// console.log(res);
res.send("ok");
});
// Catch all. If we want to add pages later, then we should probably change this.
app.get("*", (_req, res) => {
res.sendFile(path.join(__dirname + "/../client/build/index.html"));
});
// socket.io server
const io = new Server(server, {
cors: {
origin: allowed_origins,
methods: ["GET", "POST"],
credentials: true,
}
});
io.use(isAuthSocketMiddleware);
io.on("connection", async (socket) => {
console.log(`socket ${socket.id} connected`);
// client.emit("search_contacts","ankit")
socket.on("search_contacts",(search_string:string)=>{
const contacts = searchContacts(socket.data.user.id,search_string);
socket.emit("search_results",contacts);
})
//Old chats
socket.on("get_chats", async () => {
// get all chats of client
const chats = getMyChats(socket.data.user.id);
socket.emit("chats", chats);
})
socket.on("get_messages", async (chat_id) => {
var messages = getAllMessages(socket.data.user.id, chat_id);
// console.log(socket.data.user.id, chat_id);
// console.log(messages);
socket.emit("messages", messages);
});
socket.on("send_message", async (data) => {
// an event was received from the client
console.log(data);
const message = addMessage({
content: data.content,
type: data.type,
sender_id: socket.data.user.id,
receiver_id: data.receiver_id,
})
console.log("saved message:", message.content , "from:",message.sender_id);
const sockets = await io.fetchSockets();
const receivers = sockets.filter((client)=>client.data.user.id==data.receiver_id);
receivers.forEach((client)=>{
client.emit("receive_message",message);
})
socket.emit("receive_message",message);
});
socket.on("mark_messages_seen", async (msg_ids: any) => {
// console.log(messages.length)
msg_ids.forEach((msg_id:any)=>{
markMessageSeen(socket.data.user.id,msg_id);
})
})
socket.on("get_contact", async contact_id => {
const contact: any = getContact(socket.data.user.id,contact_id);
socket.emit("contact", contact);
})
// upon disconnection
socket.on("disconnect", (reason) => {
console.log(`socket ${socket.id} disconnected due to ${reason}`);
});
});
const port = 3000;
server.listen(port, () => {
console.log(`Running at port ${port}`);
});
|