stations.js 54 KB

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