stations.js 40 KB

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