stations.js 39 KB

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