stations.js 62 KB

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