stations.js 60 KB

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