stations.js 42 KB

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