stations.js 61 KB

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