stations.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. import async from "async";
  2. // import mongoose from "mongoose";
  3. import CoreClass from "../core";
  4. let StationsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let WSModule;
  9. let SongsModule;
  10. let PlaylistsModule;
  11. let NotificationsModule;
  12. class _StationsModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("stations");
  16. StationsModule = this;
  17. }
  18. /**
  19. * Initialises the stations module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. async initialize() {
  24. CacheModule = this.moduleManager.modules.cache;
  25. DBModule = this.moduleManager.modules.db;
  26. UtilsModule = this.moduleManager.modules.utils;
  27. WSModule = this.moduleManager.modules.ws;
  28. SongsModule = this.moduleManager.modules.songs;
  29. PlaylistsModule = this.moduleManager.modules.playlists;
  30. NotificationsModule = this.moduleManager.modules.notifications;
  31. // this.defaultSong = {
  32. // songId: "60ItHLz5WEA",
  33. // title: "Faded - Alan Walker",
  34. // duration: 212,
  35. // skipDuration: 0,
  36. // likes: -1,
  37. // dislikes: -1,
  38. // requestedAt: Date.now(),
  39. // status: "unverified"
  40. // };
  41. this.userList = {};
  42. this.usersPerStation = {};
  43. this.usersPerStationCount = {};
  44. // TEMP
  45. CacheModule.runJob("SUB", {
  46. channel: "station.pause",
  47. cb: async stationId => {
  48. NotificationsModule.runJob("REMOVE", {
  49. subscription: `stations.nextSong?id=${stationId}`
  50. }).then();
  51. }
  52. });
  53. CacheModule.runJob("SUB", {
  54. channel: "station.resume",
  55. cb: async stationId => {
  56. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  57. }
  58. });
  59. CacheModule.runJob("SUB", {
  60. channel: "station.queueUpdate",
  61. cb: async stationId => {
  62. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  63. if (!station.currentSong && station.queue.length > 0) {
  64. StationsModule.runJob("INITIALIZE_STATION", {
  65. stationId
  66. }).then();
  67. }
  68. });
  69. }
  70. });
  71. CacheModule.runJob("SUB", {
  72. channel: "station.newOfficialPlaylist",
  73. cb: async stationId => {
  74. CacheModule.runJob("HGET", {
  75. table: "officialPlaylists",
  76. key: stationId
  77. }).then(playlistObj => {
  78. if (playlistObj) {
  79. WSModule.runJob("EMIT_TO_ROOM", {
  80. room: `station.${stationId}`,
  81. args: ["event:newOfficialPlaylist", playlistObj.songs]
  82. });
  83. }
  84. });
  85. }
  86. });
  87. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  88. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  89. return new Promise((resolve, reject) =>
  90. async.waterfall(
  91. [
  92. next => {
  93. this.setStage(2);
  94. CacheModule.runJob("HGETALL", { table: "stations" })
  95. .then(stations => {
  96. next(null, stations);
  97. })
  98. .catch(next);
  99. },
  100. (stations, next) => {
  101. this.setStage(3);
  102. if (!stations) return next();
  103. const stationIds = Object.keys(stations);
  104. return async.each(
  105. stationIds,
  106. (stationId, next) => {
  107. stationModel.findOne({ _id: stationId }, (err, station) => {
  108. if (err) next(err);
  109. else if (!station) {
  110. CacheModule.runJob("HDEL", {
  111. table: "stations",
  112. key: stationId
  113. })
  114. .then(() => {
  115. next();
  116. })
  117. .catch(next);
  118. } else next();
  119. });
  120. },
  121. next
  122. );
  123. },
  124. next => {
  125. this.setStage(4);
  126. stationModel.find({}, next);
  127. },
  128. (stations, next) => {
  129. this.setStage(5);
  130. async.each(
  131. stations,
  132. (station, next2) => {
  133. async.waterfall(
  134. [
  135. next => {
  136. CacheModule.runJob("HSET", {
  137. table: "stations",
  138. key: station._id,
  139. value: stationSchema(station)
  140. })
  141. .then(station => next(null, station))
  142. .catch(next);
  143. },
  144. (station, next) => {
  145. StationsModule.runJob(
  146. "INITIALIZE_STATION",
  147. {
  148. stationId: station._id
  149. },
  150. null,
  151. -1
  152. )
  153. .then(() => {
  154. next();
  155. })
  156. .catch(next);
  157. }
  158. ],
  159. err => {
  160. next2(err);
  161. }
  162. );
  163. },
  164. next
  165. );
  166. }
  167. ],
  168. async err => {
  169. if (err) {
  170. err = await UtilsModule.runJob("GET_ERROR", {
  171. error: err
  172. });
  173. reject(new Error(err));
  174. } else {
  175. resolve();
  176. }
  177. }
  178. )
  179. );
  180. }
  181. /**
  182. * Initialises a station
  183. *
  184. * @param {object} payload - object that contains the payload
  185. * @param {string} payload.stationId - id of the station to initialise
  186. * @returns {Promise} - returns a promise (resolve, reject)
  187. */
  188. INITIALIZE_STATION(payload) {
  189. return new Promise((resolve, reject) => {
  190. // if (typeof cb !== 'function') cb = ()=>{};
  191. async.waterfall(
  192. [
  193. next => {
  194. StationsModule.runJob(
  195. "GET_STATION",
  196. {
  197. stationId: payload.stationId
  198. },
  199. this
  200. )
  201. .then(station => {
  202. next(null, station);
  203. })
  204. .catch(next);
  205. },
  206. (station, next) => {
  207. if (!station) return next("Station not found.");
  208. return NotificationsModule.runJob(
  209. "UNSCHEDULE",
  210. {
  211. name: `stations.nextSong?id=${station._id}`
  212. },
  213. this
  214. )
  215. .then()
  216. .catch()
  217. .finally(() => {
  218. NotificationsModule.runJob("SUBSCRIBE", {
  219. name: `stations.nextSong?id=${station._id}`,
  220. cb: () =>
  221. StationsModule.runJob("SKIP_STATION", {
  222. stationId: station._id
  223. }),
  224. unique: true,
  225. station
  226. })
  227. .then()
  228. .catch();
  229. if (station.paused) return next(true, station);
  230. return next(null, station);
  231. });
  232. },
  233. (station, next) => {
  234. if (!station.currentSong) {
  235. return StationsModule.runJob(
  236. "SKIP_STATION",
  237. {
  238. stationId: station._id
  239. },
  240. this
  241. )
  242. .then(station => {
  243. next(true, station);
  244. })
  245. .catch(next)
  246. .finally(() => {});
  247. }
  248. let timeLeft =
  249. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  250. if (Number.isNaN(timeLeft)) timeLeft = -1;
  251. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  252. return StationsModule.runJob(
  253. "SKIP_STATION",
  254. {
  255. stationId: station._id
  256. },
  257. this
  258. )
  259. .then(station => {
  260. next(null, station);
  261. })
  262. .catch(next);
  263. }
  264. // name, time, cb, station
  265. NotificationsModule.runJob("SCHEDULE", {
  266. name: `stations.nextSong?id=${station._id}`,
  267. time: timeLeft,
  268. station
  269. });
  270. return next(null, station);
  271. }
  272. ],
  273. async (err, station) => {
  274. if (err && err !== true) {
  275. err = await UtilsModule.runJob(
  276. "GET_ERROR",
  277. {
  278. error: err
  279. },
  280. this
  281. );
  282. reject(new Error(err));
  283. } else resolve(station);
  284. }
  285. );
  286. });
  287. }
  288. /**
  289. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  290. *
  291. * @param {object} payload - object that contains the payload
  292. * @param {string} payload.stationId - id of the station
  293. * @returns {Promise} - returns a promise (resolve, reject)
  294. */
  295. GET_STATION(payload) {
  296. return new Promise((resolve, reject) => {
  297. async.waterfall(
  298. [
  299. next => {
  300. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  301. .then(station => next(null, station))
  302. .catch(next);
  303. },
  304. (station, next) => {
  305. if (station) return next(true, station);
  306. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  307. },
  308. (station, next) => {
  309. if (station) {
  310. station = StationsModule.stationSchema(station);
  311. CacheModule.runJob("HSET", {
  312. table: "stations",
  313. key: payload.stationId,
  314. value: station
  315. })
  316. .then()
  317. .catch();
  318. next(true, station);
  319. } else next("Station not found");
  320. }
  321. ],
  322. async (err, station) => {
  323. if (err && err !== true) {
  324. err = await UtilsModule.runJob(
  325. "GET_ERROR",
  326. {
  327. error: err
  328. },
  329. this
  330. );
  331. reject(new Error(err));
  332. } else resolve(station);
  333. }
  334. );
  335. });
  336. }
  337. /**
  338. * Attempts to get a station by name, firstly from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  339. *
  340. * @param {object} payload - object that contains the payload
  341. * @param {string} payload.stationName - the unique name of the station
  342. * @returns {Promise} - returns a promise (resolve, reject)
  343. */
  344. async GET_STATION_BY_NAME(payload) {
  345. return new Promise((resolve, reject) =>
  346. async.waterfall(
  347. [
  348. next => {
  349. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  350. },
  351. (station, next) => {
  352. if (station) {
  353. station = StationsModule.stationSchema(station);
  354. CacheModule.runJob("HSET", {
  355. table: "stations",
  356. key: station._id,
  357. value: station
  358. });
  359. next(true, station);
  360. } else next("Station not found");
  361. }
  362. ],
  363. (err, station) => {
  364. if (err && err !== true) return reject(new Error(err));
  365. return resolve(station);
  366. }
  367. )
  368. );
  369. }
  370. /**
  371. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  372. *
  373. * @param {object} payload - object that contains the payload
  374. * @param {string} payload.stationId - the id of the station to update
  375. * @returns {Promise} - returns a promise (resolve, reject)
  376. */
  377. UPDATE_STATION(payload) {
  378. return new Promise((resolve, reject) => {
  379. async.waterfall(
  380. [
  381. next => {
  382. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  383. },
  384. (station, next) => {
  385. if (!station) {
  386. CacheModule.runJob("HDEL", {
  387. table: "stations",
  388. key: payload.stationId
  389. })
  390. .then()
  391. .catch();
  392. return next("Station not found");
  393. }
  394. return CacheModule.runJob(
  395. "HSET",
  396. {
  397. table: "stations",
  398. key: payload.stationId,
  399. value: station
  400. },
  401. this
  402. )
  403. .then(station => {
  404. next(null, station);
  405. })
  406. .catch(next);
  407. }
  408. ],
  409. async (err, station) => {
  410. if (err && err !== true) {
  411. err = await UtilsModule.runJob(
  412. "GET_ERROR",
  413. {
  414. error: err
  415. },
  416. this
  417. );
  418. reject(new Error(err));
  419. } else resolve(station);
  420. }
  421. );
  422. });
  423. }
  424. /**
  425. * Fills up the official station playlist queue using the songs from the official station playlist
  426. *
  427. * @param {object} payload - object that contains the payload
  428. * @param {string} payload.stationId - the id of the station
  429. * @returns {Promise} - returns a promise (resolve, reject)
  430. */
  431. FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST(payload) {
  432. return new Promise((resolve, reject) => {
  433. const { stationId } = payload;
  434. async.waterfall(
  435. [
  436. next => {
  437. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  438. .then(response => {
  439. next(null, response.playlist);
  440. })
  441. .catch(next);
  442. },
  443. (playlist, next) => {
  444. StationsModule.runJob("GET_STATION", { stationId }, this)
  445. .then(station => {
  446. next(null, playlist, station);
  447. })
  448. .catch(next);
  449. },
  450. (playlist, station, next) => {
  451. if (station.playMode === "random") {
  452. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  453. .then(response => {
  454. next(null, response.array, station);
  455. })
  456. .catch(next);
  457. } else next(null, playlist.songs, station);
  458. },
  459. (_playlistSongs, station, next) => {
  460. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  461. if (station.playMode === "sequential") {
  462. if (station.currentSongIndex <= playlistSongs.length) {
  463. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  464. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  465. }
  466. }
  467. const songsStillNeeded = 50 - station.queue.length;
  468. const currentSongs = station.queue;
  469. const currentSongIds = station.queue.map(song => song.songId);
  470. const songsToAdd = [];
  471. let lastSongAdded = null;
  472. playlistSongs
  473. // .map(song => song._doc)
  474. .every(song => {
  475. if (
  476. songsToAdd.length < songsStillNeeded &&
  477. currentSongIds.indexOf(song.songId) === -1
  478. ) {
  479. lastSongAdded = song;
  480. songsToAdd.push(song);
  481. return true;
  482. }
  483. if (songsToAdd.length >= songsStillNeeded) return false;
  484. return true;
  485. });
  486. let { currentSongIndex } = station;
  487. if (station.playMode === "sequential" && lastSongAdded) {
  488. const indexOfLastSong = _playlistSongs
  489. .map(song => song.songId)
  490. .indexOf(lastSongAdded.songId);
  491. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  492. }
  493. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  494. if (!song._id) song._id = null;
  495. return song;
  496. });
  497. next(null, newPlaylist, currentSongIndex);
  498. },
  499. (newPlaylist, currentSongIndex, next) => {
  500. StationsModule.stationModel.updateOne(
  501. { _id: stationId },
  502. { $set: { queue: newPlaylist, currentSongIndex } },
  503. { runValidators: true },
  504. err => {
  505. if (err) next(err);
  506. else
  507. StationsModule.runJob(
  508. "UPDATE_STATION",
  509. {
  510. stationId
  511. },
  512. this
  513. )
  514. .then(() => {
  515. next(null);
  516. })
  517. .catch(next);
  518. }
  519. );
  520. }
  521. ],
  522. err => {
  523. if (err) reject(err);
  524. else resolve();
  525. }
  526. );
  527. });
  528. }
  529. /**
  530. * Gets next station song
  531. *
  532. * @param {object} payload - object that contains the payload
  533. * @param {string} payload.stationId - the id of the station
  534. * @returns {Promise} - returns a promise (resolve, reject)
  535. */
  536. GET_NEXT_STATION_SONG(payload) {
  537. return new Promise((resolve, reject) => {
  538. const { stationId } = payload;
  539. async.waterfall(
  540. [
  541. next => {
  542. StationsModule.runJob("GET_STATION", { stationId }, this)
  543. .then(station => {
  544. next(null, station);
  545. })
  546. .catch(next);
  547. },
  548. (station, next) => {
  549. if (station.queue.length === 0) next("No songs available.");
  550. else {
  551. next(null, station.queue[0]);
  552. }
  553. },
  554. (queueSong, next) => {
  555. if (!queueSong._id) next(null, queueSong);
  556. else
  557. SongsModule.runJob("GET_SONG", { id: queueSong._id }, this)
  558. .then(response => {
  559. const { song } = response;
  560. if (song) {
  561. const newSong = {
  562. _id: song._id,
  563. songId: song.songId,
  564. title: song.title,
  565. artists: song.artists,
  566. duration: song.duration,
  567. skipDuration: song.skipDuration,
  568. thumbnail: song.thumbnail,
  569. requestedAt: queueSong.requestedAt,
  570. requestedBy: queueSong.requestedBy,
  571. likes: song.likes,
  572. dislikes: song.dislikes,
  573. status: song.status
  574. };
  575. return next(null, newSong);
  576. }
  577. return next(null, song);
  578. })
  579. .catch(err => {
  580. next(err);
  581. });
  582. }
  583. ],
  584. (err, song) => {
  585. if (err) console.log(33333, err, payload);
  586. if (err) reject(err);
  587. else resolve({ song });
  588. }
  589. );
  590. });
  591. }
  592. /**
  593. * Removes first station queue song
  594. *
  595. * @param {object} payload - object that contains the payload
  596. * @param {string} payload.stationId - the id of the station
  597. * @returns {Promise} - returns a promise (resolve, reject)
  598. */
  599. REMOVE_FIRST_QUEUE_SONG(payload) {
  600. return new Promise((resolve, reject) => {
  601. const { stationId } = payload;
  602. async.waterfall(
  603. [
  604. next => {
  605. StationsModule.stationModel.updateOne(
  606. { _id: stationId },
  607. { $pop: { queue: -1 } },
  608. { runValidators: true },
  609. err => {
  610. if (err) next(err);
  611. else
  612. StationsModule.runJob(
  613. "UPDATE_STATION",
  614. {
  615. stationId
  616. },
  617. this
  618. )
  619. .then(() => {
  620. next(null);
  621. })
  622. .catch(next);
  623. }
  624. );
  625. }
  626. ],
  627. err => {
  628. if (err) reject(err);
  629. else resolve();
  630. }
  631. );
  632. });
  633. }
  634. /**
  635. * Skips a station
  636. *
  637. * @param {object} payload - object that contains the payload
  638. * @param {string} payload.stationId - the id of the station to skip
  639. * @returns {Promise} - returns a promise (resolve, reject)
  640. */
  641. SKIP_STATION(payload) {
  642. return new Promise((resolve, reject) => {
  643. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  644. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  645. async.waterfall(
  646. [
  647. // Clears up any existing timers that would skip the station if the song ends
  648. next => {
  649. NotificationsModule.runJob("UNSCHEDULE", {
  650. name: `stations.nextSong?id=${payload.stationId}`
  651. })
  652. .then(() => {
  653. next();
  654. })
  655. .catch(next);
  656. },
  657. // Gets the station object
  658. next => {
  659. StationsModule.runJob(
  660. "GET_STATION",
  661. {
  662. stationId: payload.stationId
  663. },
  664. this
  665. )
  666. .then(station => {
  667. next(null, station);
  668. })
  669. .catch(() => {});
  670. },
  671. // eslint-disable-next-line consistent-return
  672. (station, next) => {
  673. if (!station) return next("Station not found.");
  674. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  675. return next(null, null, station); // Community station with party mode enabled and no songs in the queue
  676. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  677. // Community station with party mode enabled and songs in the queue
  678. if (station.paused) return next(null, null, station);
  679. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  680. .then(response => {
  681. StationsModule.runJob(
  682. "REMOVE_FIRST_QUEUE_SONG",
  683. { stationId: station._id },
  684. this
  685. ).then(() => {
  686. next(null, response.song, station);
  687. });
  688. })
  689. .catch(err => {
  690. if (err === "No songs available.") next(null, null, station);
  691. else next(err);
  692. });
  693. // return StationsModule.stationModel.updateOne(
  694. // { _id: payload.stationId },
  695. // {
  696. // $pull: {
  697. // queue: {
  698. // _id: station.queue[0]._id
  699. // }
  700. // }
  701. // },
  702. // err => {
  703. // if (err) return next(err);
  704. // return next(null, station.queue[0], -12, station);
  705. // }
  706. // );
  707. }
  708. if (station.type === "community" && !station.partyMode) {
  709. StationsModule.runJob(
  710. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  711. { stationId: station._id },
  712. this
  713. )
  714. .then(() => {
  715. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  716. .then(response => {
  717. StationsModule.runJob(
  718. "REMOVE_FIRST_QUEUE_SONG",
  719. { stationId: station._id },
  720. this
  721. ).then(() => {
  722. next(null, response.song, station);
  723. });
  724. })
  725. .catch(err => {
  726. if (err === "No songs available.") next(null, null, station);
  727. else next(err);
  728. });
  729. })
  730. .catch(next);
  731. }
  732. // if (station.type === "community" && !station.partyMode) {
  733. // return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  734. // playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  735. // if (err) return next(err);
  736. // if (!playlist) return next(null, null, -13, station);
  737. // playlist = playlist.songs;
  738. // if (playlist.length > 0) {
  739. // let currentSongIndex;
  740. // if (station.currentSongIndex < playlist.length - 1)
  741. // currentSongIndex = station.currentSongIndex + 1;
  742. // else currentSongIndex = 0;
  743. // const callback = (err, song) => {
  744. // if (err) return next(err);
  745. // if (song) return next(null, song, currentSongIndex, station);
  746. // const currentSong = {
  747. // songId: playlist[currentSongIndex].songId,
  748. // title: playlist[currentSongIndex].title,
  749. // duration: playlist[currentSongIndex].duration,
  750. // likes: -1,
  751. // dislikes: -1,
  752. // requestedAt: playlist[currentSongIndex].requestedAt
  753. // };
  754. // return next(null, currentSong, currentSongIndex, station);
  755. // };
  756. // if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  757. // return SongsModule.runJob(
  758. // "GET_SONG",
  759. // {
  760. // id: playlist[currentSongIndex]._id
  761. // },
  762. // this
  763. // )
  764. // .then(response => callback(null, response.song))
  765. // .catch(callback);
  766. // return SongsModule.runJob(
  767. // "GET_SONG_FROM_ID",
  768. // {
  769. // songId: playlist[currentSongIndex].songId
  770. // },
  771. // this
  772. // )
  773. // .then(response => callback(null, response.song))
  774. // .catch(callback);
  775. // }
  776. // return next(null, null, -14, station);
  777. // })
  778. // );
  779. // }
  780. if (station.type === "official") {
  781. StationsModule.runJob(
  782. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  783. { stationId: station._id },
  784. this
  785. )
  786. .then(() => {
  787. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  788. .then(response => {
  789. StationsModule.runJob(
  790. "REMOVE_FIRST_QUEUE_SONG",
  791. { stationId: station._id },
  792. this
  793. )
  794. .then(() => {
  795. next(null, response.song, station);
  796. })
  797. .catch(next);
  798. })
  799. .catch(err => {
  800. if (err === "No songs available.") next(null, null, station);
  801. else next(err);
  802. });
  803. })
  804. .catch(next);
  805. }
  806. },
  807. (song, station, next) => {
  808. const $set = {};
  809. if (song === null) $set.currentSong = null;
  810. else {
  811. $set.currentSong = {
  812. _id: song._id,
  813. songId: song.songId,
  814. title: song.title,
  815. artists: song.artists,
  816. duration: song.duration,
  817. likes: song.likes,
  818. dislikes: song.dislikes,
  819. skipDuration: song.skipDuration,
  820. thumbnail: song.thumbnail,
  821. requestedAt: song.requestedAt,
  822. requestedBy: song.requestedBy,
  823. status: song.status
  824. };
  825. }
  826. // if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  827. $set.startedAt = Date.now();
  828. $set.timePaused = 0;
  829. if (station.paused) $set.pausedAt = Date.now();
  830. next(null, $set, station);
  831. },
  832. ($set, station, next) => {
  833. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  834. if (err) return next(err);
  835. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  836. .then(station => {
  837. CacheModule.runJob("PUB", {
  838. channel: "station.queueUpdate",
  839. value: payload.stationId
  840. })
  841. .then()
  842. .catch();
  843. next(null, station);
  844. })
  845. .catch(next);
  846. });
  847. }
  848. ],
  849. async (err, station) => {
  850. if (err) {
  851. err = await UtilsModule.runJob(
  852. "GET_ERROR",
  853. {
  854. error: err
  855. },
  856. this
  857. );
  858. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  859. reject(new Error(err));
  860. } else {
  861. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  862. station.currentSong.skipVotes = 0;
  863. }
  864. // TODO Pub/Sub this
  865. WSModule.runJob("EMIT_TO_ROOM", {
  866. room: `station.${station._id}`,
  867. args: [
  868. "event:songs.next",
  869. {
  870. currentSong: station.currentSong,
  871. startedAt: station.startedAt,
  872. paused: station.paused,
  873. timePaused: 0
  874. }
  875. ]
  876. })
  877. .then()
  878. .catch();
  879. if (station.privacy === "public") {
  880. WSModule.runJob("EMIT_TO_ROOM", {
  881. room: "home",
  882. args: ["event:station.nextSong", station._id, station.currentSong]
  883. })
  884. .then()
  885. .catch();
  886. } else {
  887. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  888. sockets.forEach(async socketId => {
  889. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  890. const { session } = socket;
  891. if (session.sessionId) {
  892. CacheModule.runJob(
  893. "HGET",
  894. { table: "sessions", key: session.sessionId },
  895. this
  896. // eslint-disable-next-line no-loop-func
  897. ).then(session => {
  898. if (session) {
  899. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  900. userModel => {
  901. userModel.findOne(
  902. {
  903. _id: session.userId
  904. },
  905. (err, user) => {
  906. if (!err && user) {
  907. if (user.role === "admin")
  908. socket.dispatch(
  909. "event:station.nextSong",
  910. station._id,
  911. station.currentSong
  912. );
  913. else if (
  914. station.type === "community" &&
  915. station.owner === session.userId
  916. )
  917. socket.dispatch(
  918. "event:station.nextSong",
  919. station._id,
  920. station.currentSong
  921. );
  922. }
  923. }
  924. );
  925. }
  926. );
  927. }
  928. });
  929. }
  930. });
  931. }
  932. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  933. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  934. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  935. sockets,
  936. room: `song.${station.currentSong.songId}`
  937. });
  938. if (!station.paused) {
  939. NotificationsModule.runJob("SCHEDULE", {
  940. name: `stations.nextSong?id=${station._id}`,
  941. time: station.currentSong.duration * 1000,
  942. station
  943. });
  944. }
  945. } else {
  946. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  947. sockets
  948. });
  949. }
  950. });
  951. resolve({ station });
  952. }
  953. }
  954. );
  955. });
  956. }
  957. /**
  958. * Checks if a user can view/access a station
  959. *
  960. * @param {object} payload - object that contains the payload
  961. * @param {object} payload.station - the station object of the station in question
  962. * @param {string} payload.userId - the id of the user in question
  963. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  964. * @returns {Promise} - returns a promise (resolve, reject)
  965. */
  966. CAN_USER_VIEW_STATION(payload) {
  967. return new Promise((resolve, reject) => {
  968. async.waterfall(
  969. [
  970. next => {
  971. if (payload.station.privacy === "public") return next(true);
  972. if (payload.station.privacy === "unlisted")
  973. if (payload.hideUnlisted === true) return next();
  974. else return next(true);
  975. if (!payload.userId) return next("Not allowed");
  976. return next();
  977. },
  978. next => {
  979. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  980. userModel.findOne({ _id: payload.userId }, next);
  981. });
  982. },
  983. (user, next) => {
  984. if (!user) return next("Not allowed");
  985. if (user.role === "admin") return next(true);
  986. if (payload.station.type === "official") return next("Not allowed");
  987. if (payload.station.owner === payload.userId) return next(true);
  988. return next("Not allowed");
  989. }
  990. ],
  991. async errOrResult => {
  992. if (errOrResult !== true && errOrResult !== "Not allowed") {
  993. errOrResult = await UtilsModule.runJob(
  994. "GET_ERROR",
  995. {
  996. error: errOrResult
  997. },
  998. this
  999. );
  1000. reject(new Error(errOrResult));
  1001. } else {
  1002. resolve(errOrResult === true);
  1003. }
  1004. }
  1005. );
  1006. });
  1007. }
  1008. /**
  1009. * Checks if a user has favorited a station or not
  1010. *
  1011. * @param {object} payload - object that contains the payload
  1012. * @param {object} payload.stationId - the id of the station in question
  1013. * @param {string} payload.userId - the id of the user in question
  1014. * @returns {Promise} - returns a promise (resolve, reject)
  1015. */
  1016. HAS_USER_FAVORITED_STATION(payload) {
  1017. return new Promise((resolve, reject) => {
  1018. async.waterfall(
  1019. [
  1020. next => {
  1021. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1022. userModel.findOne({ _id: payload.userId }, next);
  1023. });
  1024. },
  1025. (user, next) => {
  1026. if (!user) return next("User not found.");
  1027. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1028. return next(null, false);
  1029. }
  1030. ],
  1031. async (err, isStationFavorited) => {
  1032. if (err && err !== true) {
  1033. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1034. return reject(new Error(err));
  1035. }
  1036. return resolve(isStationFavorited);
  1037. }
  1038. );
  1039. });
  1040. }
  1041. /**
  1042. * Returns a list of sockets in a room that can and can't know about a station
  1043. *
  1044. * @param {object} payload - the payload object
  1045. * @param {object} payload.station - the station object
  1046. * @param {string} payload.room - the websockets room to get the sockets from
  1047. * @returns {Promise} - returns a promise (resolve, reject)
  1048. */
  1049. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1050. return new Promise((resolve, reject) => {
  1051. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1052. .then(socketsObject => {
  1053. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1054. let socketsThatCan = [];
  1055. const socketsThatCannot = [];
  1056. if (payload.station.privacy === "public") {
  1057. socketsThatCan = sockets;
  1058. resolve({ socketsThatCan, socketsThatCannot });
  1059. } else {
  1060. async.eachLimit(
  1061. sockets,
  1062. 1,
  1063. (socket, next) => {
  1064. const { session } = socket;
  1065. async.waterfall(
  1066. [
  1067. next => {
  1068. if (!session.sessionId) next("No session id");
  1069. else next();
  1070. },
  1071. next => {
  1072. CacheModule.runJob(
  1073. "HGET",
  1074. {
  1075. table: "sessions",
  1076. key: session.sessionId
  1077. },
  1078. this
  1079. )
  1080. .then(response => {
  1081. next(null, response);
  1082. })
  1083. .catch(next);
  1084. },
  1085. (session, next) => {
  1086. if (!session) next("No session");
  1087. else {
  1088. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1089. .then(userModel => {
  1090. next(null, userModel);
  1091. })
  1092. .catch(next);
  1093. }
  1094. },
  1095. (userModel, next) => {
  1096. if (!userModel) next("No user model");
  1097. else
  1098. userModel.findOne(
  1099. {
  1100. _id: session.userId
  1101. },
  1102. next
  1103. );
  1104. },
  1105. (user, next) => {
  1106. if (!user) next("No user found");
  1107. else if (user.role === "admin") {
  1108. socketsThatCan.push(socket);
  1109. next();
  1110. } else if (
  1111. payload.station.type === "community" &&
  1112. payload.station.owner === session.userId
  1113. ) {
  1114. socketsThatCan.push(socket);
  1115. next();
  1116. }
  1117. }
  1118. ],
  1119. err => {
  1120. if (err) socketsThatCannot.push(socket);
  1121. next();
  1122. }
  1123. );
  1124. },
  1125. err => {
  1126. if (err) reject(err);
  1127. else resolve({ socketsThatCan, socketsThatCannot });
  1128. }
  1129. );
  1130. }
  1131. })
  1132. .catch(reject);
  1133. });
  1134. }
  1135. /**
  1136. * Adds a playlist to be included in a station
  1137. *
  1138. * @param {object} payload - object that contains the payload
  1139. * @param {object} payload.stationId - the id of the station to include the playlist in
  1140. * @param {object} payload.playlistId - the id of the playlist to be included
  1141. * @returns {Promise} - returns a promise (resolve, reject)
  1142. */
  1143. INCLUDE_PLAYLIST(payload) {
  1144. return new Promise((resolve, reject) => {
  1145. async.waterfall(
  1146. [
  1147. next => {
  1148. if (!payload.stationId) next("Please specify a station id");
  1149. else if (!payload.playlistId) next("Please specify a playlist id");
  1150. else next();
  1151. },
  1152. next => {
  1153. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1154. .then(station => {
  1155. next(null, station);
  1156. })
  1157. .catch(next);
  1158. },
  1159. (station, next) => {
  1160. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1161. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1162. next("This playlist is already included");
  1163. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1164. next(
  1165. "This playlist is currently excluded, please remove it from there before including it"
  1166. );
  1167. else
  1168. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1169. .then(() => {
  1170. next(null);
  1171. })
  1172. .catch(next);
  1173. },
  1174. next => {
  1175. DBModule.runJob(
  1176. "GET_MODEL",
  1177. {
  1178. modelName: "station"
  1179. },
  1180. this
  1181. ).then(stationModel => {
  1182. stationModel.updateOne(
  1183. { _id: payload.stationId },
  1184. { $push: { includedPlaylists: payload.playlistId } },
  1185. next
  1186. );
  1187. });
  1188. },
  1189. (res, next) => {
  1190. StationsModule.runJob(
  1191. "UPDATE_STATION",
  1192. {
  1193. stationId: payload.stationId
  1194. },
  1195. this
  1196. )
  1197. .then(() => {
  1198. next();
  1199. })
  1200. .catch(next);
  1201. }
  1202. ],
  1203. async err => {
  1204. if (err && err !== true) {
  1205. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1206. return reject(new Error(err));
  1207. }
  1208. return resolve();
  1209. }
  1210. );
  1211. });
  1212. }
  1213. /**
  1214. * Removes a playlist that is included in a station
  1215. *
  1216. * @param {object} payload - object that contains the payload
  1217. * @param {object} payload.stationId - the id of the station
  1218. * @param {object} payload.playlistId - the id of the playlist
  1219. * @returns {Promise} - returns a promise (resolve, reject)
  1220. */
  1221. REMOVE_INCLUDED_PLAYLIST(payload) {
  1222. return new Promise((resolve, reject) => {
  1223. async.waterfall(
  1224. [
  1225. next => {
  1226. if (!payload.stationId) next("Please specify a station id");
  1227. else if (!payload.playlistId) next("Please specify a playlist id");
  1228. else next();
  1229. },
  1230. next => {
  1231. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1232. .then(station => {
  1233. next(null, station);
  1234. })
  1235. .catch(next);
  1236. },
  1237. (station, next) => {
  1238. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1239. next("This playlist isn't included");
  1240. else next();
  1241. },
  1242. next => {
  1243. DBModule.runJob(
  1244. "GET_MODEL",
  1245. {
  1246. modelName: "station"
  1247. },
  1248. this
  1249. ).then(stationModel => {
  1250. stationModel.updateOne(
  1251. { _id: payload.stationId },
  1252. { $pull: { includedPlaylists: payload.playlistId } },
  1253. next
  1254. );
  1255. });
  1256. },
  1257. (res, next) => {
  1258. StationsModule.runJob(
  1259. "UPDATE_STATION",
  1260. {
  1261. stationId: payload.stationId
  1262. },
  1263. this
  1264. )
  1265. .then(() => {
  1266. next();
  1267. })
  1268. .catch(next);
  1269. }
  1270. ],
  1271. async err => {
  1272. if (err && err !== true) {
  1273. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1274. return reject(new Error(err));
  1275. }
  1276. return resolve();
  1277. }
  1278. );
  1279. });
  1280. }
  1281. /**
  1282. * Adds a playlist to be excluded in a station
  1283. *
  1284. * @param {object} payload - object that contains the payload
  1285. * @param {object} payload.stationId - the id of the station
  1286. * @param {object} payload.playlistId - the id of the playlist
  1287. * @returns {Promise} - returns a promise (resolve, reject)
  1288. */
  1289. EXCLUDE_PLAYLIST(payload) {
  1290. return new Promise((resolve, reject) => {
  1291. async.waterfall(
  1292. [
  1293. next => {
  1294. if (!payload.stationId) next("Please specify a station id");
  1295. else if (!payload.playlistId) next("Please specify a playlist id");
  1296. else next();
  1297. },
  1298. next => {
  1299. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1300. .then(station => {
  1301. next(null, station);
  1302. })
  1303. .catch(next);
  1304. },
  1305. (station, next) => {
  1306. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1307. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1308. next("This playlist is already excluded");
  1309. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1310. next(
  1311. "This playlist is currently included, please remove it from there before excluding it"
  1312. );
  1313. else
  1314. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1315. .then(() => {
  1316. next(null);
  1317. })
  1318. .catch(next);
  1319. },
  1320. next => {
  1321. DBModule.runJob(
  1322. "GET_MODEL",
  1323. {
  1324. modelName: "station"
  1325. },
  1326. this
  1327. ).then(stationModel => {
  1328. stationModel.updateOne(
  1329. { _id: payload.stationId },
  1330. { $push: { excludedPlaylists: payload.playlistId } },
  1331. next
  1332. );
  1333. });
  1334. },
  1335. (res, next) => {
  1336. StationsModule.runJob(
  1337. "UPDATE_STATION",
  1338. {
  1339. stationId: payload.stationId
  1340. },
  1341. this
  1342. )
  1343. .then(() => {
  1344. next();
  1345. })
  1346. .catch(next);
  1347. }
  1348. ],
  1349. async err => {
  1350. if (err && err !== true) {
  1351. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1352. return reject(new Error(err));
  1353. }
  1354. return resolve();
  1355. }
  1356. );
  1357. });
  1358. }
  1359. /**
  1360. * Removes a playlist that is excluded in a station
  1361. *
  1362. * @param {object} payload - object that contains the payload
  1363. * @param {object} payload.stationId - the id of the station
  1364. * @param {object} payload.playlistId - the id of the playlist
  1365. * @returns {Promise} - returns a promise (resolve, reject)
  1366. */
  1367. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1368. return new Promise((resolve, reject) => {
  1369. console.log(112, payload);
  1370. async.waterfall(
  1371. [
  1372. next => {
  1373. if (!payload.stationId) next("Please specify a station id");
  1374. else if (!payload.playlistId) next("Please specify a playlist id");
  1375. else next();
  1376. },
  1377. next => {
  1378. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1379. .then(station => {
  1380. next(null, station);
  1381. })
  1382. .catch(next);
  1383. },
  1384. (station, next) => {
  1385. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1386. next("This playlist isn't excluded");
  1387. else next();
  1388. },
  1389. next => {
  1390. DBModule.runJob(
  1391. "GET_MODEL",
  1392. {
  1393. modelName: "station"
  1394. },
  1395. this
  1396. ).then(stationModel => {
  1397. stationModel.updateOne(
  1398. { _id: payload.stationId },
  1399. { $pull: { excludedPlaylists: payload.playlistId } },
  1400. next
  1401. );
  1402. });
  1403. },
  1404. (res, next) => {
  1405. StationsModule.runJob(
  1406. "UPDATE_STATION",
  1407. {
  1408. stationId: payload.stationId
  1409. },
  1410. this
  1411. )
  1412. .then(() => {
  1413. next();
  1414. })
  1415. .catch(next);
  1416. }
  1417. ],
  1418. async err => {
  1419. if (err && err !== true) {
  1420. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1421. return reject(new Error(err));
  1422. }
  1423. return resolve();
  1424. }
  1425. );
  1426. });
  1427. }
  1428. /**
  1429. * Gets stations that include or exclude a specific playlist
  1430. *
  1431. * @param {object} payload - object that contains the payload
  1432. * @param {string} payload.playlistId - the playlist id
  1433. * @returns {Promise} - returns promise (reject, resolve)
  1434. */
  1435. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1436. return new Promise((resolve, reject) => {
  1437. DBModule.runJob(
  1438. "GET_MODEL",
  1439. {
  1440. modelName: "station"
  1441. },
  1442. this
  1443. ).then(stationModel => {
  1444. stationModel.find(
  1445. {
  1446. $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }]
  1447. },
  1448. (err, stations) => {
  1449. if (err) reject(err);
  1450. else resolve({ stationIds: stations.map(station => station._id) });
  1451. }
  1452. );
  1453. });
  1454. });
  1455. }
  1456. /**
  1457. * Clears every queue
  1458. *
  1459. * @returns {Promise} - returns a promise (resolve, reject)
  1460. */
  1461. CLEAR_EVERY_STATION_QUEUE() {
  1462. return new Promise((resolve, reject) => {
  1463. async.waterfall(
  1464. [
  1465. next => {
  1466. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1467. if (err) next(err);
  1468. else {
  1469. StationsModule.stationModel.find({}, (err, stations) => {
  1470. if (err) next(err);
  1471. else {
  1472. async.eachLimit(
  1473. stations,
  1474. 1,
  1475. (station, next) => {
  1476. StationsModule.runJob("UPDATE_STATION", {
  1477. stationId: station._id
  1478. })
  1479. .then(() => next())
  1480. .catch(next);
  1481. CacheModule.runJob("PUB", {
  1482. channel: "station.queueUpdate",
  1483. value: station._id
  1484. })
  1485. .then()
  1486. .catch();
  1487. },
  1488. next
  1489. );
  1490. }
  1491. });
  1492. }
  1493. });
  1494. }
  1495. ],
  1496. err => {
  1497. if (err) reject(err);
  1498. else resolve();
  1499. }
  1500. );
  1501. });
  1502. }
  1503. }
  1504. export default new _StationsModule();