stations.js 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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. verified: false
  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. (song, next) => {
  555. if (!song._id) next(null, song);
  556. else
  557. SongsModule.runJob("GET_SONG", { id: song._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. thumbnail: song.thumbnail,
  568. requestedAt: song.requestedAt,
  569. likes: song.likes,
  570. dislikes: song.dislikes,
  571. verified: song.verified
  572. };
  573. return next(null, newSong);
  574. }
  575. return next(null, song);
  576. })
  577. .catch(err => {
  578. if (err.message === "Song not found.") {
  579. this.log(
  580. "ERROR",
  581. `In GET_NEXT_STATION_SONG, attempted to get song "${song._id}", but got the error "Song not found.". Ignoring it for now, but this is not normal.`
  582. );
  583. next(null, song);
  584. } else next(err);
  585. });
  586. }
  587. ],
  588. (err, song) => {
  589. if (err) console.log(33333, err, payload);
  590. if (err) reject(err);
  591. else resolve({ song });
  592. }
  593. );
  594. });
  595. }
  596. /**
  597. * Removes first station queue song
  598. *
  599. * @param {object} payload - object that contains the payload
  600. * @param {string} payload.stationId - the id of the station
  601. * @returns {Promise} - returns a promise (resolve, reject)
  602. */
  603. REMOVE_FIRST_QUEUE_SONG(payload) {
  604. return new Promise((resolve, reject) => {
  605. const { stationId } = payload;
  606. async.waterfall(
  607. [
  608. next => {
  609. StationsModule.stationModel.updateOne(
  610. { _id: stationId },
  611. { $pop: { queue: -1 } },
  612. { runValidators: true },
  613. err => {
  614. if (err) next(err);
  615. else
  616. StationsModule.runJob(
  617. "UPDATE_STATION",
  618. {
  619. stationId
  620. },
  621. this
  622. )
  623. .then(() => {
  624. next(null);
  625. })
  626. .catch(next);
  627. }
  628. );
  629. }
  630. ],
  631. err => {
  632. if (err) reject(err);
  633. else resolve();
  634. }
  635. );
  636. });
  637. }
  638. /**
  639. * Skips a station
  640. *
  641. * @param {object} payload - object that contains the payload
  642. * @param {string} payload.stationId - the id of the station to skip
  643. * @returns {Promise} - returns a promise (resolve, reject)
  644. */
  645. SKIP_STATION(payload) {
  646. return new Promise((resolve, reject) => {
  647. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  648. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  649. async.waterfall(
  650. [
  651. // Clears up any existing timers that would skip the station if the song ends
  652. next => {
  653. NotificationsModule.runJob("UNSCHEDULE", {
  654. name: `stations.nextSong?id=${payload.stationId}`
  655. })
  656. .then(() => {
  657. next();
  658. })
  659. .catch(next);
  660. },
  661. // Gets the station object
  662. next => {
  663. StationsModule.runJob(
  664. "GET_STATION",
  665. {
  666. stationId: payload.stationId
  667. },
  668. this
  669. )
  670. .then(station => {
  671. next(null, station);
  672. })
  673. .catch(() => {});
  674. },
  675. // eslint-disable-next-line consistent-return
  676. (station, next) => {
  677. if (!station) return next("Station not found.");
  678. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  679. return next(null, null, station); // Community station with party mode enabled and no songs in the queue
  680. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  681. // Community station with party mode enabled and songs in the queue
  682. if (station.paused) return next(null, null, station);
  683. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  684. .then(response => {
  685. StationsModule.runJob(
  686. "REMOVE_FIRST_QUEUE_SONG",
  687. { stationId: station._id },
  688. this
  689. ).then(() => {
  690. next(null, response.song, station);
  691. });
  692. })
  693. .catch(err => {
  694. if (err === "No songs available.") next(null, null, station);
  695. else next(err);
  696. });
  697. // return StationsModule.stationModel.updateOne(
  698. // { _id: payload.stationId },
  699. // {
  700. // $pull: {
  701. // queue: {
  702. // _id: station.queue[0]._id
  703. // }
  704. // }
  705. // },
  706. // err => {
  707. // if (err) return next(err);
  708. // return next(null, station.queue[0], -12, station);
  709. // }
  710. // );
  711. }
  712. if (station.type === "community" && !station.partyMode) {
  713. StationsModule.runJob(
  714. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  715. { stationId: station._id },
  716. this
  717. )
  718. .then(() => {
  719. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  720. .then(response => {
  721. StationsModule.runJob(
  722. "REMOVE_FIRST_QUEUE_SONG",
  723. { stationId: station._id },
  724. this
  725. ).then(() => {
  726. next(null, response.song, station);
  727. });
  728. })
  729. .catch(err => {
  730. if (err === "No songs available.") next(null, null, station);
  731. else next(err);
  732. });
  733. })
  734. .catch(next);
  735. }
  736. // if (station.type === "community" && !station.partyMode) {
  737. // return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  738. // playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  739. // if (err) return next(err);
  740. // if (!playlist) return next(null, null, -13, station);
  741. // playlist = playlist.songs;
  742. // if (playlist.length > 0) {
  743. // let currentSongIndex;
  744. // if (station.currentSongIndex < playlist.length - 1)
  745. // currentSongIndex = station.currentSongIndex + 1;
  746. // else currentSongIndex = 0;
  747. // const callback = (err, song) => {
  748. // if (err) return next(err);
  749. // if (song) return next(null, song, currentSongIndex, station);
  750. // const currentSong = {
  751. // songId: playlist[currentSongIndex].songId,
  752. // title: playlist[currentSongIndex].title,
  753. // duration: playlist[currentSongIndex].duration,
  754. // likes: -1,
  755. // dislikes: -1,
  756. // requestedAt: playlist[currentSongIndex].requestedAt
  757. // };
  758. // return next(null, currentSong, currentSongIndex, station);
  759. // };
  760. // if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  761. // return SongsModule.runJob(
  762. // "GET_SONG",
  763. // {
  764. // id: playlist[currentSongIndex]._id
  765. // },
  766. // this
  767. // )
  768. // .then(response => callback(null, response.song))
  769. // .catch(callback);
  770. // return SongsModule.runJob(
  771. // "GET_SONG_FROM_ID",
  772. // {
  773. // songId: playlist[currentSongIndex].songId
  774. // },
  775. // this
  776. // )
  777. // .then(response => callback(null, response.song))
  778. // .catch(callback);
  779. // }
  780. // return next(null, null, -14, station);
  781. // })
  782. // );
  783. // }
  784. if (station.type === "official") {
  785. StationsModule.runJob(
  786. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  787. { stationId: station._id },
  788. this
  789. )
  790. .then(() => {
  791. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  792. .then(response => {
  793. StationsModule.runJob(
  794. "REMOVE_FIRST_QUEUE_SONG",
  795. { stationId: station._id },
  796. this
  797. )
  798. .then(() => {
  799. next(null, response.song, station);
  800. })
  801. .catch(next);
  802. })
  803. .catch(err => {
  804. if (err === "No songs available.") next(null, null, station);
  805. else next(err);
  806. });
  807. })
  808. .catch(next);
  809. }
  810. },
  811. (song, station, next) => {
  812. const $set = {};
  813. if (song === null) $set.currentSong = null;
  814. else {
  815. $set.currentSong = {
  816. _id: song._id,
  817. songId: song.songId,
  818. title: song.title,
  819. artists: song.artists,
  820. duration: song.duration,
  821. likes: song.likes,
  822. dislikes: song.dislikes,
  823. skipDuration: song.skipDuration,
  824. thumbnail: song.thumbnail,
  825. requestedAt: song.requestedAt,
  826. verified: song.verified
  827. };
  828. }
  829. // if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  830. $set.startedAt = Date.now();
  831. $set.timePaused = 0;
  832. if (station.paused) $set.pausedAt = Date.now();
  833. next(null, $set, station);
  834. },
  835. ($set, station, next) => {
  836. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  837. if (err) return next(err);
  838. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  839. .then(station => {
  840. CacheModule.runJob("PUB", {
  841. channel: "station.queueUpdate",
  842. value: payload.stationId
  843. })
  844. .then()
  845. .catch();
  846. next(null, station);
  847. })
  848. .catch(next);
  849. });
  850. }
  851. ],
  852. async (err, station) => {
  853. if (err) {
  854. err = await UtilsModule.runJob(
  855. "GET_ERROR",
  856. {
  857. error: err
  858. },
  859. this
  860. );
  861. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  862. reject(new Error(err));
  863. } else {
  864. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  865. station.currentSong.skipVotes = 0;
  866. }
  867. // TODO Pub/Sub this
  868. WSModule.runJob("EMIT_TO_ROOM", {
  869. room: `station.${station._id}`,
  870. args: [
  871. "event:songs.next",
  872. {
  873. currentSong: station.currentSong,
  874. startedAt: station.startedAt,
  875. paused: station.paused,
  876. timePaused: 0
  877. }
  878. ]
  879. })
  880. .then()
  881. .catch();
  882. if (station.privacy === "public") {
  883. WSModule.runJob("EMIT_TO_ROOM", {
  884. room: "home",
  885. args: ["event:station.nextSong", station._id, station.currentSong]
  886. })
  887. .then()
  888. .catch();
  889. } else {
  890. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  891. sockets.forEach(async socketId => {
  892. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  893. const { session } = socket;
  894. if (session.sessionId) {
  895. CacheModule.runJob(
  896. "HGET",
  897. { table: "sessions", key: session.sessionId },
  898. this
  899. // eslint-disable-next-line no-loop-func
  900. ).then(session => {
  901. if (session) {
  902. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  903. userModel => {
  904. userModel.findOne(
  905. {
  906. _id: session.userId
  907. },
  908. (err, user) => {
  909. if (!err && user) {
  910. if (user.role === "admin")
  911. socket.dispatch(
  912. "event:station.nextSong",
  913. station._id,
  914. station.currentSong
  915. );
  916. else if (
  917. station.type === "community" &&
  918. station.owner === session.userId
  919. )
  920. socket.dispatch(
  921. "event:station.nextSong",
  922. station._id,
  923. station.currentSong
  924. );
  925. }
  926. }
  927. );
  928. }
  929. );
  930. }
  931. });
  932. }
  933. });
  934. }
  935. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  936. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  937. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  938. sockets,
  939. room: `song.${station.currentSong.songId}`
  940. });
  941. if (!station.paused) {
  942. NotificationsModule.runJob("SCHEDULE", {
  943. name: `stations.nextSong?id=${station._id}`,
  944. time: station.currentSong.duration * 1000,
  945. station
  946. });
  947. }
  948. } else {
  949. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  950. sockets
  951. });
  952. }
  953. });
  954. resolve({ station });
  955. }
  956. }
  957. );
  958. });
  959. }
  960. /**
  961. * Checks if a user can view/access a station
  962. *
  963. * @param {object} payload - object that contains the payload
  964. * @param {object} payload.station - the station object of the station in question
  965. * @param {string} payload.userId - the id of the user in question
  966. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  967. * @returns {Promise} - returns a promise (resolve, reject)
  968. */
  969. CAN_USER_VIEW_STATION(payload) {
  970. return new Promise((resolve, reject) => {
  971. async.waterfall(
  972. [
  973. next => {
  974. if (payload.station.privacy === "public") return next(true);
  975. if (payload.station.privacy === "unlisted")
  976. if (payload.hideUnlisted === true) return next();
  977. else return next(true);
  978. if (!payload.userId) return next("Not allowed");
  979. return next();
  980. },
  981. next => {
  982. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  983. userModel.findOne({ _id: payload.userId }, next);
  984. });
  985. },
  986. (user, next) => {
  987. if (!user) return next("Not allowed");
  988. if (user.role === "admin") return next(true);
  989. if (payload.station.type === "official") return next("Not allowed");
  990. if (payload.station.owner === payload.userId) return next(true);
  991. return next("Not allowed");
  992. }
  993. ],
  994. async errOrResult => {
  995. if (errOrResult !== true && errOrResult !== "Not allowed") {
  996. errOrResult = await UtilsModule.runJob(
  997. "GET_ERROR",
  998. {
  999. error: errOrResult
  1000. },
  1001. this
  1002. );
  1003. reject(new Error(errOrResult));
  1004. } else {
  1005. resolve(errOrResult === true);
  1006. }
  1007. }
  1008. );
  1009. });
  1010. }
  1011. /**
  1012. * Checks if a user has favorited a station or not
  1013. *
  1014. * @param {object} payload - object that contains the payload
  1015. * @param {object} payload.stationId - the id of the station in question
  1016. * @param {string} payload.userId - the id of the user in question
  1017. * @returns {Promise} - returns a promise (resolve, reject)
  1018. */
  1019. HAS_USER_FAVORITED_STATION(payload) {
  1020. return new Promise((resolve, reject) => {
  1021. async.waterfall(
  1022. [
  1023. next => {
  1024. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1025. userModel.findOne({ _id: payload.userId }, next);
  1026. });
  1027. },
  1028. (user, next) => {
  1029. if (!user) return next("User not found.");
  1030. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1031. return next(null, false);
  1032. }
  1033. ],
  1034. async (err, isStationFavorited) => {
  1035. if (err && err !== true) {
  1036. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1037. return reject(new Error(err));
  1038. }
  1039. return resolve(isStationFavorited);
  1040. }
  1041. );
  1042. });
  1043. }
  1044. /**
  1045. * Returns a list of sockets in a room that can and can't know about a station
  1046. *
  1047. * @param {object} payload - the payload object
  1048. * @param {object} payload.station - the station object
  1049. * @param {string} payload.room - the websockets room to get the sockets from
  1050. * @returns {Promise} - returns a promise (resolve, reject)
  1051. */
  1052. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1053. return new Promise((resolve, reject) => {
  1054. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1055. .then(socketsObject => {
  1056. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1057. let socketsThatCan = [];
  1058. const socketsThatCannot = [];
  1059. if (payload.station.privacy === "public") {
  1060. socketsThatCan = sockets;
  1061. resolve({ socketsThatCan, socketsThatCannot });
  1062. } else {
  1063. async.eachLimit(
  1064. sockets,
  1065. 1,
  1066. (socket, next) => {
  1067. const { session } = socket;
  1068. async.waterfall(
  1069. [
  1070. next => {
  1071. if (!session.sessionId) next("No session id");
  1072. else next();
  1073. },
  1074. next => {
  1075. CacheModule.runJob(
  1076. "HGET",
  1077. {
  1078. table: "sessions",
  1079. key: session.sessionId
  1080. },
  1081. this
  1082. )
  1083. .then(response => {
  1084. next(null, response);
  1085. })
  1086. .catch(next);
  1087. },
  1088. (session, next) => {
  1089. if (!session) next("No session");
  1090. else {
  1091. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1092. .then(userModel => {
  1093. next(null, userModel);
  1094. })
  1095. .catch(next);
  1096. }
  1097. },
  1098. (userModel, next) => {
  1099. if (!userModel) next("No user model");
  1100. else
  1101. userModel.findOne(
  1102. {
  1103. _id: session.userId
  1104. },
  1105. next
  1106. );
  1107. },
  1108. (user, next) => {
  1109. if (!user) next("No user found");
  1110. else if (user.role === "admin") {
  1111. socketsThatCan.push(socket);
  1112. next();
  1113. } else if (
  1114. payload.station.type === "community" &&
  1115. payload.station.owner === session.userId
  1116. ) {
  1117. socketsThatCan.push(socket);
  1118. next();
  1119. }
  1120. }
  1121. ],
  1122. err => {
  1123. if (err) socketsThatCannot.push(socket);
  1124. next();
  1125. }
  1126. );
  1127. },
  1128. err => {
  1129. if (err) reject(err);
  1130. else resolve({ socketsThatCan, socketsThatCannot });
  1131. }
  1132. );
  1133. }
  1134. })
  1135. .catch(reject);
  1136. });
  1137. }
  1138. /**
  1139. * Adds a playlist to be included in a station
  1140. *
  1141. * @param {object} payload - object that contains the payload
  1142. * @param {object} payload.stationId - the id of the station to include the playlist in
  1143. * @param {object} payload.playlistId - the id of the playlist to be included
  1144. * @returns {Promise} - returns a promise (resolve, reject)
  1145. */
  1146. INCLUDE_PLAYLIST(payload) {
  1147. return new Promise((resolve, reject) => {
  1148. async.waterfall(
  1149. [
  1150. next => {
  1151. if (!payload.stationId) next("Please specify a station id");
  1152. else if (!payload.playlistId) next("Please specify a playlist id");
  1153. else next();
  1154. },
  1155. next => {
  1156. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1157. .then(station => {
  1158. next(null, station);
  1159. })
  1160. .catch(next);
  1161. },
  1162. (station, next) => {
  1163. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1164. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1165. next("This playlist is already included");
  1166. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1167. next(
  1168. "This playlist is currently excluded, please remove it from there before including it"
  1169. );
  1170. else
  1171. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1172. .then(() => {
  1173. next(null);
  1174. })
  1175. .catch(next);
  1176. },
  1177. next => {
  1178. DBModule.runJob(
  1179. "GET_MODEL",
  1180. {
  1181. modelName: "station"
  1182. },
  1183. this
  1184. ).then(stationModel => {
  1185. stationModel.updateOne(
  1186. { _id: payload.stationId },
  1187. { $push: { includedPlaylists: payload.playlistId } },
  1188. next
  1189. );
  1190. });
  1191. },
  1192. (res, next) => {
  1193. StationsModule.runJob(
  1194. "UPDATE_STATION",
  1195. {
  1196. stationId: payload.stationId
  1197. },
  1198. this
  1199. )
  1200. .then(() => {
  1201. next();
  1202. })
  1203. .catch(next);
  1204. }
  1205. ],
  1206. async err => {
  1207. if (err && err !== true) {
  1208. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1209. return reject(new Error(err));
  1210. }
  1211. return resolve();
  1212. }
  1213. );
  1214. });
  1215. }
  1216. /**
  1217. * Removes a playlist that is included in a station
  1218. *
  1219. * @param {object} payload - object that contains the payload
  1220. * @param {object} payload.stationId - the id of the station
  1221. * @param {object} payload.playlistId - the id of the playlist
  1222. * @returns {Promise} - returns a promise (resolve, reject)
  1223. */
  1224. REMOVE_INCLUDED_PLAYLIST(payload) {
  1225. return new Promise((resolve, reject) => {
  1226. async.waterfall(
  1227. [
  1228. next => {
  1229. if (!payload.stationId) next("Please specify a station id");
  1230. else if (!payload.playlistId) next("Please specify a playlist id");
  1231. else next();
  1232. },
  1233. next => {
  1234. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1235. .then(station => {
  1236. next(null, station);
  1237. })
  1238. .catch(next);
  1239. },
  1240. (station, next) => {
  1241. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1242. next("This playlist isn't included");
  1243. else next();
  1244. },
  1245. next => {
  1246. DBModule.runJob(
  1247. "GET_MODEL",
  1248. {
  1249. modelName: "station"
  1250. },
  1251. this
  1252. ).then(stationModel => {
  1253. stationModel.updateOne(
  1254. { _id: payload.stationId },
  1255. { $pull: { includedPlaylists: payload.playlistId } },
  1256. next
  1257. );
  1258. });
  1259. },
  1260. (res, next) => {
  1261. StationsModule.runJob(
  1262. "UPDATE_STATION",
  1263. {
  1264. stationId: payload.stationId
  1265. },
  1266. this
  1267. )
  1268. .then(() => {
  1269. next();
  1270. })
  1271. .catch(next);
  1272. }
  1273. ],
  1274. async err => {
  1275. if (err && err !== true) {
  1276. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1277. return reject(new Error(err));
  1278. }
  1279. return resolve();
  1280. }
  1281. );
  1282. });
  1283. }
  1284. /**
  1285. * Adds a playlist to be excluded in a station
  1286. *
  1287. * @param {object} payload - object that contains the payload
  1288. * @param {object} payload.stationId - the id of the station
  1289. * @param {object} payload.playlistId - the id of the playlist
  1290. * @returns {Promise} - returns a promise (resolve, reject)
  1291. */
  1292. EXCLUDE_PLAYLIST(payload) {
  1293. return new Promise((resolve, reject) => {
  1294. async.waterfall(
  1295. [
  1296. next => {
  1297. if (!payload.stationId) next("Please specify a station id");
  1298. else if (!payload.playlistId) next("Please specify a playlist id");
  1299. else next();
  1300. },
  1301. next => {
  1302. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1303. .then(station => {
  1304. next(null, station);
  1305. })
  1306. .catch(next);
  1307. },
  1308. (station, next) => {
  1309. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1310. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1311. next("This playlist is already excluded");
  1312. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1313. next(
  1314. "This playlist is currently included, please remove it from there before excluding it"
  1315. );
  1316. else
  1317. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1318. .then(() => {
  1319. next(null);
  1320. })
  1321. .catch(next);
  1322. },
  1323. next => {
  1324. DBModule.runJob(
  1325. "GET_MODEL",
  1326. {
  1327. modelName: "station"
  1328. },
  1329. this
  1330. ).then(stationModel => {
  1331. stationModel.updateOne(
  1332. { _id: payload.stationId },
  1333. { $push: { excludedPlaylists: payload.playlistId } },
  1334. next
  1335. );
  1336. });
  1337. },
  1338. (res, next) => {
  1339. StationsModule.runJob(
  1340. "UPDATE_STATION",
  1341. {
  1342. stationId: payload.stationId
  1343. },
  1344. this
  1345. )
  1346. .then(() => {
  1347. next();
  1348. })
  1349. .catch(next);
  1350. }
  1351. ],
  1352. async err => {
  1353. if (err && err !== true) {
  1354. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1355. return reject(new Error(err));
  1356. }
  1357. return resolve();
  1358. }
  1359. );
  1360. });
  1361. }
  1362. /**
  1363. * Removes a playlist that is excluded in a station
  1364. *
  1365. * @param {object} payload - object that contains the payload
  1366. * @param {object} payload.stationId - the id of the station
  1367. * @param {object} payload.playlistId - the id of the playlist
  1368. * @returns {Promise} - returns a promise (resolve, reject)
  1369. */
  1370. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1371. return new Promise((resolve, reject) => {
  1372. console.log(112, payload);
  1373. async.waterfall(
  1374. [
  1375. next => {
  1376. if (!payload.stationId) next("Please specify a station id");
  1377. else if (!payload.playlistId) next("Please specify a playlist id");
  1378. else next();
  1379. },
  1380. next => {
  1381. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1382. .then(station => {
  1383. next(null, station);
  1384. })
  1385. .catch(next);
  1386. },
  1387. (station, next) => {
  1388. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1389. next("This playlist isn't excluded");
  1390. else next();
  1391. },
  1392. next => {
  1393. DBModule.runJob(
  1394. "GET_MODEL",
  1395. {
  1396. modelName: "station"
  1397. },
  1398. this
  1399. ).then(stationModel => {
  1400. stationModel.updateOne(
  1401. { _id: payload.stationId },
  1402. { $pull: { excludedPlaylists: payload.playlistId } },
  1403. next
  1404. );
  1405. });
  1406. },
  1407. (res, next) => {
  1408. StationsModule.runJob(
  1409. "UPDATE_STATION",
  1410. {
  1411. stationId: payload.stationId
  1412. },
  1413. this
  1414. )
  1415. .then(() => {
  1416. next();
  1417. })
  1418. .catch(next);
  1419. }
  1420. ],
  1421. async err => {
  1422. if (err && err !== true) {
  1423. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1424. return reject(new Error(err));
  1425. }
  1426. return resolve();
  1427. }
  1428. );
  1429. });
  1430. }
  1431. /**
  1432. * Gets stations that include or exclude a specific playlist
  1433. *
  1434. * @param {object} payload - object that contains the payload
  1435. * @param {string} payload.playlistId - the playlist id
  1436. * @returns {Promise} - returns promise (reject, resolve)
  1437. */
  1438. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1439. return new Promise((resolve, reject) => {
  1440. DBModule.runJob(
  1441. "GET_MODEL",
  1442. {
  1443. modelName: "station"
  1444. },
  1445. this
  1446. ).then(stationModel => {
  1447. stationModel.find(
  1448. {
  1449. $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }]
  1450. },
  1451. (err, stations) => {
  1452. if (err) reject(err);
  1453. else resolve({ stationIds: stations.map(station => station._id) });
  1454. }
  1455. );
  1456. });
  1457. });
  1458. }
  1459. /**
  1460. * Clears every queue
  1461. *
  1462. * @returns {Promise} - returns a promise (resolve, reject)
  1463. */
  1464. CLEAR_EVERY_STATION_QUEUE() {
  1465. return new Promise((resolve, reject) => {
  1466. async.waterfall(
  1467. [
  1468. next => {
  1469. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1470. if (err) next(err);
  1471. else {
  1472. StationsModule.stationModel.find({}, (err, stations) => {
  1473. if (err) next(err);
  1474. else {
  1475. async.eachLimit(
  1476. stations,
  1477. 1,
  1478. (station, next) => {
  1479. StationsModule.runJob("UPDATE_STATION", {
  1480. stationId: station._id
  1481. })
  1482. .then(() => next())
  1483. .catch(next);
  1484. CacheModule.runJob("PUB", {
  1485. channel: "station.queueUpdate",
  1486. value: station._id
  1487. })
  1488. .then()
  1489. .catch();
  1490. },
  1491. next
  1492. );
  1493. }
  1494. });
  1495. }
  1496. });
  1497. }
  1498. ],
  1499. err => {
  1500. if (err) reject(err);
  1501. else resolve();
  1502. }
  1503. );
  1504. });
  1505. }
  1506. }
  1507. export default new _StationsModule();