stations.js 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  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. if (!socket) return;
  920. const { session } = socket;
  921. if (session.sessionId) {
  922. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  923. session => {
  924. if (session) {
  925. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  926. userModel.findOne({ _id: session.userId }, (err, user) => {
  927. if (!err && user) {
  928. if (user.role === "admin")
  929. socket.dispatch("event:station.nextSong", {
  930. data: {
  931. stationId: station._id,
  932. currentSong
  933. }
  934. });
  935. else if (
  936. station.type === "community" &&
  937. station.owner === session.userId
  938. )
  939. socket.dispatch("event:station.nextSong", {
  940. data: {
  941. stationId: station._id,
  942. currentSong
  943. }
  944. });
  945. }
  946. });
  947. });
  948. }
  949. }
  950. );
  951. }
  952. });
  953. }
  954. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  955. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  956. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  957. sockets,
  958. room: `song.${station.currentSong.youtubeId}`
  959. });
  960. if (!station.paused) {
  961. NotificationsModule.runJob("SCHEDULE", {
  962. name: `stations.nextSong?id=${station._id}`,
  963. time: station.currentSong.duration * 1000,
  964. station
  965. });
  966. }
  967. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  968. });
  969. return resolve({ station });
  970. }
  971. );
  972. });
  973. }
  974. /**
  975. * Checks if a user can view/access a station
  976. *
  977. * @param {object} payload - object that contains the payload
  978. * @param {object} payload.station - the station object of the station in question
  979. * @param {string} payload.userId - the id of the user in question
  980. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  981. * @returns {Promise} - returns a promise (resolve, reject)
  982. */
  983. CAN_USER_VIEW_STATION(payload) {
  984. return new Promise((resolve, reject) => {
  985. async.waterfall(
  986. [
  987. next => {
  988. if (payload.station.privacy === "public") return next(true);
  989. if (payload.station.privacy === "unlisted")
  990. if (payload.hideUnlisted === true) return next();
  991. else return next(true);
  992. if (!payload.userId) return next("Not allowed");
  993. return next();
  994. },
  995. next => {
  996. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  997. userModel.findOne({ _id: payload.userId }, next);
  998. });
  999. },
  1000. (user, next) => {
  1001. if (!user) return next("Not allowed");
  1002. if (user.role === "admin") return next(true);
  1003. if (payload.station.type === "official") return next("Not allowed");
  1004. if (payload.station.owner === payload.userId) return next(true);
  1005. return next("Not allowed");
  1006. }
  1007. ],
  1008. async errOrResult => {
  1009. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1010. errOrResult = await UtilsModule.runJob(
  1011. "GET_ERROR",
  1012. {
  1013. error: errOrResult
  1014. },
  1015. this
  1016. );
  1017. reject(new Error(errOrResult));
  1018. } else {
  1019. resolve(errOrResult === true);
  1020. }
  1021. }
  1022. );
  1023. });
  1024. }
  1025. /**
  1026. * Checks if a user has favorited a station or not
  1027. *
  1028. * @param {object} payload - object that contains the payload
  1029. * @param {object} payload.stationId - the id of the station in question
  1030. * @param {string} payload.userId - the id of the user in question
  1031. * @returns {Promise} - returns a promise (resolve, reject)
  1032. */
  1033. HAS_USER_FAVORITED_STATION(payload) {
  1034. return new Promise((resolve, reject) => {
  1035. async.waterfall(
  1036. [
  1037. next => {
  1038. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1039. userModel.findOne({ _id: payload.userId }, next);
  1040. });
  1041. },
  1042. (user, next) => {
  1043. if (!user) return next("User not found.");
  1044. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1045. return next(null, false);
  1046. }
  1047. ],
  1048. async (err, isStationFavorited) => {
  1049. if (err && err !== true) {
  1050. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1051. return reject(new Error(err));
  1052. }
  1053. return resolve(isStationFavorited);
  1054. }
  1055. );
  1056. });
  1057. }
  1058. /**
  1059. * Returns a list of sockets in a room that can and can't know about a station
  1060. *
  1061. * @param {object} payload - the payload object
  1062. * @param {object} payload.station - the station object
  1063. * @param {string} payload.room - the websockets room to get the sockets from
  1064. * @returns {Promise} - returns a promise (resolve, reject)
  1065. */
  1066. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1067. return new Promise((resolve, reject) => {
  1068. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1069. .then(socketIds => {
  1070. const sockets = [];
  1071. async.eachLimit(
  1072. socketIds,
  1073. 1,
  1074. (socketId, next) => {
  1075. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1076. .then(socket => {
  1077. if (socket) sockets.push(socket);
  1078. next();
  1079. })
  1080. .catch(err => {
  1081. reject(err);
  1082. });
  1083. },
  1084. err => {
  1085. if (err) reject(err);
  1086. else {
  1087. let socketsThatCan = [];
  1088. const socketsThatCannot = [];
  1089. if (payload.station.privacy === "public") {
  1090. socketsThatCan = sockets;
  1091. resolve({ socketsThatCan, socketsThatCannot });
  1092. } else {
  1093. async.eachLimit(
  1094. sockets,
  1095. 1,
  1096. (socket, next) => {
  1097. const { session } = socket;
  1098. async.waterfall(
  1099. [
  1100. next => {
  1101. if (!session.sessionId) next("No session id");
  1102. else next();
  1103. },
  1104. next => {
  1105. CacheModule.runJob(
  1106. "HGET",
  1107. {
  1108. table: "sessions",
  1109. key: session.sessionId
  1110. },
  1111. this
  1112. )
  1113. .then(response => {
  1114. next(null, response);
  1115. })
  1116. .catch(next);
  1117. },
  1118. (session, next) => {
  1119. if (!session) next("No session");
  1120. else {
  1121. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1122. .then(userModel => {
  1123. next(null, userModel);
  1124. })
  1125. .catch(next);
  1126. }
  1127. },
  1128. (userModel, next) => {
  1129. if (!userModel) next("No user model");
  1130. else
  1131. userModel.findOne(
  1132. {
  1133. _id: session.userId
  1134. },
  1135. next
  1136. );
  1137. },
  1138. (user, next) => {
  1139. if (!user) next("No user found");
  1140. else if (user.role === "admin") {
  1141. socketsThatCan.push(socket);
  1142. next();
  1143. } else if (
  1144. payload.station.type === "community" &&
  1145. payload.station.owner === session.userId
  1146. ) {
  1147. socketsThatCan.push(socket);
  1148. next();
  1149. }
  1150. }
  1151. ],
  1152. err => {
  1153. if (err) socketsThatCannot.push(socket);
  1154. next();
  1155. }
  1156. );
  1157. },
  1158. err => {
  1159. if (err) reject(err);
  1160. else resolve({ socketsThatCan, socketsThatCannot });
  1161. }
  1162. );
  1163. }
  1164. }
  1165. }
  1166. );
  1167. })
  1168. .catch(reject);
  1169. });
  1170. }
  1171. /**
  1172. * Adds a playlist to be included in a station
  1173. *
  1174. * @param {object} payload - object that contains the payload
  1175. * @param {object} payload.stationId - the id of the station to include the playlist in
  1176. * @param {object} payload.playlistId - the id of the playlist to be included
  1177. * @returns {Promise} - returns a promise (resolve, reject)
  1178. */
  1179. INCLUDE_PLAYLIST(payload) {
  1180. return new Promise((resolve, reject) => {
  1181. async.waterfall(
  1182. [
  1183. next => {
  1184. if (!payload.stationId) next("Please specify a station id");
  1185. else if (!payload.playlistId) next("Please specify a playlist id");
  1186. else next();
  1187. },
  1188. next => {
  1189. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1190. .then(station => {
  1191. next(null, station);
  1192. })
  1193. .catch(next);
  1194. },
  1195. (station, next) => {
  1196. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1197. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1198. next("This playlist is already included");
  1199. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1200. next(
  1201. "This playlist is currently excluded, please remove it from there before including it"
  1202. );
  1203. else
  1204. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1205. .then(() => {
  1206. next(null);
  1207. })
  1208. .catch(next);
  1209. },
  1210. next => {
  1211. DBModule.runJob(
  1212. "GET_MODEL",
  1213. {
  1214. modelName: "station"
  1215. },
  1216. this
  1217. ).then(stationModel => {
  1218. stationModel.updateOne(
  1219. { _id: payload.stationId },
  1220. { $push: { includedPlaylists: payload.playlistId } },
  1221. next
  1222. );
  1223. });
  1224. },
  1225. (res, next) => {
  1226. StationsModule.runJob(
  1227. "UPDATE_STATION",
  1228. {
  1229. stationId: payload.stationId
  1230. },
  1231. this
  1232. )
  1233. .then(() => {
  1234. next();
  1235. })
  1236. .catch(next);
  1237. }
  1238. ],
  1239. async err => {
  1240. if (err && err !== true) {
  1241. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1242. return reject(new Error(err));
  1243. }
  1244. return resolve();
  1245. }
  1246. );
  1247. });
  1248. }
  1249. /**
  1250. * Removes a playlist that is included in a station
  1251. *
  1252. * @param {object} payload - object that contains the payload
  1253. * @param {object} payload.stationId - the id of the station
  1254. * @param {object} payload.playlistId - the id of the playlist
  1255. * @returns {Promise} - returns a promise (resolve, reject)
  1256. */
  1257. REMOVE_INCLUDED_PLAYLIST(payload) {
  1258. return new Promise((resolve, reject) => {
  1259. async.waterfall(
  1260. [
  1261. next => {
  1262. if (!payload.stationId) next("Please specify a station id");
  1263. else if (!payload.playlistId) next("Please specify a playlist id");
  1264. else next();
  1265. },
  1266. next => {
  1267. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1268. .then(station => {
  1269. next(null, station);
  1270. })
  1271. .catch(next);
  1272. },
  1273. (station, next) => {
  1274. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1275. next("This playlist isn't included");
  1276. else next();
  1277. },
  1278. next => {
  1279. DBModule.runJob(
  1280. "GET_MODEL",
  1281. {
  1282. modelName: "station"
  1283. },
  1284. this
  1285. ).then(stationModel => {
  1286. stationModel.updateOne(
  1287. { _id: payload.stationId },
  1288. { $pull: { includedPlaylists: payload.playlistId } },
  1289. next
  1290. );
  1291. });
  1292. },
  1293. (res, next) => {
  1294. StationsModule.runJob(
  1295. "UPDATE_STATION",
  1296. {
  1297. stationId: payload.stationId
  1298. },
  1299. this
  1300. )
  1301. .then(() => {
  1302. next();
  1303. })
  1304. .catch(next);
  1305. }
  1306. ],
  1307. async err => {
  1308. if (err && err !== true) {
  1309. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1310. return reject(new Error(err));
  1311. }
  1312. return resolve();
  1313. }
  1314. );
  1315. });
  1316. }
  1317. /**
  1318. * Adds a playlist to be excluded in a station
  1319. *
  1320. * @param {object} payload - object that contains the payload
  1321. * @param {object} payload.stationId - the id of the station
  1322. * @param {object} payload.playlistId - the id of the playlist
  1323. * @returns {Promise} - returns a promise (resolve, reject)
  1324. */
  1325. EXCLUDE_PLAYLIST(payload) {
  1326. return new Promise((resolve, reject) => {
  1327. async.waterfall(
  1328. [
  1329. next => {
  1330. if (!payload.stationId) next("Please specify a station id");
  1331. else if (!payload.playlistId) next("Please specify a playlist id");
  1332. else next();
  1333. },
  1334. next => {
  1335. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1336. .then(station => {
  1337. next(null, station);
  1338. })
  1339. .catch(next);
  1340. },
  1341. (station, next) => {
  1342. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1343. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1344. next("This playlist is already excluded");
  1345. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1346. next(
  1347. "This playlist is currently included, please remove it from there before excluding it"
  1348. );
  1349. else
  1350. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1351. .then(() => {
  1352. next(null);
  1353. })
  1354. .catch(next);
  1355. },
  1356. next => {
  1357. DBModule.runJob(
  1358. "GET_MODEL",
  1359. {
  1360. modelName: "station"
  1361. },
  1362. this
  1363. ).then(stationModel => {
  1364. stationModel.updateOne(
  1365. { _id: payload.stationId },
  1366. { $push: { excludedPlaylists: payload.playlistId } },
  1367. next
  1368. );
  1369. });
  1370. },
  1371. (res, next) => {
  1372. StationsModule.runJob(
  1373. "UPDATE_STATION",
  1374. {
  1375. stationId: payload.stationId
  1376. },
  1377. this
  1378. )
  1379. .then(() => {
  1380. next();
  1381. })
  1382. .catch(next);
  1383. }
  1384. ],
  1385. async err => {
  1386. if (err && err !== true) {
  1387. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1388. return reject(new Error(err));
  1389. }
  1390. return resolve();
  1391. }
  1392. );
  1393. });
  1394. }
  1395. /**
  1396. * Removes a playlist that is excluded in a station
  1397. *
  1398. * @param {object} payload - object that contains the payload
  1399. * @param {object} payload.stationId - the id of the station
  1400. * @param {object} payload.playlistId - the id of the playlist
  1401. * @returns {Promise} - returns a promise (resolve, reject)
  1402. */
  1403. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1404. return new Promise((resolve, reject) => {
  1405. console.log(112, payload);
  1406. async.waterfall(
  1407. [
  1408. next => {
  1409. if (!payload.stationId) next("Please specify a station id");
  1410. else if (!payload.playlistId) next("Please specify a playlist id");
  1411. else next();
  1412. },
  1413. next => {
  1414. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1415. .then(station => {
  1416. next(null, station);
  1417. })
  1418. .catch(next);
  1419. },
  1420. (station, next) => {
  1421. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1422. next("This playlist isn't excluded");
  1423. else next();
  1424. },
  1425. next => {
  1426. DBModule.runJob(
  1427. "GET_MODEL",
  1428. {
  1429. modelName: "station"
  1430. },
  1431. this
  1432. ).then(stationModel => {
  1433. stationModel.updateOne(
  1434. { _id: payload.stationId },
  1435. { $pull: { excludedPlaylists: payload.playlistId } },
  1436. next
  1437. );
  1438. });
  1439. },
  1440. (res, next) => {
  1441. StationsModule.runJob(
  1442. "UPDATE_STATION",
  1443. {
  1444. stationId: payload.stationId
  1445. },
  1446. this
  1447. )
  1448. .then(() => {
  1449. next();
  1450. })
  1451. .catch(next);
  1452. }
  1453. ],
  1454. async err => {
  1455. if (err && err !== true) {
  1456. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1457. return reject(new Error(err));
  1458. }
  1459. return resolve();
  1460. }
  1461. );
  1462. });
  1463. }
  1464. /**
  1465. * Gets stations that include or exclude a specific playlist
  1466. *
  1467. * @param {object} payload - object that contains the payload
  1468. * @param {string} payload.playlistId - the playlist id
  1469. * @returns {Promise} - returns promise (reject, resolve)
  1470. */
  1471. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1472. return new Promise((resolve, reject) => {
  1473. DBModule.runJob(
  1474. "GET_MODEL",
  1475. {
  1476. modelName: "station"
  1477. },
  1478. this
  1479. ).then(stationModel => {
  1480. stationModel.find(
  1481. {
  1482. $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }]
  1483. },
  1484. (err, stations) => {
  1485. if (err) reject(err);
  1486. else resolve({ stationIds: stations.map(station => station._id) });
  1487. }
  1488. );
  1489. });
  1490. });
  1491. }
  1492. /**
  1493. * Clears every queue
  1494. *
  1495. * @returns {Promise} - returns a promise (resolve, reject)
  1496. */
  1497. CLEAR_EVERY_STATION_QUEUE() {
  1498. return new Promise((resolve, reject) => {
  1499. async.waterfall(
  1500. [
  1501. next => {
  1502. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1503. if (err) next(err);
  1504. else {
  1505. StationsModule.stationModel.find({}, (err, stations) => {
  1506. if (err) next(err);
  1507. else {
  1508. async.eachLimit(
  1509. stations,
  1510. 1,
  1511. (station, next) => {
  1512. StationsModule.runJob("UPDATE_STATION", {
  1513. stationId: station._id
  1514. })
  1515. .then(() => next())
  1516. .catch(next);
  1517. CacheModule.runJob("PUB", {
  1518. channel: "station.queueUpdate",
  1519. value: station._id
  1520. })
  1521. .then()
  1522. .catch();
  1523. },
  1524. next
  1525. );
  1526. }
  1527. });
  1528. }
  1529. });
  1530. }
  1531. ],
  1532. err => {
  1533. if (err) reject(err);
  1534. else resolve();
  1535. }
  1536. );
  1537. });
  1538. }
  1539. /**
  1540. * Clears and refills a station queue
  1541. *
  1542. * @param {object} payload - object that contains the payload
  1543. * @param {string} payload.stationId - the station id
  1544. * @returns {Promise} - returns a promise (resolve, reject)
  1545. */
  1546. CLEAR_AND_REFILL_STATION_QUEUE(payload) {
  1547. return new Promise((resolve, reject) => {
  1548. async.waterfall(
  1549. [
  1550. next => {
  1551. StationsModule.runJob(
  1552. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  1553. { stationId: payload.stationId, ignoreExistingQueue: true },
  1554. this
  1555. )
  1556. .then(() => {
  1557. CacheModule.runJob("PUB", {
  1558. channel: "station.queueUpdate",
  1559. value: payload.stationId
  1560. })
  1561. .then()
  1562. .catch();
  1563. next();
  1564. })
  1565. .catch(err => {
  1566. next(err);
  1567. });
  1568. }
  1569. ],
  1570. err => {
  1571. if (err) reject(err);
  1572. else resolve();
  1573. }
  1574. );
  1575. });
  1576. }
  1577. }
  1578. export default new _StationsModule();