stations.js 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  1. import async from "async";
  2. import mongoose from "mongoose";
  3. import CoreClass from "../core";
  4. let StationsModule;
  5. let CacheModule;
  6. let DBModule;
  7. let UtilsModule;
  8. let IOModule;
  9. let SongsModule;
  10. let PlaylistsModule;
  11. let NotificationsModule;
  12. class _StationsModule extends CoreClass {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor() {
  15. super("stations");
  16. StationsModule = this;
  17. }
  18. /**
  19. * Initialises the stations module
  20. *
  21. * @returns {Promise} - returns promise (reject, resolve)
  22. */
  23. async initialize() {
  24. CacheModule = this.moduleManager.modules.cache;
  25. DBModule = this.moduleManager.modules.db;
  26. UtilsModule = this.moduleManager.modules.utils;
  27. IOModule = this.moduleManager.modules.io;
  28. SongsModule = this.moduleManager.modules.songs;
  29. PlaylistsModule = this.moduleManager.modules.playlists;
  30. NotificationsModule = this.moduleManager.modules.notifications;
  31. this.defaultSong = {
  32. songId: "60ItHLz5WEA",
  33. title: "Faded - Alan Walker",
  34. duration: 212,
  35. skipDuration: 0,
  36. likes: -1,
  37. dislikes: -1,
  38. requestedAt: Date.now()
  39. };
  40. this.userList = {};
  41. this.usersPerStation = {};
  42. this.usersPerStationCount = {};
  43. // TEMP
  44. CacheModule.runJob("SUB", {
  45. channel: "station.pause",
  46. cb: async stationId => {
  47. NotificationsModule.runJob("REMOVE", {
  48. subscription: `stations.nextSong?id=${stationId}`
  49. }).then();
  50. }
  51. });
  52. CacheModule.runJob("SUB", {
  53. channel: "station.resume",
  54. cb: async stationId => {
  55. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  56. }
  57. });
  58. CacheModule.runJob("SUB", {
  59. channel: "station.queueUpdate",
  60. cb: async stationId => {
  61. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  62. if (!station.currentSong && station.queue.length > 0) {
  63. StationsModule.runJob("INITIALIZE_STATION", {
  64. stationId
  65. }).then();
  66. }
  67. });
  68. }
  69. });
  70. CacheModule.runJob("SUB", {
  71. channel: "station.newOfficialPlaylist",
  72. cb: async stationId => {
  73. CacheModule.runJob("HGET", {
  74. table: "officialPlaylists",
  75. key: stationId
  76. }).then(playlistObj => {
  77. if (playlistObj) {
  78. IOModule.runJob("EMIT_TO_ROOM", {
  79. room: `station.${stationId}`,
  80. args: ["event:newOfficialPlaylist", playlistObj.songs]
  81. });
  82. }
  83. });
  84. }
  85. });
  86. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  87. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  88. return new Promise((resolve, reject) =>
  89. async.waterfall(
  90. [
  91. next => {
  92. this.setStage(2);
  93. CacheModule.runJob("HGETALL", { table: "stations" })
  94. .then(stations => {
  95. next(null, stations);
  96. })
  97. .catch(next);
  98. },
  99. (stations, next) => {
  100. this.setStage(3);
  101. if (!stations) return next();
  102. const stationIds = Object.keys(stations);
  103. return async.each(
  104. stationIds,
  105. (stationId, next) => {
  106. stationModel.findOne({ _id: stationId }, (err, station) => {
  107. if (err) next(err);
  108. else if (!station) {
  109. CacheModule.runJob("HDEL", {
  110. table: "stations",
  111. key: stationId
  112. })
  113. .then(() => {
  114. next();
  115. })
  116. .catch(next);
  117. } else next();
  118. });
  119. },
  120. next
  121. );
  122. },
  123. next => {
  124. this.setStage(4);
  125. stationModel.find({}, next);
  126. },
  127. (stations, next) => {
  128. this.setStage(5);
  129. async.each(
  130. stations,
  131. (station, next2) => {
  132. async.waterfall(
  133. [
  134. next => {
  135. CacheModule.runJob("HSET", {
  136. table: "stations",
  137. key: station._id,
  138. value: stationSchema(station)
  139. })
  140. .then(station => next(null, station))
  141. .catch(next);
  142. },
  143. (station, next) => {
  144. StationsModule.runJob(
  145. "INITIALIZE_STATION",
  146. {
  147. stationId: station._id
  148. },
  149. null,
  150. -1
  151. )
  152. .then(() => {
  153. next();
  154. })
  155. .catch(next);
  156. }
  157. ],
  158. err => {
  159. next2(err);
  160. }
  161. );
  162. },
  163. next
  164. );
  165. }
  166. ],
  167. async err => {
  168. if (err) {
  169. err = await UtilsModule.runJob("GET_ERROR", {
  170. error: err
  171. });
  172. reject(new Error(err));
  173. } else {
  174. resolve();
  175. }
  176. }
  177. )
  178. );
  179. }
  180. /**
  181. * Initialises a station
  182. *
  183. * @param {object} payload - object that contains the payload
  184. * @param {string} payload.stationId - id of the station to initialise
  185. * @returns {Promise} - returns a promise (resolve, reject)
  186. */
  187. INITIALIZE_STATION(payload) {
  188. return new Promise((resolve, reject) => {
  189. // if (typeof cb !== 'function') cb = ()=>{};
  190. async.waterfall(
  191. [
  192. next => {
  193. StationsModule.runJob(
  194. "GET_STATION",
  195. {
  196. stationId: payload.stationId
  197. },
  198. this
  199. )
  200. .then(station => {
  201. next(null, station);
  202. })
  203. .catch(next);
  204. },
  205. (station, next) => {
  206. if (!station) return next("Station not found.");
  207. return NotificationsModule.runJob(
  208. "UNSCHEDULE",
  209. {
  210. name: `stations.nextSong?id=${station._id}`
  211. },
  212. this
  213. )
  214. .then()
  215. .catch()
  216. .finally(() => {
  217. NotificationsModule.runJob("SUBSCRIBE", {
  218. name: `stations.nextSong?id=${station._id}`,
  219. cb: () =>
  220. StationsModule.runJob("SKIP_STATION", {
  221. stationId: station._id
  222. }),
  223. unique: true,
  224. station
  225. })
  226. .then()
  227. .catch();
  228. if (station.paused) return next(true, station);
  229. return next(null, station);
  230. });
  231. },
  232. (station, next) => {
  233. if (!station.currentSong) {
  234. return StationsModule.runJob(
  235. "SKIP_STATION",
  236. {
  237. stationId: station._id
  238. },
  239. this
  240. )
  241. .then(station => {
  242. next(true, station);
  243. })
  244. .catch(next)
  245. .finally(() => {});
  246. }
  247. let timeLeft =
  248. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  249. if (Number.isNaN(timeLeft)) timeLeft = -1;
  250. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  251. return StationsModule.runJob(
  252. "SKIP_STATION",
  253. {
  254. stationId: station._id
  255. },
  256. this
  257. )
  258. .then(station => {
  259. next(null, station);
  260. })
  261. .catch(next);
  262. }
  263. // name, time, cb, station
  264. NotificationsModule.runJob("SCHEDULE", {
  265. name: `stations.nextSong?id=${station._id}`,
  266. time: timeLeft,
  267. station
  268. });
  269. return next(null, station);
  270. }
  271. ],
  272. async (err, station) => {
  273. if (err && err !== true) {
  274. err = await UtilsModule.runJob(
  275. "GET_ERROR",
  276. {
  277. error: err
  278. },
  279. this
  280. );
  281. reject(new Error(err));
  282. } else resolve(station);
  283. }
  284. );
  285. });
  286. }
  287. /**
  288. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  289. *
  290. * @param {object} payload - object that contains the payload
  291. * @param {string} payload.stationId - id of the station
  292. * @returns {Promise} - returns a promise (resolve, reject)
  293. */
  294. GET_STATION(payload) {
  295. return new Promise((resolve, reject) => {
  296. async.waterfall(
  297. [
  298. next => {
  299. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  300. .then(station => next(null, station))
  301. .catch(next);
  302. },
  303. (station, next) => {
  304. if (station) return next(true, station);
  305. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  306. },
  307. (station, next) => {
  308. if (station) {
  309. station = StationsModule.stationSchema(station);
  310. CacheModule.runJob("HSET", {
  311. table: "stations",
  312. key: payload.stationId,
  313. value: station
  314. })
  315. .then()
  316. .catch();
  317. next(true, station);
  318. } else next("Station not found");
  319. }
  320. ],
  321. async (err, station) => {
  322. if (err && err !== true) {
  323. err = await UtilsModule.runJob(
  324. "GET_ERROR",
  325. {
  326. error: err
  327. },
  328. this
  329. );
  330. reject(new Error(err));
  331. } else resolve(station);
  332. }
  333. );
  334. });
  335. }
  336. /**
  337. * 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.
  338. *
  339. * @param {object} payload - object that contains the payload
  340. * @param {string} payload.stationName - the unique name of the station
  341. * @returns {Promise} - returns a promise (resolve, reject)
  342. */
  343. async GET_STATION_BY_NAME(payload) {
  344. return new Promise((resolve, reject) =>
  345. async.waterfall(
  346. [
  347. next => {
  348. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  349. },
  350. (station, next) => {
  351. if (station) {
  352. station = StationsModule.stationSchema(station);
  353. CacheModule.runJob("HSET", {
  354. table: "stations",
  355. key: station._id,
  356. value: station
  357. });
  358. next(true, station);
  359. } else next("Station not found");
  360. }
  361. ],
  362. (err, station) => {
  363. if (err && err !== true) return reject(new Error(err));
  364. return resolve(station);
  365. }
  366. )
  367. );
  368. }
  369. /**
  370. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  371. *
  372. * @param {object} payload - object that contains the payload
  373. * @param {string} payload.stationId - the id of the station to update
  374. * @returns {Promise} - returns a promise (resolve, reject)
  375. */
  376. UPDATE_STATION(payload) {
  377. return new Promise((resolve, reject) => {
  378. async.waterfall(
  379. [
  380. next => {
  381. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  382. },
  383. (station, next) => {
  384. if (!station) {
  385. CacheModule.runJob("HDEL", {
  386. table: "stations",
  387. key: payload.stationId
  388. })
  389. .then()
  390. .catch();
  391. return next("Station not found");
  392. }
  393. return CacheModule.runJob(
  394. "HSET",
  395. {
  396. table: "stations",
  397. key: payload.stationId,
  398. value: station
  399. },
  400. this
  401. )
  402. .then(station => {
  403. next(null, station);
  404. })
  405. .catch(next);
  406. }
  407. ],
  408. async (err, station) => {
  409. if (err && err !== true) {
  410. err = await UtilsModule.runJob(
  411. "GET_ERROR",
  412. {
  413. error: err
  414. },
  415. this
  416. );
  417. reject(new Error(err));
  418. } else resolve(station);
  419. }
  420. );
  421. });
  422. }
  423. /**
  424. * Fills up the official station playlist queue using the songs from the official station playlist
  425. *
  426. * @param {object} payload - object that contains the payload
  427. * @param {string} payload.stationId - the id of the station
  428. * @returns {Promise} - returns a promise (resolve, reject)
  429. */
  430. FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE(payload) {
  431. return new Promise((resolve, reject) => {
  432. const { stationId } = payload;
  433. async.waterfall(
  434. [
  435. next => {
  436. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  437. .then(response => {
  438. next(null, response.playlist);
  439. })
  440. .catch(next);
  441. },
  442. (playlist, next) => {
  443. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  444. .then(response => {
  445. next(null, response.array);
  446. })
  447. .catch(next);
  448. },
  449. (playlistSongs, next) => {
  450. StationsModule.runJob("GET_STATION", { stationId }, this)
  451. .then(station => {
  452. next(null, playlistSongs, station);
  453. })
  454. .catch(next);
  455. },
  456. (playlistSongs, station, next) => {
  457. const songsStillNeeded = 50 - station.playlist.length;
  458. const currentSongs = station.playlist;
  459. const currentSongIds = station.playlist.map(song => song._id);
  460. const songsToAdd = [];
  461. playlistSongs
  462. .map(song => song._doc)
  463. .forEach(song => {
  464. if (
  465. songsToAdd.length < songsStillNeeded &&
  466. currentSongIds.indexOf(song._id.toString()) === -1
  467. )
  468. songsToAdd.push(song);
  469. });
  470. next(null, [...currentSongs, ...songsToAdd]);
  471. },
  472. (newPlaylist, next) => {
  473. StationsModule.stationModel.updateOne(
  474. { _id: stationId },
  475. { $set: { playlist: newPlaylist } },
  476. { runValidators: true },
  477. () => {
  478. StationsModule.runJob(
  479. "UPDATE_STATION",
  480. {
  481. stationId
  482. },
  483. this
  484. )
  485. .then(() => {
  486. next(null);
  487. })
  488. .catch(next);
  489. }
  490. );
  491. }
  492. ],
  493. err => {
  494. if (err) reject(err);
  495. else resolve();
  496. }
  497. );
  498. });
  499. }
  500. /**
  501. * Gets next official station song
  502. *
  503. * @param {object} payload - object that contains the payload
  504. * @param {string} payload.stationId - the id of the station
  505. * @returns {Promise} - returns a promise (resolve, reject)
  506. */
  507. GET_NEXT_OFFICIAL_STATION_SONG(payload) {
  508. return new Promise((resolve, reject) => {
  509. const { stationId } = payload;
  510. async.waterfall(
  511. [
  512. next => {
  513. StationsModule.runJob("GET_STATION", { stationId }, this)
  514. .then(station => {
  515. next(null, station);
  516. })
  517. .catch(next);
  518. },
  519. (station, next) => {
  520. if (station.playlist.length === 0) next("No songs available.");
  521. else {
  522. next(null, station.playlist[0]);
  523. }
  524. },
  525. (song, next) => {
  526. console.log(44444, song, song._id);
  527. SongsModule.runJob("GET_SONG", { id: song._id }, this)
  528. .then(response => {
  529. const { song } = response;
  530. if (song) {
  531. const newSong = {
  532. _id: song._id,
  533. songId: song.songId,
  534. title: song.title,
  535. artists: song.artists,
  536. duration: song.duration,
  537. thumbnail: song.thumbnail,
  538. requestedAt: song.requestedAt
  539. };
  540. next(null, newSong);
  541. } else {
  542. next(null, song);
  543. }
  544. })
  545. .catch(next);
  546. }
  547. ],
  548. (err, song) => {
  549. if (err) console.log(33333, err, payload);
  550. if (err) reject(err);
  551. else resolve({ song });
  552. }
  553. );
  554. });
  555. }
  556. /**
  557. * Removes first official playlist queue song
  558. *
  559. * @param {object} payload - object that contains the payload
  560. * @param {string} payload.stationId - the id of the station
  561. * @returns {Promise} - returns a promise (resolve, reject)
  562. */
  563. REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG(payload) {
  564. return new Promise((resolve, reject) => {
  565. const { stationId } = payload;
  566. async.waterfall(
  567. [
  568. next => {
  569. StationsModule.stationModel.updateOne(
  570. { _id: stationId },
  571. { $pop: { playlist: -1 } },
  572. { runValidators: true },
  573. err => {
  574. if (err) next(err);
  575. else
  576. StationsModule.runJob(
  577. "UPDATE_STATION",
  578. {
  579. stationId
  580. },
  581. this
  582. )
  583. .then(() => {
  584. next(null);
  585. })
  586. .catch(next);
  587. }
  588. );
  589. }
  590. ],
  591. err => {
  592. if (err) reject(err);
  593. else resolve();
  594. }
  595. );
  596. });
  597. }
  598. /**
  599. * Skips a station
  600. *
  601. * @param {object} payload - object that contains the payload
  602. * @param {string} payload.stationId - the id of the station to skip
  603. * @returns {Promise} - returns a promise (resolve, reject)
  604. */
  605. SKIP_STATION(payload) {
  606. return new Promise((resolve, reject) => {
  607. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  608. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  609. async.waterfall(
  610. [
  611. next => {
  612. NotificationsModule.runJob("UNSCHEDULE", {
  613. name: `stations.nextSong?id=${payload.stationId}`
  614. })
  615. .then(() => {
  616. next();
  617. })
  618. .catch(next);
  619. },
  620. next => {
  621. StationsModule.runJob(
  622. "GET_STATION",
  623. {
  624. stationId: payload.stationId
  625. },
  626. this
  627. )
  628. .then(station => {
  629. next(null, station);
  630. })
  631. .catch(() => {});
  632. },
  633. // eslint-disable-next-line consistent-return
  634. (station, next) => {
  635. if (!station) return next("Station not found.");
  636. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  637. return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  638. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  639. // Community station with party mode enabled and songs in the queue
  640. if (station.paused) return next(null, null, -19, station);
  641. return StationsModule.stationModel.updateOne(
  642. { _id: payload.stationId },
  643. {
  644. $pull: {
  645. queue: {
  646. _id: station.queue[0]._id
  647. }
  648. }
  649. },
  650. err => {
  651. if (err) return next(err);
  652. return next(null, station.queue[0], -12, station);
  653. }
  654. );
  655. }
  656. if (station.type === "community" && !station.partyMode) {
  657. return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  658. playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  659. if (err) return next(err);
  660. if (!playlist) return next(null, null, -13, station);
  661. playlist = playlist.songs;
  662. if (playlist.length > 0) {
  663. let currentSongIndex;
  664. if (station.currentSongIndex < playlist.length - 1)
  665. currentSongIndex = station.currentSongIndex + 1;
  666. else currentSongIndex = 0;
  667. const callback = (err, song) => {
  668. if (err) return next(err);
  669. if (song) return next(null, song, currentSongIndex, station);
  670. const currentSong = {
  671. songId: playlist[currentSongIndex].songId,
  672. title: playlist[currentSongIndex].title,
  673. duration: playlist[currentSongIndex].duration,
  674. likes: -1,
  675. dislikes: -1,
  676. requestedAt: playlist[currentSongIndex].requestedAt
  677. };
  678. return next(null, currentSong, currentSongIndex, station);
  679. };
  680. if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  681. return SongsModule.runJob(
  682. "GET_SONG",
  683. {
  684. id: playlist[currentSongIndex]._id
  685. },
  686. this
  687. )
  688. .then(response => callback(null, response.song))
  689. .catch(callback);
  690. return SongsModule.runJob(
  691. "GET_SONG_FROM_ID",
  692. {
  693. songId: playlist[currentSongIndex].songId
  694. },
  695. this
  696. )
  697. .then(response => callback(null, response.song))
  698. .catch(callback);
  699. }
  700. return next(null, null, -14, station);
  701. })
  702. );
  703. }
  704. if (station.type === "official") {
  705. StationsModule.runJob(
  706. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  707. { stationId: station._id },
  708. this
  709. )
  710. .then(() => {
  711. StationsModule.runJob(
  712. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  713. { stationId: station._id },
  714. this
  715. )
  716. .then(() => {
  717. StationsModule.runJob(
  718. "GET_NEXT_OFFICIAL_STATION_SONG",
  719. { stationId: station._id },
  720. this
  721. )
  722. .then(response => {
  723. next(null, response.song, 0, station);
  724. })
  725. .catch(err => {
  726. if (err === "No songs available.") next(null, null, 0, station);
  727. else next(err);
  728. });
  729. })
  730. .catch(next);
  731. })
  732. .catch(next);
  733. }
  734. },
  735. (song, currentSongIndex, station, next) => {
  736. const $set = {};
  737. if (song === null) $set.currentSong = null;
  738. else if (song.likes === -1 && song.dislikes === -1) {
  739. $set.currentSong = {
  740. songId: song.songId,
  741. title: song.title,
  742. duration: song.duration,
  743. skipDuration: 0,
  744. likes: -1,
  745. dislikes: -1,
  746. requestedAt: song.requestedAt
  747. };
  748. } else {
  749. $set.currentSong = {
  750. _id: song._id,
  751. songId: song.songId,
  752. title: song.title,
  753. artists: song.artists,
  754. duration: song.duration,
  755. likes: song.likes,
  756. dislikes: song.dislikes,
  757. skipDuration: song.skipDuration,
  758. thumbnail: song.thumbnail,
  759. requestedAt: song.requestedAt
  760. };
  761. }
  762. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  763. $set.startedAt = Date.now();
  764. $set.timePaused = 0;
  765. if (station.paused) $set.pausedAt = Date.now();
  766. next(null, $set, station);
  767. },
  768. ($set, station, next) => {
  769. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  770. if (err) return next(err);
  771. return StationsModule.runJob(
  772. "UPDATE_STATION",
  773. {
  774. stationId: station._id
  775. },
  776. this
  777. )
  778. .then(station => {
  779. if (station.type === "community" && station.partyMode === true)
  780. CacheModule.runJob("PUB", {
  781. channel: "station.queueUpdate",
  782. value: payload.stationId
  783. })
  784. .then()
  785. .catch();
  786. next(null, station);
  787. })
  788. .catch(next);
  789. });
  790. }
  791. ],
  792. async (err, station) => {
  793. if (err) {
  794. console.log(123, 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();