io.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  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. // UNKNOWN
  284. // eslint-disable-next-line require-jsdoc
  285. async SOCKET_FROM_SESSION(payload) {
  286. // socketId
  287. return new Promise((resolve, reject) => {
  288. const ns = IOModule._io.of("/");
  289. if (ns) {
  290. return resolve(ns.connected[payload.socketId]);
  291. }
  292. return reject();
  293. });
  294. }
  295. /**
  296. * Gets all sockets for a specified session id
  297. *
  298. * @param {object} payload - object containing the payload
  299. * @param {string} payload.sessionId - user session id
  300. * @returns {Promise} - returns promise (reject, resolve)
  301. */
  302. async SOCKETS_FROM_SESSION_ID(payload) {
  303. return new Promise(resolve => {
  304. const ns = IOModule._io.of("/");
  305. const sockets = [];
  306. if (ns) {
  307. return async.each(
  308. Object.keys(ns.connected),
  309. (id, next) => {
  310. const { session } = ns.connected[id];
  311. if (session.sessionId === payload.sessionId) sockets.push(session.sessionId);
  312. next();
  313. },
  314. () => {
  315. resolve({ sockets });
  316. }
  317. );
  318. }
  319. return resolve();
  320. });
  321. }
  322. /**
  323. * Returns any sockets for a specific user
  324. *
  325. * @param {object} payload - object that contains the payload
  326. * @param {string} payload.userId - the user id
  327. * @returns {Promise} - returns promise (reject, resolve)
  328. */
  329. async SOCKETS_FROM_USER(payload) {
  330. return new Promise((resolve, reject) => {
  331. const ns = IOModule._io.of("/");
  332. const sockets = [];
  333. if (ns) {
  334. return async.each(
  335. Object.keys(ns.connected),
  336. (id, next) => {
  337. const { session } = ns.connected[id];
  338. CacheModule.runJob(
  339. "HGET",
  340. {
  341. table: "sessions",
  342. key: session.sessionId
  343. },
  344. this
  345. )
  346. .then(session => {
  347. if (session && session.userId === payload.userId) sockets.push(ns.connected[id]);
  348. next();
  349. })
  350. .catch(err => {
  351. next(err);
  352. });
  353. },
  354. err => {
  355. if (err) return reject(err);
  356. return resolve({ sockets });
  357. }
  358. );
  359. }
  360. return resolve();
  361. });
  362. }
  363. /**
  364. * Returns any sockets from a specific ip address
  365. *
  366. * @param {object} payload - object that contains the payload
  367. * @param {string} payload.ip - the ip address in question
  368. * @returns {Promise} - returns promise (reject, resolve)
  369. */
  370. async SOCKETS_FROM_IP(payload) {
  371. return new Promise(resolve => {
  372. const ns = IOModule._io.of("/");
  373. const sockets = [];
  374. if (ns) {
  375. return async.each(
  376. Object.keys(ns.connected),
  377. (id, next) => {
  378. const { session } = ns.connected[id];
  379. CacheModule.runJob(
  380. "HGET",
  381. {
  382. table: "sessions",
  383. key: session.sessionId
  384. },
  385. this
  386. )
  387. .then(session => {
  388. if (session && ns.connected[id].ip === payload.ip) sockets.push(ns.connected[id]);
  389. next();
  390. })
  391. .catch(() => next());
  392. },
  393. () => {
  394. resolve({ sockets });
  395. }
  396. );
  397. }
  398. return resolve();
  399. });
  400. }
  401. /**
  402. * Returns any sockets from a specific user without using redis/cache
  403. *
  404. * @param {object} payload - object that contains the payload
  405. * @param {string} payload.userId - the id of the user in question
  406. * @returns {Promise} - returns promise (reject, resolve)
  407. */
  408. async SOCKETS_FROM_USER_WITHOUT_CACHE(payload) {
  409. return new Promise(resolve => {
  410. const ns = IOModule._io.of("/");
  411. const sockets = [];
  412. if (ns) {
  413. return async.each(
  414. Object.keys(ns.connected),
  415. (id, next) => {
  416. const { session } = ns.connected[id];
  417. if (session.userId === payload.userId) sockets.push(ns.connected[id]);
  418. next();
  419. },
  420. () => {
  421. resolve({ sockets });
  422. }
  423. );
  424. }
  425. return resolve();
  426. });
  427. }
  428. /**
  429. * Allows a socket to leave any rooms they are connected to
  430. *
  431. * @param {object} payload - object that contains the payload
  432. * @param {string} payload.socketId - the id of the socket which should leave all their rooms
  433. * @returns {Promise} - returns promise (reject, resolve)
  434. */
  435. async SOCKET_LEAVE_ROOMS(payload) {
  436. const socket = await IOModule.runJob(
  437. "SOCKET_FROM_SESSION",
  438. {
  439. socketId: payload.socketId
  440. },
  441. this
  442. );
  443. return new Promise(resolve => {
  444. const { rooms } = socket;
  445. Object.keys(rooms).forEach(roomKey => {
  446. const room = rooms[roomKey];
  447. socket.leave(room);
  448. });
  449. return resolve();
  450. });
  451. }
  452. /**
  453. * Allows a socket to join a specified room
  454. *
  455. * @param {object} payload - object that contains the payload
  456. * @param {string} payload.socketId - the id of the socket which should join the room
  457. * @param {object} payload.room - the object representing the room the socket should join
  458. * @returns {Promise} - returns promise (reject, resolve)
  459. */
  460. async SOCKET_JOIN_ROOM(payload) {
  461. const socket = await IOModule.runJob(
  462. "SOCKET_FROM_SESSION",
  463. {
  464. socketId: payload.socketId
  465. },
  466. this
  467. );
  468. return new Promise(resolve => {
  469. const { rooms } = socket;
  470. Object.keys(rooms).forEach(roomKey => {
  471. const room = rooms[roomKey];
  472. socket.leave(room);
  473. });
  474. socket.join(payload.room);
  475. return resolve();
  476. });
  477. }
  478. // UNKNOWN
  479. // eslint-disable-next-line require-jsdoc
  480. async SOCKET_JOIN_SONG_ROOM(payload) {
  481. // socketId, room
  482. const socket = await IOModule.runJob(
  483. "SOCKET_FROM_SESSION",
  484. {
  485. socketId: payload.socketId
  486. },
  487. this
  488. );
  489. return new Promise(resolve => {
  490. const { rooms } = socket;
  491. Object.keys(rooms).forEach(roomKey => {
  492. const room = rooms[roomKey];
  493. if (room.indexOf("song.") !== -1) socket.leave(room);
  494. });
  495. socket.join(payload.room);
  496. return resolve();
  497. });
  498. }
  499. // UNKNOWN
  500. // eslint-disable-next-line require-jsdoc
  501. SOCKETS_JOIN_SONG_ROOM(payload) {
  502. // sockets, room
  503. return new Promise(resolve => {
  504. Object.keys(payload.sockets).forEach(socketKey => {
  505. const socket = payload.sockets[socketKey];
  506. const { rooms } = socket;
  507. Object.keys(rooms).forEach(roomKey => {
  508. const room = rooms[roomKey];
  509. if (room.indexOf("song.") !== -1) socket.leave(room);
  510. });
  511. socket.join(payload.room);
  512. });
  513. return resolve();
  514. });
  515. }
  516. // UNKNOWN
  517. // eslint-disable-next-line require-jsdoc
  518. SOCKETS_LEAVE_SONG_ROOMS(payload) {
  519. // sockets
  520. return new Promise(resolve => {
  521. Object.keys(payload.sockets).forEach(socketKey => {
  522. const socket = payload.sockets[socketKey];
  523. const { rooms } = socket;
  524. Object.keys(rooms).forEach(roomKey => {
  525. const room = rooms[roomKey];
  526. if (room.indexOf("song.") !== -1) socket.leave(room);
  527. });
  528. });
  529. resolve();
  530. });
  531. }
  532. /**
  533. * Emits arguments to any sockets that are in a specified a room
  534. *
  535. * @param {object} payload - object that contains the payload
  536. * @param {string} payload.room - the name of the room to emit arguments
  537. * @param {object} payload.args - any arguments to be emitted to the sockets in the specific room
  538. * @returns {Promise} - returns promise (reject, resolve)
  539. */
  540. async EMIT_TO_ROOM(payload) {
  541. return new Promise(resolve => {
  542. const { sockets } = IOModule._io.sockets;
  543. Object.keys(sockets).forEach(socketKey => {
  544. const socket = sockets[socketKey];
  545. if (socket.rooms[payload.room]) {
  546. socket.emit(...payload.args);
  547. }
  548. });
  549. return resolve();
  550. });
  551. }
  552. /**
  553. * Gets any sockets connected to a room
  554. *
  555. * @param {object} payload - object that contains the payload
  556. * @param {string} payload.room - the name of the room
  557. * @returns {Promise} - returns promise (reject, resolve)
  558. */
  559. async GET_ROOM_SOCKETS(payload) {
  560. return new Promise(resolve => {
  561. const { sockets } = IOModule._io.sockets;
  562. const roomSockets = [];
  563. Object.keys(sockets).forEach(socketKey => {
  564. const socket = sockets[socketKey];
  565. if (socket.rooms[payload.room]) roomSockets.push(socket);
  566. });
  567. return resolve(roomSockets);
  568. });
  569. }
  570. }
  571. export default new _IOModule();