Added the Digital Release Date back in.

Improved performance and system load when loading content #4082
pull/4252/head
tidusjar 4 years ago
parent 4082f6ad41
commit 0c4bd10b0f

@ -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,

@ -30,7 +30,7 @@ namespace Ombi.Core.Engine
public MovieRequestEngine(IMovieDbApi movieApi, IRequestServiceMain requestService, IPrincipal user,
INotificationHelper helper, IRuleEvaluator r, IMovieSender sender, ILogger<MovieRequestEngine> log,
OmbiUserManager manager, IRepository<RequestLog> rl, ICacheService cache,
ISettingsService<OmbiSettings> ombiSettings, IRepository<RequestSubscription> sub)
ISettingsService<OmbiSettings> ombiSettings, IRepository<RequestSubscription> 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<MovieRequestEngine> Logger { get; }
private readonly IRepository<RequestLog> _requestLog;
private readonly IMediaCacheService _mediaCacheService;
/// <summary>
/// Requests the movie.
@ -371,7 +373,6 @@ namespace Ombi.Core.Engine
};
}
public async Task<RequestEngineResult> 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<RequestEngineResult> 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<RequestEngineResult>();
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<bool> 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,

@ -45,9 +45,9 @@ namespace Ombi.Core.Engine
public async Task<SearchMovieViewModel> 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<SearchMovieViewModel>(movieInfo);
return await ProcessSingleMovie(viewMovie, true);
@ -121,11 +121,11 @@ namespace Ombi.Core.Engine
public async Task<IEnumerable<SearchMovieViewModel>> 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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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

@ -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<TvRequestEngine> logger,
ITvSender sender, IRepository<RequestLog> rl, ISettingsService<OmbiSettings> settings, ICacheService cache,
IRepository<RequestSubscription> sub) : base(user, requestService, rule, manager, cache, settings, sub)
IRepository<RequestSubscription> 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<TvRequestEngine> _logger;
private readonly IRepository<RequestLog> _requestLog;
private readonly IMediaCacheService _mediaCacheService;
public async Task<RequestEngineResult> RequestTvShow(TvRequestViewModel tv)
{
@ -329,6 +331,7 @@ namespace Ombi.Core.Engine
Collection = allRequests
};
}
public async Task<IEnumerable<TvRequests>> GetRequests()
{
var shouldHide = await HideFromOtherUsers();
@ -348,7 +351,6 @@ namespace Ombi.Core.Engine
return allRequests;
}
public async Task<RequestsViewModel<ChildRequests>> GetRequests(int count, int position, string sortProperty, string sortOrder)
{
var shouldHide = await HideFromOtherUsers();
@ -404,7 +406,7 @@ namespace Ombi.Core.Engine
};
}
public async Task<RequestsViewModel<ChildRequests>> GetRequests(int count, int position, string sortProperty, string sortOrder, RequestStatus status)
public async Task<RequestsViewModel<ChildRequests>> GetRequests(int count, int position, string sortProperty, string sortOrder, RequestStatus status)
{
var shouldHide = await HideFromOtherUsers();
List<ChildRequests> allRequests;
@ -476,6 +478,7 @@ namespace Ombi.Core.Engine
Total = total,
};
}
public async Task<RequestsViewModel<ChildRequests>> GetUnavailableRequests(int count, int position, string sortProperty, string sortOrder)
{
var shouldHide = await HideFromOtherUsers();
@ -529,7 +532,6 @@ namespace Ombi.Core.Engine
};
}
public async Task<IEnumerable<TvRequests>> 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<ChildRequests> 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<bool> 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<ChildRequests> SortEpisodes(List<ChildRequests> 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<RequestEngineResult> 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);
}

@ -77,16 +77,16 @@ namespace Ombi.Core.Engine
public async Task<SearchTvShowViewModel> 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<IEnumerable<SearchTvShowViewModel>> 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<TraktShow>();
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<IEnumerable<SearchTvShowViewModel>> 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<TraktShow>();
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<IEnumerable<SearchTvShowViewModel>> 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<TraktShow>();
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);

@ -51,8 +51,8 @@ namespace Ombi.Core.Engine.V2
public async Task<MovieFullInfoViewModel> 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<MovieCollectionsViewModel> 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<IEnumerable<SearchMovieViewModel>> 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<MovieDbSearchResult>();
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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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<MovieDbSearchResult>();
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<MovieDbSearchResult>();
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<MovieDbSearchResult>();
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<MovieResponseDto>();
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<MovieResponseDto>();
@ -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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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<MovieDbSearchResult>();
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
/// <returns></returns>
public async Task<IEnumerable<SearchMovieViewModel>> 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<ActorCredits> 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<MovieFullInfoViewModel> ProcessSingleMovie(FullMovieInfo movie)
{
var viewMovie = Mapper.Map<SearchMovieViewModel>(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<MovieFullInfoViewModel> 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);
}

@ -60,8 +60,8 @@ namespace Ombi.Core.Engine.V2
public async Task<SearchFullInfoTvShowViewModel> 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<MovieDbSearchResult>();
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<MovieDbSearchResult>();
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<MovieDbSearchResult>();
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<SearchFullInfoTvShowViewModel>();
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<TvInfo>();
@ -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<List<SearchFullInfoTvShowViewModel>>(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);
}

@ -23,8 +23,8 @@ namespace Ombi.Core
public async Task<string> 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)
{

@ -206,6 +206,7 @@ namespace Ombi.DependencyInjection
services.AddTransient<IEmailProvider, GenericEmailProvider>();
services.AddTransient<INotificationHelper, NotificationHelper>();
services.AddSingleton<ICacheService, CacheService>();
services.AddSingleton<IMediaCacheService, MediaCacheService>();
services.AddScoped<IImageService, ImageService>();
services.AddTransient<IDiscordNotification, DiscordNotification>();

@ -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<T> GetOrAdd<T>(string cacheKey, Func<Task<T>> factory, DateTime absoluteExpiration = default(DateTime), CancellationToken cancellationToken = default(CancellationToken))
public virtual async Task<T> GetOrAddAsync<T>(string cacheKey, Func<Task<T>> 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<T>(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<T>(cacheKey, () => factory(), absoluteExpiration);
}
public void Remove(string key)
@ -50,28 +28,10 @@ namespace Ombi.Helpers
_memoryCache.Remove(key);
}
public T GetOrAdd<T>(string cacheKey, Func<T> factory, DateTime absoluteExpiration)
public T GetOrAdd<T>(string cacheKey, Func<T> factory, DateTimeOffset absoluteExpiration)
{
// locks get and set internally
if (_memoryCache.TryGetValue<T>(cacheKey, out var result))
{
return result;
}
lock (TypeLock<T>.Lock)
{
if (_memoryCache.TryGetValue(cacheKey, out result))
{
return result;
}
result = factory();
_memoryCache.Set(cacheKey, result, absoluteExpiration);
return result;
}
return _memoryCache.GetOrAdd<T>(cacheKey, () => factory(), absoluteExpiration);
}
private static class TypeLock<T>

@ -6,8 +6,8 @@ namespace Ombi.Helpers
{
public interface ICacheService
{
Task<T> GetOrAdd<T>(string cacheKey, Func<Task<T>> factory, DateTime absoluteExpiration = default(DateTime), CancellationToken cancellationToken = default(CancellationToken));
T GetOrAdd<T>(string cacheKey, Func<T> factory, DateTime absoluteExpiration);
Task<T> GetOrAddAsync<T>(string cacheKey, Func<Task<T>> factory, DateTimeOffset absoluteExpiration = default);
T GetOrAdd<T>(string cacheKey, Func<T> factory, DateTimeOffset absoluteExpiration);
void Remove(string key);
}
}

@ -0,0 +1,61 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using LazyCache;
namespace Ombi.Helpers
{
public interface IMediaCacheService
{
Task<T> GetOrAddAsync<T>(string cacheKey, System.Func<Task<T>> 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<T> GetOrAddAsync<T>(string cacheKey, System.Func<Task<T>> factory, DateTimeOffset absoluteExpiration = default)
{
if (absoluteExpiration == default)
{
absoluteExpiration = DateTimeOffset.Now.AddHours(1);
}
if (_memoryCache.TryGetValue<T>($"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<T>(cacheKey, () => factory(), absoluteExpiration);
}
private async Task UpdateLocalCache(string cacheKey)
{
var mediaServiceCache = await _memoryCache.GetAsync<List<string>>(CacheKey);
if (mediaServiceCache == null)
{
mediaServiceCache = new List<string>();
}
mediaServiceCache.Add(cacheKey);
_memoryCache.Remove(CacheKey);
_memoryCache.Add(CacheKey, mediaServiceCache);
}
public async Task Purge()
{
var keys = await _memoryCache.GetAsync<List<string>>(CacheKey);
foreach (var key in keys)
{
base.Remove(key);
}
}
}
}

@ -11,6 +11,7 @@
<ItemGroup>
<PackageReference Include="EasyCrypto" Version="3.3.2" />
<PackageReference Include="LazyCache.AspNetCore" Version="2.1.3" />
<PackageReference Include="Microsoft.Extensions.Caching.Abstractions" Version="5.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="5.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />

@ -41,12 +41,12 @@ namespace Ombi.Settings.Settings
var model = obj;
return model;
}, DateTime.Now.AddHours(2));
}, DateTimeOffset.Now.AddHours(2));
}
public async Task<T> 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)

@ -44,7 +44,7 @@
</div>
<div *ngIf="request">
<span class="label">{{'Requests.RequestedBy' | translate }}:</span>
<span class="label">{{'Requests.RequestedBy' | translate }}: </span>
<span id="requestedByInfo">{{request.requestedUser.userAlias}}</span>
</div>

@ -69,7 +69,7 @@ namespace Ombi.Controllers.V1.External
[HttpGet("Profiles")]
public async Task<IEnumerable<LidarrProfile>> 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));
}
/// <summary>
@ -88,7 +88,7 @@ namespace Ombi.Controllers.V1.External
[HttpGet("RootFolders")]
public async Task<IEnumerable<LidarrRootFolder>> 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));
}
}
}

@ -293,8 +293,8 @@ namespace Ombi.Controllers.V1
[PowerUser]
public async Task<IEnumerable<UserViewModelDropdown>> 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<UserViewModelDropdown>();

@ -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<string> 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<string> 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<string> 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<string> 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);

@ -66,7 +66,7 @@ namespace Ombi.Controllers.V1
[HttpGet("updateCached")]
public async Task<bool> CheckForUpdateCached()
{
var val = await _memCache.GetOrAdd(CacheKeys.Update, async () =>
var val = await _memCache.GetOrAddAsync(CacheKeys.Update, async () =>
{
var productArray = _updater.GetVersion();

@ -21,10 +21,10 @@ namespace Ombi.Controllers.V1
private readonly ICacheService _cache;
private readonly IChangeLogProcessor _processor;
[HttpGet()]
[HttpGet]
public async Task<UpdateModel> UpdateAvailable()
{
return await _cache.GetOrAdd("Update", async () => await _processor.Process());
return await _cache.GetOrAddAsync("Update", () => _processor.Process());
}
}
}

@ -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
{

@ -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;
/// <summary>
/// Returns search results for both TV and Movies
@ -59,24 +60,30 @@ namespace Ombi.Controllers.V2
/// </summary>
/// <param name="movieDbId">The MovieDB Id</param>
[HttpGet("movie/{movieDbId}")]
public async Task<MovieFullInfoViewModel> GetMovieInfo(int movieDbId)
public Task<MovieFullInfoViewModel> 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<MovieFullInfoViewModel> GetMovieInfoByImdbId(string imdbId)
public Task<MovieFullInfoViewModel> 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));
}
/// <summary>
/// Returns details for a single movie
/// </summary>
[HttpGet("movie/request/{requestId}")]
public async Task<MovieFullInfoViewModel> GetMovieByRequest(int requestId)
public Task<MovieFullInfoViewModel> 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));
}
/// <summary>
@ -85,9 +92,11 @@ namespace Ombi.Controllers.V2
/// <param name="collectionId">The collection id from TheMovieDb</param>
/// <returns></returns>
[HttpGet("movie/collection/{collectionId}")]
public async Task<MovieCollectionsViewModel> GetMovieCollections(int collectionId)
public Task<MovieCollectionsViewModel> 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));
}
/// <summary>
@ -96,9 +105,11 @@ namespace Ombi.Controllers.V2
/// <remarks>TVMaze is the TV Show Provider</remarks>
/// <param name="tvdbid">The TVDB Id</param>
[HttpGet("tv/{tvdbId}")]
public async Task<SearchFullInfoTvShowViewModel> GetTvInfo(string tvdbid)
public Task<SearchFullInfoTvShowViewModel> 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));
}
/// <summary>
@ -107,9 +118,11 @@ namespace Ombi.Controllers.V2
/// <remarks>TVMaze is the TV Show Provider</remarks>
///
[HttpGet("tv/request/{requestId}")]
public async Task<SearchFullInfoTvShowViewModel> GetTvInfoByRequest(int requestId)
public Task<SearchFullInfoTvShowViewModel> 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));
}
/// <summary>
@ -117,9 +130,11 @@ namespace Ombi.Controllers.V2
/// </summary>
/// <returns></returns>
[HttpGet("tv/moviedb/{moviedbid}")]
public async Task<SearchFullInfoTvShowViewModel> GetTvInfoByMovieId(string moviedbid)
public Task<SearchFullInfoTvShowViewModel> 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));
}
/// <summary>
@ -131,9 +146,11 @@ namespace Ombi.Controllers.V2
[HttpPost("movie/similar")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchMovieViewModel>> SimilarMovies([FromBody] SimilarMoviesRefineModel model)
public Task<IEnumerable<SearchMovieViewModel>> 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<IEnumerable<SearchMovieViewModel>> Popular(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchMovieViewModel>> 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));
}
/// <summary>
@ -172,9 +191,11 @@ namespace Ombi.Controllers.V2
[HttpGet("movie/seasonal/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchMovieViewModel>> Seasonal(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchMovieViewModel>> 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));
}
/// <summary>
@ -224,9 +245,11 @@ namespace Ombi.Controllers.V2
[HttpGet("movie/nowplaying/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchMovieViewModel>> NowPlayingMovies(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchMovieViewModel>> 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));
}
/// <summary>
@ -250,9 +273,11 @@ namespace Ombi.Controllers.V2
[HttpGet("movie/toprated/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchMovieViewModel>> TopRatedMovies(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchMovieViewModel>> 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));
}
/// <summary>
@ -276,9 +301,11 @@ namespace Ombi.Controllers.V2
[HttpGet("movie/upcoming/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchMovieViewModel>> UpcomingMovies(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchMovieViewModel>> 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));
}
/// <summary>
@ -289,9 +316,11 @@ namespace Ombi.Controllers.V2
[HttpGet("tv/popular/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchTvShowViewModel>> PopularTv(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchTvShowViewModel>> 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));
}
/// <summary>
@ -302,9 +331,11 @@ namespace Ombi.Controllers.V2
[HttpGet("tv/anticipated/{currentPosition}/{amountToLoad}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesDefaultResponseType]
public async Task<IEnumerable<SearchTvShowViewModel>> AnticipatedTv(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchTvShowViewModel>> 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));
}
/// <summary>
@ -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<IEnumerable<SearchTvShowViewModel>> MostWatched(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchTvShowViewModel>> 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<IEnumerable<SearchTvShowViewModel>> Trending(int currentPosition, int amountToLoad)
public Task<IEnumerable<SearchTvShowViewModel>> 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));
}
/// <summary>
@ -386,7 +421,9 @@ namespace Ombi.Controllers.V2
[ProducesDefaultResponseType]
public Task<MovieRatings> 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<TvRatings> 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<IEnumerable<StreamingData>> 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<IEnumerable<StreamingData>> GetTvStreams(int movieDbId)
{
return _tvEngineV2.GetStreamInformation(movieDbId, HttpContext.RequestAborted);
return _mediaCacheService.GetOrAddAsync(nameof(GetTvStreams) + movieDbId,
() => _tvEngineV2.GetStreamInformation(movieDbId, HttpContext.RequestAborted),
DateTimeOffset.Now.AddHours(12));
}
}
}

@ -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<ICacheService>();
var user = await cache.GetOrAdd(userid + "token", async () =>
var user = await cache.GetOrAddAsync(userid + "token", async () =>
{
var um = context.HttpContext.RequestServices.GetRequiredService<OmbiUserManager>();
return await um.FindByIdAsync(userid);

@ -56,6 +56,7 @@
<PackageReference Include="AspNetCore.HealthChecks.Sqlite" Version="3.0.0" />
<PackageReference Include="AutoMapper" Version="10.0.0" />
<PackageReference Include="CommandLineParser" Version="2.6.0" />
<PackageReference Include="LazyCache.AspNetCore" Version="2.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>

@ -84,7 +84,7 @@ namespace Ombi
//{
// setup.AddHealthCheckEndpoint("Ombi", "/health");
//});
services.AddMemoryCache();
services.AddLazyCache();
services.AddHttpClient();
services.AddJwtAuthentication();

Loading…
Cancel
Save