ws.js 20 KB

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