stations.js 62 KB

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