stations.js 62 KB

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