ws.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  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])
  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. console.log("room doesn't exist");
  246. return resolve();
  247. });
  248. }
  249. /**
  250. * Allows a socket to join a 'song' room
  251. *
  252. * @param {object} payload - object that contains the payload
  253. * @param {string} payload.socketId - the id of the socket which should join the room
  254. * @param {string} payload.room - the name of the room
  255. * @returns {Promise} - returns promise (reject, resolve)
  256. */
  257. async SOCKET_JOIN_SONG_ROOM(payload) {
  258. const { room, socketId } = payload;
  259. // leave any other song rooms the user is in
  260. await WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets: [socketId] }, this);
  261. return new Promise(resolve => {
  262. // join the room
  263. if (WSModule.rooms[room]) WSModule.rooms[room].push(socketId);
  264. else WSModule.rooms[room] = [socketId];
  265. return resolve();
  266. });
  267. }
  268. /**
  269. * Allows multiple sockets to join a 'song' room
  270. *
  271. * @param {object} payload - object that contains the payload
  272. * @param {Array} payload.sockets - array of socketIds
  273. * @param {object} payload.room - the name of the room
  274. * @returns {Promise} - returns promise (reject, resolve)
  275. */
  276. SOCKETS_JOIN_SONG_ROOM(payload) {
  277. return new Promise(resolve => {
  278. Promise.allSettled(
  279. payload.sockets.map(async socketId => {
  280. await WSModule.runJob("SOCKET_JOIN_SONG_ROOM", { socketId }, this);
  281. })
  282. ).then(() => resolve());
  283. });
  284. }
  285. /**
  286. * Allows multiple sockets to leave any 'song' rooms they are in
  287. *
  288. * @param {object} payload - object that contains the payload
  289. * @param {Array} payload.sockets - array of socketIds
  290. * @returns {Promise} - returns promise (reject, resolve)
  291. */
  292. SOCKETS_LEAVE_SONG_ROOMS(payload) {
  293. return new Promise(resolve =>
  294. Promise.allSettled(
  295. payload.sockets.map(async socketId => {
  296. const rooms = await WSModule.runJob("GET_ROOMS_FOR_SOCKET", { socketId }, this);
  297. rooms.forEach(room => {
  298. if (room.indexOf("song.") !== -1)
  299. WSModule.rooms[room] = WSModule.rooms[room].filter(
  300. participant => participant !== payload.socketId
  301. );
  302. });
  303. })
  304. ).then(() => resolve())
  305. );
  306. }
  307. /**
  308. * Gets any sockets connected to a room
  309. *
  310. * @param {object} payload - object that contains the payload
  311. * @param {string} payload.room - the name of the room
  312. * @returns {Promise} - returns promise (reject, resolve)
  313. */
  314. async GET_SOCKETS_FOR_ROOM(payload) {
  315. return new Promise(resolve => {
  316. if (WSModule.rooms[payload.room]) return resolve(WSModule.rooms[payload.room]);
  317. return resolve([]);
  318. });
  319. }
  320. /**
  321. * Gets any rooms a socket is connected to
  322. *
  323. * @param {object} payload - object that contains the payload
  324. * @param {string} payload.socketId - the id of the socket to check the rooms for
  325. * @returns {Promise} - returns promise (reject, resolve)
  326. */
  327. async GET_ROOMS_FOR_SOCKET(payload) {
  328. return new Promise(resolve => {
  329. const rooms = [];
  330. Object.keys(WSModule.rooms).forEach(room => {
  331. if (WSModule.rooms[room].includes(payload.socketId)) rooms.push(room);
  332. });
  333. return resolve(rooms);
  334. });
  335. }
  336. /**
  337. * Handles use of websockets
  338. *
  339. * @param {object} payload - object that contains the payload
  340. * @returns {Promise} - returns promise (reject, resolve)
  341. */
  342. async HANDLE_WS_USE(payload) {
  343. return new Promise(resolve => {
  344. const { socket, req } = payload;
  345. let SID = "";
  346. socket.ip = req.headers["x-forwarded-for"] || "0..0.0";
  347. return async.waterfall(
  348. [
  349. next => {
  350. if (!req.headers.cookie) return next("No cookie exists yet.");
  351. return UtilsModule.runJob("PARSE_COOKIES", { cookieString: req.headers.cookie }, this).then(
  352. res => {
  353. SID = res[WSModule.SIDname];
  354. next(null);
  355. }
  356. );
  357. },
  358. next => {
  359. if (!SID) return next("No SID.");
  360. return next();
  361. },
  362. // see if session exists for cookie
  363. next => {
  364. CacheModule.runJob("HGET", { table: "sessions", key: SID }, this)
  365. .then(session => next(null, session))
  366. .catch(next);
  367. },
  368. (session, next) => {
  369. if (!session) return next("No session found.");
  370. session.refreshDate = Date.now();
  371. socket.session = session;
  372. return CacheModule.runJob(
  373. "HSET",
  374. { table: "sessions", key: SID, value: session },
  375. this
  376. ).then(session => next(null, session));
  377. },
  378. (res, next) => {
  379. // check if a session's user / IP is banned
  380. PunishmentsModule.runJob("GET_PUNISHMENTS", {}, this)
  381. .then(punishments => {
  382. const isLoggedIn = !!(socket.session && socket.session.refreshDate);
  383. const userId = isLoggedIn ? socket.session.userId : null;
  384. const banishment = {
  385. banned: false,
  386. ban: 0
  387. };
  388. punishments.forEach(punishment => {
  389. if (punishment.expiresAt > banishment.ban) banishment.ban = punishment;
  390. if (punishment.type === "banUserId" && isLoggedIn && punishment.value === userId)
  391. banishment.banned = true;
  392. if (punishment.type === "banUserIp" && punishment.value === socket.ip)
  393. banishment.banned = true;
  394. });
  395. socket.banishment = banishment;
  396. next();
  397. })
  398. .catch(() => next());
  399. }
  400. ],
  401. () => {
  402. if (!socket.session) socket.session = { socketId: req.headers["sec-websocket-key"] };
  403. else socket.session.socketId = req.headers["sec-websocket-key"];
  404. resolve(socket);
  405. }
  406. );
  407. });
  408. }
  409. /**
  410. * Handles a websocket connection
  411. *
  412. * @param {object} payload - object that contains the payload
  413. * @param {object} payload.socket - socket itself
  414. * @returns {Promise} - returns promise (reject, resolve)
  415. */
  416. async HANDLE_WS_CONNECTION(payload) {
  417. return new Promise(resolve => {
  418. const { socket } = payload;
  419. let sessionInfo = "";
  420. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  421. // if session is banned
  422. if (socket.banishment && socket.banishment.banned) {
  423. WSModule.log(
  424. "INFO",
  425. "IO_BANNED_CONNECTION",
  426. `A user tried to connect, but is currently banned. IP: ${socket.ip}.${sessionInfo}`
  427. );
  428. socket.dispatch("keep.event:banned", socket.banishment.ban);
  429. return socket.close(); // close socket connection
  430. }
  431. WSModule.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
  432. // catch when the socket has been disconnected
  433. socket.on("close", async () => {
  434. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  435. WSModule.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  436. // leave all rooms when a socket connection is closed (to prevent rooms object building up)
  437. await WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: socket.session.socketId });
  438. });
  439. // catch errors on the socket
  440. socket.onerror = error => {
  441. console.error("SOCKET ERROR: ", error);
  442. };
  443. if (socket.session.sessionId) {
  444. CacheModule.runJob("HGET", {
  445. table: "sessions",
  446. key: socket.session.sessionId
  447. })
  448. .then(session => {
  449. if (session && session.userId) {
  450. WSModule.userModel.findOne({ _id: session.userId }, (err, user) => {
  451. if (err || !user) return socket.dispatch("ready", false);
  452. let role = "";
  453. let username = "";
  454. let userId = "";
  455. if (user) {
  456. role = user.role;
  457. username = user.username;
  458. userId = session.userId;
  459. }
  460. return socket.dispatch("ready", true, role, username, userId);
  461. });
  462. } else socket.dispatch("ready", false);
  463. })
  464. .catch(() => socket.dispatch("ready", false));
  465. } else socket.dispatch("ready", false);
  466. socket.onmessage = message => {
  467. const data = JSON.parse(message.data);
  468. if (data.length === 0) return socket.dispatch("ERROR", "Not enough arguments specified.");
  469. if (typeof data[0] !== "string") return socket.dispatch("ERROR", "First argument must be a string.");
  470. const namespaceAction = data[0];
  471. if (
  472. !namespaceAction ||
  473. namespaceAction.indexOf(".") === -1 ||
  474. namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
  475. )
  476. return socket.dispatch("ERROR", "Invalid first argument");
  477. const namespace = data[0].split(".")[0];
  478. const action = data[0].split(".")[1];
  479. if (!namespace) return socket.dispatch("ERROR", "Invalid namespace.");
  480. if (!action) return socket.dispatch("ERROR", "Invalid action.");
  481. if (!WSModule.actions[namespace]) return socket.dispatch("ERROR", "Namespace not found.");
  482. if (!WSModule.actions[namespace][action]) return socket.dispatch("ERROR", "Action not found.");
  483. if (data[data.length - 1].CB_REF) {
  484. const { CB_REF } = data[data.length - 1];
  485. data.pop();
  486. return socket.actions.emit(data.shift(0), [...data, res => socket.dispatch("CB_REF", CB_REF, res)]);
  487. }
  488. return socket.actions.emit(data.shift(0), data);
  489. };
  490. // have the socket listen for each action
  491. Object.keys(WSModule.actions).forEach(namespace => {
  492. Object.keys(WSModule.actions[namespace]).forEach(action => {
  493. // the full name of the action
  494. const name = `${namespace}.${action}`;
  495. // listen for this action to be called
  496. socket.listen(name, async args =>
  497. WSModule.runJob("RUN_ACTION", { socket, namespace, action, args })
  498. );
  499. });
  500. });
  501. return resolve();
  502. });
  503. }
  504. /**
  505. * Runs an action
  506. *
  507. * @param {object} payload - object that contains the payload
  508. * @returns {Promise} - returns promise (reject, resolve)
  509. */
  510. async RUN_ACTION(payload) {
  511. return new Promise((resolve, reject) => {
  512. const { socket, namespace, action, args } = payload;
  513. // the full name of the action
  514. const name = `${namespace}.${action}`;
  515. let cb = args[args.length - 1];
  516. if (typeof cb !== "function")
  517. cb = () => {
  518. WSModule.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
  519. };
  520. else args.pop();
  521. WSModule.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
  522. // load the session from the cache
  523. new Promise(resolve => {
  524. if (socket.session.sessionId)
  525. CacheModule.runJob("HGET", {
  526. table: "sessions",
  527. key: socket.session.sessionId
  528. })
  529. .then(session => {
  530. // make sure the sockets sessionId isn't set if there is no session
  531. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  532. resolve();
  533. })
  534. .catch(() => {
  535. if (typeof cb === "function")
  536. cb({
  537. status: "error",
  538. message: "An error occurred while obtaining your session"
  539. });
  540. reject(new Error("An error occurred while obtaining the session"));
  541. });
  542. else resolve();
  543. })
  544. .then(() => {
  545. // call the job that calls the action, passing it the session, and the arguments the websocket passed us
  546. WSModule.runJob("RUN_ACTION2", { session: socket.session, namespace, action, args }, this)
  547. .then(response => {
  548. cb(response);
  549. resolve();
  550. })
  551. .catch(err => {
  552. if (typeof cb === "function")
  553. cb({
  554. status: "error",
  555. message: "An error occurred while executing the specified action."
  556. });
  557. reject(err);
  558. WSModule.log(
  559. "ERROR",
  560. "IO_ACTION_ERROR",
  561. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  562. );
  563. });
  564. })
  565. .catch(reject);
  566. });
  567. }
  568. /**
  569. * Runs an action
  570. *
  571. * @param {object} payload - object that contains the payload
  572. * @returns {Promise} - returns promise (reject, resolve)
  573. */
  574. async RUN_ACTION2(payload) {
  575. return new Promise((resolve, reject) => {
  576. const { session, namespace, action, args } = payload;
  577. try {
  578. // call the the action, passing it the session, and the arguments the websocket passed us
  579. WSModule.actions[namespace][action].apply(
  580. this,
  581. [session].concat(args).concat([
  582. result => {
  583. WSModule.log(
  584. "INFO",
  585. "RUN_ACTION2",
  586. `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
  587. );
  588. resolve(result);
  589. }
  590. ])
  591. );
  592. } catch (err) {
  593. reject(err);
  594. WSModule.log(
  595. "ERROR",
  596. "IO_ACTION_ERROR",
  597. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  598. );
  599. }
  600. });
  601. }
  602. }
  603. export default new _WSModule();