stations.js 40 KB

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