stations.js 43 KB

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