stations.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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("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(next);
  730. })
  731. .catch(next);
  732. })
  733. .catch(next);
  734. }
  735. },
  736. (song, currentSongIndex, station, next) => {
  737. const $set = {};
  738. if (song === null) $set.currentSong = null;
  739. else if (song.likes === -1 && song.dislikes === -1) {
  740. $set.currentSong = {
  741. songId: song.songId,
  742. title: song.title,
  743. duration: song.duration,
  744. skipDuration: 0,
  745. likes: -1,
  746. dislikes: -1,
  747. requestedAt: song.requestedAt
  748. };
  749. } else {
  750. $set.currentSong = {
  751. _id: song._id,
  752. songId: song.songId,
  753. title: song.title,
  754. artists: song.artists,
  755. duration: song.duration,
  756. likes: song.likes,
  757. dislikes: song.dislikes,
  758. skipDuration: song.skipDuration,
  759. thumbnail: song.thumbnail,
  760. requestedAt: song.requestedAt
  761. };
  762. }
  763. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  764. $set.startedAt = Date.now();
  765. $set.timePaused = 0;
  766. if (station.paused) $set.pausedAt = Date.now();
  767. next(null, $set, station);
  768. },
  769. ($set, station, next) => {
  770. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  771. if (err) return next(err);
  772. return StationsModule.runJob(
  773. "UPDATE_STATION",
  774. {
  775. stationId: station._id
  776. },
  777. this
  778. )
  779. .then(station => {
  780. if (station.type === "community" && station.partyMode === true)
  781. CacheModule.runJob("PUB", {
  782. channel: "station.queueUpdate",
  783. value: payload.stationId
  784. })
  785. .then()
  786. .catch();
  787. next(null, station);
  788. })
  789. .catch(next);
  790. });
  791. }
  792. ],
  793. async (err, station) => {
  794. if (err) {
  795. err = await UtilsModule.runJob(
  796. "GET_ERROR",
  797. {
  798. error: err
  799. },
  800. this
  801. );
  802. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  803. reject(new Error(err));
  804. } else {
  805. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  806. station.currentSong.skipVotes = 0;
  807. }
  808. // TODO Pub/Sub this
  809. IOModule.runJob("EMIT_TO_ROOM", {
  810. room: `station.${station._id}`,
  811. args: [
  812. "event:songs.next",
  813. {
  814. currentSong: station.currentSong,
  815. startedAt: station.startedAt,
  816. paused: station.paused,
  817. timePaused: 0
  818. }
  819. ]
  820. })
  821. .then()
  822. .catch();
  823. if (station.privacy === "public") {
  824. IOModule.runJob("EMIT_TO_ROOM", {
  825. room: "home",
  826. args: ["event:station.nextSong", station._id, station.currentSong]
  827. })
  828. .then()
  829. .catch();
  830. } else {
  831. const sockets = await IOModule.runJob("GET_ROOM_SOCKETS", { room: "home" }, this);
  832. Object.keys(sockets).forEach(socketKey => {
  833. const socket = sockets[socketKey];
  834. const { session } = socket;
  835. if (session.sessionId) {
  836. CacheModule.runJob(
  837. "HGET",
  838. {
  839. table: "sessions",
  840. key: session.sessionId
  841. },
  842. this
  843. // eslint-disable-next-line no-loop-func
  844. ).then(session => {
  845. if (session) {
  846. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  847. userModel => {
  848. userModel.findOne(
  849. {
  850. _id: session.userId
  851. },
  852. (err, user) => {
  853. if (!err && user) {
  854. if (user.role === "admin")
  855. socket.emit(
  856. "event:station.nextSong",
  857. station._id,
  858. station.currentSong
  859. );
  860. else if (
  861. station.type === "community" &&
  862. station.owner === session.userId
  863. )
  864. socket.emit(
  865. "event:station.nextSong",
  866. station._id,
  867. station.currentSong
  868. );
  869. }
  870. }
  871. );
  872. }
  873. );
  874. }
  875. });
  876. }
  877. });
  878. }
  879. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  880. IOModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  881. sockets: await IOModule.runJob(
  882. "GET_ROOM_SOCKETS",
  883. {
  884. room: `station.${station._id}`
  885. },
  886. this
  887. ),
  888. room: `song.${station.currentSong.songId}`
  889. });
  890. if (!station.paused) {
  891. NotificationsModule.runJob("SCHEDULE", {
  892. name: `stations.nextSong?id=${station._id}`,
  893. time: station.currentSong.duration * 1000,
  894. station
  895. });
  896. }
  897. } else {
  898. IOModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  899. sockets: await IOModule.runJob(
  900. "GET_ROOM_SOCKETS",
  901. {
  902. room: `station.${station._id}`
  903. },
  904. this
  905. )
  906. })
  907. .then()
  908. .catch();
  909. }
  910. resolve({ station });
  911. }
  912. }
  913. );
  914. });
  915. }
  916. /**
  917. * Checks if a user can view/access a station
  918. *
  919. * @param {object} payload - object that contains the payload
  920. * @param {object} payload.station - the station object of the station in question
  921. * @param {string} payload.userId - the id of the user in question
  922. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  923. * @returns {Promise} - returns a promise (resolve, reject)
  924. */
  925. CAN_USER_VIEW_STATION(payload) {
  926. return new Promise((resolve, reject) => {
  927. async.waterfall(
  928. [
  929. next => {
  930. if (payload.station.privacy === "public") return next(true);
  931. if (payload.station.privacy === "unlisted")
  932. if (payload.hideUnlisted === true) return next();
  933. else return next(true);
  934. if (!payload.userId) return next("Not allowed");
  935. return next();
  936. },
  937. next => {
  938. DBModule.runJob(
  939. "GET_MODEL",
  940. {
  941. modelName: "user"
  942. },
  943. this
  944. ).then(userModel => {
  945. userModel.findOne({ _id: payload.userId }, next);
  946. });
  947. },
  948. (user, next) => {
  949. if (!user) return next("Not allowed");
  950. if (user.role === "admin") return next(true);
  951. if (payload.station.type === "official") return next("Not allowed");
  952. if (payload.station.owner === payload.userId) return next(true);
  953. return next("Not allowed");
  954. }
  955. ],
  956. async errOrResult => {
  957. if (errOrResult !== true && errOrResult !== "Not allowed") {
  958. errOrResult = await UtilsModule.runJob(
  959. "GET_ERROR",
  960. {
  961. error: errOrResult
  962. },
  963. this
  964. );
  965. reject(new Error(errOrResult));
  966. } else {
  967. resolve(errOrResult === true);
  968. }
  969. }
  970. );
  971. });
  972. }
  973. /**
  974. * Checks if a user has favorited a station or not
  975. *
  976. * @param {object} payload - object that contains the payload
  977. * @param {object} payload.stationId - the id of the station in question
  978. * @param {string} payload.userId - the id of the user in question
  979. * @returns {Promise} - returns a promise (resolve, reject)
  980. */
  981. HAS_USER_FAVORITED_STATION(payload) {
  982. return new Promise((resolve, reject) => {
  983. async.waterfall(
  984. [
  985. next => {
  986. DBModule.runJob(
  987. "GET_MODEL",
  988. {
  989. modelName: "user"
  990. },
  991. this
  992. ).then(userModel => {
  993. userModel.findOne({ _id: payload.userId }, next);
  994. });
  995. },
  996. (user, next) => {
  997. if (!user) return next("User not found.");
  998. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  999. return next(null, false);
  1000. }
  1001. ],
  1002. async (err, isStationFavorited) => {
  1003. if (err && err !== true) {
  1004. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1005. return reject(new Error(err));
  1006. }
  1007. return resolve(isStationFavorited);
  1008. }
  1009. );
  1010. });
  1011. }
  1012. /**
  1013. * Returns a list of sockets in a room that can and can't know about a station
  1014. *
  1015. * @param {object} payload - the payload object
  1016. * @param {object} payload.station - the station object
  1017. * @param {string} payload.room - the socket.io room to get the sockets from
  1018. * @returns {Promise} - returns a promise (resolve, reject)
  1019. */
  1020. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1021. return new Promise((resolve, reject) => {
  1022. IOModule.runJob("GET_ROOM_SOCKETS", { room: payload.room }, this)
  1023. .then(socketsObject => {
  1024. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1025. let socketsThatCan = [];
  1026. const socketsThatCannot = [];
  1027. if (payload.station.privacy === "public") {
  1028. socketsThatCan = sockets;
  1029. resolve({ socketsThatCan, socketsThatCannot });
  1030. } else {
  1031. async.eachLimit(
  1032. sockets,
  1033. 1,
  1034. (socket, next) => {
  1035. const { session } = socket;
  1036. async.waterfall(
  1037. [
  1038. next => {
  1039. if (!session.sessionId) next("No session id");
  1040. else next();
  1041. },
  1042. next => {
  1043. CacheModule.runJob(
  1044. "HGET",
  1045. {
  1046. table: "sessions",
  1047. key: session.sessionId
  1048. },
  1049. this
  1050. )
  1051. .then(response => {
  1052. next(null, response);
  1053. })
  1054. .catch(next);
  1055. },
  1056. (session, next) => {
  1057. if (!session) next("No session");
  1058. else {
  1059. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1060. .then(userModel => {
  1061. next(null, userModel);
  1062. })
  1063. .catch(next);
  1064. }
  1065. },
  1066. (userModel, next) => {
  1067. if (!userModel) next("No user model");
  1068. else
  1069. userModel.findOne(
  1070. {
  1071. _id: session.userId
  1072. },
  1073. next
  1074. );
  1075. },
  1076. (user, next) => {
  1077. if (!user) next("No user found");
  1078. else if (user.role === "admin") {
  1079. socketsThatCan.push(socket);
  1080. next();
  1081. } else if (
  1082. payload.station.type === "community" &&
  1083. payload.station.owner === session.userId
  1084. ) {
  1085. socketsThatCan.push(socket);
  1086. next();
  1087. }
  1088. }
  1089. ],
  1090. err => {
  1091. if (err) socketsThatCannot.push(socket);
  1092. next();
  1093. }
  1094. );
  1095. },
  1096. err => {
  1097. if (err) reject(err);
  1098. else resolve({ socketsThatCan, socketsThatCannot });
  1099. }
  1100. );
  1101. }
  1102. })
  1103. .catch(reject);
  1104. });
  1105. }
  1106. /**
  1107. * Adds a playlist to be included in a station
  1108. *
  1109. * @param {object} payload - object that contains the payload
  1110. * @param {object} payload.stationId - the id of the station to include the playlist in
  1111. * @param {object} payload.playlistId - the id of the playlist to be included
  1112. * @returns {Promise} - returns a promise (resolve, reject)
  1113. */
  1114. INCLUDE_PLAYLIST(payload) {
  1115. return new Promise((resolve, reject) => {
  1116. async.waterfall(
  1117. [
  1118. next => {
  1119. if (!payload.stationId) next("Please specify a station id");
  1120. else if (!payload.playlistId) next("Please specify a playlist id");
  1121. else next();
  1122. },
  1123. next => {
  1124. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1125. .then(station => {
  1126. next(null, station);
  1127. })
  1128. .catch(next);
  1129. },
  1130. (station, next) => {
  1131. if (station.playlist2 === payload.playlistId) next("You cannot include the station playlist");
  1132. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1133. next("This playlist is already included");
  1134. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1135. next(
  1136. "This playlist is currently excluded, please remove it from there before including it"
  1137. );
  1138. else
  1139. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1140. .then(() => {
  1141. next(null);
  1142. })
  1143. .catch(next);
  1144. },
  1145. next => {
  1146. DBModule.runJob(
  1147. "GET_MODEL",
  1148. {
  1149. modelName: "station"
  1150. },
  1151. this
  1152. ).then(stationModel => {
  1153. stationModel.updateOne(
  1154. { _id: payload.stationId },
  1155. { $push: { includedPlaylists: payload.playlistId } },
  1156. next
  1157. );
  1158. });
  1159. },
  1160. (res, next) => {
  1161. StationsModule.runJob(
  1162. "UPDATE_STATION",
  1163. {
  1164. stationId: payload.stationId
  1165. },
  1166. this
  1167. )
  1168. .then(() => {
  1169. next();
  1170. })
  1171. .catch(next);
  1172. }
  1173. ],
  1174. async err => {
  1175. if (err && err !== true) {
  1176. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1177. return reject(new Error(err));
  1178. }
  1179. return resolve();
  1180. }
  1181. );
  1182. });
  1183. }
  1184. /**
  1185. * Removes a playlist that is included in a station
  1186. *
  1187. * @param {object} payload - object that contains the payload
  1188. * @param {object} payload.stationId - the id of the station
  1189. * @param {object} payload.playlistId - the id of the playlist
  1190. * @returns {Promise} - returns a promise (resolve, reject)
  1191. */
  1192. REMOVE_INCLUDED_PLAYLIST(payload) {
  1193. return new Promise((resolve, reject) => {
  1194. async.waterfall(
  1195. [
  1196. next => {
  1197. if (!payload.stationId) next("Please specify a station id");
  1198. else if (!payload.playlistId) next("Please specify a playlist id");
  1199. else next();
  1200. },
  1201. next => {
  1202. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1203. .then(station => {
  1204. next(null, station);
  1205. })
  1206. .catch(next);
  1207. },
  1208. (station, next) => {
  1209. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1210. next("This playlist isn't included");
  1211. else next();
  1212. },
  1213. next => {
  1214. DBModule.runJob(
  1215. "GET_MODEL",
  1216. {
  1217. modelName: "station"
  1218. },
  1219. this
  1220. ).then(stationModel => {
  1221. stationModel.updateOne(
  1222. { _id: payload.stationId },
  1223. { $pull: { includedPlaylists: payload.playlistId } },
  1224. next
  1225. );
  1226. });
  1227. },
  1228. (res, next) => {
  1229. StationsModule.runJob(
  1230. "UPDATE_STATION",
  1231. {
  1232. stationId: payload.stationId
  1233. },
  1234. this
  1235. )
  1236. .then(() => {
  1237. next();
  1238. })
  1239. .catch(next);
  1240. }
  1241. ],
  1242. async err => {
  1243. if (err && err !== true) {
  1244. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1245. return reject(new Error(err));
  1246. }
  1247. return resolve();
  1248. }
  1249. );
  1250. });
  1251. }
  1252. /**
  1253. * Adds a playlist to be excluded in a station
  1254. *
  1255. * @param {object} payload - object that contains the payload
  1256. * @param {object} payload.stationId - the id of the station
  1257. * @param {object} payload.playlistId - the id of the playlist
  1258. * @returns {Promise} - returns a promise (resolve, reject)
  1259. */
  1260. EXCLUDE_PLAYLIST(payload) {
  1261. return new Promise((resolve, reject) => {
  1262. async.waterfall(
  1263. [
  1264. next => {
  1265. if (!payload.stationId) next("Please specify a station id");
  1266. else if (!payload.playlistId) next("Please specify a playlist id");
  1267. else next();
  1268. },
  1269. next => {
  1270. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1271. .then(station => {
  1272. next(null, station);
  1273. })
  1274. .catch(next);
  1275. },
  1276. (station, next) => {
  1277. if (station.playlist2 === payload.playlistId) next("You cannot exclude the station playlist");
  1278. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1279. next("This playlist is already excluded");
  1280. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1281. next(
  1282. "This playlist is currently included, please remove it from there before excluding it"
  1283. );
  1284. else
  1285. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1286. .then(() => {
  1287. next(null);
  1288. })
  1289. .catch(next);
  1290. },
  1291. next => {
  1292. DBModule.runJob(
  1293. "GET_MODEL",
  1294. {
  1295. modelName: "station"
  1296. },
  1297. this
  1298. ).then(stationModel => {
  1299. stationModel.updateOne(
  1300. { _id: payload.stationId },
  1301. { $push: { excludedPlaylists: payload.playlistId } },
  1302. next
  1303. );
  1304. });
  1305. },
  1306. (res, next) => {
  1307. StationsModule.runJob(
  1308. "UPDATE_STATION",
  1309. {
  1310. stationId: payload.stationId
  1311. },
  1312. this
  1313. )
  1314. .then(() => {
  1315. next();
  1316. })
  1317. .catch(next);
  1318. }
  1319. ],
  1320. async err => {
  1321. if (err && err !== true) {
  1322. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1323. return reject(new Error(err));
  1324. }
  1325. return resolve();
  1326. }
  1327. );
  1328. });
  1329. }
  1330. /**
  1331. * Removes a playlist that is excluded in a station
  1332. *
  1333. * @param {object} payload - object that contains the payload
  1334. * @param {object} payload.stationId - the id of the station
  1335. * @param {object} payload.playlistId - the id of the playlist
  1336. * @returns {Promise} - returns a promise (resolve, reject)
  1337. */
  1338. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1339. return new Promise((resolve, reject) => {
  1340. console.log(112, payload);
  1341. async.waterfall(
  1342. [
  1343. next => {
  1344. if (!payload.stationId) next("Please specify a station id");
  1345. else if (!payload.playlistId) next("Please specify a playlist id");
  1346. else next();
  1347. },
  1348. next => {
  1349. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1350. .then(station => {
  1351. next(null, station);
  1352. })
  1353. .catch(next);
  1354. },
  1355. (station, next) => {
  1356. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1357. next("This playlist isn't excluded");
  1358. else next();
  1359. },
  1360. next => {
  1361. DBModule.runJob(
  1362. "GET_MODEL",
  1363. {
  1364. modelName: "station"
  1365. },
  1366. this
  1367. ).then(stationModel => {
  1368. stationModel.updateOne(
  1369. { _id: payload.stationId },
  1370. { $pull: { excludedPlaylists: payload.playlistId } },
  1371. next
  1372. );
  1373. });
  1374. },
  1375. (res, next) => {
  1376. StationsModule.runJob(
  1377. "UPDATE_STATION",
  1378. {
  1379. stationId: payload.stationId
  1380. },
  1381. this
  1382. )
  1383. .then(() => {
  1384. next();
  1385. })
  1386. .catch(next);
  1387. }
  1388. ],
  1389. async err => {
  1390. if (err && err !== true) {
  1391. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1392. return reject(new Error(err));
  1393. }
  1394. return resolve();
  1395. }
  1396. );
  1397. });
  1398. }
  1399. /**
  1400. * Gets stations that include or exclude a specific playlist
  1401. *
  1402. * @param {object} payload - object that contains the payload
  1403. * @param {string} payload.playlistId - the playlist id
  1404. * @returns {Promise} - returns promise (reject, resolve)
  1405. */
  1406. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1407. return new Promise((resolve, reject) => {
  1408. DBModule.runJob(
  1409. "GET_MODEL",
  1410. {
  1411. modelName: "station"
  1412. },
  1413. this
  1414. ).then(stationModel => {
  1415. stationModel.find(
  1416. { $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }] },
  1417. (err, stations) => {
  1418. if (err) reject(err);
  1419. else resolve({ stationIds: stations.map(station => station._id) });
  1420. }
  1421. );
  1422. });
  1423. });
  1424. }
  1425. }
  1426. export default new _StationsModule();