stations.js 43 KB

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