stations.js 44 KB

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