Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const express = require('express');
- const MongoClient = require('mongodb').MongoClient;
- const WebSocket = require('ws');
- var cookieParser = require('cookie-parser');
- const sha256 = require('sha256');
- const uuid = require('rand-token').uid;
- const Room = require('./Classes/Room');
- const Client = require('./Classes/Client');
- const Lurker = require('./Classes/Lurker');
- const Message = require('./Classes/Message');
- const Tool = require('./utils/Tool');
- const Logger = require('./utils/Logger');
- const WSHandler = require('./utils/WebSocketHandler');
- const Error = require('./consts/Error')
- const Type = require('./consts/Type');
- let db;
- const app = express();
- let ROOMS = [];
- let ROOMSLIST = [];
- app.use(express.json());
- app.use(express.urlencoded({ extended: false }));
- app.use(cookieParser());
- app.use(function (req, res, next) {
- res.setHeader('Access-Control-Allow-Origin', 'http://app.math');
- res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
- res.setHeader('Access-Control-Allow-Credentials', true);
- res.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
- next();
- })
- //Run websocket server
- const wss = new WebSocket.Server({ port: 8080 });
- wss.on('connection', (ws, req) => {
- ws.on('message', async message => {
- let roomReq;
- try {
- roomReq = JSON.parse(message);
- } catch (e) {
- return;
- }
- //Check if requested room exists
- if (roomReq.type === Type.EXISTS) {
- const room = Tool.getRoomById(ROOMS, roomReq.roomID);
- Logger.WebSocket.request(roomReq.roomID);
- if (room === undefined || room.gameStarted || room.spaceLimit === 0 || Tool.isAlreadyPlaying(ROOMS, roomReq.token))
- return ws.send(JSON.stringify({
- error: Error.ROOMLOADFAILED,
- exists: false
- }));
- //Check if users exists
- const tuser = await Tool.findUserInDatabase(db, roomReq.token);
- if (tuser.length === 0)
- return ws.send(JSON.stringify({
- error: Error.USERNOTFOUND,
- exists: false
- }));
- const user = tuser[0];
- room.spaceLimit--;
- room.clients.push(new Client(user.login, user.token, ws));
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- room.creatorFound = room.creator === roomReq.token;
- ws.token = roomReq.token;
- ws.roomID = roomReq.roomID;
- const formattedClients = Tool.getFormattedClients(room.clients);
- WSHandler.sendClientsUpdateInfo(room, user.token, formattedClients);
- return ws.send(JSON.stringify({
- type: Type.EXISTS,
- error: null,
- exists: true,
- room: {
- roomName: room.name,
- roomID: room.id,
- clients: formattedClients,
- isListed: room.isListed
- },
- creator: room.creator === roomReq.token,
- creatorNick: room.creatorNick,
- spaceLimit: room.spaceLimit,
- nick: user.login
- }));
- }
- //Start a game in the room
- else if (roomReq.type === Type.GAMEINIT) {
- const room = Tool.getRoomById(ROOMS, roomReq.roomID);
- Logger.WebSocket.gameStarted(room.id);
- room.questions = await Tool.getQuestions(db);
- room.gameStarted = true;
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- for (const client of room.clients)
- if (client.socket.readyState !== 3)
- client.socket.send(JSON.stringify({
- type: Type.GAMEINIT,
- error: null,
- questions: room.questions
- }));
- }
- //Client has answered the questions
- else if (roomReq.type === Type.GAMESTOP) {
- const room = Tool.getRoomById(ROOMS, roomReq.roomID);
- const points = roomReq.points;
- const token = roomReq.token;
- Logger.WebSocket.donePlaying(token, room.id);
- room.clients.find(client => client.token === token).currentPoints += points;
- room.clientsDoneCounter++;
- await Tool.updateCurrentProgress(db, token, points, roomReq.correct, roomReq.incorrect);
- //If everyone has ended playing a game, send informations to everyone
- if (room.clientsDoneCounter >= room.clients.length) {
- const formattedClients = Tool.getFormattedClients(room.clients);
- room.gameStarted = false;
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- for (const client of room.clients)
- if (client.socket.readyState !== 3)
- client.socket.send(JSON.stringify({
- type: Type.GAMESTOP,
- error: null,
- clients: formattedClients
- }));
- room.clientsDoneCounter = 0;
- }
- }
- //There is a new message in the room
- else if (roomReq.type === Type.NEWMESSAGE) {
- const room = Tool.getRoomById(ROOMS, roomReq.roomID);
- //If request comes from a person that has recently joined the room,
- //return every message sent till now.
- if (roomReq.new) {
- return ws.send(JSON.stringify({
- type: Type.NEWMESSAGE,
- messages: room.messages
- }))
- }
- room.messages.push(new Message(roomReq.sender, roomReq.content))
- for (client of room.clients) {
- if (client.socket.readyState !== 3) {
- client.socket.send(JSON.stringify({
- type: Type.NEWMESSAGE,
- messages: room.messages
- }))
- }
- }
- }
- //List of available rooms
- else if (roomReq.type === Type.GETROOMS) {
- ROOMSLIST.push(new Lurker(ws, roomReq.token));
- return WSHandler.sendRoomsData(ROOMS, new Array(new Lurker(ws, roomReq.token)));
- }
- //Change if room is listed or not.
- else if (roomReq.type === Type.LISTED) {
- const room = Tool.getRoomById(ROOMS, roomReq.roomID);
- if (room === undefined)
- return;
- room.isListed = roomReq.isListed;
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- WSHandler.changeListedState(room);
- return;
- }
- })
- ws.on('close', async () => {
- const token = ws.token;
- const roomID = ws.roomID;
- const room = Tool.getRoomById(ROOMS, roomID);
- Logger.WebSocket.connectionClosed(token, roomID)
- if (room === undefined)
- return;
- room.spaceLimit++;
- let newClients = room.clients.find(client => client.token !== token)
- if (!Array.isArray(newClients) && newClients !== undefined)
- newClients = new Array(newClients);
- room.clients = newClients;
- if (newClients === undefined || newClients.length === 0) {
- ROOMS = Tool.resetRoom(ROOMS, room);
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- return;
- }
- else if (token === room.creator) {
- const index = Math.floor(Math.random()*(room.clients.length));
- room.creator = room.clients[index].token;
- room.creatorNick = room.clients[index].nick;
- WSHandler.changeCreator(room)
- }
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- WSHandler.sendClientsUpdateInfo(room, null, Tool.getFormattedClients(room.clients));
- return room.clients = newClients;
- })
- })
- //app
- app.get('/api/Account/Logged', async (req, res) => {
- const cookie = req.cookies.mathimeauth;
- const acc = await Tool.findUserInDatabase(db, cookie);
- if (acc.length === 0)
- return res.send(JSON.stringify({
- isLogged: false
- }));
- return res.send(JSON.stringify({
- isLogged: true,
- login: acc[0].login
- }));
- })
- //Create new room
- app.post('/api/Room/Create', async (req, res) => {
- const roomName = req.body.room;
- const token = req.cookies.mathimeauth;
- const roomID = uuid(16);
- if (token === undefined || Tool.isAlreadyPlaying(ROOMS, token))
- return res.send(JSON.stringify({
- hbCreated: false
- }));
- const acc = await Tool.findUserInDatabase(db, token);
- const room = new Room(roomID, roomName, token, acc[0].login);
- ROOMS.push(room);
- WSHandler.sendRoomsData(ROOMS, ROOMSLIST);
- Logger.backend.newRoom(token, roomName);
- return res.send({
- roomCreated: true,
- roomID: roomID,
- roomName: roomName
- });
- })
- // Handling register and login
- app.post('/api/Account/Login', async (req, response) => {
- const dbo = db.db('mathime');
- const login = req.body.login;
- const password = sha256(req.body.password);
- const acc = await Tool.findUserInDatabaseByName(db, login);
- if (acc.length === 0 || acc[0].password !== password) {
- return response.send(JSON.stringify({
- isLogged: false
- }));
- }
- const token = uuid(32);
- const obj = {
- $set: {
- token: token
- }
- }
- await dbo.collection('users').updateOne({login: login}, obj, (err)=> {
- if (err)
- throw err
- Logger.backend.loggedIn(login);
- response.cookie('mathimeauth', token, {expires: new Date(Date.now() + 1000*60*60*24*14), path: '/' });
- response.send(JSON.stringify({
- isLogged: true,
- token: token
- }));
- })
- })
- //Create an account
- app.post('/api/Account/Register', async (req, response) => {
- const dbo = db.db('mathime');
- const login = req.body.login;
- const password = sha256(req.body.password);
- const email = req.body.email;
- const token = uuid(32);
- const obj = {
- token: token,
- login: login,
- password: password,
- email: email,
- points: 0,
- correct: 0,
- incorrect: 0,
- gamesPlayed: 0
- }
- const acc = await Tool.findUserInDatabaseByName(db, login);
- if (acc.length !== 0)
- return response.send(JSON.stringify({
- hbCreated: false
- }));
- await dbo.collection('users').insertOne(obj, (err, res) => {
- if (err)
- return response.send(JSON.stringify({
- hbCreated: false
- }));
- Logger.backend.newAccount(login);
- response.cookie('mathimeauth', token, { expires: new Date(Date.now() + 1000*60*60*24*14), path: '/' });
- response.send(JSON.stringify({
- hbCreated: true,
- token: token
- }));
- })
- })
- //Return requested profile (is exists)
- app.post('/api/Profile/Fetch', async (req, response) => {
- const nick = req.body.nick;
- const user = await Tool.findUserInDatabaseByName(db, nick);
- if (user.length === 0)
- return response.send(JSON.stringify({
- fetched: false,
- profile: null
- }))
- return response.send(JSON.stringify({
- fetched: true,
- profile: {
- nick: user[0].login,
- points: user[0].points,
- correct: user[0].correct,
- incorrect: user[0].incorrect,
- gamesPlayed: user[0].gamesPlayed
- }
- }))
- })
- app.get('/api/Ranking/Get', async (req, response) => {
- const users = await db.db('mathime').collection('users')
- .find({}, {sort: {points: -1}, fields: { _id: 0, login: 1, points: 1 }})
- .limit(100)
- .toArray();
- return response.send(JSON.stringify({
- fetched: true,
- users: users
- }))
- })
- MongoClient.connect('mongodb://localhost:27017/', (err, database) => {
- if (err)
- throw err;
- console.log('[Database] Running at 27017');
- db = database;
- app.listen(3000, () => {
- Logger.backend.running();
- })
- })
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement