stations.js 44 KB

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