stations.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996
  1. import async from "async";
  2. import CoreClass from "../core";
  3. let StationsModule;
  4. let CacheModule;
  5. let DBModule;
  6. let UtilsModule;
  7. let WSModule;
  8. let PlaylistsModule;
  9. let NotificationsModule;
  10. let MediaModule;
  11. class _StationsModule extends CoreClass {
  12. // eslint-disable-next-line require-jsdoc
  13. constructor() {
  14. super("stations");
  15. StationsModule = this;
  16. }
  17. /**
  18. * Initialises the stations module
  19. *
  20. * @returns {Promise} - returns promise (reject, resolve)
  21. */
  22. async initialize() {
  23. CacheModule = this.moduleManager.modules.cache;
  24. DBModule = this.moduleManager.modules.db;
  25. UtilsModule = this.moduleManager.modules.utils;
  26. WSModule = this.moduleManager.modules.ws;
  27. PlaylistsModule = this.moduleManager.modules.playlists;
  28. NotificationsModule = this.moduleManager.modules.notifications;
  29. MediaModule = this.moduleManager.modules.media;
  30. this.userList = {};
  31. this.usersPerStation = {};
  32. this.usersPerStationCount = {};
  33. // TEMP
  34. CacheModule.runJob("SUB", {
  35. channel: "station.pause",
  36. cb: async stationId => {
  37. NotificationsModule.runJob("REMOVE", {
  38. subscription: `stations.nextSong?id=${stationId}`
  39. }).then();
  40. }
  41. });
  42. CacheModule.runJob("SUB", {
  43. channel: "station.resume",
  44. cb: async stationId => {
  45. StationsModule.runJob("INITIALIZE_STATION", { stationId }).then();
  46. }
  47. });
  48. CacheModule.runJob("SUB", {
  49. channel: "station.queueUpdate",
  50. cb: async stationId => {
  51. StationsModule.runJob("GET_STATION", { stationId }).then(station => {
  52. if (!station.currentSong && station.queue.length > 0) {
  53. StationsModule.runJob("INITIALIZE_STATION", {
  54. stationId
  55. }).then();
  56. }
  57. WSModule.runJob("EMIT_TO_ROOM", {
  58. room: `station.${stationId}`,
  59. args: ["event:station.queue.updated", { data: { queue: station.queue } }]
  60. });
  61. WSModule.runJob("EMIT_TO_ROOM", {
  62. room: `manage-station.${stationId}`,
  63. args: ["event:manageStation.queue.updated", { data: { stationId, queue: station.queue } }]
  64. });
  65. });
  66. }
  67. });
  68. const stationModel = (this.stationModel = await DBModule.runJob("GET_MODEL", { modelName: "station" }));
  69. const stationSchema = (this.stationSchema = await CacheModule.runJob("GET_SCHEMA", { schemaName: "station" }));
  70. return new Promise((resolve, reject) => {
  71. async.waterfall(
  72. [
  73. next => {
  74. this.setStage(2);
  75. CacheModule.runJob("HGETALL", { table: "stations" })
  76. .then(stations => {
  77. next(null, stations);
  78. })
  79. .catch(next);
  80. },
  81. (stations, next) => {
  82. this.setStage(3);
  83. if (!stations) return next();
  84. const stationIds = Object.keys(stations);
  85. return async.each(
  86. stationIds,
  87. (stationId, next) => {
  88. stationModel.findOne({ _id: stationId }, (err, station) => {
  89. if (err) next(err);
  90. else if (!station) {
  91. CacheModule.runJob("HDEL", {
  92. table: "stations",
  93. key: stationId
  94. })
  95. .then(() => {
  96. next();
  97. })
  98. .catch(next);
  99. } else next();
  100. });
  101. },
  102. next
  103. );
  104. },
  105. next => {
  106. this.setStage(4);
  107. stationModel.find({}, next);
  108. },
  109. (stations, next) => {
  110. this.setStage(5);
  111. async.each(
  112. stations,
  113. (station, next2) => {
  114. async.waterfall(
  115. [
  116. next => {
  117. CacheModule.runJob("HSET", {
  118. table: "stations",
  119. key: station._id,
  120. value: stationSchema(station)
  121. })
  122. .then(station => next(null, station))
  123. .catch(next);
  124. },
  125. (station, next) => {
  126. StationsModule.runJob(
  127. "INITIALIZE_STATION",
  128. {
  129. stationId: station._id
  130. },
  131. null,
  132. -1
  133. )
  134. .then(() => {
  135. next();
  136. })
  137. .catch(next);
  138. }
  139. ],
  140. err => {
  141. next2(err);
  142. }
  143. );
  144. },
  145. next
  146. );
  147. }
  148. ],
  149. async err => {
  150. if (err) {
  151. err = await UtilsModule.runJob("GET_ERROR", {
  152. error: err
  153. });
  154. reject(new Error(err));
  155. } else {
  156. resolve();
  157. }
  158. }
  159. );
  160. });
  161. }
  162. /**
  163. * Initialises a station
  164. *
  165. * @param {object} payload - object that contains the payload
  166. * @param {string} payload.stationId - id of the station to initialise
  167. * @returns {Promise} - returns a promise (resolve, reject)
  168. */
  169. INITIALIZE_STATION(payload) {
  170. return new Promise((resolve, reject) => {
  171. async.waterfall(
  172. [
  173. next => {
  174. StationsModule.runJob(
  175. "GET_STATION",
  176. {
  177. stationId: payload.stationId
  178. },
  179. this
  180. )
  181. .then(station => {
  182. next(null, station);
  183. })
  184. .catch(next);
  185. },
  186. (station, next) => {
  187. if (!station) return next("Station not found.");
  188. return NotificationsModule.runJob(
  189. "UNSCHEDULE",
  190. {
  191. name: `stations.nextSong?id=${station._id}`
  192. },
  193. this
  194. )
  195. .then()
  196. .catch()
  197. .finally(() => {
  198. NotificationsModule.runJob("SUBSCRIBE", {
  199. name: `stations.nextSong?id=${station._id}`,
  200. cb: () =>
  201. StationsModule.runJob("SKIP_STATION", {
  202. stationId: station._id,
  203. natural: true
  204. }),
  205. unique: true,
  206. station
  207. })
  208. .then()
  209. .catch();
  210. if (station.paused) return next(true, station);
  211. return next(null, station);
  212. });
  213. },
  214. (station, next) => {
  215. if (!station.currentSong) {
  216. return StationsModule.runJob(
  217. "SKIP_STATION",
  218. {
  219. stationId: station._id,
  220. natural: false
  221. },
  222. this
  223. )
  224. .then(station => {
  225. next(true, station);
  226. })
  227. .catch(next)
  228. .finally(() => {});
  229. }
  230. let timeLeft =
  231. station.currentSong.duration * 1000 - (Date.now() - station.startedAt - station.timePaused);
  232. if (Number.isNaN(timeLeft)) timeLeft = -1;
  233. if (station.currentSong.duration * 1000 < timeLeft || timeLeft < 0) {
  234. return StationsModule.runJob(
  235. "SKIP_STATION",
  236. {
  237. stationId: station._id,
  238. natural: false
  239. },
  240. this
  241. )
  242. .then(station => {
  243. next(null, station);
  244. })
  245. .catch(next);
  246. }
  247. // name, time, cb, station
  248. NotificationsModule.runJob("SCHEDULE", {
  249. name: `stations.nextSong?id=${station._id}`,
  250. time: timeLeft,
  251. station
  252. });
  253. return next(null, station);
  254. }
  255. ],
  256. async (err, station) => {
  257. if (err && err !== true) {
  258. err = await UtilsModule.runJob(
  259. "GET_ERROR",
  260. {
  261. error: err
  262. },
  263. this
  264. );
  265. reject(new Error(err));
  266. } else resolve(station);
  267. }
  268. );
  269. });
  270. }
  271. /**
  272. * Attempts to get the station from Redis. If it's not in Redis, get it from Mongo and add it to Redis.
  273. *
  274. * @param {object} payload - object that contains the payload
  275. * @param {string} payload.stationId - id of the station
  276. * @returns {Promise} - returns a promise (resolve, reject)
  277. */
  278. GET_STATION(payload) {
  279. return new Promise((resolve, reject) => {
  280. async.waterfall(
  281. [
  282. next => {
  283. CacheModule.runJob("HGET", { table: "stations", key: payload.stationId }, this)
  284. .then(station => next(null, station))
  285. .catch(next);
  286. },
  287. (station, next) => {
  288. if (station) return next(true, station);
  289. return StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  290. },
  291. (station, next) => {
  292. if (station) {
  293. station = StationsModule.stationSchema(station);
  294. CacheModule.runJob("HSET", {
  295. table: "stations",
  296. key: payload.stationId,
  297. value: station
  298. })
  299. .then()
  300. .catch();
  301. next(true, station);
  302. } else next("Station not found");
  303. }
  304. ],
  305. async (err, station) => {
  306. if (err && err !== true) {
  307. err = await UtilsModule.runJob(
  308. "GET_ERROR",
  309. {
  310. error: err
  311. },
  312. this
  313. );
  314. reject(new Error(err));
  315. } else resolve(station);
  316. }
  317. );
  318. });
  319. }
  320. /**
  321. * 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.
  322. *
  323. * @param {object} payload - object that contains the payload
  324. * @param {string} payload.stationName - the unique name of the station
  325. * @returns {Promise} - returns a promise (resolve, reject)
  326. */
  327. async GET_STATION_BY_NAME(payload) {
  328. return new Promise((resolve, reject) => {
  329. async.waterfall(
  330. [
  331. next => {
  332. StationsModule.stationModel.findOne({ name: payload.stationName }, next);
  333. },
  334. (station, next) => {
  335. if (station) {
  336. station = StationsModule.stationSchema(station);
  337. CacheModule.runJob("HSET", {
  338. table: "stations",
  339. key: station._id,
  340. value: station
  341. });
  342. next(true, station);
  343. } else next("Station not found");
  344. }
  345. ],
  346. (err, station) => {
  347. if (err && err !== true) return reject(new Error(err));
  348. return resolve(station);
  349. }
  350. );
  351. });
  352. }
  353. /**
  354. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  355. *
  356. * @param {object} payload - object that contains the payload
  357. * @param {string} payload.stationId - the id of the station to update
  358. * @returns {Promise} - returns a promise (resolve, reject)
  359. */
  360. UPDATE_STATION(payload) {
  361. return new Promise((resolve, reject) => {
  362. async.waterfall(
  363. [
  364. next => {
  365. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  366. },
  367. (station, next) => {
  368. if (!station) {
  369. CacheModule.runJob("HDEL", {
  370. table: "stations",
  371. key: payload.stationId
  372. })
  373. .then()
  374. .catch();
  375. return next("Station not found");
  376. }
  377. return CacheModule.runJob(
  378. "HSET",
  379. {
  380. table: "stations",
  381. key: payload.stationId,
  382. value: station
  383. },
  384. this
  385. )
  386. .then(station => {
  387. next(null, station);
  388. })
  389. .catch(next);
  390. }
  391. ],
  392. async (err, station) => {
  393. if (err && err !== true) {
  394. err = await UtilsModule.runJob(
  395. "GET_ERROR",
  396. {
  397. error: err
  398. },
  399. this
  400. );
  401. reject(new Error(err));
  402. } else resolve(station);
  403. }
  404. );
  405. });
  406. }
  407. /**
  408. * Autofill station queue from station playlist
  409. *
  410. * @param {object} payload - object that contains the payload
  411. * @param {string} payload.stationId - the id of the station
  412. * @param {string} payload.ignoreExistingQueue - ignore the existing queue songs, replacing the old queue with a completely fresh one
  413. * @returns {Promise} - returns a promise (resolve, reject)
  414. */
  415. AUTOFILL_STATION(payload) {
  416. return new Promise((resolve, reject) => {
  417. const { stationId, ignoreExistingQueue } = payload;
  418. async.waterfall(
  419. [
  420. next => {
  421. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  422. .then(response => {
  423. next(null, response.playlist);
  424. })
  425. .catch(next);
  426. },
  427. (playlist, next) => {
  428. StationsModule.runJob("GET_STATION", { stationId }, this)
  429. .then(station => {
  430. if (!station.autofill.enabled) return next("Autofill is disabled in this station");
  431. if (
  432. !ignoreExistingQueue &&
  433. station.autofill.limit <= station.queue.filter(song => !song.requestedBy).length
  434. )
  435. return next("Autofill limit reached");
  436. if (ignoreExistingQueue) station.queue = [];
  437. return next(null, playlist, station);
  438. })
  439. .catch(next);
  440. },
  441. (playlist, station, next) => {
  442. if (station.autofill.mode === "random") {
  443. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  444. .then(response => {
  445. next(null, response.array, station);
  446. })
  447. .catch(next);
  448. } else next(null, playlist.songs, station);
  449. },
  450. (_playlistSongs, station, next) => {
  451. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  452. if (station.autofill.mode === "sequential") {
  453. if (station.currentSongIndex <= playlistSongs.length) {
  454. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  455. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  456. }
  457. }
  458. const currentRequests = station.queue.filter(song => !song.requestedBy).length;
  459. const songsStillNeeded = station.autofill.limit - currentRequests;
  460. const currentSongs = station.queue;
  461. const currentYoutubeIds = station.queue.map(song => song.youtubeId);
  462. const songsToAdd = [];
  463. let lastSongAdded = null;
  464. if (station.currentSong && station.currentSong.youtubeId)
  465. currentYoutubeIds.push(station.currentSong.youtubeId);
  466. playlistSongs.every(song => {
  467. if (
  468. songsToAdd.length < songsStillNeeded &&
  469. currentYoutubeIds.indexOf(song.youtubeId) === -1
  470. ) {
  471. lastSongAdded = song;
  472. songsToAdd.push(song);
  473. return true;
  474. }
  475. if (songsToAdd.length >= songsStillNeeded) return false;
  476. return true;
  477. });
  478. let { currentSongIndex } = station;
  479. if (station.autofill.mode === "sequential" && lastSongAdded) {
  480. const indexOfLastSong = _playlistSongs
  481. .map(song => song.youtubeId)
  482. .indexOf(lastSongAdded.youtubeId);
  483. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  484. }
  485. next(null, currentSongs, songsToAdd, currentSongIndex);
  486. },
  487. (currentSongs, songsToAdd, currentSongIndex, next) => {
  488. const songs = [];
  489. async.eachLimit(
  490. songsToAdd.map(song => song.youtubeId),
  491. 2,
  492. (youtubeId, next) => {
  493. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  494. .then(response => {
  495. const { song } = response;
  496. const { _id, title, artists, thumbnail, duration, skipDuration, verified } =
  497. song;
  498. songs.push({
  499. _id,
  500. youtubeId,
  501. title,
  502. artists,
  503. thumbnail,
  504. duration,
  505. skipDuration,
  506. verified
  507. });
  508. next();
  509. })
  510. .catch(next);
  511. },
  512. err => {
  513. if (err) next(err);
  514. else {
  515. const newSongsToAdd = songsToAdd.map(song =>
  516. songs.find(newSong => newSong.youtubeId === song.youtubeId)
  517. );
  518. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  519. }
  520. }
  521. );
  522. },
  523. (currentSongs, songsToAdd, currentSongIndex, next) => {
  524. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  525. if (!song._id) song._id = null;
  526. if (!song.requestedAt) song.requestedAt = Date.now();
  527. return song;
  528. });
  529. next(null, newPlaylist, currentSongIndex);
  530. },
  531. (newPlaylist, currentSongIndex, next) => {
  532. StationsModule.stationModel.updateOne(
  533. { _id: stationId },
  534. { $set: { queue: newPlaylist, currentSongIndex } },
  535. { runValidators: true },
  536. err => {
  537. if (err) next(err);
  538. else
  539. StationsModule.runJob(
  540. "UPDATE_STATION",
  541. {
  542. stationId
  543. },
  544. this
  545. )
  546. .then(() => {
  547. next(null);
  548. })
  549. .catch(next);
  550. }
  551. );
  552. }
  553. ],
  554. err => {
  555. if (err) reject(err);
  556. else resolve();
  557. }
  558. );
  559. });
  560. }
  561. /**
  562. * Gets next station 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. GET_NEXT_STATION_SONG(payload) {
  569. return new Promise((resolve, reject) => {
  570. const { stationId } = payload;
  571. async.waterfall(
  572. [
  573. next => {
  574. StationsModule.runJob("GET_STATION", { stationId }, this)
  575. .then(station => {
  576. next(null, station);
  577. })
  578. .catch(next);
  579. },
  580. (station, next) => {
  581. if (station.queue.length === 0) next("No songs available.");
  582. else {
  583. next(null, station.queue[0]);
  584. }
  585. },
  586. (queueSong, next) => {
  587. MediaModule.runJob(
  588. "GET_MEDIA",
  589. {
  590. youtubeId: queueSong.youtubeId
  591. },
  592. this
  593. )
  594. .then(response => {
  595. const { song } = response;
  596. const { _id, youtubeId, title, skipDuration, artists, thumbnail, duration, verified } =
  597. song;
  598. next(null, {
  599. _id,
  600. youtubeId,
  601. title,
  602. skipDuration,
  603. artists,
  604. thumbnail,
  605. duration,
  606. verified,
  607. requestedAt: queueSong.requestedAt,
  608. requestedBy: queueSong.requestedBy,
  609. likes: song.likes || 0,
  610. dislikes: song.dislikes || 0
  611. });
  612. })
  613. .catch(next);
  614. }
  615. ],
  616. (err, song) => {
  617. if (err) reject(err);
  618. else resolve({ song });
  619. }
  620. );
  621. });
  622. }
  623. /**
  624. * Removes first station queue song
  625. *
  626. * @param {object} payload - object that contains the payload
  627. * @param {string} payload.stationId - the id of the station
  628. * @returns {Promise} - returns a promise (resolve, reject)
  629. */
  630. REMOVE_FIRST_QUEUE_SONG(payload) {
  631. return new Promise((resolve, reject) => {
  632. const { stationId } = payload;
  633. async.waterfall(
  634. [
  635. next => {
  636. StationsModule.stationModel.updateOne(
  637. { _id: stationId },
  638. { $pop: { queue: -1 } },
  639. { runValidators: true },
  640. err => {
  641. if (err) next(err);
  642. else
  643. StationsModule.runJob(
  644. "UPDATE_STATION",
  645. {
  646. stationId
  647. },
  648. this
  649. )
  650. .then(() => {
  651. next(null);
  652. })
  653. .catch(next);
  654. }
  655. );
  656. }
  657. ],
  658. err => {
  659. if (err) reject(err);
  660. else resolve();
  661. }
  662. );
  663. });
  664. }
  665. /**
  666. * Process vote to skips for a station
  667. *
  668. * @param {object} payload - object that contains the payload
  669. * @param {string} payload.stationId - the id of the station to process
  670. * @returns {Promise} - returns a promise (resolve, reject)
  671. */
  672. PROCESS_VOTE_SKIPS(payload) {
  673. return new Promise((resolve, reject) => {
  674. StationsModule.log("INFO", `Processing vote skips for station ${payload.stationId}.`);
  675. async.waterfall(
  676. [
  677. next => {
  678. StationsModule.runJob(
  679. "GET_STATION",
  680. {
  681. stationId: payload.stationId
  682. },
  683. this
  684. )
  685. .then(station => next(null, station))
  686. .catch(next);
  687. },
  688. (station, next) => {
  689. if (!station) return next("Station not found.");
  690. return next(null, station);
  691. },
  692. (station, next) => {
  693. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }, this)
  694. .then(sockets => next(null, station, sockets))
  695. .catch(next);
  696. },
  697. (station, sockets, next) => {
  698. const skipVotes = station.currentSong.skipVotes.length;
  699. let shouldSkip = false;
  700. if (sockets.length <= skipVotes) {
  701. if (!station.paused) shouldSkip = true;
  702. return next(null, shouldSkip);
  703. }
  704. const users = [];
  705. return async.each(
  706. sockets,
  707. (socketId, next) => {
  708. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  709. .then(socket => {
  710. if (socket && socket.session && socket.session.userId) {
  711. if (!users.includes(socket.session.userId))
  712. users.push(socket.session.userId);
  713. }
  714. return next();
  715. })
  716. .catch(next);
  717. },
  718. err => {
  719. if (err) return next(err);
  720. if (!station.paused && users.length <= skipVotes) shouldSkip = true;
  721. return next(null, shouldSkip);
  722. }
  723. );
  724. },
  725. (shouldSkip, next) => {
  726. if (shouldSkip)
  727. StationsModule.runJob(
  728. "SKIP_STATION",
  729. {
  730. stationId: payload.stationId,
  731. natural: false
  732. },
  733. this
  734. )
  735. .then(() => next())
  736. .catch(next);
  737. else next();
  738. }
  739. ],
  740. err => {
  741. if (err) reject(err);
  742. else resolve();
  743. }
  744. );
  745. });
  746. }
  747. /**
  748. * Skips a station
  749. *
  750. * @param {object} payload - object that contains the payload
  751. * @param {string} payload.stationId - the id of the station to skip
  752. * @param {string} payload.natural - whether to skip naturally or forcefully
  753. * @returns {Promise} - returns a promise (resolve, reject)
  754. */
  755. SKIP_STATION(payload) {
  756. return new Promise((resolve, reject) => {
  757. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  758. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  759. async.waterfall(
  760. [
  761. // Clears up any existing timers that would skip the station if the song ends
  762. next => {
  763. NotificationsModule.runJob("UNSCHEDULE", {
  764. name: `stations.nextSong?id=${payload.stationId}`
  765. })
  766. .then(() => {
  767. next();
  768. })
  769. .catch(next);
  770. },
  771. // Gets the station object
  772. next => {
  773. StationsModule.runJob(
  774. "GET_STATION",
  775. {
  776. stationId: payload.stationId
  777. },
  778. this
  779. )
  780. .then(station => next(null, station))
  781. .catch(next);
  782. },
  783. (station, next) => {
  784. if (!station) return next("Station not found.");
  785. if (station.autofill.enabled)
  786. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  787. .then(() => next(null, station))
  788. .catch(err => {
  789. if (
  790. err === "Autofill is disabled in this station" ||
  791. err === "Autofill limit reached"
  792. )
  793. return next(null, station);
  794. return next(err);
  795. });
  796. return next(null, station);
  797. },
  798. (station, next) => {
  799. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  800. .then(response => {
  801. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  802. .then(() => {
  803. next(null, response.song, station);
  804. })
  805. .catch(next);
  806. })
  807. .catch(err => {
  808. if (err === "No songs available.") next(null, null, station);
  809. else next(err);
  810. });
  811. },
  812. (song, station, next) => {
  813. const $set = {};
  814. if (song === null) $set.currentSong = null;
  815. else {
  816. $set.currentSong = {
  817. _id: song._id,
  818. youtubeId: song.youtubeId,
  819. title: song.title,
  820. artists: song.artists,
  821. duration: song.duration,
  822. skipDuration: song.skipDuration,
  823. thumbnail: song.thumbnail,
  824. requestedAt: song.requestedAt,
  825. requestedBy: song.requestedBy,
  826. verified: song.verified
  827. };
  828. }
  829. $set.startedAt = Date.now();
  830. $set.timePaused = 0;
  831. if (station.paused) $set.pausedAt = Date.now();
  832. next(null, $set, station);
  833. },
  834. ($set, station, next) => {
  835. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  836. if (err) return next(err);
  837. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  838. .then(station => {
  839. next(null, station);
  840. })
  841. .catch(next);
  842. });
  843. },
  844. (station, next) => {
  845. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  846. station.currentSong.skipVotes = 0;
  847. }
  848. next(null, station);
  849. },
  850. (station, next) => {
  851. if (station.autofill.enabled)
  852. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  853. .then(() => next(null, station))
  854. .catch(err => {
  855. if (
  856. err === "Autofill is disabled in this station" ||
  857. err === "Autofill limit reached"
  858. )
  859. return next(null, station);
  860. return next(err);
  861. });
  862. return next(null, station);
  863. },
  864. (station, next) =>
  865. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  866. .then(station => {
  867. CacheModule.runJob("PUB", {
  868. channel: "station.queueUpdate",
  869. value: payload.stationId
  870. })
  871. .then()
  872. .catch();
  873. next(null, station);
  874. })
  875. .catch(next)
  876. ],
  877. async (err, station) => {
  878. if (err === "Autofill limit reached") return resolve({ station });
  879. if (err) {
  880. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  881. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  882. return reject(new Error(err));
  883. }
  884. // TODO Pub/Sub this
  885. const { currentSong } = station;
  886. WSModule.runJob("EMIT_TO_ROOM", {
  887. room: `station.${station._id}`,
  888. args: [
  889. "event:station.nextSong",
  890. {
  891. data: {
  892. currentSong,
  893. startedAt: station.startedAt,
  894. paused: station.paused,
  895. timePaused: 0,
  896. natural: payload.natural
  897. }
  898. }
  899. ]
  900. });
  901. WSModule.runJob("EMIT_TO_ROOM", {
  902. room: `manage-station.${station._id}`,
  903. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  904. });
  905. if (station.privacy === "public")
  906. WSModule.runJob("EMIT_TO_ROOM", {
  907. room: "home",
  908. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  909. });
  910. else {
  911. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  912. sockets.forEach(async socketId => {
  913. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  914. if (!socket) return;
  915. const { session } = socket;
  916. if (session.sessionId) {
  917. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  918. session => {
  919. if (session) {
  920. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  921. userModel.findOne({ _id: session.userId }, (err, user) => {
  922. if (!err && user) {
  923. if (user.role === "admin")
  924. socket.dispatch("event:station.nextSong", {
  925. data: {
  926. stationId: station._id,
  927. currentSong
  928. }
  929. });
  930. else if (
  931. station.type === "community" &&
  932. station.owner === session.userId
  933. )
  934. socket.dispatch("event:station.nextSong", {
  935. data: {
  936. stationId: station._id,
  937. currentSong
  938. }
  939. });
  940. }
  941. });
  942. });
  943. }
  944. }
  945. );
  946. }
  947. });
  948. }
  949. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  950. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  951. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  952. sockets,
  953. room: `song.${station.currentSong.youtubeId}`
  954. });
  955. if (!station.paused) {
  956. NotificationsModule.runJob("SCHEDULE", {
  957. name: `stations.nextSong?id=${station._id}`,
  958. time: station.currentSong.duration * 1000,
  959. station
  960. });
  961. }
  962. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  963. });
  964. return resolve({ station });
  965. }
  966. );
  967. });
  968. }
  969. /**
  970. * Checks if a user can view/access a station
  971. *
  972. * @param {object} payload - object that contains the payload
  973. * @param {object} payload.station - the station object of the station in question
  974. * @param {string} payload.userId - the id of the user in question
  975. * @returns {Promise} - returns a promise (resolve, reject)
  976. */
  977. CAN_USER_VIEW_STATION(payload) {
  978. return new Promise((resolve, reject) => {
  979. async.waterfall(
  980. [
  981. next => {
  982. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  983. return next(true);
  984. if (!payload.userId) return next("Not allowed");
  985. return next();
  986. },
  987. next => {
  988. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  989. userModel.findOne({ _id: payload.userId }, next);
  990. });
  991. },
  992. (user, next) => {
  993. if (!user) return next("Not allowed");
  994. if (user.role === "admin" || payload.station.owner === payload.userId) return next(true);
  995. if (payload.station.type === "official") return next("Not allowed");
  996. return next("Not allowed");
  997. }
  998. ],
  999. async errOrResult => {
  1000. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1001. errOrResult = await UtilsModule.runJob(
  1002. "GET_ERROR",
  1003. {
  1004. error: errOrResult
  1005. },
  1006. this
  1007. );
  1008. reject(new Error(errOrResult));
  1009. } else {
  1010. resolve(errOrResult === true);
  1011. }
  1012. }
  1013. );
  1014. });
  1015. }
  1016. /**
  1017. * Checks if a user has favorited a station or not
  1018. *
  1019. * @param {object} payload - object that contains the payload
  1020. * @param {object} payload.stationId - the id of the station in question
  1021. * @param {string} payload.userId - the id of the user in question
  1022. * @returns {Promise} - returns a promise (resolve, reject)
  1023. */
  1024. HAS_USER_FAVORITED_STATION(payload) {
  1025. return new Promise((resolve, reject) => {
  1026. async.waterfall(
  1027. [
  1028. next => {
  1029. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1030. userModel.findOne({ _id: payload.userId }, next);
  1031. });
  1032. },
  1033. (user, next) => {
  1034. if (!user) return next("User not found.");
  1035. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1036. return next(null, false);
  1037. }
  1038. ],
  1039. async (err, isStationFavorited) => {
  1040. if (err && err !== true) {
  1041. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1042. return reject(new Error(err));
  1043. }
  1044. return resolve(isStationFavorited);
  1045. }
  1046. );
  1047. });
  1048. }
  1049. /**
  1050. * Returns a list of sockets in a room that can and can't know about a station
  1051. *
  1052. * @param {object} payload - the payload object
  1053. * @param {object} payload.station - the station object
  1054. * @param {string} payload.room - the websockets room to get the sockets from
  1055. * @returns {Promise} - returns a promise (resolve, reject)
  1056. */
  1057. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1058. return new Promise((resolve, reject) => {
  1059. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1060. .then(socketIds => {
  1061. const sockets = [];
  1062. async.eachLimit(
  1063. socketIds,
  1064. 1,
  1065. (socketId, next) => {
  1066. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1067. .then(socket => {
  1068. if (socket) sockets.push(socket);
  1069. next();
  1070. })
  1071. .catch(err => {
  1072. reject(err);
  1073. });
  1074. },
  1075. err => {
  1076. if (err) reject(err);
  1077. else {
  1078. let socketsThatCan = [];
  1079. const socketsThatCannot = [];
  1080. if (payload.station.privacy === "public") {
  1081. socketsThatCan = sockets;
  1082. resolve({ socketsThatCan, socketsThatCannot });
  1083. } else {
  1084. async.eachLimit(
  1085. sockets,
  1086. 1,
  1087. (socket, next) => {
  1088. const { session } = socket;
  1089. async.waterfall(
  1090. [
  1091. next => {
  1092. if (!session.sessionId) next("No session id");
  1093. else next();
  1094. },
  1095. next => {
  1096. CacheModule.runJob(
  1097. "HGET",
  1098. {
  1099. table: "sessions",
  1100. key: session.sessionId
  1101. },
  1102. this
  1103. )
  1104. .then(response => {
  1105. next(null, response);
  1106. })
  1107. .catch(next);
  1108. },
  1109. (session, next) => {
  1110. if (!session) next("No session");
  1111. else {
  1112. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1113. .then(userModel => {
  1114. next(null, userModel);
  1115. })
  1116. .catch(next);
  1117. }
  1118. },
  1119. (userModel, next) => {
  1120. if (!userModel) next("No user model");
  1121. else
  1122. userModel.findOne(
  1123. {
  1124. _id: session.userId
  1125. },
  1126. next
  1127. );
  1128. },
  1129. (user, next) => {
  1130. if (!user) next("No user found");
  1131. else if (user.role === "admin") {
  1132. socketsThatCan.push(socket);
  1133. next();
  1134. } else if (
  1135. payload.station.type === "community" &&
  1136. payload.station.owner === session.userId
  1137. ) {
  1138. socketsThatCan.push(socket);
  1139. next();
  1140. }
  1141. }
  1142. ],
  1143. err => {
  1144. if (err) socketsThatCannot.push(socket);
  1145. next();
  1146. }
  1147. );
  1148. },
  1149. err => {
  1150. if (err) reject(err);
  1151. else resolve({ socketsThatCan, socketsThatCannot });
  1152. }
  1153. );
  1154. }
  1155. }
  1156. }
  1157. );
  1158. })
  1159. .catch(reject);
  1160. });
  1161. }
  1162. /**
  1163. * Adds a playlist to autofill a station
  1164. *
  1165. * @param {object} payload - object that contains the payload
  1166. * @param {object} payload.stationId - the id of the station
  1167. * @param {object} payload.playlistId - the id of the playlist
  1168. * @returns {Promise} - returns a promise (resolve, reject)
  1169. */
  1170. AUTOFILL_PLAYLIST(payload) {
  1171. return new Promise((resolve, reject) => {
  1172. async.waterfall(
  1173. [
  1174. next => {
  1175. if (!payload.stationId) next("Please specify a station id");
  1176. else if (!payload.playlistId) next("Please specify a playlist id");
  1177. else next();
  1178. },
  1179. next => {
  1180. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1181. .then(station => {
  1182. next(null, station);
  1183. })
  1184. .catch(next);
  1185. },
  1186. (station, next) => {
  1187. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1188. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1189. next("This playlist is already autofilling");
  1190. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1191. next("This playlist is currently blacklisted");
  1192. else
  1193. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1194. .then(() => {
  1195. next(null);
  1196. })
  1197. .catch(next);
  1198. },
  1199. next => {
  1200. StationsModule.stationModel.updateOne(
  1201. { _id: payload.stationId },
  1202. { $push: { "autofill.playlists": payload.playlistId } },
  1203. next
  1204. );
  1205. },
  1206. (res, next) => {
  1207. StationsModule.runJob(
  1208. "UPDATE_STATION",
  1209. {
  1210. stationId: payload.stationId
  1211. },
  1212. this
  1213. )
  1214. .then(() => {
  1215. next();
  1216. })
  1217. .catch(next);
  1218. }
  1219. ],
  1220. async err => {
  1221. if (err && err !== true) {
  1222. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1223. return reject(new Error(err));
  1224. }
  1225. return resolve();
  1226. }
  1227. );
  1228. });
  1229. }
  1230. /**
  1231. * Removes a playlist from autofill
  1232. *
  1233. * @param {object} payload - object that contains the payload
  1234. * @param {object} payload.stationId - the id of the station
  1235. * @param {object} payload.playlistId - the id of the playlist
  1236. * @returns {Promise} - returns a promise (resolve, reject)
  1237. */
  1238. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1239. return new Promise((resolve, reject) => {
  1240. async.waterfall(
  1241. [
  1242. next => {
  1243. if (!payload.stationId) next("Please specify a station id");
  1244. else if (!payload.playlistId) next("Please specify a playlist id");
  1245. else next();
  1246. },
  1247. next => {
  1248. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1249. .then(station => {
  1250. next(null, station);
  1251. })
  1252. .catch(next);
  1253. },
  1254. (station, next) => {
  1255. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1256. next("This playlist isn't autofilling");
  1257. else next();
  1258. },
  1259. next => {
  1260. StationsModule.stationModel.updateOne(
  1261. { _id: payload.stationId },
  1262. { $pull: { "autofill.playlists": payload.playlistId } },
  1263. next
  1264. );
  1265. },
  1266. (res, next) => {
  1267. StationsModule.runJob(
  1268. "UPDATE_STATION",
  1269. {
  1270. stationId: payload.stationId
  1271. },
  1272. this
  1273. )
  1274. .then(() => {
  1275. next();
  1276. })
  1277. .catch(next);
  1278. }
  1279. ],
  1280. async err => {
  1281. if (err && err !== true) {
  1282. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1283. return reject(new Error(err));
  1284. }
  1285. return resolve();
  1286. }
  1287. );
  1288. });
  1289. }
  1290. /**
  1291. * Add a playlist to station blacklist
  1292. *
  1293. * @param {object} payload - object that contains the payload
  1294. * @param {object} payload.stationId - the id of the station
  1295. * @param {object} payload.playlistId - the id of the playlist
  1296. * @returns {Promise} - returns a promise (resolve, reject)
  1297. */
  1298. BLACKLIST_PLAYLIST(payload) {
  1299. return new Promise((resolve, reject) => {
  1300. async.waterfall(
  1301. [
  1302. next => {
  1303. if (!payload.stationId) next("Please specify a station id");
  1304. else if (!payload.playlistId) next("Please specify a playlist id");
  1305. else next();
  1306. },
  1307. next => {
  1308. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1309. .then(station => {
  1310. next(null, station);
  1311. })
  1312. .catch(next);
  1313. },
  1314. (station, next) => {
  1315. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1316. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1317. next("This playlist is already blacklisted");
  1318. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1319. next(
  1320. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1321. );
  1322. else
  1323. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1324. .then(() => {
  1325. next(null);
  1326. })
  1327. .catch(next);
  1328. },
  1329. next => {
  1330. StationsModule.stationModel.updateOne(
  1331. { _id: payload.stationId },
  1332. { $push: { blacklist: payload.playlistId } },
  1333. next
  1334. );
  1335. },
  1336. (res, next) => {
  1337. StationsModule.runJob(
  1338. "UPDATE_STATION",
  1339. {
  1340. stationId: payload.stationId
  1341. },
  1342. this
  1343. )
  1344. .then(() => {
  1345. next();
  1346. })
  1347. .catch(next);
  1348. }
  1349. ],
  1350. async err => {
  1351. if (err && err !== true) {
  1352. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1353. return reject(new Error(err));
  1354. }
  1355. return resolve();
  1356. }
  1357. );
  1358. });
  1359. }
  1360. /**
  1361. * Remove a playlist from station blacklist
  1362. *
  1363. * @param {object} payload - object that contains the payload
  1364. * @param {object} payload.stationId - the id of the station
  1365. * @param {object} payload.playlistId - the id of the playlist
  1366. * @returns {Promise} - returns a promise (resolve, reject)
  1367. */
  1368. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1369. return new Promise((resolve, reject) => {
  1370. async.waterfall(
  1371. [
  1372. next => {
  1373. if (!payload.stationId) next("Please specify a station id");
  1374. else if (!payload.playlistId) next("Please specify a playlist id");
  1375. else next();
  1376. },
  1377. next => {
  1378. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1379. .then(station => {
  1380. next(null, station);
  1381. })
  1382. .catch(next);
  1383. },
  1384. (station, next) => {
  1385. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1386. next("This playlist isn't blacklisted");
  1387. else next();
  1388. },
  1389. next => {
  1390. StationsModule.stationModel.updateOne(
  1391. { _id: payload.stationId },
  1392. { $pull: { blacklist: payload.playlistId } },
  1393. next
  1394. );
  1395. },
  1396. (res, next) => {
  1397. StationsModule.runJob(
  1398. "UPDATE_STATION",
  1399. {
  1400. stationId: payload.stationId
  1401. },
  1402. this
  1403. )
  1404. .then(() => {
  1405. next();
  1406. })
  1407. .catch(next);
  1408. }
  1409. ],
  1410. async err => {
  1411. if (err && err !== true) {
  1412. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1413. return reject(new Error(err));
  1414. }
  1415. return resolve();
  1416. }
  1417. );
  1418. });
  1419. }
  1420. /**
  1421. * Removes autofilled or blacklisted playlist from a station
  1422. *
  1423. * @param {object} payload - object that contains the payload
  1424. * @param {string} payload.playlistId - the playlist id
  1425. * @returns {Promise} - returns promise (reject, resolve)
  1426. */
  1427. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1428. return new Promise((resolve, reject) => {
  1429. async.waterfall(
  1430. [
  1431. next => {
  1432. if (!payload.playlistId) next("Please specify a playlist id");
  1433. else next();
  1434. },
  1435. next => {
  1436. StationsModule.stationModel.updateMany(
  1437. {
  1438. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1439. },
  1440. {
  1441. $pull: {
  1442. "autofill.playlists": payload.playlistId,
  1443. blacklist: payload.playlistId
  1444. }
  1445. },
  1446. err => {
  1447. if (err) next(err);
  1448. else next();
  1449. }
  1450. );
  1451. }
  1452. ],
  1453. async err => {
  1454. if (err && err !== true) {
  1455. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1456. return reject(new Error(err));
  1457. }
  1458. return resolve();
  1459. }
  1460. );
  1461. });
  1462. }
  1463. /**
  1464. * Gets stations that autofill or blacklist a specific playlist
  1465. *
  1466. * @param {object} payload - object that contains the payload
  1467. * @param {string} payload.playlistId - the playlist id
  1468. * @returns {Promise} - returns promise (reject, resolve)
  1469. */
  1470. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1471. return new Promise((resolve, reject) => {
  1472. DBModule.runJob(
  1473. "GET_MODEL",
  1474. {
  1475. modelName: "station"
  1476. },
  1477. this
  1478. ).then(stationModel => {
  1479. stationModel.find(
  1480. {
  1481. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1482. },
  1483. (err, stations) => {
  1484. if (err) reject(err);
  1485. else resolve({ stationIds: stations.map(station => station._id) });
  1486. }
  1487. );
  1488. });
  1489. });
  1490. }
  1491. /**
  1492. * Clears every queue
  1493. *
  1494. * @returns {Promise} - returns a promise (resolve, reject)
  1495. */
  1496. CLEAR_EVERY_STATION_QUEUE() {
  1497. return new Promise((resolve, reject) => {
  1498. async.waterfall(
  1499. [
  1500. next => {
  1501. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1502. if (err) next(err);
  1503. else {
  1504. StationsModule.stationModel.find({}, (err, stations) => {
  1505. if (err) next(err);
  1506. else {
  1507. async.eachLimit(
  1508. stations,
  1509. 1,
  1510. (station, next) => {
  1511. this.publishProgress({
  1512. status: "update",
  1513. message: `Updating station "${station._id}"`
  1514. });
  1515. StationsModule.runJob("UPDATE_STATION", {
  1516. stationId: station._id
  1517. })
  1518. .then(() => next())
  1519. .catch(next);
  1520. CacheModule.runJob("PUB", {
  1521. channel: "station.queueUpdate",
  1522. value: station._id
  1523. })
  1524. .then()
  1525. .catch();
  1526. },
  1527. next
  1528. );
  1529. }
  1530. });
  1531. }
  1532. });
  1533. }
  1534. ],
  1535. err => {
  1536. if (err) reject(err);
  1537. else resolve();
  1538. }
  1539. );
  1540. });
  1541. }
  1542. /**
  1543. * Resets a station queue
  1544. *
  1545. * @param {object} payload - object that contains the payload
  1546. * @param {string} payload.stationId - the station id
  1547. * @returns {Promise} - returns a promise (resolve, reject)
  1548. */
  1549. RESET_QUEUE(payload) {
  1550. return new Promise((resolve, reject) => {
  1551. async.waterfall(
  1552. [
  1553. next => {
  1554. StationsModule.runJob(
  1555. "AUTOFILL_STATION",
  1556. { stationId: payload.stationId, ignoreExistingQueue: true },
  1557. this
  1558. )
  1559. .then(() => {
  1560. CacheModule.runJob("PUB", {
  1561. channel: "station.queueUpdate",
  1562. value: payload.stationId
  1563. })
  1564. .then()
  1565. .catch();
  1566. next();
  1567. })
  1568. .catch(err => {
  1569. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1570. StationsModule.stationModel
  1571. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1572. .then(() => next())
  1573. .catch(next);
  1574. else next(err);
  1575. });
  1576. },
  1577. next => {
  1578. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1579. .then(() => next())
  1580. .catch(next);
  1581. },
  1582. next => {
  1583. CacheModule.runJob("PUB", {
  1584. channel: "station.queueUpdate",
  1585. value: payload.stationId
  1586. })
  1587. .then(() => next())
  1588. .catch(next);
  1589. }
  1590. ],
  1591. err => {
  1592. if (err) reject(err);
  1593. else resolve();
  1594. }
  1595. );
  1596. });
  1597. }
  1598. /**
  1599. * Add to a station queue
  1600. *
  1601. * @param {object} payload - object that contains the payload
  1602. * @param {string} payload.stationId - the station id
  1603. * @param {string} payload.youtubeId - the youtube id
  1604. * @param {string} payload.requestUser - the requesting user id
  1605. * @returns {Promise} - returns a promise (resolve, reject)
  1606. */
  1607. ADD_TO_QUEUE(payload) {
  1608. return new Promise((resolve, reject) => {
  1609. const { stationId, youtubeId, requestUser } = payload;
  1610. async.waterfall(
  1611. [
  1612. next => {
  1613. StationsModule.runJob("GET_STATION", { stationId }, this)
  1614. .then(station => {
  1615. next(null, station);
  1616. })
  1617. .catch(next);
  1618. },
  1619. (station, next) => {
  1620. if (!station) return next("Station not found.");
  1621. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1622. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1623. return next("That song is currently playing.");
  1624. if (station.queue.find(song => song.youtubeId === youtubeId))
  1625. return next("That song is already in the queue.");
  1626. return next(null, station);
  1627. },
  1628. (station, next) => {
  1629. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1630. .then(response => {
  1631. const { song } = response;
  1632. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1633. next(
  1634. null,
  1635. {
  1636. _id,
  1637. youtubeId,
  1638. title,
  1639. skipDuration,
  1640. artists,
  1641. thumbnail,
  1642. duration,
  1643. verified
  1644. },
  1645. station
  1646. );
  1647. })
  1648. .catch(next);
  1649. },
  1650. (song, station, next) => {
  1651. const blacklist = [];
  1652. async.eachLimit(
  1653. station.blacklist,
  1654. 1,
  1655. (playlistId, next) => {
  1656. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1657. .then(playlist => {
  1658. blacklist.push(playlist);
  1659. next();
  1660. })
  1661. .catch(next);
  1662. },
  1663. err => {
  1664. next(err, song, station, blacklist);
  1665. }
  1666. );
  1667. },
  1668. (song, station, blacklist, next) => {
  1669. const blacklistedSongs = blacklist
  1670. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1671. .reduce(
  1672. (items, item) =>
  1673. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1674. []
  1675. );
  1676. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1677. next("That song is in an blacklisted playlist and cannot be played.");
  1678. else next(null, song, station);
  1679. },
  1680. (song, station, next) => {
  1681. song.requestedBy = requestUser;
  1682. song.requestedAt = Date.now();
  1683. if (station.queue.length === 0) return next(null, song);
  1684. if (
  1685. requestUser &&
  1686. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1687. station.requests.limit
  1688. )
  1689. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1690. return next(null, song);
  1691. },
  1692. // (song, station, next) => {
  1693. // song.requestedBy = session.userId;
  1694. // song.requestedAt = Date.now();
  1695. // let totalDuration = 0;
  1696. // station.queue.forEach(song => {
  1697. // totalDuration += song.duration;
  1698. // });
  1699. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1700. // return next(null, song, station);
  1701. // },
  1702. // (song, station, next) => {
  1703. // if (station.queue.length === 0) return next(null, song, station);
  1704. // let totalDuration = 0;
  1705. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1706. // station.queue.forEach(song => {
  1707. // if (userId === song.requestedBy) {
  1708. // totalDuration += song.duration;
  1709. // }
  1710. // });
  1711. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1712. // return next(null, song, station);
  1713. // },
  1714. // (song, station, next) => {
  1715. // if (station.queue.length === 0) return next(null, song);
  1716. // let totalSongs = 0;
  1717. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1718. // station.queue.forEach(song => {
  1719. // if (userId === song.requestedBy) {
  1720. // totalSongs += 1;
  1721. // }
  1722. // });
  1723. // if (totalSongs <= 2) return next(null, song);
  1724. // if (totalSongs > 3)
  1725. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1726. // if (
  1727. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1728. // station.queue[station.queue.length - 3] !== userId
  1729. // )
  1730. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1731. // return next(null, song);
  1732. // },
  1733. (song, next) => {
  1734. StationsModule.stationModel.updateOne(
  1735. { _id: stationId },
  1736. { $push: { queue: song } },
  1737. { runValidators: true },
  1738. next
  1739. );
  1740. },
  1741. (res, next) => {
  1742. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1743. .then(() => next())
  1744. .catch(next);
  1745. },
  1746. next => {
  1747. CacheModule.runJob(
  1748. "PUB",
  1749. {
  1750. channel: "station.queueUpdate",
  1751. value: stationId
  1752. },
  1753. this
  1754. )
  1755. .then(() => next())
  1756. .catch(next);
  1757. }
  1758. ],
  1759. err => {
  1760. if (err) reject(err);
  1761. else resolve();
  1762. }
  1763. );
  1764. });
  1765. }
  1766. /**
  1767. * Remove from a station queue
  1768. *
  1769. * @param {object} payload - object that contains the payload
  1770. * @param {string} payload.stationId - the station id
  1771. * @param {string} payload.youtubeId - the youtube id
  1772. * @returns {Promise} - returns a promise (resolve, reject)
  1773. */
  1774. REMOVE_FROM_QUEUE(payload) {
  1775. return new Promise((resolve, reject) => {
  1776. const { stationId, youtubeId } = payload;
  1777. async.waterfall(
  1778. [
  1779. next => {
  1780. StationsModule.runJob("GET_STATION", { stationId }, this)
  1781. .then(station => {
  1782. next(null, station);
  1783. })
  1784. .catch(next);
  1785. },
  1786. (station, next) => {
  1787. if (!station) return next("Station not found.");
  1788. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1789. return next("That song is not currently in the queue.");
  1790. return StationsModule.stationModel.updateOne(
  1791. { _id: stationId },
  1792. { $pull: { queue: { youtubeId } } },
  1793. next
  1794. );
  1795. },
  1796. (res, next) => {
  1797. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1798. .then(station => {
  1799. if (station.autofill.enabled)
  1800. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1801. .then(() => next())
  1802. .catch(err => {
  1803. if (
  1804. err === "Autofill is disabled in this station" ||
  1805. err === "Autofill limit reached"
  1806. )
  1807. return next();
  1808. return next(err);
  1809. });
  1810. else next();
  1811. })
  1812. .catch(next);
  1813. },
  1814. next =>
  1815. CacheModule.runJob(
  1816. "PUB",
  1817. {
  1818. channel: "station.queueUpdate",
  1819. value: stationId
  1820. },
  1821. this
  1822. )
  1823. .then(() => next())
  1824. .catch(next)
  1825. ],
  1826. err => {
  1827. if (err) reject(err);
  1828. else resolve();
  1829. }
  1830. );
  1831. });
  1832. }
  1833. }
  1834. export default new _StationsModule();