stations.js 45 KB

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