stations.js 43 KB

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