io.js 17 KB

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