stations.js 38 KB

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