stations.js 58 KB

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