Skip to content

Commit

Permalink
refactor: move the remaining tmdb search methods
Browse files Browse the repository at this point in the history
from the metadata service to the search service.
  • Loading branch information
revam committed Aug 26, 2024
1 parent 50f6fe1 commit 845dc12
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 124 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ public partial class ShokoServiceImplementation : Controller, IShokoServer
private readonly TraktTVHelper _traktHelper;
private readonly TmdbLinkingService _tmdbLinkingService;
private readonly TmdbMetadataService _tmdbMetadataService;
private readonly TmdbSearchService _tmdbSearchService;
private readonly ISettingsProvider _settingsProvider;
private readonly ISchedulerFactory _schedulerFactory;
private readonly ActionService _actionService;
Expand All @@ -57,7 +58,8 @@ public ShokoServiceImplementation(
TvDBApiHelper tvdbHelper,
TraktTVHelper traktHelper,
TmdbLinkingService tmdbLinkingService,
TmdbMetadataService tmdbService,
TmdbMetadataService tmdbMetadataService,
TmdbSearchService tmdbSearchService,
ISchedulerFactory schedulerFactory,
ISettingsProvider settingsProvider,
ILogger<ShokoServiceImplementation> logger,
Expand All @@ -72,7 +74,8 @@ VideoLocalService videoLocalService
_tvdbHelper = tvdbHelper;
_traktHelper = traktHelper;
_tmdbLinkingService = tmdbLinkingService;
_tmdbMetadataService = tmdbService;
_tmdbMetadataService = tmdbMetadataService;
_tmdbSearchService = tmdbSearchService;
_schedulerFactory = schedulerFactory;
_settingsProvider = settingsProvider;
_logger = logger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1074,7 +1074,7 @@ public List<CL_MovieDBMovieSearch_Response> SearchTheMovieDB(string criteria)
var results = new List<CL_MovieDBMovieSearch_Response>();
try
{
var (movieResults, _) = _tmdbMetadataService.SearchMovies(System.Web.HttpUtility.UrlDecode(criteria)).ConfigureAwait(false).GetAwaiter().GetResult();
var (movieResults, _) = _tmdbSearchService.SearchMovies(System.Web.HttpUtility.UrlDecode(criteria)).ConfigureAwait(false).GetAwaiter().GetResult();

results.AddRange(movieResults.Select(movie => movie.ToContract()));

Expand Down
37 changes: 20 additions & 17 deletions Shoko.Server/API/v3/Controllers/TmdbController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,15 @@ public class TmdbController : BaseController
{
private readonly ILogger<TmdbController> _logger;

private readonly TmdbMetadataService _tmdbService;
private readonly TmdbSearchService _tmdbSearchService;

public TmdbController(ISettingsProvider settingsProvider, ILogger<TmdbController> logger, TmdbMetadataService tmdbService) : base(settingsProvider)
private readonly TmdbMetadataService _tmdbMetadataService;

public TmdbController(ISettingsProvider settingsProvider, ILogger<TmdbController> logger, TmdbSearchService tmdbSearchService, TmdbMetadataService tmdbService) : base(settingsProvider)
{
_logger = logger;
_tmdbService = tmdbService;
_tmdbSearchService = tmdbSearchService;
_tmdbMetadataService = tmdbService;
}

#region Movies
Expand Down Expand Up @@ -183,7 +186,7 @@ public async Task<ActionResult> RemoveTmdbMovieByMovieID(
[FromQuery] bool removeImageFiles = true
)
{
await _tmdbService.SchedulePurgeOfMovie(movieID, removeImageFiles);
await _tmdbMetadataService.SchedulePurgeOfMovie(movieID, removeImageFiles);

return NoContent();
}
Expand Down Expand Up @@ -436,11 +439,11 @@ public async Task<ActionResult> RefreshTmdbMovieByMovieID(
{
if (body.Immediate)
{
await _tmdbService.UpdateMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCrewAndCast, body.DownloadCollections ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCollections);
await _tmdbMetadataService.UpdateMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCrewAndCast, body.DownloadCollections ?? SettingsProvider.GetSettings().TMDB.AutoDownloadCollections);
return Ok();
}

await _tmdbService.ScheduleUpdateOfMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast, body.DownloadCollections);
await _tmdbMetadataService.ScheduleUpdateOfMovie(movieID, body.Force, body.DownloadImages, body.DownloadCrewAndCast, body.DownloadCollections);
return NoContent();
}

Expand All @@ -466,11 +469,11 @@ public async Task<ActionResult> DownloadImagesForTmdbMovieByMovieID(

if (body.Immediate)
{
await _tmdbService.DownloadAllMovieImages(movieID, body.Force);
await _tmdbMetadataService.DownloadAllMovieImages(movieID, body.Force);
return Ok();
}

await _tmdbService.ScheduleDownloadAllMovieImages(movieID, body.Force);
await _tmdbMetadataService.ScheduleDownloadAllMovieImages(movieID, body.Force);
return NoContent();
}

Expand All @@ -497,7 +500,7 @@ public async Task<ActionResult> DownloadImagesForTmdbMovieByMovieID(
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
var (pageView, totalMovies) = _tmdbService.SearchMovies(query, includeRestricted, year, page, pageSize)
var (pageView, totalMovies) = _tmdbSearchService.SearchMovies(query, includeRestricted, year, page, pageSize)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
Expand Down Expand Up @@ -768,7 +771,7 @@ public async Task<ActionResult> RemoveTmdbShowByShowID(
[FromQuery] bool removeImageFiles = true
)
{
await _tmdbService.SchedulePurgeOfShow(showID, removeImageFiles);
await _tmdbMetadataService.SchedulePurgeOfShow(showID, removeImageFiles);

return NoContent();
}
Expand Down Expand Up @@ -1080,11 +1083,11 @@ public async Task<ActionResult> RefreshTmdbShowByShowID(
if (body.Immediate)
{
var settings = SettingsProvider.GetSettings();
await _tmdbService.UpdateShow(showID, body.Force, body.DownloadImages, body.DownloadCrewAndCast ?? settings.TMDB.AutoDownloadCrewAndCast, body.DownloadAlternateOrdering ?? settings.TMDB.AutoDownloadAlternateOrdering);
await _tmdbMetadataService.UpdateShow(showID, body.Force, body.DownloadImages, body.DownloadCrewAndCast ?? settings.TMDB.AutoDownloadCrewAndCast, body.DownloadAlternateOrdering ?? settings.TMDB.AutoDownloadAlternateOrdering);
return Ok();
}

await _tmdbService.ScheduleUpdateOfShow(showID, body.Force, body.DownloadImages, body.DownloadCrewAndCast, body.DownloadAlternateOrdering);
await _tmdbMetadataService.ScheduleUpdateOfShow(showID, body.Force, body.DownloadImages, body.DownloadCrewAndCast, body.DownloadAlternateOrdering);
return NoContent();
}

Expand All @@ -1110,11 +1113,11 @@ public async Task<ActionResult> DownloadImagesForTmdbShowByShowID(

if (body.Immediate)
{
await _tmdbService.DownloadAllShowImages(showID, body.Force);
await _tmdbMetadataService.DownloadAllShowImages(showID, body.Force);
return Ok();
}

await _tmdbService.ScheduleDownloadAllShowImages(showID, body.Force);
await _tmdbMetadataService.ScheduleDownloadAllShowImages(showID, body.Force);
return NoContent();
}

Expand All @@ -1141,7 +1144,7 @@ public async Task<ActionResult> DownloadImagesForTmdbShowByShowID(
[FromQuery, Range(1, int.MaxValue)] int page = 1
)
{
var (pageView, totalShows) = _tmdbService.SearchShows(query, includeRestricted, year, page, pageSize)
var (pageView, totalShows) = _tmdbSearchService.SearchShows(query, includeRestricted, year, page, pageSize)
.ConfigureAwait(false)
.GetAwaiter()
.GetResult();
Expand Down Expand Up @@ -2145,7 +2148,7 @@ IFormFile file
RepoFactory.CrossRef_AniDB_TMDB_Movie.Save(movieXrefsToSave);

foreach (var movieId in moviesToUpdate)
await _tmdbService.SchedulePurgeOfMovie(movieId);
await _tmdbMetadataService.ScheduleUpdateOfMovie(movieId);
}

if (episodeXrefsToSave.Count > 0 || showXrefsToSave.Count > 0 || showsToUpdate.Count > 0)
Expand All @@ -2163,7 +2166,7 @@ IFormFile file
RepoFactory.CrossRef_AniDB_TMDB_Episode.Save(episodeXrefsToSave);

foreach (var showId in showsToUpdate)
await _tmdbService.SchedulePurgeOfShow(showId);
await _tmdbMetadataService.ScheduleUpdateOfShow(showId);
}

return NoContent();
Expand Down
98 changes: 11 additions & 87 deletions Shoko.Server/Providers/TMDB/TmdbMetadataService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ public static string? ImageServerUrl
/// <typeparam name="T">The type of the result of the function.</typeparam>
/// <param name="func">The function to execute with the TMDb client.</param>
/// <returns>A task that will complete with the result of the function, after applying the rate limiting and retry policies.</returns>
protected Task<T> UseClient<T>(Func<TMDbClient, Task<T>> func) =>
public Task<T> UseClient<T>(Func<TMDbClient, Task<T>> func) =>
_bulkheadPolicy.ExecuteAsync(() => _retryPolicy.ExecuteAsync(() => _rateLimitPolicy.ExecuteAsync(() => func(CachedClient))));

public TmdbMetadataService(
Expand Down Expand Up @@ -319,45 +319,7 @@ public async Task ScanForMatches()

#region Movies

#region Search

public async Task<(List<SearchMovie> Page, int TotalCount)> SearchMovies(string query, bool includeRestricted = false, int year = 0, int page = 1, int pageSize = 6)
{
var results = new List<SearchMovie>();
var firstPage = await UseClient(c => c.SearchMovieAsync(query, 1, includeRestricted, year)).ConfigureAwait(false);
var total = firstPage.TotalResults;
if (total == 0)
return (results, total);

var lastPage = firstPage.TotalPages;
var actualPageSize = firstPage.Results.Count;
var startIndex = (page - 1) * pageSize;
var startPage = (int)Math.Floor((decimal)startIndex / actualPageSize) + 1;
var endIndex = Math.Min(startIndex + pageSize, total);
var endPage = total == endIndex ? lastPage : Math.Min((int)Math.Floor((decimal)endIndex / actualPageSize) + (endIndex % actualPageSize > 0 ? 1 : 0), lastPage);
for (var i = startPage; i <= endPage; i++)
{
var actualPage = await UseClient(c => c.SearchMovieAsync(query, i, includeRestricted, year)).ConfigureAwait(false);
results.AddRange(actualPage.Results);
}

var skipCount = startIndex - (startPage - 1) * actualPageSize;
var pagedResults = results.Skip(skipCount).Take(pageSize).ToList();

_logger.LogTrace(
"Got {Count} movies from {Results} total movies at {IndexRange} across {PageRange}.",
pagedResults.Count,
total,
startIndex == endIndex ? $"index {startIndex}" : $"indexes {startIndex}-{endIndex}",
startPage == endPage ? $"{startPage} actual page" : $"{startPage}-{endPage} actual pages"
);

return (pagedResults, total);
}

#endregion

#region Update
#region Update (Movies)

public async Task UpdateAllMovies(bool force, bool saveImages)
{
Expand Down Expand Up @@ -728,7 +690,7 @@ public async Task DownloadMovieImages(int movieId, TitleLanguage? mainLanguage =

#endregion

#region Purge
#region Purge (Movies)

public async Task PurgeAllUnusedMovies()
{
Expand Down Expand Up @@ -868,47 +830,9 @@ private void PurgeMovieCollection(int collectionId, bool removeImageFiles = true

#endregion

#region Show

#region Search

public async Task<(List<SearchTv> Page, int TotalCount)> SearchShows(string query, bool includeRestricted = false, int year = 0, int page = 1, int pageSize = 6)
{
var results = new List<SearchTv>();
var firstPage = await UseClient(c => c.SearchTvShowAsync(query, 1, includeRestricted, year)).ConfigureAwait(false);
var total = firstPage.TotalResults;
if (total == 0)
return (results, total);

var lastPage = firstPage.TotalPages;
var actualPageSize = firstPage.Results.Count;
var startIndex = (page - 1) * pageSize;
var startPage = (int)Math.Floor((decimal)startIndex / actualPageSize) + 1;
var endIndex = Math.Min(startIndex + pageSize, total);
var endPage = total == endIndex ? lastPage : Math.Min((int)Math.Floor((decimal)endIndex / actualPageSize) + (endIndex % actualPageSize > 0 ? 1 : 0), lastPage);
for (var i = startPage; i <= endPage; i++)
{
var actualPage = await UseClient(c => c.SearchTvShowAsync(query, i, includeRestricted, year)).ConfigureAwait(false);
results.AddRange(actualPage.Results);
}

var skipCount = startIndex - (startPage - 1) * actualPageSize;
var pagedResults = results.Skip(skipCount).Take(pageSize).ToList();

_logger.LogTrace(
"Got {Count} shows from {Results} total shows at {IndexRange} across {PageRange}.",
pagedResults.Count,
total,
startIndex == endIndex ? $"index {startIndex}" : $"indexes {startIndex}-{endIndex}",
startPage == endPage ? $"{startPage} actual page" : $"{startPage}-{endPage} actual pages"
);

return (pagedResults, total);
}

#endregion
#region Shows

#region Update
#region Update (Shows)

public async Task UpdateAllShows(bool force = false, bool downloadImages = false)
{
Expand Down Expand Up @@ -1536,7 +1460,7 @@ private List<TitleLanguage> GetLanguages(TitleLanguage? mainLanguage = null) =>

#endregion

#region Purge
#region Purge (Shows)

public async Task PurgeAllUnusedShows()
{
Expand Down Expand Up @@ -1738,7 +1662,7 @@ private void PurgeShowEpisodeGroups(int showId)

#region Shared

#region Titles & Overviews
#region Titles & Overviews (Shared)

/// <summary>
/// Updates the titles and overviews for the <paramref name="tmdbEntity"/>
Expand Down Expand Up @@ -1890,7 +1814,7 @@ private void PurgeTitlesAndOverviews(ForeignEntityType foreignType, int foreignI

#endregion

#region Companies
#region Companies (Shared)

private async Task<bool> UpdateCompanies(IEntityMetadata tmdbEntity, List<ProductionCompany> companies)
{
Expand Down Expand Up @@ -1990,7 +1914,7 @@ private void PurgeCompany(int companyId, bool removeImageFiles = true)

#endregion

#region People
#region People (Shared)

public async Task DownloadPersonImages(int personId, bool forceDownload = false)
{
Expand Down Expand Up @@ -2069,7 +1993,7 @@ private bool IsPersonLinkedToOtherEntities(int tmdbPersonId)

#endregion

#region Helpers
#region Helpers (Shared)

private static async Task ProcessWithConcurrencyAsync<T>(
int maxConcurrent,
Expand Down Expand Up @@ -2128,7 +2052,7 @@ Func<T, Task> processAsync

#endregion

#region External IDs
#region External IDs (Shared)

/// <summary>
/// Update TvDB ID for the TMDB show if needed and the ID is available.
Expand Down
Loading

0 comments on commit 845dc12

Please sign in to comment.