stations.js 43 KB

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