stations.js 62 KB

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