stations.js 61 KB

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