stations.js 43 KB

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