ws.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727
  1. /**
  2. * @file
  3. */
  4. import config from "config";
  5. import async from "async";
  6. import WebSocket from "ws";
  7. import { EventEmitter } from "events";
  8. import CoreClass from "../core";
  9. let WSModule;
  10. let AppModule;
  11. let CacheModule;
  12. let UtilsModule;
  13. let DBModule;
  14. let PunishmentsModule;
  15. class _WSModule extends CoreClass {
  16. // eslint-disable-next-line require-jsdoc
  17. constructor() {
  18. super("ws");
  19. WSModule = this;
  20. }
  21. /**
  22. * Initialises the ws module
  23. *
  24. * @returns {Promise} - returns promise (reject, resolve)
  25. */
  26. async initialize() {
  27. this.setStage(1);
  28. AppModule = this.moduleManager.modules.app;
  29. CacheModule = this.moduleManager.modules.cache;
  30. UtilsModule = this.moduleManager.modules.utils;
  31. DBModule = this.moduleManager.modules.db;
  32. PunishmentsModule = this.moduleManager.modules.punishments;
  33. this.actions = (await import("./actions")).default;
  34. this.userModel = await DBModule.runJob("GET_MODEL", { modelName: "user" });
  35. this.setStage(2);
  36. this.SIDname = config.get("cookie.SIDname");
  37. // 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)
  38. const server = await AppModule.runJob("SERVER");
  39. // this._io.origins(config.get("cors.origin"));
  40. this._io = new WebSocket.Server({ server, path: "/ws" });
  41. this.rooms = {};
  42. return new Promise(resolve => {
  43. this.setStage(3);
  44. this._io.on("connection", async (socket, req) => {
  45. socket.dispatch = (...args) => socket.send(JSON.stringify(args));
  46. socket.actions = new EventEmitter();
  47. socket.actions.setMaxListeners(0);
  48. socket.listen = (target, cb) => socket.actions.addListener(target, args => cb(args));
  49. WSModule.runJob("HANDLE_WS_USE", { socket, req }).then(socket =>
  50. WSModule.runJob("HANDLE_WS_CONNECTION", { socket })
  51. );
  52. socket.isAlive = true;
  53. socket.on("pong", function heartbeat() {
  54. this.isAlive = true;
  55. });
  56. });
  57. const keepAliveInterval = setInterval(() => {
  58. this._io.clients.forEach(socket => {
  59. if (socket.isAlive === false) return socket.terminate();
  60. socket.isAlive = false;
  61. return socket.ping(() => {});
  62. });
  63. }, 45000);
  64. this._io.on("close", () => clearInterval(keepAliveInterval));
  65. this.setStage(4);
  66. return resolve();
  67. });
  68. }
  69. /**
  70. * Returns the websockets variable
  71. *
  72. * @returns {Promise} - returns a promise (resolve, reject)
  73. */
  74. WS() {
  75. return new Promise(resolve => resolve(WSModule._io));
  76. }
  77. /**
  78. * Obtains socket object for a specified socket id
  79. *
  80. * @param {object} payload - object containing the payload
  81. * @param {string} payload.socketId - the id of the socket
  82. * @returns {Promise} - returns promise (reject, resolve)
  83. */
  84. async SOCKET_FROM_SOCKET_ID(payload) {
  85. return new Promise(resolve => {
  86. const { clients } = WSModule._io;
  87. if (clients)
  88. // eslint-disable-next-line consistent-return
  89. clients.forEach(socket => {
  90. if (socket.session.socketId === payload.socketId) return resolve(socket);
  91. });
  92. // socket doesn't exist
  93. return resolve();
  94. });
  95. }
  96. /**
  97. * Gets all sockets for a specified session id
  98. *
  99. * @param {object} payload - object containing the payload
  100. * @param {string} payload.sessionId - user session id
  101. * @returns {Promise} - returns promise (reject, resolve)
  102. */
  103. async SOCKETS_FROM_SESSION_ID(payload) {
  104. return new Promise(resolve => {
  105. const { clients } = WSModule._io;
  106. const sockets = [];
  107. if (clients) {
  108. return async.each(
  109. Object.keys(clients),
  110. (id, next) => {
  111. const { session } = clients[id];
  112. if (session.sessionId === payload.sessionId) sockets.push(session.sessionId);
  113. next();
  114. },
  115. () => resolve(sockets)
  116. );
  117. }
  118. return resolve();
  119. });
  120. }
  121. /**
  122. * Returns any sockets for a specific user
  123. *
  124. * @param {object} payload - object that contains the payload
  125. * @param {string} payload.userId - the user id
  126. * @returns {Promise} - returns promise (reject, resolve)
  127. */
  128. async SOCKETS_FROM_USER(payload) {
  129. return new Promise((resolve, reject) => {
  130. const sockets = [];
  131. return async.eachLimit(
  132. WSModule._io.clients,
  133. 1,
  134. (socket, next) => {
  135. const { sessionId } = socket.session;
  136. if (sessionId) {
  137. return CacheModule.runJob("HGET", { table: "sessions", key: sessionId }, this)
  138. .then(session => {
  139. if (session && session.userId === payload.userId) sockets.push(socket);
  140. next();
  141. })
  142. .catch(err => next(err));
  143. }
  144. return next();
  145. },
  146. err => {
  147. if (err) return reject(err);
  148. return resolve(sockets);
  149. }
  150. );
  151. });
  152. }
  153. /**
  154. * Returns any sockets from a specific ip address
  155. *
  156. * @param {object} payload - object that contains the payload
  157. * @param {string} payload.ip - the ip address in question
  158. * @returns {Promise} - returns promise (reject, resolve)
  159. */
  160. async SOCKETS_FROM_IP(payload) {
  161. return new Promise(resolve => {
  162. const { clients } = WSModule._io;
  163. const sockets = [];
  164. return async.each(
  165. Object.keys(clients),
  166. (id, next) => {
  167. const { session } = clients[id];
  168. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }, this)
  169. .then(session => {
  170. if (session && clients[id].ip === payload.ip) sockets.push(clients[id]);
  171. next();
  172. })
  173. .catch(() => next());
  174. },
  175. () => resolve(sockets)
  176. );
  177. });
  178. }
  179. /**
  180. * Returns any sockets from a specific user without using redis/cache
  181. *
  182. * @param {object} payload - object that contains the payload
  183. * @param {string} payload.userId - the id of the user in question
  184. * @returns {Promise} - returns promise (reject, resolve)
  185. */
  186. async SOCKETS_FROM_USER_WITHOUT_CACHE(payload) {
  187. return new Promise(resolve => {
  188. const { clients } = WSModule._io;
  189. const sockets = [];
  190. if (clients) {
  191. return async.each(
  192. Object.keys(clients),
  193. (id, next) => {
  194. const { session } = clients[id];
  195. if (session.userId === payload.userId) sockets.push(clients[id]);
  196. next();
  197. },
  198. () => resolve(sockets)
  199. );
  200. }
  201. return resolve();
  202. });
  203. }
  204. /**
  205. * Allows a socket to leave any rooms they are connected to
  206. *
  207. * @param {object} payload - object that contains the payload
  208. * @param {string} payload.socketId - the id of the socket which should leave all their rooms
  209. * @returns {Promise} - returns promise (reject, resolve)
  210. */
  211. async SOCKET_LEAVE_ROOMS(payload) {
  212. return new Promise(resolve => {
  213. // filter out rooms that the user is in
  214. Object.keys(WSModule.rooms).forEach(room => {
  215. WSModule.rooms[room] = WSModule.rooms[room].filter(participant => participant !== payload.socketId);
  216. });
  217. return resolve();
  218. });
  219. }
  220. /**
  221. * Allows a socket to join a specified room (this will remove them from any rooms they are currently in)
  222. *
  223. * @param {object} payload - object that contains the payload
  224. * @param {string} payload.socketId - the id of the socket which should join the room
  225. * @param {string} payload.room - the name of the room
  226. * @returns {Promise} - returns promise (reject, resolve)
  227. */
  228. async SOCKET_JOIN_ROOM(payload) {
  229. const { room, socketId } = payload;
  230. // leave all other rooms
  231. await WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId }, this);
  232. return new Promise(resolve => {
  233. // create room if it doesn't exist, and add socketId to array
  234. if (WSModule.rooms[room]) WSModule.rooms[room].push(socketId);
  235. else WSModule.rooms[room] = [socketId];
  236. return resolve();
  237. });
  238. }
  239. /**
  240. * Emits arguments to any sockets that are in a specified a room
  241. *
  242. * @param {object} payload - object that contains the payload
  243. * @param {string} payload.room - the name of the room to emit arguments
  244. * @param {object} payload.args - any arguments to be emitted to the sockets in the specific room
  245. * @returns {Promise} - returns promise (reject, resolve)
  246. */
  247. async EMIT_TO_ROOM(payload) {
  248. return new Promise(resolve => {
  249. // if the room exists
  250. if (WSModule.rooms[payload.room] && WSModule.rooms[payload.room].length > 0)
  251. return WSModule.rooms[payload.room].forEach(async socketId => {
  252. // get every socketId (and thus every socket) in the room, and dispatch to each
  253. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  254. socket.dispatch(...payload.args);
  255. return resolve();
  256. });
  257. return resolve();
  258. });
  259. }
  260. /**
  261. * Allows a socket to join a 'song' room
  262. *
  263. * @param {object} payload - object that contains the payload
  264. * @param {string} payload.socketId - the id of the socket which should join the room
  265. * @param {string} payload.room - the name of the room
  266. * @returns {Promise} - returns promise (reject, resolve)
  267. */
  268. async SOCKET_JOIN_SONG_ROOM(payload) {
  269. const { room, socketId } = payload;
  270. // leave any other song rooms the user is in
  271. await WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets: [socketId] }, this);
  272. return new Promise(resolve => {
  273. // join the room
  274. if (WSModule.rooms[room]) WSModule.rooms[room].push(socketId);
  275. else WSModule.rooms[room] = [socketId];
  276. return resolve();
  277. });
  278. }
  279. /**
  280. * Allows multiple sockets to join a 'song' room
  281. *
  282. * @param {object} payload - object that contains the payload
  283. * @param {Array} payload.sockets - array of socketIds
  284. * @param {object} payload.room - the name of the room
  285. * @returns {Promise} - returns promise (reject, resolve)
  286. */
  287. SOCKETS_JOIN_SONG_ROOM(payload) {
  288. return new Promise(resolve => {
  289. Promise.allSettled(
  290. payload.sockets.map(async socketId => {
  291. await WSModule.runJob("SOCKET_JOIN_SONG_ROOM", { socketId, room: payload.room }, this);
  292. })
  293. ).then(() => resolve());
  294. });
  295. }
  296. /**
  297. * Allows multiple sockets to leave any 'song' rooms they are in
  298. *
  299. * @param {object} payload - object that contains the payload
  300. * @param {Array} payload.sockets - array of socketIds
  301. * @returns {Promise} - returns promise (reject, resolve)
  302. */
  303. SOCKETS_LEAVE_SONG_ROOMS(payload) {
  304. return new Promise(resolve =>
  305. Promise.allSettled(
  306. payload.sockets.map(async socketId => {
  307. const rooms = await WSModule.runJob("GET_ROOMS_FOR_SOCKET", { socketId }, this);
  308. rooms.forEach(room => {
  309. if (room.indexOf("song.") !== -1)
  310. WSModule.rooms[room] = WSModule.rooms[room].filter(participant => participant !== socketId);
  311. });
  312. })
  313. ).then(() => resolve())
  314. );
  315. }
  316. /**
  317. * Gets any sockets connected to a room
  318. *
  319. * @param {object} payload - object that contains the payload
  320. * @param {string} payload.room - the name of the room
  321. * @returns {Promise} - returns promise (reject, resolve)
  322. */
  323. async GET_SOCKETS_FOR_ROOM(payload) {
  324. return new Promise(resolve => {
  325. if (WSModule.rooms[payload.room]) return resolve(WSModule.rooms[payload.room]);
  326. return resolve([]);
  327. });
  328. }
  329. /**
  330. * Gets any rooms a socket is connected to
  331. *
  332. * @param {object} payload - object that contains the payload
  333. * @param {string} payload.socketId - the id of the socket to check the rooms for
  334. * @returns {Promise} - returns promise (reject, resolve)
  335. */
  336. async GET_ROOMS_FOR_SOCKET(payload) {
  337. return new Promise(resolve => {
  338. const rooms = [];
  339. Object.keys(WSModule.rooms).forEach(room => {
  340. if (WSModule.rooms[room].includes(payload.socketId)) rooms.push(room);
  341. });
  342. return resolve(rooms);
  343. });
  344. }
  345. /**
  346. * Handles use of websockets
  347. *
  348. * @param {object} payload - object that contains the payload
  349. * @returns {Promise} - returns promise (reject, resolve)
  350. */
  351. async HANDLE_WS_USE(payload) {
  352. return new Promise(resolve => {
  353. const { socket, req } = payload;
  354. let SID = "";
  355. socket.ip = req.headers["x-forwarded-for"] || "0..0.0";
  356. return async.waterfall(
  357. [
  358. next => {
  359. if (!req.headers.cookie) return next("No cookie exists yet.");
  360. return UtilsModule.runJob("PARSE_COOKIES", { cookieString: req.headers.cookie }, this).then(
  361. res => {
  362. SID = res[WSModule.SIDname];
  363. next(null);
  364. }
  365. );
  366. },
  367. next => {
  368. if (!SID) return next("No SID.");
  369. return next();
  370. },
  371. // see if session exists for cookie
  372. next => {
  373. CacheModule.runJob("HGET", { table: "sessions", key: SID }, this)
  374. .then(session => next(null, session))
  375. .catch(next);
  376. },
  377. (session, next) => {
  378. if (!session) return next("No session found.");
  379. session.refreshDate = Date.now();
  380. socket.session = session;
  381. return CacheModule.runJob(
  382. "HSET",
  383. { table: "sessions", key: SID, value: session },
  384. this
  385. ).then(session => next(null, session));
  386. },
  387. (res, next) => {
  388. // check if a session's user / IP is banned
  389. PunishmentsModule.runJob("GET_PUNISHMENTS", {}, this)
  390. .then(punishments => {
  391. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  392. const userId = isLoggedIn ? socket.session.userId : null;
  393. const banishment = {
  394. banned: false,
  395. ban: 0
  396. };
  397. punishments.forEach(punishment => {
  398. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  399. if (punishment.type === "banUserId" && isLoggedIn && punishment.value === userId)
  400. banishment.banned = true;
  401. if (punishment.type === "banUserIp" && punishment.value === socket.ip)
  402. banishment.banned = true;
  403. });
  404. socket.banishment = banishment;
  405. next();
  406. })
  407. .catch(() => next());
  408. }
  409. ],
  410. () => {
  411. if (!socket.session) socket.session = { socketId: req.headers["sec-websocket-key"] };
  412. else socket.session.socketId = req.headers["sec-websocket-key"];
  413. resolve(socket);
  414. }
  415. );
  416. });
  417. }
  418. /**
  419. * Handles a websocket connection
  420. *
  421. * @param {object} payload - object that contains the payload
  422. * @param {object} payload.socket - socket itself
  423. * @returns {Promise} - returns promise (reject, resolve)
  424. */
  425. async HANDLE_WS_CONNECTION(payload) {
  426. return new Promise(resolve => {
  427. const { socket } = payload;
  428. let sessionInfo = "";
  429. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  430. // if session is banned
  431. if (socket.banishment && socket.banishment.banned) {
  432. WSModule.log(
  433. "INFO",
  434. "IO_BANNED_CONNECTION",
  435. `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`
  436. );
  437. socket.dispatch("keep.event:banned", socket.banishment.ban);
  438. return socket.close(); // close socket connection
  439. }
  440. WSModule.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
  441. // catch when the socket has been disconnected
  442. socket.on("close", async () => {
  443. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  444. WSModule.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  445. // leave all rooms when a socket connection is closed (to prevent rooms object building up)
  446. await WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: socket.session.socketId });
  447. });
  448. // catch errors on the socket
  449. socket.onerror = error => {
  450. console.error("SOCKET ERROR: ", error);
  451. };
  452. if (socket.session.sessionId) {
  453. CacheModule.runJob("HGET", {
  454. table: "sessions",
  455. key: socket.session.sessionId
  456. })
  457. .then(session => {
  458. if (session && session.userId) {
  459. WSModule.userModel.findOne({ _id: session.userId }, (err, user) => {
  460. if (err || !user) return socket.dispatch("ready", false);
  461. let role = "";
  462. let username = "";
  463. let userId = "";
  464. if (user) {
  465. role = user.role;
  466. username = user.username;
  467. userId = session.userId;
  468. }
  469. return socket.dispatch("ready", true, role, username, userId);
  470. });
  471. } else socket.dispatch("ready", false);
  472. })
  473. .catch(() => socket.dispatch("ready", false));
  474. } else socket.dispatch("ready", false);
  475. socket.onmessage = message => {
  476. const data = JSON.parse(message.data);
  477. if (data.length === 0) return socket.dispatch("ERROR", "Not enough arguments specified.");
  478. if (typeof data[0] !== "string") return socket.dispatch("ERROR", "First argument must be a string.");
  479. const namespaceAction = data[0];
  480. if (
  481. !namespaceAction ||
  482. namespaceAction.indexOf(".") === -1 ||
  483. namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
  484. )
  485. return socket.dispatch("ERROR", "Invalid first argument");
  486. const namespace = data[0].split(".")[0];
  487. const action = data[0].split(".")[1];
  488. if (!namespace) return socket.dispatch("ERROR", "Invalid namespace.");
  489. if (!action) return socket.dispatch("ERROR", "Invalid action.");
  490. if (!WSModule.actions[namespace]) return socket.dispatch("ERROR", "Namespace not found.");
  491. if (!WSModule.actions[namespace][action]) return socket.dispatch("ERROR", "Action not found.");
  492. if (data[data.length - 1].CB_REF) {
  493. const { CB_REF } = data[data.length - 1];
  494. data.pop();
  495. return socket.actions.emit(data.shift(0), [...data, res => socket.dispatch("CB_REF", CB_REF, res)]);
  496. }
  497. return socket.actions.emit(data.shift(0), data);
  498. };
  499. // have the socket listen for each action
  500. Object.keys(WSModule.actions).forEach(namespace => {
  501. Object.keys(WSModule.actions[namespace]).forEach(action => {
  502. // the full name of the action
  503. const name = `${namespace}.${action}`;
  504. // listen for this action to be called
  505. socket.listen(name, async args =>
  506. WSModule.runJob("RUN_ACTION", { socket, namespace, action, args })
  507. );
  508. });
  509. });
  510. return resolve();
  511. });
  512. }
  513. /**
  514. * Runs an action
  515. *
  516. * @param {object} payload - object that contains the payload
  517. * @returns {Promise} - returns promise (reject, resolve)
  518. */
  519. async RUN_ACTION(payload) {
  520. return new Promise((resolve, reject) => {
  521. const { socket, namespace, action, args } = payload;
  522. // the full name of the action
  523. const name = `${namespace}.${action}`;
  524. let cb = args[args.length - 1];
  525. if (typeof cb !== "function")
  526. cb = () => {
  527. WSModule.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
  528. };
  529. else args.pop();
  530. WSModule.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
  531. // load the session from the cache
  532. new Promise(resolve => {
  533. if (socket.session.sessionId)
  534. CacheModule.runJob("HGET", {
  535. table: "sessions",
  536. key: socket.session.sessionId
  537. })
  538. .then(session => {
  539. // make sure the sockets sessionId isn't set if there is no session
  540. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  541. resolve();
  542. })
  543. .catch(() => {
  544. if (typeof cb === "function")
  545. cb({
  546. status: "error",
  547. message: "An error occurred while obtaining your session"
  548. });
  549. reject(new Error("An error occurred while obtaining the session"));
  550. });
  551. else resolve();
  552. })
  553. .then(() => {
  554. // call the job that calls the action, passing it the session, and the arguments the websocket passed us
  555. WSModule.runJob("RUN_ACTION2", { session: socket.session, namespace, action, args }, this)
  556. .then(response => {
  557. cb(response);
  558. resolve();
  559. })
  560. .catch(err => {
  561. if (typeof cb === "function")
  562. cb({
  563. status: "error",
  564. message: "An error occurred while executing the specified action."
  565. });
  566. reject(err);
  567. WSModule.log(
  568. "ERROR",
  569. "IO_ACTION_ERROR",
  570. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  571. );
  572. });
  573. })
  574. .catch(reject);
  575. });
  576. }
  577. /**
  578. * Runs an action
  579. *
  580. * @param {object} payload - object that contains the payload
  581. * @returns {Promise} - returns promise (reject, resolve)
  582. */
  583. async RUN_ACTION2(payload) {
  584. return new Promise((resolve, reject) => {
  585. const { session, namespace, action, args } = payload;
  586. try {
  587. // call the the action, passing it the session, and the arguments the websocket passed us
  588. WSModule.actions[namespace][action].apply(
  589. this,
  590. [session].concat(args).concat([
  591. result => {
  592. WSModule.log(
  593. "INFO",
  594. "RUN_ACTION2",
  595. `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
  596. );
  597. resolve(result);
  598. }
  599. ])
  600. );
  601. } catch (err) {
  602. reject(err);
  603. WSModule.log(
  604. "ERROR",
  605. "IO_ACTION_ERROR",
  606. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  607. );
  608. }
  609. });
  610. }
  611. }
  612. export default new _WSModule();