stations.js 46 KB

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