diff --git a/src/Ombi.Core/Engine/BaseMediaEngine.cs b/src/Ombi.Core/Engine/BaseMediaEngine.cs index deef9ebea..71a756543 100644 --- a/src/Ombi.Core/Engine/BaseMediaEngine.cs +++ b/src/Ombi.Core/Engine/BaseMediaEngine.cs @@ -127,7 +127,7 @@ namespace Ombi.Core.Engine UserId = user.Id }; } - var settings = await Cache.GetOrAdd(CacheKeys.OmbiSettings, async () => await OmbiSettings.GetSettingsAsync()); + var settings = await Cache.GetOrAddAsync(CacheKeys.OmbiSettings, () => OmbiSettings.GetSettingsAsync()); var result = new HideResult { Hide = settings.HideRequestsUsers, diff --git a/src/Ombi.Core/Engine/MovieRequestEngine.cs b/src/Ombi.Core/Engine/MovieRequestEngine.cs index 269961c2f..88958971e 100644 --- a/src/Ombi.Core/Engine/MovieRequestEngine.cs +++ b/src/Ombi.Core/Engine/MovieRequestEngine.cs @@ -30,7 +30,7 @@ namespace Ombi.Core.Engine public MovieRequestEngine(IMovieDbApi movieApi, IRequestServiceMain requestService, IPrincipal user, INotificationHelper helper, IRuleEvaluator r, IMovieSender sender, ILogger log, OmbiUserManager manager, IRepository rl, ICacheService cache, - ISettingsService ombiSettings, IRepository sub) + ISettingsService ombiSettings, IRepository sub, IMediaCacheService mediaCacheService) : base(user, requestService, r, manager, cache, ombiSettings, sub) { MovieApi = movieApi; @@ -38,6 +38,7 @@ namespace Ombi.Core.Engine Sender = sender; Logger = log; _requestLog = rl; + _mediaCacheService = mediaCacheService; } private IMovieDbApi MovieApi { get; } @@ -45,6 +46,7 @@ namespace Ombi.Core.Engine private IMovieSender Sender { get; } private ILogger Logger { get; } private readonly IRepository _requestLog; + private readonly IMediaCacheService _mediaCacheService; /// /// Requests the movie. @@ -371,7 +373,6 @@ namespace Ombi.Core.Engine }; } - public async Task UpdateAdvancedOptions(MediaAdvancedOptions options) { var request = await MovieRepository.Find(options.RequestId); @@ -527,6 +528,7 @@ namespace Ombi.Core.Engine // We are denying a request await NotificationHelper.Notify(request, NotificationType.RequestDeclined); await MovieRepository.Update(request); + await _mediaCacheService.Purge(); return new RequestEngineResult { @@ -555,6 +557,7 @@ namespace Ombi.Core.Engine { await NotificationHelper.Notify(request, NotificationType.RequestApproved); } + await _mediaCacheService.Purge(); return await ProcessSendingMovie(request); } @@ -562,8 +565,8 @@ namespace Ombi.Core.Engine public async Task RequestCollection(int collectionId, CancellationToken cancellationToken) { var langCode = await DefaultLanguageCode(null); - var collections = await Cache.GetOrAdd($"GetCollection{collectionId}{langCode}", - async () => await MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTime.Now.AddDays(1), cancellationToken); + var collections = await Cache.GetOrAddAsync($"GetCollection{collectionId}{langCode}", + () => MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTimeOffset.Now.AddDays(1)); var results = new List(); foreach (var collection in collections.parts) @@ -639,6 +642,7 @@ namespace Ombi.Core.Engine results.RootPathOverride = request.RootPathOverride; await MovieRepository.Update(results); + await _mediaCacheService.Purge(); return results; } @@ -651,12 +655,14 @@ namespace Ombi.Core.Engine { var request = await MovieRepository.GetAll().FirstOrDefaultAsync(x => x.Id == requestId); await MovieRepository.Delete(request); + await _mediaCacheService.Purge(); } public async Task RemoveAllMovieRequests() { var request = MovieRepository.GetAll(); await MovieRepository.DeleteRange(request); + await _mediaCacheService.Purge(); } public async Task UserHasRequest(string userId) @@ -692,6 +698,7 @@ namespace Ombi.Core.Engine request.Available = false; await MovieRepository.Update(request); + await _mediaCacheService.Purge(); return new RequestEngineResult { @@ -715,6 +722,7 @@ namespace Ombi.Core.Engine request.MarkedAsAvailable = DateTime.Now; await NotificationHelper.Notify(request, NotificationType.RequestAvailable); await MovieRepository.Update(request); + await _mediaCacheService.Purge(); return new RequestEngineResult { @@ -733,6 +741,8 @@ namespace Ombi.Core.Engine await NotificationHelper.NewRequest(model); } + await _mediaCacheService.Purge(); + await _requestLog.Add(new RequestLog { UserId = requestOnBehalf.HasValue() ? requestOnBehalf : (await GetUser()).Id, diff --git a/src/Ombi.Core/Engine/MovieSearchEngine.cs b/src/Ombi.Core/Engine/MovieSearchEngine.cs index 11bcfbfa2..d911c1cf5 100644 --- a/src/Ombi.Core/Engine/MovieSearchEngine.cs +++ b/src/Ombi.Core/Engine/MovieSearchEngine.cs @@ -45,9 +45,9 @@ namespace Ombi.Core.Engine public async Task LookupImdbInformation(int theMovieDbId, string langCode = null) { langCode = await DefaultLanguageCode(langCode); - var movieInfo = await Cache.GetOrAdd(nameof(LookupImdbInformation) + langCode + theMovieDbId, - async () => await MovieApi.GetMovieInformationWithExtraInfo(theMovieDbId, langCode), - DateTime.Now.AddHours(12)); + var movieInfo = await Cache.GetOrAddAsync(nameof(LookupImdbInformation) + langCode + theMovieDbId, + () => MovieApi.GetMovieInformationWithExtraInfo(theMovieDbId, langCode), + DateTimeOffset.Now.AddHours(12)); var viewMovie = Mapper.Map(movieInfo); return await ProcessSingleMovie(viewMovie, true); @@ -121,11 +121,11 @@ namespace Ombi.Core.Engine public async Task> PopularMovies() { - var result = await Cache.GetOrAdd(CacheKeys.PopularMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.PopularMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.PopularMovies(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Take(ResultLimit)); // Take x to stop us overloading the API @@ -139,11 +139,11 @@ namespace Ombi.Core.Engine /// public async Task> TopRatedMovies() { - var result = await Cache.GetOrAdd(CacheKeys.TopRatedMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.TopRatedMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.TopRated(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Take(ResultLimit)); // Take x to stop us overloading the API @@ -157,11 +157,11 @@ namespace Ombi.Core.Engine /// public async Task> UpcomingMovies() { - var result = await Cache.GetOrAdd(CacheKeys.UpcomingMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.UpcomingMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.Upcoming(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { Logger.LogDebug("Search Result: {result}", result); @@ -176,11 +176,11 @@ namespace Ombi.Core.Engine /// public async Task> NowPlayingMovies() { - var result = await Cache.GetOrAdd(CacheKeys.NowPlayingMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.NowPlayingMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.NowPlaying(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Take(ResultLimit)); // Take x to stop us overloading the API diff --git a/src/Ombi.Core/Engine/TvRequestEngine.cs b/src/Ombi.Core/Engine/TvRequestEngine.cs index 531fa161d..086eff0c9 100644 --- a/src/Ombi.Core/Engine/TvRequestEngine.cs +++ b/src/Ombi.Core/Engine/TvRequestEngine.cs @@ -35,7 +35,7 @@ namespace Ombi.Core.Engine public TvRequestEngine(ITvMazeApi tvApi, IMovieDbApi movApi, IRequestServiceMain requestService, IPrincipal user, INotificationHelper helper, IRuleEvaluator rule, OmbiUserManager manager, ILogger logger, ITvSender sender, IRepository rl, ISettingsService settings, ICacheService cache, - IRepository sub) : base(user, requestService, rule, manager, cache, settings, sub) + IRepository sub, IMediaCacheService mediaCacheService) : base(user, requestService, rule, manager, cache, settings, sub) { TvApi = tvApi; MovieDbApi = movApi; @@ -43,6 +43,7 @@ namespace Ombi.Core.Engine _logger = logger; TvSender = sender; _requestLog = rl; + _mediaCacheService = mediaCacheService; } private INotificationHelper NotificationHelper { get; } @@ -52,6 +53,7 @@ namespace Ombi.Core.Engine private readonly ILogger _logger; private readonly IRepository _requestLog; + private readonly IMediaCacheService _mediaCacheService; public async Task RequestTvShow(TvRequestViewModel tv) { @@ -329,6 +331,7 @@ namespace Ombi.Core.Engine Collection = allRequests }; } + public async Task> GetRequests() { var shouldHide = await HideFromOtherUsers(); @@ -348,7 +351,6 @@ namespace Ombi.Core.Engine return allRequests; } - public async Task> GetRequests(int count, int position, string sortProperty, string sortOrder) { var shouldHide = await HideFromOtherUsers(); @@ -404,7 +406,7 @@ namespace Ombi.Core.Engine }; } - public async Task> GetRequests(int count, int position, string sortProperty, string sortOrder, RequestStatus status) + public async Task> GetRequests(int count, int position, string sortProperty, string sortOrder, RequestStatus status) { var shouldHide = await HideFromOtherUsers(); List allRequests; @@ -476,6 +478,7 @@ namespace Ombi.Core.Engine Total = total, }; } + public async Task> GetUnavailableRequests(int count, int position, string sortProperty, string sortOrder) { var shouldHide = await HideFromOtherUsers(); @@ -529,7 +532,6 @@ namespace Ombi.Core.Engine }; } - public async Task> GetRequestsLite() { var shouldHide = await HideFromOtherUsers(); @@ -699,6 +701,7 @@ namespace Ombi.Core.Engine } await TvRepository.UpdateChild(request); + await _mediaCacheService.Purge(); if (request.Approved) { @@ -725,6 +728,7 @@ namespace Ombi.Core.Engine request.Denied = true; request.DeniedReason = reason; await TvRepository.UpdateChild(request); + await _mediaCacheService.Purge(); await NotificationHelper.Notify(request, NotificationType.RequestDeclined); return new RequestEngineResult { @@ -735,6 +739,7 @@ namespace Ombi.Core.Engine public async Task UpdateChildRequest(ChildRequests request) { await TvRepository.UpdateChild(request); + await _mediaCacheService.Purge(); return request; } @@ -754,12 +759,14 @@ namespace Ombi.Core.Engine } await TvRepository.Db.SaveChangesAsync(); + await _mediaCacheService.Purge(); } public async Task RemoveTvRequest(int requestId) { var request = await TvRepository.Get().FirstOrDefaultAsync(x => x.Id == requestId); await TvRepository.Delete(request); + await _mediaCacheService.Purge(); } public async Task UserHasRequest(string userId) @@ -786,6 +793,7 @@ namespace Ombi.Core.Engine } } await TvRepository.UpdateChild(request); + await _mediaCacheService.Purge(); return new RequestEngineResult { Result = true, @@ -814,6 +822,7 @@ namespace Ombi.Core.Engine } await TvRepository.UpdateChild(request); await NotificationHelper.Notify(request, NotificationType.RequestAvailable); + await _mediaCacheService.Purge(); return new RequestEngineResult { Result = true, @@ -888,19 +897,6 @@ namespace Ombi.Core.Engine return await AfterRequest(model.ChildRequests.FirstOrDefault(), requestOnBehalf); } - private static List SortEpisodes(List items) - { - foreach (var value in items) - { - foreach (var requests in value.SeasonRequests) - { - requests.Episodes = requests.Episodes.OrderBy(x => x.EpisodeNumber).ToList(); - } - } - return items; - } - - public async Task ReProcessRequest(int requestId, CancellationToken cancellationToken) { var request = await TvRepository.GetChild().FirstOrDefaultAsync(x => x.Id == requestId, cancellationToken); @@ -933,6 +929,7 @@ namespace Ombi.Core.Engine RequestType = RequestType.TvShow, EpisodeCount = model.SeasonRequests.Select(m => m.Episodes.Count).Sum(), }); + await _mediaCacheService.Purge(); return await ProcessSendingShow(model); } diff --git a/src/Ombi.Core/Engine/TvSearchEngine.cs b/src/Ombi.Core/Engine/TvSearchEngine.cs index d549f9f56..518b97720 100644 --- a/src/Ombi.Core/Engine/TvSearchEngine.cs +++ b/src/Ombi.Core/Engine/TvSearchEngine.cs @@ -77,16 +77,16 @@ namespace Ombi.Core.Engine public async Task GetShowInformation(string tvdbid, CancellationToken token) { - var show = await Cache.GetOrAdd(nameof(GetShowInformation) + tvdbid, - async () => await TvMazeApi.ShowLookupByTheTvDbId(int.Parse(tvdbid)), DateTime.Now.AddHours(12)); + var show = await Cache.GetOrAddAsync(nameof(GetShowInformation) + tvdbid, + () => TvMazeApi.ShowLookupByTheTvDbId(int.Parse(tvdbid)), DateTimeOffset.Now.AddHours(12)); if (show == null) { // We don't have enough information return null; } - var episodes = await Cache.GetOrAdd("TvMazeEpisodeLookup" + show.id, - async () => await TvMazeApi.EpisodeLookup(show.id), DateTime.Now.AddHours(12)); + var episodes = await Cache.GetOrAddAsync("TvMazeEpisodeLookup" + show.id, + () => TvMazeApi.EpisodeLookup(show.id), DateTimeOffset.Now.AddHours(12)); if (episodes == null || !episodes.Any()) { // We don't have enough information @@ -133,7 +133,7 @@ namespace Ombi.Core.Engine public async Task> Popular() { - var result = await Cache.GetOrAdd(CacheKeys.PopularTv, async () => await TraktApi.GetPopularShows(null, ResultLimit), DateTime.Now.AddHours(12)); + var result = await Cache.GetOrAddAsync(CacheKeys.PopularTv, () => TraktApi.GetPopularShows(null, ResultLimit), DateTimeOffset.Now.AddHours(12)); var processed = ProcessResults(result); return await processed; } @@ -146,8 +146,8 @@ namespace Ombi.Core.Engine var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Popular) + langCode + pagesToLoad.Page, - async () => await TraktApi.GetPopularShows(pagesToLoad.Page, ResultLimit), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Popular) + langCode + pagesToLoad.Page, + () => TraktApi.GetPopularShows(pagesToLoad.Page, ResultLimit), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } @@ -158,7 +158,7 @@ namespace Ombi.Core.Engine public async Task> Anticipated() { - var result = await Cache.GetOrAdd(CacheKeys.AnticipatedTv, async () => await TraktApi.GetAnticipatedShows(null, ResultLimit), DateTime.Now.AddHours(12)); + var result = await Cache.GetOrAddAsync(CacheKeys.AnticipatedTv, () => TraktApi.GetAnticipatedShows(null, ResultLimit), DateTimeOffset.Now.AddHours(12)); var processed = ProcessResults(result); return await processed; } @@ -171,8 +171,8 @@ namespace Ombi.Core.Engine var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Anticipated) + langCode + pagesToLoad.Page, - async () => await TraktApi.GetAnticipatedShows(pagesToLoad.Page, ResultLimit), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Anticipated) + langCode + pagesToLoad.Page, + () => TraktApi.GetAnticipatedShows(pagesToLoad.Page, ResultLimit), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } var processed = ProcessResults(results); @@ -181,7 +181,7 @@ namespace Ombi.Core.Engine public async Task> Trending() { - var result = await Cache.GetOrAdd(CacheKeys.TrendingTv, async () => await TraktApi.GetTrendingShows(null, ResultLimit), DateTime.Now.AddHours(12)); + var result = await Cache.GetOrAddAsync(CacheKeys.TrendingTv, () => TraktApi.GetTrendingShows(null, ResultLimit), DateTimeOffset.Now.AddHours(12)); var processed = ProcessResults(result); return await processed; } @@ -195,8 +195,8 @@ namespace Ombi.Core.Engine var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Trending) + langCode + pagesToLoad.Page, - async () => await TraktApi.GetTrendingShows(pagesToLoad.Page, ResultLimit), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Trending) + langCode + pagesToLoad.Page, + () => TraktApi.GetTrendingShows(pagesToLoad.Page, ResultLimit), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } var processed = ProcessResults(results); diff --git a/src/Ombi.Core/Engine/V2/MovieSearchEngineV2.cs b/src/Ombi.Core/Engine/V2/MovieSearchEngineV2.cs index 4ff99225a..25c0fc2a2 100644 --- a/src/Ombi.Core/Engine/V2/MovieSearchEngineV2.cs +++ b/src/Ombi.Core/Engine/V2/MovieSearchEngineV2.cs @@ -51,8 +51,8 @@ namespace Ombi.Core.Engine.V2 public async Task GetFullMovieInformation(int theMovieDbId, CancellationToken cancellationToken, string langCode = null) { langCode = await DefaultLanguageCode(langCode); - var movieInfo = await Cache.GetOrAdd(nameof(GetFullMovieInformation) + theMovieDbId + langCode, - async () => await MovieApi.GetFullMovieInfo(theMovieDbId, cancellationToken, langCode), DateTime.Now.AddHours(12), cancellationToken); + var movieInfo = await Cache.GetOrAddAsync(nameof(GetFullMovieInformation) + theMovieDbId + langCode, + () => MovieApi.GetFullMovieInfo(theMovieDbId, cancellationToken, langCode), DateTimeOffset.Now.AddHours(12)); return await ProcessSingleMovie(movieInfo); } @@ -61,8 +61,8 @@ namespace Ombi.Core.Engine.V2 { langCode = await DefaultLanguageCode(langCode); var request = await RequestService.MovieRequestService.Find(requestId); - var movieInfo = await Cache.GetOrAdd(nameof(GetFullMovieInformation) + request.TheMovieDbId + langCode, - async () => await MovieApi.GetFullMovieInfo(request.TheMovieDbId, cancellationToken, langCode), DateTime.Now.AddHours(12), cancellationToken); + var movieInfo = await Cache.GetOrAddAsync(nameof(GetFullMovieInformation) + request.TheMovieDbId + langCode, + () => MovieApi.GetFullMovieInfo(request.TheMovieDbId, cancellationToken, langCode), DateTimeOffset.Now.AddHours(12)); return await ProcessSingleMovie(movieInfo); } @@ -70,8 +70,8 @@ namespace Ombi.Core.Engine.V2 public async Task GetCollection(int collectionId, CancellationToken cancellationToken, string langCode = null) { langCode = await DefaultLanguageCode(langCode); - var collections = await Cache.GetOrAdd(nameof(GetCollection) + collectionId + langCode, - async () => await MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTime.Now.AddDays(1), cancellationToken); + var collections = await Cache.GetOrAddAsync(nameof(GetCollection) + collectionId + langCode, + () => MovieApi.GetCollection(langCode, collectionId, cancellationToken), DateTimeOffset.Now.AddDays(1)); var c = await ProcessCollection(collections); c.Collection = c.Collection.OrderBy(x => x.ReleaseDate).ToList(); @@ -108,11 +108,11 @@ namespace Ombi.Core.Engine.V2 public async Task> PopularMovies() { - var result = await Cache.GetOrAdd(CacheKeys.PopularMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.PopularMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.PopularMovies(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Shuffle().Take(ResultLimit)); // Take x to stop us overloading the API @@ -136,8 +136,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(PopularMovies) + pagesToLoad.Page + langCode, - async () => await MovieApi.PopularMovies(langCode, pagesToLoad.Page, cancellationToken), DateTime.Now.AddHours(12), cancellationToken); + var apiResult = await Cache.GetOrAddAsync(nameof(PopularMovies) + pagesToLoad.Page + langCode, + () => MovieApi.PopularMovies(langCode, pagesToLoad.Page, cancellationToken), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } return await TransformMovieResultsToResponse(results); @@ -149,11 +149,11 @@ namespace Ombi.Core.Engine.V2 /// public async Task> TopRatedMovies() { - var result = await Cache.GetOrAdd(CacheKeys.TopRatedMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.TopRatedMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.TopRated(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Shuffle().Take(ResultLimit)); // Take x to stop us overloading the API @@ -170,8 +170,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(TopRatedMovies) + pagesToLoad.Page + langCode, - async () => await MovieApi.TopRated(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(TopRatedMovies) + pagesToLoad.Page + langCode, + () => MovieApi.TopRated(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } return await TransformMovieResultsToResponse(results); @@ -186,8 +186,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(NowPlayingMovies) + pagesToLoad.Page + langCode, - async () => await MovieApi.NowPlaying(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(NowPlayingMovies) + pagesToLoad.Page + langCode, + () => MovieApi.NowPlaying(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } return await TransformMovieResultsToResponse(results); @@ -210,8 +210,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(SeasonalList) + pagesToLoad.Page + langCode + keyWordIds, - async () => await MovieApi.GetMoviesViaKeywords(keyWordIds, langCode, cancellationToken, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(SeasonalList) + pagesToLoad.Page + langCode + keyWordIds, + () => MovieApi.GetMoviesViaKeywords(keyWordIds, langCode, cancellationToken, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } return await TransformMovieResultsToResponse(results); @@ -227,16 +227,16 @@ namespace Ombi.Core.Engine.V2 var results = new List(); - var requestResult = await Cache.GetOrAdd(nameof(RecentlyRequestedMovies) + "Requests" + toLoad + langCode, + var requestResult = await Cache.GetOrAddAsync(nameof(RecentlyRequestedMovies) + "Requests" + toLoad + langCode, async () => { return await _movieRequestEngine.GetRequests(toLoad, currentlyLoaded, new Models.UI.OrderFilterModel { OrderType = OrderType.RequestedDateDesc }); - }, DateTime.Now.AddMinutes(15), cancellationToken); + }, DateTimeOffset.Now.AddMinutes(15)); - var movieDBResults = await Cache.GetOrAdd(nameof(RecentlyRequestedMovies) + toLoad + langCode, + var movieDBResults = await Cache.GetOrAddAsync(nameof(RecentlyRequestedMovies) + toLoad + langCode, async () => { var responses = new List(); @@ -245,7 +245,7 @@ namespace Ombi.Core.Engine.V2 responses.Add(await MovieApi.GetMovieInformation(movie.TheMovieDbId)); } return responses; - }, DateTime.Now.AddHours(12), cancellationToken); + }, DateTimeOffset.Now.AddHours(12)); results.AddRange(movieDBResults); @@ -259,11 +259,11 @@ namespace Ombi.Core.Engine.V2 /// public async Task> UpcomingMovies() { - var result = await Cache.GetOrAdd(CacheKeys.UpcomingMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.UpcomingMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.Upcoming(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { Logger.LogDebug("Search Result: {result}", result); @@ -281,8 +281,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(UpcomingMovies) + pagesToLoad.Page + langCode, - async () => await MovieApi.Upcoming(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(UpcomingMovies) + pagesToLoad.Page + langCode, + () => MovieApi.Upcoming(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } return await TransformMovieResultsToResponse(results); @@ -294,11 +294,11 @@ namespace Ombi.Core.Engine.V2 /// public async Task> NowPlayingMovies() { - var result = await Cache.GetOrAdd(CacheKeys.NowPlayingMovies, async () => + var result = await Cache.GetOrAddAsync(CacheKeys.NowPlayingMovies, async () => { var langCode = await DefaultLanguageCode(null); return await MovieApi.NowPlaying(langCode); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); if (result != null) { return await TransformMovieResultsToResponse(result.Shuffle().Take(ResultLimit)); // Take x to stop us overloading the API @@ -308,8 +308,8 @@ namespace Ombi.Core.Engine.V2 public async Task GetMoviesByActor(int actorId, string langCode) { - var result = await Cache.GetOrAdd(nameof(GetMoviesByActor) + actorId + langCode, - async () => await MovieApi.GetActorMovieCredits(actorId, langCode)); + var result = await Cache.GetOrAddAsync(nameof(GetMoviesByActor) + actorId + langCode, + () => MovieApi.GetActorMovieCredits(actorId, langCode), DateTimeOffset.Now.AddHours(12)); // Later we run this through the rules engine return result; } @@ -366,6 +366,14 @@ namespace Ombi.Core.Engine.V2 private async Task ProcessSingleMovie(FullMovieInfo movie) { var viewMovie = Mapper.Map(movie); + var user = await GetUser(); + var digitalReleaseDate = viewMovie.ReleaseDates?.Results?.FirstOrDefault(x => x.IsoCode == user.StreamingCountry); + if (digitalReleaseDate == null) + { + digitalReleaseDate = viewMovie.ReleaseDates?.Results?.FirstOrDefault(x => x.IsoCode == "US"); + } + viewMovie.DigitalReleaseDate = digitalReleaseDate?.ReleaseDate?.FirstOrDefault(x => x.Type == ReleaseDateType.Digital)?.ReleaseDate; + await RunSearchRules(viewMovie); // This requires the rules to be run first to populate the RequestId property @@ -381,6 +389,7 @@ namespace Ombi.Core.Engine.V2 mapped.JellyfinUrl = viewMovie.JellyfinUrl; mapped.Subscribed = viewMovie.Subscribed; mapped.ShowSubscribe = viewMovie.ShowSubscribe; + mapped.DigitalReleaseDate = viewMovie.DigitalReleaseDate; return mapped; } @@ -416,12 +425,21 @@ namespace Ombi.Core.Engine.V2 { if (viewMovie.ImdbId.IsNullOrEmpty()) { - var showInfo = await Cache.GetOrAdd("GetMovieInformationWIthImdbId" + viewMovie.Id, - async () => await MovieApi.GetMovieInformation(viewMovie.Id), DateTime.Now.AddHours(12)); + var showInfo = await Cache.GetOrAddAsync("GetMovieInformationWIthImdbId" + viewMovie.Id, + () => MovieApi.GetMovieInformation(viewMovie.Id), DateTimeOffset.Now.AddHours(12)); viewMovie.Id = showInfo.Id; // TheMovieDbId viewMovie.ImdbId = showInfo.ImdbId; } + var user = await GetUser(); + var digitalReleaseDate = viewMovie.ReleaseDates?.Results?.FirstOrDefault(x => x.IsoCode == user.StreamingCountry); + if (digitalReleaseDate == null) + { + digitalReleaseDate = viewMovie.ReleaseDates?.Results?.FirstOrDefault(x => x.IsoCode == "US"); + } + viewMovie.DigitalReleaseDate = digitalReleaseDate?.ReleaseDate?.FirstOrDefault(x => x.Type == ReleaseDateType.Digital)?.ReleaseDate; + + viewMovie.TheMovieDbId = viewMovie.Id.ToString(); await RunSearchRules(viewMovie); @@ -458,12 +476,12 @@ namespace Ombi.Core.Engine.V2 public async Task GetMovieInfoByImdbId(string imdbId, CancellationToken cancellationToken) { var langCode = await DefaultLanguageCode(null); - var findResult = await Cache.GetOrAdd(nameof(GetMovieInfoByImdbId) + imdbId + langCode, - async () => await MovieApi.Find(imdbId, ExternalSource.imdb_id), DateTime.Now.AddHours(12), cancellationToken); + var findResult = await Cache.GetOrAddAsync(nameof(GetMovieInfoByImdbId) + imdbId + langCode, + () => MovieApi.Find(imdbId, ExternalSource.imdb_id), DateTimeOffset.Now.AddHours(12)); var movie = findResult.movie_results.FirstOrDefault(); - var movieInfo = await Cache.GetOrAdd(nameof(GetMovieInfoByImdbId) + movie.id + langCode, - async () => await MovieApi.GetFullMovieInfo(movie.id, cancellationToken, langCode), DateTime.Now.AddHours(12), cancellationToken); + var movieInfo = await Cache.GetOrAddAsync(nameof(GetMovieInfoByImdbId) + movie.id + langCode, + () => MovieApi.GetFullMovieInfo(movie.id, cancellationToken, langCode), DateTimeOffset.Now.AddHours(12)); return await ProcessSingleMovie(movieInfo); } diff --git a/src/Ombi.Core/Engine/V2/TvSearchEngineV2.cs b/src/Ombi.Core/Engine/V2/TvSearchEngineV2.cs index 6bb67debd..26cba7c14 100644 --- a/src/Ombi.Core/Engine/V2/TvSearchEngineV2.cs +++ b/src/Ombi.Core/Engine/V2/TvSearchEngineV2.cs @@ -60,8 +60,8 @@ namespace Ombi.Core.Engine.V2 public async Task GetShowInformation(string tvdbid, CancellationToken token) { var langCode = await DefaultLanguageCode(null); - var show = await Cache.GetOrAdd(nameof(GetShowInformation) + langCode + tvdbid, - async () => await _movieApi.GetTVInfo(tvdbid, langCode), DateTime.Now.AddHours(12)); + var show = await Cache.GetOrAddAsync(nameof(GetShowInformation) + langCode + tvdbid, + async () => await _movieApi.GetTVInfo(tvdbid, langCode), DateTimeOffset.Now.AddHours(12)); if (show == null || show.name == null) { // We don't have enough information @@ -72,8 +72,8 @@ namespace Ombi.Core.Engine.V2 { // There's no regional assets for this, so // lookup the en-us version to get them - var enShow = await Cache.GetOrAdd(nameof(GetShowInformation) + "en" + tvdbid, - async () => await _movieApi.GetTVInfo(tvdbid, "en"), DateTime.Now.AddHours(12)); + var enShow = await Cache.GetOrAddAsync(nameof(GetShowInformation) + "en" + tvdbid, + async () => await _movieApi.GetTVInfo(tvdbid, "en"), DateTimeOffset.Now.AddHours(12)); // For some of the more obsecure cases if (!show.overview.HasValue()) @@ -105,8 +105,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Popular) + langCode + pagesToLoad.Page, - async () => await _movieApi.PopularTv(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Popular) + langCode + pagesToLoad.Page, + async () => await _movieApi.PopularTv(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } @@ -122,8 +122,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Anticipated) + langCode + pagesToLoad.Page, - async () => await _movieApi.UpcomingTv(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Anticipated) + langCode + pagesToLoad.Page, + async () => await _movieApi.UpcomingTv(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } var processed = ProcessResults(results); @@ -138,8 +138,8 @@ namespace Ombi.Core.Engine.V2 var results = new List(); foreach (var pagesToLoad in pages) { - var apiResult = await Cache.GetOrAdd(nameof(Trending) + langCode + pagesToLoad.Page, - async () => await _movieApi.TopRatedTv(langCode, pagesToLoad.Page), DateTime.Now.AddHours(12)); + var apiResult = await Cache.GetOrAddAsync(nameof(Trending) + langCode + pagesToLoad.Page, + async () => await _movieApi.TopRatedTv(langCode, pagesToLoad.Page), DateTimeOffset.Now.AddHours(12)); results.AddRange(apiResult.Skip(pagesToLoad.Skip).Take(pagesToLoad.Take)); } @@ -175,16 +175,16 @@ namespace Ombi.Core.Engine.V2 var results = new List(); - var requestResult = await Cache.GetOrAdd(nameof(RecentlyRequestedShows) + "Requests" + toLoad + langCode, + var requestResult = await Cache.GetOrAddAsync(nameof(RecentlyRequestedShows) + "Requests" + toLoad + langCode, async () => { return await _requestEngine.GetRequests(toLoad, currentlyLoaded, new Models.UI.OrderFilterModel { OrderType = OrderType.RequestedDateDesc }); - }, DateTime.Now.AddMinutes(15), cancellationToken); + }, DateTimeOffset.Now.AddMinutes(15)); - var movieDBResults = await Cache.GetOrAdd(nameof(RecentlyRequestedShows) + toLoad + langCode, + var movieDBResults = await Cache.GetOrAddAsync(nameof(RecentlyRequestedShows) + toLoad + langCode, async () => { var responses = new List(); @@ -193,7 +193,7 @@ namespace Ombi.Core.Engine.V2 responses.Add(await _movieApi.GetTVInfo(movie.ExternalProviderId.ToString())); } return responses; - }, DateTime.Now.AddHours(12), cancellationToken); + }, DateTimeOffset.Now.AddHours(12)); var mapped = _mapper.Map>(movieDBResults); @@ -219,14 +219,14 @@ namespace Ombi.Core.Engine.V2 if (settings.HideAvailableFromDiscover) { // To hide, we need to know if it's fully available, the only way to do this is to lookup it's episodes to check if we have every episode - var show = await Cache.GetOrAdd(nameof(GetShowInformation) + tvMazeSearch.Id.ToString(), + var show = await Cache.GetOrAddAsync(nameof(GetShowInformation) + tvMazeSearch.Id.ToString(), async () => await _movieApi.GetTVInfo(tvMazeSearch.Id.ToString()), DateTime.Now.AddHours(12)); foreach (var tvSeason in show.seasons.Where(x => x.season_number != 0)) // skip the first season { - var seasonEpisodes = await Cache.GetOrAdd("SeasonEpisodes" + show.id + tvSeason.season_number, async () => + var seasonEpisodes = await Cache.GetOrAddAsync("SeasonEpisodes" + show.id + tvSeason.season_number, async () => { return await _movieApi.GetSeasonEpisodes(show.id, tvSeason.season_number, CancellationToken.None); - }, DateTime.Now.AddHours(12)); + }, DateTimeOffset.Now.AddHours(12)); MapSeasons(tvMazeSearch.SeasonRequests, tvSeason, seasonEpisodes); } diff --git a/src/Ombi.Core/ImageService.cs b/src/Ombi.Core/ImageService.cs index e22605441..f9c8b40b9 100644 --- a/src/Ombi.Core/ImageService.cs +++ b/src/Ombi.Core/ImageService.cs @@ -23,8 +23,8 @@ namespace Ombi.Core public async Task GetTvBackground(string tvdbId) { - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await _configRepository.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}tv{tvdbId}", async () => await _fanartTvApi.GetTvImages(int.Parse(tvdbId), key.Value), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => _configRepository.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}tv{tvdbId}", () => _fanartTvApi.GetTvImages(int.Parse(tvdbId), key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { diff --git a/src/Ombi.DependencyInjection/IocExtensions.cs b/src/Ombi.DependencyInjection/IocExtensions.cs index 73a69203a..62686deec 100644 --- a/src/Ombi.DependencyInjection/IocExtensions.cs +++ b/src/Ombi.DependencyInjection/IocExtensions.cs @@ -206,6 +206,7 @@ namespace Ombi.DependencyInjection services.AddTransient(); services.AddTransient(); services.AddSingleton(); + services.AddSingleton(); services.AddScoped(); services.AddTransient(); diff --git a/src/Ombi.Helpers/CacheService.cs b/src/Ombi.Helpers/CacheService.cs index 4f2f69dc8..3cf392880 100644 --- a/src/Ombi.Helpers/CacheService.cs +++ b/src/Ombi.Helpers/CacheService.cs @@ -1,48 +1,26 @@ using System; -using System.Collections.Generic; -using System.Text; using System.Threading; using System.Threading.Tasks; -using Microsoft.Extensions.Caching.Memory; -using Nito.AsyncEx; +using LazyCache; namespace Ombi.Helpers { public class CacheService : ICacheService { - private readonly IMemoryCache _memoryCache; - private readonly AsyncLock _mutex = new AsyncLock(); - public CacheService(IMemoryCache memoryCache) + protected readonly IAppCache _memoryCache; + public CacheService(IAppCache memoryCache) { - _memoryCache = memoryCache ?? throw new ArgumentNullException(nameof(memoryCache)); + _memoryCache = memoryCache; } - public async Task GetOrAdd(string cacheKey, Func> factory, DateTime absoluteExpiration = default(DateTime), CancellationToken cancellationToken = default(CancellationToken)) + public virtual async Task GetOrAddAsync(string cacheKey, Func> factory, DateTimeOffset absoluteExpiration = default) { - if (absoluteExpiration == default(DateTime)) + if (absoluteExpiration == default) { - absoluteExpiration = DateTime.Now.AddHours(1); + absoluteExpiration = DateTimeOffset.Now.AddHours(1); } - // locks get and set internally - if (_memoryCache.TryGetValue(cacheKey, out var result)) - { - return result; - } - - if (_memoryCache.TryGetValue(cacheKey, out result)) - { - return result; - } - - if (cancellationToken.CanBeCanceled) - { - cancellationToken.ThrowIfCancellationRequested(); - } - - result = await factory(); - _memoryCache.Set(cacheKey, result, absoluteExpiration); - return result; + return await _memoryCache.GetOrAddAsync(cacheKey, () => factory(), absoluteExpiration); } public void Remove(string key) @@ -50,28 +28,10 @@ namespace Ombi.Helpers _memoryCache.Remove(key); } - - - public T GetOrAdd(string cacheKey, Func factory, DateTime absoluteExpiration) + public T GetOrAdd(string cacheKey, Func factory, DateTimeOffset absoluteExpiration) { // locks get and set internally - if (_memoryCache.TryGetValue(cacheKey, out var result)) - { - return result; - } - - lock (TypeLock.Lock) - { - if (_memoryCache.TryGetValue(cacheKey, out result)) - { - return result; - } - - result = factory(); - _memoryCache.Set(cacheKey, result, absoluteExpiration); - - return result; - } + return _memoryCache.GetOrAdd(cacheKey, () => factory(), absoluteExpiration); } private static class TypeLock diff --git a/src/Ombi.Helpers/ICacheService.cs b/src/Ombi.Helpers/ICacheService.cs index e3996a0e1..f22355ee7 100644 --- a/src/Ombi.Helpers/ICacheService.cs +++ b/src/Ombi.Helpers/ICacheService.cs @@ -6,8 +6,8 @@ namespace Ombi.Helpers { public interface ICacheService { - Task GetOrAdd(string cacheKey, Func> factory, DateTime absoluteExpiration = default(DateTime), CancellationToken cancellationToken = default(CancellationToken)); - T GetOrAdd(string cacheKey, Func factory, DateTime absoluteExpiration); + Task GetOrAddAsync(string cacheKey, Func> factory, DateTimeOffset absoluteExpiration = default); + T GetOrAdd(string cacheKey, Func factory, DateTimeOffset absoluteExpiration); void Remove(string key); } } \ No newline at end of file diff --git a/src/Ombi.Helpers/MediaCacheService.cs b/src/Ombi.Helpers/MediaCacheService.cs new file mode 100644 index 000000000..69ad8ec09 --- /dev/null +++ b/src/Ombi.Helpers/MediaCacheService.cs @@ -0,0 +1,61 @@ +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using LazyCache; + +namespace Ombi.Helpers +{ + public interface IMediaCacheService + { + Task GetOrAddAsync(string cacheKey, System.Func> factory, DateTimeOffset absoluteExpiration = default); + Task Purge(); + } + public class MediaCacheService : CacheService, IMediaCacheService + { + private const string CacheKey = "MediaCacheServiceKeys"; + + public MediaCacheService(IAppCache memoryCache) : base(memoryCache) + { + } + + public async override Task GetOrAddAsync(string cacheKey, System.Func> factory, DateTimeOffset absoluteExpiration = default) + { + if (absoluteExpiration == default) + { + absoluteExpiration = DateTimeOffset.Now.AddHours(1); + } + + if (_memoryCache.TryGetValue($"MediaCacheService_{cacheKey}", out var result)) + { + return (T)result; + } + + // Not in the cache, so add this Key into our MediaServiceCache + await UpdateLocalCache(cacheKey); + + return await _memoryCache.GetOrAddAsync(cacheKey, () => factory(), absoluteExpiration); + } + + private async Task UpdateLocalCache(string cacheKey) + { + var mediaServiceCache = await _memoryCache.GetAsync>(CacheKey); + if (mediaServiceCache == null) + { + mediaServiceCache = new List(); + } + mediaServiceCache.Add(cacheKey); + _memoryCache.Remove(CacheKey); + _memoryCache.Add(CacheKey, mediaServiceCache); + } + + public async Task Purge() + { + var keys = await _memoryCache.GetAsync>(CacheKey); + foreach (var key in keys) + { + base.Remove(key); + } + } + + } +} diff --git a/src/Ombi.Helpers/Ombi.Helpers.csproj b/src/Ombi.Helpers/Ombi.Helpers.csproj index 48969ac1a..7492444d1 100644 --- a/src/Ombi.Helpers/Ombi.Helpers.csproj +++ b/src/Ombi.Helpers/Ombi.Helpers.csproj @@ -11,6 +11,7 @@ + diff --git a/src/Ombi.Settings/Settings/SettingsService.cs b/src/Ombi.Settings/Settings/SettingsService.cs index d2f2fdef6..70313430f 100644 --- a/src/Ombi.Settings/Settings/SettingsService.cs +++ b/src/Ombi.Settings/Settings/SettingsService.cs @@ -41,12 +41,12 @@ namespace Ombi.Settings.Settings var model = obj; return model; - }, DateTime.Now.AddHours(2)); + }, DateTimeOffset.Now.AddHours(2)); } public async Task GetSettingsAsync() { - return await _cache.GetOrAdd(CacheName, async () => + return await _cache.GetOrAddAsync(CacheName, async () => { var result = await Repo.GetAsync(EntityName); if (result == null) @@ -61,7 +61,7 @@ namespace Ombi.Settings.Settings var model = obj; return model; - }, DateTime.Now.AddHours(5)); + }, DateTimeOffset.Now.AddHours(5)); } public bool SaveSettings(T model) diff --git a/src/Ombi/ClientApp/src/app/media-details/components/movie/panels/movie-information-panel.component.html b/src/Ombi/ClientApp/src/app/media-details/components/movie/panels/movie-information-panel.component.html index 6b0da8604..62908b361 100644 --- a/src/Ombi/ClientApp/src/app/media-details/components/movie/panels/movie-information-panel.component.html +++ b/src/Ombi/ClientApp/src/app/media-details/components/movie/panels/movie-information-panel.component.html @@ -44,7 +44,7 @@
- {{'Requests.RequestedBy' | translate }}: + {{'Requests.RequestedBy' | translate }}: {{request.requestedUser.userAlias}}
diff --git a/src/Ombi/Controllers/V1/External/LidarrController.cs b/src/Ombi/Controllers/V1/External/LidarrController.cs index 33af536d7..616f01918 100644 --- a/src/Ombi/Controllers/V1/External/LidarrController.cs +++ b/src/Ombi/Controllers/V1/External/LidarrController.cs @@ -69,7 +69,7 @@ namespace Ombi.Controllers.V1.External [HttpGet("Profiles")] public async Task> GetProfiles() { - return await Cache.GetOrAdd(CacheKeys.LidarrQualityProfiles, async () => + return await Cache.GetOrAddAsync(CacheKeys.LidarrQualityProfiles, async () => { var settings = await _lidarrSettings.GetSettingsAsync(); if (settings.Enabled) @@ -77,7 +77,7 @@ namespace Ombi.Controllers.V1.External return await _lidarrApi.GetProfiles(settings.ApiKey, settings.FullUri); } return null; - }, DateTime.Now.AddHours(1)); + }, DateTimeOffset.Now.AddHours(1)); } /// @@ -88,7 +88,7 @@ namespace Ombi.Controllers.V1.External [HttpGet("RootFolders")] public async Task> GetRootFolders() { - return await Cache.GetOrAdd(CacheKeys.LidarrRootFolders, async () => + return await Cache.GetOrAddAsync(CacheKeys.LidarrRootFolders, async () => { var settings = await _lidarrSettings.GetSettingsAsync(); if (settings.Enabled) @@ -96,7 +96,7 @@ namespace Ombi.Controllers.V1.External return await _lidarrApi.GetRootFolders(settings.ApiKey, settings.FullUri); } return null; - }, DateTime.Now.AddHours(1)); + }, DateTimeOffset.Now.AddHours(1)); } } } \ No newline at end of file diff --git a/src/Ombi/Controllers/V1/IdentityController.cs b/src/Ombi/Controllers/V1/IdentityController.cs index 70cb73e74..ca10902b8 100644 --- a/src/Ombi/Controllers/V1/IdentityController.cs +++ b/src/Ombi/Controllers/V1/IdentityController.cs @@ -293,8 +293,8 @@ namespace Ombi.Controllers.V1 [PowerUser] public async Task> GetAllUsersDropdown() { - var users = await _cacheService.GetOrAdd(CacheKeys.UsersDropdown, - async () => await UserManager.Users.Where(x => x.UserType != UserType.SystemUser).ToListAsync()); + var users = await _cacheService.GetOrAddAsync(CacheKeys.UsersDropdown, + () => UserManager.Users.Where(x => x.UserType != UserType.SystemUser).ToListAsync()); var model = new List(); diff --git a/src/Ombi/Controllers/V1/ImagesController.cs b/src/Ombi/Controllers/V1/ImagesController.cs index 847cd8777..9683c54b0 100644 --- a/src/Ombi/Controllers/V1/ImagesController.cs +++ b/src/Ombi/Controllers/V1/ImagesController.cs @@ -45,9 +45,9 @@ namespace Ombi.Controllers.V1 { return string.Empty; } - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}tv{tvdbid}", async () => await FanartTvApi.GetTvImages(tvdbid, key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}tv{tvdbid}", () => FanartTvApi.GetTvImages(tvdbid, key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { return string.Empty; @@ -70,7 +70,7 @@ namespace Ombi.Controllers.V1 [HttpGet("poster")] public async Task GetRandomPoster() { - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); var rand = new Random(); var val = rand.Next(1, 3); if (val == 1) @@ -79,7 +79,7 @@ namespace Ombi.Controllers.V1 var selectedMovieIndex = rand.Next(movies.Count()); var movie = movies[selectedMovieIndex]; - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{movie.Id}", async () => await FanartTvApi.GetMovieImages(movie.Id.ToString(), key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{movie.Id}", () => FanartTvApi.GetMovieImages(movie.Id.ToString(), key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { return string.Empty; @@ -114,9 +114,9 @@ namespace Ombi.Controllers.V1 [HttpGet("poster/movie/{movieDbId}")] public async Task GetMoviePoster(string movieDbId) { - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{movieDbId}", async () => await FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{movieDbId}", () => FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { @@ -148,9 +148,9 @@ namespace Ombi.Controllers.V1 { return string.Empty; } - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}tv{tvdbid}", async () => await FanartTvApi.GetTvImages(tvdbid, key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}tv{tvdbid}", () => FanartTvApi.GetTvImages(tvdbid, key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { @@ -178,9 +178,9 @@ namespace Ombi.Controllers.V1 [HttpGet("background/movie/{movieDbId}")] public async Task GetMovieBackground(string movieDbId) { - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{movieDbId}", async () => await FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{movieDbId}", () => FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { @@ -203,9 +203,9 @@ namespace Ombi.Controllers.V1 [HttpGet("banner/movie/{movieDbId}")] public async Task GetMovieBanner(string movieDbId) { - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); - var images = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{movieDbId}", async () => await FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTime.Now.AddDays(1)); + var images = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{movieDbId}", () => FanartTvApi.GetMovieImages(movieDbId, key.Value), DateTimeOffset.Now.AddDays(1)); if (images == null) { @@ -246,17 +246,17 @@ namespace Ombi.Controllers.V1 var movieUrl = string.Empty; var tvUrl = string.Empty; - var key = await _cache.GetOrAdd(CacheKeys.FanartTv, async () => await Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTime.Now.AddDays(1)); + var key = await _cache.GetOrAddAsync(CacheKeys.FanartTv, () => Config.GetAsync(Store.Entities.ConfigurationTypes.FanartTv), DateTimeOffset.Now.AddDays(1)); if (moviesArray.Length > 0) { var item = rand.Next(moviesArray.Length); - var result = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{moviesArray[item]}", async () => await FanartTvApi.GetMovieImages(moviesArray[item].ToString(), key.Value), DateTime.Now.AddDays(1)); + var result = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{moviesArray[item]}", () => FanartTvApi.GetMovieImages(moviesArray[item].ToString(), key.Value), DateTimeOffset.Now.AddDays(1)); while (!result.moviebackground?.Any() ?? true) { item = rand.Next(moviesArray.Length); - result = await _cache.GetOrAdd($"{CacheKeys.FanartTv}movie{moviesArray[item]}", async () => await FanartTvApi.GetMovieImages(moviesArray[item].ToString(), key.Value), DateTime.Now.AddDays(1)); + result = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}movie{moviesArray[item]}", () => FanartTvApi.GetMovieImages(moviesArray[item].ToString(), key.Value), DateTimeOffset.Now.AddDays(1)); } @@ -268,12 +268,12 @@ namespace Ombi.Controllers.V1 if (tvArray.Length > 0) { var item = rand.Next(tvArray.Length); - var result = await _cache.GetOrAdd($"{CacheKeys.FanartTv}tv{tvArray[item]}", async () => await FanartTvApi.GetTvImages(tvArray[item], key.Value), DateTime.Now.AddDays(1)); + var result = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}tv{tvArray[item]}", () => FanartTvApi.GetTvImages(tvArray[item], key.Value), DateTimeOffset.Now.AddDays(1)); while (!result.showbackground?.Any() ?? true) { item = rand.Next(tvArray.Length); - result = await _cache.GetOrAdd($"{CacheKeys.FanartTv}tv{tvArray[item]}", async () => await FanartTvApi.GetTvImages(tvArray[item], key.Value), DateTime.Now.AddDays(1)); + result = await _cache.GetOrAddAsync($"{CacheKeys.FanartTv}tv{tvArray[item]}", () => FanartTvApi.GetTvImages(tvArray[item], key.Value), DateTimeOffset.Now.AddDays(1)); } var otherRand = new Random(); var res = otherRand.Next(result.showbackground.Length); diff --git a/src/Ombi/Controllers/V1/JobController.cs b/src/Ombi/Controllers/V1/JobController.cs index 668a795a1..2dd694619 100644 --- a/src/Ombi/Controllers/V1/JobController.cs +++ b/src/Ombi/Controllers/V1/JobController.cs @@ -66,7 +66,7 @@ namespace Ombi.Controllers.V1 [HttpGet("updateCached")] public async Task CheckForUpdateCached() { - var val = await _memCache.GetOrAdd(CacheKeys.Update, async () => + var val = await _memCache.GetOrAddAsync(CacheKeys.Update, async () => { var productArray = _updater.GetVersion(); diff --git a/src/Ombi/Controllers/V1/UpdateController.cs b/src/Ombi/Controllers/V1/UpdateController.cs index 419442205..fc654933f 100644 --- a/src/Ombi/Controllers/V1/UpdateController.cs +++ b/src/Ombi/Controllers/V1/UpdateController.cs @@ -21,10 +21,10 @@ namespace Ombi.Controllers.V1 private readonly ICacheService _cache; private readonly IChangeLogProcessor _processor; - [HttpGet()] + [HttpGet] public async Task UpdateAvailable() { - return await _cache.GetOrAdd("Update", async () => await _processor.Process()); + return await _cache.GetOrAddAsync("Update", () => _processor.Process()); } } } \ No newline at end of file diff --git a/src/Ombi/Controllers/V2/RequestsController.cs b/src/Ombi/Controllers/V2/RequestsController.cs index 6449db438..9f26e95bf 100644 --- a/src/Ombi/Controllers/V2/RequestsController.cs +++ b/src/Ombi/Controllers/V2/RequestsController.cs @@ -12,6 +12,7 @@ using Ombi.Store.Entities; using System.Linq; using Microsoft.Extensions.Logging; using Ombi.Attributes; +using Ombi.Helpers; namespace Ombi.Controllers.V2 { diff --git a/src/Ombi/Controllers/V2/SearchController.cs b/src/Ombi/Controllers/V2/SearchController.cs index 9391815dd..4bf8f15da 100644 --- a/src/Ombi/Controllers/V2/SearchController.cs +++ b/src/Ombi/Controllers/V2/SearchController.cs @@ -1,11 +1,9 @@ using System; -using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using System.Collections.Generic; -using System.Threading; using Ombi.Core; using Ombi.Api.TheMovieDb.Models; using Ombi.Core.Engine.V2; @@ -16,14 +14,15 @@ using Ombi.Core.Models.Search.V2.Music; using Ombi.Models; using Ombi.Api.RottenTomatoes.Models; using Ombi.Api.RottenTomatoes; -using Hqub.MusicBrainz.API.Entities.Collections; +using Ombi.Helpers; namespace Ombi.Controllers.V2 { public class SearchController : V2Controller { public SearchController(IMultiSearchEngine multiSearchEngine, - IMovieEngineV2 v2Movie, ITVSearchEngineV2 v2Tv, IMusicSearchEngineV2 musicEngine, IRottenTomatoesApi rottenTomatoesApi) + IMovieEngineV2 v2Movie, ITVSearchEngineV2 v2Tv, IMusicSearchEngineV2 musicEngine, IRottenTomatoesApi rottenTomatoesApi, + IMediaCacheService mediaCacheService) { _multiSearchEngine = multiSearchEngine; _movieEngineV2 = v2Movie; @@ -31,6 +30,7 @@ namespace Ombi.Controllers.V2 _tvEngineV2 = v2Tv; _musicEngine = musicEngine; _rottenTomatoesApi = rottenTomatoesApi; + _mediaCacheService = mediaCacheService; } private readonly IMultiSearchEngine _multiSearchEngine; @@ -38,6 +38,7 @@ namespace Ombi.Controllers.V2 private readonly ITVSearchEngineV2 _tvEngineV2; private readonly IMusicSearchEngineV2 _musicEngine; private readonly IRottenTomatoesApi _rottenTomatoesApi; + private readonly IMediaCacheService _mediaCacheService; /// /// Returns search results for both TV and Movies @@ -59,24 +60,30 @@ namespace Ombi.Controllers.V2 /// /// The MovieDB Id [HttpGet("movie/{movieDbId}")] - public async Task GetMovieInfo(int movieDbId) + public Task GetMovieInfo(int movieDbId) { - return await _movieEngineV2.GetFullMovieInformation(movieDbId, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetMovieInfo) + movieDbId, + () => _movieEngineV2.GetFullMovieInformation(movieDbId, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } [HttpGet("movie/imdb/{imdbid}")] - public async Task GetMovieInfoByImdbId(string imdbId) + public Task GetMovieInfoByImdbId(string imdbId) { - return await _movieEngineV2.GetMovieInfoByImdbId(imdbId, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetMovieInfoByImdbId) + imdbId, + () => _movieEngineV2.GetMovieInfoByImdbId(imdbId, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// /// Returns details for a single movie /// [HttpGet("movie/request/{requestId}")] - public async Task GetMovieByRequest(int requestId) + public Task GetMovieByRequest(int requestId) { - return await _movieEngineV2.GetMovieInfoByRequestId(requestId, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetMovieByRequest) + requestId, + () => _movieEngineV2.GetMovieInfoByRequestId(requestId, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -85,9 +92,11 @@ namespace Ombi.Controllers.V2 /// The collection id from TheMovieDb /// [HttpGet("movie/collection/{collectionId}")] - public async Task GetMovieCollections(int collectionId) + public Task GetMovieCollections(int collectionId) { - return await _movieEngineV2.GetCollection(collectionId, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetMovieCollections) + collectionId, + () => _movieEngineV2.GetCollection(collectionId, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -96,9 +105,11 @@ namespace Ombi.Controllers.V2 /// TVMaze is the TV Show Provider /// The TVDB Id [HttpGet("tv/{tvdbId}")] - public async Task GetTvInfo(string tvdbid) + public Task GetTvInfo(string tvdbid) { - return await _tvEngineV2.GetShowInformation(tvdbid, HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetTvInfo) + tvdbid, + () => _tvEngineV2.GetShowInformation(tvdbid, HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -107,9 +118,11 @@ namespace Ombi.Controllers.V2 /// TVMaze is the TV Show Provider /// [HttpGet("tv/request/{requestId}")] - public async Task GetTvInfoByRequest(int requestId) + public Task GetTvInfoByRequest(int requestId) { - return await _tvEngineV2.GetShowByRequest(requestId, HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetTvInfoByRequest) + requestId, + () => _tvEngineV2.GetShowByRequest(requestId, HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -117,9 +130,11 @@ namespace Ombi.Controllers.V2 /// /// [HttpGet("tv/moviedb/{moviedbid}")] - public async Task GetTvInfoByMovieId(string moviedbid) + public Task GetTvInfoByMovieId(string moviedbid) { - return await _tvEngineV2.GetShowInformation(moviedbid, HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetTvInfoByMovieId) + moviedbid, + () => _tvEngineV2.GetShowInformation(moviedbid, HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -131,9 +146,11 @@ namespace Ombi.Controllers.V2 [HttpPost("movie/similar")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> SimilarMovies([FromBody] SimilarMoviesRefineModel model) + public Task> SimilarMovies([FromBody] SimilarMoviesRefineModel model) { - return await _movieEngineV2.SimilarMovies(model.TheMovieDbId, model.LanguageCode); + return _mediaCacheService.GetOrAddAsync(nameof(SimilarMovies) + model.TheMovieDbId + model.LanguageCode, + () => _movieEngineV2.SimilarMovies(model.TheMovieDbId, model.LanguageCode), + DateTimeOffset.Now.AddHours(12)); } @@ -159,9 +176,11 @@ namespace Ombi.Controllers.V2 [HttpGet("movie/popular/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> Popular(int currentPosition, int amountToLoad) + public Task> Popular(int currentPosition, int amountToLoad) { - return await _movieEngineV2.PopularMovies(currentPosition, amountToLoad, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(Popular) + "Movies" + currentPosition + amountToLoad, + () => _movieEngineV2.PopularMovies(currentPosition, amountToLoad, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } /// @@ -172,9 +191,11 @@ namespace Ombi.Controllers.V2 [HttpGet("movie/seasonal/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> Seasonal(int currentPosition, int amountToLoad) + public Task> Seasonal(int currentPosition, int amountToLoad) { - return await _movieEngineV2.SeasonalList(currentPosition, amountToLoad, Request.HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(Seasonal) + "Movies" + currentPosition + amountToLoad, + () => _movieEngineV2.SeasonalList(currentPosition, amountToLoad, Request.HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(1)); } /// @@ -224,9 +245,11 @@ namespace Ombi.Controllers.V2 [HttpGet("movie/nowplaying/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> NowPlayingMovies(int currentPosition, int amountToLoad) + public Task> NowPlayingMovies(int currentPosition, int amountToLoad) { - return await _movieEngineV2.NowPlayingMovies(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(NowPlayingMovies) + currentPosition + amountToLoad, + () => _movieEngineV2.NowPlayingMovies(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -250,9 +273,11 @@ namespace Ombi.Controllers.V2 [HttpGet("movie/toprated/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> TopRatedMovies(int currentPosition, int amountToLoad) + public Task> TopRatedMovies(int currentPosition, int amountToLoad) { - return await _movieEngineV2.TopRatedMovies(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(TopRatedMovies) + currentPosition + amountToLoad, + () => _movieEngineV2.TopRatedMovies(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -276,9 +301,11 @@ namespace Ombi.Controllers.V2 [HttpGet("movie/upcoming/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> UpcomingMovies(int currentPosition, int amountToLoad) + public Task> UpcomingMovies(int currentPosition, int amountToLoad) { - return await _movieEngineV2.UpcomingMovies(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(UpcomingMovies) + currentPosition + amountToLoad, + () => _movieEngineV2.UpcomingMovies(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -289,9 +316,11 @@ namespace Ombi.Controllers.V2 [HttpGet("tv/popular/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> PopularTv(int currentPosition, int amountToLoad) + public Task> PopularTv(int currentPosition, int amountToLoad) { - return await _tvEngineV2.Popular(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(PopularTv) + currentPosition + amountToLoad, + () => _tvEngineV2.Popular(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -302,9 +331,11 @@ namespace Ombi.Controllers.V2 [HttpGet("tv/anticipated/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> AnticipatedTv(int currentPosition, int amountToLoad) + public Task> AnticipatedTv(int currentPosition, int amountToLoad) { - return await _tvEngineV2.Anticipated(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(AnticipatedTv) + currentPosition + amountToLoad, + () => _tvEngineV2.Anticipated(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -316,9 +347,11 @@ namespace Ombi.Controllers.V2 [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] [Obsolete("This method is obsolete, Trakt API no longer supports this")] - public async Task> MostWatched(int currentPosition, int amountToLoad) + public Task> MostWatched(int currentPosition, int amountToLoad) { - return await _tvEngineV2.Popular(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(MostWatched) + currentPosition + amountToLoad, + () => _tvEngineV2.Popular(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } @@ -330,9 +363,11 @@ namespace Ombi.Controllers.V2 [HttpGet("tv/trending/{currentPosition}/{amountToLoad}")] [ProducesResponseType(StatusCodes.Status200OK)] [ProducesDefaultResponseType] - public async Task> Trending(int currentPosition, int amountToLoad) + public Task> Trending(int currentPosition, int amountToLoad) { - return await _tvEngineV2.Trending(currentPosition, amountToLoad); + return _mediaCacheService.GetOrAddAsync(nameof(Trending) + currentPosition + amountToLoad, + () => _tvEngineV2.Trending(currentPosition, amountToLoad), + DateTimeOffset.Now.AddHours(12)); } /// @@ -386,7 +421,9 @@ namespace Ombi.Controllers.V2 [ProducesDefaultResponseType] public Task GetRottenMovieRatings(string name, int year) { - return _rottenTomatoesApi.GetMovieRatings(name, year); + return _mediaCacheService.GetOrAddAsync(nameof(GetRottenMovieRatings) + name + year, + () => _rottenTomatoesApi.GetMovieRatings(name, year), + DateTimeOffset.Now.AddHours(12)); } [HttpGet("ratings/tv/{name}/{year}")] @@ -394,7 +431,9 @@ namespace Ombi.Controllers.V2 [ProducesDefaultResponseType] public Task GetRottenTvRatings(string name, int year) { - return _rottenTomatoesApi.GetTvRatings(name, year); + return _mediaCacheService.GetOrAddAsync(nameof(GetRottenTvRatings) + name + year, + () => _rottenTomatoesApi.GetTvRatings(name, year), + DateTimeOffset.Now.AddHours(12)); } [HttpGet("stream/movie/{movieDbId}")] @@ -402,7 +441,9 @@ namespace Ombi.Controllers.V2 [ProducesDefaultResponseType] public Task> GetMovieStreams(int movieDBId) { - return _movieEngineV2.GetStreamInformation(movieDBId, HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetMovieStreams) + movieDBId, + () => _movieEngineV2.GetStreamInformation(movieDBId, HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } [HttpGet("stream/tv/{movieDbId}")] @@ -410,7 +451,9 @@ namespace Ombi.Controllers.V2 [ProducesDefaultResponseType] public Task> GetTvStreams(int movieDbId) { - return _tvEngineV2.GetStreamInformation(movieDbId, HttpContext.RequestAborted); + return _mediaCacheService.GetOrAddAsync(nameof(GetTvStreams) + movieDbId, + () => _tvEngineV2.GetStreamInformation(movieDbId, HttpContext.RequestAborted), + DateTimeOffset.Now.AddHours(12)); } } } \ No newline at end of file diff --git a/src/Ombi/Extensions/StartupExtensions.cs b/src/Ombi/Extensions/StartupExtensions.cs index 5149c4fea..e3253045a 100644 --- a/src/Ombi/Extensions/StartupExtensions.cs +++ b/src/Ombi/Extensions/StartupExtensions.cs @@ -116,7 +116,7 @@ namespace Ombi { var userid = context.Principal?.Claims?.Where(x => x.Type.Equals("id", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault()?.Value ?? default; var cache = context.HttpContext.RequestServices.GetRequiredService(); - var user = await cache.GetOrAdd(userid + "token", async () => + var user = await cache.GetOrAddAsync(userid + "token", async () => { var um = context.HttpContext.RequestServices.GetRequiredService(); return await um.FindByIdAsync(userid); diff --git a/src/Ombi/Ombi.csproj b/src/Ombi/Ombi.csproj index 63c4f5a87..53c98534b 100644 --- a/src/Ombi/Ombi.csproj +++ b/src/Ombi/Ombi.csproj @@ -56,6 +56,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/src/Ombi/Startup.cs b/src/Ombi/Startup.cs index bb10c22a2..4b82c3124 100644 --- a/src/Ombi/Startup.cs +++ b/src/Ombi/Startup.cs @@ -84,7 +84,7 @@ namespace Ombi //{ // setup.AddHealthCheckEndpoint("Ombi", "/health"); //}); - services.AddMemoryCache(); + services.AddLazyCache(); services.AddHttpClient(); services.AddJwtAuthentication();