stations.js 42 KB

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