Skip to content
17 changes: 12 additions & 5 deletions dbTools.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,21 @@ async function clearFiles() {

sequelize.sync({ alter: true })
.then(() => {
if (process.argv[2].toLowerCase() == "reset") {
resetDB()
} else if (process.argv[2].toLowerCase() == "clearfiles") {
clearFiles()
} else {
const tools = process.argv.slice(2)
if (tools.length == 0) {
console.log("No tool activated.")
return
}
console.log(`Tools activated: ${tools.join(", ")}`)
console.log()

if (tools.includes("reset")) {
resetDB()
}

if (tools.includes("clearfiles")) {
clearFiles()
}
})
.catch(err => {
console.error(err)
Expand Down
61 changes: 6 additions & 55 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@ const SEQUELIZE_ACTIVE = true;

// Set up services
const Universal = require('./services/Universal')
const FileOps = require('./services/FileOps')

const Logger = require('./services/Logger')
Logger.setup()
Expand All @@ -33,7 +32,7 @@ FileManager.setup().catch(err => { Logger.logAndThrow(err) })
const checkHeaders = require('./middleware/headersCheck');
const logRoutes = require('./middleware/logRoutes');

// Configure express app
// Configure express app and chat web socket server
const app = express();
app.use(cors())
app.use(express.json())
Expand Down Expand Up @@ -68,59 +67,9 @@ app.use("/listings", require("./routes/listings/listings"));
app.use("/", require("./routes/orders/listingDetails"));

async function onDBSynchronise() {
const currentDatetime = new Date()
const datetime = new Date(currentDatetime.getTime() + 24 * 60 * 60 * 1000).toISOString();

const listings = await FoodListing.findAll()
if (listings.length > 0) {
Universal.data["DUMMY_LISTING_ID"] = listings[0].listingID
console.log(`Found existing listing, using as dummy. Listing ID: ${listings[0].listingID}`)
} else {
const newListing = await FoodListing.create({
listingID: uuidv4(),
title: "Chili Crab for Dinner",
images: "sample3.jpg",
shortDescription: "Making chili crab for dinner again! Come join!",
longDescription: "Seeing that chili crab last time was a hit, cooking some again! Bought fresh groceries from the market today for it too. Come join me for dinner!",
portionPrice: "5.00",
approxAddress: "Near Tampines West Community Centre, Singapore",
address: "Block 67, Tampines Avenue 10, Singapore 520678",
totalSlots: "5",
datetime: datetime,
published: false
})
Universal.data["DUMMY_LISTING_ID"] = newListing.listingID
console.log(`Created new dummy listing. Listing ID: ${newListing.listingID}`)

}

const hosts = await Host.findAll()
if (hosts.length > 0) {
Universal.data["DUMMY_HOST_ID"] = (hosts[0].userID)
console.log(`Found existing dummy host. Host ID: ${Universal.data["DUMMY_HOST_ID"]}`)
} else {
const newHost = await Host.create({
"userID": "272d3d17-fa63-49c4-b1ef-1a3b7fe63cf4",
"username": "Jamie Oliver",
"email": "jamie_oliver@gmail.com",
"password": "JamieOliver123",
"contactNum": "81118222",
"address": "Block 123, Hougang Avenue 1, #01-234",
"emailVerified": "false",
"favCuisine": "Chilli Crab",
"mealsMatched": "0",
"foodRating": "4",
"hygieneGrade": "5",
"paymentImage": null,
"resetKeyExpiration": null
})
Universal.data["DUMMY_HOST_ID"] = newHost.userID
console.log(`Created new dummy host. Host ID: ${newHost.userID}`)
}

const guests = await Guest.findAll()
if (guests.length > 0) {
Universal.data["DUMMY_GUEST_USERID"] = guests[0].userID
Universal.data["DUMMY_GUEST_ID"] = guests[0].userID
Universal.data["DUMMY_GUEST_USERNAME"] = guests[0].username
console.log(`Found existing guest, using as dummy. Guest User ID: ${guests[0].userID}`)
} else {
Expand All @@ -137,7 +86,7 @@ async function onDBSynchronise() {
resetKey: "265c18",
resetKeyExpiration: "2024-06-22T14:30:00.000Z"
})
Universal.data["DUMMY_GUEST_USERID"] = newGuest.userID
Universal.data["DUMMY_GUEST_ID"] = newGuest.userID
Universal.data["DUMMY_GUEST_USERNAME"] = newGuest.username
console.log(`Created dummy guest with User ID: ${newGuest.userID}`)
}
Expand All @@ -162,11 +111,13 @@ async function onDBSynchronise() {
if (!newHost) {
console.log("WARNING: Failed to create dummy host.")
} else {
Universal.data["DUMMY_HOST_ID"] = newHost.userID
Universal.data["DUMMY_HOST_USERNAME"] = newHost.username
Universal.data["DUMMY_HOST_FOODRATING"] = newHost.foodRating
console.log("Created dummy host.")
}
} else {
Universal.data["DUMMY_HOST_ID"] = joshuasHost.userID
Universal.data["DUMMY_HOST_USERNAME"] = joshuasHost.username
Universal.data["DUMMY_HOST_FOODRATING"] = joshuasHost.foodRating
console.log("Found dummy host existing already, skipping creation.")
Expand All @@ -181,7 +132,7 @@ if (!SEQUELIZE_ACTIVE) {
} else {
// Server initialisation with sequelize
const db = require("./models");
db.sequelize.sync({ alter: true })
db.sequelize.sync()
.then(() => {
// Create sample FoodListing
onDBSynchronise()
Expand Down
5 changes: 2 additions & 3 deletions routes/cdn/coreData.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ router.get("/fetchHostDetails", async (req, res) => {
})

router.get("/fetchGuestDetails", async (req, res) => {
const targetGuest = await Guest.findByPk(Universal.data["DUMMY_GUEST_USERID"])
const targetGuest = await Guest.findByPk(Universal.data["DUMMY_GUEST_ID"])
if (!targetGuest) {
return res.status(404).send("Dummy Guest not found.");
}
const guestFavCuisine = targetGuest.favCuisine;
const guestDetails = {
guestUserID: Universal.data["DUMMY_GUEST_USERID"],
guestUserID: Universal.data["DUMMY_GUEST_ID"],
guestUsername: Universal.data["DUMMY_GUEST_USERNAME"],
guestFavCuisine: guestFavCuisine
}
Expand Down Expand Up @@ -131,7 +131,6 @@ router.get("/accountInfo", async (req, res) => { // GET account information
accountInfo.mealsMatched = user.mealsMatched;
}

// console.log(`Account info for userID ${targetUserID}: ${JSON.stringify(accountInfo)}`)
res.status(200).json(accountInfo);

} catch (err) {
Expand Down
187 changes: 95 additions & 92 deletions routes/chat/WebSocketServer.js
Original file line number Diff line number Diff line change
@@ -1,108 +1,111 @@
const express = require("express");
const http = require("http");
const WebSocket = require("ws");
const { ChatHistory, ChatMessage } = require("../../models");
const Universal = require("../../services/Universal");
const Cache = require("../../services/Cache");

function startWebSocketServer(app) {
const PORT = 8080;

const server = http.createServer(app);

const wss = new WebSocket.Server({ server });

const clients = [];

wss.on("connection", (ws) => {
console.log("WS connection arrived");
clients.push(ws);

if (!Cache.cache["chat"]) {
Cache.cache["chat"] = {};
}

const cachedMessages = Cache.cache["chat"];
for (const messageId in cachedMessages) {
const message = {
id: messageId,
...cachedMessages[messageId],
};
ws.send(JSON.stringify(message));
}

ws.on("message", (message) => {
const parsedMessage = JSON.parse(message);

Cache.cache["chat"][parsedMessage.id] = {
sender: parsedMessage.sender,
message: parsedMessage.message,
timestamp: parsedMessage.timestamp,
};
Cache.save();

if (parsedMessage.action === "edit") {
handleEditMessage(parsedMessage);
} else if (parsedMessage.action === "delete") {
handleDeleteMessage(parsedMessage);
} else {
broadcastMessage(message, ws);
}
});

ws.on("close", () => {
const index = clients.indexOf(ws);
if (index > -1) {
clients.splice(index, 1);
}
if (!process.env.WS_PORT) { console.log("WARNING: WS_PORT environment variable not set. Defaulting to 8080.") }
const PORT = process.env.WS_PORT || 8080;

const server = http.createServer(app);

const wss = new WebSocket.Server({ server });

const clients = [];

wss.on("connection", (ws) => {
console.log("WS connection arrived");
clients.push(ws);

if (!Cache.cache["chat"]) {
Cache.cache["chat"] = {};
}

const cachedMessages = Cache.cache["chat"];
for (const messageId in cachedMessages) {
const message = {
id: messageId,
...cachedMessages[messageId],
};
ws.send(JSON.stringify(message));
}

ws.on("message", (message) => {
const parsedMessage = JSON.parse(message);

Cache.cache["chat"][parsedMessage.id] = {
sender: parsedMessage.sender,
message: parsedMessage.message,
timestamp: parsedMessage.timestamp,
};
Cache.save();

if (parsedMessage.action === "edit") {
handleEditMessage(parsedMessage);
} else if (parsedMessage.action === "delete") {
handleDeleteMessage(parsedMessage);
} else {
broadcastMessage(message, ws);
}
});

ws.on("close", () => {
const index = clients.indexOf(ws);
if (index > -1) {
clients.splice(index, 1);
}
});
});
});

wss.on("error", (error) => {
console.error("WebSocket server error:", error);
});

function broadcastMessage(message, sender) {
clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(message);
}
wss.on("error", (error) => {
console.error("WebSocket server error:", error);
});
}

function handleDeleteMessage(deleteMessage) {
const messageId = deleteMessage.id;
delete Cache.cache["chat"][messageId];
Cache.save();
function broadcastMessage(message, sender) {
clients.forEach((client) => {
if (client !== sender && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
}

function handleDeleteMessage(deleteMessage) {
const messageId = deleteMessage.id;
delete Cache.cache["chat"][messageId];
Cache.save();

const jsonMessage = JSON.stringify({
id: messageId,
action: "delete",
action: "reload",
});
broadcastMessage(jsonMessage);
}

const jsonMessage = JSON.stringify({
id: messageId,
action: "delete",
action: "reload",
});
broadcastMessage(jsonMessage);
}

function handleEditMessage(editedMessage) {
const messageId = editedMessage.id;
if (Cache.cache["chat"][messageId]) {
Cache.cache["chat"][messageId].message = editedMessage.message;
Cache.cache["chat"][messageId].edited = true;
Cache.save();

const jsonMessage = JSON.stringify({
...Cache.cache["chat"][messageId],
id: messageId,
action: "edit",
action: "reload",
});
broadcastMessage(jsonMessage);
} else {
console.error(`Message with ID ${messageId} not found.`);
function handleEditMessage(editedMessage) {
const messageId = editedMessage.id;
if (Cache.cache["chat"][messageId]) {
Cache.cache["chat"][messageId].message = editedMessage.message;
Cache.cache["chat"][messageId].edited = true;
Cache.save();

const jsonMessage = JSON.stringify({
...Cache.cache["chat"][messageId],
id: messageId,
action: "edit",
action: "reload",
});
broadcastMessage(jsonMessage);
} else {
console.error(`Message with ID ${messageId} not found.`);
}
}
}

server.listen(PORT, () => {
console.log(`WebSocket Server running on port ${PORT}`);
});
server.listen(PORT, () => {
console.log(`WebSocket Server running on port ${PORT}`);
});
}

module.exports = startWebSocketServer;
Loading