io.js 20 KB

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