stations.js 40 KB

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