ws.js 22 KB

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