ws.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  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:user.banned", { data: { ban: socket.banishment.ban } });
  484. socket.close(); // close socket connection
  485. resolve();
  486. return;
  487. }
  488. WSModule.log("INFO", "IO_CONNECTION", `User connected. IP: ${socket.ip}.${sessionInfo}`);
  489. // catch when the socket has been disconnected
  490. socket.on("close", async () => {
  491. if (socket.session.sessionId) sessionInfo = ` UserID: ${socket.session.userId}.`;
  492. WSModule.log("INFO", "IO_DISCONNECTION", `User disconnected. IP: ${socket.ip}.${sessionInfo}`);
  493. // leave all rooms when a socket connection is closed (to prevent rooms object building up)
  494. await WSModule.runJob("SOCKET_LEAVE_ROOMS", { socketId: socket.session.socketId });
  495. });
  496. // catch errors on the socket
  497. socket.onerror = error => {
  498. console.error("SOCKET ERROR: ", error);
  499. };
  500. if (socket.session.sessionId) {
  501. CacheModule.runJob("HGET", {
  502. table: "sessions",
  503. key: socket.session.sessionId
  504. })
  505. .then(session => {
  506. if (session && session.userId) {
  507. WSModule.userModel.findOne({ _id: session.userId }, (err, user) => {
  508. if (err || !user) return socket.dispatch("ready", { data: { loggedIn: false } });
  509. let role = "";
  510. let username = "";
  511. let userId = "";
  512. let email = "";
  513. if (user) {
  514. role = user.role;
  515. username = user.username;
  516. email = user.email.address;
  517. userId = session.userId;
  518. }
  519. return socket.dispatch("ready", {
  520. data: { loggedIn: true, role, username, userId, email }
  521. });
  522. });
  523. } else socket.dispatch("ready", { data: { loggedIn: false } });
  524. })
  525. .catch(() => socket.dispatch("ready", { data: { loggedIn: false } }));
  526. } else socket.dispatch("ready", { data: { loggedIn: false } });
  527. socket.onmessage = message => {
  528. const data = JSON.parse(message.data);
  529. if (data.length === 0) return socket.dispatch("ERROR", "Not enough arguments specified.");
  530. if (typeof data[0] !== "string") return socket.dispatch("ERROR", "First argument must be a string.");
  531. const namespaceAction = data[0];
  532. if (
  533. !namespaceAction ||
  534. namespaceAction.indexOf(".") === -1 ||
  535. namespaceAction.indexOf(".") !== namespaceAction.lastIndexOf(".")
  536. )
  537. return socket.dispatch("ERROR", "Invalid first argument");
  538. const namespace = data[0].split(".")[0];
  539. const action = data[0].split(".")[1];
  540. if (!namespace) return socket.dispatch("ERROR", "Invalid namespace.");
  541. if (!action) return socket.dispatch("ERROR", "Invalid action.");
  542. if (!WSModule.actions[namespace]) return socket.dispatch("ERROR", `Namespace ${namespace} not found.`);
  543. if (!WSModule.actions[namespace][action])
  544. return socket.dispatch("ERROR", `Action ${namespace}.${action} not found.`);
  545. if (data[data.length - 1].CB_REF) {
  546. const { CB_REF, onProgress } = data[data.length - 1];
  547. data.pop();
  548. return socket.actions.emit(data.shift(0), {
  549. args: [...data, res => socket.dispatch("CB_REF", CB_REF, res)],
  550. onProgress: onProgress ? res => socket.dispatch("PROGRESS_CB_REF", CB_REF, res) : null
  551. });
  552. }
  553. return socket.actions.emit(data.shift(0), { args: data });
  554. };
  555. // have the socket listen for each action
  556. Object.keys(WSModule.actions).forEach(namespace => {
  557. Object.keys(WSModule.actions[namespace]).forEach(action => {
  558. // the full name of the action
  559. const name = `${namespace}.${action}`;
  560. // listen for this action to be called
  561. socket.listen(name, async ({ args, onProgress }) => {
  562. WSModule.runJob("RUN_ACTION", { socket, namespace, action, args }, { onProgress });
  563. });
  564. });
  565. });
  566. resolve();
  567. });
  568. }
  569. /**
  570. * Runs an action
  571. *
  572. * @param {object} payload - object that contains the payload
  573. * @returns {Promise} - returns promise (reject, resolve)
  574. */
  575. async RUN_ACTION(payload) {
  576. return new Promise((resolve, reject) => {
  577. const { socket, namespace, action, args } = payload;
  578. // the full name of the action
  579. const name = `${namespace}.${action}`;
  580. let cb = args[args.length - 1];
  581. if (typeof cb !== "function")
  582. cb = () => {
  583. WSModule.log("INFO", "IO_MODULE", `There was no callback provided for ${name}.`);
  584. };
  585. else args.pop();
  586. WSModule.log("INFO", "IO_ACTION", `A user executed an action. Action: ${namespace}.${action}.`);
  587. // load the session from the cache
  588. new Promise(resolve => {
  589. if (socket.session.sessionId)
  590. CacheModule.runJob("HGET", {
  591. table: "sessions",
  592. key: socket.session.sessionId
  593. })
  594. .then(session => {
  595. // make sure the sockets sessionId isn't set if there is no session
  596. if (socket.session.sessionId && session === null) delete socket.session.sessionId;
  597. resolve();
  598. })
  599. .catch(() => {
  600. if (typeof cb === "function")
  601. cb({
  602. status: "error",
  603. message: "An error occurred while obtaining your session"
  604. });
  605. reject(new Error("An error occurred while obtaining the session"));
  606. });
  607. else resolve();
  608. })
  609. .then(() => {
  610. // call the job that calls the action, passing it the session, and the arguments the websocket passed us
  611. WSModule.runJob("RUN_ACTION2", { session: socket.session, namespace, action, args }, this)
  612. .then(response => {
  613. cb(response);
  614. resolve();
  615. })
  616. .catch(err => {
  617. if (typeof cb === "function")
  618. cb({
  619. status: "error",
  620. message: "An error occurred while executing the specified action."
  621. });
  622. reject(err);
  623. WSModule.log(
  624. "ERROR",
  625. "IO_ACTION_ERROR",
  626. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  627. );
  628. });
  629. })
  630. .catch(reject);
  631. });
  632. }
  633. /**
  634. * Runs an action
  635. *
  636. * @param {object} payload - object that contains the payload
  637. * @returns {Promise} - returns promise (reject, resolve)
  638. */
  639. async RUN_ACTION2(payload) {
  640. return new Promise((resolve, reject) => {
  641. const { session, namespace, action, args } = payload;
  642. try {
  643. // call the the action, passing it the session, and the arguments the websocket passed us
  644. WSModule.actions[namespace][action].apply(
  645. this,
  646. [session].concat(args).concat([
  647. result => {
  648. WSModule.log(
  649. "INFO",
  650. "RUN_ACTION2",
  651. `Response to action. Action: ${namespace}.${action}. Response status: ${result.status}`
  652. );
  653. resolve(result);
  654. }
  655. ])
  656. );
  657. } catch (err) {
  658. reject(err);
  659. WSModule.log(
  660. "ERROR",
  661. "IO_ACTION_ERROR",
  662. `Some type of exception occurred in the action ${namespace}.${action}. Error message: ${err.message}`
  663. );
  664. }
  665. });
  666. }
  667. }
  668. export default new _WSModule();