ws.js 23 KB

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