stations.js 44 KB

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