stations.js 42 KB

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