ws.js 22 KB

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