stations.js 60 KB

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