stations.js 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  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 =
  699. station.currentSong && station.currentSong.skipVotes
  700. ? station.currentSong.skipVotes.length
  701. : 0;
  702. let shouldSkip = false;
  703. if (skipVotes === 0) {
  704. if (!station.paused && !station.currentSong && station.queue.length > 0) shouldSkip = true;
  705. return next(null, shouldSkip);
  706. }
  707. const users = [];
  708. return async.each(
  709. sockets,
  710. (socketId, next) => {
  711. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  712. .then(socket => {
  713. if (socket && socket.session && socket.session.userId) {
  714. if (!users.includes(socket.session.userId))
  715. users.push(socket.session.userId);
  716. }
  717. return next();
  718. })
  719. .catch(next);
  720. },
  721. err => {
  722. if (err) return next(err);
  723. if (!station.paused && users.length <= skipVotes) shouldSkip = true;
  724. return next(null, shouldSkip);
  725. }
  726. );
  727. },
  728. (shouldSkip, next) => {
  729. if (shouldSkip)
  730. StationsModule.runJob(
  731. "SKIP_STATION",
  732. {
  733. stationId: payload.stationId,
  734. natural: false
  735. },
  736. this
  737. )
  738. .then(() => next())
  739. .catch(next);
  740. else next();
  741. }
  742. ],
  743. err => {
  744. if (err) reject(err);
  745. else resolve();
  746. }
  747. );
  748. });
  749. }
  750. /**
  751. * Skips a station
  752. *
  753. * @param {object} payload - object that contains the payload
  754. * @param {string} payload.stationId - the id of the station to skip
  755. * @param {string} payload.natural - whether to skip naturally or forcefully
  756. * @returns {Promise} - returns a promise (resolve, reject)
  757. */
  758. SKIP_STATION(payload) {
  759. return new Promise((resolve, reject) => {
  760. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  761. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  762. async.waterfall(
  763. [
  764. // Clears up any existing timers that would skip the station if the song ends
  765. next => {
  766. NotificationsModule.runJob("UNSCHEDULE", {
  767. name: `stations.nextSong?id=${payload.stationId}`
  768. })
  769. .then(() => {
  770. next();
  771. })
  772. .catch(next);
  773. },
  774. // Gets the station object
  775. next => {
  776. StationsModule.runJob(
  777. "GET_STATION",
  778. {
  779. stationId: payload.stationId
  780. },
  781. this
  782. )
  783. .then(station => next(null, station))
  784. .catch(next);
  785. },
  786. (station, next) => {
  787. if (!station) return next("Station not found.");
  788. if (station.autofill.enabled)
  789. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  790. .then(() => next(null, station))
  791. .catch(err => {
  792. if (
  793. err === "Autofill is disabled in this station" ||
  794. err === "Autofill limit reached"
  795. )
  796. return next(null, station);
  797. return next(err);
  798. });
  799. return next(null, station);
  800. },
  801. (station, next) => {
  802. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  803. .then(response => {
  804. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  805. .then(() => {
  806. next(null, response.song, station);
  807. })
  808. .catch(next);
  809. })
  810. .catch(err => {
  811. if (err === "No songs available.") next(null, null, station);
  812. else next(err);
  813. });
  814. },
  815. (song, station, next) => {
  816. const $set = {};
  817. if (song === null) $set.currentSong = null;
  818. else {
  819. $set.currentSong = {
  820. _id: song._id,
  821. youtubeId: song.youtubeId,
  822. title: song.title,
  823. artists: song.artists,
  824. duration: song.duration,
  825. skipDuration: song.skipDuration,
  826. thumbnail: song.thumbnail,
  827. requestedAt: song.requestedAt,
  828. requestedBy: song.requestedBy,
  829. verified: song.verified
  830. };
  831. }
  832. $set.startedAt = Date.now();
  833. $set.timePaused = 0;
  834. if (station.paused) $set.pausedAt = Date.now();
  835. next(null, $set, station);
  836. },
  837. ($set, station, next) => {
  838. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  839. if (err) return next(err);
  840. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  841. .then(station => {
  842. next(null, station);
  843. })
  844. .catch(next);
  845. });
  846. },
  847. (station, next) => {
  848. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  849. station.currentSong.skipVotes = 0;
  850. }
  851. next(null, station);
  852. },
  853. (station, next) => {
  854. if (station.autofill.enabled)
  855. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  856. .then(() => next(null, station))
  857. .catch(err => {
  858. if (
  859. err === "Autofill is disabled in this station" ||
  860. err === "Autofill limit reached"
  861. )
  862. return next(null, station);
  863. return next(err);
  864. });
  865. return next(null, station);
  866. },
  867. (station, next) =>
  868. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  869. .then(station => {
  870. CacheModule.runJob("PUB", {
  871. channel: "station.queueUpdate",
  872. value: payload.stationId
  873. })
  874. .then()
  875. .catch();
  876. next(null, station);
  877. })
  878. .catch(next)
  879. ],
  880. async (err, station) => {
  881. if (err === "Autofill limit reached") return resolve({ station });
  882. if (err) {
  883. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  884. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  885. return reject(new Error(err));
  886. }
  887. // TODO Pub/Sub this
  888. const { currentSong } = station;
  889. WSModule.runJob("EMIT_TO_ROOM", {
  890. room: `station.${station._id}`,
  891. args: [
  892. "event:station.nextSong",
  893. {
  894. data: {
  895. currentSong,
  896. startedAt: station.startedAt,
  897. paused: station.paused,
  898. timePaused: 0,
  899. natural: payload.natural
  900. }
  901. }
  902. ]
  903. });
  904. WSModule.runJob("EMIT_TO_ROOM", {
  905. room: `manage-station.${station._id}`,
  906. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  907. });
  908. if (station.privacy === "public")
  909. WSModule.runJob("EMIT_TO_ROOM", {
  910. room: "home",
  911. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  912. });
  913. else {
  914. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  915. sockets.forEach(async socketId => {
  916. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  917. if (!socket) return;
  918. const { session } = socket;
  919. if (session.sessionId) {
  920. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  921. session => {
  922. if (session) {
  923. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  924. userModel.findOne({ _id: session.userId }, (err, user) => {
  925. if (!err && user) {
  926. if (user.role === "admin")
  927. socket.dispatch("event:station.nextSong", {
  928. data: {
  929. stationId: station._id,
  930. currentSong
  931. }
  932. });
  933. else if (
  934. station.type === "community" &&
  935. station.owner === session.userId
  936. )
  937. socket.dispatch("event:station.nextSong", {
  938. data: {
  939. stationId: station._id,
  940. currentSong
  941. }
  942. });
  943. }
  944. });
  945. });
  946. }
  947. }
  948. );
  949. }
  950. });
  951. }
  952. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  953. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  954. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  955. sockets,
  956. room: `song.${station.currentSong.youtubeId}`
  957. });
  958. if (!station.paused) {
  959. NotificationsModule.runJob("SCHEDULE", {
  960. name: `stations.nextSong?id=${station._id}`,
  961. time: station.currentSong.duration * 1000,
  962. station
  963. });
  964. }
  965. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  966. });
  967. return resolve({ station });
  968. }
  969. );
  970. });
  971. }
  972. /**
  973. * Checks if a user can view/access a station
  974. *
  975. * @param {object} payload - object that contains the payload
  976. * @param {object} payload.station - the station object of the station in question
  977. * @param {string} payload.userId - the id of the user in question
  978. * @returns {Promise} - returns a promise (resolve, reject)
  979. */
  980. CAN_USER_VIEW_STATION(payload) {
  981. return new Promise((resolve, reject) => {
  982. async.waterfall(
  983. [
  984. next => {
  985. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  986. return next(true);
  987. if (!payload.userId) return next("Not allowed");
  988. return next();
  989. },
  990. next => {
  991. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  992. userModel.findOne({ _id: payload.userId }, next);
  993. });
  994. },
  995. (user, next) => {
  996. if (!user) return next("Not allowed");
  997. if (user.role === "admin" || payload.station.owner === payload.userId) return next(true);
  998. if (payload.station.type === "official") return next("Not allowed");
  999. return next("Not allowed");
  1000. }
  1001. ],
  1002. async errOrResult => {
  1003. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1004. errOrResult = await UtilsModule.runJob(
  1005. "GET_ERROR",
  1006. {
  1007. error: errOrResult
  1008. },
  1009. this
  1010. );
  1011. reject(new Error(errOrResult));
  1012. } else {
  1013. resolve(errOrResult === true);
  1014. }
  1015. }
  1016. );
  1017. });
  1018. }
  1019. /**
  1020. * Checks if a user has favorited a station or not
  1021. *
  1022. * @param {object} payload - object that contains the payload
  1023. * @param {object} payload.stationId - the id of the station in question
  1024. * @param {string} payload.userId - the id of the user in question
  1025. * @returns {Promise} - returns a promise (resolve, reject)
  1026. */
  1027. HAS_USER_FAVORITED_STATION(payload) {
  1028. return new Promise((resolve, reject) => {
  1029. async.waterfall(
  1030. [
  1031. next => {
  1032. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1033. userModel.findOne({ _id: payload.userId }, next);
  1034. });
  1035. },
  1036. (user, next) => {
  1037. if (!user) return next("User not found.");
  1038. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1039. return next(null, false);
  1040. }
  1041. ],
  1042. async (err, isStationFavorited) => {
  1043. if (err && err !== true) {
  1044. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1045. return reject(new Error(err));
  1046. }
  1047. return resolve(isStationFavorited);
  1048. }
  1049. );
  1050. });
  1051. }
  1052. /**
  1053. * Returns a list of sockets in a room that can and can't know about a station
  1054. *
  1055. * @param {object} payload - the payload object
  1056. * @param {object} payload.station - the station object
  1057. * @param {string} payload.room - the websockets room to get the sockets from
  1058. * @returns {Promise} - returns a promise (resolve, reject)
  1059. */
  1060. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1061. return new Promise((resolve, reject) => {
  1062. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1063. .then(socketIds => {
  1064. const sockets = [];
  1065. async.eachLimit(
  1066. socketIds,
  1067. 1,
  1068. (socketId, next) => {
  1069. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1070. .then(socket => {
  1071. if (socket) sockets.push(socket);
  1072. next();
  1073. })
  1074. .catch(err => {
  1075. reject(err);
  1076. });
  1077. },
  1078. err => {
  1079. if (err) reject(err);
  1080. else {
  1081. let socketsThatCan = [];
  1082. const socketsThatCannot = [];
  1083. if (payload.station.privacy === "public") {
  1084. socketsThatCan = sockets;
  1085. resolve({ socketsThatCan, socketsThatCannot });
  1086. } else {
  1087. async.eachLimit(
  1088. sockets,
  1089. 1,
  1090. (socket, next) => {
  1091. const { session } = socket;
  1092. async.waterfall(
  1093. [
  1094. next => {
  1095. if (!session.sessionId) next("No session id");
  1096. else next();
  1097. },
  1098. next => {
  1099. CacheModule.runJob(
  1100. "HGET",
  1101. {
  1102. table: "sessions",
  1103. key: session.sessionId
  1104. },
  1105. this
  1106. )
  1107. .then(response => {
  1108. next(null, response);
  1109. })
  1110. .catch(next);
  1111. },
  1112. (session, next) => {
  1113. if (!session) next("No session");
  1114. else {
  1115. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1116. .then(userModel => {
  1117. next(null, userModel);
  1118. })
  1119. .catch(next);
  1120. }
  1121. },
  1122. (userModel, next) => {
  1123. if (!userModel) next("No user model");
  1124. else
  1125. userModel.findOne(
  1126. {
  1127. _id: session.userId
  1128. },
  1129. next
  1130. );
  1131. },
  1132. (user, next) => {
  1133. if (!user) next("No user found");
  1134. else if (user.role === "admin") {
  1135. socketsThatCan.push(socket);
  1136. next();
  1137. } else if (
  1138. payload.station.type === "community" &&
  1139. payload.station.owner === session.userId
  1140. ) {
  1141. socketsThatCan.push(socket);
  1142. next();
  1143. }
  1144. }
  1145. ],
  1146. err => {
  1147. if (err) socketsThatCannot.push(socket);
  1148. next();
  1149. }
  1150. );
  1151. },
  1152. err => {
  1153. if (err) reject(err);
  1154. else resolve({ socketsThatCan, socketsThatCannot });
  1155. }
  1156. );
  1157. }
  1158. }
  1159. }
  1160. );
  1161. })
  1162. .catch(reject);
  1163. });
  1164. }
  1165. /**
  1166. * Adds a playlist to autofill a station
  1167. *
  1168. * @param {object} payload - object that contains the payload
  1169. * @param {object} payload.stationId - the id of the station
  1170. * @param {object} payload.playlistId - the id of the playlist
  1171. * @returns {Promise} - returns a promise (resolve, reject)
  1172. */
  1173. AUTOFILL_PLAYLIST(payload) {
  1174. return new Promise((resolve, reject) => {
  1175. async.waterfall(
  1176. [
  1177. next => {
  1178. if (!payload.stationId) next("Please specify a station id");
  1179. else if (!payload.playlistId) next("Please specify a playlist id");
  1180. else next();
  1181. },
  1182. next => {
  1183. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1184. .then(station => {
  1185. next(null, station);
  1186. })
  1187. .catch(next);
  1188. },
  1189. (station, next) => {
  1190. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1191. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1192. next("This playlist is already autofilling");
  1193. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1194. next("This playlist is currently blacklisted");
  1195. else
  1196. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1197. .then(() => {
  1198. next(null);
  1199. })
  1200. .catch(next);
  1201. },
  1202. next => {
  1203. StationsModule.stationModel.updateOne(
  1204. { _id: payload.stationId },
  1205. { $push: { "autofill.playlists": payload.playlistId } },
  1206. next
  1207. );
  1208. },
  1209. (res, next) => {
  1210. StationsModule.runJob(
  1211. "UPDATE_STATION",
  1212. {
  1213. stationId: payload.stationId
  1214. },
  1215. this
  1216. )
  1217. .then(() => {
  1218. next();
  1219. })
  1220. .catch(next);
  1221. }
  1222. ],
  1223. async err => {
  1224. if (err && err !== true) {
  1225. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1226. return reject(new Error(err));
  1227. }
  1228. return resolve();
  1229. }
  1230. );
  1231. });
  1232. }
  1233. /**
  1234. * Removes a playlist from autofill
  1235. *
  1236. * @param {object} payload - object that contains the payload
  1237. * @param {object} payload.stationId - the id of the station
  1238. * @param {object} payload.playlistId - the id of the playlist
  1239. * @returns {Promise} - returns a promise (resolve, reject)
  1240. */
  1241. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1242. return new Promise((resolve, reject) => {
  1243. async.waterfall(
  1244. [
  1245. next => {
  1246. if (!payload.stationId) next("Please specify a station id");
  1247. else if (!payload.playlistId) next("Please specify a playlist id");
  1248. else next();
  1249. },
  1250. next => {
  1251. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1252. .then(station => {
  1253. next(null, station);
  1254. })
  1255. .catch(next);
  1256. },
  1257. (station, next) => {
  1258. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1259. next("This playlist isn't autofilling");
  1260. else next();
  1261. },
  1262. next => {
  1263. StationsModule.stationModel.updateOne(
  1264. { _id: payload.stationId },
  1265. { $pull: { "autofill.playlists": payload.playlistId } },
  1266. next
  1267. );
  1268. },
  1269. (res, next) => {
  1270. StationsModule.runJob(
  1271. "UPDATE_STATION",
  1272. {
  1273. stationId: payload.stationId
  1274. },
  1275. this
  1276. )
  1277. .then(() => {
  1278. next();
  1279. })
  1280. .catch(next);
  1281. }
  1282. ],
  1283. async err => {
  1284. if (err && err !== true) {
  1285. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1286. return reject(new Error(err));
  1287. }
  1288. return resolve();
  1289. }
  1290. );
  1291. });
  1292. }
  1293. /**
  1294. * Add a playlist to station blacklist
  1295. *
  1296. * @param {object} payload - object that contains the payload
  1297. * @param {object} payload.stationId - the id of the station
  1298. * @param {object} payload.playlistId - the id of the playlist
  1299. * @returns {Promise} - returns a promise (resolve, reject)
  1300. */
  1301. BLACKLIST_PLAYLIST(payload) {
  1302. return new Promise((resolve, reject) => {
  1303. async.waterfall(
  1304. [
  1305. next => {
  1306. if (!payload.stationId) next("Please specify a station id");
  1307. else if (!payload.playlistId) next("Please specify a playlist id");
  1308. else next();
  1309. },
  1310. next => {
  1311. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1312. .then(station => {
  1313. next(null, station);
  1314. })
  1315. .catch(next);
  1316. },
  1317. (station, next) => {
  1318. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1319. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1320. next("This playlist is already blacklisted");
  1321. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1322. next(
  1323. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1324. );
  1325. else
  1326. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1327. .then(() => {
  1328. next(null);
  1329. })
  1330. .catch(next);
  1331. },
  1332. next => {
  1333. StationsModule.stationModel.updateOne(
  1334. { _id: payload.stationId },
  1335. { $push: { blacklist: payload.playlistId } },
  1336. next
  1337. );
  1338. },
  1339. (res, next) => {
  1340. StationsModule.runJob(
  1341. "UPDATE_STATION",
  1342. {
  1343. stationId: payload.stationId
  1344. },
  1345. this
  1346. )
  1347. .then(() => {
  1348. next();
  1349. })
  1350. .catch(next);
  1351. }
  1352. ],
  1353. async err => {
  1354. if (err && err !== true) {
  1355. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1356. return reject(new Error(err));
  1357. }
  1358. return resolve();
  1359. }
  1360. );
  1361. });
  1362. }
  1363. /**
  1364. * Remove a playlist from station blacklist
  1365. *
  1366. * @param {object} payload - object that contains the payload
  1367. * @param {object} payload.stationId - the id of the station
  1368. * @param {object} payload.playlistId - the id of the playlist
  1369. * @returns {Promise} - returns a promise (resolve, reject)
  1370. */
  1371. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1372. return new Promise((resolve, reject) => {
  1373. async.waterfall(
  1374. [
  1375. next => {
  1376. if (!payload.stationId) next("Please specify a station id");
  1377. else if (!payload.playlistId) next("Please specify a playlist id");
  1378. else next();
  1379. },
  1380. next => {
  1381. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1382. .then(station => {
  1383. next(null, station);
  1384. })
  1385. .catch(next);
  1386. },
  1387. (station, next) => {
  1388. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1389. next("This playlist isn't blacklisted");
  1390. else next();
  1391. },
  1392. next => {
  1393. StationsModule.stationModel.updateOne(
  1394. { _id: payload.stationId },
  1395. { $pull: { blacklist: payload.playlistId } },
  1396. next
  1397. );
  1398. },
  1399. (res, next) => {
  1400. StationsModule.runJob(
  1401. "UPDATE_STATION",
  1402. {
  1403. stationId: payload.stationId
  1404. },
  1405. this
  1406. )
  1407. .then(() => {
  1408. next();
  1409. })
  1410. .catch(next);
  1411. }
  1412. ],
  1413. async err => {
  1414. if (err && err !== true) {
  1415. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1416. return reject(new Error(err));
  1417. }
  1418. return resolve();
  1419. }
  1420. );
  1421. });
  1422. }
  1423. /**
  1424. * Removes autofilled or blacklisted playlist from a station
  1425. *
  1426. * @param {object} payload - object that contains the payload
  1427. * @param {string} payload.playlistId - the playlist id
  1428. * @returns {Promise} - returns promise (reject, resolve)
  1429. */
  1430. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1431. return new Promise((resolve, reject) => {
  1432. async.waterfall(
  1433. [
  1434. next => {
  1435. if (!payload.playlistId) next("Please specify a playlist id");
  1436. else next();
  1437. },
  1438. next => {
  1439. StationsModule.stationModel.updateMany(
  1440. {
  1441. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1442. },
  1443. {
  1444. $pull: {
  1445. "autofill.playlists": payload.playlistId,
  1446. blacklist: payload.playlistId
  1447. }
  1448. },
  1449. err => {
  1450. if (err) next(err);
  1451. else next();
  1452. }
  1453. );
  1454. }
  1455. ],
  1456. async err => {
  1457. if (err && err !== true) {
  1458. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1459. return reject(new Error(err));
  1460. }
  1461. return resolve();
  1462. }
  1463. );
  1464. });
  1465. }
  1466. /**
  1467. * Gets stations that autofill or blacklist a specific playlist
  1468. *
  1469. * @param {object} payload - object that contains the payload
  1470. * @param {string} payload.playlistId - the playlist id
  1471. * @returns {Promise} - returns promise (reject, resolve)
  1472. */
  1473. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1474. return new Promise((resolve, reject) => {
  1475. DBModule.runJob(
  1476. "GET_MODEL",
  1477. {
  1478. modelName: "station"
  1479. },
  1480. this
  1481. ).then(stationModel => {
  1482. stationModel.find(
  1483. {
  1484. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1485. },
  1486. (err, stations) => {
  1487. if (err) reject(err);
  1488. else resolve({ stationIds: stations.map(station => station._id) });
  1489. }
  1490. );
  1491. });
  1492. });
  1493. }
  1494. /**
  1495. * Clears every queue
  1496. *
  1497. * @returns {Promise} - returns a promise (resolve, reject)
  1498. */
  1499. CLEAR_EVERY_STATION_QUEUE() {
  1500. return new Promise((resolve, reject) => {
  1501. async.waterfall(
  1502. [
  1503. next => {
  1504. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1505. if (err) next(err);
  1506. else {
  1507. StationsModule.stationModel.find({}, (err, stations) => {
  1508. if (err) next(err);
  1509. else {
  1510. async.eachLimit(
  1511. stations,
  1512. 1,
  1513. (station, next) => {
  1514. this.publishProgress({
  1515. status: "update",
  1516. message: `Updating station "${station._id}"`
  1517. });
  1518. StationsModule.runJob("UPDATE_STATION", {
  1519. stationId: station._id
  1520. })
  1521. .then(() => next())
  1522. .catch(next);
  1523. CacheModule.runJob("PUB", {
  1524. channel: "station.queueUpdate",
  1525. value: station._id
  1526. })
  1527. .then()
  1528. .catch();
  1529. },
  1530. next
  1531. );
  1532. }
  1533. });
  1534. }
  1535. });
  1536. }
  1537. ],
  1538. err => {
  1539. if (err) reject(err);
  1540. else resolve();
  1541. }
  1542. );
  1543. });
  1544. }
  1545. /**
  1546. * Resets a station queue
  1547. *
  1548. * @param {object} payload - object that contains the payload
  1549. * @param {string} payload.stationId - the station id
  1550. * @returns {Promise} - returns a promise (resolve, reject)
  1551. */
  1552. RESET_QUEUE(payload) {
  1553. return new Promise((resolve, reject) => {
  1554. async.waterfall(
  1555. [
  1556. next => {
  1557. StationsModule.runJob(
  1558. "AUTOFILL_STATION",
  1559. { stationId: payload.stationId, ignoreExistingQueue: true },
  1560. this
  1561. )
  1562. .then(() => {
  1563. CacheModule.runJob("PUB", {
  1564. channel: "station.queueUpdate",
  1565. value: payload.stationId
  1566. })
  1567. .then()
  1568. .catch();
  1569. next();
  1570. })
  1571. .catch(err => {
  1572. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1573. StationsModule.stationModel
  1574. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1575. .then(() => next())
  1576. .catch(next);
  1577. else next(err);
  1578. });
  1579. },
  1580. next => {
  1581. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1582. .then(() => next())
  1583. .catch(next);
  1584. },
  1585. next => {
  1586. CacheModule.runJob("PUB", {
  1587. channel: "station.queueUpdate",
  1588. value: payload.stationId
  1589. })
  1590. .then(() => next())
  1591. .catch(next);
  1592. }
  1593. ],
  1594. err => {
  1595. if (err) reject(err);
  1596. else resolve();
  1597. }
  1598. );
  1599. });
  1600. }
  1601. /**
  1602. * Add to a station queue
  1603. *
  1604. * @param {object} payload - object that contains the payload
  1605. * @param {string} payload.stationId - the station id
  1606. * @param {string} payload.youtubeId - the youtube id
  1607. * @param {string} payload.requestUser - the requesting user id
  1608. * @returns {Promise} - returns a promise (resolve, reject)
  1609. */
  1610. ADD_TO_QUEUE(payload) {
  1611. return new Promise((resolve, reject) => {
  1612. const { stationId, youtubeId, requestUser } = payload;
  1613. async.waterfall(
  1614. [
  1615. next => {
  1616. StationsModule.runJob("GET_STATION", { stationId }, this)
  1617. .then(station => {
  1618. next(null, station);
  1619. })
  1620. .catch(next);
  1621. },
  1622. (station, next) => {
  1623. if (!station) return next("Station not found.");
  1624. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1625. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1626. return next("That song is currently playing.");
  1627. if (station.queue.find(song => song.youtubeId === youtubeId))
  1628. return next("That song is already in the queue.");
  1629. return next(null, station);
  1630. },
  1631. (station, next) => {
  1632. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1633. .then(response => {
  1634. const { song } = response;
  1635. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1636. next(
  1637. null,
  1638. {
  1639. _id,
  1640. youtubeId,
  1641. title,
  1642. skipDuration,
  1643. artists,
  1644. thumbnail,
  1645. duration,
  1646. verified
  1647. },
  1648. station
  1649. );
  1650. })
  1651. .catch(next);
  1652. },
  1653. (song, station, next) => {
  1654. const blacklist = [];
  1655. async.eachLimit(
  1656. station.blacklist,
  1657. 1,
  1658. (playlistId, next) => {
  1659. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1660. .then(playlist => {
  1661. blacklist.push(playlist);
  1662. next();
  1663. })
  1664. .catch(next);
  1665. },
  1666. err => {
  1667. next(err, song, station, blacklist);
  1668. }
  1669. );
  1670. },
  1671. (song, station, blacklist, next) => {
  1672. const blacklistedSongs = blacklist
  1673. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1674. .reduce(
  1675. (items, item) =>
  1676. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1677. []
  1678. );
  1679. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1680. next("That song is in an blacklisted playlist and cannot be played.");
  1681. else next(null, song, station);
  1682. },
  1683. (song, station, next) => {
  1684. song.requestedBy = requestUser;
  1685. song.requestedAt = Date.now();
  1686. if (station.queue.length === 0) return next(null, song);
  1687. if (
  1688. requestUser &&
  1689. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1690. station.requests.limit
  1691. )
  1692. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1693. return next(null, song);
  1694. },
  1695. // (song, station, next) => {
  1696. // song.requestedBy = session.userId;
  1697. // song.requestedAt = Date.now();
  1698. // let totalDuration = 0;
  1699. // station.queue.forEach(song => {
  1700. // totalDuration += song.duration;
  1701. // });
  1702. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1703. // return next(null, song, station);
  1704. // },
  1705. // (song, station, next) => {
  1706. // if (station.queue.length === 0) return next(null, song, station);
  1707. // let totalDuration = 0;
  1708. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1709. // station.queue.forEach(song => {
  1710. // if (userId === song.requestedBy) {
  1711. // totalDuration += song.duration;
  1712. // }
  1713. // });
  1714. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1715. // return next(null, song, station);
  1716. // },
  1717. // (song, station, next) => {
  1718. // if (station.queue.length === 0) return next(null, song);
  1719. // let totalSongs = 0;
  1720. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1721. // station.queue.forEach(song => {
  1722. // if (userId === song.requestedBy) {
  1723. // totalSongs += 1;
  1724. // }
  1725. // });
  1726. // if (totalSongs <= 2) return next(null, song);
  1727. // if (totalSongs > 3)
  1728. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1729. // if (
  1730. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1731. // station.queue[station.queue.length - 3] !== userId
  1732. // )
  1733. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1734. // return next(null, song);
  1735. // },
  1736. (song, next) => {
  1737. StationsModule.stationModel.updateOne(
  1738. { _id: stationId },
  1739. { $push: { queue: song } },
  1740. { runValidators: true },
  1741. next
  1742. );
  1743. },
  1744. (res, next) => {
  1745. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1746. .then(() => next())
  1747. .catch(next);
  1748. },
  1749. next => {
  1750. CacheModule.runJob(
  1751. "PUB",
  1752. {
  1753. channel: "station.queueUpdate",
  1754. value: stationId
  1755. },
  1756. this
  1757. )
  1758. .then(() => next())
  1759. .catch(next);
  1760. }
  1761. ],
  1762. err => {
  1763. if (err) reject(err);
  1764. else resolve();
  1765. }
  1766. );
  1767. });
  1768. }
  1769. /**
  1770. * Remove from a station queue
  1771. *
  1772. * @param {object} payload - object that contains the payload
  1773. * @param {string} payload.stationId - the station id
  1774. * @param {string} payload.youtubeId - the youtube id
  1775. * @returns {Promise} - returns a promise (resolve, reject)
  1776. */
  1777. REMOVE_FROM_QUEUE(payload) {
  1778. return new Promise((resolve, reject) => {
  1779. const { stationId, youtubeId } = payload;
  1780. async.waterfall(
  1781. [
  1782. next => {
  1783. StationsModule.runJob("GET_STATION", { stationId }, this)
  1784. .then(station => {
  1785. next(null, station);
  1786. })
  1787. .catch(next);
  1788. },
  1789. (station, next) => {
  1790. if (!station) return next("Station not found.");
  1791. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1792. return next("That song is not currently in the queue.");
  1793. return StationsModule.stationModel.updateOne(
  1794. { _id: stationId },
  1795. { $pull: { queue: { youtubeId } } },
  1796. next
  1797. );
  1798. },
  1799. (res, next) => {
  1800. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1801. .then(station => {
  1802. if (station.autofill.enabled)
  1803. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1804. .then(() => next())
  1805. .catch(err => {
  1806. if (
  1807. err === "Autofill is disabled in this station" ||
  1808. err === "Autofill limit reached"
  1809. )
  1810. return next();
  1811. return next(err);
  1812. });
  1813. else next();
  1814. })
  1815. .catch(next);
  1816. },
  1817. next =>
  1818. CacheModule.runJob(
  1819. "PUB",
  1820. {
  1821. channel: "station.queueUpdate",
  1822. value: stationId
  1823. },
  1824. this
  1825. )
  1826. .then(() => next())
  1827. .catch(next)
  1828. ],
  1829. err => {
  1830. if (err) reject(err);
  1831. else resolve();
  1832. }
  1833. );
  1834. });
  1835. }
  1836. }
  1837. export default new _StationsModule();