stations.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554
  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_OFFICIAL_STATION_PLAYLIST_QUEUE(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.playlist.length;
  458. const currentSongs = station.playlist;
  459. const currentSongIds = station.playlist.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 false;
  470. }
  471. return true;
  472. });
  473. next(null, [...currentSongs, ...songsToAdd]);
  474. },
  475. (newPlaylist, next) => {
  476. StationsModule.stationModel.updateOne(
  477. { _id: stationId },
  478. { $set: { playlist: newPlaylist } },
  479. { runValidators: true },
  480. () => {
  481. StationsModule.runJob(
  482. "UPDATE_STATION",
  483. {
  484. stationId
  485. },
  486. this
  487. )
  488. .then(() => {
  489. next(null);
  490. })
  491. .catch(next);
  492. }
  493. );
  494. }
  495. ],
  496. err => {
  497. if (err) reject(err);
  498. else resolve();
  499. }
  500. );
  501. });
  502. }
  503. /**
  504. * Gets next station song
  505. *
  506. * @param {object} payload - object that contains the payload
  507. * @param {string} payload.stationId - the id of the station
  508. * @returns {Promise} - returns a promise (resolve, reject)
  509. */
  510. GET_NEXT_STATION_SONG(payload) {
  511. return new Promise((resolve, reject) => {
  512. const { stationId } = payload;
  513. async.waterfall(
  514. [
  515. next => {
  516. StationsModule.runJob("GET_STATION", { stationId }, this)
  517. .then(station => {
  518. next(null, station);
  519. })
  520. .catch(next);
  521. },
  522. (station, next) => {
  523. if (station.playlist.length === 0) next("No songs available.");
  524. else {
  525. next(null, station.playlist[0]);
  526. }
  527. },
  528. (song, next) => {
  529. if (!song._id) next(null, song);
  530. else
  531. SongsModule.runJob("GET_SONG", { id: song._id }, this)
  532. .then(response => {
  533. const { song } = response;
  534. if (song) {
  535. const newSong = {
  536. _id: song._id,
  537. songId: song.songId,
  538. title: song.title,
  539. artists: song.artists,
  540. duration: song.duration,
  541. thumbnail: song.thumbnail,
  542. requestedAt: song.requestedAt
  543. };
  544. next(null, newSong);
  545. } else {
  546. next(null, song);
  547. }
  548. })
  549. .catch(next);
  550. }
  551. ],
  552. (err, song) => {
  553. if (err) console.log(33333, err, payload);
  554. if (err) reject(err);
  555. else resolve({ song });
  556. }
  557. );
  558. });
  559. }
  560. /**
  561. * Removes first official playlist queue song
  562. *
  563. * @param {object} payload - object that contains the payload
  564. * @param {string} payload.stationId - the id of the station
  565. * @returns {Promise} - returns a promise (resolve, reject)
  566. */
  567. REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG(payload) {
  568. return new Promise((resolve, reject) => {
  569. const { stationId } = payload;
  570. async.waterfall(
  571. [
  572. next => {
  573. StationsModule.stationModel.updateOne(
  574. { _id: stationId },
  575. { $pop: { playlist: -1 } },
  576. { runValidators: true },
  577. err => {
  578. if (err) next(err);
  579. else
  580. StationsModule.runJob(
  581. "UPDATE_STATION",
  582. {
  583. stationId
  584. },
  585. this
  586. )
  587. .then(() => {
  588. next(null);
  589. })
  590. .catch(next);
  591. }
  592. );
  593. }
  594. ],
  595. err => {
  596. if (err) reject(err);
  597. else resolve();
  598. }
  599. );
  600. });
  601. }
  602. /**
  603. * Skips a station
  604. *
  605. * @param {object} payload - object that contains the payload
  606. * @param {string} payload.stationId - the id of the station to skip
  607. * @returns {Promise} - returns a promise (resolve, reject)
  608. */
  609. SKIP_STATION(payload) {
  610. return new Promise((resolve, reject) => {
  611. StationsModule.log("INFO", `Skipping station ${payload.stationId}.`);
  612. StationsModule.log("STATION_ISSUE", `SKIP_STATION_CB - Station ID: ${payload.stationId}.`);
  613. async.waterfall(
  614. [
  615. // Clears up any existing timers that would skip the station if the song ends
  616. next => {
  617. NotificationsModule.runJob("UNSCHEDULE", {
  618. name: `stations.nextSong?id=${payload.stationId}`
  619. })
  620. .then(() => {
  621. next();
  622. })
  623. .catch(next);
  624. },
  625. // Gets the station object
  626. next => {
  627. StationsModule.runJob(
  628. "GET_STATION",
  629. {
  630. stationId: payload.stationId
  631. },
  632. this
  633. )
  634. .then(station => {
  635. next(null, station);
  636. })
  637. .catch(() => {});
  638. },
  639. // eslint-disable-next-line consistent-return
  640. (station, next) => {
  641. if (!station) return next("Station not found.");
  642. if (station.type === "community" && station.partyMode && station.queue.length === 0)
  643. return next(null, null, -11, station); // Community station with party mode enabled and no songs in the queue
  644. if (station.type === "community" && station.partyMode && station.queue.length > 0) {
  645. // Community station with party mode enabled and songs in the queue
  646. if (station.paused) return next(null, null, -19, station);
  647. return StationsModule.stationModel.updateOne(
  648. { _id: payload.stationId },
  649. {
  650. $pull: {
  651. queue: {
  652. _id: station.queue[0]._id
  653. }
  654. }
  655. },
  656. err => {
  657. if (err) return next(err);
  658. return next(null, station.queue[0], -12, station);
  659. }
  660. );
  661. }
  662. if (station.type === "community" && !station.partyMode) {
  663. StationsModule.runJob(
  664. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  665. { stationId: station._id },
  666. this
  667. )
  668. .then(() => {
  669. StationsModule.runJob(
  670. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  671. { stationId: station._id },
  672. this
  673. )
  674. .then(() => {
  675. StationsModule.runJob(
  676. "GET_NEXT_STATION_SONG",
  677. { stationId: station._id },
  678. this
  679. )
  680. .then(response => {
  681. next(null, response.song, 0, station);
  682. })
  683. .catch(err => {
  684. if (err === "No songs available.") next(null, null, 0, station);
  685. else next(err);
  686. });
  687. })
  688. .catch(next);
  689. })
  690. .catch(next);
  691. }
  692. // if (station.type === "community" && !station.partyMode) {
  693. // return DBModule.runJob("GET_MODEL", { modelName: "playlist" }, this).then(playlistModel =>
  694. // playlistModel.findOne({ _id: station.privatePlaylist }, (err, playlist) => {
  695. // if (err) return next(err);
  696. // if (!playlist) return next(null, null, -13, station);
  697. // playlist = playlist.songs;
  698. // if (playlist.length > 0) {
  699. // let currentSongIndex;
  700. // if (station.currentSongIndex < playlist.length - 1)
  701. // currentSongIndex = station.currentSongIndex + 1;
  702. // else currentSongIndex = 0;
  703. // const callback = (err, song) => {
  704. // if (err) return next(err);
  705. // if (song) return next(null, song, currentSongIndex, station);
  706. // const currentSong = {
  707. // songId: playlist[currentSongIndex].songId,
  708. // title: playlist[currentSongIndex].title,
  709. // duration: playlist[currentSongIndex].duration,
  710. // likes: -1,
  711. // dislikes: -1,
  712. // requestedAt: playlist[currentSongIndex].requestedAt
  713. // };
  714. // return next(null, currentSong, currentSongIndex, station);
  715. // };
  716. // if (mongoose.Types.ObjectId.isValid(playlist[currentSongIndex]._id))
  717. // return SongsModule.runJob(
  718. // "GET_SONG",
  719. // {
  720. // id: playlist[currentSongIndex]._id
  721. // },
  722. // this
  723. // )
  724. // .then(response => callback(null, response.song))
  725. // .catch(callback);
  726. // return SongsModule.runJob(
  727. // "GET_SONG_FROM_ID",
  728. // {
  729. // songId: playlist[currentSongIndex].songId
  730. // },
  731. // this
  732. // )
  733. // .then(response => callback(null, response.song))
  734. // .catch(callback);
  735. // }
  736. // return next(null, null, -14, station);
  737. // })
  738. // );
  739. // }
  740. if (station.type === "official") {
  741. StationsModule.runJob(
  742. "REMOVE_FIRST_OFFICIAL_PLAYLIST_QUEUE_SONG",
  743. { stationId: station._id },
  744. this
  745. )
  746. .then(() => {
  747. StationsModule.runJob(
  748. "FILL_UP_OFFICIAL_STATION_PLAYLIST_QUEUE",
  749. { stationId: station._id },
  750. this
  751. )
  752. .then(() => {
  753. StationsModule.runJob(
  754. "GET_NEXT_STATION_SONG",
  755. { stationId: station._id },
  756. this
  757. )
  758. .then(response => {
  759. next(null, response.song, 0, station);
  760. })
  761. .catch(err => {
  762. if (err === "No songs available.") next(null, null, 0, station);
  763. else next(err);
  764. });
  765. })
  766. .catch(next);
  767. })
  768. .catch(next);
  769. }
  770. },
  771. (song, currentSongIndex, station, next) => {
  772. const $set = {};
  773. if (song === null) $set.currentSong = null;
  774. else if (song.likes === -1 && song.dislikes === -1) {
  775. $set.currentSong = {
  776. songId: song.songId,
  777. title: song.title,
  778. duration: song.duration,
  779. skipDuration: 0,
  780. likes: -1,
  781. dislikes: -1,
  782. requestedAt: song.requestedAt
  783. };
  784. } else {
  785. $set.currentSong = {
  786. _id: song._id,
  787. songId: song.songId,
  788. title: song.title,
  789. artists: song.artists,
  790. duration: song.duration,
  791. likes: song.likes,
  792. dislikes: song.dislikes,
  793. skipDuration: song.skipDuration,
  794. thumbnail: song.thumbnail,
  795. requestedAt: song.requestedAt
  796. };
  797. }
  798. if (currentSongIndex >= 0) $set.currentSongIndex = currentSongIndex;
  799. $set.startedAt = Date.now();
  800. $set.timePaused = 0;
  801. if (station.paused) $set.pausedAt = Date.now();
  802. next(null, $set, station);
  803. },
  804. ($set, station, next) => {
  805. StationsModule.stationModel.updateOne({ _id: station._id }, { $set }, err => {
  806. if (err) return next(err);
  807. return StationsModule.runJob(
  808. "UPDATE_STATION",
  809. {
  810. stationId: station._id
  811. },
  812. this
  813. )
  814. .then(station => {
  815. if (station.type === "community" && station.partyMode === true)
  816. CacheModule.runJob("PUB", {
  817. channel: "station.queueUpdate",
  818. value: payload.stationId
  819. })
  820. .then()
  821. .catch();
  822. next(null, station);
  823. })
  824. .catch(next);
  825. });
  826. }
  827. ],
  828. async (err, station) => {
  829. if (err) {
  830. console.log(123, err);
  831. err = await UtilsModule.runJob(
  832. "GET_ERROR",
  833. {
  834. error: err
  835. },
  836. this
  837. );
  838. StationsModule.log("ERROR", `Skipping station "${payload.stationId}" failed. "${err}"`);
  839. reject(new Error(err));
  840. } else {
  841. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  842. station.currentSong.skipVotes = 0;
  843. }
  844. // TODO Pub/Sub this
  845. WSModule.runJob("EMIT_TO_ROOM", {
  846. room: `station.${station._id}`,
  847. args: [
  848. "event:songs.next",
  849. {
  850. currentSong: station.currentSong,
  851. startedAt: station.startedAt,
  852. paused: station.paused,
  853. timePaused: 0
  854. }
  855. ]
  856. })
  857. .then()
  858. .catch();
  859. if (station.privacy === "public") {
  860. WSModule.runJob("EMIT_TO_ROOM", {
  861. room: "home",
  862. args: ["event:station.nextSong", station._id, station.currentSong]
  863. })
  864. .then()
  865. .catch();
  866. } else {
  867. const sockets = await WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: "home" }, this);
  868. sockets.forEach(async socketId => {
  869. const socket = await WSModule.runJob("SOCKET_FROM_SOCKET_ID", { socketId }, this);
  870. const { session } = socket;
  871. if (session.sessionId) {
  872. CacheModule.runJob(
  873. "HGET",
  874. { table: "sessions", key: session.sessionId },
  875. this
  876. // eslint-disable-next-line no-loop-func
  877. ).then(session => {
  878. if (session) {
  879. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(
  880. userModel => {
  881. userModel.findOne(
  882. {
  883. _id: session.userId
  884. },
  885. (err, user) => {
  886. if (!err && user) {
  887. if (user.role === "admin")
  888. socket.dispatch(
  889. "event:station.nextSong",
  890. station._id,
  891. station.currentSong
  892. );
  893. else if (
  894. station.type === "community" &&
  895. station.owner === session.userId
  896. )
  897. socket.dispatch(
  898. "event:station.nextSong",
  899. station._id,
  900. station.currentSong
  901. );
  902. }
  903. }
  904. );
  905. }
  906. );
  907. }
  908. });
  909. }
  910. });
  911. }
  912. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: `station.${station._id}` }).then(sockets => {
  913. if (station.currentSong !== null && station.currentSong.songId !== undefined) {
  914. WSModule.runJob("SOCKETS_JOIN_SONG_ROOM", {
  915. sockets,
  916. room: `song.${station.currentSong.songId}`
  917. });
  918. if (!station.paused) {
  919. NotificationsModule.runJob("SCHEDULE", {
  920. name: `stations.nextSong?id=${station._id}`,
  921. time: station.currentSong.duration * 1000,
  922. station
  923. });
  924. }
  925. } else {
  926. WSModule.runJob("SOCKETS_LEAVE_SONG_ROOMS", {
  927. sockets
  928. });
  929. }
  930. });
  931. resolve({ station });
  932. }
  933. }
  934. );
  935. });
  936. }
  937. /**
  938. * Checks if a user can view/access a station
  939. *
  940. * @param {object} payload - object that contains the payload
  941. * @param {object} payload.station - the station object of the station in question
  942. * @param {string} payload.userId - the id of the user in question
  943. * @param {boolean} payload.hideUnlisted - whether the user is allowed to see unlisted stations or not
  944. * @returns {Promise} - returns a promise (resolve, reject)
  945. */
  946. CAN_USER_VIEW_STATION(payload) {
  947. return new Promise((resolve, reject) => {
  948. async.waterfall(
  949. [
  950. next => {
  951. if (payload.station.privacy === "public") return next(true);
  952. if (payload.station.privacy === "unlisted")
  953. if (payload.hideUnlisted === true) return next();
  954. else return next(true);
  955. if (!payload.userId) return next("Not allowed");
  956. return next();
  957. },
  958. next => {
  959. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  960. userModel.findOne({ _id: payload.userId }, next);
  961. });
  962. },
  963. (user, next) => {
  964. if (!user) return next("Not allowed");
  965. if (user.role === "admin") return next(true);
  966. if (payload.station.type === "official") return next("Not allowed");
  967. if (payload.station.owner === payload.userId) return next(true);
  968. return next("Not allowed");
  969. }
  970. ],
  971. async errOrResult => {
  972. if (errOrResult !== true && errOrResult !== "Not allowed") {
  973. errOrResult = await UtilsModule.runJob(
  974. "GET_ERROR",
  975. {
  976. error: errOrResult
  977. },
  978. this
  979. );
  980. reject(new Error(errOrResult));
  981. } else {
  982. resolve(errOrResult === true);
  983. }
  984. }
  985. );
  986. });
  987. }
  988. /**
  989. * Checks if a user has favorited a station or not
  990. *
  991. * @param {object} payload - object that contains the payload
  992. * @param {object} payload.stationId - the id of the station in question
  993. * @param {string} payload.userId - the id of the user in question
  994. * @returns {Promise} - returns a promise (resolve, reject)
  995. */
  996. HAS_USER_FAVORITED_STATION(payload) {
  997. return new Promise((resolve, reject) => {
  998. async.waterfall(
  999. [
  1000. next => {
  1001. DBModule.runJob("GET_MODEL", { modelName: "user" }, this).then(userModel => {
  1002. userModel.findOne({ _id: payload.userId }, next);
  1003. });
  1004. },
  1005. (user, next) => {
  1006. if (!user) return next("User not found.");
  1007. if (user.favoriteStations.indexOf(payload.stationId) !== -1) return next(null, true);
  1008. return next(null, false);
  1009. }
  1010. ],
  1011. async (err, isStationFavorited) => {
  1012. if (err && err !== true) {
  1013. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1014. return reject(new Error(err));
  1015. }
  1016. return resolve(isStationFavorited);
  1017. }
  1018. );
  1019. });
  1020. }
  1021. /**
  1022. * Returns a list of sockets in a room that can and can't know about a station
  1023. *
  1024. * @param {object} payload - the payload object
  1025. * @param {object} payload.station - the station object
  1026. * @param {string} payload.room - the websockets room to get the sockets from
  1027. * @returns {Promise} - returns a promise (resolve, reject)
  1028. */
  1029. GET_SOCKETS_THAT_CAN_KNOW_ABOUT_STATION(payload) {
  1030. return new Promise((resolve, reject) => {
  1031. WSModule.runJob("GET_SOCKETS_FOR_ROOM", { room: payload.room }, this)
  1032. .then(socketsObject => {
  1033. const sockets = Object.keys(socketsObject).map(socketKey => socketsObject[socketKey]);
  1034. let socketsThatCan = [];
  1035. const socketsThatCannot = [];
  1036. if (payload.station.privacy === "public") {
  1037. socketsThatCan = sockets;
  1038. resolve({ socketsThatCan, socketsThatCannot });
  1039. } else {
  1040. async.eachLimit(
  1041. sockets,
  1042. 1,
  1043. (socket, next) => {
  1044. const { session } = socket;
  1045. async.waterfall(
  1046. [
  1047. next => {
  1048. if (!session.sessionId) next("No session id");
  1049. else next();
  1050. },
  1051. next => {
  1052. CacheModule.runJob(
  1053. "HGET",
  1054. {
  1055. table: "sessions",
  1056. key: session.sessionId
  1057. },
  1058. this
  1059. )
  1060. .then(response => {
  1061. next(null, response);
  1062. })
  1063. .catch(next);
  1064. },
  1065. (session, next) => {
  1066. if (!session) next("No session");
  1067. else {
  1068. DBModule.runJob("GET_MODEL", { modelName: "user" }, this)
  1069. .then(userModel => {
  1070. next(null, userModel);
  1071. })
  1072. .catch(next);
  1073. }
  1074. },
  1075. (userModel, next) => {
  1076. if (!userModel) next("No user model");
  1077. else
  1078. userModel.findOne(
  1079. {
  1080. _id: session.userId
  1081. },
  1082. next
  1083. );
  1084. },
  1085. (user, next) => {
  1086. if (!user) next("No user found");
  1087. else if (user.role === "admin") {
  1088. socketsThatCan.push(socket);
  1089. next();
  1090. } else if (
  1091. payload.station.type === "community" &&
  1092. payload.station.owner === session.userId
  1093. ) {
  1094. socketsThatCan.push(socket);
  1095. next();
  1096. }
  1097. }
  1098. ],
  1099. err => {
  1100. if (err) socketsThatCannot.push(socket);
  1101. next();
  1102. }
  1103. );
  1104. },
  1105. err => {
  1106. if (err) reject(err);
  1107. else resolve({ socketsThatCan, socketsThatCannot });
  1108. }
  1109. );
  1110. }
  1111. })
  1112. .catch(reject);
  1113. });
  1114. }
  1115. /**
  1116. * Adds a playlist to be included in a station
  1117. *
  1118. * @param {object} payload - object that contains the payload
  1119. * @param {object} payload.stationId - the id of the station to include the playlist in
  1120. * @param {object} payload.playlistId - the id of the playlist to be included
  1121. * @returns {Promise} - returns a promise (resolve, reject)
  1122. */
  1123. INCLUDE_PLAYLIST(payload) {
  1124. return new Promise((resolve, reject) => {
  1125. async.waterfall(
  1126. [
  1127. next => {
  1128. if (!payload.stationId) next("Please specify a station id");
  1129. else if (!payload.playlistId) next("Please specify a playlist id");
  1130. else next();
  1131. },
  1132. next => {
  1133. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1134. .then(station => {
  1135. next(null, station);
  1136. })
  1137. .catch(next);
  1138. },
  1139. (station, next) => {
  1140. if (station.playlist2 === payload.playlistId) next("You cannot include the station playlist");
  1141. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1142. next("This playlist is already included");
  1143. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1144. next(
  1145. "This playlist is currently excluded, please remove it from there before including it"
  1146. );
  1147. else
  1148. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1149. .then(() => {
  1150. next(null);
  1151. })
  1152. .catch(next);
  1153. },
  1154. next => {
  1155. DBModule.runJob(
  1156. "GET_MODEL",
  1157. {
  1158. modelName: "station"
  1159. },
  1160. this
  1161. ).then(stationModel => {
  1162. stationModel.updateOne(
  1163. { _id: payload.stationId },
  1164. { $push: { includedPlaylists: payload.playlistId } },
  1165. next
  1166. );
  1167. });
  1168. },
  1169. (res, next) => {
  1170. StationsModule.runJob(
  1171. "UPDATE_STATION",
  1172. {
  1173. stationId: payload.stationId
  1174. },
  1175. this
  1176. )
  1177. .then(() => {
  1178. next();
  1179. })
  1180. .catch(next);
  1181. }
  1182. ],
  1183. async err => {
  1184. if (err && err !== true) {
  1185. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1186. return reject(new Error(err));
  1187. }
  1188. return resolve();
  1189. }
  1190. );
  1191. });
  1192. }
  1193. /**
  1194. * Removes a playlist that is included in a station
  1195. *
  1196. * @param {object} payload - object that contains the payload
  1197. * @param {object} payload.stationId - the id of the station
  1198. * @param {object} payload.playlistId - the id of the playlist
  1199. * @returns {Promise} - returns a promise (resolve, reject)
  1200. */
  1201. REMOVE_INCLUDED_PLAYLIST(payload) {
  1202. return new Promise((resolve, reject) => {
  1203. async.waterfall(
  1204. [
  1205. next => {
  1206. if (!payload.stationId) next("Please specify a station id");
  1207. else if (!payload.playlistId) next("Please specify a playlist id");
  1208. else next();
  1209. },
  1210. next => {
  1211. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1212. .then(station => {
  1213. next(null, station);
  1214. })
  1215. .catch(next);
  1216. },
  1217. (station, next) => {
  1218. if (station.includedPlaylists.indexOf(payload.playlistId) === -1)
  1219. next("This playlist isn't included");
  1220. else next();
  1221. },
  1222. next => {
  1223. DBModule.runJob(
  1224. "GET_MODEL",
  1225. {
  1226. modelName: "station"
  1227. },
  1228. this
  1229. ).then(stationModel => {
  1230. stationModel.updateOne(
  1231. { _id: payload.stationId },
  1232. { $pull: { includedPlaylists: payload.playlistId } },
  1233. next
  1234. );
  1235. });
  1236. },
  1237. (res, next) => {
  1238. StationsModule.runJob(
  1239. "UPDATE_STATION",
  1240. {
  1241. stationId: payload.stationId
  1242. },
  1243. this
  1244. )
  1245. .then(() => {
  1246. next();
  1247. })
  1248. .catch(next);
  1249. }
  1250. ],
  1251. async err => {
  1252. if (err && err !== true) {
  1253. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1254. return reject(new Error(err));
  1255. }
  1256. return resolve();
  1257. }
  1258. );
  1259. });
  1260. }
  1261. /**
  1262. * Adds a playlist to be excluded in a station
  1263. *
  1264. * @param {object} payload - object that contains the payload
  1265. * @param {object} payload.stationId - the id of the station
  1266. * @param {object} payload.playlistId - the id of the playlist
  1267. * @returns {Promise} - returns a promise (resolve, reject)
  1268. */
  1269. EXCLUDE_PLAYLIST(payload) {
  1270. return new Promise((resolve, reject) => {
  1271. async.waterfall(
  1272. [
  1273. next => {
  1274. if (!payload.stationId) next("Please specify a station id");
  1275. else if (!payload.playlistId) next("Please specify a playlist id");
  1276. else next();
  1277. },
  1278. next => {
  1279. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1280. .then(station => {
  1281. next(null, station);
  1282. })
  1283. .catch(next);
  1284. },
  1285. (station, next) => {
  1286. if (station.playlist2 === payload.playlistId) next("You cannot exclude the station playlist");
  1287. else if (station.excludedPlaylists.indexOf(payload.playlistId) !== -1)
  1288. next("This playlist is already excluded");
  1289. else if (station.includedPlaylists.indexOf(payload.playlistId) !== -1)
  1290. next(
  1291. "This playlist is currently included, please remove it from there before excluding it"
  1292. );
  1293. else
  1294. PlaylistsModule.runJob("GET_PLAYLIST", { playlistId: payload.playlistId }, this)
  1295. .then(() => {
  1296. next(null);
  1297. })
  1298. .catch(next);
  1299. },
  1300. next => {
  1301. DBModule.runJob(
  1302. "GET_MODEL",
  1303. {
  1304. modelName: "station"
  1305. },
  1306. this
  1307. ).then(stationModel => {
  1308. stationModel.updateOne(
  1309. { _id: payload.stationId },
  1310. { $push: { excludedPlaylists: payload.playlistId } },
  1311. next
  1312. );
  1313. });
  1314. },
  1315. (res, next) => {
  1316. StationsModule.runJob(
  1317. "UPDATE_STATION",
  1318. {
  1319. stationId: payload.stationId
  1320. },
  1321. this
  1322. )
  1323. .then(() => {
  1324. next();
  1325. })
  1326. .catch(next);
  1327. }
  1328. ],
  1329. async err => {
  1330. if (err && err !== true) {
  1331. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1332. return reject(new Error(err));
  1333. }
  1334. return resolve();
  1335. }
  1336. );
  1337. });
  1338. }
  1339. /**
  1340. * Removes a playlist that is excluded in a station
  1341. *
  1342. * @param {object} payload - object that contains the payload
  1343. * @param {object} payload.stationId - the id of the station
  1344. * @param {object} payload.playlistId - the id of the playlist
  1345. * @returns {Promise} - returns a promise (resolve, reject)
  1346. */
  1347. REMOVE_EXCLUDED_PLAYLIST(payload) {
  1348. return new Promise((resolve, reject) => {
  1349. console.log(112, payload);
  1350. async.waterfall(
  1351. [
  1352. next => {
  1353. if (!payload.stationId) next("Please specify a station id");
  1354. else if (!payload.playlistId) next("Please specify a playlist id");
  1355. else next();
  1356. },
  1357. next => {
  1358. StationsModule.runJob("GET_STATION", { stationId: payload.stationId }, this)
  1359. .then(station => {
  1360. next(null, station);
  1361. })
  1362. .catch(next);
  1363. },
  1364. (station, next) => {
  1365. if (station.excludedPlaylists.indexOf(payload.playlistId) === -1)
  1366. next("This playlist isn't excluded");
  1367. else next();
  1368. },
  1369. next => {
  1370. DBModule.runJob(
  1371. "GET_MODEL",
  1372. {
  1373. modelName: "station"
  1374. },
  1375. this
  1376. ).then(stationModel => {
  1377. stationModel.updateOne(
  1378. { _id: payload.stationId },
  1379. { $pull: { excludedPlaylists: payload.playlistId } },
  1380. next
  1381. );
  1382. });
  1383. },
  1384. (res, next) => {
  1385. StationsModule.runJob(
  1386. "UPDATE_STATION",
  1387. {
  1388. stationId: payload.stationId
  1389. },
  1390. this
  1391. )
  1392. .then(() => {
  1393. next();
  1394. })
  1395. .catch(next);
  1396. }
  1397. ],
  1398. async err => {
  1399. if (err && err !== true) {
  1400. err = await UtilsModule.runJob("GET_ERROR", { error: err }, this);
  1401. return reject(new Error(err));
  1402. }
  1403. return resolve();
  1404. }
  1405. );
  1406. });
  1407. }
  1408. /**
  1409. * Gets stations that include or exclude a specific playlist
  1410. *
  1411. * @param {object} payload - object that contains the payload
  1412. * @param {string} payload.playlistId - the playlist id
  1413. * @returns {Promise} - returns promise (reject, resolve)
  1414. */
  1415. GET_STATIONS_THAT_INCLUDE_OR_EXCLUDE_PLAYLIST(payload) {
  1416. return new Promise((resolve, reject) => {
  1417. DBModule.runJob(
  1418. "GET_MODEL",
  1419. {
  1420. modelName: "station"
  1421. },
  1422. this
  1423. ).then(stationModel => {
  1424. stationModel.find(
  1425. { $or: [{ includedPlaylists: payload.playlistId }, { excludedPlaylists: payload.playlistId }] },
  1426. (err, stations) => {
  1427. if (err) reject(err);
  1428. else resolve({ stationIds: stations.map(station => station._id) });
  1429. }
  1430. );
  1431. });
  1432. });
  1433. }
  1434. }
  1435. export default new _StationsModule();