123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772 |
- /**
- * @file
- */
- import config from "config";
- import async from "async";
- import socketio from "socket.io";
- import CoreClass from "../core";
- let IOModule;
- let AppModule;
- let CacheModule;
- let UtilsModule;
- let DBModule;
- let PunishmentsModule;
- class _IOModule extends CoreClass {
- // eslint-disable-next-line require-jsdoc
- constructor() {
- super("io");
- IOModule = this;
- }
- /**
- * Initialises the io module
- *
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async initialize() {
- this.setStage(1);
- AppModule = this.moduleManager.modules.app;
- CacheModule = this.moduleManager.modules.cache;
- UtilsModule = this.moduleManager.modules.utils;
- DBModule = this.moduleManager.modules.db;
- PunishmentsModule = this.moduleManager.modules.punishments;
- this.actions = (await import("./actions")).default;
- this.userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
- this.setStage(2);
- this.SIDname = config.get("cookie.SIDname");
- // TODO: Check every 30s/, for all sockets, if they are still allowed to be in the rooms they are in, and on socket at all (permission changing/banning)
- const server = await AppModule.runJob("SERVER");
- this._io = socketio(server);
- return new Promise(resolve => {
- this.setStage(3);
- this._io.use(async (socket, cb) => {
- IOModule.runJob("HANDLE_IO_USE", { socket, cb });
- });
- this.setStage(4);
- this._io.on("connection", async socket => {
- IOModule.runJob("HANDLE_IO_CONNECTION", { socket });
- });
- this.setStage(5);
- return resolve();
- });
- }
- /**
- * Returns the socket io variable
- *
- * @returns {Promise} - returns a promise (resolve, reject)
- */
- IO() {
- return new Promise(resolve => {
- resolve(IOModule._io);
- });
- }
- /**
- * Returns whether there is a socket for a session id or not
- *
- * @param {object} payload - object containing the payload
- * @param {string} payload.sessionId - user session id
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKET_FROM_SESSION(payload) {
- // socketId
- return new Promise((resolve, reject) => {
- const ns = IOModule._io.of("/");
- if (ns) {
- return resolve(ns.connected[payload.socketId]);
- }
- return reject();
- });
- }
- /**
- * Gets all sockets for a specified session id
- *
- * @param {object} payload - object containing the payload
- * @param {string} payload.sessionId - user session id
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKETS_FROM_SESSION_ID(payload) {
- return new Promise(resolve => {
- const ns = IOModule._io.of("/");
- const sockets = [];
- if (ns) {
- return async.each(
- Object.keys(ns.connected),
- (id, next) => {
- const { session } = ns.connected[id];
- if (session.sessionId === payload.sessionId) sockets.push(session.sessionId);
- next();
- },
- () => {
- resolve({ sockets });
- }
- );
- }
- return resolve();
- });
- }
- /**
- * Returns any sockets for a specific user
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.userId - the user id
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKETS_FROM_USER(payload) {
- return new Promise((resolve, reject) => {
- const ns = IOModule._io.of("/");
- const sockets = [];
- if (ns) {
- return async.each(
- Object.keys(ns.connected),
- (id, next) => {
- const { session } = ns.connected[id];
- CacheModule.runJob(
- "HGET",
- {
- table: "sessions",
- key: session.sessionId
- },
- this
- )
- .then(session => {
- if (session && session.userId === payload.userId) sockets.push(ns.connected[id]);
- next();
- })
- .catch(err => {
- next(err);
- });
- },
- err => {
- if (err) return reject(err);
- return resolve({ sockets });
- }
- );
- }
- return resolve();
- });
- }
- /**
- * Returns any sockets from a specific ip address
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.ip - the ip address in question
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKETS_FROM_IP(payload) {
- return new Promise(resolve => {
- const ns = IOModule._io.of("/");
- const sockets = [];
- if (ns) {
- return async.each(
- Object.keys(ns.connected),
- (id, next) => {
- const { session } = ns.connected[id];
- CacheModule.runJob(
- "HGET",
- {
- table: "sessions",
- key: session.sessionId
- },
- this
- )
- .then(session => {
- if (session && ns.connected[id].ip === payload.ip) sockets.push(ns.connected[id]);
- next();
- })
- .catch(() => next());
- },
- () => {
- resolve({ sockets });
- }
- );
- }
- return resolve();
- });
- }
- /**
- * Returns any sockets from a specific user without using redis/cache
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.userId - the id of the user in question
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKETS_FROM_USER_WITHOUT_CACHE(payload) {
- return new Promise(resolve => {
- const ns = IOModule._io.of("/");
- const sockets = [];
- if (ns) {
- return async.each(
- Object.keys(ns.connected),
- (id, next) => {
- const { session } = ns.connected[id];
- if (session.userId === payload.userId) sockets.push(ns.connected[id]);
- next();
- },
- () => {
- resolve({ sockets });
- }
- );
- }
- return resolve();
- });
- }
- /**
- * Allows a socket to leave any rooms they are connected to
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.socketId - the id of the socket which should leave all their rooms
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKET_LEAVE_ROOMS(payload) {
- const socket = await IOModule.runJob(
- "SOCKET_FROM_SESSION",
- {
- socketId: payload.socketId
- },
- this
- );
- return new Promise(resolve => {
- const { rooms } = socket;
- Object.keys(rooms).forEach(roomKey => {
- const room = rooms[roomKey];
- socket.leave(room);
- });
- return resolve();
- });
- }
- /**
- * Allows a socket to join a specified room
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.socketId - the id of the socket which should join the room
- * @param {object} payload.room - the object representing the room the socket should join
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async SOCKET_JOIN_ROOM(payload) {
- const socket = await IOModule.runJob(
- "SOCKET_FROM_SESSION",
- {
- socketId: payload.socketId
- },
- this
- );
- return new Promise(resolve => {
- const { rooms } = socket;
- Object.keys(rooms).forEach(roomKey => {
- const room = rooms[roomKey];
- socket.leave(room);
- });
- socket.join(payload.room);
- return resolve();
- });
- }
- // UNKNOWN
- // eslint-disable-next-line require-jsdoc
- async SOCKET_JOIN_SONG_ROOM(payload) {
- // socketId, room
- const socket = await IOModule.runJob(
- "SOCKET_FROM_SESSION",
- {
- socketId: payload.socketId
- },
- this
- );
- return new Promise(resolve => {
- const { rooms } = socket;
- Object.keys(rooms).forEach(roomKey => {
- const room = rooms[roomKey];
- if (room.indexOf("song.") !== -1) socket.leave(room);
- });
- socket.join(payload.room);
- return resolve();
- });
- }
- // UNKNOWN
- // eslint-disable-next-line require-jsdoc
- SOCKETS_JOIN_SONG_ROOM(payload) {
- // sockets, room
- return new Promise(resolve => {
- Object.keys(payload.sockets).forEach(socketKey => {
- const socket = payload.sockets[socketKey];
- const { rooms } = socket;
- Object.keys(rooms).forEach(roomKey => {
- const room = rooms[roomKey];
- if (room.indexOf("song.") !== -1) socket.leave(room);
- });
- socket.join(payload.room);
- });
- return resolve();
- });
- }
- // UNKNOWN
- // eslint-disable-next-line require-jsdoc
- SOCKETS_LEAVE_SONG_ROOMS(payload) {
- // sockets
- return new Promise(resolve => {
- Object.keys(payload.sockets).forEach(socketKey => {
- const socket = payload.sockets[socketKey];
- const { rooms } = socket;
- Object.keys(rooms).forEach(roomKey => {
- const room = rooms[roomKey];
- if (room.indexOf("song.") !== -1) socket.leave(room);
- });
- });
- resolve();
- });
- }
- /**
- * Emits arguments to any sockets that are in a specified a room
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.room - the name of the room to emit arguments
- * @param {object} payload.args - any arguments to be emitted to the sockets in the specific room
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async EMIT_TO_ROOM(payload) {
- return new Promise(resolve => {
- const { sockets } = IOModule._io.sockets;
- Object.keys(sockets).forEach(socketKey => {
- const socket = sockets[socketKey];
- if (socket.rooms[payload.room]) {
- socket.emit(...payload.args);
- }
- });
- return resolve();
- });
- }
- /**
- * Gets any sockets connected to a room
- *
- * @param {object} payload - object that contains the payload
- * @param {string} payload.room - the name of the room
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async GET_ROOM_SOCKETS(payload) {
- return new Promise(resolve => {
- const { sockets } = IOModule._io.sockets;
- const roomSockets = [];
- Object.keys(sockets).forEach(socketKey => {
- const socket = sockets[socketKey];
- if (socket.rooms[payload.room]) roomSockets.push(socket);
- });
- return resolve(roomSockets);
- });
- }
- /**
- * Handles io.use
- *
- * @param {object} payload - object that contains the payload
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async HANDLE_IO_USE(payload) {
- return new Promise(resolve => {
- const { socket, cb } = payload;
- let SID;
- socket.ip = socket.request.headers["x-forwarded-for"] || "0.0.0.0";
- return async.waterfall(
- [
- next => {
- UtilsModule.runJob(
- "PARSE_COOKIES",
- {
- cookieString: socket.request.headers.cookie
- },
- this
- ).then(res => {
- SID = res[IOModule.SIDname];
- next(null);
- });
- },
- next => {
- if (!SID) return next("No SID.");
- return next();
- },
- next => {
- CacheModule.runJob("HGET", { table: "sessions", key: SID }, this)
- .then(session => {
- next(null, session);
- })
- .catch(next);
- },
- (session, next) => {
- if (!session) return next("No session found.");
- session.refreshDate = Date.now();
- socket.session = session;
- return CacheModule.runJob(
- "HSET",
- {
- table: "sessions",
- key: SID,
- value: session
- },
- this
- ).then(session => {
- next(null, session);
- });
- },
- (res, next) => {
- // check if a session's user / IP is banned
- PunishmentsModule.runJob("GET_PUNISHMENTS", {}, this)
- .then(punishments => {
- const isLoggedIn = !!(socket.session && socket.session.refreshDate);
- const userId = isLoggedIn ? socket.session.userId : null;
- const banishment = {
- banned: false,
- ban: 0
- };
- punishments.forEach(punishment => {
- if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
- if (punishment.type === "banUserId" && isLoggedIn && punishment.value === userId)
- banishment.banned = true;
- if (punishment.type === "banUserIp" && punishment.value === socket.ip)
- banishment.banned = true;
- });
- socket.banishment = banishment;
- next();
- })
- .catch(() => {
- next();
- });
- }
- ],
- () => {
- if (!socket.session) socket.session = { socketId: socket.id };
- else socket.session.socketId = socket.id;
- cb();
- resolve();
- }
- );
- });
- }
- /**
- * Handles io.connection
- *
- * @param {object} payload - object that contains the payload
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async HANDLE_IO_CONNECTION(payload) {
- return new Promise(resolve => {
- const { socket } = payload;
- let sessionInfo = "";
- if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
- // if session is banned
- if (socket.banishment && socket.banishment.banned) {
- IOModule.log(
- "INFO",
- "IO_BANNED_CONNECTION",
- `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`
- );
- socket.emit("keep.event:banned", socket.banishment.ban);
- return socket.disconnect(true);
- }
- IOModule.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
- // catch when the socket has been disconnected
- socket.on("disconnect", () => {
- if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
- IOModule.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
- });
- socket.use((data, next) => {
- if (data.length === 0) return next(new Error("Not enough arguments specified."));
- if (typeof data[0] !== "string") return next(new Error("First argument must be a string."));
- const namespaceAction = data[0];
- if (
- !namespaceAction ||
- namespaceAction.indexOf(".") === -1 ||
- namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
- )
- return next(new Error("Invalid first argument"));
- const namespace = data[0].split(".")[0];
- const action = data[0].split(".")[1];
- if (!namespace) return next(new Error("Invalid namespace."));
- if (!action) return next(new Error("Invalid action."));
- if (!IOModule.actions[namespace]) return next(new Error("Namespace not found."));
- if (!IOModule.actions[namespace][action]) return next(new Error("Action not found."));
- return next();
- });
- // catch errors on the socket (internal to socket.io)
- socket.on("error", console.error);
- if (socket.session.sessionId) {
- CacheModule.runJob("HGET", {
- table: "sessions",
- key: socket.session.sessionId
- })
- .then(session => {
- if (session && session.userId) {
- IOModule.userModel.findOne({ _id: session.userId }, (err, user) => {
- if (err || !user) return socket.emit("ready", false);
- let role = "";
- let username = "";
- let userId = "";
- if (user) {
- role = user.role;
- username = user.username;
- userId = session.userId;
- }
- return socket.emit("ready", true, role, username, userId);
- });
- } else socket.emit("ready", false);
- })
- .catch(() => {
- socket.emit("ready", false);
- });
- } else socket.emit("ready", false);
- // have the socket listen for each action
- Object.keys(IOModule.actions).forEach(namespace => {
- Object.keys(IOModule.actions[namespace]).forEach(action => {
- // the full name of the action
- const name = `${namespace}.${action}`;
- // listen for this action to be called
- socket.on(name, async (...args) => {
- IOModule.runJob("RUN_ACTION", { socket, namespace, action, args });
- /* let cb = args[args.length - 1];
- if (typeof cb !== "function")
- cb = () => {
- IOModule.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
- };
- else args.pop();
- if (this.getStatus() !== "READY") {
- IOModule.log(
- "INFO",
- "IO_REJECTED_ACTION",
- `A user tried to execute an action, but the IO module is currently not ready. Action: ${namespace}.${action}.`
- );
- return;
- }
- IOModule.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
- let failedGettingSession = false;
- // load the session from the cache
- if (socket.session.sessionId)
- await CacheModule.runJob("HGET", {
- table: "sessions",
- key: socket.session.sessionId
- })
- .then(session => {
- // make sure the sockets sessionId isn't set if there is no session
- if (socket.session.sessionId && session === null) delete socket.session.sessionId;
- })
- .catch(() => {
- failedGettingSession = true;
- if (typeof cb === "function")
- cb({
- status: "error",
- message: "An error occurred while obtaining your session"
- });
- });
- if (!failedGettingSession)
- try {
- // call the action, passing it the session, and the arguments socket.io passed us
- this.runJob("RUN_ACTION", { namespace, action, session: socket.session, args })
- .then(response => {
- if (typeof cb === "function") cb(response);
- })
- .catch(err => {
- if (typeof cb === "function") cb(err);
- });
- // actions[namespace][action].apply(
- // null,
- // [socket.session].concat(args).concat([
- // result => {
- // IOModule.log(
- // "INFO",
- // "IO_ACTION",
- // `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
- // );
- // // respond to the socket with our message
- // if (typeof cb === "function") cb(result);
- // }
- // ])
- // );
- } catch (err) {
- if (typeof cb === "function")
- cb({
- status: "error",
- message: "An error occurred while executing the specified action."
- });
- IOModule.log(
- "ERROR",
- "IO_ACTION_ERROR",
- `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
- );
- } */
- });
- });
- });
- return resolve();
- });
- }
- /**
- * Runs an action
- *
- * @param {object} payload - object that contains the payload
- * @returns {Promise} - returns promise (reject, resolve)
- */
- async RUN_ACTION(payload) {
- return new Promise((resolve, reject) => {
- const { socket, namespace, action, args } = payload;
- // the full name of the action
- const name = `${namespace}.${action}`;
- let cb = args[args.length - 1];
- if (typeof cb !== "function")
- cb = () => {
- IOModule.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
- };
- else args.pop();
- IOModule.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
- // load the session from the cache
- new Promise(resolve => {
- if (socket.session.sessionId)
- CacheModule.runJob("HGET", {
- table: "sessions",
- key: socket.session.sessionId
- })
- .then(session => {
- // make sure the sockets sessionId isn't set if there is no session
- if (socket.session.sessionId && session === null) delete socket.session.sessionId;
- resolve();
- })
- .catch(() => {
- if (typeof cb === "function")
- cb({
- status: "error",
- message: "An error occurred while obtaining your session"
- });
- reject(new Error("An error occurred while obtaining the session"));
- });
- })
- .then(() => {
- try {
- // call the action, passing it the session, and the arguments socket.io passed us
- IOModule.actions[namespace][action].apply(
- this,
- [socket.session].concat(args).concat([
- result => {
- IOModule.log(
- "INFO",
- "RUN_ACTION",
- `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
- );
- // respond to the socket with our message
- if (typeof cb === "function") cb(result);
- resolve();
- }
- ])
- );
- } catch (err) {
- if (typeof cb === "function")
- cb({
- status: "error",
- message: "An error occurred while executing the specified action."
- });
- reject(err);
- IOModule.log(
- "ERROR",
- "IO_ACTION_ERROR",
- `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
- );
- }
- })
- .catch(reject);
- });
- }
- }
- export default new _IOModule();
|