stations.js 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926
  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 =
  700. station.currentSong && station.currentSong.skipVotes
  701. ? station.currentSong.skipVotes.length
  702. : 0;
  703. let shouldSkip = false;
  704. if (skipVotes === 0) {
  705. if (!station.paused && !station.currentSong && station.queue.length > 0) shouldSkip = true;
  706. return next(null, shouldSkip);
  707. }
  708. const users = [];
  709. return async.each(
  710. sockets,
  711. (socketId, next) => {
  712. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  713. .then(socket => {
  714. if (socket && socket.session && socket.session.userId) {
  715. if (!users.includes(socket.session.userId))
  716. users.push(socket.session.userId);
  717. }
  718. return next();
  719. })
  720. .catch(next);
  721. },
  722. err => {
  723. if (err) return next(err);
  724. if (!station.paused && users.length <= skipVotes) shouldSkip = true;
  725. return next(null, shouldSkip);
  726. }
  727. );
  728. },
  729. (shouldSkip, next) => {
  730. if (shouldSkip)
  731. StationsModule.runJob(
  732. "SKIP_STATION",
  733. {
  734. stationId: payload.stationId,
  735. natural: false
  736. },
  737. this
  738. )
  739. .then(() => next())
  740. .catch(next);
  741. else next();
  742. }
  743. ],
  744. err => {
  745. if (err) reject(err);
  746. else resolve();
  747. }
  748. );
  749. });
  750. }
  751. /**
  752. * Skips a station
  753. *
  754. * @param {object} payload - object that contains the payload
  755. * @param {string} payload.stationId - the id of the station to skip
  756. * @param {string} payload.natural - whether to skip naturally or forcefully
  757. * @returns {Promise} - returns a promise (resolve, reject)
  758. */
  759. SKIP_STATION(payload) {
  760. return new Promise((resolve, reject) => {
  761. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  762. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  763. async.waterfall(
  764. [
  765. // Clears up any existing timers that would skip the station if the song ends
  766. next => {
  767. NotificationsModule.runJob("UNSCHEDULE", {
  768. name: `stations.nextSong?id=${payload.stationId}`
  769. })
  770. .then(() => {
  771. next();
  772. })
  773. .catch(next);
  774. },
  775. // Gets the station object
  776. next => {
  777. StationsModule.runJob(
  778. "GET_STATION",
  779. {
  780. stationId: payload.stationId
  781. },
  782. this
  783. )
  784. .then(station => next(null, station))
  785. .catch(next);
  786. },
  787. (station, next) => {
  788. if (!station) return next("Station not found.");
  789. if (station.autofill.enabled)
  790. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  791. .then(() => next(null, station))
  792. .catch(err => {
  793. if (
  794. err === "Autofill is disabled in this station" ||
  795. err === "Autofill limit reached"
  796. )
  797. return next(null, station);
  798. return next(err);
  799. });
  800. return next(null, station);
  801. },
  802. (station, next) => {
  803. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  804. .then(response => {
  805. StationsModule.runJob("REMOVE_FIRST_QUEUE_SONG", { stationId: station._id }, this)
  806. .then(() => {
  807. next(null, response.song, station);
  808. })
  809. .catch(next);
  810. })
  811. .catch(err => {
  812. if (err === "No songs available.") next(null, null, station);
  813. else next(err);
  814. });
  815. },
  816. (song, station, next) => {
  817. const $set = {};
  818. if (song === null) $set.currentSong = null;
  819. else {
  820. $set.currentSong = {
  821. _id: song._id,
  822. youtubeId: song.youtubeId,
  823. title: song.title,
  824. artists: song.artists,
  825. duration: song.duration,
  826. skipDuration: song.skipDuration,
  827. thumbnail: song.thumbnail,
  828. requestedAt: song.requestedAt,
  829. requestedBy: song.requestedBy,
  830. verified: song.verified
  831. };
  832. }
  833. $set.startedAt = Date.now();
  834. $set.timePaused = 0;
  835. if (station.paused) $set.pausedAt = Date.now();
  836. next(null, $set, station);
  837. },
  838. ($set, station, next) => {
  839. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  840. if (err) return next(err);
  841. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  842. .then(station => {
  843. next(null, station);
  844. })
  845. .catch(next);
  846. });
  847. },
  848. (station, next) => {
  849. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  850. station.currentSong.skipVotes = 0;
  851. }
  852. next(null, station);
  853. },
  854. (station, next) => {
  855. if (station.autofill.enabled)
  856. return StationsModule.runJob("AUTOFILL_STATION", { stationId: station._id }, this)
  857. .then(() => next(null, station))
  858. .catch(err => {
  859. if (
  860. err === "Autofill is disabled in this station" ||
  861. err === "Autofill limit reached"
  862. )
  863. return next(null, station);
  864. return next(err);
  865. });
  866. return next(null, station);
  867. },
  868. (station, next) =>
  869. StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  870. .then(station => {
  871. CacheModule.runJob("PUB", {
  872. channel: "station.queueUpdate",
  873. value: payload.stationId
  874. })
  875. .then()
  876. .catch();
  877. next(null, station);
  878. })
  879. .catch(next)
  880. ],
  881. async (err, station) => {
  882. if (err === "Autofill limit reached") return resolve({ station });
  883. if (err) {
  884. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  885. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  886. return reject(new Error(err));
  887. }
  888. // TODO Pub/Sub this
  889. const { currentSong } = station;
  890. WSModule.runJob("EMIT_TO_ROOM", {
  891. room: `station.${station._id}`,
  892. args: [
  893. "event:station.nextSong",
  894. {
  895. data: {
  896. currentSong,
  897. startedAt: station.startedAt,
  898. paused: station.paused,
  899. timePaused: 0,
  900. natural: payload.natural
  901. }
  902. }
  903. ]
  904. });
  905. WSModule.runJob("EMIT_TO_ROOM", {
  906. room: `manage-station.${station._id}`,
  907. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  908. });
  909. if (station.privacy === "public")
  910. WSModule.runJob("EMIT_TO_ROOM", {
  911. room: "home",
  912. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  913. });
  914. else {
  915. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  916. sockets.forEach(async socketId => {
  917. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  918. if (!socket) return;
  919. const { session } = socket;
  920. if (session.sessionId) {
  921. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  922. session => {
  923. hasPermission("stations.skip", session, station._id)
  924. .then(() =>
  925. socket.dispatch("event:station.nextSong", {
  926. data: {
  927. stationId: station._id,
  928. currentSong
  929. }
  930. })
  931. )
  932. .catch(() => {});
  933. }
  934. );
  935. }
  936. });
  937. }
  938. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  939. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  940. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  941. sockets,
  942. room: `song.${station.currentSong.youtubeId}`
  943. });
  944. if (!station.paused) {
  945. NotificationsModule.runJob("SCHEDULE", {
  946. name: `stations.nextSong?id=${station._id}`,
  947. time: station.currentSong.duration * 1000,
  948. station
  949. });
  950. }
  951. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  952. });
  953. return resolve({ station });
  954. }
  955. );
  956. });
  957. }
  958. /**
  959. * Checks if a user can view/access a station
  960. *
  961. * @param {object} payload - object that contains the payload
  962. * @param {object} payload.station - the station object of the station in question
  963. * @param {string} payload.userId - the id of the user in question
  964. * @returns {Promise} - returns a promise (resolve, reject)
  965. */
  966. CAN_USER_VIEW_STATION(payload) {
  967. return new Promise((resolve, reject) => {
  968. async.waterfall(
  969. [
  970. next => {
  971. if (payload.station.privacy === "public" || payload.station.privacy === "unlisted")
  972. return next(true);
  973. if (!payload.userId) return next("Not allowed");
  974. return next();
  975. },
  976. next => {
  977. hasPermission("stations.view", payload.userId, payload.station._id)
  978. .then(() => next(true))
  979. .catch(() => next("Not allowed"));
  980. }
  981. ],
  982. async errOrResult => {
  983. if (errOrResult !== true && errOrResult !== "Not allowed") {
  984. errOrResult = await UtilsModule.runJob(
  985. "GET_ERROR",
  986. {
  987. error: errOrResult
  988. },
  989. this
  990. );
  991. reject(new Error(errOrResult));
  992. } else {
  993. resolve(errOrResult === true);
  994. }
  995. }
  996. );
  997. });
  998. }
  999. /**
  1000. * Checks if a user has favorited a station or not
  1001. *
  1002. * @param {object} payload - object that contains the payload
  1003. * @param {object} payload.stationId - the id of the station in question
  1004. * @param {string} payload.userId - the id of the user in question
  1005. * @returns {Promise} - returns a promise (resolve, reject)
  1006. */
  1007. HAS_USER_FAVORITED_STATION(payload) {
  1008. return new Promise((resolve, reject) => {
  1009. async.waterfall(
  1010. [
  1011. next => {
  1012. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1013. userModel.findOne({ _id: payload.userId }, next);
  1014. });
  1015. },
  1016. (user, next) => {
  1017. if (!user) return next("User not found.");
  1018. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1019. return next(null, false);
  1020. }
  1021. ],
  1022. async (err, isStationFavorited) => {
  1023. if (err && err !== true) {
  1024. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1025. return reject(new Error(err));
  1026. }
  1027. return resolve(isStationFavorited);
  1028. }
  1029. );
  1030. });
  1031. }
  1032. /**
  1033. * Returns a list of sockets in a room that can and can't know about a station
  1034. *
  1035. * @param {object} payload - the payload object
  1036. * @param {object} payload.station - the station object
  1037. * @param {string} payload.room - the websockets room to get the sockets from
  1038. * @returns {Promise} - returns a promise (resolve, reject)
  1039. */
  1040. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1041. return new Promise((resolve, reject) => {
  1042. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1043. .then(socketIds => {
  1044. const sockets = [];
  1045. async.eachLimit(
  1046. socketIds,
  1047. 1,
  1048. (socketId, next) => {
  1049. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1050. .then(socket => {
  1051. if (socket) sockets.push(socket);
  1052. next();
  1053. })
  1054. .catch(err => {
  1055. reject(err);
  1056. });
  1057. },
  1058. err => {
  1059. if (err) reject(err);
  1060. else {
  1061. let socketsThatCan = [];
  1062. const socketsThatCannot = [];
  1063. if (payload.station.privacy === "public") {
  1064. socketsThatCan = sockets;
  1065. resolve({ socketsThatCan, socketsThatCannot });
  1066. } else {
  1067. async.eachLimit(
  1068. sockets,
  1069. 1,
  1070. (socket, next) => {
  1071. if (!(socket.session && socket.session.sessionId)) {
  1072. socketsThatCannot.push(socket);
  1073. next();
  1074. } else
  1075. hasPermission("stations.view", socket.session, payload.station._id)
  1076. .then(() => {
  1077. socketsThatCan.push(socket);
  1078. next();
  1079. })
  1080. .catch(() => {
  1081. socketsThatCannot.push(socket);
  1082. next();
  1083. });
  1084. },
  1085. err => {
  1086. if (err) reject(err);
  1087. else resolve({ socketsThatCan, socketsThatCannot });
  1088. }
  1089. );
  1090. }
  1091. }
  1092. }
  1093. );
  1094. })
  1095. .catch(reject);
  1096. });
  1097. }
  1098. /**
  1099. * Adds a playlist to autofill a station
  1100. *
  1101. * @param {object} payload - object that contains the payload
  1102. * @param {object} payload.stationId - the id of the station
  1103. * @param {object} payload.playlistId - the id of the playlist
  1104. * @returns {Promise} - returns a promise (resolve, reject)
  1105. */
  1106. AUTOFILL_PLAYLIST(payload) {
  1107. return new Promise((resolve, reject) => {
  1108. async.waterfall(
  1109. [
  1110. next => {
  1111. if (!payload.stationId) next("Please specify a station id");
  1112. else if (!payload.playlistId) next("Please specify a playlist id");
  1113. else next();
  1114. },
  1115. next => {
  1116. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1117. .then(station => {
  1118. next(null, station);
  1119. })
  1120. .catch(next);
  1121. },
  1122. (station, next) => {
  1123. if (station.playlist === payload.playlistId) next("You cannot autofill the station playlist");
  1124. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1125. next("This playlist is already autofilling");
  1126. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1127. next("This playlist is currently blacklisted");
  1128. else
  1129. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1130. .then(() => {
  1131. next(null);
  1132. })
  1133. .catch(next);
  1134. },
  1135. next => {
  1136. StationsModule.stationModel.updateOne(
  1137. { _id: payload.stationId },
  1138. { $push: { "autofill.playlists": payload.playlistId } },
  1139. next
  1140. );
  1141. },
  1142. (res, next) => {
  1143. StationsModule.runJob(
  1144. "UPDATE_STATION",
  1145. {
  1146. stationId: payload.stationId
  1147. },
  1148. this
  1149. )
  1150. .then(() => {
  1151. next();
  1152. })
  1153. .catch(next);
  1154. }
  1155. ],
  1156. async err => {
  1157. if (err && err !== true) {
  1158. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1159. return reject(new Error(err));
  1160. }
  1161. return resolve();
  1162. }
  1163. );
  1164. });
  1165. }
  1166. /**
  1167. * Removes a playlist from autofill
  1168. *
  1169. * @param {object} payload - object that contains the payload
  1170. * @param {object} payload.stationId - the id of the station
  1171. * @param {object} payload.playlistId - the id of the playlist
  1172. * @returns {Promise} - returns a promise (resolve, reject)
  1173. */
  1174. REMOVE_AUTOFILL_PLAYLIST(payload) {
  1175. return new Promise((resolve, reject) => {
  1176. async.waterfall(
  1177. [
  1178. next => {
  1179. if (!payload.stationId) next("Please specify a station id");
  1180. else if (!payload.playlistId) next("Please specify a playlist id");
  1181. else next();
  1182. },
  1183. next => {
  1184. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1185. .then(station => {
  1186. next(null, station);
  1187. })
  1188. .catch(next);
  1189. },
  1190. (station, next) => {
  1191. if (station.autofill.playlists.indexOf(payload.playlistId) === -1)
  1192. next("This playlist isn't autofilling");
  1193. else next();
  1194. },
  1195. next => {
  1196. StationsModule.stationModel.updateOne(
  1197. { _id: payload.stationId },
  1198. { $pull: { "autofill.playlists": payload.playlistId } },
  1199. next
  1200. );
  1201. },
  1202. (res, next) => {
  1203. StationsModule.runJob(
  1204. "UPDATE_STATION",
  1205. {
  1206. stationId: payload.stationId
  1207. },
  1208. this
  1209. )
  1210. .then(() => {
  1211. next();
  1212. })
  1213. .catch(next);
  1214. }
  1215. ],
  1216. async err => {
  1217. if (err && err !== true) {
  1218. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1219. return reject(new Error(err));
  1220. }
  1221. return resolve();
  1222. }
  1223. );
  1224. });
  1225. }
  1226. /**
  1227. * Add a playlist to station blacklist
  1228. *
  1229. * @param {object} payload - object that contains the payload
  1230. * @param {object} payload.stationId - the id of the station
  1231. * @param {object} payload.playlistId - the id of the playlist
  1232. * @returns {Promise} - returns a promise (resolve, reject)
  1233. */
  1234. BLACKLIST_PLAYLIST(payload) {
  1235. return new Promise((resolve, reject) => {
  1236. async.waterfall(
  1237. [
  1238. next => {
  1239. if (!payload.stationId) next("Please specify a station id");
  1240. else if (!payload.playlistId) next("Please specify a playlist id");
  1241. else next();
  1242. },
  1243. next => {
  1244. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1245. .then(station => {
  1246. next(null, station);
  1247. })
  1248. .catch(next);
  1249. },
  1250. (station, next) => {
  1251. if (station.playlist === payload.playlistId) next("You cannot blacklist the station playlist");
  1252. else if (station.blacklist.indexOf(payload.playlistId) !== -1)
  1253. next("This playlist is already blacklisted");
  1254. else if (station.autofill.playlists.indexOf(payload.playlistId) !== -1)
  1255. next(
  1256. "This playlist is currently autofilling, please remove it from there before blacklisting it"
  1257. );
  1258. else
  1259. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1260. .then(() => {
  1261. next(null);
  1262. })
  1263. .catch(next);
  1264. },
  1265. next => {
  1266. StationsModule.stationModel.updateOne(
  1267. { _id: payload.stationId },
  1268. { $push: { blacklist: payload.playlistId } },
  1269. next
  1270. );
  1271. },
  1272. (res, next) => {
  1273. StationsModule.runJob(
  1274. "UPDATE_STATION",
  1275. {
  1276. stationId: payload.stationId
  1277. },
  1278. this
  1279. )
  1280. .then(() => {
  1281. next();
  1282. })
  1283. .catch(next);
  1284. }
  1285. ],
  1286. async err => {
  1287. if (err && err !== true) {
  1288. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1289. return reject(new Error(err));
  1290. }
  1291. return resolve();
  1292. }
  1293. );
  1294. });
  1295. }
  1296. /**
  1297. * Remove a playlist from station blacklist
  1298. *
  1299. * @param {object} payload - object that contains the payload
  1300. * @param {object} payload.stationId - the id of the station
  1301. * @param {object} payload.playlistId - the id of the playlist
  1302. * @returns {Promise} - returns a promise (resolve, reject)
  1303. */
  1304. REMOVE_BLACKLISTED_PLAYLIST(payload) {
  1305. return new Promise((resolve, reject) => {
  1306. async.waterfall(
  1307. [
  1308. next => {
  1309. if (!payload.stationId) next("Please specify a station id");
  1310. else if (!payload.playlistId) next("Please specify a playlist id");
  1311. else next();
  1312. },
  1313. next => {
  1314. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1315. .then(station => {
  1316. next(null, station);
  1317. })
  1318. .catch(next);
  1319. },
  1320. (station, next) => {
  1321. if (station.blacklist.indexOf(payload.playlistId) === -1)
  1322. next("This playlist isn't blacklisted");
  1323. else next();
  1324. },
  1325. next => {
  1326. StationsModule.stationModel.updateOne(
  1327. { _id: payload.stationId },
  1328. { $pull: { blacklist: payload.playlistId } },
  1329. next
  1330. );
  1331. },
  1332. (res, next) => {
  1333. StationsModule.runJob(
  1334. "UPDATE_STATION",
  1335. {
  1336. stationId: payload.stationId
  1337. },
  1338. this
  1339. )
  1340. .then(() => {
  1341. next();
  1342. })
  1343. .catch(next);
  1344. }
  1345. ],
  1346. async err => {
  1347. if (err && err !== true) {
  1348. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1349. return reject(new Error(err));
  1350. }
  1351. return resolve();
  1352. }
  1353. );
  1354. });
  1355. }
  1356. /**
  1357. * Removes autofilled or blacklisted playlist from a station
  1358. *
  1359. * @param {object} payload - object that contains the payload
  1360. * @param {string} payload.playlistId - the playlist id
  1361. * @returns {Promise} - returns promise (reject, resolve)
  1362. */
  1363. REMOVE_AUTOFILLED_OR_BLACKLISTED_PLAYLIST_FROM_STATIONS(payload) {
  1364. return new Promise((resolve, reject) => {
  1365. async.waterfall(
  1366. [
  1367. next => {
  1368. if (!payload.playlistId) next("Please specify a playlist id");
  1369. else next();
  1370. },
  1371. next => {
  1372. StationsModule.stationModel.updateMany(
  1373. {
  1374. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1375. },
  1376. {
  1377. $pull: {
  1378. "autofill.playlists": payload.playlistId,
  1379. blacklist: payload.playlistId
  1380. }
  1381. },
  1382. err => {
  1383. if (err) next(err);
  1384. else next();
  1385. }
  1386. );
  1387. }
  1388. ],
  1389. async err => {
  1390. if (err && err !== true) {
  1391. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1392. return reject(new Error(err));
  1393. }
  1394. return resolve();
  1395. }
  1396. );
  1397. });
  1398. }
  1399. /**
  1400. * Gets stations that autofill or blacklist a specific playlist
  1401. *
  1402. * @param {object} payload - object that contains the payload
  1403. * @param {string} payload.playlistId - the playlist id
  1404. * @returns {Promise} - returns promise (reject, resolve)
  1405. */
  1406. GET_STATIONS_THAT_AUTOFILL_OR_BLACKLIST_PLAYLIST(payload) {
  1407. return new Promise((resolve, reject) => {
  1408. DBModule.runJob(
  1409. "GET_MODEL",
  1410. {
  1411. modelName: "station"
  1412. },
  1413. this
  1414. ).then(stationModel => {
  1415. stationModel.find(
  1416. {
  1417. $or: [{ "autofill.playlists": payload.playlistId }, { blacklist: payload.playlistId }]
  1418. },
  1419. (err, stations) => {
  1420. if (err) reject(err);
  1421. else resolve({ stationIds: stations.map(station => station._id) });
  1422. }
  1423. );
  1424. });
  1425. });
  1426. }
  1427. /**
  1428. * Clears every queue
  1429. *
  1430. * @returns {Promise} - returns a promise (resolve, reject)
  1431. */
  1432. CLEAR_EVERY_STATION_QUEUE() {
  1433. return new Promise((resolve, reject) => {
  1434. async.waterfall(
  1435. [
  1436. next => {
  1437. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1438. if (err) next(err);
  1439. else {
  1440. StationsModule.stationModel.find({}, (err, stations) => {
  1441. if (err) next(err);
  1442. else {
  1443. async.eachLimit(
  1444. stations,
  1445. 1,
  1446. (station, next) => {
  1447. this.publishProgress({
  1448. status: "update",
  1449. message: `Updating station "${station._id}"`
  1450. });
  1451. StationsModule.runJob("UPDATE_STATION", {
  1452. stationId: station._id
  1453. })
  1454. .then(() => next())
  1455. .catch(next);
  1456. CacheModule.runJob("PUB", {
  1457. channel: "station.queueUpdate",
  1458. value: station._id
  1459. })
  1460. .then()
  1461. .catch();
  1462. },
  1463. next
  1464. );
  1465. }
  1466. });
  1467. }
  1468. });
  1469. }
  1470. ],
  1471. err => {
  1472. if (err) reject(err);
  1473. else resolve();
  1474. }
  1475. );
  1476. });
  1477. }
  1478. /**
  1479. * Resets a station queue
  1480. *
  1481. * @param {object} payload - object that contains the payload
  1482. * @param {string} payload.stationId - the station id
  1483. * @returns {Promise} - returns a promise (resolve, reject)
  1484. */
  1485. RESET_QUEUE(payload) {
  1486. return new Promise((resolve, reject) => {
  1487. async.waterfall(
  1488. [
  1489. next => {
  1490. StationsModule.runJob(
  1491. "AUTOFILL_STATION",
  1492. { stationId: payload.stationId, ignoreExistingQueue: true },
  1493. this
  1494. )
  1495. .then(() => {
  1496. CacheModule.runJob("PUB", {
  1497. channel: "station.queueUpdate",
  1498. value: payload.stationId
  1499. })
  1500. .then()
  1501. .catch();
  1502. next();
  1503. })
  1504. .catch(err => {
  1505. if (err === "Autofill is disabled in this station" || err === "Autofill limit reached")
  1506. StationsModule.stationModel
  1507. .updateOne({ _id: payload.stationId }, { $set: { queue: [] } }, this)
  1508. .then(() => next())
  1509. .catch(next);
  1510. else next(err);
  1511. });
  1512. },
  1513. next => {
  1514. StationsModule.runJob("UPDATE_STATION", { stationId: payload.stationId }, this)
  1515. .then(() => next())
  1516. .catch(next);
  1517. },
  1518. next => {
  1519. CacheModule.runJob("PUB", {
  1520. channel: "station.queueUpdate",
  1521. value: payload.stationId
  1522. })
  1523. .then(() => next())
  1524. .catch(next);
  1525. }
  1526. ],
  1527. err => {
  1528. if (err) reject(err);
  1529. else resolve();
  1530. }
  1531. );
  1532. });
  1533. }
  1534. /**
  1535. * Add to a station queue
  1536. *
  1537. * @param {object} payload - object that contains the payload
  1538. * @param {string} payload.stationId - the station id
  1539. * @param {string} payload.youtubeId - the youtube id
  1540. * @param {string} payload.requestUser - the requesting user id
  1541. * @returns {Promise} - returns a promise (resolve, reject)
  1542. */
  1543. ADD_TO_QUEUE(payload) {
  1544. return new Promise((resolve, reject) => {
  1545. const { stationId, youtubeId, requestUser } = payload;
  1546. async.waterfall(
  1547. [
  1548. next => {
  1549. StationsModule.runJob("GET_STATION", { stationId }, this)
  1550. .then(station => {
  1551. next(null, station);
  1552. })
  1553. .catch(next);
  1554. },
  1555. (station, next) => {
  1556. if (!station) return next("Station not found.");
  1557. if (!station.requests.enabled) return next("Requests are disabled in this station.");
  1558. if (station.currentSong && station.currentSong.youtubeId === youtubeId)
  1559. return next("That song is currently playing.");
  1560. if (station.queue.find(song => song.youtubeId === youtubeId))
  1561. return next("That song is already in the queue.");
  1562. return next(null, station);
  1563. },
  1564. (station, next) => {
  1565. MediaModule.runJob("GET_MEDIA", { youtubeId }, this)
  1566. .then(response => {
  1567. const { song } = response;
  1568. const { _id, title, skipDuration, artists, thumbnail, duration, verified } = song;
  1569. next(
  1570. null,
  1571. {
  1572. _id,
  1573. youtubeId,
  1574. title,
  1575. skipDuration,
  1576. artists,
  1577. thumbnail,
  1578. duration,
  1579. verified
  1580. },
  1581. station
  1582. );
  1583. })
  1584. .catch(next);
  1585. },
  1586. (song, station, next) => {
  1587. const blacklist = [];
  1588. async.eachLimit(
  1589. station.blacklist,
  1590. 1,
  1591. (playlistId, next) => {
  1592. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId }, this)
  1593. .then(playlist => {
  1594. blacklist.push(playlist);
  1595. next();
  1596. })
  1597. .catch(next);
  1598. },
  1599. err => {
  1600. next(err, song, station, blacklist);
  1601. }
  1602. );
  1603. },
  1604. (song, station, blacklist, next) => {
  1605. const blacklistedSongs = blacklist
  1606. .flatMap(blacklistedPlaylist => blacklistedPlaylist.songs)
  1607. .reduce(
  1608. (items, item) =>
  1609. items.find(x => x.youtubeId === item.youtubeId) ? [...items] : [...items, item],
  1610. []
  1611. );
  1612. if (blacklistedSongs.find(blacklistedSong => blacklistedSong.youtubeId === song.youtubeId))
  1613. next("That song is in an blacklisted playlist and cannot be played.");
  1614. else next(null, song, station);
  1615. },
  1616. (song, station, next) => {
  1617. song.requestedBy = requestUser;
  1618. song.requestedAt = Date.now();
  1619. if (station.queue.length === 0) return next(null, song);
  1620. if (
  1621. requestUser &&
  1622. station.queue.filter(queueSong => queueSong.requestedBy === song.requestedBy).length >=
  1623. station.requests.limit
  1624. )
  1625. return next(`The max amount of songs per user is ${station.requests.limit}.`);
  1626. return next(null, song);
  1627. },
  1628. // (song, station, next) => {
  1629. // song.requestedBy = session.userId;
  1630. // song.requestedAt = Date.now();
  1631. // let totalDuration = 0;
  1632. // station.queue.forEach(song => {
  1633. // totalDuration += song.duration;
  1634. // });
  1635. // if (totalDuration >= 3600 * 3) return next("The max length of the queue is 3 hours.");
  1636. // return next(null, song, station);
  1637. // },
  1638. // (song, station, next) => {
  1639. // if (station.queue.length === 0) return next(null, song, station);
  1640. // let totalDuration = 0;
  1641. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1642. // station.queue.forEach(song => {
  1643. // if (userId === song.requestedBy) {
  1644. // totalDuration += song.duration;
  1645. // }
  1646. // });
  1647. // if (totalDuration >= 900) return next("The max length of songs per user is 15 minutes.");
  1648. // return next(null, song, station);
  1649. // },
  1650. // (song, station, next) => {
  1651. // if (station.queue.length === 0) return next(null, song);
  1652. // let totalSongs = 0;
  1653. // const userId = station.queue[station.queue.length - 1].requestedBy;
  1654. // station.queue.forEach(song => {
  1655. // if (userId === song.requestedBy) {
  1656. // totalSongs += 1;
  1657. // }
  1658. // });
  1659. // if (totalSongs <= 2) return next(null, song);
  1660. // if (totalSongs > 3)
  1661. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1662. // if (
  1663. // station.queue[station.queue.length - 2].requestedBy !== userId ||
  1664. // station.queue[station.queue.length - 3] !== userId
  1665. // )
  1666. // return next("The max amount of songs per user is 3, and only 2 in a row is allowed.");
  1667. // return next(null, song);
  1668. // },
  1669. (song, next) => {
  1670. StationsModule.stationModel.updateOne(
  1671. { _id: stationId },
  1672. { $push: { queue: song } },
  1673. { runValidators: true },
  1674. next
  1675. );
  1676. },
  1677. (res, next) => {
  1678. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1679. .then(() => next())
  1680. .catch(next);
  1681. },
  1682. next => {
  1683. CacheModule.runJob(
  1684. "PUB",
  1685. {
  1686. channel: "station.queueUpdate",
  1687. value: stationId
  1688. },
  1689. this
  1690. )
  1691. .then(() => next())
  1692. .catch(next);
  1693. }
  1694. ],
  1695. err => {
  1696. if (err) reject(err);
  1697. else resolve();
  1698. }
  1699. );
  1700. });
  1701. }
  1702. /**
  1703. * Remove from a station queue
  1704. *
  1705. * @param {object} payload - object that contains the payload
  1706. * @param {string} payload.stationId - the station id
  1707. * @param {string} payload.youtubeId - the youtube id
  1708. * @returns {Promise} - returns a promise (resolve, reject)
  1709. */
  1710. REMOVE_FROM_QUEUE(payload) {
  1711. return new Promise((resolve, reject) => {
  1712. const { stationId, youtubeId } = payload;
  1713. async.waterfall(
  1714. [
  1715. next => {
  1716. StationsModule.runJob("GET_STATION", { stationId }, this)
  1717. .then(station => {
  1718. next(null, station);
  1719. })
  1720. .catch(next);
  1721. },
  1722. (station, next) => {
  1723. if (!station) return next("Station not found.");
  1724. if (!station.queue.find(song => song.youtubeId === youtubeId))
  1725. return next("That song is not currently in the queue.");
  1726. return StationsModule.stationModel.updateOne(
  1727. { _id: stationId },
  1728. { $pull: { queue: { youtubeId } } },
  1729. next
  1730. );
  1731. },
  1732. (res, next) => {
  1733. StationsModule.runJob("UPDATE_STATION", { stationId }, this)
  1734. .then(station => {
  1735. if (station.autofill.enabled)
  1736. StationsModule.runJob("AUTOFILL_STATION", { stationId }, this)
  1737. .then(() => next())
  1738. .catch(err => {
  1739. if (
  1740. err === "Autofill is disabled in this station" ||
  1741. err === "Autofill limit reached"
  1742. )
  1743. return next();
  1744. return next(err);
  1745. });
  1746. else next();
  1747. })
  1748. .catch(next);
  1749. },
  1750. next =>
  1751. CacheModule.runJob(
  1752. "PUB",
  1753. {
  1754. channel: "station.queueUpdate",
  1755. value: stationId
  1756. },
  1757. this
  1758. )
  1759. .then(() => next())
  1760. .catch(next)
  1761. ],
  1762. err => {
  1763. if (err) reject(err);
  1764. else resolve();
  1765. }
  1766. );
  1767. });
  1768. }
  1769. }
  1770. export default new _StationsModule();