stations.js 62 KB

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