stations.js 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347
  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 currentMediaSources = station.queue.map(song => song.mediaSource);
  539. const songsToAdd = [];
  540. let lastSongAdded = null;
  541. if (station.currentSong && station.currentSong.mediaSource)
  542. currentMediaSources.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. currentMediaSources = [...currentMediaSources, ...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 => currentMediaSources.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 (songsToAdd.length >= songsStillNeeded) return false;
  593. // Skip Spotify songs
  594. if (song.mediaSource.startsWith("spotify:")) return true;
  595. // Skip SoundCloud songs if Soundcloud isn't enabled
  596. if (song.mediaSource.startsWith("soundcloud:") && !config.get("experimental.soundcloud"))
  597. return true;
  598. // Skip songs already in songsToAdd
  599. if (songsToAdd.find(songToAdd => songToAdd.mediaSource === song.mediaSource)) return true;
  600. // Skips songs already in the queue
  601. if (currentMediaSources.indexOf(song.mediaSource) !== -1) return true;
  602. lastSongAdded = song;
  603. songsToAdd.push(song);
  604. return true;
  605. });
  606. let { currentSongIndex } = station;
  607. if (station.autofill.mode === "sequential" && lastSongAdded) {
  608. const indexOfLastSong = _playlistSongs
  609. .map(song => song.mediaSource)
  610. .indexOf(lastSongAdded.mediaSource);
  611. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  612. }
  613. return { currentSongs, songsToAdd, currentSongIndex };
  614. },
  615. ({ currentSongs, songsToAdd, currentSongIndex }, next) => {
  616. const songs = [];
  617. async.eachLimit(
  618. songsToAdd.map(song => song.mediaSource),
  619. 2,
  620. (mediaSource, next) => {
  621. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  622. .then(response => {
  623. const { song } = response;
  624. const { _id, title, artists, thumbnail, duration, skipDuration, verified } =
  625. song;
  626. songs.push({
  627. _id,
  628. mediaSource,
  629. title,
  630. artists,
  631. thumbnail,
  632. duration,
  633. skipDuration,
  634. verified
  635. });
  636. next();
  637. })
  638. .catch(next);
  639. },
  640. err => {
  641. if (err) next(err);
  642. else {
  643. const newSongsToAdd = songsToAdd.map(song =>
  644. songs.find(newSong => newSong.mediaSource === song.mediaSource)
  645. );
  646. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  647. }
  648. }
  649. );
  650. },
  651. (currentSongs, songsToAdd, currentSongIndex, next) => {
  652. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  653. if (!song._id) song._id = null;
  654. if (!song.requestedAt) song.requestedAt = Date.now();
  655. if (!song.requestedType) song.requestedType = "autofill";
  656. return song;
  657. });
  658. next(null, newPlaylist, currentSongIndex);
  659. },
  660. (newPlaylist, currentSongIndex, next) => {
  661. StationsModule.stationModel.updateOne(
  662. { _id: stationId },
  663. { $set: { queue: newPlaylist, currentSongIndex } },
  664. { runValidators: true },
  665. err => {
  666. if (err) next(err);
  667. else
  668. StationsModule.runJob(
  669. "UPDATE_STATION",
  670. {
  671. stationId
  672. },
  673. this
  674. )
  675. .then(() => {
  676. next(null);
  677. })
  678. .catch(next);
  679. }
  680. );
  681. }
  682. ],
  683. err => {
  684. if (err) reject(err);
  685. else resolve();
  686. }
  687. );
  688. });
  689. }
  690. /**
  691. * Gets next station song
  692. *
  693. * @param {object} payload - object that contains the payload
  694. * @param {string} payload.stationId - the id of the station
  695. * @returns {Promise} - returns a promise (resolve, reject)
  696. */
  697. GET_NEXT_STATION_SONG(payload) {
  698. return new Promise((resolve, reject) => {
  699. const { stationId } = payload;
  700. async.waterfall(
  701. [
  702. next => {
  703. StationsModule.runJob("GET_STATION", { stationId }, this)
  704. .then(station => {
  705. next(null, station);
  706. })
  707. .catch(next);
  708. },
  709. (station, next) => {
  710. if (station.queue.length === 0) next("No songs available.");
  711. else {
  712. next(null, station.queue[0]);
  713. }
  714. },
  715. (queueSong, next) => {
  716. MediaModule.runJob(
  717. "GET_MEDIA",
  718. {
  719. mediaSource: queueSong.mediaSource
  720. },
  721. this
  722. )
  723. .then(response => {
  724. const { song } = response;
  725. const {
  726. _id,
  727. mediaSource,
  728. title,
  729. skipDuration,
  730. artists,
  731. thumbnail,
  732. duration,
  733. verified
  734. } = song;
  735. next(null, {
  736. _id,
  737. mediaSource,
  738. title,
  739. skipDuration,
  740. artists,
  741. thumbnail,
  742. duration,
  743. verified,
  744. requestedAt: queueSong.requestedAt,
  745. requestedBy: queueSong.requestedBy,
  746. requestedType: queueSong.requestedType,
  747. likes: song.likes || 0,
  748. dislikes: song.dislikes || 0
  749. });
  750. })
  751. .catch(next);
  752. }
  753. ],
  754. (err, song) => {
  755. if (err) reject(err);
  756. else resolve({ song });
  757. }
  758. );
  759. });
  760. }
  761. /**
  762. * Removes first station queue song
  763. *
  764. * @param {object} payload - object that contains the payload
  765. * @param {string} payload.stationId - the id of the station
  766. * @returns {Promise} - returns a promise (resolve, reject)
  767. */
  768. REMOVE_FIRST_QUEUE_SONG(payload) {
  769. return new Promise((resolve, reject) => {
  770. const { stationId } = payload;
  771. async.waterfall(
  772. [
  773. next => {
  774. StationsModule.stationModel.updateOne(
  775. { _id: stationId },
  776. { $pop: { queue: -1 } },
  777. { runValidators: true },
  778. err => {
  779. if (err) next(err);
  780. else
  781. StationsModule.runJob(
  782. "UPDATE_STATION",
  783. {
  784. stationId
  785. },
  786. this
  787. )
  788. .then(() => {
  789. next(null);
  790. })
  791. .catch(next);
  792. }
  793. );
  794. }
  795. ],
  796. err => {
  797. if (err) reject(err);
  798. else resolve();
  799. }
  800. );
  801. });
  802. }
  803. /**
  804. * Process vote to skips for a station
  805. *
  806. * @param {object} payload - object that contains the payload
  807. * @param {string} payload.stationId - the id of the station to process
  808. * @returns {Promise} - returns a promise (resolve, reject)
  809. */
  810. PROCESS_SKIP_VOTES(payload) {
  811. return new Promise((resolve, reject) => {
  812. StationsModule.log("INFO", `Processing skip votes for station ${payload.stationId}.`);
  813. async.waterfall(
  814. [
  815. next => {
  816. StationsModule.runJob(
  817. "GET_STATION",
  818. {
  819. stationId: payload.stationId
  820. },
  821. this
  822. )
  823. .then(station => next(null, station))
  824. .catch(next);
  825. },
  826. (station, next) => {
  827. if (!station) return next("Station not found.");
  828. return next(null, station);
  829. },
  830. (station, next) => {
  831. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }, this)
  832. .then(sockets => next(null, station, sockets))
  833. .catch(next);
  834. },
  835. (station, sockets, next) => {
  836. const skipVotes =
  837. station.currentSong && station.currentSong.skipVotes
  838. ? station.currentSong.skipVotes.length
  839. : 0;
  840. let shouldSkip = false;
  841. if (skipVotes === 0) {
  842. if (!station.paused && !station.currentSong && station.queue.length > 0) shouldSkip = true;
  843. return next(null, shouldSkip);
  844. }
  845. const users = [];
  846. return async.each(
  847. sockets,
  848. (socketId, next) => {
  849. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  850. .then(socket => {
  851. if (socket && socket.session && socket.session.userId) {
  852. if (!users.includes(socket.session.userId))
  853. users.push(socket.session.userId);
  854. }
  855. return next();
  856. })
  857. .catch(next);
  858. },
  859. err => {
  860. if (err) return next(err);
  861. if (
  862. !station.paused &&
  863. Math.min(skipVotes, users.length) / users.length >= station.skipVoteThreshold / 100
  864. )
  865. shouldSkip = true;
  866. return next(null, shouldSkip);
  867. }
  868. );
  869. },
  870. (shouldSkip, next) => {
  871. if (shouldSkip)
  872. StationsModule.runJob(
  873. "SKIP_STATION",
  874. {
  875. stationId: payload.stationId,
  876. natural: false,
  877. skipReason: "vote_skip"
  878. },
  879. this
  880. )
  881. .then(() => next())
  882. .catch(next);
  883. else next();
  884. }
  885. ],
  886. err => {
  887. if (err) reject(err);
  888. else resolve();
  889. }
  890. );
  891. });
  892. }
  893. /**
  894. * Creates a station history item
  895. *
  896. * @param {object} payload - object containing the payload
  897. * @param {string} payload.stationId - the station id to create the history item for
  898. * @param {string} payload.currentSong - the song to create the history item for
  899. * @param {string} payload.skipReason - the reason the song was skipped
  900. * @param {string} payload.skippedAt - the date/time the song was skipped
  901. * @returns {Promise} - returns a promise (resolve, reject)
  902. */
  903. async ADD_STATION_HISTORY_ITEM(payload) {
  904. if (!config.get("experimental.station_history")) throw new Error("Station history is not enabled");
  905. const { stationId, currentSong, skipReason, skippedAt } = payload;
  906. let document = await StationsModule.stationHistoryModel.create({
  907. stationId,
  908. type: "song_played",
  909. payload: {
  910. song: currentSong,
  911. skippedAt,
  912. skipReason
  913. }
  914. });
  915. if (!document) return;
  916. document = document._doc;
  917. delete document.__v;
  918. delete document.documentVersion;
  919. WSModule.runJob("EMIT_TO_ROOM", {
  920. room: `station.${stationId}`,
  921. args: ["event:station.history.new", { data: { historyItem: document } }]
  922. });
  923. WSModule.runJob("EMIT_TO_ROOM", {
  924. room: `manage-station.${stationId}`,
  925. args: ["event:manageStation.history.new", { data: { stationId, historyItem: document } }]
  926. });
  927. }
  928. /**
  929. * Skips a station
  930. *
  931. * @param {object} payload - object that contains the payload
  932. * @param {string} payload.stationId - the id of the station to skip
  933. * @param {string} payload.natural - whether to skip naturally or forcefully
  934. * @param {string} payload.skipReason - if it was skipped via force skip or via vote skipping or if it was natural
  935. * @returns {Promise} - returns a promise (resolve, reject)
  936. */
  937. SKIP_STATION(payload) {
  938. return new Promise((resolve, reject) => {
  939. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  940. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  941. async.waterfall(
  942. [
  943. // Clears up any existing timers that would skip the station if the song ends
  944. next => {
  945. NotificationsModule.runJob("UNSCHEDULE", {
  946. name: `stations.nextSong?id=${payload.stationId}`
  947. })
  948. .then(() => {
  949. next();
  950. })
  951. .catch(next);
  952. },
  953. // Gets the station object
  954. next => {
  955. StationsModule.runJob(
  956. "GET_STATION",
  957. {
  958. stationId: payload.stationId
  959. },
  960. this
  961. )
  962. .then(station => next(null, station))
  963. .catch(next);
  964. },
  965. (station, next) => {
  966. if (!station) return next("Station not found.");
  967. if (!config.get("experimental.station_history")) return next(null, station);
  968. const { currentSong } = station;
  969. if (!currentSong || !currentSong.mediaSource) return next(null, station);
  970. const stationId = station._id;
  971. const skippedAt = new Date();
  972. const { skipReason } = payload;
  973. return StationsModule.runJob(
  974. "ADD_STATION_HISTORY_ITEM",
  975. {
  976. stationId,
  977. currentSong,
  978. skippedAt,
  979. skipReason
  980. },
  981. this
  982. ).finally(() => {
  983. next(null, station);
  984. });
  985. },
  986. (station, next) => {
  987. if (station.autofill.enabled)
  988. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  989. .then(() => next(null, station))
  990. .catch(err => {
  991. if (
  992. err === "Autofill is disabled in this station" ||
  993. err === "Autofill limit reached"
  994. )
  995. return next(null, station);
  996. return next(err);
  997. });
  998. return next(null, station);
  999. },
  1000. (station, next) => {
  1001. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  1002. .then(response => {
  1003. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  1004. .then(() => {
  1005. next(null, response.song, station);
  1006. })
  1007. .catch(next);
  1008. })
  1009. .catch(err => {
  1010. if (err === "No songs available.") next(null, null, station);
  1011. else next(err);
  1012. });
  1013. },
  1014. async (song, station) => {
  1015. const $set = {};
  1016. if (song === null) $set.currentSong = null;
  1017. else {
  1018. // Block for experiment: queue_autofill_skip_last_x_played
  1019. if (config.has(`experimental.queue_autofill_skip_last_x_played.${payload.stationId}`)) {
  1020. const redisList = `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`;
  1021. const maxListLength = Number(
  1022. config.get(`experimental.queue_autofill_skip_last_x_played.${payload.stationId}`)
  1023. );
  1024. // Add mediaSource to list for this station in Redis list
  1025. await CacheModule.runJob(
  1026. "LPUSH",
  1027. {
  1028. key: `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`,
  1029. value: song.mediaSource
  1030. },
  1031. this
  1032. );
  1033. const currentListLength = await CacheModule.runJob("LLEN", { key: redisList }, this);
  1034. // Removes oldest mediaSource from list for this station in Redis list
  1035. if (currentListLength > maxListLength) {
  1036. const amount = currentListLength - maxListLength;
  1037. const promises = Array.from({ length: amount }).map(() =>
  1038. CacheModule.runJob(
  1039. "RPOP",
  1040. {
  1041. key: `experimental:queue_autofill_skip_last_x_played:${payload.stationId}`
  1042. },
  1043. this
  1044. )
  1045. );
  1046. await Promise.all(promises);
  1047. }
  1048. }
  1049. $set.currentSong = {
  1050. _id: song._id,
  1051. mediaSource: song.mediaSource,
  1052. title: song.title,
  1053. artists: song.artists,
  1054. duration: song.duration,
  1055. skipDuration: song.skipDuration,
  1056. thumbnail: song.thumbnail,
  1057. requestedAt: song.requestedAt,
  1058. requestedBy: song.requestedBy,
  1059. requestedType: song.requestedType,
  1060. verified: song.verified
  1061. };
  1062. }
  1063. $set.startedAt = Date.now();
  1064. $set.timePaused = 0;
  1065. if (station.paused) $set.pausedAt = Date.now();
  1066. return { $set, station };
  1067. },
  1068. ({ $set, station }, next) => {
  1069. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  1070. if (err) return next(err);
  1071. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  1072. .then(station => {
  1073. next(null, station);
  1074. })
  1075. .catch(next);
  1076. });
  1077. },
  1078. (station, next) => {
  1079. if (station.currentSong !== null && station.currentSong.mediaSource !== undefined) {
  1080. station.currentSong.skipVotes = 0;
  1081. }
  1082. next(null, station);
  1083. },
  1084. (station, next) => {
  1085. if (station.autofill.enabled)
  1086. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  1087. .then(() => next(null, station))
  1088. .catch(err => {
  1089. if (
  1090. err === "Autofill is disabled in this station" ||
  1091. err === "Autofill limit reached"
  1092. )
  1093. return next(null, station);
  1094. return next(err);
  1095. });
  1096. return next(null, station);
  1097. },
  1098. (station, next) =>
  1099. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  1100. .then(station => {
  1101. CacheModule.runJob("PUB", {
  1102. channel: "station.queueUpdate",
  1103. value: payload.stationId
  1104. })
  1105. .then()
  1106. .catch();
  1107. next(null, station);
  1108. })
  1109. .catch(next)
  1110. ],
  1111. async (err, station) => {
  1112. if (err === "Autofill limit reached") return resolve({ station });
  1113. if (err) {
  1114. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1115. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  1116. return reject(new Error(err));
  1117. }
  1118. // TODO Pub/Sub this
  1119. const { currentSong } = station;
  1120. WSModule.runJob("EMIT_TO_ROOM", {
  1121. room: `station.${station._id}`,
  1122. args: [
  1123. "event:station.nextSong",
  1124. {
  1125. data: {
  1126. currentSong,
  1127. startedAt: station.startedAt,
  1128. paused: station.paused,
  1129. timePaused: 0,
  1130. natural: payload.natural
  1131. }
  1132. }
  1133. ]
  1134. });
  1135. WSModule.runJob("EMIT_TO_ROOM", {
  1136. room: `manage-station.${station._id}`,
  1137. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  1138. });
  1139. if (station.privacy === "public")
  1140. WSModule.runJob("EMIT_TO_ROOM", {
  1141. room: "home",
  1142. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  1143. });
  1144. else {
  1145. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  1146. sockets.forEach(async socketId => {
  1147. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  1148. if (!socket) return;
  1149. const { session } = socket;
  1150. if (session.sessionId) {
  1151. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  1152. session => {
  1153. const dispatchNextSong = () => {
  1154. socket.dispatch("event:station.nextSong", {
  1155. data: {
  1156. stationId: station._id,
  1157. currentSong
  1158. }
  1159. });
  1160. };
  1161. hasPermission("stations.index", session, station._id)
  1162. .then(() => dispatchNextSong())
  1163. .catch(() => {
  1164. hasPermission("stations.index.other", session)
  1165. .then(() => dispatchNextSong())
  1166. .catch(() => {});
  1167. });
  1168. }
  1169. );
  1170. }
  1171. });
  1172. }
  1173. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  1174. if (station.currentSong !== null && station.currentSong.mediaSource !== undefined) {
  1175. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  1176. sockets,
  1177. room: `song.${station.currentSong.mediaSource}`
  1178. });
  1179. if (!station.paused) {
  1180. NotificationsModule.runJob("SCHEDULE", {
  1181. name: `stations.nextSong?id=${station._id}`,
  1182. time: station.currentSong.duration * 1000,
  1183. station
  1184. });
  1185. }
  1186. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  1187. });
  1188. return resolve({ station });
  1189. }
  1190. );
  1191. });
  1192. }
  1193. /**
  1194. * Checks if a user can view/access a station
  1195. *
  1196. * @param {object} payload - object that contains the payload
  1197. * @param {object} payload.station - the station object of the station in question
  1198. * @param {string} payload.userId - the id of the user in question
  1199. * @returns {Promise} - returns a promise (resolve, reject)
  1200. */
  1201. CAN_USER_VIEW_STATION(payload) {
  1202. return new Promise((resolve, reject) => {
  1203. async.waterfall(
  1204. [
  1205. next => {
  1206. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  1207. return next(true);
  1208. if (!payload.userId) return next("Not allowed");
  1209. return next();
  1210. },
  1211. next => {
  1212. hasPermission("stations.view", payload.userId, payload.station._id)
  1213. .then(() => next(true))
  1214. .catch(() => next("Not allowed"));
  1215. }
  1216. ],
  1217. async errOrResult => {
  1218. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1219. errOrResult = await UtilsModule.runJob(
  1220. "GET_ERROR",
  1221. {
  1222. error: errOrResult
  1223. },
  1224. this
  1225. );
  1226. reject(new Error(errOrResult));
  1227. } else {
  1228. resolve(errOrResult === true);
  1229. }
  1230. }
  1231. );
  1232. });
  1233. }
  1234. /**
  1235. * Checks if a user has favorited a station or not
  1236. *
  1237. * @param {object} payload - object that contains the payload
  1238. * @param {object} payload.stationId - the id of the station in question
  1239. * @param {string} payload.userId - the id of the user in question
  1240. * @returns {Promise} - returns a promise (resolve, reject)
  1241. */
  1242. HAS_USER_FAVORITED_STATION(payload) {
  1243. return new Promise((resolve, reject) => {
  1244. async.waterfall(
  1245. [
  1246. next => {
  1247. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1248. userModel.findOne({ _id: payload.userId }, next);
  1249. });
  1250. },
  1251. (user, next) => {
  1252. if (!user) return next("User not found.");
  1253. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1254. return next(null, false);
  1255. }
  1256. ],
  1257. async (err, isStationFavorited) => {
  1258. if (err && err !== true) {
  1259. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1260. return reject(new Error(err));
  1261. }
  1262. return resolve(isStationFavorited);
  1263. }
  1264. );
  1265. });
  1266. }
  1267. /**
  1268. * Returns a list of sockets in a room that can and can't know about a station
  1269. *
  1270. * @param {object} payload - the payload object
  1271. * @param {object} payload.station - the station object
  1272. * @param {string} payload.room - the websockets room to get the sockets from
  1273. * @returns {Promise} - returns a promise (resolve, reject)
  1274. */
  1275. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1276. return new Promise((resolve, reject) => {
  1277. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1278. .then(socketIds => {
  1279. const sockets = [];
  1280. async.eachLimit(
  1281. socketIds,
  1282. 1,
  1283. (socketId, next) => {
  1284. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1285. .then(socket => {
  1286. if (socket) sockets.push(socket);
  1287. next();
  1288. })
  1289. .catch(err => {
  1290. reject(err);
  1291. });
  1292. },
  1293. err => {
  1294. if (err) reject(err);
  1295. else {
  1296. let socketsThatCan = [];
  1297. const socketsThatCannot = [];
  1298. if (payload.station.privacy === "public") {
  1299. socketsThatCan = sockets;
  1300. resolve({ socketsThatCan, socketsThatCannot });
  1301. } else {
  1302. async.eachLimit(
  1303. sockets,
  1304. 1,
  1305. (socket, next) => {
  1306. if (!(socket.session && socket.session.sessionId)) {
  1307. socketsThatCannot.push(socket);
  1308. next();
  1309. } else
  1310. hasPermission("stations.view", socket.session, payload.station._id)
  1311. .then(() => {
  1312. socketsThatCan.push(socket);
  1313. next();
  1314. })
  1315. .catch(() => {
  1316. socketsThatCannot.push(socket);
  1317. next();
  1318. });
  1319. },
  1320. err => {
  1321. if (err) reject(err);
  1322. else resolve({ socketsThatCan, socketsThatCannot });
  1323. }
  1324. );
  1325. }
  1326. }
  1327. }
  1328. );
  1329. })
  1330. .catch(reject);
  1331. });
  1332. }
  1333. /**
  1334. * Adds a playlist to autofill a station
  1335. *
  1336. * @param {object} payload - object that contains the payload
  1337. * @param {object} payload.stationId - the id of the station
  1338. * @param {object} payload.playlistId - the id of the playlist
  1339. * @returns {Promise} - returns a promise (resolve, reject)
  1340. */
  1341. AUTOFILL_PLAYLIST(payload) {
  1342. return new Promise((resolve, reject) => {
  1343. async.waterfall(
  1344. [
  1345. next => {
  1346. if (!payload.stationId) next("Please specify a station id");
  1347. else if (!payload.playlistId) next("Please specify a playlist id");
  1348. else next();
  1349. },
  1350. next => {
  1351. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1352. .then(station => {
  1353. next(null, station);
  1354. })
  1355. .catch(next);
  1356. },
  1357. (station, next) => {
  1358. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1359. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1360. next("This playlist is already autofilling");
  1361. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1362. next("This playlist is currently blacklisted");
  1363. else
  1364. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1365. .then(() => {
  1366. next(null);
  1367. })
  1368. .catch(next);
  1369. },
  1370. next => {
  1371. StationsModule.stationModel.updateOne(
  1372. { _id: payload.stationId },
  1373. { $push: { "autofill.playlists": payload.playlistId } },
  1374. next
  1375. );
  1376. },
  1377. (res, next) => {
  1378. StationsModule.runJob(
  1379. "UPDATE_STATION",
  1380. {
  1381. stationId: payload.stationId
  1382. },
  1383. this
  1384. )
  1385. .then(() => {
  1386. next();
  1387. })
  1388. .catch(next);
  1389. }
  1390. ],
  1391. async err => {
  1392. if (err && err !== true) {
  1393. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1394. return reject(new Error(err));
  1395. }
  1396. return resolve();
  1397. }
  1398. );
  1399. });
  1400. }
  1401. /**
  1402. * Removes a playlist from autofill
  1403. *
  1404. * @param {object} payload - object that contains the payload
  1405. * @param {object} payload.stationId - the id of the station
  1406. * @param {object} payload.playlistId - the id of the playlist
  1407. * @returns {Promise} - returns a promise (resolve, reject)
  1408. */
  1409. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1410. return new Promise((resolve, reject) => {
  1411. async.waterfall(
  1412. [
  1413. next => {
  1414. if (!payload.stationId) next("Please specify a station id");
  1415. else if (!payload.playlistId) next("Please specify a playlist id");
  1416. else next();
  1417. },
  1418. next => {
  1419. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1420. .then(station => {
  1421. next(null, station);
  1422. })
  1423. .catch(next);
  1424. },
  1425. (station, next) => {
  1426. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1427. next("This playlist isn't autofilling");
  1428. else next();
  1429. },
  1430. next => {
  1431. StationsModule.stationModel.updateOne(
  1432. { _id: payload.stationId },
  1433. { $pull: { "autofill.playlists": payload.playlistId } },
  1434. next
  1435. );
  1436. },
  1437. (res, next) => {
  1438. StationsModule.runJob(
  1439. "UPDATE_STATION",
  1440. {
  1441. stationId: payload.stationId
  1442. },
  1443. this
  1444. )
  1445. .then(() => {
  1446. next();
  1447. })
  1448. .catch(next);
  1449. }
  1450. ],
  1451. async err => {
  1452. if (err && err !== true) {
  1453. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1454. return reject(new Error(err));
  1455. }
  1456. return resolve();
  1457. }
  1458. );
  1459. });
  1460. }
  1461. /**
  1462. * Add a playlist to station blacklist
  1463. *
  1464. * @param {object} payload - object that contains the payload
  1465. * @param {object} payload.stationId - the id of the station
  1466. * @param {object} payload.playlistId - the id of the playlist
  1467. * @returns {Promise} - returns a promise (resolve, reject)
  1468. */
  1469. BLACKLIST_PLAYLIST(payload) {
  1470. return new Promise((resolve, reject) => {
  1471. async.waterfall(
  1472. [
  1473. next => {
  1474. if (!payload.stationId) next("Please specify a station id");
  1475. else if (!payload.playlistId) next("Please specify a playlist id");
  1476. else next();
  1477. },
  1478. next => {
  1479. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1480. .then(station => {
  1481. next(null, station);
  1482. })
  1483. .catch(next);
  1484. },
  1485. (station, next) => {
  1486. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1487. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1488. next("This playlist is already blacklisted");
  1489. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1490. next(
  1491. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1492. );
  1493. else
  1494. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1495. .then(() => {
  1496. next(null);
  1497. })
  1498. .catch(next);
  1499. },
  1500. next => {
  1501. StationsModule.stationModel.updateOne(
  1502. { _id: payload.stationId },
  1503. { $push: { blacklist: payload.playlistId } },
  1504. next
  1505. );
  1506. },
  1507. (res, next) => {
  1508. StationsModule.runJob(
  1509. "UPDATE_STATION",
  1510. {
  1511. stationId: payload.stationId
  1512. },
  1513. this
  1514. )
  1515. .then(() => {
  1516. next();
  1517. })
  1518. .catch(next);
  1519. }
  1520. ],
  1521. async err => {
  1522. if (err && err !== true) {
  1523. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1524. return reject(new Error(err));
  1525. }
  1526. return resolve();
  1527. }
  1528. );
  1529. });
  1530. }
  1531. /**
  1532. * Remove a playlist from station blacklist
  1533. *
  1534. * @param {object} payload - object that contains the payload
  1535. * @param {object} payload.stationId - the id of the station
  1536. * @param {object} payload.playlistId - the id of the playlist
  1537. * @returns {Promise} - returns a promise (resolve, reject)
  1538. */
  1539. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1540. return new Promise((resolve, reject) => {
  1541. async.waterfall(
  1542. [
  1543. next => {
  1544. if (!payload.stationId) next("Please specify a station id");
  1545. else if (!payload.playlistId) next("Please specify a playlist id");
  1546. else next();
  1547. },
  1548. next => {
  1549. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1550. .then(station => {
  1551. next(null, station);
  1552. })
  1553. .catch(next);
  1554. },
  1555. (station, next) => {
  1556. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1557. next("This playlist isn't blacklisted");
  1558. else next();
  1559. },
  1560. next => {
  1561. StationsModule.stationModel.updateOne(
  1562. { _id: payload.stationId },
  1563. { $pull: { blacklist: payload.playlistId } },
  1564. next
  1565. );
  1566. },
  1567. (res, next) => {
  1568. StationsModule.runJob(
  1569. "UPDATE_STATION",
  1570. {
  1571. stationId: payload.stationId
  1572. },
  1573. this
  1574. )
  1575. .then(() => {
  1576. next();
  1577. })
  1578. .catch(next);
  1579. }
  1580. ],
  1581. async err => {
  1582. if (err && err !== true) {
  1583. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1584. return reject(new Error(err));
  1585. }
  1586. return resolve();
  1587. }
  1588. );
  1589. });
  1590. }
  1591. /**
  1592. * Removes autofilled or blacklisted playlist from a station
  1593. *
  1594. * @param {object} payload - object that contains the payload
  1595. * @param {string} payload.playlistId - the playlist id
  1596. * @returns {Promise} - returns promise (reject, resolve)
  1597. */
  1598. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1599. return new Promise((resolve, reject) => {
  1600. async.waterfall(
  1601. [
  1602. next => {
  1603. if (!payload.playlistId) next("Please specify a playlist id");
  1604. else next();
  1605. },
  1606. next => {
  1607. StationsModule.stationModel.updateMany(
  1608. {
  1609. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1610. },
  1611. {
  1612. $pull: {
  1613. "autofill.playlists": payload.playlistId,
  1614. blacklist: payload.playlistId
  1615. }
  1616. },
  1617. err => {
  1618. if (err) next(err);
  1619. else next();
  1620. }
  1621. );
  1622. }
  1623. ],
  1624. async err => {
  1625. if (err && err !== true) {
  1626. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1627. return reject(new Error(err));
  1628. }
  1629. return resolve();
  1630. }
  1631. );
  1632. });
  1633. }
  1634. /**
  1635. * Gets stations that autofill or blacklist a specific playlist
  1636. *
  1637. * @param {object} payload - object that contains the payload
  1638. * @param {string} payload.playlistId - the playlist id
  1639. * @returns {Promise} - returns promise (reject, resolve)
  1640. */
  1641. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1642. return new Promise((resolve, reject) => {
  1643. DBModule.runJob(
  1644. "GET_MODEL",
  1645. {
  1646. modelName: "station"
  1647. },
  1648. this
  1649. ).then(stationModel => {
  1650. stationModel.find(
  1651. {
  1652. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1653. },
  1654. (err, stations) => {
  1655. if (err) reject(err);
  1656. else resolve({ stationIds: stations.map(station => station._id) });
  1657. }
  1658. );
  1659. });
  1660. });
  1661. }
  1662. /**
  1663. * Clears every queue
  1664. *
  1665. * @returns {Promise} - returns a promise (resolve, reject)
  1666. */
  1667. CLEAR_EVERY_STATION_QUEUE() {
  1668. return new Promise((resolve, reject) => {
  1669. async.waterfall(
  1670. [
  1671. next => {
  1672. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1673. if (err) next(err);
  1674. else {
  1675. StationsModule.stationModel.find({}, (err, stations) => {
  1676. if (err) next(err);
  1677. else {
  1678. async.eachLimit(
  1679. stations,
  1680. 1,
  1681. (station, next) => {
  1682. this.publishProgress({
  1683. status: "update",
  1684. message: `Updating station "${station._id}"`
  1685. });
  1686. StationsModule.runJob("UPDATE_STATION", {
  1687. stationId: station._id
  1688. })
  1689. .then(() => next())
  1690. .catch(next);
  1691. CacheModule.runJob("PUB", {
  1692. channel: "station.queueUpdate",
  1693. value: station._id
  1694. })
  1695. .then()
  1696. .catch();
  1697. },
  1698. next
  1699. );
  1700. }
  1701. });
  1702. }
  1703. });
  1704. }
  1705. ],
  1706. err => {
  1707. if (err) reject(err);
  1708. else resolve();
  1709. }
  1710. );
  1711. });
  1712. }
  1713. /**
  1714. * Resets a station queue
  1715. *
  1716. * @param {object} payload - object that contains the payload
  1717. * @param {string} payload.stationId - the station id
  1718. * @returns {Promise} - returns a promise (resolve, reject)
  1719. */
  1720. RESET_QUEUE(payload) {
  1721. return new Promise((resolve, reject) => {
  1722. async.waterfall(
  1723. [
  1724. next => {
  1725. StationsModule.runJob(
  1726. "AUTOFILL_STATION",
  1727. { stationId: payload.stationId, ignoreExistingQueue: true },
  1728. this
  1729. )
  1730. .then(() => {
  1731. CacheModule.runJob("PUB", {
  1732. channel: "station.queueUpdate",
  1733. value: payload.stationId
  1734. })
  1735. .then()
  1736. .catch();
  1737. next();
  1738. })
  1739. .catch(err => {
  1740. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1741. StationsModule.stationModel
  1742. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1743. .then(() => next())
  1744. .catch(next);
  1745. else next(err);
  1746. });
  1747. },
  1748. next => {
  1749. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1750. .then(() => next())
  1751. .catch(next);
  1752. },
  1753. next => {
  1754. CacheModule.runJob("PUB", {
  1755. channel: "station.queueUpdate",
  1756. value: payload.stationId
  1757. })
  1758. .then(() => next())
  1759. .catch(next);
  1760. }
  1761. ],
  1762. err => {
  1763. if (err) reject(err);
  1764. else resolve();
  1765. }
  1766. );
  1767. });
  1768. }
  1769. /**
  1770. * Add to a station queue
  1771. *
  1772. * @param {object} payload - object that contains the payload
  1773. * @param {string} payload.stationId - the station id
  1774. * @param {string} payload.mediaSource - the media source
  1775. * @param {string} payload.requestUser - the requesting user id
  1776. * @param {string} payload.requestType - the request type
  1777. * @returns {Promise} - returns a promise (resolve, reject)
  1778. */
  1779. ADD_TO_QUEUE(payload) {
  1780. return new Promise((resolve, reject) => {
  1781. const { stationId, mediaSource, requestUser, requestType } = payload;
  1782. console.log(45436546, mediaSource);
  1783. async.waterfall(
  1784. [
  1785. next => {
  1786. StationsModule.runJob("GET_STATION", { stationId }, this)
  1787. .then(station => {
  1788. next(null, station);
  1789. })
  1790. .catch(next);
  1791. },
  1792. (station, next) => {
  1793. if (!station) return next("Station not found.");
  1794. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1795. if (mediaSource.startsWith("spotify:")) return next("Spotify playback is not supported.");
  1796. if (station.currentSong && station.currentSong.mediaSource === mediaSource)
  1797. return next("That song is currently playing.");
  1798. if (station.queue.find(song => song.mediaSource === mediaSource))
  1799. return next("That song is already in the queue.");
  1800. return next(null, station);
  1801. },
  1802. (station, next) => {
  1803. MediaModule.runJob("GET_MEDIA", { mediaSource }, this)
  1804. .then(response => {
  1805. const { song } = response;
  1806. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1807. next(
  1808. null,
  1809. {
  1810. _id,
  1811. mediaSource,
  1812. title,
  1813. skipDuration,
  1814. artists,
  1815. thumbnail,
  1816. duration,
  1817. verified
  1818. },
  1819. station
  1820. );
  1821. })
  1822. .catch(next);
  1823. },
  1824. (song, station, next) => {
  1825. const blacklist = [];
  1826. async.eachLimit(
  1827. station.blacklist,
  1828. 1,
  1829. (playlistId, next) => {
  1830. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1831. .then(playlist => {
  1832. blacklist.push(playlist);
  1833. next();
  1834. })
  1835. .catch(next);
  1836. },
  1837. err => {
  1838. next(err, song, station, blacklist);
  1839. }
  1840. );
  1841. },
  1842. (song, station, blacklist, next) => {
  1843. const blacklistedSongs = blacklist
  1844. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1845. .reduce(
  1846. (items, item) =>
  1847. items.find(x => x.mediaSource === item.mediaSource) ? [...items] : [...items, item],
  1848. []
  1849. );
  1850. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.mediaSource === song.mediaSource))
  1851. next("That song is in an blacklisted playlist and cannot be played.");
  1852. else next(null, song, station);
  1853. },
  1854. (song, station, next) => {
  1855. song.requestedBy = requestUser;
  1856. song.requestedAt = Date.now();
  1857. song.requestedType = requestType;
  1858. if (station.queue.length === 0) return next(null, song, station);
  1859. if (
  1860. requestUser &&
  1861. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1862. station.requests.limit
  1863. )
  1864. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1865. return next(null, song, station);
  1866. },
  1867. // (song, station, next) => {
  1868. // song.requestedBy = session.userId;
  1869. // song.requestedAt = Date.now();
  1870. // let totalDuration = 0;
  1871. // station.queue.forEach(song => {
  1872. // totalDuration += song.duration;
  1873. // });
  1874. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1875. // return next(null, song, station);
  1876. // },
  1877. // (song, station, next) => {
  1878. // if (station.queue.length === 0) return next(null, song, station);
  1879. // let totalDuration = 0;
  1880. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1881. // station.queue.forEach(song => {
  1882. // if (userId === song.requestedBy) {
  1883. // totalDuration += song.duration;
  1884. // }
  1885. // });
  1886. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1887. // return next(null, song, station);
  1888. // },
  1889. // (song, station, next) => {
  1890. // if (station.queue.length === 0) return next(null, song);
  1891. // let totalSongs = 0;
  1892. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1893. // station.queue.forEach(song => {
  1894. // if (userId === song.requestedBy) {
  1895. // totalSongs += 1;
  1896. // }
  1897. // });
  1898. // if (totalSongs <= 2) return next(null, song);
  1899. // if (totalSongs > 3)
  1900. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1901. // if (
  1902. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1903. // station.queue[station.queue.length - 3] !== userId
  1904. // )
  1905. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1906. // return next(null, song);
  1907. // },
  1908. (song, station, next) => {
  1909. const queueAddBeforeAutofilled = config.get(`experimental.queue_add_before_autofilled`);
  1910. if (
  1911. queueAddBeforeAutofilled === true ||
  1912. (Array.isArray(queueAddBeforeAutofilled) &&
  1913. queueAddBeforeAutofilled.indexOf(stationId) !== -1)
  1914. ) {
  1915. let position = station.queue.length;
  1916. if (station.autofill.enabled && station.queue.length >= station.autofill.limit) {
  1917. position = -station.autofill.limit;
  1918. }
  1919. StationsModule.stationModel.updateOne(
  1920. { _id: stationId },
  1921. {
  1922. $push: {
  1923. queue: {
  1924. $each: [song],
  1925. $position: position
  1926. }
  1927. }
  1928. },
  1929. { runValidators: true },
  1930. next
  1931. );
  1932. return;
  1933. }
  1934. StationsModule.stationModel.updateOne(
  1935. { _id: stationId },
  1936. { $push: { queue: song } },
  1937. { runValidators: true },
  1938. next
  1939. );
  1940. },
  1941. (res, next) => {
  1942. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1943. .then(() => next())
  1944. .catch(next);
  1945. },
  1946. next => {
  1947. CacheModule.runJob(
  1948. "PUB",
  1949. {
  1950. channel: "station.queueUpdate",
  1951. value: stationId
  1952. },
  1953. this
  1954. )
  1955. .then(() => next())
  1956. .catch(next);
  1957. }
  1958. ],
  1959. err => {
  1960. if (err) reject(err);
  1961. else resolve();
  1962. }
  1963. );
  1964. });
  1965. }
  1966. /**
  1967. * Remove from a station queue
  1968. *
  1969. * @param {object} payload - object that contains the payload
  1970. * @param {string} payload.stationId - the station id
  1971. * @param {string} payload.mediaSource - the media source
  1972. * @returns {Promise} - returns a promise (resolve, reject)
  1973. */
  1974. REMOVE_FROM_QUEUE(payload) {
  1975. return new Promise((resolve, reject) => {
  1976. const { stationId, mediaSource } = payload;
  1977. async.waterfall(
  1978. [
  1979. next => {
  1980. StationsModule.runJob("GET_STATION", { stationId }, this)
  1981. .then(station => {
  1982. next(null, station);
  1983. })
  1984. .catch(next);
  1985. },
  1986. (station, next) => {
  1987. if (!station) return next("Station not found.");
  1988. if (!station.queue.find(song => song.mediaSource === mediaSource))
  1989. return next("That song is not currently in the queue.");
  1990. return StationsModule.stationModel.updateOne(
  1991. { _id: stationId },
  1992. { $pull: { queue: { mediaSource } } },
  1993. next
  1994. );
  1995. },
  1996. (res, next) => {
  1997. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1998. .then(station => {
  1999. if (station.autofill.enabled)
  2000. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  2001. .then(() => next())
  2002. .catch(err => {
  2003. if (
  2004. err === "Autofill is disabled in this station" ||
  2005. err === "Autofill limit reached"
  2006. )
  2007. return next();
  2008. return next(err);
  2009. });
  2010. else next();
  2011. })
  2012. .catch(next);
  2013. },
  2014. next =>
  2015. CacheModule.runJob(
  2016. "PUB",
  2017. {
  2018. channel: "station.queueUpdate",
  2019. value: stationId
  2020. },
  2021. this
  2022. )
  2023. .then(() => next())
  2024. .catch(next)
  2025. ],
  2026. err => {
  2027. if (err) reject(err);
  2028. else resolve();
  2029. }
  2030. );
  2031. });
  2032. }
  2033. /**
  2034. * Add DJ to station
  2035. *
  2036. * @param {object} payload - object that contains the payload
  2037. * @param {string} payload.stationId - the station id
  2038. * @param {string} payload.userId - the dj user id
  2039. * @returns {Promise} - returns a promise (resolve, reject)
  2040. */
  2041. ADD_DJ(payload) {
  2042. return new Promise((resolve, reject) => {
  2043. const { stationId, userId } = payload;
  2044. async.waterfall(
  2045. [
  2046. next => {
  2047. StationsModule.runJob("GET_STATION", { stationId }, this)
  2048. .then(station => {
  2049. next(null, station);
  2050. })
  2051. .catch(next);
  2052. },
  2053. (station, next) => {
  2054. if (!station) return next("Station not found.");
  2055. if (station.djs.find(dj => dj === userId)) return next("That user is already a DJ.");
  2056. return StationsModule.stationModel.updateOne(
  2057. { _id: stationId },
  2058. { $push: { djs: userId } },
  2059. next
  2060. );
  2061. },
  2062. (res, next) => {
  2063. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2064. .then(() => next())
  2065. .catch(next);
  2066. },
  2067. next =>
  2068. CacheModule.runJob(
  2069. "PUB",
  2070. {
  2071. channel: "station.djs.added",
  2072. value: { stationId, userId }
  2073. },
  2074. this
  2075. )
  2076. .then(() => next())
  2077. .catch(next)
  2078. ],
  2079. err => {
  2080. if (err) reject(err);
  2081. else resolve();
  2082. }
  2083. );
  2084. });
  2085. }
  2086. /**
  2087. * Remove DJ from station
  2088. *
  2089. * @param {object} payload - object that contains the payload
  2090. * @param {string} payload.stationId - the station id
  2091. * @param {string} payload.userId - the dj user id
  2092. * @returns {Promise} - returns a promise (resolve, reject)
  2093. */
  2094. REMOVE_DJ(payload) {
  2095. return new Promise((resolve, reject) => {
  2096. const { stationId, userId } = payload;
  2097. async.waterfall(
  2098. [
  2099. next => {
  2100. StationsModule.runJob("GET_STATION", { stationId }, this)
  2101. .then(station => {
  2102. next(null, station);
  2103. })
  2104. .catch(next);
  2105. },
  2106. (station, next) => {
  2107. if (!station) return next("Station not found.");
  2108. if (!station.djs.find(dj => dj === userId)) return next("That user is not currently a DJ.");
  2109. return StationsModule.stationModel.updateOne(
  2110. { _id: stationId },
  2111. { $pull: { djs: userId } },
  2112. next
  2113. );
  2114. },
  2115. (res, next) => {
  2116. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  2117. .then(() => next())
  2118. .catch(next);
  2119. },
  2120. next =>
  2121. CacheModule.runJob(
  2122. "PUB",
  2123. {
  2124. channel: "station.djs.removed",
  2125. value: { stationId, userId }
  2126. },
  2127. this
  2128. )
  2129. .then(() => next())
  2130. .catch(next)
  2131. ],
  2132. err => {
  2133. if (err) reject(err);
  2134. else resolve();
  2135. }
  2136. );
  2137. });
  2138. }
  2139. }
  2140. export default new _StationsModule();