stations.js 51 KB

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