stations.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673
  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. });
  58. }
  59. });
  60. CacheModule.runJob("SUB", {
  61. channel: "station.newOfficialPlaylist",
  62. cb: async stationId => {
  63. CacheModule.runJob("HGET", {
  64. table: "officialPlaylists",
  65. key: stationId
  66. }).then(playlistObj => {
  67. if (playlistObj) {
  68. WSModule.runJob("EMIT_TO_ROOM", {
  69. room: `station.${stationId}`,
  70. args: ["event:newOfficialPlaylist", { data: { playlist: playlistObj.songs } }]
  71. });
  72. }
  73. });
  74. }
  75. });
  76. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  77. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  78. return new Promise((resolve, reject) => {
  79. async.waterfall(
  80. [
  81. next => {
  82. this.setStage(2);
  83. CacheModule.runJob("HGETALL", { table: "stations" })
  84. .then(stations => {
  85. next(null, stations);
  86. })
  87. .catch(next);
  88. },
  89. (stations, next) => {
  90. this.setStage(3);
  91. if (!stations) return next();
  92. const stationIds = Object.keys(stations);
  93. return async.each(
  94. stationIds,
  95. (stationId, next) => {
  96. stationModel.findOne({ _id: stationId }, (err, station) => {
  97. if (err) next(err);
  98. else if (!station) {
  99. CacheModule.runJob("HDEL", {
  100. table: "stations",
  101. key: stationId
  102. })
  103. .then(() => {
  104. next();
  105. })
  106. .catch(next);
  107. } else next();
  108. });
  109. },
  110. next
  111. );
  112. },
  113. next => {
  114. this.setStage(4);
  115. stationModel.find({}, next);
  116. },
  117. (stations, next) => {
  118. this.setStage(5);
  119. async.each(
  120. stations,
  121. (station, next2) => {
  122. async.waterfall(
  123. [
  124. next => {
  125. CacheModule.runJob("HSET", {
  126. table: "stations",
  127. key: station._id,
  128. value: stationSchema(station)
  129. })
  130. .then(station => next(null, station))
  131. .catch(next);
  132. },
  133. (station, next) => {
  134. StationsModule.runJob(
  135. "INITIALIZE_STATION",
  136. {
  137. stationId: station._id
  138. },
  139. null,
  140. -1
  141. )
  142. .then(() => {
  143. next();
  144. })
  145. .catch(next);
  146. }
  147. ],
  148. err => {
  149. next2(err);
  150. }
  151. );
  152. },
  153. next
  154. );
  155. }
  156. ],
  157. async err => {
  158. if (err) {
  159. err = await UtilsModule.runJob("GET_ERROR", {
  160. error: err
  161. });
  162. reject(new Error(err));
  163. } else {
  164. resolve();
  165. }
  166. }
  167. );
  168. });
  169. }
  170. /**
  171. * Initialises a station
  172. *
  173. * @param {object} payload - object that contains the payload
  174. * @param {string} payload.stationId - id of the station to initialise
  175. * @returns {Promise} - returns a promise (resolve, reject)
  176. */
  177. INITIALIZE_STATION(payload) {
  178. return new Promise((resolve, reject) => {
  179. async.waterfall(
  180. [
  181. next => {
  182. StationsModule.runJob(
  183. "GET_STATION",
  184. {
  185. stationId: payload.stationId
  186. },
  187. this
  188. )
  189. .then(station => {
  190. next(null, station);
  191. })
  192. .catch(next);
  193. },
  194. (station, next) => {
  195. if (!station) return next("Station not found.");
  196. return NotificationsModule.runJob(
  197. "UNSCHEDULE",
  198. {
  199. name: `stations.nextSong?id=${station._id}`
  200. },
  201. this
  202. )
  203. .then()
  204. .catch()
  205. .finally(() => {
  206. NotificationsModule.runJob("SUBSCRIBE", {
  207. name: `stations.nextSong?id=${station._id}`,
  208. cb: () =>
  209. StationsModule.runJob("SKIP_STATION", {
  210. stationId: station._id,
  211. natural: true
  212. }),
  213. unique: true,
  214. station
  215. })
  216. .then()
  217. .catch();
  218. if (station.paused) return next(true, station);
  219. return next(null, station);
  220. });
  221. },
  222. (station, next) => {
  223. if (!station.currentSong) {
  224. return StationsModule.runJob(
  225. "SKIP_STATION",
  226. {
  227. stationId: station._id,
  228. natural: false
  229. },
  230. this
  231. )
  232. .then(station => {
  233. next(true, station);
  234. })
  235. .catch(next)
  236. .finally(() => {});
  237. }
  238. let timeLeft =
  239. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  240. if (Number.isNaN(timeLeft)) timeLeft = -1;
  241. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  242. return StationsModule.runJob(
  243. "SKIP_STATION",
  244. {
  245. stationId: station._id,
  246. natural: false
  247. },
  248. this
  249. )
  250. .then(station => {
  251. next(null, station);
  252. })
  253. .catch(next);
  254. }
  255. // name, time, cb, station
  256. NotificationsModule.runJob("SCHEDULE", {
  257. name: `stations.nextSong?id=${station._id}`,
  258. time: timeLeft,
  259. station
  260. });
  261. return next(null, station);
  262. }
  263. ],
  264. async (err, station) => {
  265. if (err && err !== true) {
  266. err = await UtilsModule.runJob(
  267. "GET_ERROR",
  268. {
  269. error: err
  270. },
  271. this
  272. );
  273. reject(new Error(err));
  274. } else resolve(station);
  275. }
  276. );
  277. });
  278. }
  279. /**
  280. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  281. *
  282. * @param {object} payload - object that contains the payload
  283. * @param {string} payload.stationId - id of the station
  284. * @returns {Promise} - returns a promise (resolve, reject)
  285. */
  286. GET_STATION(payload) {
  287. return new Promise((resolve, reject) => {
  288. async.waterfall(
  289. [
  290. next => {
  291. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  292. .then(station => next(null, station))
  293. .catch(next);
  294. },
  295. (station, next) => {
  296. if (station) return next(true, station);
  297. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  298. },
  299. (station, next) => {
  300. if (station) {
  301. station = StationsModule.stationSchema(station);
  302. CacheModule.runJob("HSET", {
  303. table: "stations",
  304. key: payload.stationId,
  305. value: station
  306. })
  307. .then()
  308. .catch();
  309. next(true, station);
  310. } else next("Station not found");
  311. }
  312. ],
  313. async (err, station) => {
  314. if (err && err !== true) {
  315. err = await UtilsModule.runJob(
  316. "GET_ERROR",
  317. {
  318. error: err
  319. },
  320. this
  321. );
  322. reject(new Error(err));
  323. } else resolve(station);
  324. }
  325. );
  326. });
  327. }
  328. /**
  329. * 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.
  330. *
  331. * @param {object} payload - object that contains the payload
  332. * @param {string} payload.stationName - the unique name of the station
  333. * @returns {Promise} - returns a promise (resolve, reject)
  334. */
  335. async GET_STATION_BY_NAME(payload) {
  336. return new Promise((resolve, reject) => {
  337. async.waterfall(
  338. [
  339. next => {
  340. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  341. },
  342. (station, next) => {
  343. if (station) {
  344. station = StationsModule.stationSchema(station);
  345. CacheModule.runJob("HSET", {
  346. table: "stations",
  347. key: station._id,
  348. value: station
  349. });
  350. next(true, station);
  351. } else next("Station not found");
  352. }
  353. ],
  354. (err, station) => {
  355. if (err && err !== true) return reject(new Error(err));
  356. return resolve(station);
  357. }
  358. );
  359. });
  360. }
  361. /**
  362. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  363. *
  364. * @param {object} payload - object that contains the payload
  365. * @param {string} payload.stationId - the id of the station to update
  366. * @returns {Promise} - returns a promise (resolve, reject)
  367. */
  368. UPDATE_STATION(payload) {
  369. return new Promise((resolve, reject) => {
  370. async.waterfall(
  371. [
  372. next => {
  373. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  374. },
  375. (station, next) => {
  376. if (!station) {
  377. CacheModule.runJob("HDEL", {
  378. table: "stations",
  379. key: payload.stationId
  380. })
  381. .then()
  382. .catch();
  383. return next("Station not found");
  384. }
  385. return CacheModule.runJob(
  386. "HSET",
  387. {
  388. table: "stations",
  389. key: payload.stationId,
  390. value: station
  391. },
  392. this
  393. )
  394. .then(station => {
  395. next(null, station);
  396. })
  397. .catch(next);
  398. }
  399. ],
  400. async (err, station) => {
  401. if (err && err !== true) {
  402. err = await UtilsModule.runJob(
  403. "GET_ERROR",
  404. {
  405. error: err
  406. },
  407. this
  408. );
  409. reject(new Error(err));
  410. } else resolve(station);
  411. }
  412. );
  413. });
  414. }
  415. /**
  416. * Fills up the official station playlist queue using the songs from the official station playlist
  417. *
  418. * @param {object} payload - object that contains the payload
  419. * @param {string} payload.stationId - the id of the station
  420. * @param {string} payload.ignoreExistingQueue - ignore the existing queue songs, replacing the old queue with a completely fresh one
  421. * @returns {Promise} - returns a promise (resolve, reject)
  422. */
  423. FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST(payload) {
  424. return new Promise((resolve, reject) => {
  425. const { stationId, ignoreExistingQueue } = payload;
  426. async.waterfall(
  427. [
  428. next => {
  429. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  430. .then(response => {
  431. next(null, response.playlist);
  432. })
  433. .catch(next);
  434. },
  435. (playlist, next) => {
  436. StationsModule.runJob("GET_STATION", { stationId }, this)
  437. .then(station => {
  438. if (ignoreExistingQueue) station.queue = [];
  439. next(null, playlist, station);
  440. })
  441. .catch(next);
  442. },
  443. (playlist, station, next) => {
  444. if (station.playMode === "random") {
  445. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  446. .then(response => {
  447. next(null, response.array, station);
  448. })
  449. .catch(next);
  450. } else next(null, playlist.songs, station);
  451. },
  452. (_playlistSongs, station, next) => {
  453. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  454. if (station.playMode === "sequential") {
  455. if (station.currentSongIndex <= playlistSongs.length) {
  456. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  457. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  458. }
  459. }
  460. const songsStillNeeded = 50 - station.queue.length;
  461. const currentSongs = station.queue;
  462. const currentYoutubeIds = station.queue.map(song => song.youtubeId);
  463. const songsToAdd = [];
  464. let lastSongAdded = null;
  465. if (station.currentSong && station.currentSong.youtubeId)
  466. currentYoutubeIds.push(station.currentSong.youtubeId);
  467. playlistSongs.every(song => {
  468. if (
  469. songsToAdd.length < songsStillNeeded &&
  470. currentYoutubeIds.indexOf(song.youtubeId) === -1
  471. ) {
  472. lastSongAdded = song;
  473. songsToAdd.push(song);
  474. return true;
  475. }
  476. if (songsToAdd.length >= songsStillNeeded) return false;
  477. return true;
  478. });
  479. let { currentSongIndex } = station;
  480. if (station.playMode === "sequential" && lastSongAdded) {
  481. const indexOfLastSong = _playlistSongs
  482. .map(song => song.youtubeId)
  483. .indexOf(lastSongAdded.youtubeId);
  484. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  485. }
  486. next(null, currentSongs, songsToAdd, currentSongIndex);
  487. },
  488. (currentSongs, songsToAdd, currentSongIndex, next) => {
  489. SongsModule.runJob("GET_SONGS", {
  490. songIds: songsToAdd.map(song => song._id),
  491. properties: [
  492. "youtubeId",
  493. "title",
  494. "duration",
  495. "skipDuration",
  496. "artists",
  497. "thumbnail",
  498. "verified"
  499. ]
  500. })
  501. .then(response => {
  502. const newSongsToAdd = songsToAdd.map(song =>
  503. response.songs.find(newSong => newSong._id.toString() === song._id.toString())
  504. );
  505. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  506. })
  507. .catch(err => next(err));
  508. },
  509. (currentSongs, songsToAdd, currentSongIndex, next) => {
  510. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  511. if (!song._id) song._id = null;
  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. // eslint-disable-next-line consistent-return
  688. (station, next) => {
  689. if (!station) return next("Station not found.");
  690. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  691. return next(null, null, station); // Community station with party mode enabled and no songs in the queue
  692. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  693. // Community station with party mode enabled and songs in the queue
  694. if (station.paused) return next(null, null, station);
  695. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  696. .then(response => {
  697. StationsModule.runJob(
  698. "REMOVE_FIRST_QUEUE_SONG",
  699. { stationId: station._id },
  700. this
  701. ).then(() => {
  702. next(null, response.song, station);
  703. });
  704. })
  705. .catch(err => {
  706. if (err === "No songs available.") next(null, null, station);
  707. else next(err);
  708. });
  709. }
  710. if (station.type === "community" && !station.partyMode) {
  711. StationsModule.runJob(
  712. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  713. { stationId: station._id },
  714. this
  715. )
  716. .then(() => {
  717. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  718. .then(response => {
  719. StationsModule.runJob(
  720. "REMOVE_FIRST_QUEUE_SONG",
  721. { stationId: station._id },
  722. this
  723. ).then(() => {
  724. next(null, response.song, station);
  725. });
  726. })
  727. .catch(err => {
  728. if (err === "No songs available.") next(null, null, station);
  729. else next(err);
  730. });
  731. })
  732. .catch(next);
  733. }
  734. if (station.type === "official") {
  735. StationsModule.runJob(
  736. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  737. { stationId: station._id },
  738. this
  739. )
  740. .then(() => {
  741. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  742. .then(response => {
  743. StationsModule.runJob(
  744. "REMOVE_FIRST_QUEUE_SONG",
  745. { stationId: station._id },
  746. this
  747. )
  748. .then(() => {
  749. next(null, response.song, station);
  750. })
  751. .catch(next);
  752. })
  753. .catch(err => {
  754. if (err === "No songs available.") next(null, null, station);
  755. else next(err);
  756. });
  757. })
  758. .catch(next);
  759. }
  760. },
  761. (song, station, next) => {
  762. const $set = {};
  763. if (song === null) $set.currentSong = null;
  764. else {
  765. $set.currentSong = {
  766. _id: song._id,
  767. youtubeId: song.youtubeId,
  768. title: song.title,
  769. artists: song.artists,
  770. duration: song.duration,
  771. skipDuration: song.skipDuration,
  772. thumbnail: song.thumbnail,
  773. requestedAt: song.requestedAt,
  774. requestedBy: song.requestedBy,
  775. verified: song.verified
  776. };
  777. }
  778. $set.startedAt = Date.now();
  779. $set.timePaused = 0;
  780. if (station.paused) $set.pausedAt = Date.now();
  781. next(null, $set, song, station);
  782. },
  783. ($set, song, station, next) => {
  784. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  785. if (err) return next(err);
  786. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  787. .then(station => {
  788. CacheModule.runJob("PUB", {
  789. channel: "station.queueUpdate",
  790. value: payload.stationId
  791. })
  792. .then()
  793. .catch();
  794. next(null, station, song);
  795. })
  796. .catch(next);
  797. });
  798. },
  799. (station, song, next) => {
  800. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  801. station.currentSong.likes = song.likes;
  802. station.currentSong.dislikes = song.dislikes;
  803. station.currentSong.skipVotes = 0;
  804. }
  805. next(null, station);
  806. }
  807. ],
  808. async (err, station) => {
  809. if (err) {
  810. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  811. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  812. return reject(new Error(err));
  813. }
  814. // TODO Pub/Sub this
  815. const { currentSong } = station;
  816. WSModule.runJob("EMIT_TO_ROOM", {
  817. room: `station.${station._id}`,
  818. args: [
  819. "event:station.nextSong",
  820. {
  821. data: {
  822. currentSong,
  823. startedAt: station.startedAt,
  824. paused: station.paused,
  825. timePaused: 0,
  826. natural: payload.natural
  827. }
  828. }
  829. ]
  830. });
  831. WSModule.runJob("EMIT_TO_ROOM", {
  832. room: `manage-station.${station._id}`,
  833. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  834. });
  835. if (station.privacy === "public")
  836. WSModule.runJob("EMIT_TO_ROOM", {
  837. room: "home",
  838. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  839. });
  840. else {
  841. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  842. sockets.forEach(async socketId => {
  843. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  844. if (!socket) return;
  845. const { session } = socket;
  846. if (session.sessionId) {
  847. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  848. session => {
  849. if (session) {
  850. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  851. userModel.findOne({ _id: session.userId }, (err, user) => {
  852. if (!err && user) {
  853. if (user.role === "admin")
  854. socket.dispatch("event:station.nextSong", {
  855. data: {
  856. stationId: station._id,
  857. currentSong
  858. }
  859. });
  860. else if (
  861. station.type === "community" &&
  862. station.owner === session.userId
  863. )
  864. socket.dispatch("event:station.nextSong", {
  865. data: {
  866. stationId: station._id,
  867. currentSong
  868. }
  869. });
  870. }
  871. });
  872. });
  873. }
  874. }
  875. );
  876. }
  877. });
  878. }
  879. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  880. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  881. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  882. sockets,
  883. room: `song.${station.currentSong.youtubeId}`
  884. });
  885. if (!station.paused) {
  886. NotificationsModule.runJob("SCHEDULE", {
  887. name: `stations.nextSong?id=${station._id}`,
  888. time: station.currentSong.duration * 1000,
  889. station
  890. });
  891. }
  892. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  893. });
  894. return resolve({ station });
  895. }
  896. );
  897. });
  898. }
  899. /**
  900. * Checks if a user can view/access a station
  901. *
  902. * @param {object} payload - object that contains the payload
  903. * @param {object} payload.station - the station object of the station in question
  904. * @param {string} payload.userId - the id of the user in question
  905. * @param {boolean} payload.homeView - whether to modify output for homepage usage
  906. * @returns {Promise} - returns a promise (resolve, reject)
  907. */
  908. CAN_USER_VIEW_STATION(payload) {
  909. return new Promise((resolve, reject) => {
  910. async.waterfall(
  911. [
  912. next => {
  913. if (payload.station.privacy === "public") return next(true);
  914. if (payload.station.privacy === "unlisted" && !payload.homeView) return next(true);
  915. if (!payload.userId) return next("Not allowed");
  916. return next();
  917. },
  918. next => {
  919. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  920. userModel.findOne({ _id: payload.userId }, next);
  921. });
  922. },
  923. (user, next) => {
  924. if (!user) return next("Not allowed");
  925. if (!payload.homeView && user.role === "admin") return next(true);
  926. if (payload.station.type === "official") return next("Not allowed");
  927. if (payload.station.owner === payload.userId) return next(true);
  928. return next("Not allowed");
  929. }
  930. ],
  931. async errOrResult => {
  932. if (errOrResult !== true && errOrResult !== "Not allowed") {
  933. errOrResult = await UtilsModule.runJob(
  934. "GET_ERROR",
  935. {
  936. error: errOrResult
  937. },
  938. this
  939. );
  940. reject(new Error(errOrResult));
  941. } else {
  942. resolve(errOrResult === true);
  943. }
  944. }
  945. );
  946. });
  947. }
  948. /**
  949. * Checks if a user has favorited a station or not
  950. *
  951. * @param {object} payload - object that contains the payload
  952. * @param {object} payload.stationId - the id of the station in question
  953. * @param {string} payload.userId - the id of the user in question
  954. * @returns {Promise} - returns a promise (resolve, reject)
  955. */
  956. HAS_USER_FAVORITED_STATION(payload) {
  957. return new Promise((resolve, reject) => {
  958. async.waterfall(
  959. [
  960. next => {
  961. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  962. userModel.findOne({ _id: payload.userId }, next);
  963. });
  964. },
  965. (user, next) => {
  966. if (!user) return next("User not found.");
  967. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  968. return next(null, false);
  969. }
  970. ],
  971. async (err, isStationFavorited) => {
  972. if (err && err !== true) {
  973. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  974. return reject(new Error(err));
  975. }
  976. return resolve(isStationFavorited);
  977. }
  978. );
  979. });
  980. }
  981. /**
  982. * Returns a list of sockets in a room that can and can't know about a station
  983. *
  984. * @param {object} payload - the payload object
  985. * @param {object} payload.station - the station object
  986. * @param {string} payload.room - the websockets room to get the sockets from
  987. * @returns {Promise} - returns a promise (resolve, reject)
  988. */
  989. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  990. return new Promise((resolve, reject) => {
  991. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  992. .then(socketIds => {
  993. const sockets = [];
  994. async.eachLimit(
  995. socketIds,
  996. 1,
  997. (socketId, next) => {
  998. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  999. .then(socket => {
  1000. if (socket) sockets.push(socket);
  1001. next();
  1002. })
  1003. .catch(err => {
  1004. reject(err);
  1005. });
  1006. },
  1007. err => {
  1008. if (err) reject(err);
  1009. else {
  1010. let socketsThatCan = [];
  1011. const socketsThatCannot = [];
  1012. if (payload.station.privacy === "public") {
  1013. socketsThatCan = sockets;
  1014. resolve({ socketsThatCan, socketsThatCannot });
  1015. } else {
  1016. async.eachLimit(
  1017. sockets,
  1018. 1,
  1019. (socket, next) => {
  1020. const { session } = socket;
  1021. async.waterfall(
  1022. [
  1023. next => {
  1024. if (!session.sessionId) next("No session id");
  1025. else next();
  1026. },
  1027. next => {
  1028. CacheModule.runJob(
  1029. "HGET",
  1030. {
  1031. table: "sessions",
  1032. key: session.sessionId
  1033. },
  1034. this
  1035. )
  1036. .then(response => {
  1037. next(null, response);
  1038. })
  1039. .catch(next);
  1040. },
  1041. (session, next) => {
  1042. if (!session) next("No session");
  1043. else {
  1044. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1045. .then(userModel => {
  1046. next(null, userModel);
  1047. })
  1048. .catch(next);
  1049. }
  1050. },
  1051. (userModel, next) => {
  1052. if (!userModel) next("No user model");
  1053. else
  1054. userModel.findOne(
  1055. {
  1056. _id: session.userId
  1057. },
  1058. next
  1059. );
  1060. },
  1061. (user, next) => {
  1062. if (!user) next("No user found");
  1063. else if (user.role === "admin") {
  1064. socketsThatCan.push(socket);
  1065. next();
  1066. } else if (
  1067. payload.station.type === "community" &&
  1068. payload.station.owner === session.userId
  1069. ) {
  1070. socketsThatCan.push(socket);
  1071. next();
  1072. }
  1073. }
  1074. ],
  1075. err => {
  1076. if (err) socketsThatCannot.push(socket);
  1077. next();
  1078. }
  1079. );
  1080. },
  1081. err => {
  1082. if (err) reject(err);
  1083. else resolve({ socketsThatCan, socketsThatCannot });
  1084. }
  1085. );
  1086. }
  1087. }
  1088. }
  1089. );
  1090. })
  1091. .catch(reject);
  1092. });
  1093. }
  1094. /**
  1095. * Adds a playlist to be included in a station
  1096. *
  1097. * @param {object} payload - object that contains the payload
  1098. * @param {object} payload.stationId - the id of the station to include the playlist in
  1099. * @param {object} payload.playlistId - the id of the playlist to be included
  1100. * @returns {Promise} - returns a promise (resolve, reject)
  1101. */
  1102. INCLUDE_PLAYLIST(payload) {
  1103. return new Promise((resolve, reject) => {
  1104. async.waterfall(
  1105. [
  1106. next => {
  1107. if (!payload.stationId) next("Please specify a station id");
  1108. else if (!payload.playlistId) next("Please specify a playlist id");
  1109. else next();
  1110. },
  1111. next => {
  1112. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1113. .then(station => {
  1114. next(null, station);
  1115. })
  1116. .catch(next);
  1117. },
  1118. (station, next) => {
  1119. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1120. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1121. next("This playlist is already included");
  1122. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1123. next(
  1124. "This playlist is currently excluded, please remove it from there before including it"
  1125. );
  1126. else
  1127. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1128. .then(() => {
  1129. next(null);
  1130. })
  1131. .catch(next);
  1132. },
  1133. next => {
  1134. DBModule.runJob(
  1135. "GET_MODEL",
  1136. {
  1137. modelName: "station"
  1138. },
  1139. this
  1140. ).then(stationModel => {
  1141. stationModel.updateOne(
  1142. { _id: payload.stationId },
  1143. { $push: { includedPlaylists: payload.playlistId } },
  1144. next
  1145. );
  1146. });
  1147. },
  1148. (res, next) => {
  1149. StationsModule.runJob(
  1150. "UPDATE_STATION",
  1151. {
  1152. stationId: payload.stationId
  1153. },
  1154. this
  1155. )
  1156. .then(() => {
  1157. next();
  1158. })
  1159. .catch(next);
  1160. }
  1161. ],
  1162. async err => {
  1163. if (err && err !== true) {
  1164. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1165. return reject(new Error(err));
  1166. }
  1167. return resolve();
  1168. }
  1169. );
  1170. });
  1171. }
  1172. /**
  1173. * Removes a playlist that is included in a station
  1174. *
  1175. * @param {object} payload - object that contains the payload
  1176. * @param {object} payload.stationId - the id of the station
  1177. * @param {object} payload.playlistId - the id of the playlist
  1178. * @returns {Promise} - returns a promise (resolve, reject)
  1179. */
  1180. REMOVE_INCLUDED_PLAYLIST(payload) {
  1181. return new Promise((resolve, reject) => {
  1182. async.waterfall(
  1183. [
  1184. next => {
  1185. if (!payload.stationId) next("Please specify a station id");
  1186. else if (!payload.playlistId) next("Please specify a playlist id");
  1187. else next();
  1188. },
  1189. next => {
  1190. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1191. .then(station => {
  1192. next(null, station);
  1193. })
  1194. .catch(next);
  1195. },
  1196. (station, next) => {
  1197. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1198. next("This playlist isn't included");
  1199. else next();
  1200. },
  1201. next => {
  1202. DBModule.runJob(
  1203. "GET_MODEL",
  1204. {
  1205. modelName: "station"
  1206. },
  1207. this
  1208. ).then(stationModel => {
  1209. stationModel.updateOne(
  1210. { _id: payload.stationId },
  1211. { $pull: { includedPlaylists: payload.playlistId } },
  1212. next
  1213. );
  1214. });
  1215. },
  1216. (res, next) => {
  1217. StationsModule.runJob(
  1218. "UPDATE_STATION",
  1219. {
  1220. stationId: payload.stationId
  1221. },
  1222. this
  1223. )
  1224. .then(() => {
  1225. next();
  1226. })
  1227. .catch(next);
  1228. }
  1229. ],
  1230. async err => {
  1231. if (err && err !== true) {
  1232. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1233. return reject(new Error(err));
  1234. }
  1235. return resolve();
  1236. }
  1237. );
  1238. });
  1239. }
  1240. /**
  1241. * Adds a playlist to be excluded in a station
  1242. *
  1243. * @param {object} payload - object that contains the payload
  1244. * @param {object} payload.stationId - the id of the station
  1245. * @param {object} payload.playlistId - the id of the playlist
  1246. * @returns {Promise} - returns a promise (resolve, reject)
  1247. */
  1248. EXCLUDE_PLAYLIST(payload) {
  1249. return new Promise((resolve, reject) => {
  1250. async.waterfall(
  1251. [
  1252. next => {
  1253. if (!payload.stationId) next("Please specify a station id");
  1254. else if (!payload.playlistId) next("Please specify a playlist id");
  1255. else next();
  1256. },
  1257. next => {
  1258. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1259. .then(station => {
  1260. next(null, station);
  1261. })
  1262. .catch(next);
  1263. },
  1264. (station, next) => {
  1265. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1266. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1267. next("This playlist is already excluded");
  1268. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1269. next(
  1270. "This playlist is currently included, please remove it from there before excluding it"
  1271. );
  1272. else
  1273. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1274. .then(() => {
  1275. next(null);
  1276. })
  1277. .catch(next);
  1278. },
  1279. next => {
  1280. DBModule.runJob(
  1281. "GET_MODEL",
  1282. {
  1283. modelName: "station"
  1284. },
  1285. this
  1286. ).then(stationModel => {
  1287. stationModel.updateOne(
  1288. { _id: payload.stationId },
  1289. { $push: { excludedPlaylists: payload.playlistId } },
  1290. next
  1291. );
  1292. });
  1293. },
  1294. (res, next) => {
  1295. StationsModule.runJob(
  1296. "UPDATE_STATION",
  1297. {
  1298. stationId: payload.stationId
  1299. },
  1300. this
  1301. )
  1302. .then(() => {
  1303. next();
  1304. })
  1305. .catch(next);
  1306. }
  1307. ],
  1308. async err => {
  1309. if (err && err !== true) {
  1310. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1311. return reject(new Error(err));
  1312. }
  1313. return resolve();
  1314. }
  1315. );
  1316. });
  1317. }
  1318. /**
  1319. * Removes a playlist that is excluded in a station
  1320. *
  1321. * @param {object} payload - object that contains the payload
  1322. * @param {object} payload.stationId - the id of the station
  1323. * @param {object} payload.playlistId - the id of the playlist
  1324. * @returns {Promise} - returns a promise (resolve, reject)
  1325. */
  1326. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1327. return new Promise((resolve, reject) => {
  1328. async.waterfall(
  1329. [
  1330. next => {
  1331. if (!payload.stationId) next("Please specify a station id");
  1332. else if (!payload.playlistId) next("Please specify a playlist id");
  1333. else next();
  1334. },
  1335. next => {
  1336. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1337. .then(station => {
  1338. next(null, station);
  1339. })
  1340. .catch(next);
  1341. },
  1342. (station, next) => {
  1343. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1344. next("This playlist isn't excluded");
  1345. else next();
  1346. },
  1347. next => {
  1348. DBModule.runJob(
  1349. "GET_MODEL",
  1350. {
  1351. modelName: "station"
  1352. },
  1353. this
  1354. ).then(stationModel => {
  1355. stationModel.updateOne(
  1356. { _id: payload.stationId },
  1357. { $pull: { excludedPlaylists: payload.playlistId } },
  1358. next
  1359. );
  1360. });
  1361. },
  1362. (res, next) => {
  1363. StationsModule.runJob(
  1364. "UPDATE_STATION",
  1365. {
  1366. stationId: payload.stationId
  1367. },
  1368. this
  1369. )
  1370. .then(() => {
  1371. next();
  1372. })
  1373. .catch(next);
  1374. }
  1375. ],
  1376. async err => {
  1377. if (err && err !== true) {
  1378. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1379. return reject(new Error(err));
  1380. }
  1381. return resolve();
  1382. }
  1383. );
  1384. });
  1385. }
  1386. /**
  1387. * Removes included or excluded playlist from a station
  1388. *
  1389. * @param {object} payload - object that contains the payload
  1390. * @param {string} payload.playlistId - the playlist id
  1391. * @returns {Promise} - returns promise (reject, resolve)
  1392. */
  1393. REMOVE_INCLUDED_OR_EXCLUDED_PLAYLIST_FROM_STATIONS(payload) {
  1394. return new Promise((resolve, reject) => {
  1395. async.waterfall(
  1396. [
  1397. next => {
  1398. if (!payload.playlistId) next("Please specify a playlist id");
  1399. else next();
  1400. },
  1401. next => {
  1402. StationsModule.stationModel.updateMany(
  1403. {
  1404. $or: [
  1405. { includedPlaylists: payload.playlistId },
  1406. { excludedPlaylists: payload.playlistId }
  1407. ]
  1408. },
  1409. {
  1410. $pull: {
  1411. includedPlaylists: payload.playlistId,
  1412. excludedPlaylists: payload.playlistId
  1413. }
  1414. },
  1415. err => {
  1416. if (err) next(err);
  1417. else next();
  1418. }
  1419. );
  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. * Clears and refills a station queue
  1509. *
  1510. * @param {object} payload - object that contains the payload
  1511. * @param {string} payload.stationId - the station id
  1512. * @returns {Promise} - returns a promise (resolve, reject)
  1513. */
  1514. CLEAR_AND_REFILL_STATION_QUEUE(payload) {
  1515. return new Promise((resolve, reject) => {
  1516. async.waterfall(
  1517. [
  1518. next => {
  1519. StationsModule.runJob(
  1520. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  1521. { stationId: payload.stationId, ignoreExistingQueue: true },
  1522. this
  1523. )
  1524. .then(() => {
  1525. CacheModule.runJob("PUB", {
  1526. channel: "station.queueUpdate",
  1527. value: payload.stationId
  1528. })
  1529. .then()
  1530. .catch();
  1531. next();
  1532. })
  1533. .catch(err => {
  1534. next(err);
  1535. });
  1536. }
  1537. ],
  1538. err => {
  1539. if (err) reject(err);
  1540. else resolve();
  1541. }
  1542. );
  1543. });
  1544. }
  1545. }
  1546. export default new _StationsModule();