stations.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761
  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. }
  407. return newQuery;
  408. });
  409. if (queryError) next(queryError);
  410. const queryObject = {};
  411. if (newQueries.length > 0) {
  412. if (operator === "and") queryObject.$and = newQueries;
  413. else if (operator === "or") queryObject.$or = newQueries;
  414. else if (operator === "nor") queryObject.$nor = newQueries;
  415. }
  416. next(null, queryObject);
  417. },
  418. (queryObject, next) => {
  419. StationsModule.stationModel.find(queryObject).count((err, count) => {
  420. next(err, queryObject, count);
  421. });
  422. },
  423. (queryObject, count, next) => {
  424. const { page, pageSize, properties, sort } = payload;
  425. StationsModule.stationModel
  426. .find(queryObject)
  427. .sort(sort)
  428. .skip(pageSize * (page - 1))
  429. .limit(pageSize)
  430. .select(properties.join(" "))
  431. .exec((err, stations) => {
  432. next(err, count, stations);
  433. });
  434. }
  435. ],
  436. (err, count, stations) => {
  437. if (err && err !== true) return reject(new Error(err));
  438. return resolve({ data: stations, count });
  439. }
  440. );
  441. });
  442. }
  443. /**
  444. * Updates the station in cache from mongo or deletes station in cache if no longer in mongo.
  445. *
  446. * @param {object} payload - object that contains the payload
  447. * @param {string} payload.stationId - the id of the station to update
  448. * @returns {Promise} - returns a promise (resolve, reject)
  449. */
  450. UPDATE_STATION(payload) {
  451. return new Promise((resolve, reject) => {
  452. async.waterfall(
  453. [
  454. next => {
  455. StationsModule.stationModel.findOne({ _id: payload.stationId }, next);
  456. },
  457. (station, next) => {
  458. if (!station) {
  459. CacheModule.runJob("HDEL", {
  460. table: "stations",
  461. key: payload.stationId
  462. })
  463. .then()
  464. .catch();
  465. return next("Station not found");
  466. }
  467. return CacheModule.runJob(
  468. "HSET",
  469. {
  470. table: "stations",
  471. key: payload.stationId,
  472. value: station
  473. },
  474. this
  475. )
  476. .then(station => {
  477. next(null, station);
  478. })
  479. .catch(next);
  480. }
  481. ],
  482. async (err, station) => {
  483. if (err && err !== true) {
  484. err = await UtilsModule.runJob(
  485. "GET_ERROR",
  486. {
  487. error: err
  488. },
  489. this
  490. );
  491. reject(new Error(err));
  492. } else resolve(station);
  493. }
  494. );
  495. });
  496. }
  497. /**
  498. * Fills up the official station playlist queue using the songs from the official station playlist
  499. *
  500. * @param {object} payload - object that contains the payload
  501. * @param {string} payload.stationId - the id of the station
  502. * @param {string} payload.ignoreExistingQueue - ignore the existing queue songs, replacing the old queue with a completely fresh one
  503. * @returns {Promise} - returns a promise (resolve, reject)
  504. */
  505. FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST(payload) {
  506. return new Promise((resolve, reject) => {
  507. const { stationId, ignoreExistingQueue } = payload;
  508. async.waterfall(
  509. [
  510. next => {
  511. PlaylistsModule.runJob("GET_STATION_PLAYLIST", { stationId, includeSongs: true }, this)
  512. .then(response => {
  513. next(null, response.playlist);
  514. })
  515. .catch(next);
  516. },
  517. (playlist, next) => {
  518. StationsModule.runJob("GET_STATION", { stationId }, this)
  519. .then(station => {
  520. if (ignoreExistingQueue) station.queue = [];
  521. next(null, playlist, station);
  522. })
  523. .catch(next);
  524. },
  525. (playlist, station, next) => {
  526. if (station.playMode === "random") {
  527. UtilsModule.runJob("SHUFFLE", { array: playlist.songs }, this)
  528. .then(response => {
  529. next(null, response.array, station);
  530. })
  531. .catch(next);
  532. } else next(null, playlist.songs, station);
  533. },
  534. (_playlistSongs, station, next) => {
  535. let playlistSongs = JSON.parse(JSON.stringify(_playlistSongs));
  536. if (station.playMode === "sequential") {
  537. if (station.currentSongIndex <= playlistSongs.length) {
  538. const songsToAddToEnd = playlistSongs.splice(0, station.currentSongIndex);
  539. playlistSongs = [...playlistSongs, ...songsToAddToEnd];
  540. }
  541. }
  542. const songsStillNeeded = 50 - station.queue.length;
  543. const currentSongs = station.queue;
  544. const currentYoutubeIds = station.queue.map(song => song.youtubeId);
  545. const songsToAdd = [];
  546. let lastSongAdded = null;
  547. playlistSongs.every(song => {
  548. if (
  549. songsToAdd.length < songsStillNeeded &&
  550. currentYoutubeIds.indexOf(song.youtubeId) === -1
  551. ) {
  552. lastSongAdded = song;
  553. songsToAdd.push(song);
  554. return true;
  555. }
  556. if (songsToAdd.length >= songsStillNeeded) return false;
  557. return true;
  558. });
  559. let { currentSongIndex } = station;
  560. if (station.playMode === "sequential" && lastSongAdded) {
  561. const indexOfLastSong = _playlistSongs
  562. .map(song => song.youtubeId)
  563. .indexOf(lastSongAdded.youtubeId);
  564. if (indexOfLastSong !== -1) currentSongIndex = indexOfLastSong;
  565. }
  566. next(null, currentSongs, songsToAdd, currentSongIndex);
  567. },
  568. (currentSongs, songsToAdd, currentSongIndex, next) => {
  569. SongsModule.runJob("GET_SONGS", {
  570. songIds: songsToAdd.map(song => song._id),
  571. properties: [
  572. "youtubeId",
  573. "title",
  574. "duration",
  575. "skipDuration",
  576. "artists",
  577. "thumbnail",
  578. "status"
  579. ]
  580. })
  581. .then(response => {
  582. const newSongsToAdd = songsToAdd.map(song =>
  583. response.songs.find(newSong => newSong._id.toString() === song._id.toString())
  584. );
  585. next(null, currentSongs, newSongsToAdd, currentSongIndex);
  586. })
  587. .catch(err => next(err));
  588. },
  589. (currentSongs, songsToAdd, currentSongIndex, next) => {
  590. const newPlaylist = [...currentSongs, ...songsToAdd].map(song => {
  591. if (!song._id) song._id = null;
  592. return song;
  593. });
  594. next(null, newPlaylist, currentSongIndex);
  595. },
  596. (newPlaylist, currentSongIndex, next) => {
  597. StationsModule.stationModel.updateOne(
  598. { _id: stationId },
  599. { $set: { queue: newPlaylist, currentSongIndex } },
  600. { runValidators: true },
  601. err => {
  602. if (err) next(err);
  603. else
  604. StationsModule.runJob(
  605. "UPDATE_STATION",
  606. {
  607. stationId
  608. },
  609. this
  610. )
  611. .then(() => {
  612. next(null);
  613. })
  614. .catch(next);
  615. }
  616. );
  617. }
  618. ],
  619. err => {
  620. if (err) reject(err);
  621. else resolve();
  622. }
  623. );
  624. });
  625. }
  626. /**
  627. * Gets next station song
  628. *
  629. * @param {object} payload - object that contains the payload
  630. * @param {string} payload.stationId - the id of the station
  631. * @returns {Promise} - returns a promise (resolve, reject)
  632. */
  633. GET_NEXT_STATION_SONG(payload) {
  634. return new Promise((resolve, reject) => {
  635. const { stationId } = payload;
  636. async.waterfall(
  637. [
  638. next => {
  639. StationsModule.runJob("GET_STATION", { stationId }, this)
  640. .then(station => {
  641. next(null, station);
  642. })
  643. .catch(next);
  644. },
  645. (station, next) => {
  646. if (station.queue.length === 0) next("No songs available.");
  647. else {
  648. next(null, station.queue[0]);
  649. }
  650. },
  651. (queueSong, next) => {
  652. if (!queueSong._id) next(null, queueSong);
  653. else
  654. SongsModule.runJob("GET_SONG", { songId: queueSong._id }, this)
  655. .then(response => {
  656. const { song } = response;
  657. if (song) {
  658. const newSong = {
  659. _id: song._id,
  660. youtubeId: song.youtubeId,
  661. title: song.title,
  662. artists: song.artists,
  663. duration: song.duration,
  664. skipDuration: song.skipDuration,
  665. thumbnail: song.thumbnail,
  666. requestedAt: queueSong.requestedAt,
  667. requestedBy: queueSong.requestedBy,
  668. likes: song.likes,
  669. dislikes: song.dislikes,
  670. status: song.status
  671. };
  672. return next(null, newSong);
  673. }
  674. return next(null, song);
  675. })
  676. .catch(err => {
  677. next(err);
  678. });
  679. }
  680. ],
  681. (err, song) => {
  682. if (err) console.log(33333, err, payload);
  683. if (err) reject(err);
  684. else resolve({ song });
  685. }
  686. );
  687. });
  688. }
  689. /**
  690. * Removes first station queue song
  691. *
  692. * @param {object} payload - object that contains the payload
  693. * @param {string} payload.stationId - the id of the station
  694. * @returns {Promise} - returns a promise (resolve, reject)
  695. */
  696. REMOVE_FIRST_QUEUE_SONG(payload) {
  697. return new Promise((resolve, reject) => {
  698. const { stationId } = payload;
  699. async.waterfall(
  700. [
  701. next => {
  702. StationsModule.stationModel.updateOne(
  703. { _id: stationId },
  704. { $pop: { queue: -1 } },
  705. { runValidators: true },
  706. err => {
  707. if (err) next(err);
  708. else
  709. StationsModule.runJob(
  710. "UPDATE_STATION",
  711. {
  712. stationId
  713. },
  714. this
  715. )
  716. .then(() => {
  717. next(null);
  718. })
  719. .catch(next);
  720. }
  721. );
  722. }
  723. ],
  724. err => {
  725. if (err) reject(err);
  726. else resolve();
  727. }
  728. );
  729. });
  730. }
  731. /**
  732. * Skips a station
  733. *
  734. * @param {object} payload - object that contains the payload
  735. * @param {string} payload.stationId - the id of the station to skip
  736. * @param {string} payload.natural - whether to skip naturally or forcefully
  737. * @returns {Promise} - returns a promise (resolve, reject)
  738. */
  739. SKIP_STATION(payload) {
  740. return new Promise((resolve, reject) => {
  741. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  742. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  743. async.waterfall(
  744. [
  745. // Clears up any existing timers that would skip the station if the song ends
  746. next => {
  747. NotificationsModule.runJob("UNSCHEDULE", {
  748. name: `stations.nextSong?id=${payload.stationId}`
  749. })
  750. .then(() => {
  751. next();
  752. })
  753. .catch(next);
  754. },
  755. // Gets the station object
  756. next => {
  757. StationsModule.runJob(
  758. "GET_STATION",
  759. {
  760. stationId: payload.stationId
  761. },
  762. this
  763. )
  764. .then(station => next(null, station))
  765. .catch(next);
  766. },
  767. // eslint-disable-next-line consistent-return
  768. (station, next) => {
  769. if (!station) return next("Station not found.");
  770. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  771. return next(null, null, station); // Community station with party mode enabled and no songs in the queue
  772. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  773. // Community station with party mode enabled and songs in the queue
  774. if (station.paused) return next(null, null, station);
  775. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  776. .then(response => {
  777. StationsModule.runJob(
  778. "REMOVE_FIRST_QUEUE_SONG",
  779. { stationId: station._id },
  780. this
  781. ).then(() => {
  782. next(null, response.song, station);
  783. });
  784. })
  785. .catch(err => {
  786. if (err === "No songs available.") next(null, null, station);
  787. else next(err);
  788. });
  789. }
  790. if (station.type === "community" && !station.partyMode) {
  791. StationsModule.runJob(
  792. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  793. { stationId: station._id },
  794. this
  795. )
  796. .then(() => {
  797. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  798. .then(response => {
  799. StationsModule.runJob(
  800. "REMOVE_FIRST_QUEUE_SONG",
  801. { stationId: station._id },
  802. this
  803. ).then(() => {
  804. next(null, response.song, station);
  805. });
  806. })
  807. .catch(err => {
  808. if (err === "No songs available.") next(null, null, station);
  809. else next(err);
  810. });
  811. })
  812. .catch(next);
  813. }
  814. if (station.type === "official") {
  815. StationsModule.runJob(
  816. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  817. { stationId: station._id },
  818. this
  819. )
  820. .then(() => {
  821. StationsModule.runJob("GET_NEXT_STATION_SONG", { stationId: station._id }, this)
  822. .then(response => {
  823. StationsModule.runJob(
  824. "REMOVE_FIRST_QUEUE_SONG",
  825. { stationId: station._id },
  826. this
  827. )
  828. .then(() => {
  829. next(null, response.song, station);
  830. })
  831. .catch(next);
  832. })
  833. .catch(err => {
  834. if (err === "No songs available.") next(null, null, station);
  835. else next(err);
  836. });
  837. })
  838. .catch(next);
  839. }
  840. },
  841. (song, station, next) => {
  842. const $set = {};
  843. if (song === null) $set.currentSong = null;
  844. else {
  845. $set.currentSong = {
  846. _id: song._id,
  847. youtubeId: song.youtubeId,
  848. title: song.title,
  849. artists: song.artists,
  850. duration: song.duration,
  851. skipDuration: song.skipDuration,
  852. thumbnail: song.thumbnail,
  853. requestedAt: song.requestedAt,
  854. requestedBy: song.requestedBy,
  855. status: song.status
  856. };
  857. }
  858. $set.startedAt = Date.now();
  859. $set.timePaused = 0;
  860. if (station.paused) $set.pausedAt = Date.now();
  861. next(null, $set, song, station);
  862. },
  863. ($set, song, station, next) => {
  864. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  865. if (err) return next(err);
  866. return StationsModule.runJob("UPDATE_STATION", { stationId: station._id }, this)
  867. .then(station => {
  868. CacheModule.runJob("PUB", {
  869. channel: "station.queueUpdate",
  870. value: payload.stationId
  871. })
  872. .then()
  873. .catch();
  874. next(null, station, song);
  875. })
  876. .catch(next);
  877. });
  878. },
  879. (station, song, next) => {
  880. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  881. station.currentSong.likes = song.likes;
  882. station.currentSong.dislikes = song.dislikes;
  883. station.currentSong.skipVotes = 0;
  884. }
  885. next(null, station);
  886. }
  887. ],
  888. async (err, station) => {
  889. if (err) {
  890. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  891. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  892. return reject(new Error(err));
  893. }
  894. // TODO Pub/Sub this
  895. const { currentSong } = station;
  896. WSModule.runJob("EMIT_TO_ROOM", {
  897. room: `station.${station._id}`,
  898. args: [
  899. "event:station.nextSong",
  900. {
  901. data: {
  902. currentSong,
  903. startedAt: station.startedAt,
  904. paused: station.paused,
  905. timePaused: 0,
  906. natural: payload.natural
  907. }
  908. }
  909. ]
  910. });
  911. WSModule.runJob("EMIT_TO_ROOM", {
  912. room: `manage-station.${station._id}`,
  913. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  914. });
  915. if (station.privacy === "public")
  916. WSModule.runJob("EMIT_TO_ROOM", {
  917. room: "home",
  918. args: ["event:station.nextSong", { data: { stationId: station._id, currentSong } }]
  919. });
  920. else {
  921. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  922. sockets.forEach(async socketId => {
  923. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId });
  924. if (!socket) return;
  925. const { session } = socket;
  926. if (session.sessionId) {
  927. CacheModule.runJob("HGET", { table: "sessions", key: session.sessionId }).then(
  928. session => {
  929. if (session) {
  930. DBModule.runJob("GET_MODEL", { modelName: "user" }).then(userModel => {
  931. userModel.findOne({ _id: session.userId }, (err, user) => {
  932. if (!err && user) {
  933. if (user.role === "admin")
  934. socket.dispatch("event:station.nextSong", {
  935. data: {
  936. stationId: station._id,
  937. currentSong
  938. }
  939. });
  940. else if (
  941. station.type === "community" &&
  942. station.owner === session.userId
  943. )
  944. socket.dispatch("event:station.nextSong", {
  945. data: {
  946. stationId: station._id,
  947. currentSong
  948. }
  949. });
  950. }
  951. });
  952. });
  953. }
  954. }
  955. );
  956. }
  957. });
  958. }
  959. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  960. if (station.currentSong !== null && station.currentSong.youtubeId !== undefined) {
  961. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  962. sockets,
  963. room: `song.${station.currentSong.youtubeId}`
  964. });
  965. if (!station.paused) {
  966. NotificationsModule.runJob("SCHEDULE", {
  967. name: `stations.nextSong?id=${station._id}`,
  968. time: station.currentSong.duration * 1000,
  969. station
  970. });
  971. }
  972. } else WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", { sockets });
  973. });
  974. return resolve({ station });
  975. }
  976. );
  977. });
  978. }
  979. /**
  980. * Checks if a user can view/access a station
  981. *
  982. * @param {object} payload - object that contains the payload
  983. * @param {object} payload.station - the station object of the station in question
  984. * @param {string} payload.userId - the id of the user in question
  985. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  986. * @returns {Promise} - returns a promise (resolve, reject)
  987. */
  988. CAN_USER_VIEW_STATION(payload) {
  989. return new Promise((resolve, reject) => {
  990. async.waterfall(
  991. [
  992. next => {
  993. if (payload.station.privacy === "public") return next(true);
  994. if (payload.station.privacy === "unlisted")
  995. if (payload.hideUnlisted === true) return next();
  996. else return next(true);
  997. if (!payload.userId) return next("Not allowed");
  998. return next();
  999. },
  1000. next => {
  1001. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1002. userModel.findOne({ _id: payload.userId }, next);
  1003. });
  1004. },
  1005. (user, next) => {
  1006. if (!user) return next("Not allowed");
  1007. if (user.role === "admin") return next(true);
  1008. if (payload.station.type === "official") return next("Not allowed");
  1009. if (payload.station.owner === payload.userId) return next(true);
  1010. return next("Not allowed");
  1011. }
  1012. ],
  1013. async errOrResult => {
  1014. if (errOrResult !== true && errOrResult !== "Not allowed") {
  1015. errOrResult = await UtilsModule.runJob(
  1016. "GET_ERROR",
  1017. {
  1018. error: errOrResult
  1019. },
  1020. this
  1021. );
  1022. reject(new Error(errOrResult));
  1023. } else {
  1024. resolve(errOrResult === true);
  1025. }
  1026. }
  1027. );
  1028. });
  1029. }
  1030. /**
  1031. * Checks if a user has favorited a station or not
  1032. *
  1033. * @param {object} payload - object that contains the payload
  1034. * @param {object} payload.stationId - the id of the station in question
  1035. * @param {string} payload.userId - the id of the user in question
  1036. * @returns {Promise} - returns a promise (resolve, reject)
  1037. */
  1038. HAS_USER_FAVORITED_STATION(payload) {
  1039. return new Promise((resolve, reject) => {
  1040. async.waterfall(
  1041. [
  1042. next => {
  1043. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1044. userModel.findOne({ _id: payload.userId }, next);
  1045. });
  1046. },
  1047. (user, next) => {
  1048. if (!user) return next("User not found.");
  1049. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1050. return next(null, false);
  1051. }
  1052. ],
  1053. async (err, isStationFavorited) => {
  1054. if (err && err !== true) {
  1055. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1056. return reject(new Error(err));
  1057. }
  1058. return resolve(isStationFavorited);
  1059. }
  1060. );
  1061. });
  1062. }
  1063. /**
  1064. * Returns a list of sockets in a room that can and can't know about a station
  1065. *
  1066. * @param {object} payload - the payload object
  1067. * @param {object} payload.station - the station object
  1068. * @param {string} payload.room - the websockets room to get the sockets from
  1069. * @returns {Promise} - returns a promise (resolve, reject)
  1070. */
  1071. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1072. return new Promise((resolve, reject) => {
  1073. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1074. .then(socketIds => {
  1075. const sockets = [];
  1076. async.eachLimit(
  1077. socketIds,
  1078. 1,
  1079. (socketId, next) => {
  1080. WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this)
  1081. .then(socket => {
  1082. if (socket) sockets.push(socket);
  1083. next();
  1084. })
  1085. .catch(err => {
  1086. reject(err);
  1087. });
  1088. },
  1089. err => {
  1090. if (err) reject(err);
  1091. else {
  1092. let socketsThatCan = [];
  1093. const socketsThatCannot = [];
  1094. if (payload.station.privacy === "public") {
  1095. socketsThatCan = sockets;
  1096. resolve({ socketsThatCan, socketsThatCannot });
  1097. } else {
  1098. async.eachLimit(
  1099. sockets,
  1100. 1,
  1101. (socket, next) => {
  1102. const { session } = socket;
  1103. async.waterfall(
  1104. [
  1105. next => {
  1106. if (!session.sessionId) next("No session id");
  1107. else next();
  1108. },
  1109. next => {
  1110. CacheModule.runJob(
  1111. "HGET",
  1112. {
  1113. table: "sessions",
  1114. key: session.sessionId
  1115. },
  1116. this
  1117. )
  1118. .then(response => {
  1119. next(null, response);
  1120. })
  1121. .catch(next);
  1122. },
  1123. (session, next) => {
  1124. if (!session) next("No session");
  1125. else {
  1126. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1127. .then(userModel => {
  1128. next(null, userModel);
  1129. })
  1130. .catch(next);
  1131. }
  1132. },
  1133. (userModel, next) => {
  1134. if (!userModel) next("No user model");
  1135. else
  1136. userModel.findOne(
  1137. {
  1138. _id: session.userId
  1139. },
  1140. next
  1141. );
  1142. },
  1143. (user, next) => {
  1144. if (!user) next("No user found");
  1145. else if (user.role === "admin") {
  1146. socketsThatCan.push(socket);
  1147. next();
  1148. } else if (
  1149. payload.station.type === "community" &&
  1150. payload.station.owner === session.userId
  1151. ) {
  1152. socketsThatCan.push(socket);
  1153. next();
  1154. }
  1155. }
  1156. ],
  1157. err => {
  1158. if (err) socketsThatCannot.push(socket);
  1159. next();
  1160. }
  1161. );
  1162. },
  1163. err => {
  1164. if (err) reject(err);
  1165. else resolve({ socketsThatCan, socketsThatCannot });
  1166. }
  1167. );
  1168. }
  1169. }
  1170. }
  1171. );
  1172. })
  1173. .catch(reject);
  1174. });
  1175. }
  1176. /**
  1177. * Adds a playlist to be included in a station
  1178. *
  1179. * @param {object} payload - object that contains the payload
  1180. * @param {object} payload.stationId - the id of the station to include the playlist in
  1181. * @param {object} payload.playlistId - the id of the playlist to be included
  1182. * @returns {Promise} - returns a promise (resolve, reject)
  1183. */
  1184. INCLUDE_PLAYLIST(payload) {
  1185. return new Promise((resolve, reject) => {
  1186. async.waterfall(
  1187. [
  1188. next => {
  1189. if (!payload.stationId) next("Please specify a station id");
  1190. else if (!payload.playlistId) next("Please specify a playlist id");
  1191. else next();
  1192. },
  1193. next => {
  1194. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1195. .then(station => {
  1196. next(null, station);
  1197. })
  1198. .catch(next);
  1199. },
  1200. (station, next) => {
  1201. if (station.playlist === payload.playlistId) next("You cannot include the station playlist");
  1202. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1203. next("This playlist is already included");
  1204. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1205. next(
  1206. "This playlist is currently excluded, please remove it from there before including it"
  1207. );
  1208. else
  1209. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1210. .then(() => {
  1211. next(null);
  1212. })
  1213. .catch(next);
  1214. },
  1215. next => {
  1216. DBModule.runJob(
  1217. "GET_MODEL",
  1218. {
  1219. modelName: "station"
  1220. },
  1221. this
  1222. ).then(stationModel => {
  1223. stationModel.updateOne(
  1224. { _id: payload.stationId },
  1225. { $push: { includedPlaylists: payload.playlistId } },
  1226. next
  1227. );
  1228. });
  1229. },
  1230. (res, next) => {
  1231. StationsModule.runJob(
  1232. "UPDATE_STATION",
  1233. {
  1234. stationId: payload.stationId
  1235. },
  1236. this
  1237. )
  1238. .then(() => {
  1239. next();
  1240. })
  1241. .catch(next);
  1242. }
  1243. ],
  1244. async err => {
  1245. if (err && err !== true) {
  1246. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1247. return reject(new Error(err));
  1248. }
  1249. return resolve();
  1250. }
  1251. );
  1252. });
  1253. }
  1254. /**
  1255. * Removes a playlist that is included in a station
  1256. *
  1257. * @param {object} payload - object that contains the payload
  1258. * @param {object} payload.stationId - the id of the station
  1259. * @param {object} payload.playlistId - the id of the playlist
  1260. * @returns {Promise} - returns a promise (resolve, reject)
  1261. */
  1262. REMOVE_INCLUDED_PLAYLIST(payload) {
  1263. return new Promise((resolve, reject) => {
  1264. async.waterfall(
  1265. [
  1266. next => {
  1267. if (!payload.stationId) next("Please specify a station id");
  1268. else if (!payload.playlistId) next("Please specify a playlist id");
  1269. else next();
  1270. },
  1271. next => {
  1272. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1273. .then(station => {
  1274. next(null, station);
  1275. })
  1276. .catch(next);
  1277. },
  1278. (station, next) => {
  1279. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1280. next("This playlist isn't included");
  1281. else next();
  1282. },
  1283. next => {
  1284. DBModule.runJob(
  1285. "GET_MODEL",
  1286. {
  1287. modelName: "station"
  1288. },
  1289. this
  1290. ).then(stationModel => {
  1291. stationModel.updateOne(
  1292. { _id: payload.stationId },
  1293. { $pull: { includedPlaylists: payload.playlistId } },
  1294. next
  1295. );
  1296. });
  1297. },
  1298. (res, next) => {
  1299. StationsModule.runJob(
  1300. "UPDATE_STATION",
  1301. {
  1302. stationId: payload.stationId
  1303. },
  1304. this
  1305. )
  1306. .then(() => {
  1307. next();
  1308. })
  1309. .catch(next);
  1310. }
  1311. ],
  1312. async err => {
  1313. if (err && err !== true) {
  1314. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1315. return reject(new Error(err));
  1316. }
  1317. return resolve();
  1318. }
  1319. );
  1320. });
  1321. }
  1322. /**
  1323. * Adds a playlist to be excluded in a station
  1324. *
  1325. * @param {object} payload - object that contains the payload
  1326. * @param {object} payload.stationId - the id of the station
  1327. * @param {object} payload.playlistId - the id of the playlist
  1328. * @returns {Promise} - returns a promise (resolve, reject)
  1329. */
  1330. EXCLUDE_PLAYLIST(payload) {
  1331. return new Promise((resolve, reject) => {
  1332. async.waterfall(
  1333. [
  1334. next => {
  1335. if (!payload.stationId) next("Please specify a station id");
  1336. else if (!payload.playlistId) next("Please specify a playlist id");
  1337. else next();
  1338. },
  1339. next => {
  1340. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1341. .then(station => {
  1342. next(null, station);
  1343. })
  1344. .catch(next);
  1345. },
  1346. (station, next) => {
  1347. if (station.playlist === payload.playlistId) next("You cannot exclude the station playlist");
  1348. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1349. next("This playlist is already excluded");
  1350. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1351. next(
  1352. "This playlist is currently included, please remove it from there before excluding it"
  1353. );
  1354. else
  1355. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1356. .then(() => {
  1357. next(null);
  1358. })
  1359. .catch(next);
  1360. },
  1361. next => {
  1362. DBModule.runJob(
  1363. "GET_MODEL",
  1364. {
  1365. modelName: "station"
  1366. },
  1367. this
  1368. ).then(stationModel => {
  1369. stationModel.updateOne(
  1370. { _id: payload.stationId },
  1371. { $push: { excludedPlaylists: payload.playlistId } },
  1372. next
  1373. );
  1374. });
  1375. },
  1376. (res, next) => {
  1377. StationsModule.runJob(
  1378. "UPDATE_STATION",
  1379. {
  1380. stationId: payload.stationId
  1381. },
  1382. this
  1383. )
  1384. .then(() => {
  1385. next();
  1386. })
  1387. .catch(next);
  1388. }
  1389. ],
  1390. async err => {
  1391. if (err && err !== true) {
  1392. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1393. return reject(new Error(err));
  1394. }
  1395. return resolve();
  1396. }
  1397. );
  1398. });
  1399. }
  1400. /**
  1401. * Removes a playlist that is excluded in a station
  1402. *
  1403. * @param {object} payload - object that contains the payload
  1404. * @param {object} payload.stationId - the id of the station
  1405. * @param {object} payload.playlistId - the id of the playlist
  1406. * @returns {Promise} - returns a promise (resolve, reject)
  1407. */
  1408. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1409. return new Promise((resolve, reject) => {
  1410. async.waterfall(
  1411. [
  1412. next => {
  1413. if (!payload.stationId) next("Please specify a station id");
  1414. else if (!payload.playlistId) next("Please specify a playlist id");
  1415. else next();
  1416. },
  1417. next => {
  1418. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1419. .then(station => {
  1420. next(null, station);
  1421. })
  1422. .catch(next);
  1423. },
  1424. (station, next) => {
  1425. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1426. next("This playlist isn't excluded");
  1427. else next();
  1428. },
  1429. next => {
  1430. DBModule.runJob(
  1431. "GET_MODEL",
  1432. {
  1433. modelName: "station"
  1434. },
  1435. this
  1436. ).then(stationModel => {
  1437. stationModel.updateOne(
  1438. { _id: payload.stationId },
  1439. { $pull: { excludedPlaylists: payload.playlistId } },
  1440. next
  1441. );
  1442. });
  1443. },
  1444. (res, next) => {
  1445. StationsModule.runJob(
  1446. "UPDATE_STATION",
  1447. {
  1448. stationId: payload.stationId
  1449. },
  1450. this
  1451. )
  1452. .then(() => {
  1453. next();
  1454. })
  1455. .catch(next);
  1456. }
  1457. ],
  1458. async err => {
  1459. if (err && err !== true) {
  1460. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1461. return reject(new Error(err));
  1462. }
  1463. return resolve();
  1464. }
  1465. );
  1466. });
  1467. }
  1468. /**
  1469. * Removes included or excluded playlist from a station
  1470. *
  1471. * @param {object} payload - object that contains the payload
  1472. * @param {string} payload.playlistId - the playlist id
  1473. * @returns {Promise} - returns promise (reject, resolve)
  1474. */
  1475. REMOVE_INCLUDED_OR_EXCLUDED_PLAYLIST_FROM_STATIONS(payload) {
  1476. return new Promise((resolve, reject) => {
  1477. async.waterfall(
  1478. [
  1479. next => {
  1480. if (!payload.playlistId) next("Please specify a playlist id");
  1481. else next();
  1482. },
  1483. next => {
  1484. StationsModule.stationModel.updateMany(
  1485. {
  1486. $or: [
  1487. { includedPlaylists: payload.playlistId },
  1488. { excludedPlaylists: payload.playlistId }
  1489. ]
  1490. },
  1491. {
  1492. $pull: {
  1493. includedPlaylists: payload.playlistId,
  1494. excludedPlaylists: payload.playlistId
  1495. }
  1496. },
  1497. err => {
  1498. if (err) next(err);
  1499. else next();
  1500. }
  1501. );
  1502. }
  1503. ],
  1504. async err => {
  1505. if (err && err !== true) {
  1506. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1507. return reject(new Error(err));
  1508. }
  1509. return resolve();
  1510. }
  1511. );
  1512. });
  1513. }
  1514. /**
  1515. * Gets stations that include or exclude a specific playlist
  1516. *
  1517. * @param {object} payload - object that contains the payload
  1518. * @param {string} payload.playlistId - the playlist id
  1519. * @returns {Promise} - returns promise (reject, resolve)
  1520. */
  1521. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1522. return new Promise((resolve, reject) => {
  1523. DBModule.runJob(
  1524. "GET_MODEL",
  1525. {
  1526. modelName: "station"
  1527. },
  1528. this
  1529. ).then(stationModel => {
  1530. stationModel.find(
  1531. {
  1532. $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }]
  1533. },
  1534. (err, stations) => {
  1535. if (err) reject(err);
  1536. else resolve({ stationIds: stations.map(station => station._id) });
  1537. }
  1538. );
  1539. });
  1540. });
  1541. }
  1542. /**
  1543. * Clears every queue
  1544. *
  1545. * @returns {Promise} - returns a promise (resolve, reject)
  1546. */
  1547. CLEAR_EVERY_STATION_QUEUE() {
  1548. return new Promise((resolve, reject) => {
  1549. async.waterfall(
  1550. [
  1551. next => {
  1552. StationsModule.stationModel.updateMany({}, { $set: { queue: [] } }, err => {
  1553. if (err) next(err);
  1554. else {
  1555. StationsModule.stationModel.find({}, (err, stations) => {
  1556. if (err) next(err);
  1557. else {
  1558. async.eachLimit(
  1559. stations,
  1560. 1,
  1561. (station, next) => {
  1562. StationsModule.runJob("UPDATE_STATION", {
  1563. stationId: station._id
  1564. })
  1565. .then(() => next())
  1566. .catch(next);
  1567. CacheModule.runJob("PUB", {
  1568. channel: "station.queueUpdate",
  1569. value: station._id
  1570. })
  1571. .then()
  1572. .catch();
  1573. },
  1574. next
  1575. );
  1576. }
  1577. });
  1578. }
  1579. });
  1580. }
  1581. ],
  1582. err => {
  1583. if (err) reject(err);
  1584. else resolve();
  1585. }
  1586. );
  1587. });
  1588. }
  1589. /**
  1590. * Clears and refills a station queue
  1591. *
  1592. * @param {object} payload - object that contains the payload
  1593. * @param {string} payload.stationId - the station id
  1594. * @returns {Promise} - returns a promise (resolve, reject)
  1595. */
  1596. CLEAR_AND_REFILL_STATION_QUEUE(payload) {
  1597. return new Promise((resolve, reject) => {
  1598. async.waterfall(
  1599. [
  1600. next => {
  1601. StationsModule.runJob(
  1602. "FILL_UP_STATION_QUEUE_FROM_STATION_PLAYLIST",
  1603. { stationId: payload.stationId, ignoreExistingQueue: true },
  1604. this
  1605. )
  1606. .then(() => {
  1607. CacheModule.runJob("PUB", {
  1608. channel: "station.queueUpdate",
  1609. value: payload.stationId
  1610. })
  1611. .then()
  1612. .catch();
  1613. next();
  1614. })
  1615. .catch(err => {
  1616. next(err);
  1617. });
  1618. }
  1619. ],
  1620. err => {
  1621. if (err) reject(err);
  1622. else resolve();
  1623. }
  1624. );
  1625. });
  1626. }
  1627. }
  1628. export default new _StationsModule();