stations.js 42 KB

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