stations.js 40 KB

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