ws.js 23 KB

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