stations.js 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694
  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. // youtubeId: "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", { data: { playlist: 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. natural: true
  224. }),
  225. unique: true,
  226. station
  227. })
  228. .then()
  229. .catch();
  230. if (station.paused) return next(true, station);
  231. return next(null, station);
  232. });
  233. },
  234. (station, next) => {
  235. if (!station.currentSong) {
  236. return StationsModule.runJob(
  237. "SKIP_STATION",
  238. {
  239. stationId: station._id,
  240. natural: false
  241. },
  242. this
  243. )
  244. .then(station => {
  245. next(true, station);
  246. })
  247. .catch(next)
  248. .finally(() => {});
  249. }
  250. let timeLeft =
  251. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  252. if (Number.isNaN(timeLeft)) timeLeft = -1;
  253. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  254. return StationsModule.runJob(
  255. "SKIP_STATION",
  256. {
  257. stationId: station._id,
  258. natural: false
  259. },
  260. this
  261. )
  262. .then(station => {
  263. next(null, station);
  264. })
  265. .catch(next);
  266. }
  267. // name, time, cb, station
  268. NotificationsModule.runJob("SCHEDULE", {
  269. name: `stations.nextSong?id=${station._id}`,
  270. time: timeLeft,
  271. station
  272. });
  273. return next(null, station);
  274. }
  275. ],
  276. async (err, station) => {
  277. if (err && err !== true) {
  278. err = await UtilsModule.runJob(
  279. "GET_ERROR",
  280. {
  281. error: err
  282. },
  283. this
  284. );
  285. reject(new Error(err));
  286. } else resolve(station);
  287. }
  288. );
  289. });
  290. }
  291. /**
  292. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  293. *
  294. * @param {object} payload - object that contains the payload
  295. * @param {string} payload.stationId - id of the station
  296. * @returns {Promise} - returns a promise (resolve, reject)
  297. */
  298. GET_STATION(payload) {
  299. return new Promise((resolve, reject) => {
  300. async.waterfall(
  301. [
  302. next => {
  303. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  304. .then(station => next(null, station))
  305. .catch(next);
  306. },
  307. (station, next) => {
  308. if (station) return next(true, station);
  309. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  310. },
  311. (station, next) => {
  312. if (station) {
  313. station = StationsModule.stationSchema(station);
  314. CacheModule.runJob("HSET", {
  315. table: "stations",
  316. key: payload.stationId,
  317. value: station
  318. })
  319. .then()
  320. .catch();
  321. next(true, station);
  322. } else next("Station not found");
  323. }
  324. ],
  325. async (err, station) => {
  326. if (err && err !== true) {
  327. err = await UtilsModule.runJob(
  328. "GET_ERROR",
  329. {
  330. error: err
  331. },
  332. this
  333. );
  334. reject(new Error(err));
  335. } else resolve(station);
  336. }
  337. );
  338. });
  339. }
  340. /**
  341. * 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.
  342. *
  343. * @param {object} payload - object that contains the payload
  344. * @param {string} payload.stationName - the unique name of the station
  345. * @returns {Promise} - returns a promise (resolve, reject)
  346. */
  347. async GET_STATION_BY_NAME(payload) {
  348. return new Promise((resolve, reject) =>
  349. async.waterfall(
  350. [
  351. next => {
  352. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  353. },
  354. (station, next) => {
  355. if (station) {
  356. station = StationsModule.stationSchema(station);
  357. CacheModule.runJob("HSET", {
  358. table: "stations",
  359. key: station._id,
  360. value: station
  361. });
  362. next(true, station);
  363. } else next("Station not found");
  364. }
  365. ],
  366. (err, station) => {
  367. if (err && err !== true) return reject(new Error(err));
  368. return resolve(station);
  369. }
  370. )
  371. );
  372. }
  373. /**
  374. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  375. *
  376. * @param {object} payload - object that contains the payload
  377. * @param {string} payload.stationId - the id of the station to update
  378. * @returns {Promise} - returns a promise (resolve, reject)
  379. */
  380. UPDATE_STATION(payload) {
  381. return new Promise((resolve, reject) => {
  382. async.waterfall(
  383. [
  384. next => {
  385. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  386. },
  387. (station, next) => {
  388. if (!station) {
  389. CacheModule.runJob("HDEL", {
  390. table: "stations",
  391. key: payload.stationId
  392. })
  393. .then()
  394. .catch();
  395. return next("Station not found");
  396. }
  397. return CacheModule.runJob(
  398. "HSET",
  399. {
  400. table: "stations",
  401. key: payload.stationId,
  402. value: station
  403. },
  404. this
  405. )
  406. .then(station => {
  407. next(null, station);
  408. })
  409. .catch(next);
  410. }
  411. ],
  412. async (err, station) => {
  413. if (err && err !== true) {
  414. err = await UtilsModule.runJob(
  415. "GET_ERROR",
  416. {
  417. error: err
  418. },
  419. this
  420. );
  421. reject(new Error(err));
  422. } else resolve(station);
  423. }
  424. );
  425. });
  426. }
  427. /**
  428. * Fills up the official station playlist queue using the songs from the official station playlist
  429. *
  430. * @param {object} payload - object that contains the payload
  431. * @param {string} payload.stationId - the id of the station
  432. * @param {string} payload.ignoreExistingQueue - ignore the existing queue songs, replacing the old queue with a completely fresh one
  433. * @returns {Promise} - returns a promise (resolve, reject)
  434. */
  435. FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST(payload) {
  436. return new Promise((resolve, reject) => {
  437. const { stationId, ignoreExistingQueue } = payload;
  438. async.waterfall(
  439. [
  440. next => {
  441. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  442. .then(response => {
  443. next(null, response.playlist);
  444. })
  445. .catch(next);
  446. },
  447. (playlist, next) => {
  448. StationsModule.runJob("GET_STATION", { stationId }, this)
  449. .then(station => {
  450. if (ignoreExistingQueue) station.queue = [];
  451. next(null, playlist, station);
  452. })
  453. .catch(next);
  454. },
  455. (playlist, station, next) => {
  456. if (station.playMode === "random") {
  457. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  458. .then(response => {
  459. next(null, response.array, station);
  460. })
  461. .catch(next);
  462. } else next(null, playlist.songs, station);
  463. },
  464. (_playlistSongs, station, next) => {
  465. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  466. if (station.playMode === "sequential") {
  467. if (station.currentSongIndex <= playlistSongs.length) {
  468. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  469. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  470. }
  471. }
  472. const songsStillNeeded = 50 - station.queue.length;
  473. const currentSongs = station.queue;
  474. const currentYoutubeIds = station.queue.map(song => song.youtubeId);
  475. const songsToAdd = [];
  476. let lastSongAdded = null;
  477. playlistSongs
  478. // .map(song => song._doc)
  479. .every(song => {
  480. if (
  481. songsToAdd.length < songsStillNeeded &&
  482. currentYoutubeIds.indexOf(song.youtubeId) === -1
  483. ) {
  484. lastSongAdded = song;
  485. songsToAdd.push(song);
  486. return true;
  487. }
  488. if (songsToAdd.length >= songsStillNeeded) return false;
  489. return true;
  490. });
  491. let { currentSongIndex } = station;
  492. if (station.playMode === "sequential" && lastSongAdded) {
  493. const indexOfLastSong = _playlistSongs
  494. .map(song => song.youtubeId)
  495. .indexOf(lastSongAdded.youtubeId);
  496. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  497. }
  498. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  499. if (!song._id) song._id = null;
  500. return song;
  501. });
  502. next(null, newPlaylist, currentSongIndex);
  503. },
  504. (newPlaylist, currentSongIndex, next) => {
  505. StationsModule.stationModel.updateOne(
  506. { _id: stationId },
  507. { $set: { queue: newPlaylist, currentSongIndex } },
  508. { runValidators: true },
  509. err => {
  510. if (err) next(err);
  511. else
  512. StationsModule.runJob(
  513. "UPDATE_STATION",
  514. {
  515. stationId
  516. },
  517. this
  518. )
  519. .then(() => {
  520. next(null);
  521. })
  522. .catch(next);
  523. }
  524. );
  525. }
  526. ],
  527. err => {
  528. if (err) reject(err);
  529. else resolve();
  530. }
  531. );
  532. });
  533. }
  534. /**
  535. * Gets next station song
  536. *
  537. * @param {object} payload - object that contains the payload
  538. * @param {string} payload.stationId - the id of the station
  539. * @returns {Promise} - returns a promise (resolve, reject)
  540. */
  541. GET_NEXT_STATION_SONG(payload) {
  542. return new Promise((resolve, reject) => {
  543. const { stationId } = payload;
  544. async.waterfall(
  545. [
  546. next => {
  547. StationsModule.runJob("GET_STATION", { stationId }, this)
  548. .then(station => {
  549. next(null, station);
  550. })
  551. .catch(next);
  552. },
  553. (station, next) => {
  554. if (station.queue.length === 0) next("No songs available.");
  555. else {
  556. next(null, station.queue[0]);
  557. }
  558. },
  559. (queueSong, next) => {
  560. if (!queueSong._id) next(null, queueSong);
  561. else
  562. SongsModule.runJob("GET_SONG", { songId: queueSong._id }, this)
  563. .then(response => {
  564. const { song } = response;
  565. if (song) {
  566. const newSong = {
  567. _id: song._id,
  568. youtubeId: song.youtubeId,
  569. title: song.title,
  570. artists: song.artists,
  571. duration: song.duration,
  572. skipDuration: song.skipDuration,
  573. thumbnail: song.thumbnail,
  574. requestedAt: queueSong.requestedAt,
  575. requestedBy: queueSong.requestedBy,
  576. likes: song.likes,
  577. dislikes: song.dislikes,
  578. status: song.status
  579. };
  580. return next(null, newSong);
  581. }
  582. return next(null, song);
  583. })
  584. .catch(err => {
  585. 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. * @param {string} payload.natural - whether to skip naturally or forcefully
  645. * @returns {Promise} - returns a promise (resolve, reject)
  646. */
  647. SKIP_STATION(payload) {
  648. return new Promise((resolve, reject) => {
  649. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  650. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  651. async.waterfall(
  652. [
  653. // Clears up any existing timers that would skip the station if the song ends
  654. next => {
  655. NotificationsModule.runJob("UNSCHEDULE", {
  656. name: `stations.nextSong?id=${payload.stationId}`
  657. })
  658. .then(() => {
  659. next();
  660. })
  661. .catch(next);
  662. },
  663. // Gets the station object
  664. next => {
  665. StationsModule.runJob(
  666. "GET_STATION",
  667. {
  668. stationId: payload.stationId
  669. },
  670. this
  671. )
  672. .then(station => next(null, station))
  673. .catch(next);
  674. },
  675. // eslint-disable-next-line consistent-return
  676. (station, next) => {
  677. if (!station) return next("Station not found.");
  678. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  679. return next(null, null, station); // Community station with party mode enabled and no songs in the queue
  680. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  681. // Community station with party mode enabled and songs in the queue
  682. if (station.paused) return next(null, null, station);
  683. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  684. .then(response => {
  685. StationsModule.runJob(
  686. "REMOVE_FIRST_QUEUE_SONG",
  687. { stationId: station._id },
  688. this
  689. ).then(() => {
  690. next(null, response.song, station);
  691. });
  692. })
  693. .catch(err => {
  694. if (err === "No songs available.") next(null, null, station);
  695. else next(err);
  696. });
  697. // return StationsModule.stationModel.updateOne(
  698. // { _id: payload.stationId },
  699. // {
  700. // $pull: {
  701. // queue: {
  702. // _id: station.queue[0]._id
  703. // }
  704. // }
  705. // },
  706. // err => {
  707. // if (err) return next(err);
  708. // return next(null, station.queue[0], -12, station);
  709. // }
  710. // );
  711. }
  712. if (station.type === "community" && !station.partyMode) {
  713. StationsModule.runJob(
  714. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  715. { stationId: station._id },
  716. this
  717. )
  718. .then(() => {
  719. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  720. .then(response => {
  721. StationsModule.runJob(
  722. "REMOVE_FIRST_QUEUE_SONG",
  723. { stationId: station._id },
  724. this
  725. ).then(() => {
  726. next(null, response.song, station);
  727. });
  728. })
  729. .catch(err => {
  730. if (err === "No songs available.") next(null, null, station);
  731. else next(err);
  732. });
  733. })
  734. .catch(next);
  735. }
  736. // if (station.type === "community" && !station.partyMode) {
  737. // return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  738. // playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  739. // if (err) return next(err);
  740. // if (!playlist) return next(null, null, -13, station);
  741. // playlist = playlist.songs;
  742. // if (playlist.length > 0) {
  743. // let currentSongIndex;
  744. // if (station.currentSongIndex < playlist.length - 1)
  745. // currentSongIndex = station.currentSongIndex + 1;
  746. // else currentSongIndex = 0;
  747. // const callback = (err, song) => {
  748. // if (err) return next(err);
  749. // if (song) return next(null, song, currentSongIndex, station);
  750. // const currentSong = {
  751. // youtubeId: playlist[currentSongIndex].youtubeId,
  752. // title: playlist[currentSongIndex].title,
  753. // duration: playlist[currentSongIndex].duration,
  754. // likes: -1,
  755. // dislikes: -1,
  756. // requestedAt: playlist[currentSongIndex].requestedAt
  757. // };
  758. // return next(null, currentSong, currentSongIndex, station);
  759. // };
  760. // if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  761. // return SongsModule.runJob(
  762. // "GET_SONG",
  763. // {
  764. // id: playlist[currentSongIndex]._id
  765. // },
  766. // this
  767. // )
  768. // .then(response => callback(null, response.song))
  769. // .catch(callback);
  770. // return SongsModule.runJob(
  771. // "GET_SONG_FROM_YOUTUBE_ID",
  772. // {
  773. // youtubeId: playlist[currentSongIndex].youtubeId
  774. // },
  775. // this
  776. // )
  777. // .then(response => callback(null, response.song))
  778. // .catch(callback);
  779. // }
  780. // return next(null, null, -14, station);
  781. // })
  782. // );
  783. // }
  784. if (station.type === "official") {
  785. StationsModule.runJob(
  786. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  787. { stationId: station._id },
  788. this
  789. )
  790. .then(() => {
  791. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  792. .then(response => {
  793. StationsModule.runJob(
  794. "REMOVE_FIRST_QUEUE_SONG",
  795. { stationId: station._id },
  796. this
  797. )
  798. .then(() => {
  799. next(null, response.song, station);
  800. })
  801. .catch(next);
  802. })
  803. .catch(err => {
  804. if (err === "No songs available.") next(null, null, station);
  805. else next(err);
  806. });
  807. })
  808. .catch(next);
  809. }
  810. },
  811. (song, station, next) => {
  812. const $set = {};
  813. if (song === null) $set.currentSong = null;
  814. else {
  815. $set.currentSong = {
  816. _id: song._id,
  817. youtubeId: song.youtubeId,
  818. title: song.title,
  819. artists: song.artists,
  820. duration: song.duration,
  821. likes: song.likes,
  822. dislikes: song.dislikes,
  823. skipDuration: song.skipDuration,
  824. thumbnail: song.thumbnail,
  825. requestedAt: song.requestedAt,
  826. requestedBy: song.requestedBy,
  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.youtubeId !== 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. data: {
  875. currentSong: station.currentSong,
  876. startedAt: station.startedAt,
  877. paused: station.paused,
  878. timePaused: 0,
  879. natural: payload.natural
  880. }
  881. }
  882. ]
  883. });
  884. if (station.privacy === "public")
  885. WSModule.runJob("EMIT_TO_ROOM", {
  886. room: "home",
  887. args: [
  888. "event:station.nextSong",
  889. { data: { stationId: station._id, song: station.currentSong } }
  890. ]
  891. });
  892. else {
  893. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  894. sockets.forEach(async socketId => {
  895. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  896. const { session } = socket;
  897. if (session.sessionId) {
  898. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  899. session => {
  900. if (session) {
  901. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  902. userModel.findOne(
  903. {
  904. _id: session.userId
  905. },
  906. (err, user) => {
  907. if (!err && user) {
  908. if (user.role === "admin")
  909. socket.dispatch("event:station.nextSong", {
  910. data: {
  911. stationId: station._id,
  912. song: station.currentSong
  913. }
  914. });
  915. else if (
  916. station.type === "community" &&
  917. station.owner === session.userId
  918. )
  919. socket.dispatch("event:station.nextSong", {
  920. data: {
  921. stationId: station._id,
  922. song: station.currentSong
  923. }
  924. });
  925. }
  926. }
  927. );
  928. });
  929. }
  930. }
  931. );
  932. }
  933. });
  934. }
  935. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  936. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  937. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  938. sockets,
  939. room: `song.${station.currentSong.youtubeId}`
  940. });
  941. if (!station.paused) {
  942. NotificationsModule.runJob("SCHEDULE", {
  943. name: `stations.nextSong?id=${station._id}`,
  944. time: station.currentSong.duration * 1000,
  945. station
  946. });
  947. }
  948. } else {
  949. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  950. sockets
  951. });
  952. }
  953. });
  954. resolve({ station });
  955. }
  956. }
  957. );
  958. });
  959. }
  960. /**
  961. * Checks if a user can view/access a station
  962. *
  963. * @param {object} payload - object that contains the payload
  964. * @param {object} payload.station - the station object of the station in question
  965. * @param {string} payload.userId - the id of the user in question
  966. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  967. * @returns {Promise} - returns a promise (resolve, reject)
  968. */
  969. CAN_USER_VIEW_STATION(payload) {
  970. return new Promise((resolve, reject) => {
  971. async.waterfall(
  972. [
  973. next => {
  974. if (payload.station.privacy === "public") return next(true);
  975. if (payload.station.privacy === "unlisted")
  976. if (payload.hideUnlisted === true) return next();
  977. else return next(true);
  978. if (!payload.userId) return next("Not allowed");
  979. return next();
  980. },
  981. next => {
  982. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  983. userModel.findOne({ _id: payload.userId }, next);
  984. });
  985. },
  986. (user, next) => {
  987. if (!user) return next("Not allowed");
  988. if (user.role === "admin") return next(true);
  989. if (payload.station.type === "official") return next("Not allowed");
  990. if (payload.station.owner === payload.userId) return next(true);
  991. return next("Not allowed");
  992. }
  993. ],
  994. async errOrResult => {
  995. if (errOrResult !== true && errOrResult !== "Not allowed") {
  996. errOrResult = await UtilsModule.runJob(
  997. "GET_ERROR",
  998. {
  999. error: errOrResult
  1000. },
  1001. this
  1002. );
  1003. reject(new Error(errOrResult));
  1004. } else {
  1005. resolve(errOrResult === true);
  1006. }
  1007. }
  1008. );
  1009. });
  1010. }
  1011. /**
  1012. * Checks if a user has favorited a station or not
  1013. *
  1014. * @param {object} payload - object that contains the payload
  1015. * @param {object} payload.stationId - the id of the station in question
  1016. * @param {string} payload.userId - the id of the user in question
  1017. * @returns {Promise} - returns a promise (resolve, reject)
  1018. */
  1019. HAS_USER_FAVORITED_STATION(payload) {
  1020. return new Promise((resolve, reject) => {
  1021. async.waterfall(
  1022. [
  1023. next => {
  1024. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1025. userModel.findOne({ _id: payload.userId }, next);
  1026. });
  1027. },
  1028. (user, next) => {
  1029. if (!user) return next("User not found.");
  1030. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1031. return next(null, false);
  1032. }
  1033. ],
  1034. async (err, isStationFavorited) => {
  1035. if (err && err !== true) {
  1036. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1037. return reject(new Error(err));
  1038. }
  1039. return resolve(isStationFavorited);
  1040. }
  1041. );
  1042. });
  1043. }
  1044. /**
  1045. * Returns a list of sockets in a room that can and can't know about a station
  1046. *
  1047. * @param {object} payload - the payload object
  1048. * @param {object} payload.station - the station object
  1049. * @param {string} payload.room - the websockets room to get the sockets from
  1050. * @returns {Promise} - returns a promise (resolve, reject)
  1051. */
  1052. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1053. return new Promise((resolve, reject) => {
  1054. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1055. .then(socketIds => {
  1056. const sockets = [];
  1057. async.eachLimit(
  1058. socketIds,
  1059. 1,
  1060. (socketId, next) => {
  1061. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1062. .then(socket => {
  1063. sockets.push(socket);
  1064. next();
  1065. })
  1066. .catch(err => {
  1067. reject(err);
  1068. });
  1069. },
  1070. err => {
  1071. if (err) reject(err);
  1072. else {
  1073. let socketsThatCan = [];
  1074. const socketsThatCannot = [];
  1075. if (payload.station.privacy === "public") {
  1076. socketsThatCan = sockets;
  1077. resolve({ socketsThatCan, socketsThatCannot });
  1078. } else {
  1079. async.eachLimit(
  1080. sockets,
  1081. 1,
  1082. (socket, next) => {
  1083. const { session } = socket;
  1084. async.waterfall(
  1085. [
  1086. next => {
  1087. if (!session.sessionId) next("No session id");
  1088. else next();
  1089. },
  1090. next => {
  1091. CacheModule.runJob(
  1092. "HGET",
  1093. {
  1094. table: "sessions",
  1095. key: session.sessionId
  1096. },
  1097. this
  1098. )
  1099. .then(response => {
  1100. next(null, response);
  1101. })
  1102. .catch(next);
  1103. },
  1104. (session, next) => {
  1105. if (!session) next("No session");
  1106. else {
  1107. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1108. .then(userModel => {
  1109. next(null, userModel);
  1110. })
  1111. .catch(next);
  1112. }
  1113. },
  1114. (userModel, next) => {
  1115. if (!userModel) next("No user model");
  1116. else
  1117. userModel.findOne(
  1118. {
  1119. _id: session.userId
  1120. },
  1121. next
  1122. );
  1123. },
  1124. (user, next) => {
  1125. if (!user) next("No user found");
  1126. else if (user.role === "admin") {
  1127. socketsThatCan.push(socket);
  1128. next();
  1129. } else if (
  1130. payload.station.type === "community" &&
  1131. payload.station.owner === session.userId
  1132. ) {
  1133. socketsThatCan.push(socket);
  1134. next();
  1135. }
  1136. }
  1137. ],
  1138. err => {
  1139. if (err) socketsThatCannot.push(socket);
  1140. next();
  1141. }
  1142. );
  1143. },
  1144. err => {
  1145. if (err) reject(err);
  1146. else resolve({ socketsThatCan, socketsThatCannot });
  1147. }
  1148. );
  1149. }
  1150. }
  1151. }
  1152. );
  1153. })
  1154. .catch(reject);
  1155. });
  1156. }
  1157. /**
  1158. * Adds a playlist to be included in a station
  1159. *
  1160. * @param {object} payload - object that contains the payload
  1161. * @param {object} payload.stationId - the id of the station to include the playlist in
  1162. * @param {object} payload.playlistId - the id of the playlist to be included
  1163. * @returns {Promise} - returns a promise (resolve, reject)
  1164. */
  1165. INCLUDE_PLAYLIST(payload) {
  1166. return new Promise((resolve, reject) => {
  1167. async.waterfall(
  1168. [
  1169. next => {
  1170. if (!payload.stationId) next("Please specify a station id");
  1171. else if (!payload.playlistId) next("Please specify a playlist id");
  1172. else next();
  1173. },
  1174. next => {
  1175. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1176. .then(station => {
  1177. next(null, station);
  1178. })
  1179. .catch(next);
  1180. },
  1181. (station, next) => {
  1182. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1183. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1184. next("This playlist is already included");
  1185. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1186. next(
  1187. "This playlist is currently excluded, please remove it from there before including it"
  1188. );
  1189. else
  1190. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1191. .then(() => {
  1192. next(null);
  1193. })
  1194. .catch(next);
  1195. },
  1196. next => {
  1197. DBModule.runJob(
  1198. "GET_MODEL",
  1199. {
  1200. modelName: "station"
  1201. },
  1202. this
  1203. ).then(stationModel => {
  1204. stationModel.updateOne(
  1205. { _id: payload.stationId },
  1206. { $push: { includedPlaylists: payload.playlistId } },
  1207. next
  1208. );
  1209. });
  1210. },
  1211. (res, next) => {
  1212. StationsModule.runJob(
  1213. "UPDATE_STATION",
  1214. {
  1215. stationId: payload.stationId
  1216. },
  1217. this
  1218. )
  1219. .then(() => {
  1220. next();
  1221. })
  1222. .catch(next);
  1223. }
  1224. ],
  1225. async err => {
  1226. if (err && err !== true) {
  1227. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1228. return reject(new Error(err));
  1229. }
  1230. return resolve();
  1231. }
  1232. );
  1233. });
  1234. }
  1235. /**
  1236. * Removes a playlist that is included in a station
  1237. *
  1238. * @param {object} payload - object that contains the payload
  1239. * @param {object} payload.stationId - the id of the station
  1240. * @param {object} payload.playlistId - the id of the playlist
  1241. * @returns {Promise} - returns a promise (resolve, reject)
  1242. */
  1243. REMOVE_INCLUDED_PLAYLIST(payload) {
  1244. return new Promise((resolve, reject) => {
  1245. async.waterfall(
  1246. [
  1247. next => {
  1248. if (!payload.stationId) next("Please specify a station id");
  1249. else if (!payload.playlistId) next("Please specify a playlist id");
  1250. else next();
  1251. },
  1252. next => {
  1253. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1254. .then(station => {
  1255. next(null, station);
  1256. })
  1257. .catch(next);
  1258. },
  1259. (station, next) => {
  1260. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1261. next("This playlist isn't included");
  1262. else next();
  1263. },
  1264. next => {
  1265. DBModule.runJob(
  1266. "GET_MODEL",
  1267. {
  1268. modelName: "station"
  1269. },
  1270. this
  1271. ).then(stationModel => {
  1272. stationModel.updateOne(
  1273. { _id: payload.stationId },
  1274. { $pull: { includedPlaylists: payload.playlistId } },
  1275. next
  1276. );
  1277. });
  1278. },
  1279. (res, next) => {
  1280. StationsModule.runJob(
  1281. "UPDATE_STATION",
  1282. {
  1283. stationId: payload.stationId
  1284. },
  1285. this
  1286. )
  1287. .then(() => {
  1288. next();
  1289. })
  1290. .catch(next);
  1291. }
  1292. ],
  1293. async err => {
  1294. if (err && err !== true) {
  1295. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1296. return reject(new Error(err));
  1297. }
  1298. return resolve();
  1299. }
  1300. );
  1301. });
  1302. }
  1303. /**
  1304. * Adds a playlist to be excluded in a station
  1305. *
  1306. * @param {object} payload - object that contains the payload
  1307. * @param {object} payload.stationId - the id of the station
  1308. * @param {object} payload.playlistId - the id of the playlist
  1309. * @returns {Promise} - returns a promise (resolve, reject)
  1310. */
  1311. EXCLUDE_PLAYLIST(payload) {
  1312. return new Promise((resolve, reject) => {
  1313. async.waterfall(
  1314. [
  1315. next => {
  1316. if (!payload.stationId) next("Please specify a station id");
  1317. else if (!payload.playlistId) next("Please specify a playlist id");
  1318. else next();
  1319. },
  1320. next => {
  1321. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1322. .then(station => {
  1323. next(null, station);
  1324. })
  1325. .catch(next);
  1326. },
  1327. (station, next) => {
  1328. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1329. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1330. next("This playlist is already excluded");
  1331. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1332. next(
  1333. "This playlist is currently included, please remove it from there before excluding it"
  1334. );
  1335. else
  1336. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1337. .then(() => {
  1338. next(null);
  1339. })
  1340. .catch(next);
  1341. },
  1342. next => {
  1343. DBModule.runJob(
  1344. "GET_MODEL",
  1345. {
  1346. modelName: "station"
  1347. },
  1348. this
  1349. ).then(stationModel => {
  1350. stationModel.updateOne(
  1351. { _id: payload.stationId },
  1352. { $push: { excludedPlaylists: payload.playlistId } },
  1353. next
  1354. );
  1355. });
  1356. },
  1357. (res, next) => {
  1358. StationsModule.runJob(
  1359. "UPDATE_STATION",
  1360. {
  1361. stationId: payload.stationId
  1362. },
  1363. this
  1364. )
  1365. .then(() => {
  1366. next();
  1367. })
  1368. .catch(next);
  1369. }
  1370. ],
  1371. async err => {
  1372. if (err && err !== true) {
  1373. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1374. return reject(new Error(err));
  1375. }
  1376. return resolve();
  1377. }
  1378. );
  1379. });
  1380. }
  1381. /**
  1382. * Removes a playlist that is excluded in a station
  1383. *
  1384. * @param {object} payload - object that contains the payload
  1385. * @param {object} payload.stationId - the id of the station
  1386. * @param {object} payload.playlistId - the id of the playlist
  1387. * @returns {Promise} - returns a promise (resolve, reject)
  1388. */
  1389. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1390. return new Promise((resolve, reject) => {
  1391. console.log(112, payload);
  1392. async.waterfall(
  1393. [
  1394. next => {
  1395. if (!payload.stationId) next("Please specify a station id");
  1396. else if (!payload.playlistId) next("Please specify a playlist id");
  1397. else next();
  1398. },
  1399. next => {
  1400. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1401. .then(station => {
  1402. next(null, station);
  1403. })
  1404. .catch(next);
  1405. },
  1406. (station, next) => {
  1407. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1408. next("This playlist isn't excluded");
  1409. else next();
  1410. },
  1411. next => {
  1412. DBModule.runJob(
  1413. "GET_MODEL",
  1414. {
  1415. modelName: "station"
  1416. },
  1417. this
  1418. ).then(stationModel => {
  1419. stationModel.updateOne(
  1420. { _id: payload.stationId },
  1421. { $pull: { excludedPlaylists: payload.playlistId } },
  1422. next
  1423. );
  1424. });
  1425. },
  1426. (res, next) => {
  1427. StationsModule.runJob(
  1428. "UPDATE_STATION",
  1429. {
  1430. stationId: payload.stationId
  1431. },
  1432. this
  1433. )
  1434. .then(() => {
  1435. next();
  1436. })
  1437. .catch(next);
  1438. }
  1439. ],
  1440. async err => {
  1441. if (err && err !== true) {
  1442. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1443. return reject(new Error(err));
  1444. }
  1445. return resolve();
  1446. }
  1447. );
  1448. });
  1449. }
  1450. /**
  1451. * Gets stations that include or exclude a specific playlist
  1452. *
  1453. * @param {object} payload - object that contains the payload
  1454. * @param {string} payload.playlistId - the playlist id
  1455. * @returns {Promise} - returns promise (reject, resolve)
  1456. */
  1457. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1458. return new Promise((resolve, reject) => {
  1459. DBModule.runJob(
  1460. "GET_MODEL",
  1461. {
  1462. modelName: "station"
  1463. },
  1464. this
  1465. ).then(stationModel => {
  1466. stationModel.find(
  1467. {
  1468. $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }]
  1469. },
  1470. (err, stations) => {
  1471. if (err) reject(err);
  1472. else resolve({ stationIds: stations.map(station => station._id) });
  1473. }
  1474. );
  1475. });
  1476. });
  1477. }
  1478. /**
  1479. * Clears every queue
  1480. *
  1481. * @returns {Promise} - returns a promise (resolve, reject)
  1482. */
  1483. CLEAR_EVERY_STATION_QUEUE() {
  1484. return new Promise((resolve, reject) => {
  1485. async.waterfall(
  1486. [
  1487. next => {
  1488. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1489. if (err) next(err);
  1490. else {
  1491. StationsModule.stationModel.find({}, (err, stations) => {
  1492. if (err) next(err);
  1493. else {
  1494. async.eachLimit(
  1495. stations,
  1496. 1,
  1497. (station, next) => {
  1498. StationsModule.runJob("UPDATE_STATION", {
  1499. stationId: station._id
  1500. })
  1501. .then(() => next())
  1502. .catch(next);
  1503. CacheModule.runJob("PUB", {
  1504. channel: "station.queueUpdate",
  1505. value: station._id
  1506. })
  1507. .then()
  1508. .catch();
  1509. },
  1510. next
  1511. );
  1512. }
  1513. });
  1514. }
  1515. });
  1516. }
  1517. ],
  1518. err => {
  1519. if (err) reject(err);
  1520. else resolve();
  1521. }
  1522. );
  1523. });
  1524. }
  1525. /**
  1526. * Clears and refills a station queue
  1527. *
  1528. * @param {object} payload - object that contains the payload
  1529. * @param {string} payload.stationId - the station id
  1530. * @returns {Promise} - returns a promise (resolve, reject)
  1531. */
  1532. CLEAR_AND_REFILL_STATION_QUEUE(payload) {
  1533. return new Promise((resolve, reject) => {
  1534. async.waterfall(
  1535. [
  1536. next => {
  1537. StationsModule.runJob(
  1538. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  1539. { stationId: payload.stationId, ignoreExistingQueue: true },
  1540. this
  1541. )
  1542. .then(() => {
  1543. CacheModule.runJob("PUB", {
  1544. channel: "station.queueUpdate",
  1545. value: payload.stationId
  1546. })
  1547. .then()
  1548. .catch();
  1549. next();
  1550. })
  1551. .catch(err => {
  1552. next(err);
  1553. });
  1554. }
  1555. ],
  1556. err => {
  1557. if (err) reject(err);
  1558. else resolve();
  1559. }
  1560. );
  1561. });
  1562. }
  1563. }
  1564. export default new _StationsModule();