stations.js 42 KB

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