stations.js 38 KB

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