stations.js 38 KB

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