stations.js 49 KB

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