ws.js 20 KB

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