stations.js 39 KB

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