stations.js 61 KB

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