diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..ba4a7e3 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,4 @@ +[*.cs] + +# CS4014: Because this call is not awaited, execution of the current method continues before the call is completed +dotnet_diagnostic.CS4014.severity = error diff --git a/.gitignore b/.gitignore index ceb05f0..c78ec96 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,13 @@ bin/ obj/ *.user -Build/ \ No newline at end of file +Build/ +*.DotSettings + +# Project specific +TestApplication/config.json +*.lock.json + +# Verify +# https://github.com/VerifyTests/Verify#received-and-verified +*.received.* \ No newline at end of file diff --git a/TMDbLib.sln b/TMDbLib.sln index 498cd57..a33e9e6 100644 --- a/TMDbLib.sln +++ b/TMDbLib.sln @@ -11,6 +11,7 @@ EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{26BF5A0A-354A-46F5-A20C-0BEB5D45783A}" ProjectSection(SolutionItems) = preProject Directory.Build.props = Directory.Build.props + .editorconfig = .editorconfig Readme.md = Readme.md EndProjectSection EndProject diff --git a/TMDbLib/Client/TMDbClient.cs b/TMDbLib/Client/TMDbClient.cs index 7b3cf4e..ee3a9ae 100644 --- a/TMDbLib/Client/TMDbClient.cs +++ b/TMDbLib/Client/TMDbClient.cs @@ -11,6 +11,7 @@ using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; +using TMDbLib.Rest; namespace TMDbLib.Client { @@ -157,7 +158,7 @@ namespace TMDbLib.Client public async Task GetConfigAsync() { - TMDbConfig config = await _client.Create("configuration").ExecuteGet(CancellationToken.None); + TMDbConfig config = await _client.Create("configuration").GetOfT(CancellationToken.None); if (config == null) throw new Exception("Unable to retrieve configuration"); @@ -243,7 +244,7 @@ namespace TMDbLib.Client /// - Use the 'AuthenticationGetUserSessionAsync' and 'AuthenticationCreateGuestSessionAsync' methods to optain the respective session ids. /// - User sessions have access to far for methods than guest sessions, these can currently only be used to rate media. /// - public void SetSessionInformation(string sessionId, SessionType sessionType) + public async Task SetSessionInformationAsync(string sessionId, SessionType sessionType) { ActiveAccount = null; SessionId = sessionId; @@ -259,7 +260,7 @@ namespace TMDbLib.Client { try { - ActiveAccount = AccountGetDetailsAsync().Result; + ActiveAccount = await AccountGetDetailsAsync().ConfigureAwait(false); } catch (Exception) { diff --git a/TMDbLib/Client/TMDbClientAccount.cs b/TMDbLib/Client/TMDbClientAccount.cs index a574d4a..59d0c07 100644 --- a/TMDbLib/Client/TMDbClientAccount.cs +++ b/TMDbLib/Client/TMDbClientAccount.cs @@ -13,204 +13,7 @@ namespace TMDbLib.Client { public partial class TMDbClient { - /// - /// Change the favorite status of a specific movie. Either make the movie a favorite or remove that status depending on the supplied boolean value. - /// - /// The type of media to influence - /// The id of the movie/tv show to influence - /// True if you want the specified movie to be marked as favorite, false if not - /// Cancellation token - /// True if the the movie's favorite status was successfully updated, false if not - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task AccountChangeFavoriteStatusAsync(MediaType mediaType, int mediaId, bool isFavorite, CancellationToken cancellationToken = default(CancellationToken)) - { - RequireSessionId(SessionType.UserSession); - - RestRequest request = _client.Create("account/{accountId}/favorite"); - request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); - request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, favorite = isFavorite }); - AddSessionId(request, SessionType.UserSession); - - PostReply response = await request.ExecutePost(cancellationToken).ConfigureAwait(false); - - // status code 1 = "Success" - Returned when adding a movie as favorite for the first time - // status code 13 = "The item/record was deleted successfully" - When removing an item as favorite, no matter if it exists or not - // status code 12 = "The item/record was updated successfully" - Used when an item is already marked as favorite and trying to do so doing again - return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13; - } - - /// - /// Change the state of a specific movie on the users watchlist. Either add the movie to the list or remove it, depending on the specified boolean value. - /// - /// The type of media to influence - /// The id of the movie/tv show to influence - /// True if you want the specified movie to be part of the watchlist, false if not - /// A cancellation token - /// True if the the movie's status on the watchlist was successfully updated, false if not - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task AccountChangeWatchlistStatusAsync(MediaType mediaType, int mediaId, bool isOnWatchlist, CancellationToken cancellationToken = default(CancellationToken)) - { - RequireSessionId(SessionType.UserSession); - - RestRequest request = _client.Create("account/{accountId}/watchlist"); - request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); - request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, watchlist = isOnWatchlist }); - AddSessionId(request, SessionType.UserSession); - - PostReply response = await request.ExecutePost(cancellationToken).ConfigureAwait(false); - - // status code 1 = "Success" - // status code 13 = "The item/record was deleted successfully" - When removing an item from the watchlist, no matter if it exists or not - // status code 12 = "The item/record was updated successfully" - Used when an item is already on the watchlist and trying to add it again - return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13; - } - - /// - /// Will retrieve the details of the account associated with the current session id - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task AccountGetDetailsAsync(CancellationToken cancellationToken = default(CancellationToken)) - { - RequireSessionId(SessionType.UserSession); - - RestRequest request = _client.Create("account"); - AddSessionId(request, SessionType.UserSession); - - AccountDetails response = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return response; - } - - /// - /// Get a list of all the movies marked as favorite by the current user - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetFavoriteMoviesAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteMovies, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a list of all the tv shows marked as favorite by the current user - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetFavoriteTvAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteTv, cancellationToken).ConfigureAwait(false); - } - - /// - /// Retrieve all lists associated with the provided account id - /// This can be lists that were created by the user or lists marked as favorite - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetListsAsync(int page = 1, string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - RequireSessionId(SessionType.UserSession); - - RestRequest request = _client.Create("account/{accountId}/lists"); - request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); - AddSessionId(request, SessionType.UserSession); - - if (page > 1) - { - request.AddQueryString("page", page.ToString()); - } - - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - request.AddQueryString("language", language); - - SearchContainer response = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); - - return response; - } - - /// - /// Get a list of all the movies on the current users match list - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetMovieWatchlistAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.MovieWatchlist, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a list of all the movies rated by the current user - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetRatedMoviesAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.RatedMovies, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a list of all the tv show episodes rated by the current user - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetRatedTvShowEpisodesAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.RatedTvEpisodes, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a list of all the tv shows rated by the current user - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetRatedTvShowsAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.RatedTv, cancellationToken).ConfigureAwait(false); - } - - /// - /// Get a list of all the tv shows on the current users match list - /// - /// Requires a valid user session - /// Thrown when the current client object doens't have a user session assigned. - public async Task> AccountGetTvWatchlistAsync( - int page = 1, - AccountSortBy sortBy = AccountSortBy.Undefined, - SortOrder sortOrder = SortOrder.Undefined, - string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetAccountList(page, sortBy, sortOrder, language, AccountListsMethods.TvWatchlist, cancellationToken).ConfigureAwait(false); - } - - private async Task> GetAccountList(int page, AccountSortBy sortBy, SortOrder sortOrder, string language, AccountListsMethods method, CancellationToken cancellationToken = default(CancellationToken)) + private async Task> GetAccountListInternal(int page, AccountSortBy sortBy, SortOrder sortOrder, string language, AccountListsMethods method, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -231,11 +34,208 @@ namespace TMDbLib.Client if (!string.IsNullOrWhiteSpace(language)) request.AddParameter("language", language); - SearchContainer response = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer response = await request.GetOfT>(cancellationToken).ConfigureAwait(false); return response; } + /// + /// Change the favorite status of a specific movie. Either make the movie a favorite or remove that status depending on the supplied boolean value. + /// + /// The type of media to influence + /// The id of the movie/tv show to influence + /// True if you want the specified movie to be marked as favorite, false if not + /// Cancellation token + /// True if the the movie's favorite status was successfully updated, false if not + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task AccountChangeFavoriteStatusAsync(MediaType mediaType, int mediaId, bool isFavorite, CancellationToken cancellationToken = default) + { + RequireSessionId(SessionType.UserSession); + + RestRequest request = _client.Create("account/{accountId}/favorite"); + request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); + request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, favorite = isFavorite }); + AddSessionId(request, SessionType.UserSession); + + PostReply response = await request.PostOfT(cancellationToken).ConfigureAwait(false); + + // status code 1 = "Success" - Returned when adding a movie as favorite for the first time + // status code 13 = "The item/record was deleted successfully" - When removing an item as favorite, no matter if it exists or not + // status code 12 = "The item/record was updated successfully" - Used when an item is already marked as favorite and trying to do so doing again + return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13; + } + + /// + /// Change the state of a specific movie on the users watchlist. Either add the movie to the list or remove it, depending on the specified boolean value. + /// + /// The type of media to influence + /// The id of the movie/tv show to influence + /// True if you want the specified movie to be part of the watchlist, false if not + /// A cancellation token + /// True if the the movie's status on the watchlist was successfully updated, false if not + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task AccountChangeWatchlistStatusAsync(MediaType mediaType, int mediaId, bool isOnWatchlist, CancellationToken cancellationToken = default) + { + RequireSessionId(SessionType.UserSession); + + RestRequest request = _client.Create("account/{accountId}/watchlist"); + request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); + request.SetBody(new { media_type = mediaType.GetDescription(), media_id = mediaId, watchlist = isOnWatchlist }); + AddSessionId(request, SessionType.UserSession); + + PostReply response = await request.PostOfT(cancellationToken).ConfigureAwait(false); + + // status code 1 = "Success" + // status code 13 = "The item/record was deleted successfully" - When removing an item from the watchlist, no matter if it exists or not + // status code 12 = "The item/record was updated successfully" - Used when an item is already on the watchlist and trying to add it again + return response.StatusCode == 1 || response.StatusCode == 12 || response.StatusCode == 13; + } + + /// + /// Will retrieve the details of the account associated with the current session id + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task AccountGetDetailsAsync(CancellationToken cancellationToken = default) + { + RequireSessionId(SessionType.UserSession); + + RestRequest request = _client.Create("account"); + AddSessionId(request, SessionType.UserSession); + + AccountDetails response = await request.GetOfT(cancellationToken).ConfigureAwait(false); + + return response; + } + + /// + /// Get a list of all the movies marked as favorite by the current user + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetFavoriteMoviesAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteMovies, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a list of all the tv shows marked as favorite by the current user + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetFavoriteTvAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.FavoriteTv, cancellationToken).ConfigureAwait(false); + } + + /// + /// Retrieve all lists associated with the provided account id + /// This can be lists that were created by the user or lists marked as favorite + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetListsAsync(int page = 1, string language = null, CancellationToken cancellationToken = default) + { + RequireSessionId(SessionType.UserSession); + + RestRequest request = _client.Create("account/{accountId}/lists"); + request.AddUrlSegment("accountId", ActiveAccount.Id.ToString(CultureInfo.InvariantCulture)); + AddSessionId(request, SessionType.UserSession); + + if (page > 1) + { + request.AddQueryString("page", page.ToString()); + } + + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + request.AddQueryString("language", language); + + SearchContainer response = await request.GetOfT>(cancellationToken).ConfigureAwait(false); + + return response; + } + + /// + /// Get a list of all the movies on the current users match list + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetMovieWatchlistAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.MovieWatchlist, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a list of all the movies rated by the current user + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetRatedMoviesAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.RatedMovies, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a list of all the tv show episodes rated by the current user + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetRatedTvShowEpisodesAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.RatedTvEpisodes, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a list of all the tv shows rated by the current user + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetRatedTvShowsAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.RatedTv, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get a list of all the tv shows on the current users match list + /// + /// Requires a valid user session + /// Thrown when the current client object doens't have a user session assigned. + public async Task> AccountGetTvWatchlistAsync( + int page = 1, + AccountSortBy sortBy = AccountSortBy.Undefined, + SortOrder sortOrder = SortOrder.Undefined, + string language = null, CancellationToken cancellationToken = default) + { + return await GetAccountListInternal(page, sortBy, sortOrder, language, AccountListsMethods.TvWatchlist, cancellationToken).ConfigureAwait(false); + } + private enum AccountListsMethods { [EnumValue("favorite/movies")] diff --git a/TMDbLib/Client/TMDbClientAuthentication.cs b/TMDbLib/Client/TMDbClientAuthentication.cs index 26fbfae..1d7b39d 100644 --- a/TMDbLib/Client/TMDbClientAuthentication.cs +++ b/TMDbLib/Client/TMDbClientAuthentication.cs @@ -9,29 +9,29 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task AuthenticationCreateGuestSessionAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task AuthenticationCreateGuestSessionAsync(CancellationToken cancellationToken = default) { RestRequest request = _client.Create("authentication/guest_session/new"); //{ // DateFormat = "yyyy-MM-dd HH:mm:ss UTC" //}; - RestResponse response = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); + GuestSession response = await request.GetOfT(cancellationToken).ConfigureAwait(false); return response; } - public async Task AuthenticationGetUserSessionAsync(string initialRequestToken, CancellationToken cancellationToken = default(CancellationToken)) + public async Task AuthenticationGetUserSessionAsync(string initialRequestToken, CancellationToken cancellationToken = default) { RestRequest request = _client.Create("authentication/session/new"); request.AddParameter("request_token", initialRequestToken); - RestResponse response = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await request.Get(cancellationToken).ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.Unauthorized) throw new UnauthorizedAccessException(); - return response; + return await response.GetDataObject().ConfigureAwait(false); } /// @@ -40,26 +40,26 @@ namespace TMDbLib.Client /// A valid TMDb username /// The passoword for the provided login /// A cancellation token - public async Task AuthenticationGetUserSessionAsync(string username, string password, CancellationToken cancellationToken = default(CancellationToken)) + public async Task AuthenticationGetUserSessionAsync(string username, string password, CancellationToken cancellationToken = default) { Token token = await AuthenticationRequestAutenticationTokenAsync(cancellationToken).ConfigureAwait(false); await AuthenticationValidateUserTokenAsync(token.RequestToken, username, password, cancellationToken).ConfigureAwait(false); return await AuthenticationGetUserSessionAsync(token.RequestToken, cancellationToken).ConfigureAwait(false); } - public async Task AuthenticationRequestAutenticationTokenAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task AuthenticationRequestAutenticationTokenAsync(CancellationToken cancellationToken = default) { RestRequest request = _client.Create("authentication/token/new"); - RestResponse response = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); - Token token = response; + RestResponse response = await request.Get(cancellationToken).ConfigureAwait(false); + Token token = await response.GetDataObject().ConfigureAwait(false); token.AuthenticationCallback = response.GetHeader("Authentication-Callback"); return token; } - public async Task AuthenticationValidateUserTokenAsync(string initialRequestToken, string username, string password, CancellationToken cancellationToken = default(CancellationToken)) + public async Task AuthenticationValidateUserTokenAsync(string initialRequestToken, string username, string password, CancellationToken cancellationToken = default) { RestRequest request = _client.Create("authentication/token/validate_with_login"); request.AddParameter("request_token", initialRequestToken); @@ -69,7 +69,7 @@ namespace TMDbLib.Client RestResponse response; try { - response = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); + response = await request.Get(cancellationToken).ConfigureAwait(false); } catch (AggregateException ex) { diff --git a/TMDbLib/Client/TMDbClientCertifications.cs b/TMDbLib/Client/TMDbClientCertifications.cs index 8267ace..be6c5a4 100644 --- a/TMDbLib/Client/TMDbClientCertifications.cs +++ b/TMDbLib/Client/TMDbClientCertifications.cs @@ -7,20 +7,20 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetMovieCertificationsAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieCertificationsAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("certification/movie/list"); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + CertificationsContainer resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } - public async Task GetTvCertificationsAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvCertificationsAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("certification/tv/list"); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + CertificationsContainer resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientChanges.cs b/TMDbLib/Client/TMDbClientChanges.cs index cc1e93c..0973fbb 100644 --- a/TMDbLib/Client/TMDbClientChanges.cs +++ b/TMDbLib/Client/TMDbClientChanges.cs @@ -1,4 +1,5 @@ using System; +using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.Changes; @@ -9,11 +10,20 @@ namespace TMDbLib.Client { public partial class TMDbClient { - private async Task> GetChanges(string type, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetChangesInternal(string type, int page = 0, int? id = null, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) { - RestRequest req = _client.Create("{type}/changes"); + string resource; + if (id.HasValue) + resource = "{type}/{id}/changes"; + else + resource = "{type}/changes"; + + RestRequest req = _client.Create(resource); req.AddUrlSegment("type", type); + if (id.HasValue) + req.AddUrlSegment("id", id.Value.ToString()); + if (page >= 1) req.AddParameter("page", page.ToString()); if (startDate.HasValue) @@ -21,11 +31,14 @@ namespace TMDbLib.Client if (endDate != null) req.AddParameter("end_date", endDate.Value.ToString("yyyy-MM-dd")); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); - SearchContainer res = await resp.GetDataObject().ConfigureAwait(false); + RestResponse resp = await req.Get(cancellationToken).ConfigureAwait(false); + T res = await resp.GetDataObject().ConfigureAwait(false); - // https://github.com/LordMike/TMDbLib/issues/296 - res.Results.RemoveAll(s => s.Id == 0); + if (res is SearchContainer asSearch) + { + // https://github.com/LordMike/TMDbLib/issues/296 + asSearch.Results.RemoveAll(s => s.Id == 0); + } return res; } @@ -37,9 +50,9 @@ namespace TMDbLib.Client /// You can then use the movie changes API to get the actual data that has been changed. (.GetMovieChangesAsync) /// /// the change log system to support this was changed on October 5, 2012 and will only show movies that have been edited since. - public async Task> GetChangesMoviesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMoviesChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) { - return await GetChanges("movie", page, startDate, endDate, cancellationToken).ConfigureAwait(false); + return await GetChangesInternal>("movie", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -49,9 +62,9 @@ namespace TMDbLib.Client /// You can then use the person changes API to get the actual data that has been changed.(.GetPersonChangesAsync) /// /// the change log system to support this was changed on October 5, 2012 and will only show people that have been edited since. - public async Task> GetChangesPeopleAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetPeopleChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) { - return await GetChanges("person", page, startDate, endDate, cancellationToken).ConfigureAwait(false); + return await GetChangesInternal>("person", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -64,9 +77,33 @@ namespace TMDbLib.Client /// the change log system to properly support TV was updated on May 13, 2014. /// You'll likely only find the edits made since then to be useful in the change log system. /// - public async Task> GetChangesTvAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvChangesAsync(int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) { - return await GetChanges("tv", page, startDate, endDate, cancellationToken).ConfigureAwait(false); + return await GetChangesInternal>("tv", page, startDate: startDate, endDate: endDate, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + public async Task> GetMovieChangesAsync(int movieId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) + { + ChangesContainer changesContainer = await GetChangesInternal("movie", page, movieId, startDate, endDate, cancellationToken); + return changesContainer.Changes; + } + + public async Task> GetPersonChangesAsync(int personId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) + { + ChangesContainer changesContainer = await GetChangesInternal("person", page, personId, startDate, endDate, cancellationToken).ConfigureAwait(false); + return changesContainer.Changes; + } + + public async Task> GetTvSeasonChangesAsync(int seasonId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) + { + ChangesContainer changesContainer = await GetChangesInternal("tv/season", page, seasonId, startDate, endDate, cancellationToken).ConfigureAwait(false); + return changesContainer.Changes; + } + + public async Task> GetTvEpisodeChangesAsync(int episodeId, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) + { + ChangesContainer changesContainer = await GetChangesInternal("tv/episode", page, episodeId, startDate, endDate, cancellationToken).ConfigureAwait(false); + return changesContainer.Changes; } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientCollections.cs b/TMDbLib/Client/TMDbClientCollections.cs index be3268a..bd8ae06 100644 --- a/TMDbLib/Client/TMDbClientCollections.cs +++ b/TMDbLib/Client/TMDbClientCollections.cs @@ -12,12 +12,26 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetCollectionAsync(int collectionId, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetCollectionMethodInternal(int collectionId, CollectionMethods collectionMethod, string language = null, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("collection/{collectionId}/{method}"); + req.AddUrlSegment("collectionId", collectionId.ToString()); + req.AddUrlSegment("method", collectionMethod.GetDescription()); + + if (language != null) + req.AddParameter("language", language); + + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return resp; + } + + public async Task GetCollectionAsync(int collectionId, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default) { return await GetCollectionAsync(collectionId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false); } - public async Task GetCollectionAsync(int collectionId, string language, string includeImageLanguages, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetCollectionAsync(int collectionId, string language, string includeImageLanguages, CollectionMethods extraMethods = CollectionMethods.Undefined, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("collection/{collectionId}"); req.AddUrlSegment("collectionId", collectionId.ToString()); @@ -42,7 +56,7 @@ namespace TMDbLib.Client //req.DateFormat = "yyyy-MM-dd"; - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; @@ -55,23 +69,9 @@ namespace TMDbLib.Client return item; } - public async Task GetCollectionImagesAsync(int collectionId, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetCollectionImagesAsync(int collectionId, string language = null, CancellationToken cancellationToken = default) { - return await GetCollectionMethod(collectionId, CollectionMethods.Images, language, cancellationToken).ConfigureAwait(false); + return await GetCollectionMethodInternal(collectionId, CollectionMethods.Images, language, cancellationToken).ConfigureAwait(false); } - - private async Task GetCollectionMethod(int collectionId, CollectionMethods collectionMethod, string language = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() - { - RestRequest req = _client.Create("collection/{collectionId}/{method}"); - req.AddUrlSegment("collectionId", collectionId.ToString()); - req.AddUrlSegment("method", collectionMethod.GetDescription()); - - if (language != null) - req.AddParameter("language", language); - - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return resp; } - } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientCompanies.cs b/TMDbLib/Client/TMDbClientCompanies.cs index cdc8498..39e82da 100644 --- a/TMDbLib/Client/TMDbClientCompanies.cs +++ b/TMDbLib/Client/TMDbClientCompanies.cs @@ -12,7 +12,24 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetCompanyAsync(int companyId, CompanyMethods extraMethods = CompanyMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetCompanyMethodInternal(int companyId, CompanyMethods companyMethod, int page = 0, string language = null, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("company/{companyId}/{method}"); + req.AddUrlSegment("companyId", companyId.ToString()); + req.AddUrlSegment("method", companyMethod.GetDescription()); + + if (page >= 1) + req.AddParameter("page", page.ToString()); + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return resp; + } + + public async Task GetCompanyAsync(int companyId, CompanyMethods extraMethods = CompanyMethods.Undefined, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("company/{companyId}"); req.AddUrlSegment("companyId", companyId.ToString()); @@ -29,36 +46,19 @@ namespace TMDbLib.Client //req.DateFormat = "yyyy-MM-dd"; - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + Company resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } - private async Task GetCompanyMethod(int companyId, CompanyMethods companyMethod, int page = 0, string language = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() - { - RestRequest req = _client.Create("company/{companyId}/{method}"); - req.AddUrlSegment("companyId", companyId.ToString()); - req.AddUrlSegment("method", companyMethod.GetDescription()); - - if (page >= 1) - req.AddParameter("page", page.ToString()); - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return resp; - } - - public async Task> GetCompanyMoviesAsync(int companyId, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetCompanyMoviesAsync(int companyId, int page = 0, CancellationToken cancellationToken = default) { return await GetCompanyMoviesAsync(companyId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetCompanyMoviesAsync(int companyId, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetCompanyMoviesAsync(int companyId, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetCompanyMethod>(companyId, CompanyMethods.Movies, page, language, cancellationToken).ConfigureAwait(false); + return await GetCompanyMethodInternal>(companyId, CompanyMethods.Movies, page, language, cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientConfiguration.cs b/TMDbLib/Client/TMDbClientConfiguration.cs index 7ca0e59..fe882b1 100644 --- a/TMDbLib/Client/TMDbClientConfiguration.cs +++ b/TMDbLib/Client/TMDbClientConfiguration.cs @@ -13,47 +13,47 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetAPIConfiguration(CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetAPIConfiguration(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("configuration"); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)); } - public async Task> GetCountriesAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetCountriesAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("configuration/countries"); - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + RestResponse> response = await req.Get>(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)); } - public async Task> GetLanguagesAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetLanguagesAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("configuration/languages"); - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + RestResponse> response = await req.Get>(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)); } - public async Task> GetPrimaryTranslationsAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetPrimaryTranslationsAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("configuration/primary_translations"); - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + RestResponse> response = await req.Get>(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)); } - public async Task GetTimezonesAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTimezonesAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("timezones/list"); - RestResponse>>> resp = await req.ExecuteGet>>>(cancellationToken).ConfigureAwait(false); + RestResponse>>> resp = await req.Get>>>(cancellationToken).ConfigureAwait(false); List>> item = await resp.GetDataObject().ConfigureAwait(false); @@ -77,11 +77,11 @@ namespace TMDbLib.Client /// Retrieves a list of departments and positions within /// /// Valid jobs and their departments - public async Task> GetJobsAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetJobsAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("configuration/jobs"); - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + RestResponse> response = await req.Get>(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)); } diff --git a/TMDbLib/Client/TMDbClientCredit.cs b/TMDbLib/Client/TMDbClientCredit.cs index 1846529..15dfe82 100644 --- a/TMDbLib/Client/TMDbClientCredit.cs +++ b/TMDbLib/Client/TMDbClientCredit.cs @@ -7,12 +7,12 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetCreditsAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetCreditsAsync(string id, CancellationToken cancellationToken = default) { return await GetCreditsAsync(id, DefaultLanguage, cancellationToken).ConfigureAwait(false); } - public async Task GetCreditsAsync(string id, string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetCreditsAsync(string id, string language, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("credit/{id}"); @@ -21,7 +21,7 @@ namespace TMDbLib.Client req.AddUrlSegment("id", id); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + Credit resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientDiscover.cs b/TMDbLib/Client/TMDbClientDiscover.cs index ec2f0a8..8d22b8f 100644 --- a/TMDbLib/Client/TMDbClientDiscover.cs +++ b/TMDbLib/Client/TMDbClientDiscover.cs @@ -18,7 +18,7 @@ namespace TMDbLib.Client return new DiscoverMovie(this); } - internal async Task> DiscoverPerformAsync(string endpoint, string language, int page, SimpleNamedValueCollection parameters, CancellationToken cancellationToken = default(CancellationToken)) + internal async Task> DiscoverPerformAsync(string endpoint, string language, int page, SimpleNamedValueCollection parameters, CancellationToken cancellationToken = default) { RestRequest request = _client.Create(endpoint); @@ -31,7 +31,7 @@ namespace TMDbLib.Client foreach (KeyValuePair pair in parameters) request.AddParameter(pair.Key, pair.Value); - RestResponse> response = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer response = await request.GetOfT>(cancellationToken).ConfigureAwait(false); return response; } diff --git a/TMDbLib/Client/TMDbClientFind.cs b/TMDbLib/Client/TMDbClientFind.cs index 4dff332..889261b 100644 --- a/TMDbLib/Client/TMDbClientFind.cs +++ b/TMDbLib/Client/TMDbClientFind.cs @@ -20,7 +20,7 @@ namespace TMDbLib.Client /// The id of the object you wish to located /// A list of all objects in TMDb that matched your id /// A cancellation token - public Task FindAsync(FindExternalSource source, string id, CancellationToken cancellationToken = default(CancellationToken)) + public Task FindAsync(FindExternalSource source, string id, CancellationToken cancellationToken = default) { return FindAsync(source, id, null, cancellationToken); } @@ -37,7 +37,7 @@ namespace TMDbLib.Client /// A list of all objects in TMDb that matched your id /// If specified the api will attempt to return a localized result. ex: en,it,es. /// A cancellation token - public async Task FindAsync(FindExternalSource source, string id, string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task FindAsync(FindExternalSource source, string id, string language, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("find/{id}"); @@ -49,7 +49,7 @@ namespace TMDbLib.Client if (!string.IsNullOrEmpty(language)) req.AddParameter("language", language); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + FindContainer resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientGenres.cs b/TMDbLib/Client/TMDbClientGenres.cs index c9754c0..ccfded5 100644 --- a/TMDbLib/Client/TMDbClientGenres.cs +++ b/TMDbLib/Client/TMDbClientGenres.cs @@ -12,13 +12,13 @@ namespace TMDbLib.Client public partial class TMDbClient { [Obsolete("GetGenreMovies is deprecated, use DiscoverMovies instead")] - public async Task> GetGenreMoviesAsync(int genreId, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGenreMoviesAsync(int genreId, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default) { return await GetGenreMoviesAsync(genreId, DefaultLanguage, page, includeAllMovies, cancellationToken).ConfigureAwait(false); } [Obsolete("GetGenreMovies is deprecated, use DiscoverMovies instead")] - public async Task> GetGenreMoviesAsync(int genreId, string language, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGenreMoviesAsync(int genreId, string language, int page = 0, bool? includeAllMovies = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("genre/{genreId}/movies"); req.AddUrlSegment("genreId", genreId.ToString()); @@ -32,17 +32,17 @@ namespace TMDbLib.Client if (includeAllMovies.HasValue) req.AddParameter("include_all_movies", includeAllMovies.Value ? "true" : "false"); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainerWithId resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetMovieGenresAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieGenresAsync(CancellationToken cancellationToken = default) { return await GetMovieGenresAsync(DefaultLanguage, cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieGenresAsync(string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieGenresAsync(string language, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("genre/movie/list"); @@ -50,17 +50,17 @@ namespace TMDbLib.Client if (!string.IsNullOrWhiteSpace(language)) req.AddParameter("language", language); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse resp = await req.Get(cancellationToken).ConfigureAwait(false); return (await resp.GetDataObject().ConfigureAwait(false)).Genres; } - public async Task> GetTvGenresAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvGenresAsync(CancellationToken cancellationToken = default) { return await GetTvGenresAsync(DefaultLanguage, cancellationToken).ConfigureAwait(false); } - public async Task> GetTvGenresAsync(string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvGenresAsync(string language, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("genre/tv/list"); @@ -68,7 +68,7 @@ namespace TMDbLib.Client if (!string.IsNullOrWhiteSpace(language)) req.AddParameter("language", language); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse resp = await req.Get(cancellationToken).ConfigureAwait(false); return (await resp.GetDataObject().ConfigureAwait(false)).Genres; } diff --git a/TMDbLib/Client/TMDbClientGuestSessions.cs b/TMDbLib/Client/TMDbClientGuestSessions.cs index 633eaa8..420e264 100644 --- a/TMDbLib/Client/TMDbClientGuestSessions.cs +++ b/TMDbLib/Client/TMDbClientGuestSessions.cs @@ -10,12 +10,12 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task> GetGuestSessionRatedMoviesAsync(int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedMoviesAsync(int page = 0, CancellationToken cancellationToken = default) { return await GetGuestSessionRatedMoviesAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetGuestSessionRatedMoviesAsync(string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedMoviesAsync(string language, int page = 0, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -29,17 +29,17 @@ namespace TMDbLib.Client AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment); - RestResponse> resp = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await request.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetGuestSessionRatedTvAsync(int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedTvAsync(int page = 0, CancellationToken cancellationToken = default) { return await GetGuestSessionRatedTvAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetGuestSessionRatedTvAsync(string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedTvAsync(string language, int page = 0, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -53,17 +53,17 @@ namespace TMDbLib.Client AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment); - RestResponse> resp = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await request.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetGuestSessionRatedTvEpisodesAsync(int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedTvEpisodesAsync(int page = 0, CancellationToken cancellationToken = default) { return await GetGuestSessionRatedTvEpisodesAsync(DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetGuestSessionRatedTvEpisodesAsync(string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetGuestSessionRatedTvEpisodesAsync(string language, int page = 0, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -77,7 +77,7 @@ namespace TMDbLib.Client AddSessionId(request, SessionType.GuestSession, ParameterType.UrlSegment); - RestResponse> resp = await request.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await request.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientKeywords.cs b/TMDbLib/Client/TMDbClientKeywords.cs index ed4853a..2082654 100644 --- a/TMDbLib/Client/TMDbClientKeywords.cs +++ b/TMDbLib/Client/TMDbClientKeywords.cs @@ -8,22 +8,22 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetKeywordAsync(int keywordId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetKeywordAsync(int keywordId, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("keyword/{keywordId}"); req.AddUrlSegment("keywordId", keywordId.ToString()); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + Keyword resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetKeywordMoviesAsync(int keywordId, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetKeywordMoviesAsync(int keywordId, int page = 0, CancellationToken cancellationToken = default) { return await GetKeywordMoviesAsync(keywordId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetKeywordMoviesAsync(int keywordId, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetKeywordMoviesAsync(int keywordId, string language, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("keyword/{keywordId}/movies"); req.AddUrlSegment("keywordId", keywordId.ToString()); @@ -35,7 +35,7 @@ namespace TMDbLib.Client if (page >= 1) req.AddParameter("page", page.ToString()); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainerWithId resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientLists.cs b/TMDbLib/Client/TMDbClientLists.cs index df11198..c965736 100644 --- a/TMDbLib/Client/TMDbClientLists.cs +++ b/TMDbLib/Client/TMDbClientLists.cs @@ -10,12 +10,40 @@ namespace TMDbLib.Client { public partial class TMDbClient { + private async Task GetManipulateMediaListAsyncInternal(string listId, int movieId, string method, CancellationToken cancellationToken = default) + { + RequireSessionId(SessionType.UserSession); + + if (string.IsNullOrWhiteSpace(listId)) + throw new ArgumentNullException(nameof(listId)); + + // Movie Id is expected by the API and can not be null + if (movieId <= 0) + throw new ArgumentOutOfRangeException(nameof(movieId)); + + RestRequest req = _client.Create("list/{listId}/{method}"); + req.AddUrlSegment("listId", listId); + req.AddUrlSegment("method", method); + AddSessionId(req, SessionType.UserSession); + + req.SetBody(new { media_id = movieId }); + + RestResponse response = await req.Post(cancellationToken).ConfigureAwait(false); + + // Status code 12 = "The item/record was updated successfully" + // Status code 13 = "The item/record was deleted successfully" + PostReply item = await response.GetDataObject().ConfigureAwait(false); + + // TODO: Previous code checked for item=null + return item.StatusCode == 12 || item.StatusCode == 13; + } + /// /// Retrieve a list by it's id /// /// The id of the list you want to retrieve /// A cancellation token - public async Task GetListAsync(string listId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetListAsync(string listId, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(listId)) throw new ArgumentNullException(nameof(listId)); @@ -23,7 +51,7 @@ namespace TMDbLib.Client RestRequest req = _client.Create("list/{listId}"); req.AddUrlSegment("listId", listId); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + GenericList resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } @@ -34,7 +62,7 @@ namespace TMDbLib.Client /// Id of the list to check in /// Id of the movie to check for in the list /// A cancellation token - public async Task GetListIsMoviePresentAsync(string listId, int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetListIsMoviePresentAsync(string listId, int movieId, CancellationToken cancellationToken = default) { if (string.IsNullOrWhiteSpace(listId)) throw new ArgumentNullException(nameof(listId)); @@ -46,7 +74,7 @@ namespace TMDbLib.Client req.AddUrlSegment("listId", listId); req.AddParameter("movie_id", movieId.ToString()); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)).ItemPresent; } @@ -60,9 +88,9 @@ namespace TMDbLib.Client /// True if the method was able to add the movie to the list, will retrun false in case of an issue or when the movie was already added to the list /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task ListAddMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ListAddMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default) { - return await ManipulateMediaListAsync(listId, movieId, "add_item", cancellationToken).ConfigureAwait(false); + return await GetManipulateMediaListAsyncInternal(listId, movieId, "add_item", cancellationToken).ConfigureAwait(false); } /// @@ -73,7 +101,7 @@ namespace TMDbLib.Client /// True if the method was able to remove the movie from the list, will retrun false in case of an issue or when the movie was not present in the list /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task ListClearAsync(string listId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ListClearAsync(string listId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -85,7 +113,7 @@ namespace TMDbLib.Client request.AddParameter("confirm", "true"); AddSessionId(request, SessionType.UserSession); - RestResponse response = await request.ExecutePost(cancellationToken).ConfigureAwait(false); + RestResponse response = await request.Post(cancellationToken).ConfigureAwait(false); // Status code 12 = "The item/record was updated successfully" PostReply item = await response.GetDataObject().ConfigureAwait(false); @@ -103,7 +131,7 @@ namespace TMDbLib.Client /// A cancellation token /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task ListCreateAsync(string name, string description = "", string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ListCreateAsync(string name, string description = "", string language = null, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -128,7 +156,7 @@ namespace TMDbLib.Client req.SetBody(new { name = name, description = description }); } - RestResponse response = await req.ExecutePost(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Post(cancellationToken).ConfigureAwait(false); return (await response.GetDataObject().ConfigureAwait(false)).ListId; } @@ -140,7 +168,7 @@ namespace TMDbLib.Client /// A cancellation token /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task ListDeleteAsync(string listId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ListDeleteAsync(string listId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -151,7 +179,7 @@ namespace TMDbLib.Client req.AddUrlSegment("listId", listId); AddSessionId(req, SessionType.UserSession); - RestResponse response = await req.ExecuteDelete(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Delete(cancellationToken).ConfigureAwait(false); // Status code 13 = success PostReply item = await response.GetDataObject().ConfigureAwait(false); @@ -169,37 +197,9 @@ namespace TMDbLib.Client /// True if the method was able to remove the movie from the list, will retrun false in case of an issue or when the movie was not present in the list /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task ListRemoveMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task ListRemoveMovieAsync(string listId, int movieId, CancellationToken cancellationToken = default) { - return await ManipulateMediaListAsync(listId, movieId, "remove_item", cancellationToken).ConfigureAwait(false); - } - - private async Task ManipulateMediaListAsync(string listId, int movieId, string method, CancellationToken cancellationToken = default(CancellationToken)) - { - RequireSessionId(SessionType.UserSession); - - if (string.IsNullOrWhiteSpace(listId)) - throw new ArgumentNullException(nameof(listId)); - - // Movie Id is expected by the API and can not be null - if (movieId <= 0) - throw new ArgumentOutOfRangeException(nameof(movieId)); - - RestRequest req = _client.Create("list/{listId}/{method}"); - req.AddUrlSegment("listId", listId); - req.AddUrlSegment("method", method); - AddSessionId(req, SessionType.UserSession); - - req.SetBody(new { media_id = movieId }); - - RestResponse response = await req.ExecutePost(cancellationToken).ConfigureAwait(false); - - // Status code 12 = "The item/record was updated successfully" - // Status code 13 = "The item/record was deleted successfully" - PostReply item = await response.GetDataObject().ConfigureAwait(false); - - // TODO: Previous code checked for item=null - return item.StatusCode == 12 || item.StatusCode == 13; + return await GetManipulateMediaListAsyncInternal(listId, movieId, "remove_item", cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientMovies.cs b/TMDbLib/Client/TMDbClientMovies.cs index 58a576c..cdbbf88 100644 --- a/TMDbLib/Client/TMDbClientMovies.cs +++ b/TMDbLib/Client/TMDbClientMovies.cs @@ -6,7 +6,6 @@ using System.Net; using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.Authentication; -using TMDbLib.Objects.Changes; using TMDbLib.Objects.General; using TMDbLib.Objects.Movies; using TMDbLib.Objects.Reviews; @@ -19,6 +18,35 @@ namespace TMDbLib.Client { public partial class TMDbClient { + private async Task GetMovieMethodInternal(int movieId, MovieMethods movieMethod, string dateFormat = null, + string country = null, + string language = null, string includeImageLanguage = null, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("movie/{movieId}/{method}"); + req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("method", movieMethod.GetDescription()); + + if (country != null) + req.AddParameter("country", country); + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + if (!string.IsNullOrWhiteSpace(includeImageLanguage)) + req.AddParameter("include_image_language", includeImageLanguage); + + if (page >= 1) + req.AddParameter("page", page.ToString()); + if (startDate.HasValue) + req.AddParameter("start_date", startDate.Value.ToString("yyyy-MM-dd")); + if (endDate != null) + req.AddParameter("end_date", endDate.Value.ToString("yyyy-MM-dd")); + + T response = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return response; + } + /// /// Retrieves all information for a specific movie in relation to the current user account /// @@ -26,7 +54,7 @@ namespace TMDbLib.Client /// A cancellation token /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task GetMovieAccountStateAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAccountStateAsync(int movieId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -35,32 +63,32 @@ namespace TMDbLib.Client req.AddUrlSegment("method", MovieMethods.AccountStates.GetDescription()); AddSessionId(req, SessionType.UserSession); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); return await response.GetDataObject().ConfigureAwait(false); } - public async Task GetMovieAlternativeTitlesAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAlternativeTitlesAsync(int movieId, CancellationToken cancellationToken = default) { return await GetMovieAlternativeTitlesAsync(movieId, DefaultCountry, cancellationToken).ConfigureAwait(false); } - public async Task GetMovieAlternativeTitlesAsync(int movieId, string country, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAlternativeTitlesAsync(int movieId, string country, CancellationToken cancellationToken = default) { - return await GetMovieMethod(movieId, MovieMethods.AlternativeTitles, country: country, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.AlternativeTitles, country: country, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetMovieAsync(int movieId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAsync(int movieId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default) { return await GetMovieAsync(movieId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false); } - public async Task GetMovieAsync(string imdbId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAsync(string imdbId, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default) { return await GetMovieAsync(imdbId, DefaultLanguage, null, extraMethods, cancellationToken).ConfigureAwait(false); } - public async Task GetMovieAsync(int movieId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAsync(int movieId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default) { return await GetMovieAsync(movieId.ToString(CultureInfo.InvariantCulture), language, includeImageLanguage, extraMethods, cancellationToken).ConfigureAwait(false); } @@ -76,7 +104,7 @@ namespace TMDbLib.Client /// The reqed movie or null if it could not be found /// Requires a valid user session when specifying the extra method 'AccountStates' flag /// Thrown when the current client object doens't have a user session assigned, see remarks. - public async Task GetMovieAsync(string imdbId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieAsync(string imdbId, string language, string includeImageLanguage = null, MovieMethods extraMethods = MovieMethods.Undefined, CancellationToken cancellationToken = default) { if (extraMethods.HasFlag(MovieMethods.AccountStates)) RequireSessionId(SessionType.UserSession); @@ -103,7 +131,7 @@ namespace TMDbLib.Client if (appends != string.Empty) req.AddParameter("append_to_response", appends); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; @@ -141,15 +169,9 @@ namespace TMDbLib.Client return item; } - public async Task> GetMovieChangesAsync(int movieId, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieCreditsAsync(int movieId, CancellationToken cancellationToken = default) { - ChangesContainer changesContainer = await GetMovieMethod(movieId, MovieMethods.Changes, startDate: startDate, endDate: endDate, dateFormat: "yyyy-MM-dd HH:mm:ss UTC", cancellationToken: cancellationToken).ConfigureAwait(false); - return changesContainer.Changes; - } - - public async Task GetMovieCreditsAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetMovieMethod(movieId, MovieMethods.Credits, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.Credits, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -157,30 +179,30 @@ namespace TMDbLib.Client /// /// The TMDb id of the target movie. /// A cancellation token - public async Task GetMovieExternalIdsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieExternalIdsAsync(int id, CancellationToken cancellationToken = default) { - return await GetMovieMethod(id, MovieMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(id, MovieMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetMovieImagesAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieImagesAsync(int movieId, CancellationToken cancellationToken = default) { return await GetMovieImagesAsync(movieId, DefaultLanguage, null, cancellationToken).ConfigureAwait(false); } - public async Task GetMovieImagesAsync(int movieId, string language, string includeImageLanguage = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieImagesAsync(int movieId, string language, string includeImageLanguage = null, CancellationToken cancellationToken = default) { - return await GetMovieMethod(movieId, MovieMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetMovieKeywordsAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieKeywordsAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod(movieId, MovieMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetMovieLatestAsync(CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieLatestAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("movie/latest"); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse resp = await req.Get(cancellationToken).ConfigureAwait(false); Movie item = await resp.GetDataObject().ConfigureAwait(false); @@ -191,56 +213,27 @@ namespace TMDbLib.Client return item; } - public async Task> GetMovieListsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieListsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default) { return await GetMovieListsAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieListsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieListsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(movieId, MovieMethods.Lists, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(movieId, MovieMethods.Lists, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default) { return await GetMovieRecommendationsAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(id, MovieMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(id, MovieMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); } - private async Task GetMovieMethod(int movieId, MovieMethods movieMethod, string dateFormat = null, - string country = null, - string language = null, string includeImageLanguage = null, int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() - { - RestRequest req = _client.Create("movie/{movieId}/{method}"); - req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("method", movieMethod.GetDescription()); - - if (country != null) - req.AddParameter("country", country); - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - if (!string.IsNullOrWhiteSpace(includeImageLanguage)) - req.AddParameter("include_image_language", includeImageLanguage); - - if (page >= 1) - req.AddParameter("page", page.ToString()); - if (startDate.HasValue) - req.AddParameter("start_date", startDate.Value.ToString("yyyy-MM-dd")); - if (endDate != null) - req.AddParameter("end_date", endDate.Value.ToString("yyyy-MM-dd")); - - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return response; - } - - public async Task> GetMovieNowPlayingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieNowPlayingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("movie/now_playing"); @@ -251,12 +244,12 @@ namespace TMDbLib.Client if (region != null) req.AddParameter("region", region); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainerWithDates resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetMoviePopularListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMoviePopularListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("movie/popular"); @@ -267,42 +260,42 @@ namespace TMDbLib.Client if (region != null) req.AddParameter("region", region); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetMovieReleaseDatesAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieReleaseDatesAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(movieId, MovieMethods.ReleaseDates, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(movieId, MovieMethods.ReleaseDates, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetMovieReleasesAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieReleasesAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod(movieId, MovieMethods.Releases, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.Releases, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieReviewsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieReviewsAsync(int movieId, int page = 0, CancellationToken cancellationToken = default) { return await GetMovieReviewsAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieReviewsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieReviewsAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(movieId, MovieMethods.Reviews, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(movieId, MovieMethods.Reviews, page: page, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieSimilarAsync(int movieId, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieSimilarAsync(int movieId, int page = 0, CancellationToken cancellationToken = default) { return await GetMovieSimilarAsync(movieId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieSimilarAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieSimilarAsync(int movieId, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(movieId, MovieMethods.Similar, page: page, language: language, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(movieId, MovieMethods.Similar, page: page, language: language, dateFormat: "yyyy-MM-dd", cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieTopRatedListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieTopRatedListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("movie/top_rated"); @@ -313,17 +306,17 @@ namespace TMDbLib.Client if (region != null) req.AddParameter("region", region); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task GetMovieTranslationsAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetMovieTranslationsAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod(movieId, MovieMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal(movieId, MovieMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetMovieUpcomingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieUpcomingListAsync(string language = null, int page = 0, string region = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("movie/upcoming"); @@ -334,22 +327,22 @@ namespace TMDbLib.Client if (region != null) req.AddParameter("region", region); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainerWithDates resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetMovieVideosAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetMovieVideosAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod>(movieId, MovieMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>(movieId, MovieMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task>> GetMovieWatchProvidersAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task>> GetMovieWatchProvidersAsync(int movieId, CancellationToken cancellationToken = default) { - return await GetMovieMethod>>(movieId, MovieMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetMovieMethodInternal>>(movieId, MovieMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task MovieRemoveRatingAsync(int movieId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task MovieRemoveRatingAsync(int movieId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -357,7 +350,7 @@ namespace TMDbLib.Client req.AddUrlSegment("movieId", movieId.ToString(CultureInfo.InvariantCulture)); AddSessionId(req); - RestResponse response = await req.ExecuteDelete(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Delete(cancellationToken).ConfigureAwait(false); // status code 13 = "The item/record was deleted successfully." PostReply item = await response.GetDataObject().ConfigureAwait(false); @@ -375,7 +368,7 @@ namespace TMDbLib.Client /// True if the the movie's rating was successfully updated, false if not /// Requires a valid guest or user session /// Thrown when the current client object doens't have a guest or user session assigned. - public async Task MovieSetRatingAsync(int movieId, double rating, CancellationToken cancellationToken = default(CancellationToken)) + public async Task MovieSetRatingAsync(int movieId, double rating, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -385,7 +378,7 @@ namespace TMDbLib.Client req.SetBody(new { value = rating }); - RestResponse response = await req.ExecutePost(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Post(cancellationToken).ConfigureAwait(false); // status code 1 = "Success" // status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user diff --git a/TMDbLib/Client/TMDbClientNetworks.cs b/TMDbLib/Client/TMDbClientNetworks.cs index 58d56b3..2902560 100644 --- a/TMDbLib/Client/TMDbClientNetworks.cs +++ b/TMDbLib/Client/TMDbClientNetworks.cs @@ -14,12 +14,12 @@ namespace TMDbLib.Client /// /// The id of the network object to retrieve /// A cancellation token - public async Task GetNetworkAsync(int networkId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetNetworkAsync(int networkId, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("network/{networkId}"); req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture)); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + Network response = await req.GetOfT(cancellationToken).ConfigureAwait(false); return response; } @@ -29,12 +29,12 @@ namespace TMDbLib.Client /// /// The TMDb id of the network /// A cancellation token - public async Task GetNetworkImagesAsync(int networkId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetNetworkImagesAsync(int networkId, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("network/{networkId}/images"); req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture)); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + NetworkLogos response = await req.GetOfT(cancellationToken).ConfigureAwait(false); return response; } @@ -44,12 +44,12 @@ namespace TMDbLib.Client /// /// The TMDb id of the network /// A cancellation token - public async Task GetNetworkAlternativeNamesAsync(int networkId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetNetworkAlternativeNamesAsync(int networkId, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("network/{networkId}/alternative_names"); req.AddUrlSegment("networkId", networkId.ToString(CultureInfo.InvariantCulture)); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + AlternativeNames response = await req.GetOfT(cancellationToken).ConfigureAwait(false); return response; } diff --git a/TMDbLib/Client/TMDbClientPeople.cs b/TMDbLib/Client/TMDbClientPeople.cs index 01bc34a..4163d7b 100644 --- a/TMDbLib/Client/TMDbClientPeople.cs +++ b/TMDbLib/Client/TMDbClientPeople.cs @@ -1,9 +1,7 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; -using TMDbLib.Objects.Changes; using TMDbLib.Objects.General; using TMDbLib.Objects.People; using TMDbLib.Rest; @@ -13,110 +11,8 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetLatestPersonAsync(CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req = _client.Create("person/latest"); - - // TODO: Dateformat? - //req.DateFormat = "yyyy-MM-dd"; - - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return resp; - } - - public async Task GetPersonAsync(int personId, PersonMethods extraMethods = PersonMethods.Undefined, - CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetPersonAsync(personId, DefaultLanguage, extraMethods, cancellationToken); - } - - public async Task GetPersonAsync(int personId, string language, PersonMethods extraMethods = PersonMethods.Undefined, CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req = _client.Create("person/{personId}"); - req.AddUrlSegment("personId", personId.ToString()); - - if (language != null) - req.AddParameter("language", language); - - string appends = string.Join(",", - Enum.GetValues(typeof(PersonMethods)) - .OfType() - .Except(new[] { PersonMethods.Undefined }) - .Where(s => extraMethods.HasFlag(s)) - .Select(s => s.GetDescription())); - - if (appends != string.Empty) - req.AddParameter("append_to_response", appends); - - // TODO: Dateformat? - //req.DateFormat = "yyyy-MM-dd"; - - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - if (!response.IsValid) - return null; - - Person item = await response.GetDataObject().ConfigureAwait(false); - - // Patch up data, so that the end user won't notice that we share objects between request-types. - if (item != null) - { - if (item.Images != null) - item.Images.Id = item.Id; - - if (item.TvCredits != null) - item.TvCredits.Id = item.Id; - - if (item.MovieCredits != null) - item.MovieCredits.Id = item.Id; - } - - return item; - } - - public async Task> GetPersonChangesAsync(int personId, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) - { - ChangesContainer changesContainer = await GetPersonMethod(personId, PersonMethods.Changes, startDate: startDate, endDate: endDate, dateFormat: "yyyy-MM-dd HH:mm:ss UTC", cancellationToken: cancellationToken).ConfigureAwait(false); - return changesContainer.Changes; - } - - public async Task GetPersonExternalIdsAsync(int personId, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetPersonMethod(personId, PersonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - public async Task GetPersonImagesAsync(int personId, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetPersonMethod(personId, PersonMethods.Images, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - public async Task> GetPersonListAsync(PersonListType type, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req; - switch (type) - { - case PersonListType.Popular: - req = _client.Create("person/popular"); - break; - - default: - throw new ArgumentOutOfRangeException(nameof(type)); - } - - if (page >= 1) - req.AddParameter("page", page.ToString()); - - // TODO: Dateformat? - //req.DateFormat = "yyyy-MM-dd"; - - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); - - return resp; - } - - private async Task GetPersonMethod(int personId, PersonMethods personMethod, string dateFormat = null, string country = null, string language = null, - int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() + private async Task GetPersonMethodInternal(int personId, PersonMethods personMethod, string dateFormat = null, string country = null, string language = null, + int page = 0, DateTime? startDate = null, DateTime? endDate = null, CancellationToken cancellationToken = default) where T : new() { RestRequest req = _client.Create("person/{personId}/{method}"); req.AddUrlSegment("personId", personId.ToString()); @@ -139,39 +35,135 @@ namespace TMDbLib.Client if (endDate != null) req.AddParameter("endDate", endDate.Value.ToString("yyyy-MM-dd")); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } - public async Task GetPersonMovieCreditsAsync(int personId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetLatestPersonAsync(CancellationToken cancellationToken = default) + { + RestRequest req = _client.Create("person/latest"); + + // TODO: Dateformat? + //req.DateFormat = "yyyy-MM-dd"; + + Person resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return resp; + } + + public async Task GetPersonAsync(int personId, PersonMethods extraMethods = PersonMethods.Undefined, + CancellationToken cancellationToken = default) + { + return await GetPersonAsync(personId, DefaultLanguage, extraMethods, cancellationToken); + } + + public async Task GetPersonAsync(int personId, string language, PersonMethods extraMethods = PersonMethods.Undefined, CancellationToken cancellationToken = default) + { + RestRequest req = _client.Create("person/{personId}"); + req.AddUrlSegment("personId", personId.ToString()); + + if (language != null) + req.AddParameter("language", language); + + string appends = string.Join(",", + Enum.GetValues(typeof(PersonMethods)) + .OfType() + .Except(new[] { PersonMethods.Undefined }) + .Where(s => extraMethods.HasFlag(s)) + .Select(s => s.GetDescription())); + + if (appends != string.Empty) + req.AddParameter("append_to_response", appends); + + // TODO: Dateformat? + //req.DateFormat = "yyyy-MM-dd"; + + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); + + if (!response.IsValid) + return null; + + Person item = await response.GetDataObject().ConfigureAwait(false); + + // Patch up data, so that the end user won't notice that we share objects between request-types. + if (item != null) + { + if (item.Images != null) + item.Images.Id = item.Id; + + if (item.TvCredits != null) + item.TvCredits.Id = item.Id; + + if (item.MovieCredits != null) + item.MovieCredits.Id = item.Id; + } + + return item; + } + + public async Task GetPersonExternalIdsAsync(int personId, CancellationToken cancellationToken = default) + { + return await GetPersonMethodInternal(personId, PersonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + public async Task GetPersonImagesAsync(int personId, CancellationToken cancellationToken = default) + { + return await GetPersonMethodInternal(personId, PersonMethods.Images, cancellationToken: cancellationToken).ConfigureAwait(false); + } + + public async Task> GetPersonListAsync(PersonListType type, int page = 0, CancellationToken cancellationToken = default) + { + RestRequest req; + switch (type) + { + case PersonListType.Popular: + req = _client.Create("person/popular"); + break; + + default: + throw new ArgumentOutOfRangeException(nameof(type)); + } + + if (page >= 1) + req.AddParameter("page", page.ToString()); + + // TODO: Dateformat? + //req.DateFormat = "yyyy-MM-dd"; + + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); + + return resp; + } + + public async Task GetPersonMovieCreditsAsync(int personId, CancellationToken cancellationToken = default) { return await GetPersonMovieCreditsAsync(personId, DefaultLanguage, cancellationToken).ConfigureAwait(false); } - public async Task GetPersonMovieCreditsAsync(int personId, string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetPersonMovieCreditsAsync(int personId, string language, CancellationToken cancellationToken = default) { - return await GetPersonMethod(personId, PersonMethods.MovieCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetPersonMethodInternal(personId, PersonMethods.MovieCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetPersonTaggedImagesAsync(int personId, int page, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetPersonTaggedImagesAsync(int personId, int page, CancellationToken cancellationToken = default) { return await GetPersonTaggedImagesAsync(personId, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetPersonTaggedImagesAsync(int personId, string language, int page, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetPersonTaggedImagesAsync(int personId, string language, int page, CancellationToken cancellationToken = default) { - return await GetPersonMethod>(personId, PersonMethods.TaggedImages, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetPersonMethodInternal>(personId, PersonMethods.TaggedImages, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task GetPersonTvCreditsAsync(int personId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetPersonTvCreditsAsync(int personId, CancellationToken cancellationToken = default) { return await GetPersonTvCreditsAsync(personId, DefaultLanguage, cancellationToken).ConfigureAwait(false); } - public async Task GetPersonTvCreditsAsync(int personId, string language, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetPersonTvCreditsAsync(int personId, string language, CancellationToken cancellationToken = default) { - return await GetPersonMethod(personId, PersonMethods.TvCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetPersonMethodInternal(personId, PersonMethods.TvCredits, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientReviews.cs b/TMDbLib/Client/TMDbClientReviews.cs index 694329d..eadeece 100644 --- a/TMDbLib/Client/TMDbClientReviews.cs +++ b/TMDbLib/Client/TMDbClientReviews.cs @@ -7,7 +7,7 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetReviewAsync(string reviewId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetReviewAsync(string reviewId, CancellationToken cancellationToken = default) { RestRequest request = _client.Create("review/{reviewId}"); request.AddUrlSegment("reviewId", reviewId); @@ -15,7 +15,7 @@ namespace TMDbLib.Client // TODO: Dateformat? //request.DateFormat = "yyyy-MM-dd"; - RestResponse resp = await request.ExecuteGet(cancellationToken).ConfigureAwait(false); + Review resp = await request.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientSearch.cs b/TMDbLib/Client/TMDbClientSearch.cs index a5dbbcc..b2dff13 100644 --- a/TMDbLib/Client/TMDbClientSearch.cs +++ b/TMDbLib/Client/TMDbClientSearch.cs @@ -9,7 +9,7 @@ namespace TMDbLib.Client { public partial class TMDbClient { - private async Task SearchMethod(string method, string query, int page, string language = null, bool? includeAdult = null, int year = 0, string dateFormat = null, string region = null, int primaryReleaseYear = 0, int firstAirDateYear = 0, CancellationToken cancellationToken = default(CancellationToken)) where T : new() + private async Task SearchMethodInternal(string method, string query, int page, string language = null, bool? includeAdult = null, int year = 0, string dateFormat = null, string region = null, int primaryReleaseYear = 0, int firstAirDateYear = 0, CancellationToken cancellationToken = default) where T : new() { RestRequest req = _client.Create("search/{method}"); req.AddUrlSegment("method", method); @@ -38,75 +38,75 @@ namespace TMDbLib.Client if (firstAirDateYear >= 1) req.AddParameter("first_air_date_year", firstAirDateYear.ToString()); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> SearchCollectionAsync(string query, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchCollectionAsync(string query, int page = 0, CancellationToken cancellationToken = default) { return await SearchCollectionAsync(query, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> SearchCollectionAsync(string query, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchCollectionAsync(string query, string language, int page = 0, CancellationToken cancellationToken = default) { - return await SearchMethod>("collection", query, page, language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("collection", query, page, language, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchCompanyAsync(string query, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchCompanyAsync(string query, int page = 0, CancellationToken cancellationToken = default) { - return await SearchMethod>("company", query, page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("company", query, page, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchKeywordAsync(string query, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchKeywordAsync(string query, int page = 0, CancellationToken cancellationToken = default) { - return await SearchMethod>("keyword", query, page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("keyword", query, page, cancellationToken: cancellationToken).ConfigureAwait(false); } [Obsolete("20200701 No longer present in public API")] - public async Task> SearchListAsync(string query, int page = 0, bool includeAdult = false, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchListAsync(string query, int page = 0, bool includeAdult = false, CancellationToken cancellationToken = default) { - return await SearchMethod>("list", query, page, includeAdult: includeAdult, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("list", query, page, includeAdult: includeAdult, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchMovieAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchMovieAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default) { return await SearchMovieAsync(query, DefaultLanguage, page, includeAdult, year, region, primaryReleaseYear, cancellationToken).ConfigureAwait(false); } - public async Task> SearchMovieAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchMovieAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, int primaryReleaseYear = 0, CancellationToken cancellationToken = default) { - return await SearchMethod>("movie", query, page, language, includeAdult, year, "yyyy-MM-dd", region, primaryReleaseYear, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("movie", query, page, language, includeAdult, year, "yyyy-MM-dd", region, primaryReleaseYear, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchMultiAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchMultiAsync(string query, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default) { return await SearchMultiAsync(query, DefaultLanguage, page, includeAdult, year, region, cancellationToken).ConfigureAwait(false); } - public async Task> SearchMultiAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchMultiAsync(string query, string language, int page = 0, bool includeAdult = false, int year = 0, string region = null, CancellationToken cancellationToken = default) { - return await SearchMethod>("multi", query, page, language, includeAdult, year, "yyyy-MM-dd", region, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("multi", query, page, language, includeAdult, year, "yyyy-MM-dd", region, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchPersonAsync(string query, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchPersonAsync(string query, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default) { return await SearchPersonAsync(query, DefaultLanguage, page, includeAdult, region, cancellationToken).ConfigureAwait(false); } - public async Task> SearchPersonAsync(string query, string language, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchPersonAsync(string query, string language, int page = 0, bool includeAdult = false, string region = null, CancellationToken cancellationToken = default) { - return await SearchMethod>("person", query, page, language, includeAdult, region: region, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("person", query, page, language, includeAdult, region: region, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> SearchTvShowAsync(string query, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchTvShowAsync(string query, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default) { return await SearchTvShowAsync(query, DefaultLanguage, page, includeAdult, firstAirDateYear, cancellationToken).ConfigureAwait(false); } - public async Task> SearchTvShowAsync(string query, string language, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> SearchTvShowAsync(string query, string language, int page = 0, bool includeAdult = false, int firstAirDateYear = 0, CancellationToken cancellationToken = default) { - return await SearchMethod>("tv", query, page, language, includeAdult, firstAirDateYear: firstAirDateYear, cancellationToken: cancellationToken).ConfigureAwait(false); + return await SearchMethodInternal>("tv", query, page, language, includeAdult, firstAirDateYear: firstAirDateYear, cancellationToken: cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientTrending.cs b/TMDbLib/Client/TMDbClientTrending.cs index 24d8ac1..4ec6264 100644 --- a/TMDbLib/Client/TMDbClientTrending.cs +++ b/TMDbLib/Client/TMDbClientTrending.cs @@ -9,7 +9,7 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTrendingMoviesAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/movie/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); @@ -17,12 +17,12 @@ namespace TMDbLib.Client if (page >= 1) req.AddQueryString("page", page.ToString()); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTrendingTvAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/tv/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); @@ -30,12 +30,12 @@ namespace TMDbLib.Client if (page >= 1) req.AddQueryString("page", page.ToString()); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } - public async Task> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTrendingPeopleAsync(TimeWindow timeWindow, int page = 0, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("trending/person/{time_window}"); req.AddUrlSegment("time_window", timeWindow.ToString()); @@ -43,7 +43,7 @@ namespace TMDbLib.Client if (page >= 1) req.AddQueryString("page", page.ToString()); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } diff --git a/TMDbLib/Client/TMDbClientTvEpisodeGroups.cs b/TMDbLib/Client/TMDbClientTvEpisodeGroups.cs index b84c51f..9b1b72e 100644 --- a/TMDbLib/Client/TMDbClientTvEpisodeGroups.cs +++ b/TMDbLib/Client/TMDbClientTvEpisodeGroups.cs @@ -14,7 +14,7 @@ namespace TMDbLib.Client /// If specified the api will attempt to return a localized result. ex: en,it,es /// A cancellation token /// The requested collection of tv episode groups - public async Task GetTvEpisodeGroupsAsync(string id, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvEpisodeGroupsAsync(string id, string language = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("tv/episode_group/{id}"); req.AddUrlSegment("id", id); @@ -23,7 +23,7 @@ namespace TMDbLib.Client if (!string.IsNullOrWhiteSpace(language)) req.AddParameter("language", language); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; diff --git a/TMDbLib/Client/TMDbClientTvEpisodes.cs b/TMDbLib/Client/TMDbClientTvEpisodes.cs index 3ecfb24..c5c0e49 100644 --- a/TMDbLib/Client/TMDbClientTvEpisodes.cs +++ b/TMDbLib/Client/TMDbClientTvEpisodes.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.Authentication; -using TMDbLib.Objects.Changes; using TMDbLib.Objects.General; using TMDbLib.Objects.TvShows; using TMDbLib.Rest; @@ -14,7 +13,29 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetTvEpisodeAccountStateAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetTvEpisodeMethodInternal(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/{method}"); + req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture)); + + req.AddUrlSegment("method", tvShowMethod.GetDescription()); + + // TODO: Dateformat? + //if (dateFormat != null) + // req.DateFormat = dateFormat; + + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return resp; + } + + public async Task GetTvEpisodeAccountStateAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -25,7 +46,7 @@ namespace TMDbLib.Client req.AddUrlSegment("method", TvEpisodeMethods.AccountStates.GetDescription()); AddSessionId(req, SessionType.UserSession); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); return await response.GetDataObject().ConfigureAwait(false); } @@ -40,7 +61,7 @@ namespace TMDbLib.Client /// If specified the api will attempt to return a localized result. ex: en,it,es /// If specified the api will attempt to return localized image results eg. en,it,es. /// A cancellation token - public async Task GetTvEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods extraMethods = TvEpisodeMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvEpisodeAsync(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods extraMethods = TvEpisodeMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default) { if (extraMethods.HasFlag(TvEpisodeMethods.AccountStates)) RequireSessionId(SessionType.UserSession); @@ -71,7 +92,7 @@ namespace TMDbLib.Client if (appends != string.Empty) req.AddParameter("append_to_response", appends); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; @@ -98,22 +119,12 @@ namespace TMDbLib.Client return item; } - public async Task GetTvEpisodeChangesAsync(int episodeId, CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req = _client.Create("tv/episode/{id}/changes"); - req.AddUrlSegment("id", episodeId.ToString(CultureInfo.InvariantCulture)); - - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return response; - } - - public async Task> GetTvEpisodesScreenedTheatricallyAsync(int tvShowId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvEpisodesScreenedTheatricallyAsync(int tvShowId, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("tv/{tv_id}/screened_theatrically"); req.AddUrlSegment("tv_id", tvShowId.ToString(CultureInfo.InvariantCulture)); - return await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + return await req.GetOfT>(cancellationToken).ConfigureAwait(false); } /// @@ -124,9 +135,9 @@ namespace TMDbLib.Client /// The episode number of the episode you want to retrieve information for. /// If specified the api will attempt to return a localized result. ex: en,it,es /// A cancellation token - public async Task GetTvEpisodeCreditsAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvEpisodeCreditsAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default) { - return await GetTvEpisodeMethod(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvEpisodeMethodInternal(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -136,9 +147,9 @@ namespace TMDbLib.Client /// The season number of the season the episode belongs to. Note use 0 for specials. /// The episode number of the episode you want to retrieve information for. /// A cancellation token - public async Task GetTvEpisodeExternalIdsAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvEpisodeExternalIdsAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default) { - return await GetTvEpisodeMethod(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvEpisodeMethodInternal(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -152,39 +163,17 @@ namespace TMDbLib.Client /// For images this means that the image might contain language specifc text /// /// A cancellation token - public async Task GetTvEpisodeImagesAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvEpisodeImagesAsync(int tvShowId, int seasonNumber, int episodeNumber, string language = null, CancellationToken cancellationToken = default) { - return await GetTvEpisodeMethod(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvEpisodeMethodInternal(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } - private async Task GetTvEpisodeMethod(int tvShowId, int seasonNumber, int episodeNumber, TvEpisodeMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() + public async Task> GetTvEpisodeVideosAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default) { - RestRequest req = _client.Create("tv/{id}/season/{season_number}/episode/{episode_number}/{method}"); - req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("episode_number", episodeNumber.ToString(CultureInfo.InvariantCulture)); - - req.AddUrlSegment("method", tvShowMethod.GetDescription()); - - // TODO: Dateformat? - //if (dateFormat != null) - // req.DateFormat = dateFormat; - - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return resp; + return await GetTvEpisodeMethodInternal>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvEpisodeVideosAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetTvEpisodeMethod>(tvShowId, seasonNumber, episodeNumber, TvEpisodeMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - public async Task TvEpisodeRemoveRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default(CancellationToken)) + public async Task TvEpisodeRemoveRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -195,7 +184,7 @@ namespace TMDbLib.Client AddSessionId(req); - RestResponse response = await req.ExecuteDelete(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Delete(cancellationToken).ConfigureAwait(false); // status code 13 = "The item/record was deleted successfully." PostReply item = await response.GetDataObject().ConfigureAwait(false); @@ -204,7 +193,7 @@ namespace TMDbLib.Client return item.StatusCode == 13; } - public async Task TvEpisodeSetRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, double rating, CancellationToken cancellationToken = default(CancellationToken)) + public async Task TvEpisodeSetRatingAsync(int tvShowId, int seasonNumber, int episodeNumber, double rating, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -217,7 +206,7 @@ namespace TMDbLib.Client req.SetBody(new { value = rating }); - RestResponse response = await req.ExecutePost(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Post(cancellationToken).ConfigureAwait(false); // status code 1 = "Success" // status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user diff --git a/TMDbLib/Client/TMDbClientTvSeasons.cs b/TMDbLib/Client/TMDbClientTvSeasons.cs index 0b6eec3..ef95bc2 100644 --- a/TMDbLib/Client/TMDbClientTvSeasons.cs +++ b/TMDbLib/Client/TMDbClientTvSeasons.cs @@ -4,7 +4,6 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; using TMDbLib.Objects.Authentication; -using TMDbLib.Objects.Changes; using TMDbLib.Objects.General; using TMDbLib.Objects.TvShows; using TMDbLib.Rest; @@ -15,7 +14,27 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task> GetTvSeasonAccountStateAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetTvSeasonMethodInternal(int tvShowId, int seasonNumber, TvSeasonMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("tv/{id}/season/{season_number}/{method}"); + req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("method", tvShowMethod.GetDescription()); + + // TODO: Dateformat? + //if (dateFormat != null) + // req.DateFormat = dateFormat; + + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + T response = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return response; + } + + public async Task> GetTvSeasonAccountStateAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -25,7 +44,7 @@ namespace TMDbLib.Client req.AddUrlSegment("method", TvEpisodeMethods.AccountStates.GetDescription()); AddSessionId(req, SessionType.UserSession); - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); + RestResponse> response = await req.Get>(cancellationToken).ConfigureAwait(false); return await response.GetDataObject().ConfigureAwait(false); } @@ -40,7 +59,7 @@ namespace TMDbLib.Client /// If specified the api will attempt to return localized image results eg. en,it,es. /// A cancellation token /// The requested season for the specified tv show - public async Task GetTvSeasonAsync(int tvShowId, int seasonNumber, TvSeasonMethods extraMethods = TvSeasonMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvSeasonAsync(int tvShowId, int seasonNumber, TvSeasonMethods extraMethods = TvSeasonMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default) { if (extraMethods.HasFlag(TvSeasonMethods.AccountStates)) RequireSessionId(SessionType.UserSession); @@ -70,7 +89,7 @@ namespace TMDbLib.Client if (appends != string.Empty) req.AddParameter("append_to_response", appends); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; @@ -99,16 +118,6 @@ namespace TMDbLib.Client return item; } - public async Task GetTvSeasonChangesAsync(int seasonId, CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req = _client.Create("tv/season/{id}/changes"); - req.AddUrlSegment("id", seasonId.ToString(CultureInfo.InvariantCulture)); - - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return response; - } - /// /// Returns a credits object for the season of the tv show associated with the provided TMDb id. /// @@ -116,9 +125,9 @@ namespace TMDbLib.Client /// The season number of the season you want to retrieve information for. Note use 0 for specials. /// If specified the api will attempt to return a localized result. ex: en,it,es /// A cancellation token - public async Task GetTvSeasonCreditsAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvSeasonCreditsAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default) { - return await GetTvSeasonMethod(tvShowId, seasonNumber, TvSeasonMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvSeasonMethodInternal(tvShowId, seasonNumber, TvSeasonMethods.Credits, dateFormat: "yyyy-MM-dd", language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -127,9 +136,9 @@ namespace TMDbLib.Client /// The TMDb id of the target tv show. /// The season number of the season you want to retrieve information for. Note use 0 for specials. /// A cancellation token - public async Task GetTvSeasonExternalIdsAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvSeasonExternalIdsAsync(int tvShowId, int seasonNumber, CancellationToken cancellationToken = default) { - return await GetTvSeasonMethod(tvShowId, seasonNumber, TvSeasonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvSeasonMethodInternal(tvShowId, seasonNumber, TvSeasonMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -142,34 +151,14 @@ namespace TMDbLib.Client /// For images this means that the image might contain language specifc text /// /// A cancellation token - public async Task GetTvSeasonImagesAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvSeasonImagesAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default) { - return await GetTvSeasonMethod(tvShowId, seasonNumber, TvSeasonMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvSeasonMethodInternal(tvShowId, seasonNumber, TvSeasonMethods.Images, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } - private async Task GetTvSeasonMethod(int tvShowId, int seasonNumber, TvSeasonMethods tvShowMethod, string dateFormat = null, string language = null, CancellationToken cancellationToken = default(CancellationToken)) where T : new() + public async Task> GetTvSeasonVideosAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default) { - RestRequest req = _client.Create("tv/{id}/season/{season_number}/{method}"); - req.AddUrlSegment("id", tvShowId.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("season_number", seasonNumber.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("method", tvShowMethod.GetDescription()); - - // TODO: Dateformat? - //if (dateFormat != null) - // req.DateFormat = dateFormat; - - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); - - return response; - } - - public async Task> GetTvSeasonVideosAsync(int tvShowId, int seasonNumber, string language = null, CancellationToken cancellationToken = default(CancellationToken)) - { - return await GetTvSeasonMethod>(tvShowId, seasonNumber, TvSeasonMethods.Videos, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvSeasonMethodInternal>(tvShowId, seasonNumber, TvSeasonMethods.Videos, language: language, cancellationToken: cancellationToken).ConfigureAwait(false); } } } \ No newline at end of file diff --git a/TMDbLib/Client/TMDbClientTvShows.cs b/TMDbLib/Client/TMDbClientTvShows.cs index afb8ff3..6675ec6 100644 --- a/TMDbLib/Client/TMDbClientTvShows.cs +++ b/TMDbLib/Client/TMDbClientTvShows.cs @@ -18,11 +18,53 @@ namespace TMDbLib.Client { public partial class TMDbClient { - public async Task GetLatestTvShowAsync(CancellationToken cancellationToken = default(CancellationToken)) + private async Task GetTvShowMethodInternal(int id, TvShowMethods tvShowMethod, string dateFormat = null, string language = null, string includeImageLanguage = null, int page = 0, CancellationToken cancellationToken = default) where T : new() + { + RestRequest req = _client.Create("tv/{id}/{method}"); + req.AddUrlSegment("id", id.ToString(CultureInfo.InvariantCulture)); + req.AddUrlSegment("method", tvShowMethod.GetDescription()); + + // TODO: Dateformat? + //if (dateFormat != null) + // req.DateFormat = dateFormat; + + if (page > 0) + req.AddParameter("page", page.ToString()); + + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + includeImageLanguage = includeImageLanguage ?? DefaultImageLanguage; + if (!string.IsNullOrWhiteSpace(includeImageLanguage)) + req.AddParameter("include_image_language", includeImageLanguage); + + T resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); + + return resp; + } + + private async Task> GetTvShowListInternal(int page, string language, string tvShowListType, CancellationToken cancellationToken = default) + { + RestRequest req = _client.Create("tv/" + tvShowListType); + + language = language ?? DefaultLanguage; + if (!string.IsNullOrWhiteSpace(language)) + req.AddParameter("language", language); + + if (page >= 1) + req.AddParameter("page", page.ToString()); + + SearchContainer response = await req.GetOfT>(cancellationToken).ConfigureAwait(false); + + return response; + } + + public async Task GetLatestTvShowAsync(CancellationToken cancellationToken = default) { RestRequest req = _client.Create("tv/latest"); - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + TvShow resp = await req.GetOfT(cancellationToken).ConfigureAwait(false); return resp; } @@ -34,7 +76,7 @@ namespace TMDbLib.Client /// A cancellation token /// Requires a valid user session /// Thrown when the current client object doens't have a user session assigned. - public async Task GetTvShowAccountStateAsync(int tvShowId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowAccountStateAsync(int tvShowId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.UserSession); @@ -43,14 +85,14 @@ namespace TMDbLib.Client req.AddUrlSegment("method", TvShowMethods.AccountStates.GetDescription()); AddSessionId(req, SessionType.UserSession); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); return await response.GetDataObject().ConfigureAwait(false); } - public async Task> GetTvShowAlternativeTitlesAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowAlternativeTitlesAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.AlternativeTitles, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.AlternativeTitles, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -62,7 +104,7 @@ namespace TMDbLib.Client /// If specified the api will attempt to return localized image results eg. en,it,es. /// A cancellation token /// The requested Tv Show - public async Task GetTvShowAsync(int id, TvShowMethods extraMethods = TvShowMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowAsync(int id, TvShowMethods extraMethods = TvShowMethods.Undefined, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default) { if (extraMethods.HasFlag(TvShowMethods.AccountStates)) RequireSessionId(SessionType.UserSession); @@ -90,7 +132,7 @@ namespace TMDbLib.Client if (appends != string.Empty) req.AddParameter("append_to_response", appends); - RestResponse response = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Get(cancellationToken).ConfigureAwait(false); if (!response.IsValid) return null; @@ -117,14 +159,14 @@ namespace TMDbLib.Client return item; } - public async Task GetTvShowChangesAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowChangesAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod(id, TvShowMethods.Changes, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal(id, TvShowMethods.Changes, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowContentRatingsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowContentRatingsAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.ContentRatings, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.ContentRatings, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -133,9 +175,9 @@ namespace TMDbLib.Client /// The TMDb id of the target tv show. /// If specified the api will attempt to return a localized result. ex: en,it,es /// A cancellation token - public async Task GetTvShowCreditsAsync(int id, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowCreditsAsync(int id, string language = null, CancellationToken cancellationToken = default) { - return await GetTvShowMethod(id, TvShowMethods.Credits, "yyyy-MM-dd", language, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal(id, TvShowMethods.Credits, "yyyy-MM-dd", language, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -143,9 +185,9 @@ namespace TMDbLib.Client /// /// The TMDb id of the target tv show. /// A cancellation token - public async Task GetTvShowExternalIdsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowExternalIdsAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod(id, TvShowMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal(id, TvShowMethods.ExternalIds, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -157,35 +199,19 @@ namespace TMDbLib.Client /// For images this means that the image might contain language specifc text /// /// A cancellation token - public async Task GetTvShowImagesAsync(int id, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowImagesAsync(int id, string language = null, string includeImageLanguage = null, CancellationToken cancellationToken = default) { - return await GetTvShowMethod(id, TvShowMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal(id, TvShowMethods.Images, language: language, includeImageLanguage: includeImageLanguage, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowReviewsAsync(int id, string language = null, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowReviewsAsync(int id, string language = null, int page = 0, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.Reviews, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.Reviews, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowKeywordsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowKeywordsAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false); - } - - private async Task> GetTvShowListAsync(int page, string language, string tvShowListType, CancellationToken cancellationToken = default(CancellationToken)) - { - RestRequest req = _client.Create("tv/" + tvShowListType); - - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - if (page >= 1) - req.AddParameter("page", page.ToString()); - - RestResponse> response = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); - - return response; + return await GetTvShowMethodInternal>(id, TvShowMethods.Keywords, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -196,7 +222,7 @@ namespace TMDbLib.Client /// Only relevant for list type AiringToday /// A cancellation token /// - public async Task> GetTvShowListAsync(TvShowListType list, int page = 0, string timezone = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowListAsync(TvShowListType list, int page = 0, string timezone = null, CancellationToken cancellationToken = default) { return await GetTvShowListAsync(list, DefaultLanguage, page, timezone, cancellationToken).ConfigureAwait(false); } @@ -210,7 +236,7 @@ namespace TMDbLib.Client /// Only relevant for list type AiringToday /// A cancellation token /// - public async Task> GetTvShowListAsync(TvShowListType list, string language, int page = 0, string timezone = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowListAsync(TvShowListType list, string language, int page = 0, string timezone = null, CancellationToken cancellationToken = default) { RestRequest req = _client.Create("tv/{method}"); req.AddUrlSegment("method", list.GetDescription()); @@ -225,33 +251,7 @@ namespace TMDbLib.Client if (!string.IsNullOrWhiteSpace(language)) req.AddParameter("language", language); - RestResponse> resp = await req.ExecuteGet>(cancellationToken).ConfigureAwait(false); - - return resp; - } - - private async Task GetTvShowMethod(int id, TvShowMethods tvShowMethod, string dateFormat = null, string language = null, string includeImageLanguage = null, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) where T : new() - { - RestRequest req = _client.Create("tv/{id}/{method}"); - req.AddUrlSegment("id", id.ToString(CultureInfo.InvariantCulture)); - req.AddUrlSegment("method", tvShowMethod.GetDescription()); - - // TODO: Dateformat? - //if (dateFormat != null) - // req.DateFormat = dateFormat; - - if (page > 0) - req.AddParameter("page", page.ToString()); - - language = language ?? DefaultLanguage; - if (!string.IsNullOrWhiteSpace(language)) - req.AddParameter("language", language); - - includeImageLanguage = includeImageLanguage ?? DefaultImageLanguage; - if (!string.IsNullOrWhiteSpace(includeImageLanguage)) - req.AddParameter("include_image_language", includeImageLanguage); - - RestResponse resp = await req.ExecuteGet(cancellationToken).ConfigureAwait(false); + SearchContainer resp = await req.GetOfT>(cancellationToken).ConfigureAwait(false); return resp; } @@ -263,29 +263,29 @@ namespace TMDbLib.Client /// Returns the basic information about a tv show. /// For additional data use the main GetTvShowAsync method using the tv show id as parameter. /// - public async Task> GetTvShowPopularAsync(int page = -1, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowPopularAsync(int page = -1, string language = null, CancellationToken cancellationToken = default) { - return await GetTvShowListAsync(page, language, "popular", cancellationToken).ConfigureAwait(false); + return await GetTvShowListInternal(page, language, "popular", cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowSimilarAsync(int id, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowSimilarAsync(int id, int page = 0, CancellationToken cancellationToken = default) { return await GetTvShowSimilarAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowSimilarAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowSimilarAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.Similar, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.Similar, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowRecommendationsAsync(int id, int page = 0, CancellationToken cancellationToken = default) { return await GetTvShowRecommendationsAsync(id, DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowRecommendationsAsync(int id, string language, int page = 0, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.Recommendations, language: language, page: page, cancellationToken: cancellationToken).ConfigureAwait(false); } /// @@ -295,27 +295,27 @@ namespace TMDbLib.Client /// Returns the basic information about a tv show. /// For additional data use the main GetTvShowAsync method using the tv show id as parameter /// - public async Task> GetTvShowTopRatedAsync(int page = -1, string language = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowTopRatedAsync(int page = -1, string language = null, CancellationToken cancellationToken = default) { - return await GetTvShowListAsync(page, language, "top_rated", cancellationToken).ConfigureAwait(false); + return await GetTvShowListInternal(page, language, "top_rated", cancellationToken).ConfigureAwait(false); } - public async Task GetTvShowTranslationsAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task GetTvShowTranslationsAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod(id, TvShowMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal(id, TvShowMethods.Translations, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task> GetTvShowVideosAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> GetTvShowVideosAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>(id, TvShowMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>(id, TvShowMethods.Videos, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task>> GetTvShowWatchProvidersAsync(int id, CancellationToken cancellationToken = default(CancellationToken)) + public async Task>> GetTvShowWatchProvidersAsync(int id, CancellationToken cancellationToken = default) { - return await GetTvShowMethod>>(id, TvShowMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false); + return await GetTvShowMethodInternal>>(id, TvShowMethods.WatchProviders, cancellationToken: cancellationToken).ConfigureAwait(false); } - public async Task TvShowRemoveRatingAsync(int tvShowId, CancellationToken cancellationToken = default(CancellationToken)) + public async Task TvShowRemoveRatingAsync(int tvShowId, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -323,7 +323,7 @@ namespace TMDbLib.Client req.AddUrlSegment("tvShowId", tvShowId.ToString(CultureInfo.InvariantCulture)); AddSessionId(req); - RestResponse response = await req.ExecuteDelete(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Delete(cancellationToken).ConfigureAwait(false); // status code 13 = "The item/record was deleted successfully." PostReply item = await response.GetDataObject().ConfigureAwait(false); @@ -341,7 +341,7 @@ namespace TMDbLib.Client /// True if the the tv show's rating was successfully updated, false if not /// Requires a valid guest or user session /// Thrown when the current client object doens't have a guest or user session assigned. - public async Task TvShowSetRatingAsync(int tvShowId, double rating, CancellationToken cancellationToken = default(CancellationToken)) + public async Task TvShowSetRatingAsync(int tvShowId, double rating, CancellationToken cancellationToken = default) { RequireSessionId(SessionType.GuestSession); @@ -351,7 +351,7 @@ namespace TMDbLib.Client req.SetBody(new { value = rating }); - RestResponse response = await req.ExecutePost(cancellationToken).ConfigureAwait(false); + RestResponse response = await req.Post(cancellationToken).ConfigureAwait(false); // status code 1 = "Success" // status code 12 = "The item/record was updated successfully" - Used when an item was previously rated by the user diff --git a/TMDbLib/Objects/Account/AccountMovieSortBy.cs b/TMDbLib/Objects/Account/AccountSortBy.cs similarity index 100% rename from TMDbLib/Objects/Account/AccountMovieSortBy.cs rename to TMDbLib/Objects/Account/AccountSortBy.cs diff --git a/TMDbLib/Objects/Discover/DiscoverBase.cs b/TMDbLib/Objects/Discover/DiscoverBase.cs index 535a80f..eebabd8 100644 --- a/TMDbLib/Objects/Discover/DiscoverBase.cs +++ b/TMDbLib/Objects/Discover/DiscoverBase.cs @@ -19,12 +19,12 @@ namespace TMDbLib.Objects.Discover Parameters = new SimpleNamedValueCollection(); } - public async Task> Query(int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> Query(int page = 0, CancellationToken cancellationToken = default) { return await Query(_client.DefaultLanguage, page, cancellationToken).ConfigureAwait(false); } - public async Task> Query(string language, int page = 0, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> Query(string language, int page = 0, CancellationToken cancellationToken = default) { return await _client.DiscoverPerformAsync(_endpoint, language, page, Parameters, cancellationToken).ConfigureAwait(false); } diff --git a/TMDbLib/Objects/Discover/DiscoverMovieSortBy.cs b/TMDbLib/Objects/Discover/DiscoverMovieSortBy.cs index 84f776b..39cff7a 100644 --- a/TMDbLib/Objects/Discover/DiscoverMovieSortBy.cs +++ b/TMDbLib/Objects/Discover/DiscoverMovieSortBy.cs @@ -1,11 +1,9 @@ -using System; -using TMDbLib.Utilities; +using TMDbLib.Utilities; namespace TMDbLib.Objects.Discover { public enum DiscoverMovieSortBy { - [Obsolete] Undefined, [EnumValue("popularity.asc")] Popularity, diff --git a/TMDbLib/Objects/Discover/DiscoverTvShowSortBy.cs b/TMDbLib/Objects/Discover/DiscoverTvShowSortBy.cs index 3d3afca..c93059c 100644 --- a/TMDbLib/Objects/Discover/DiscoverTvShowSortBy.cs +++ b/TMDbLib/Objects/Discover/DiscoverTvShowSortBy.cs @@ -1,11 +1,9 @@ -using System; -using TMDbLib.Utilities; +using TMDbLib.Utilities; namespace TMDbLib.Objects.Discover { public enum DiscoverTvShowSortBy { - [Obsolete] Undefined, [EnumValue("vote_average.asc")] VoteAverage, diff --git a/TMDbLib/Objects/Lists/AccountList.cs b/TMDbLib/Objects/Lists/AccountList.cs index 962909e..1595c39 100644 --- a/TMDbLib/Objects/Lists/AccountList.cs +++ b/TMDbLib/Objects/Lists/AccountList.cs @@ -3,7 +3,7 @@ using TMDbLib.Objects.General; namespace TMDbLib.Objects.Lists { - public class AccountList : List + public class AccountList : TMDbList { [JsonProperty("list_type")] public MediaType ListType { get; set; } diff --git a/TMDbLib/Objects/Lists/GenericList.cs b/TMDbLib/Objects/Lists/GenericList.cs index 8ff6ff5..772ec4d 100644 --- a/TMDbLib/Objects/Lists/GenericList.cs +++ b/TMDbLib/Objects/Lists/GenericList.cs @@ -4,7 +4,7 @@ using TMDbLib.Objects.Search; namespace TMDbLib.Objects.Lists { - public class GenericList : List + public class GenericList : TMDbList { [JsonProperty("created_by")] public string CreatedBy { get; set; } diff --git a/TMDbLib/Objects/Lists/List.cs b/TMDbLib/Objects/Lists/TMDbList.cs similarity index 89% rename from TMDbLib/Objects/Lists/List.cs rename to TMDbLib/Objects/Lists/TMDbList.cs index e527416..cf60f96 100644 --- a/TMDbLib/Objects/Lists/List.cs +++ b/TMDbLib/Objects/Lists/TMDbList.cs @@ -2,7 +2,7 @@ namespace TMDbLib.Objects.Lists { - public class List + public abstract class TMDbList { [JsonProperty("description")] public string Description { get; set; } @@ -11,7 +11,7 @@ namespace TMDbLib.Objects.Lists public int FavoriteCount { get; set; } [JsonProperty("id")] - public string Id { get; set; } + public TId Id { get; set; } /// /// A language code, e.g. en diff --git a/TMDbLib/Objects/Movies/ListResult.cs b/TMDbLib/Objects/Movies/ListResult.cs index f92b1f0..abce722 100644 --- a/TMDbLib/Objects/Movies/ListResult.cs +++ b/TMDbLib/Objects/Movies/ListResult.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using TMDbLib.Objects.General; namespace TMDbLib.Objects.Movies { @@ -18,10 +19,13 @@ namespace TMDbLib.Objects.Movies /// [JsonProperty("iso_639_1")] public string Iso_639_1 { get; set; } - + [JsonProperty("item_Count")] public int ItemCount { get; set; } + [JsonProperty("list_type")] + public MediaType ListType { get; set; } + [JsonProperty("name")] public string Name { get; set; } diff --git a/TMDbLib/Objects/Search/SearchPerson.cs b/TMDbLib/Objects/Search/SearchPerson.cs index 57dd325..75bc947 100644 --- a/TMDbLib/Objects/Search/SearchPerson.cs +++ b/TMDbLib/Objects/Search/SearchPerson.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using Newtonsoft.Json; using TMDbLib.Objects.General; -using TMDbLib.Objects.People; namespace TMDbLib.Objects.Search { diff --git a/TMDbLib/Objects/TvShows/TvEpisode.cs b/TMDbLib/Objects/TvShows/TvEpisode.cs index 9edecf5..c7c637f 100644 --- a/TMDbLib/Objects/TvShows/TvEpisode.cs +++ b/TMDbLib/Objects/TvShows/TvEpisode.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using Newtonsoft.Json; using TMDbLib.Objects.General; diff --git a/TMDbLib/Objects/TvShows/TvGroupEpisode.cs b/TMDbLib/Objects/TvShows/TvGroupEpisode.cs index 0805218..ddbfadf 100644 --- a/TMDbLib/Objects/TvShows/TvGroupEpisode.cs +++ b/TMDbLib/Objects/TvShows/TvGroupEpisode.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using Newtonsoft.Json; -using TMDbLib.Objects.General; +using Newtonsoft.Json; namespace TMDbLib.Objects.TvShows { diff --git a/TMDbLib/Objects/TvShows/TvGroupType.cs b/TMDbLib/Objects/TvShows/TvGroupType.cs index a8da717..6594b72 100644 --- a/TMDbLib/Objects/TvShows/TvGroupType.cs +++ b/TMDbLib/Objects/TvShows/TvGroupType.cs @@ -1,10 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; - -namespace TMDbLib.Objects.TvShows +namespace TMDbLib.Objects.TvShows { public enum TvGroupType { diff --git a/TMDbLib/Rest/RestRequest.cs b/TMDbLib/Rest/RestRequest.cs index 008f8e9..ec3e38c 100644 --- a/TMDbLib/Rest/RestRequest.cs +++ b/TMDbLib/Rest/RestRequest.cs @@ -86,42 +86,42 @@ namespace TMDbLib.Rest AppendQueryString(sb, value.Key, value.Value); } - public async Task ExecuteDelete(CancellationToken cancellationToken) + public async Task Delete(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Delete, cancellationToken).ConfigureAwait(false); return new RestResponse(resp); } - public async Task> ExecuteDelete(CancellationToken cancellationToken) + public async Task> Delete(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Delete, cancellationToken).ConfigureAwait(false); return new RestResponse(resp, _client); } - public async Task ExecuteGet(CancellationToken cancellationToken) + public async Task Get(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Get, cancellationToken).ConfigureAwait(false); return new RestResponse(resp); } - public async Task> ExecuteGet(CancellationToken cancellationToken) + public async Task> Get(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Get, cancellationToken).ConfigureAwait(false); return new RestResponse(resp, _client); } - public async Task ExecutePost(CancellationToken cancellationToken) + public async Task Post(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Post, cancellationToken).ConfigureAwait(false); return new RestResponse(resp); } - public async Task> ExecutePost(CancellationToken cancellationToken) + public async Task> Post(CancellationToken cancellationToken) { HttpResponseMessage resp = await SendInternal(HttpMethod.Post, cancellationToken).ConfigureAwait(false); diff --git a/TMDbLib/Rest/RestRequestExtensions.cs b/TMDbLib/Rest/RestRequestExtensions.cs new file mode 100644 index 0000000..066d0d6 --- /dev/null +++ b/TMDbLib/Rest/RestRequestExtensions.cs @@ -0,0 +1,38 @@ +using System.Threading; +using System.Threading.Tasks; + +namespace TMDbLib.Rest +{ + internal static class RestRequestExtensions + { + public static async Task DeleteOfT(this RestRequest request, CancellationToken cancellationToken) + { + RestResponse resp = await request.Delete(cancellationToken).ConfigureAwait(false); + + if (!resp.IsValid) + return default; + + return await resp.GetDataObject().ConfigureAwait(false); + } + + public static async Task GetOfT(this RestRequest request, CancellationToken cancellationToken) + { + RestResponse resp = await request.Get(cancellationToken).ConfigureAwait(false); + + if (!resp.IsValid) + return default; + + return await resp.GetDataObject().ConfigureAwait(false); + } + + public static async Task PostOfT(this RestRequest request, CancellationToken cancellationToken) + { + RestResponse resp = await request.Post(cancellationToken).ConfigureAwait(false); + + if (!resp.IsValid) + return default; + + return await resp.GetDataObject().ConfigureAwait(false); + } + } +} \ No newline at end of file diff --git a/TMDbLib/Rest/RestResponse.cs b/TMDbLib/Rest/RestResponse.cs index 6b555af..35d52dd 100644 --- a/TMDbLib/Rest/RestResponse.cs +++ b/TMDbLib/Rest/RestResponse.cs @@ -1,4 +1,3 @@ -using System; using System.IO; using System.Linq; using System.Net; @@ -50,20 +49,5 @@ namespace TMDbLib.Rest using (JsonTextReader tr = new JsonTextReader(sr)) return _client.Serializer.Deserialize(tr); } - - public static implicit operator T(RestResponse response) - { - try - { - if (response.IsValid) - return response.GetDataObject().Result; - - return default(T); - } - catch (AggregateException ex) - { - throw ex.InnerException; - } - } } } \ No newline at end of file diff --git a/TMDbLib/Utilities/Converters/TmdbIntArrayAsObjectConverter.cs b/TMDbLib/Utilities/Converters/TmdbIntArrayAsObjectConverter.cs index 47620ab..bbd50d2 100644 --- a/TMDbLib/Utilities/Converters/TmdbIntArrayAsObjectConverter.cs +++ b/TMDbLib/Utilities/Converters/TmdbIntArrayAsObjectConverter.cs @@ -33,6 +33,9 @@ namespace TMDbLib.Utilities.Converters return new List(); } + if (reader.TokenType == JsonToken.Null) + return null; + throw new Exception("Unable to convert list of integers"); } diff --git a/TMDbLib/Utilities/Converters/TmdbPartialDateConverter.cs b/TMDbLib/Utilities/Converters/TmdbPartialDateConverter.cs index db0101b..494fae7 100644 --- a/TMDbLib/Utilities/Converters/TmdbPartialDateConverter.cs +++ b/TMDbLib/Utilities/Converters/TmdbPartialDateConverter.cs @@ -26,7 +26,7 @@ namespace TMDbLib.Utilities.Converters public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { - var date = value as DateTime?; + DateTime? date = value as DateTime?; writer.WriteValue(date?.ToString(CultureInfo.InvariantCulture)); } } diff --git a/TMDbLib/Utilities/EnumMemberCache.cs b/TMDbLib/Utilities/EnumMemberCache.cs index cb320c6..e1cf4e4 100644 --- a/TMDbLib/Utilities/EnumMemberCache.cs +++ b/TMDbLib/Utilities/EnumMemberCache.cs @@ -65,7 +65,7 @@ namespace TMDbLib.Utilities } } - return default(T); + return default; } public static object GetValue(string input, Type type) diff --git a/TMDbLibTests/ClientAccountTests.cs b/TMDbLibTests/ClientAccountTests.cs index a31f92b..b9a326d 100644 --- a/TMDbLibTests/ClientAccountTests.cs +++ b/TMDbLibTests/ClientAccountTests.cs @@ -1,8 +1,8 @@ -using System; +using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Xunit; -using TMDbLib.Objects.Account; using TMDbLib.Objects.Authentication; using TMDbLib.Objects.General; using TMDbLib.Objects.Lists; @@ -15,375 +15,267 @@ namespace TMDbLibTests { public class ClientAccountTests : TestBase { - public ClientAccountTests() : base() + public ClientAccountTests() { - if (string.IsNullOrWhiteSpace(Config.UserSessionId)) + if (string.IsNullOrWhiteSpace(TestConfig.UserSessionId)) throw new ConfigurationErrorsException("To successfully complete the ClientAccountTests you will need to specify a valid 'UserSessionId' in the test config file"); } [Fact] - public void TestAccountGetDetailsGuestAccount() + public async Task TestAccountGetDetailsGuestAccount() { - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.GuestTestSessionId, SessionType.GuestSession); - Assert.Throws(() => Config.Client.AccountGetDetailsAsync().Sync()); + await Assert.ThrowsAsync(() => TMDbClient.AccountGetDetailsAsync()); } [Fact] - public void TestAccountGetDetailsUserAccount() + public async Task TestAccountGetDetailsUserAccount() { - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - AccountDetails account = Config.Client.AccountGetDetailsAsync().Sync(); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - // Naturally the specified account must have these values populated for the test to pass - Assert.NotNull(account); - Assert.True(account.Id > 1); - Assert.Equal("Test Name", account.Name); - Assert.Equal("TMDbTestAccount", account.Username); - Assert.Equal("BE", account.Iso_3166_1); - Assert.Equal("en", account.Iso_639_1); - - Assert.NotNull(account.Avatar); - Assert.NotNull(account.Avatar.Gravatar); - Assert.Equal("7cf5357dbc2014cbd616257c358ea0a1", account.Avatar.Gravatar.Hash); + await Verify(TMDbClient.ActiveAccount); } [Fact] - public void TestAccountAccountGetLists() + public async Task TestAccountAccountGetLists() { - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetListsAsync(i).Result); - AccountList list = Config.Client.AccountGetListsAsync().Sync().Results[0]; + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Assert.NotNull(list.Id); - Assert.NotNull(list.Name); - Assert.Null(list.PosterPath); - Assert.NotNull(list.Description); - Assert.NotNull(list.ListType); - Assert.NotNull(list.Iso_639_1); + SearchContainer result = await TMDbClient.AccountGetListsAsync(); + + Assert.NotEmpty(result.Results); + + AccountList single = result.Results.Single(s => s.Id == 1724); + + await Verify(single); + } + + [Fact(Skip = "TMDb has an issue in pagination of AccountGetListsAsync")] + public async Task TestAccountAccountGetListsPaged() + { + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); + + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetListsAsync(i)); } [Fact] - public void TestAccountGetFavoriteMovies() + public async Task TestAccountGetFavoriteMovies() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetFavoriteMoviesAsync(i).Result); - SearchMovie movie = Config.Client.AccountGetFavoriteMoviesAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetFavoriteMoviesAsync(i)); // Requires that you have marked at least one movie as favorite else this test will fail - Assert.True(movie.Id > 0); - Assert.NotNull(movie.Title); - Assert.NotNull(movie.PosterPath); - Assert.NotNull(movie.BackdropPath); - Assert.NotNull(movie.OriginalTitle); - Assert.NotNull(movie.Overview); - Assert.NotNull(movie.OriginalLanguage); - Assert.NotNull(movie.ReleaseDate); - Assert.True(movie.VoteCount > 0); - Assert.True(movie.VoteAverage > 0); - Assert.True(movie.Popularity > 0); + SearchContainer movies = await TMDbClient.AccountGetFavoriteMoviesAsync(); + SearchMovie movie = movies.Results.Single(s => s.Id == IdHelper.Avatar); - Assert.NotNull(movie.GenreIds); - Assert.True(movie.GenreIds.Any()); + await Verify(movie, x => x.IgnoreProperty(n => n.VoteCount, n => n.Popularity)); } [Fact] - public void TestAccountGetFavoriteTv() + public async Task TestAccountGetFavoriteTv() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetFavoriteTvAsync(i).Result); - SearchTv tvShow = Config.Client.AccountGetFavoriteTvAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetFavoriteTvAsync(i)); - // Requires that you have marked at least one movie as favorite else this test will fail - Assert.True(tvShow.Id > 0); - Assert.NotNull(tvShow.Name); - Assert.NotNull(tvShow.PosterPath); - Assert.NotNull(tvShow.BackdropPath); - Assert.NotNull(tvShow.OriginalName); - Assert.NotNull(tvShow.Overview); - Assert.NotNull(tvShow.OriginalLanguage); - Assert.NotNull(tvShow.FirstAirDate); - Assert.True(tvShow.VoteCount > 0); - Assert.True(tvShow.VoteAverage > 0); - Assert.True(tvShow.Popularity > 0); + SearchContainer tvShows = await TMDbClient.AccountGetFavoriteTvAsync(); + SearchTv tvShow = tvShows.Results.Single(s => s.Id == IdHelper.BreakingBad); - Assert.NotNull(tvShow.GenreIds); - Assert.True(tvShow.GenreIds.Any()); + await Verify(tvShow); } [Fact] - public void TestAccountGetMovieWatchlist() + public async Task TestAccountGetMovieWatchlist() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetFavoriteMoviesAsync(i).Result); - SearchMovie movie = Config.Client.AccountGetFavoriteMoviesAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetMovieWatchlistAsync(i)); - // Requires that you have added at least one movie to your watchlist else this test will fail - Assert.True(movie.Id > 0); - Assert.NotNull(movie.Title); - Assert.NotNull(movie.PosterPath); - Assert.NotNull(movie.BackdropPath); - Assert.NotNull(movie.OriginalTitle); - Assert.NotNull(movie.Overview); - Assert.NotNull(movie.OriginalLanguage); - Assert.NotNull(movie.ReleaseDate); - Assert.True(movie.VoteCount > 0); - Assert.True(movie.VoteAverage > 0); - Assert.True(movie.Popularity > 0); + SearchContainer watchlist = await TMDbClient.AccountGetMovieWatchlistAsync(); + SearchMovie movie = watchlist.Results.Single(s => s.Id == 100042); - Assert.NotNull(movie.GenreIds); - Assert.True(movie.GenreIds.Any()); + await Verify(movie); } [Fact] - public void TestAccountGetTvWatchlist() + public async Task TestAccountGetTvWatchlist() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetTvWatchlistAsync(i).Result); - SearchTv tvShow = Config.Client.AccountGetTvWatchlistAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetTvWatchlistAsync(i)); - // Requires that you have added at least one movie to your watchlist else this test will fail - Assert.True(tvShow.Id > 0); - Assert.NotNull(tvShow.Name); - Assert.NotNull(tvShow.PosterPath); - Assert.NotNull(tvShow.BackdropPath); - Assert.NotNull(tvShow.OriginalName); - Assert.NotNull(tvShow.Overview); - Assert.NotNull(tvShow.OriginalLanguage); - Assert.NotNull(tvShow.FirstAirDate); - Assert.True(tvShow.VoteCount > 0); - Assert.True(tvShow.VoteAverage > 0); - Assert.True(tvShow.Popularity > 0); + SearchContainer tvShows = await TMDbClient.AccountGetTvWatchlistAsync(); + SearchTv tvShow = tvShows.Results.Single(s => s.Id == 2691); - Assert.NotNull(tvShow.GenreIds); - Assert.True(tvShow.GenreIds.Any()); + await Verify(tvShow); } [Fact] - public void TestAccountGetRatedMovies() + public async Task TestAccountGetRatedMovies() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetFavoriteMoviesAsync(i).Result); - SearchMovie movie = Config.Client.AccountGetFavoriteMoviesAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetFavoriteMoviesAsync(i)); - // Requires that you have rated at least one movie else this test will fail - Assert.True(movie.Id > 0); - Assert.NotNull(movie.Title); - Assert.NotNull(movie.PosterPath); - Assert.NotNull(movie.BackdropPath); - Assert.NotNull(movie.OriginalTitle); - Assert.NotNull(movie.Overview); - Assert.NotNull(movie.OriginalLanguage); - Assert.NotNull(movie.ReleaseDate); - Assert.True(movie.VoteCount > 0); - Assert.True(movie.VoteAverage > 0); - Assert.True(movie.Popularity > 0); + SearchContainer movies = await TMDbClient.AccountGetFavoriteMoviesAsync(); + SearchMovie movie = movies.Results.Single(s => s.Id == IdHelper.Avatar); - Assert.NotNull(movie.GenreIds); - Assert.True(movie.GenreIds.Any()); + await Verify(movie); } [Fact] - public void TestAccountGetRatedTv() + public async Task TestAccountGetRatedTv() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetRatedTvShowsAsync(i).Result); - AccountSearchTv tvShow = Config.Client.AccountGetRatedTvShowsAsync().Sync().Results[0]; + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetRatedTvShowsAsync(i)); - // Requires that you have rated at least one movie else this test will fail - Assert.True(tvShow.Id > 0); - Assert.NotNull(tvShow.Name); - Assert.NotNull(tvShow.PosterPath); - Assert.NotNull(tvShow.BackdropPath); - Assert.NotNull(tvShow.OriginalName); - Assert.NotNull(tvShow.Overview); - Assert.NotNull(tvShow.OriginalLanguage); - Assert.NotNull(tvShow.FirstAirDate); - Assert.True(tvShow.VoteCount > 0); - Assert.True(tvShow.VoteAverage > 0); - Assert.True(tvShow.Popularity > 0); + SearchContainer tvShows = await TMDbClient.AccountGetRatedTvShowsAsync(); + AccountSearchTv tvShow = tvShows.Results.Single(s => s.Id == IdHelper.BigBangTheory); - Assert.NotNull(tvShow.GenreIds); - Assert.True(tvShow.GenreIds.Any()); + await Verify(tvShow); } [Fact] - public void TestAccountGetRatedTvEpisodes() + public async Task TestAccountGetRatedTvEpisodes() { - IgnoreMissingCSharp("results[array]._id / _id"); - // TODO: Error in TMDb: https://www.themoviedb.org/talk/557f1af49251410a2c002480 - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestHelpers.SearchPages(i => Config.Client.AccountGetRatedTvShowEpisodesAsync(i).Result); - AccountSearchTvEpisode tvEpisode = Config.Client.AccountGetRatedTvShowEpisodesAsync().Sync().Results[0]; + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - // Requires that you have rated at least one movie else this test will fail - Assert.True(tvEpisode.Id > 0); - Assert.True(tvEpisode.ShowId > 0); - Assert.True(tvEpisode.EpisodeNumber > 0); - Assert.True(tvEpisode.SeasonNumber > 0); - Assert.NotNull(tvEpisode.Name); - Assert.NotNull(tvEpisode.AirDate); - Assert.NotNull(tvEpisode.StillPath); - Assert.True(tvEpisode.VoteCount > 0); - Assert.True(tvEpisode.VoteAverage > 0); - Assert.True(tvEpisode.Rating > 0); + await TestHelpers.SearchPagesAsync(i => TMDbClient.AccountGetRatedTvShowEpisodesAsync(i)); + + SearchContainer tvEpisodes = await TMDbClient.AccountGetRatedTvShowEpisodesAsync(); + AccountSearchTvEpisode tvEpisode = tvEpisodes.Results.Single(s => s.Id == IdHelper.BreakingBadSeason1Episode1Id); + + await Verify(tvEpisode); } [Fact] - public void TestAccountChangeTvFavoriteStatus() + public async Task TestAccountChangeTvFavoriteStatusAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); // Ensure that the test movie is not marked as favorite before we start the test - if (DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)) - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false).Result); + if (await DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)) + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false)); - if (DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)) + if (await DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)) throw new Exception($"Test tv show '{IdHelper.DoctorWho}' was already marked as favorite. Unable to perform test correctly"); // Try to mark is as a favorite - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, true).Result); + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, true)); // Check if it worked - Assert.True(DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)); + Assert.True(await DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)); // Try to un-mark is as a favorite - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false).Result); + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false)); // Check if it worked - Assert.False(DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)); + Assert.False(await DoesFavoriteListContainSpecificTvShow(IdHelper.DoctorWho)); } [Fact] - public void TestAccountChangeMovieFavoriteStatus() + public async Task TestAccountChangeMovieFavoriteStatusAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); // Ensure that the test movie is not marked as favorite before we start the test - if (DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)) - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, false).Result); + if (await DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)) + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, false)); - if (DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)) + if (await DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)) throw new Exception($"Test movie '{IdHelper.Terminator}' was already marked as favorite. Unable to perform test correctly"); // Try to mark is as a favorite - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, true).Result); + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, true)); // Check if it worked - Assert.True(DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)); + Assert.True(await DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)); // Try to un-mark is as a favorite - Assert.True(Config.Client.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, false).Result); + Assert.True(await TMDbClient.AccountChangeFavoriteStatusAsync(MediaType.Movie, IdHelper.Terminator, false)); // Check if it worked - Assert.False(DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)); + Assert.False(await DoesFavoriteListContainSpecificMovie(IdHelper.Terminator)); } [Fact] - public void TestAccountChangeTvWatchlistStatus() + public async Task TestAccountChangeTvWatchlistStatusAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); // Ensure that the test movie is not marked as favorite before we start the test - if (DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)) - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false).Result); + if (await DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)) + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false)); - if (DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)) + if (await DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)) throw new Exception($"Test tv show '{IdHelper.DoctorWho}' was already on watchlist. Unable to perform test correctly"); // Try to add an item to the watchlist - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, true).Result); + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, true)); // Check if it worked - Assert.True(DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)); + Assert.True(await DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)); // Try to remove item from watchlist - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false).Result); + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Tv, IdHelper.DoctorWho, false)); // Check if it worked - Assert.False(DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)); + Assert.False(await DoesWatchListContainSpecificTvShow(IdHelper.DoctorWho)); } [Fact] - public void TestAccountChangeMovieWatchlistStatus() + public async Task TestAccountChangeMovieWatchlistStatusAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); // Ensure that the test movie is not marked as favorite before we start the test - if (DoesWatchListContainSpecificMovie(IdHelper.Terminator)) - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, false).Result); + if (await DoesWatchListContainSpecificMovie(IdHelper.Terminator)) + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, false)); - if (DoesWatchListContainSpecificMovie(IdHelper.Terminator)) + if (await DoesWatchListContainSpecificMovie(IdHelper.Terminator)) throw new Exception($"Test movie '{IdHelper.Terminator}' was already on watchlist. Unable to perform test correctly"); // Try to add an item to the watchlist - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, true).Result); + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, true)); // Check if it worked - Assert.True(DoesWatchListContainSpecificMovie(IdHelper.Terminator)); + Assert.True(await DoesWatchListContainSpecificMovie(IdHelper.Terminator)); // Try to remove item from watchlist - Assert.True(Config.Client.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, false).Result); + Assert.True(await TMDbClient.AccountChangeWatchlistStatusAsync(MediaType.Movie, IdHelper.Terminator, false)); // Check if it worked - Assert.False(DoesWatchListContainSpecificMovie(IdHelper.Terminator)); + Assert.False(await DoesWatchListContainSpecificMovie(IdHelper.Terminator)); } - private bool DoesFavoriteListContainSpecificTvShow(int tvId) + private async Task DoesFavoriteListContainSpecificTvShow(int tvId) { - return DoesListContainSpecificMovie(tvId, page => Config.Client.AccountGetFavoriteTvAsync(page).Result.Results.Select(s => s.Id)); + return await DoesListContainSpecificMovie(tvId, async page => (await TMDbClient.AccountGetFavoriteTvAsync(page)).Results.Select(s => s.Id)); } - private bool DoesWatchListContainSpecificTvShow(int tvId) + private async Task DoesWatchListContainSpecificTvShow(int tvId) { - return DoesListContainSpecificMovie(tvId, page => Config.Client.AccountGetTvWatchlistAsync(page).Result.Results.Select(s => s.Id)); + return await DoesListContainSpecificMovie(tvId, async page => (await TMDbClient.AccountGetTvWatchlistAsync(page)).Results.Select(s => s.Id)); } - private bool DoesFavoriteListContainSpecificMovie(int movieId) + private async Task DoesFavoriteListContainSpecificMovie(int movieId) { - return DoesListContainSpecificMovie(movieId, page => Config.Client.AccountGetFavoriteMoviesAsync(page).Result.Results.Select(s => s.Id)); + return await DoesListContainSpecificMovie(movieId, async page => (await TMDbClient.AccountGetFavoriteMoviesAsync(page)).Results.Select(s => s.Id)); } - private bool DoesWatchListContainSpecificMovie(int movieId) + private async Task DoesWatchListContainSpecificMovie(int movieId) { - return DoesListContainSpecificMovie(movieId, page => Config.Client.AccountGetMovieWatchlistAsync(page).Result.Results.Select(s => s.Id)); + return await DoesListContainSpecificMovie(movieId, async page => (await TMDbClient.AccountGetMovieWatchlistAsync(page)).Results.Select(s => s.Id)); } - private bool DoesListContainSpecificMovie(int movieId, Func> listGetter) + private async Task DoesListContainSpecificMovie(int movieId, Func>> listGetter) { int page = 1; - List originalList = listGetter(1).ToList(); + List originalList = (await listGetter(page)).ToList(); while (originalList != null && originalList.Any()) { // Check if the current result page contains the relevant movie @@ -391,7 +283,7 @@ namespace TMDbLibTests return true; // See if there is an other page we could try, if not the test passes - originalList = originalList.Any() ? listGetter(++page).ToList() : null; + originalList = originalList.Any() ? (await listGetter(++page)).ToList() : null; } return false; } diff --git a/TMDbLibTests/ClientAuthenticationTests.cs b/TMDbLibTests/ClientAuthenticationTests.cs index da203e8..279ec4f 100644 --- a/TMDbLibTests/ClientAuthenticationTests.cs +++ b/TMDbLibTests/ClientAuthenticationTests.cs @@ -1,8 +1,8 @@ using System; +using System.Threading.Tasks; using TMDbLibTests.Exceptions; using Xunit; using TMDbLib.Objects.Authentication; -using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; namespace TMDbLibTests @@ -14,19 +14,18 @@ namespace TMDbLibTests { public ClientAuthenticationTests() { - if (string.IsNullOrWhiteSpace(Config.Username) || string.IsNullOrWhiteSpace(Config.Password)) + if (string.IsNullOrWhiteSpace(TestConfig.Username) || string.IsNullOrWhiteSpace(TestConfig.Password)) throw new ConfigurationErrorsException("You need to provide a username and password or some tests won't be able to execute."); } [Fact] - public void TestAuthenticationRequestNewToken() + public async Task TestAuthenticationRequestNewToken() { - Token token = Config.Client.AuthenticationRequestAutenticationTokenAsync().Sync(); + Token token = await TMDbClient.AuthenticationRequestAutenticationTokenAsync(); Assert.NotNull(token); Assert.True(token.Success); Assert.NotNull(token.AuthenticationCallback); - Assert.NotNull(token.ExpiresAt); Assert.NotNull(token.RequestToken); } @@ -49,39 +48,39 @@ namespace TMDbLibTests //} [Fact] - public void TestAuthenticationUserAuthenticatedSessionInvalidToken() + public async Task TestAuthenticationUserAuthenticatedSessionInvalidTokenAsync() { const string requestToken = "bla"; - Assert.Throws(() => Config.Client.AuthenticationGetUserSessionAsync(requestToken).Sync()); + await Assert.ThrowsAsync(() => TMDbClient.AuthenticationGetUserSessionAsync(requestToken)); } /// /// Requires a valid test user to be assigned /// [Fact] - public void TestAuthenticationGetUserSessionApiUserValidationSuccess() + public async Task TestAuthenticationGetUserSessionApiUserValidationSuccessAsync() { - Token token = Config.Client.AuthenticationRequestAutenticationTokenAsync().Sync(); + Token token = await TMDbClient.AuthenticationRequestAutenticationTokenAsync(); - Config.Client.AuthenticationValidateUserTokenAsync(token.RequestToken, Config.Username, Config.Password).Sync(); + await TMDbClient.AuthenticationValidateUserTokenAsync(token.RequestToken, TestConfig.Username, TestConfig.Password); } [Fact] - public void TestAuthenticationGetUserSessionApiUserValidationInvalidLogin() + public async Task TestAuthenticationGetUserSessionApiUserValidationInvalidLoginAsync() { - Token token = Config.Client.AuthenticationRequestAutenticationTokenAsync().Sync(); + Token token = await TMDbClient.AuthenticationRequestAutenticationTokenAsync(); - Assert.Throws(() => Config.Client.AuthenticationValidateUserTokenAsync(token.RequestToken, "bla", "bla").Sync()); + await Assert.ThrowsAsync(() => TMDbClient.AuthenticationValidateUserTokenAsync(token.RequestToken, "bla", "bla")); } /// /// Requires a valid test user to be assigned /// [Fact] - public void AuthenticationGetUserSessionWithLoginSuccess() + public async Task AuthenticationGetUserSessionWithLoginSuccess() { - UserSession session = Config.Client.AuthenticationGetUserSessionAsync(Config.Username, Config.Password).Result; + UserSession session = await TMDbClient.AuthenticationGetUserSessionAsync(TestConfig.Username, TestConfig.Password); Assert.NotNull(session); Assert.True(session.Success); @@ -89,21 +88,20 @@ namespace TMDbLibTests } [Fact] - public void TestAuthenticationUserAuthenticatedSessionOldToken() + public async Task TestAuthenticationUserAuthenticatedSessionOldTokenAsync() { const string requestToken = "5f3a62c0d7977319e3d14adf1a2064c0c0938bcf"; - Assert.Throws(() => Config.Client.AuthenticationGetUserSessionAsync(requestToken).Sync()); + await Assert.ThrowsAsync(() => TMDbClient.AuthenticationGetUserSessionAsync(requestToken)); } [Fact] - public void TestAuthenticationCreateGuestSession() + public async Task TestAuthenticationCreateGuestSessionAsync() { - GuestSession guestSession = Config.Client.AuthenticationCreateGuestSessionAsync().Sync(); + GuestSession guestSession = await TMDbClient.AuthenticationCreateGuestSessionAsync(); Assert.NotNull(guestSession); Assert.True(guestSession.Success); - Assert.NotNull(guestSession.ExpiresAt); Assert.NotNull(guestSession.GuestSessionId); } } diff --git a/TMDbLibTests/ClientCertificationsTests.cs b/TMDbLibTests/ClientCertificationsTests.cs index ffccfc2..36e2360 100644 --- a/TMDbLibTests/ClientCertificationsTests.cs +++ b/TMDbLibTests/ClientCertificationsTests.cs @@ -1,8 +1,8 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Certifications; -using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; namespace TMDbLibTests @@ -10,43 +10,31 @@ namespace TMDbLibTests public class ClientCertificationsTests : TestBase { [Fact] - public void TestCertificationsListMovie() + public async Task TestCertificationsListMovieAsync() { - CertificationsContainer result = Config.Client.GetMovieCertificationsAsync().Sync(); - Assert.NotNull(result); - Assert.NotNull(result.Certifications); - Assert.True(result.Certifications.Count > 1); + CertificationsContainer result = await TMDbClient.GetMovieCertificationsAsync(); + Assert.NotEmpty(result.Certifications); List certAu = result.Certifications["AU"]; - Assert.NotNull(certAu); - Assert.True(certAu.Count > 2); + Assert.NotEmpty(certAu); CertificationItem ratingE = certAu.Single(s => s.Certification == "E"); - Assert.NotNull(ratingE); - Assert.Equal("E", ratingE.Certification); - Assert.Equal("Exempt from classification. Films that are exempt from classification must not contain contentious material (i.e. material that would ordinarily be rated M or higher).", ratingE.Meaning); - Assert.Equal(1, ratingE.Order); + await Verify(ratingE); } [Fact] - public void TestCertificationsListTv() + public async Task TestCertificationsListTvAsync() { - CertificationsContainer result = Config.Client.GetTvCertificationsAsync().Sync(); - Assert.NotNull(result); - Assert.NotNull(result.Certifications); - Assert.True(result.Certifications.Count > 1); + CertificationsContainer result = await TMDbClient.GetTvCertificationsAsync(); + Assert.NotEmpty(result.Certifications); List certUs = result.Certifications["US"]; - Assert.NotNull(certUs); - Assert.True(certUs.Count > 2); + Assert.NotEmpty(certUs); CertificationItem ratingNr = certUs.SingleOrDefault(s => s.Certification == "NR"); - - Assert.NotNull(ratingNr); - Assert.Equal("NR", ratingNr.Certification); - Assert.Equal("No rating information.", ratingNr.Meaning); - Assert.Equal(0, ratingNr.Order); + + await Verify(ratingNr); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientChangesTests.cs b/TMDbLibTests/ClientChangesTests.cs index e5e2d36..5c2bd7a 100644 --- a/TMDbLibTests/ClientChangesTests.cs +++ b/TMDbLibTests/ClientChangesTests.cs @@ -1,9 +1,9 @@ using System; using System.Linq; -using Xunit; +using System.Threading.Tasks; using TMDbLib.Objects.Changes; using TMDbLib.Objects.General; -using TMDbLibTests.Helpers; +using Xunit; using TMDbLibTests.JsonHelpers; namespace TMDbLibTests @@ -11,130 +11,42 @@ namespace TMDbLibTests public class ClientChangesTests : TestBase { [Fact] - public void TestChangesMovies() + public async Task TestChangesMoviesAsync() { - // Basic check - SearchContainer changesPage1 = Config.Client.GetChangesMoviesAsync().Sync(); + SearchContainer page1 = await TMDbClient.GetMoviesChangesAsync(1); + SearchContainer oldChanges = await TMDbClient.GetMoviesChangesAsync(endDate: DateTime.UtcNow.AddMonths(-1)); - Assert.NotNull(changesPage1); - Assert.True(changesPage1.Results.Count > 0); - Assert.True(changesPage1.TotalResults > changesPage1.Results.Count); - Assert.Equal(1, changesPage1.Page); + Assert.NotEmpty(page1.Results); + Assert.NotEmpty(oldChanges.Results); - // Page 2 - SearchContainer changesPage2 = Config.Client.GetChangesMoviesAsync(2).Result; - - Assert.NotNull(changesPage2); - Assert.Equal(2, changesPage2.Page); - - // Check date range (max) - DateTime higher = DateTime.UtcNow.AddDays(-7); - SearchContainer changesMaxDate = Config.Client.GetChangesMoviesAsync(endDate: higher).Result; - - Assert.NotNull(changesMaxDate); - Assert.Equal(1, changesMaxDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesMaxDate.TotalResults); - - // Check date range (lower) - DateTime lower = DateTime.UtcNow.AddDays(-6); // Use 6 days to avoid clashes with the 'higher' - SearchContainer changesLowDate = Config.Client.GetChangesMoviesAsync(startDate: lower).Result; - - Assert.NotNull(changesLowDate); - Assert.Equal(1, changesLowDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesLowDate.TotalResults); + // At least one item must be newer in page1 + Assert.Contains(page1.Results, x => oldChanges.Results.All(s => s.Id != x.Id)); } [Fact] - public void TestChangesPeople() + public async Task TestChangesPeopleAsync() { - // Basic check - SearchContainer changesPage1 = Config.Client.GetChangesPeopleAsync().Sync(); + SearchContainer page1 = await TMDbClient.GetPeopleChangesAsync(1); + SearchContainer oldChanges = await TMDbClient.GetPeopleChangesAsync(endDate: DateTime.UtcNow.AddMonths(-1)); - Assert.NotNull(changesPage1); - Assert.True(changesPage1.Results.Count > 0); - Assert.True(changesPage1.TotalResults > changesPage1.Results.Count); - Assert.Equal(1, changesPage1.Page); + Assert.NotEmpty(page1.Results); + Assert.NotEmpty(oldChanges.Results); - // Page 2 - SearchContainer changesPage2 = Config.Client.GetChangesPeopleAsync(2).Result; - - Assert.NotNull(changesPage2); - Assert.Equal(2, changesPage2.Page); - - // Check date range (max) - DateTime higher = DateTime.UtcNow.AddDays(-7); - SearchContainer changesMaxDate = Config.Client.GetChangesPeopleAsync(endDate: higher).Result; - - Assert.NotNull(changesMaxDate); - Assert.Equal(1, changesMaxDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesMaxDate.TotalResults); - - // Check date range (lower) - DateTime lower = DateTime.UtcNow.AddDays(-6); // Use 6 days to avoid clashes with the 'higher' - SearchContainer changesLowDate = Config.Client.GetChangesPeopleAsync(startDate: lower).Result; - - Assert.NotNull(changesLowDate); - Assert.Equal(1, changesLowDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesLowDate.TotalResults); - - // None of the id's in changesLowDate should exist in changesMaxDate, and vice versa - Assert.True(changesLowDate.Results.All(lowItem => changesMaxDate.Results.All(maxItem => maxItem.Id != lowItem.Id))); - Assert.True(changesMaxDate.Results.All(maxItem => changesLowDate.Results.All(lowItem => maxItem.Id != lowItem.Id))); + // At least one item must be newer in page1 + Assert.Contains(page1.Results, x => oldChanges.Results.All(s => s.Id != x.Id)); } - [Fact] - public void TestChangesTvShows() + public async Task TestChangesTvShowsAsync() { - // Basic check - SearchContainer changesPage1 = Config.Client.GetChangesTvAsync().Sync(); + SearchContainer page1 = await TMDbClient.GetTvChangesAsync(1); + SearchContainer oldChanges = await TMDbClient.GetTvChangesAsync(endDate: DateTime.UtcNow.AddMonths(-1)); - Assert.NotNull(changesPage1); - Assert.NotNull(changesPage1.Results); - Assert.True(changesPage1.Results.Count > 0); - Assert.True(changesPage1.TotalResults >= changesPage1.Results.Count); - Assert.Equal(1, changesPage1.Page); + Assert.NotEmpty(page1.Results); + Assert.NotEmpty(oldChanges.Results); - if (changesPage1.TotalPages > 1) - { - Assert.True(changesPage1.TotalResults > changesPage1.Results.Count); - // Page 2 - SearchContainer changesPage2 = Config.Client.GetChangesTvAsync(2).Result; - - Assert.NotNull(changesPage2); - Assert.Equal(2, changesPage2.Page); - } - - // Check date range (max) - DateTime higher = DateTime.UtcNow.AddDays(-8); - SearchContainer changesMaxDate = Config.Client.GetChangesTvAsync(endDate: higher).Result; - - Assert.NotNull(changesMaxDate); - Assert.Equal(1, changesMaxDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesMaxDate.TotalResults); - - // Check date range (lower) - DateTime lower = DateTime.UtcNow.AddDays(-6); // Use 6 days to avoid clashes with the 'higher' - SearchContainer changesLowDate = Config.Client.GetChangesTvAsync(startDate: lower).Result; - - Assert.NotNull(changesLowDate); - Assert.Equal(1, changesLowDate.Page); - Assert.NotEqual(changesPage1.TotalResults, changesLowDate.TotalResults); - - // None of the id's in changesLowDate should exist in changesMaxDate, and vice versa - foreach (ChangesListItem changeItem in changesLowDate.Results) - { - bool existsInOtherList = changesMaxDate.Results.Any(x => x.Id == changeItem.Id); - - Assert.False(existsInOtherList, "Item id " + changeItem.Id + " is duplicated"); - } - - foreach (ChangesListItem changeItem in changesMaxDate.Results) - { - bool existsInOtherList = changesLowDate.Results.Any(x => x.Id == changeItem.Id); - - Assert.False(existsInOtherList, "Item id " + changeItem.Id + " is duplicated"); - } + // At least one item must be newer in page1 + Assert.Contains(page1.Results, x => oldChanges.Results.All(s => s.Id != x.Id)); } } } diff --git a/TMDbLibTests/ClientCollectionTests.cs b/TMDbLibTests/ClientCollectionTests.cs index 7107c19..6f61812 100644 --- a/TMDbLibTests/ClientCollectionTests.cs +++ b/TMDbLibTests/ClientCollectionTests.cs @@ -1,6 +1,6 @@ using System; using System.Collections.Generic; -using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Collections; using TMDbLib.Objects.General; @@ -11,94 +11,60 @@ namespace TMDbLibTests { public class ClientCollectionTests : TestBase { - private static Dictionary> _methods; + private static readonly Dictionary> Methods; - public ClientCollectionTests() + static ClientCollectionTests() { - _methods = new Dictionary> + Methods = new Dictionary> { [CollectionMethods.Images] = collection => collection.Images }; } [Fact] - public void TestCollectionsExtrasNone() + public async Task TestCollectionsExtrasNone() { - // We will intentionally ignore errors reg. missing JSON as we do not request it - IgnoreMissingJson(" / images", "parts[array] / media_type"); - - Collection collection = Config.Client.GetCollectionAsync(IdHelper.JamesBondCollection).Result; - - Assert.NotNull(collection); - Assert.Equal("James Bond Collection", collection.Name); - Assert.NotNull(collection.Parts); - Assert.True(collection.Parts.Count > 0); + Collection collection = await TMDbClient.GetCollectionAsync(IdHelper.BackToTheFutureCollection); // Test all extras, ensure none of them exist - foreach (Func selector in _methods.Values) - { + foreach (Func selector in Methods.Values) Assert.Null(selector(collection)); - } } [Fact] - public void TestCollectionMissing() + public async Task TestCollectionMissing() { - Collection collection = Config.Client.GetCollectionAsync(IdHelper.MissingID).Result; + Collection collection = await TMDbClient.GetCollectionAsync(IdHelper.MissingID); Assert.Null(collection); } [Fact] - public void TestCollectionsParts() + public async Task TestCollectionsParts() { - // We will intentionally ignore errors reg. missing JSON as we do not request it - IgnoreMissingJson(" / images", "parts[array] / media_type"); + Collection collection = await TMDbClient.GetCollectionAsync(IdHelper.BackToTheFutureCollection); - Collection collection = Config.Client.GetCollectionAsync(IdHelper.JamesBondCollection).Result; - - Assert.NotNull(collection); - Assert.Equal("James Bond Collection", collection.Name); - - Assert.NotNull(collection.Parts); - Assert.True(collection.Parts.Count > 0); - - Assert.Contains(collection.Parts, movie => movie.Title == "Live and Let Die"); - Assert.Contains(collection.Parts, movie => movie.Title == "Dr. No"); + await Verify(collection); } [Fact] - public void TestCollectionsExtrasExclusive() + public async Task TestCollectionsExtrasExclusive() { - // Ignore missing json - IgnoreMissingJson("parts[array] / media_type"); - - TestMethodsHelper.TestGetExclusive(_methods, (id, extras) => Config.Client.GetCollectionAsync(id, extras).Result, IdHelper.JamesBondCollection); + await TestMethodsHelper.TestGetExclusive(Methods, extras => TMDbClient.GetCollectionAsync(IdHelper.BackToTheFutureCollection, extras)); } [Fact] - public void TestCollectionsExtrasAll() + public async Task TestCollectionsExtrasAll() { - // Ignore missing json - IgnoreMissingJson("parts[array] / media_type"); - - CollectionMethods combinedEnum = _methods.Keys.Aggregate((methods, movieMethods) => methods | movieMethods); - Collection item = Config.Client.GetCollectionAsync(IdHelper.JamesBondCollection, combinedEnum).Result; - - TestMethodsHelper.TestAllNotNull(_methods, item); + await TestMethodsHelper.TestGetAll(Methods, combined => TMDbClient.GetCollectionAsync(IdHelper.BackToTheFutureCollection, combined), async collection => await Verify(collection)); } [Fact] - public void TestCollectionsImages() + public async Task TestCollectionsImagesAsync() { - // Get config - Config.Client.GetConfigAsync().Sync(); + ImagesWithId images = await TMDbClient.GetCollectionImagesAsync(IdHelper.BackToTheFutureCollection); - // Test image url generator - ImagesWithId images = Config.Client.GetCollectionImagesAsync(IdHelper.JamesBondCollection).Result; - - Assert.Equal(IdHelper.JamesBondCollection, images.Id); - TestImagesHelpers.TestImages(Config, images); + TestImagesHelpers.TestImagePaths(images); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientCompanyTests.cs b/TMDbLibTests/ClientCompanyTests.cs index 0a4b0e9..71a8d2c 100644 --- a/TMDbLibTests/ClientCompanyTests.cs +++ b/TMDbLibTests/ClientCompanyTests.cs @@ -1,6 +1,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Companies; using TMDbLib.Objects.General; @@ -12,83 +13,65 @@ namespace TMDbLibTests { public class ClientCompanyTests : TestBase { - private static Dictionary> _methods; + private static readonly Dictionary> Methods; - public ClientCompanyTests() + static ClientCompanyTests() { - _methods = new Dictionary> + Methods = new Dictionary> { [CompanyMethods.Movies] = company => company.Movies }; } [Fact] - public void TestCompaniesExtrasNone() + public async Task TestCompaniesExtrasNoneAsync() { - // We will intentionally ignore errors reg. missing JSON as we do not request it - IgnoreMissingJson(" / movies"); - - Company company = Config.Client.GetCompanyAsync(IdHelper.TwentiethCenturyFox).Result; - - Assert.NotNull(company); - - // TODO: Test all properties - Assert.Equal("20th Century Fox", company.Name); + Company company = await TMDbClient.GetCompanyAsync(IdHelper.TwentiethCenturyFox); // Test all extras, ensure none of them exist - foreach (Func selector in _methods.Values) + foreach (Func selector in Methods.Values) { Assert.Null(selector(company)); } } [Fact] - public void TestCompaniesExtrasExclusive() + public async Task TestCompaniesExtrasExclusive() { - // Ignore missing json - IgnoreMissingJson("movies.results[array] / media_type"); - - TestMethodsHelper.TestGetExclusive(_methods, (id, extras) => Config.Client.GetCompanyAsync(id, extras).Result, IdHelper.TwentiethCenturyFox); + await TestMethodsHelper.TestGetExclusive(Methods, extras => TMDbClient.GetCompanyAsync(IdHelper.TwentiethCenturyFox, extras)); } [Fact] - public void TestCompaniesExtrasAll() + public async Task TestCompaniesExtrasAllAsync() { - // Ignore missing json - IgnoreMissingJson("movies.results[array] / media_type"); + await TestMethodsHelper.TestGetAll(Methods, combined => TMDbClient.GetCompanyAsync(IdHelper.TwentiethCenturyFox, combined), async company => + { + // Reduce testdata + company.Movies.Results = company.Movies.Results.OrderBy(s => s.Id).Take(1).ToList(); - CompanyMethods combinedEnum = _methods.Keys.Aggregate((methods, movieMethods) => methods | movieMethods); - Company item = Config.Client.GetCompanyAsync(IdHelper.TwentiethCenturyFox, combinedEnum).Result; - - TestMethodsHelper.TestAllNotNull(_methods, item); + await Verify(company, settings => settings.IgnoreProperty(nameof(company.Movies.TotalPages), nameof(company.Movies.TotalResults))); + }); } [Fact] - public void TestCompanyMissing() + public async Task TestCompanyMissingAsync() { - Company company = Config.Client.GetCompanyAsync(IdHelper.MissingID).Result; + Company company = await TMDbClient.GetCompanyAsync(IdHelper.MissingID); Assert.Null(company); } [Fact] - public void TestCompaniesGetters() + public async Task TestCompaniesMoviesAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - //GetCompanyMoviesAsync(int id, string language, int page = -1) - SearchContainerWithId resp = Config.Client.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox).Result; - SearchContainerWithId respPage2 = Config.Client.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox, 2).Result; - SearchContainerWithId respItalian = Config.Client.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox, "it").Result; + SearchContainerWithId resp = await TMDbClient.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox); + SearchContainerWithId respPage2 = await TMDbClient.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox, 2); + SearchContainerWithId respItalian = await TMDbClient.GetCompanyMoviesAsync(IdHelper.TwentiethCenturyFox, "it"); - Assert.NotNull(resp); - Assert.NotNull(respPage2); - Assert.NotNull(respItalian); - - Assert.True(resp.Results.Count > 0); - Assert.True(respPage2.Results.Count > 0); - Assert.True(respItalian.Results.Count > 0); + Assert.NotEmpty(resp.Results); + Assert.NotEmpty(respPage2.Results); + Assert.NotEmpty(respItalian.Results); bool allTitlesIdentical = true; for (int index = 0; index < resp.Results.Count; index++) @@ -103,44 +86,22 @@ namespace TMDbLibTests } [Fact] - public void TestCompaniesImages() + public async Task TestCompaniesImagesAsync() { - IgnoreMissingJson(" / movies"); - // Get config - Config.Client.GetConfigAsync().Sync(); + await TMDbClient.GetConfigAsync(); // Test image url generator - Company company = Config.Client.GetCompanyAsync(IdHelper.TwentiethCenturyFox).Result; + Company company = await TMDbClient.GetCompanyAsync(IdHelper.TwentiethCenturyFox); - Uri url = Config.Client.GetImageUrl("original", company.LogoPath); - Uri urlSecure = Config.Client.GetImageUrl("original", company.LogoPath, true); + Uri url = TMDbClient.GetImageUrl("original", company.LogoPath); + Uri urlSecure = TMDbClient.GetImageUrl("original", company.LogoPath, true); - Assert.True(TestHelpers.InternetUriExists(url)); - Assert.True(TestHelpers.InternetUriExists(urlSecure)); - } - - [Fact] - public void TestCompaniesFull() - { - IgnoreMissingJson(" / movies"); - - Company company = Config.Client.GetCompanyAsync(IdHelper.ColumbiaPictures).Result; - - Assert.NotNull(company); - - Assert.Equal(IdHelper.ColumbiaPictures, company.Id); - Assert.Equal("Columbia Pictures Industries, Inc. (CPII) is an American film production and distribution company. Columbia Pictures now forms part of the Columbia TriStar Motion Picture Group, owned by Sony Pictures Entertainment, a subsidiary of the Japanese conglomerate Sony. It is one of the leading film companies in the world, a member of the so-called Big Six. It was one of the so-called Little Three among the eight major film studios of Hollywood's Golden Age.", company.Description); - Assert.Equal("Culver City, California", company.Headquarters); - Assert.Equal("http://www.sonypictures.com/", company.Homepage); - Assert.Equal("US", company.OriginCountry); - Assert.Equal("/mjUSfXXUhMiLAA1Zq1TfStNSoLR.png", company.LogoPath); - Assert.Equal("Columbia Pictures", company.Name); - - Assert.NotNull(company.ParentCompany); - Assert.Equal(5752, company.ParentCompany.Id); - Assert.Equal("/sFg00KK0vVq3oqvkCxRQWApYB83.png", company.ParentCompany.LogoPath); - Assert.Equal("Sony Pictures Entertainment", company.ParentCompany.Name); + await Verify(new + { + url, + urlSecure + }); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientConfigurationTests.cs b/TMDbLibTests/ClientConfigurationTests.cs index a7bc8c4..f231efb 100644 --- a/TMDbLibTests/ClientConfigurationTests.cs +++ b/TMDbLibTests/ClientConfigurationTests.cs @@ -1,9 +1,9 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using TMDbLib.Objects.Configuration; using Xunit; using TMDbLib.Objects.Timezones; -using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; using TMDbLib.Objects.Countries; using TMDbLib.Objects.General; @@ -14,72 +14,63 @@ namespace TMDbLibTests public class ClientConfigurationTests : TestBase { [Fact] - public void TestConfiguration() + public async Task TestConfigurationAsync() { - APIConfiguration result = Config.Client.GetAPIConfiguration().Sync(); + APIConfiguration result = await TMDbClient.GetAPIConfiguration(); - Assert.NotNull(result); - - Assert.Contains(result.Images.BackdropSizes, c => c == "original"); + await Verify(result); } [Fact] - public void TestPrimaryTranslations() + public async Task TestPrimaryTranslationsAsync() { - List result = Config.Client.GetPrimaryTranslationsAsync().Sync(); + List result = await TMDbClient.GetPrimaryTranslationsAsync(); - Assert.NotNull(result); - - Assert.Contains(result, c => c == "da-DK"); + Assert.Contains("da-DK", result); } [Fact] - public void TestCountryList() + public async Task TestCountryListAsync() { - List result = Config.Client.GetCountriesAsync().Sync(); + List result = await TMDbClient.GetCountriesAsync(); - Assert.NotNull(result); - Assert.True(result.Count > 200); + Assert.NotEmpty(result); + Country single = result.Single(s => s.EnglishName == "Denmark"); - Assert.Contains(result, c => c.EnglishName == "Denmark" && c.Iso_3166_1 == "DK"); + await Verify(single); } [Fact] - public void TestLanguageList() + public async Task TestLanguageListAsync() { - List result = Config.Client.GetLanguagesAsync().Sync(); + List result = await TMDbClient.GetLanguagesAsync(); - Assert.NotNull(result); - Assert.True(result.Count > 180); + Assert.NotEmpty(result); + Language single = result.Single(s => s.Name == "Dansk"); - Assert.Contains(result, l => l.Name == "Dansk" && l.EnglishName == "Danish" && l.Iso_639_1 == "da"); + await Verify(single); } [Fact] - public void TestTimezonesList() + public async Task TestTimezonesListAsync() { - Timezones result = Config.Client.GetTimezonesAsync().Sync(); + Timezones result = await TMDbClient.GetTimezonesAsync(); - Assert.NotNull(result); - Assert.True(result.List.Count > 200); + Assert.NotEmpty(result.List); + List single = result.List["DK"]; - List item = result.List["DK"]; - Assert.NotNull(item); - Assert.Equal(1, item.Count); - Assert.Equal("Europe/Copenhagen", item[0]); + await Verify(single); } [Fact] - public void TestJobList() + public async Task TestJobListAsync() { - List jobs = Config.Client.GetJobsAsync().Sync(); + List jobs = await TMDbClient.GetJobsAsync(); - Assert.NotNull(jobs); - Assert.True(jobs.Count > 0); + Assert.NotEmpty(jobs); + Job single = jobs.Single(s => s.Department == "Writing"); - Assert.True(jobs.All(job => !string.IsNullOrEmpty(job.Department))); - Assert.True(jobs.All(job => job.Jobs != null)); - Assert.True(jobs.All(job => job.Jobs.Count > 0)); + await Verify(single); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientCreditTests.cs b/TMDbLibTests/ClientCreditTests.cs index dcad970..dd4dede 100644 --- a/TMDbLibTests/ClientCreditTests.cs +++ b/TMDbLibTests/ClientCreditTests.cs @@ -1,8 +1,6 @@ -using System; -using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Credit; -using TMDbLib.Objects.General; using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; @@ -11,71 +9,33 @@ namespace TMDbLibTests public class ClientCreditTests : TestBase { [Fact] - public void TestGetCreditTv() + public async Task TestGetCreditTv() { - Credit result = Config.Client.GetCreditsAsync(IdHelper.BruceWillisMiamiVice).Result; + Credit result = await TMDbClient.GetCreditsAsync(IdHelper.BruceWillisMiamiVice); - Assert.NotNull(result); - Assert.Equal(CreditType.Cast, result.CreditType); - Assert.Equal("Actors", result.Department); - Assert.Equal("Actor", result.Job); - Assert.Equal(MediaType.Tv, result.MediaType); - Assert.Equal(IdHelper.BruceWillisMiamiVice, result.Id); + // Episode must exist + Assert.Contains(result.Media.Episodes, s => s.Name == "No Exit"); - Assert.NotNull(result.Person); - Assert.Equal("Bruce Willis", result.Person.Name); - Assert.Equal(62, result.Person.Id); - - Assert.NotNull(result.Media); - Assert.Equal(1908, result.Media.Id); - Assert.Equal("Miami Vice", result.Media.Name); - Assert.Equal("Miami Vice", result.Media.OriginalName); - Assert.Equal("", result.Media.Character); + await Verify(result); } [Fact] - public void TestMissingCredit() + public async Task TestMissingCredit() { - Credit result = Config.Client.GetCreditsAsync(IdHelper.MissingID.ToString()).Result; + Credit result = await TMDbClient.GetCreditsAsync(IdHelper.MissingID.ToString()); Assert.Null(result); } [Fact] - public void TestGetCreditEpisode() + public async Task TestGetCreditSeasons() { - Credit result = Config.Client.GetCreditsAsync(IdHelper.BruceWillisMiamiVice).Result; + Credit result = await TMDbClient.GetCreditsAsync(IdHelper.HughLaurieHouse); - Assert.NotNull(result); - Assert.NotNull(result.Media); - Assert.NotNull(result.Media.Episodes); + // Season must exist + Assert.Contains(result.Media.Seasons, s => s.SeasonNumber == 1); - CreditEpisode item = result.Media.Episodes.SingleOrDefault(s => s.Name == "No Exit"); - Assert.NotNull(item); - - Assert.Equal(new DateTime(1984, 11, 9), item.AirDate); - Assert.Equal(8, item.EpisodeNumber); - Assert.Equal("No Exit", item.Name); - Assert.Equal("Crockett attempts to help an old flame free herself from a racketeer, then is framed for taking bribes. Martin Castillo becomes the squad's new Lieutenant.", item.Overview); - Assert.Equal(1, item.SeasonNumber); - Assert.True(TestImagesHelpers.TestImagePath(item.StillPath), "item.StillPath was not a valid image path, was: " + item.StillPath); - } - - [Fact] - public void TestGetCreditSeasons() - { - Credit result = Config.Client.GetCreditsAsync(IdHelper.HughLaurieHouse).Result; - - Assert.NotNull(result); - Assert.NotNull(result.Media); - Assert.NotNull(result.Media.Seasons); - - CreditSeason item = result.Media.Seasons.SingleOrDefault(s => s.SeasonNumber == 1); - Assert.NotNull(item); - - Assert.Equal(new DateTime(2004, 11, 16), item.AirDate); - Assert.True(TestImagesHelpers.TestImagePath(item.PosterPath), "item.PosterPath was not a valid image path, was: " + item.PosterPath); - Assert.Equal(1, item.SeasonNumber); + await Verify(result); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientDiscoverTests.cs b/TMDbLibTests/ClientDiscoverTests.cs index d9bf131..b01c212 100644 --- a/TMDbLibTests/ClientDiscoverTests.cs +++ b/TMDbLibTests/ClientDiscoverTests.cs @@ -1,112 +1,83 @@ using Xunit; using TMDbLib.Objects.Discover; using TMDbLib.Objects.General; -using System.Linq; using TMDbLib.Objects.Search; using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; using System; -using System.Collections.Generic; +using System.Threading.Tasks; namespace TMDbLibTests { public class ClientDiscoverTests : TestBase { [Fact] - public void TestDiscoverTvShowsNoParams() + public async Task TestDiscoverTvShowsNoParamsAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - TestHelpers.SearchPages(i => Config.Client.DiscoverTvShowsAsync().Query(i).Result); - - SearchContainer result = Config.Client.DiscoverTvShowsAsync().Query().Result; - - Assert.NotNull(result); - Assert.Equal(1, result.Page); - Assert.NotNull(result.Results); - Assert.True(result.Results.Any()); + await TestHelpers.SearchPagesAsync(i => TMDbClient.DiscoverTvShowsAsync().Query(i)); } [Fact] - public void TestDiscoverTvShows() + public async Task TestDiscoverMoviesNoParamsAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TestHelpers.SearchPagesAsync(i => TMDbClient.DiscoverMoviesAsync().Query(i)); + } - DiscoverTv query = Config.Client.DiscoverTvShowsAsync() + [Fact] + public async Task TestDiscoverTvShowsAsync() + { + DiscoverTv query = TMDbClient.DiscoverTvShowsAsync() .WhereVoteCountIsAtLeast(100) .WhereVoteAverageIsAtLeast(2); - TestHelpers.SearchPages(i => query.Query(i).Result); + await TestHelpers.SearchPagesAsync(i => query.Query(i)); } [Fact] - public void TestDiscoverMoviesNoParams() + public async Task TestDiscoverMoviesAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - TestHelpers.SearchPages(i => Config.Client.DiscoverMoviesAsync().Query(i).Result); - - SearchContainer result = Config.Client.DiscoverMoviesAsync().Query().Result; - - Assert.NotNull(result); - Assert.Equal(1, result.Page); - Assert.NotNull(result.Results); - Assert.True(result.Results.Any()); - } - - [Fact] - public void TestDiscoverMovies() - { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - DiscoverMovie query = Config.Client.DiscoverMoviesAsync() + DiscoverMovie query = TMDbClient.DiscoverMoviesAsync() .WhereVoteCountIsAtLeast(1000) .WhereVoteAverageIsAtLeast(2); - TestHelpers.SearchPages(i => query.Query(i).Result); + await TestHelpers.SearchPagesAsync(i => query.Query(i)); } [Fact] - public void TestDiscoverMoviesRegion() + public async Task TestDiscoverMoviesRegionAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + DiscoverMovie query = TMDbClient.DiscoverMoviesAsync() + .WhereReleaseDateIsInRegion("BR") + .WherePrimaryReleaseDateIsAfter(new DateTime(2017, 01, 01)); - DiscoverMovie query = Config.Client.DiscoverMoviesAsync().WhereReleaseDateIsInRegion("BR").WherePrimaryReleaseDateIsAfter(new DateTime(2017, 01, 01)); - - TestHelpers.SearchPages(i => query.Query(i).Result); + await TestHelpers.SearchPagesAsync(i => query.Query(i)); } [Fact] - public void TestDiscoverMoviesLanguage() + public async Task TestDiscoverMoviesLanguageAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + SearchContainer query = await TMDbClient.DiscoverMoviesAsync() + .WhereOriginalLanguageIs("en-US") + .WherePrimaryReleaseDateIsAfter(new DateTime(2017, 01, 01)) + .Query(); - DiscoverMovie query = Config.Client.DiscoverMoviesAsync().WhereLanguageIs("da-DK").WherePrimaryReleaseDateIsAfter(new DateTime(2017, 01, 01)); + SearchContainer queryDanish = await TMDbClient.DiscoverMoviesAsync() + .WhereLanguageIs("da-DK") + .WhereOriginalLanguageIs("en-US") + .WherePrimaryReleaseDateIsAfter(new DateTime(2017, 01, 01)) + .Query(); - Assert.Equal("Skønheden og Udyret", query.Query(0).Result.Results[11].Title); + // Should be the same identities, but different titles + Assert.Equal(query.TotalResults, queryDanish.TotalResults); - TestHelpers.SearchPages(i => query.Query(i).Result); - } + for (int i = 0; i < query.Results.Count; i++) + { + SearchMovie a = query.Results[i]; + SearchMovie b = queryDanish.Results[i]; - [Theory] - [InlineData("ko")] - [InlineData("zh")] - public void TestDiscoverMoviesOriginalLanguage(string language) - { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - DiscoverMovie query = Config.Client.DiscoverMoviesAsync().WhereOriginalLanguageIs(language); - List results = query.Query(0).Result.Results; - - Assert.NotEmpty(results); - Assert.All(results, item => Assert.Contains(language, item.OriginalLanguage)); + Assert.Equal(a.Id, b.Id); + Assert.NotEqual(a.Title, b.Title); + } } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientFindTests.cs b/TMDbLibTests/ClientFindTests.cs index 37836a1..0953230 100644 --- a/TMDbLibTests/ClientFindTests.cs +++ b/TMDbLibTests/ClientFindTests.cs @@ -9,65 +9,51 @@ namespace TMDbLibTests public class ClientFindTests : TestBase { [Fact] - public void TestFindImdbMovie() + public async Task TestFindImdbMovie() { - // Ignore missing json - IgnoreMissingJson("movie_results[array] / media_type", "movie_results[array] / popularity"); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbTerminatorId); - Task result = Config.Client.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbTerminatorId); - Assert.Equal(1, result.Result.MovieResults.Count); - Assert.Equal(IdHelper.TmdbTerminatorId, result.Result.MovieResults[0].Id); + await Verify(result); } [Fact] - public void TestFindImdbPerson() + public async Task TestFindImdbPerson() { - // Ignore missing json - IgnoreMissingJson("person_results[array] / media_type", " / popularity", "person_results[array] / popularity"); - - Task result = Config.Client.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBruceWillis); - Assert.Equal(1, result.Result.PersonResults.Count); - Assert.Equal(IdHelper.BruceWillis, result.Result.PersonResults[0].Id); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBruceWillis); + + await Verify(result); } [Fact] - public void TestFindImdbTvShowEpisode() + public async Task TestFindImdbTvShowEpisode() { - Task result = Config.Client.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBreakingBadSeason1Episode1Id); - Assert.Equal(1, result.Result.TvEpisode.Count); - Assert.Equal(IdHelper.BreakingBadSeason1Episode1Id, result.Result.TvEpisode[0].Id); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBreakingBadSeason1Episode1Id); + + await Verify(result); } [Fact] - public void TestFindImdbTvShowSeason() + public async Task TestFindImdbTvShowSeasonAsync() { - Task result = Config.Client.FindAsync(FindExternalSource.TvDb, IdHelper.TvdbBreakingBadSeason1Id); - Assert.Equal(1, result.Result.TvEpisode.Count); - - Assert.Equal(1, result.Result.TvSeason.Count); - Assert.Equal(IdHelper.BreakingBadSeason1Id, result.Result.TvSeason[0].Id); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.TvDb, IdHelper.TvdbBreakingBadSeason1Id); + + await Verify(result); } [Fact] - public void TestFindTvdbTvShow() + public async Task TestFindTvdbTvShowAsync() { - // Ignore missing json - IgnoreMissingJson("tv_results[array] / media_type", "tv_results[array] / popularity"); - - Task result = Config.Client.FindAsync(FindExternalSource.TvDb, IdHelper.TvdbBreakingBadId); - Assert.Equal(1, result.Result.TvResults.Count); - Assert.Equal(IdHelper.TmdbBreakingBadId, result.Result.TvResults[0].Id); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.TvDb, IdHelper.TvdbBreakingBadId); + + await Verify(result); } [Fact] - public void TestFindImdbTvShow() + public async Task TestFindImdbTvShowAsync() { - // Ignore missing json - IgnoreMissingJson("tv_results[array] / media_type", "tv_results[array] / popularity"); - - Task result = Config.Client.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBreakingBadId); - Assert.Equal(1, result.Result.TvResults.Count); - Assert.Equal(IdHelper.TmdbBreakingBadId, result.Result.TvResults[0].Id); + FindContainer result = await TMDbClient.FindAsync(FindExternalSource.Imdb, IdHelper.ImdbBreakingBadId); + + await Verify(result); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientGenreTests.cs b/TMDbLibTests/ClientGenreTests.cs index ff6db11..dd47396 100644 --- a/TMDbLibTests/ClientGenreTests.cs +++ b/TMDbLibTests/ClientGenreTests.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.General; using TMDbLib.Objects.Search; @@ -11,75 +12,57 @@ namespace TMDbLibTests public class ClientGenreTests : TestBase { [Fact] - public void TestGenreTvList() + public async Task TestGenreTvListAsync() { // Default language - List genres = Config.Client.GetTvGenresAsync().Sync(); - - Assert.NotNull(genres); - Assert.True(genres.Count > 0); + List genres = await TMDbClient.GetTvGenresAsync(); // Another language - List genresDanish = Config.Client.GetTvGenresAsync("da").Result; + List genresDanish = await TMDbClient.GetTvGenresAsync("da"); - Assert.NotNull(genresDanish); - Assert.True(genresDanish.Count > 0); - - Assert.Equal(genres.Count, genresDanish.Count); + await Verify(new + { + genres, + genresDanish + }); // At least one should be different - Assert.True(genres.Any(genre => genresDanish.First(danishGenre => danishGenre.Id == genre.Id).Name != genre.Name)); + Genre actionEn = genres.Single(s => s.Id == IdHelper.ActionAdventureTvGenre); + Genre actionDa = genresDanish.Single(s => s.Id == IdHelper.ActionAdventureTvGenre); + + Assert.NotEqual(actionEn.Name, actionDa.Name); } [Fact] - public void TestGenreMovieList() + public async Task TestGenreMovieListAsync() { // Default language - List genres = Config.Client.GetMovieGenresAsync().Sync(); - - Assert.NotNull(genres); - Assert.True(genres.Count > 0); + List genres = await TMDbClient.GetMovieGenresAsync(); // Another language - List genresDanish = Config.Client.GetMovieGenresAsync("da").Result; + List genresDanish = await TMDbClient.GetMovieGenresAsync("da"); - Assert.NotNull(genresDanish); - Assert.True(genresDanish.Count > 0); - - Assert.Equal(genres.Count, genresDanish.Count); + await Verify(new + { + genres, + genresDanish + }); // At least one should be different - Assert.True(genres.Any(genre => genresDanish.First(danishGenre => danishGenre.Id == genre.Id).Name != genre.Name)); + Genre actionEn = genres.Single(s => s.Id == IdHelper.AdventureMovieGenre); + Genre actionDa = genresDanish.Single(s => s.Id == IdHelper.AdventureMovieGenre); + + Assert.NotEqual(actionEn.Name, actionDa.Name); } [Fact] - public void TestGenreMovies() + public async Task TestGenreMoviesAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + SearchContainerWithId movies = await TMDbClient.GetGenreMoviesAsync(IdHelper.AdventureMovieGenre); - // Get first genre - Genre genre = Config.Client.GetMovieGenresAsync().Sync().First(); - - // Get movies - SearchContainerWithId movies = Config.Client.GetGenreMoviesAsync(genre.Id).Result; - SearchContainerWithId moviesPage2 = Config.Client.GetGenreMoviesAsync(genre.Id, "it", 2, includeAllMovies: false).Result; - SearchContainerWithId moviesAll = Config.Client.GetGenreMoviesAsync(genre.Id, includeAllMovies: true).Result; - - Assert.Equal(1, movies.Page); - Assert.Equal(2, moviesPage2.Page); - Assert.Equal(1, moviesAll.Page); - - Assert.True(movies.Results.Count > 0); - Assert.True(moviesPage2.Results.Count > 0); - Assert.True(moviesAll.Results.Count > 0); - - Assert.True(movies.Results.All(s => s != null)); - Assert.True(moviesPage2.Results.All(s => s != null)); - Assert.True(moviesAll.Results.All(s => s != null)); - - Assert.Equal(movies.TotalResults, moviesPage2.TotalResults); // Should be the same, despite the use of 'includeAllMovies' and Italian - Assert.True(moviesAll.TotalResults >= movies.TotalResults); + Assert.NotEmpty(movies.Results); + Assert.Equal(IdHelper.AdventureMovieGenre, movies.Id); + Assert.All(movies.Results, x => Assert.Contains(IdHelper.AdventureMovieGenre, x.GenreIds)); } } } diff --git a/TMDbLibTests/ClientGuestSessionTests.cs b/TMDbLibTests/ClientGuestSessionTests.cs index 68721ce..d96c2c1 100644 --- a/TMDbLibTests/ClientGuestSessionTests.cs +++ b/TMDbLibTests/ClientGuestSessionTests.cs @@ -1,6 +1,4 @@ -using System; -using System.Linq; -using System.Threading; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Authentication; using TMDbLib.Objects.General; @@ -14,191 +12,69 @@ namespace TMDbLibTests public class ClientGuestSessionTests : TestBase { [Fact] - public void TestTvEpisodeSetRatingGuestSession() + public async Task TestTvEpisodeSetRatingGuestSessionAsync() { - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.GuestTestSessionId, SessionType.GuestSession); - // Try changing the rating - Assert.True(Config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 1, 7.5).Result); + await TestMethodsHelper.SetValidateRemoveTest(async () => + { + Assert.True(await TMDbClient.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 1, 7.5)); + }, async () => + { + Assert.True(await TMDbClient.TvEpisodeRemoveRatingAsync(IdHelper.BreakingBad, 1, 1)); + }, async shouldBeSet => + { + SearchContainer ratings = await TMDbClient.GetGuestSessionRatedTvEpisodesAsync(); - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - SearchContainer ratings = Config.Client.GetGuestSessionRatedTvEpisodesAsync().Sync(); - - Assert.False(true, "This test has been failing for some time - TMDb has been made aware, but have not responded"); - - //double tmpRating = ratings.Results.Single(s => s.ShowId == IdHelper.BreakingBad && s.SeasonNumber == 1 && s.EpisodeNumber == 1).Rating; - //Assert.True(ratings.Results.Any(s => s.ShowId == IdHelper.BreakingBad && s.SeasonNumber == 1 && s.EpisodeNumber == 1)); - //Assert.True(Math.Abs(7.5 - tmpRating) < float.Epsilon); - - //// Try changing it back to the previous rating - //Assert.True(Config.Client.TvEpisodeSetRatingAsync(IdHelper.BreakingBad, 1, 1, 8).Result); - - //// Allow TMDb to cache our changes - //Thread.Sleep(2000); - - //ratings = Config.Client.GetGuestSessionRatedTvEpisodesAsync().Sync(); - - //tmpRating = ratings.Results.Single(s => s.ShowId == IdHelper.BreakingBad && s.SeasonNumber == 1 && s.EpisodeNumber == 1).Rating; - //Assert.True(ratings.Results.Any(s => s.ShowId == IdHelper.BreakingBad && s.SeasonNumber == 1 && s.EpisodeNumber == 1)); - //Assert.True(Math.Abs(8 - tmpRating) < float.Epsilon); - - //// Try removing the rating - //Assert.True(Config.Client.TvEpisodeRemoveRatingAsync(IdHelper.BreakingBad, 1, 1).Result); - - //// Allow TMDb to cache our changes - //Thread.Sleep(2000); - - //ratings = Config.Client.GetGuestSessionRatedTvEpisodesAsync().Sync(); - - //Assert.False(ratings.Results.Any(s => s.ShowId == IdHelper.BreakingBad && s.SeasonNumber == 1 && s.EpisodeNumber == 1)); + if (shouldBeSet) + Assert.Contains(ratings.Results, x => x.ShowId == IdHelper.BreakingBad && x.SeasonNumber == 1 && x.EpisodeNumber == 1); + else + Assert.DoesNotContain(ratings.Results, x => x.ShowId == IdHelper.BreakingBad && x.SeasonNumber == 1 && x.EpisodeNumber == 1); + }); } [Fact] - public void TestTvSetRatingGuestSession() + public async Task TestTvSetRatingGuestSessionAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.GuestTestSessionId, SessionType.GuestSession); - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); + await TestMethodsHelper.SetValidateRemoveTest(async () => + { + Assert.True(await TMDbClient.TvShowSetRatingAsync(IdHelper.House, 7.5)); + }, async () => + { + Assert.True(await TMDbClient.TvShowRemoveRatingAsync(IdHelper.House)); + }, async shouldBeSet => + { + SearchContainer ratings = await TMDbClient.GetGuestSessionRatedTvAsync(); - // Try changing the rating - Assert.True(Config.Client.TvShowSetRatingAsync(IdHelper.House, 7.5).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - SearchContainer ratings = Config.Client.GetGuestSessionRatedTvAsync().Sync(); - - double tmpRating = ratings.Results.Single(s => s.Id == IdHelper.House).Rating; - Assert.True(ratings.Results.Any(s => s.Id == IdHelper.House)); - Assert.True(Math.Abs(7.5 - tmpRating) < float.Epsilon); - - // Try changing it back to the previous rating - Assert.True(Config.Client.TvShowSetRatingAsync(IdHelper.House, 8).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - ratings = Config.Client.GetGuestSessionRatedTvAsync().Sync(); - - tmpRating = ratings.Results.Single(s => s.Id == IdHelper.House).Rating; - Assert.True(ratings.Results.Any(s => s.Id == IdHelper.House)); - Assert.True(Math.Abs(8 - tmpRating) < float.Epsilon); - - // Try removing the rating - Assert.True(Config.Client.TvShowRemoveRatingAsync(IdHelper.House).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - ratings = Config.Client.GetGuestSessionRatedTvAsync().Sync(); - - Assert.False(ratings.Results.Any(s => s.Id == IdHelper.House)); + if (shouldBeSet) + Assert.Contains(ratings.Results, x => x.Id == IdHelper.House); + else + Assert.DoesNotContain(ratings.Results, x => x.Id == IdHelper.House); + }); } [Fact] - public void TestMoviesSetRatingGuestSession() + public async Task TestMoviesSetRatingGuestSessionAsync() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.GuestTestSessionId, SessionType.GuestSession); + + await TestMethodsHelper.SetValidateRemoveTest(async () => + { + Assert.True(await TMDbClient.MovieSetRatingAsync(IdHelper.Terminator, 7.5)); + }, async () => + { + Assert.True(await TMDbClient.MovieRemoveRatingAsync(IdHelper.Terminator)); + }, async shouldBeSet => + { + SearchContainer ratings = await TMDbClient.GetGuestSessionRatedMoviesAsync(); - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); - - // Try changing the rating - Assert.True(Config.Client.MovieSetRatingAsync(IdHelper.Terminator, 7.5).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - SearchContainer ratings = Config.Client.GetGuestSessionRatedMoviesAsync().Sync(); - - double tmpRating = ratings.Results.Single(s => s.Id == IdHelper.Terminator).Rating; - Assert.True(ratings.Results.Any(s => s.Id == IdHelper.Terminator)); - Assert.True(Math.Abs(7.5 - tmpRating) < float.Epsilon); - - // Try changing it back to the previous rating - Assert.True(Config.Client.MovieSetRatingAsync(IdHelper.Terminator, 8).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - ratings = Config.Client.GetGuestSessionRatedMoviesAsync().Sync(); - - tmpRating = ratings.Results.Single(s => s.Id == IdHelper.Terminator).Rating; - Assert.True(ratings.Results.Any(s => s.Id == IdHelper.Terminator)); - Assert.True(Math.Abs(8 - tmpRating) < float.Epsilon); - - // Try removing the rating - Assert.True(Config.Client.MovieRemoveRatingAsync(IdHelper.Terminator).Result); - - // Allow TMDb to cache our changes - Thread.Sleep(2000); - - ratings = Config.Client.GetGuestSessionRatedMoviesAsync().Sync(); - - Assert.False(ratings.Results.Any(s => s.Id == IdHelper.Terminator)); - } - - [Fact] - public void TestGuestSessionGetRatedTvEpisodes() - { - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); - - // Ensure we have a rating - Assert.True(Config.Client.TvEpisodeSetRatingAsync(IdHelper.BigBangTheory, 1, 1, 7.5).Result); - - // Test paging - TestHelpers.SearchPages(i => Config.Client.GetGuestSessionRatedTvEpisodesAsync(i).Result); - - // Fetch ratings - SearchContainer result = Config.Client.GetGuestSessionRatedTvEpisodesAsync().Sync(); - - Assert.NotNull(result); - Assert.NotNull(result.Results); - } - - [Fact] - public void TestGuestSessionGetRatedTv() - { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); - - // Ensure we have a rating - Assert.True(Config.Client.TvShowSetRatingAsync(IdHelper.BigBangTheory, 7.5).Result); - - // Test paging - TestHelpers.SearchPages(i => Config.Client.GetGuestSessionRatedTvAsync(i).Result); - - // Fetch ratings - SearchContainer result = Config.Client.GetGuestSessionRatedTvAsync().Sync(); - - Assert.NotNull(result); - Assert.NotNull(result.Results); - } - - [Fact] - public void TestGuestSessionGetRatedMovies() - { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); - - Config.Client.SetSessionInformation(Config.GuestTestSessionId, SessionType.GuestSession); - - // Ensure we have a rating - Assert.True(Config.Client.MovieSetRatingAsync(IdHelper.Terminator, 7.5).Result); - - // Test paging - TestHelpers.SearchPages(i => Config.Client.GetGuestSessionRatedMoviesAsync(i).Result); - - // Fetch ratings - SearchContainer result = Config.Client.GetGuestSessionRatedMoviesAsync().Sync(); - - Assert.NotNull(result); - Assert.NotNull(result.Results); + if (shouldBeSet) + Assert.Contains(ratings.Results, x => x.Id == IdHelper.Terminator); + else + Assert.DoesNotContain(ratings.Results, x => x.Id == IdHelper.Terminator); + }); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientKeywordTests.cs b/TMDbLibTests/ClientKeywordTests.cs index a2cb1d6..de8f8c5 100644 --- a/TMDbLibTests/ClientKeywordTests.cs +++ b/TMDbLibTests/ClientKeywordTests.cs @@ -1,4 +1,5 @@ using System.Linq; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.General; using TMDbLib.Objects.Movies; @@ -11,86 +12,48 @@ namespace TMDbLibTests public class ClientKeywordTests : TestBase { [Fact] - public void TestKeywordGet() + public async Task TestGetMovieKeywordsAsync() { - KeywordsContainer keywords = Config.Client.GetMovieKeywordsAsync(IdHelper.AGoodDayToDieHard).Result; + KeywordsContainer keywords = await TMDbClient.GetMovieKeywordsAsync(IdHelper.AGoodDayToDieHard); - Assert.NotNull(keywords); - Assert.NotNull(keywords.Keywords); - Assert.True(keywords.Keywords.Count > 0); - - // Try to get all keywords - foreach (Keyword testKeyword in keywords.Keywords) - { - Keyword getKeyword = Config.Client.GetKeywordAsync(testKeyword.Id).Result; - - Assert.NotNull(getKeyword); - - Assert.Equal(testKeyword.Id, getKeyword.Id); - Assert.Equal(testKeyword.Name, getKeyword.Name); - } + await Verify(keywords); } [Fact] - public void TestKeywordsMissing() + public async Task TestGetTvShowKeywordsAsync() { - KeywordsContainer keywords = Config.Client.GetMovieKeywordsAsync(IdHelper.MissingID).Result; + ResultContainer keywords = await TMDbClient.GetTvShowKeywordsAsync(IdHelper.BigBangTheory); + + await Verify(keywords); + } + + [Fact] + public async Task TestKeywordGetSingle() + { + Keyword keyword = await TMDbClient.GetKeywordAsync(IdHelper.AgentKeyword); + + await Verify(keyword); + } + + [Fact] + public async Task TestKeywordsMissing() + { + KeywordsContainer keywords = await TMDbClient.GetMovieKeywordsAsync(IdHelper.MissingID); Assert.Null(keywords); } [Fact] - public void TestKeywordMovies() + public async Task TestKeywordMovies() { - // Ignore missing json - IgnoreMissingJson("results[array] / media_type"); + SearchContainerWithId movies = await TMDbClient.GetKeywordMoviesAsync(IdHelper.AgentKeyword); - KeywordsContainer keywords = Config.Client.GetMovieKeywordsAsync(IdHelper.AGoodDayToDieHard).Result; + Assert.Equal(IdHelper.AgentKeyword, movies.Id); + Assert.NotEmpty(movies.Results); - Assert.NotNull(keywords); - Assert.NotNull(keywords.Keywords); - Assert.True(keywords.Keywords.Count > 0); + KeywordsContainer movie = await TMDbClient.GetMovieKeywordsAsync(movies.Results.First().Id); - // Get first keyword - Keyword testKeyword = keywords.Keywords.First(); - - // Get movies - SearchContainerWithId movies = Config.Client.GetKeywordMoviesAsync(testKeyword.Id).Result; - SearchContainerWithId moviesItalian = Config.Client.GetKeywordMoviesAsync(testKeyword.Id, "it").Result; - SearchContainerWithId moviesPage2 = Config.Client.GetKeywordMoviesAsync(testKeyword.Id, 2).Result; - - Assert.NotNull(movies); - Assert.NotNull(moviesItalian); - Assert.NotNull(moviesPage2); - - Assert.Equal(testKeyword.Id, movies.Id); - Assert.Equal(testKeyword.Id, moviesItalian.Id); - Assert.Equal(testKeyword.Id, moviesPage2.Id); - - Assert.True(movies.Results.Count > 0); - Assert.True(moviesItalian.Results.Count > 0); - - if (movies.TotalResults > movies.Results.Count) - Assert.True(moviesPage2.Results.Count > 0); - else - Assert.Equal(0, moviesPage2.Results.Count); - - Assert.Equal(1, movies.Page); - Assert.Equal(1, moviesItalian.Page); - Assert.Equal(2, moviesPage2.Page); - - // All titles on page 1 must be the same - bool allTitlesIdentical = true; - for (int index = 0; index < movies.Results.Count; index++) - { - Assert.Equal(movies.Results[index].Id, moviesItalian.Results[index].Id); - - // At least one title must differ in title - if (movies.Results[index].Title != moviesItalian.Results[index].Title) - allTitlesIdentical = false; - } - - Assert.False(allTitlesIdentical); + Assert.Contains(movie.Keywords, x => IdHelper.AgentKeyword == x.Id); } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientListsTests.cs b/TMDbLibTests/ClientListsTests.cs index 5d02a8c..7633605 100644 --- a/TMDbLibTests/ClientListsTests.cs +++ b/TMDbLibTests/ClientListsTests.cs @@ -1,154 +1,119 @@ using System; using System.Linq; +using System.Threading.Tasks; +using TMDbLib.Client; using Xunit; using TMDbLib.Objects.Authentication; using TMDbLib.Objects.General; using TMDbLib.Objects.Lists; using TMDbLib.Objects.Movies; -using TMDbLib.Objects.Search; using TMDbLibTests.Helpers; using TMDbLibTests.JsonHelpers; namespace TMDbLibTests { + [Collection(nameof(ListFixturesCollection))] public class ClientListsTests : TestBase { private const string TestListId = "528349d419c2954bd21ca0a8"; + private const string EphemeralListPrefix = "TestListTMDbLib-"; [Fact] - public void TestList() + public async Task TestGetListAsync() { // Get list - GenericList list = Config.Client.GetListAsync(TestListId).Result; + GenericList list = await TMDbClient.GetListAsync(TestListId); - Assert.NotNull(list); - Assert.Equal(TestListId, list.Id); - Assert.Equal(list.ItemCount, list.Items.Count); - - foreach (SearchMovie movieResult in list.Items) - { - Assert.NotNull(movieResult); - - // Ensure all movies point to this list - int page = 1; - SearchContainer movieLists = Config.Client.GetMovieListsAsync(movieResult.Id).Result; - while (movieLists != null) - { - // Check if the current result page contains the relevant list - if (movieLists.Results.Any(s => s.Id == TestListId)) - { - movieLists = null; - continue; - } - - // See if there is an other page we could try, if not the test fails - if (movieLists.Page < movieLists.TotalPages) - movieLists = Config.Client.GetMovieListsAsync(movieResult.Id, ++page).Result; - else - throw new Exception($"Movie '{movieResult.Title}' was not linked to the test list"); - } - } + await Verify(list); } [Fact] - public void TestListMissing() + public async Task TestListAsync() { - GenericList list = Config.Client.GetListAsync(IdHelper.MissingID.ToString()).Result; + SearchContainer movieLists = await TMDbClient.GetMovieListsAsync(IdHelper.Avatar); + + Assert.NotEmpty(movieLists.Results); + Assert.All(movieLists.Results, x => Assert.Equal(MediaType.Movie, x.ListType)); + } + + [Fact] + public async Task TestListMissingAsync() + { + GenericList list = await TMDbClient.GetListAsync(IdHelper.MissingID.ToString()); Assert.Null(list); } [Fact] - public void TestListIsMoviePresentFailure() + public async Task TestListCreateAddClearAndDeleteAsync() { - Assert.False(Config.Client.GetListIsMoviePresentAsync(TestListId, IdHelper.Terminator).Result); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + string listName = EphemeralListPrefix + DateTime.UtcNow.ToString("O"); - // Clear list - Assert.True(Config.Client.ListClearAsync(TestListId).Result); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - // Verify Avatar is not present - Assert.False(Config.Client.GetListIsMoviePresentAsync(TestListId, IdHelper.Avatar).Result); + string listId = await TMDbClient.ListCreateAsync(listName); - // Add Avatar - Assert.True(Config.Client.ListAddMovieAsync(TestListId, IdHelper.Avatar).Result); + Assert.False(string.IsNullOrWhiteSpace(listId)); - // Verify Avatar is present - Assert.True(Config.Client.GetListIsMoviePresentAsync(TestListId, IdHelper.Avatar).Result); - } + GenericList newlyAddedList = await TMDbClient.GetListAsync(listId); - [Fact] - public void TestListCreateAndDelete() - { - const string listName = "Test List 123"; + await Verify(newlyAddedList, settings => settings.IgnoreProperty(x => x.Id, x => x.Name)); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - string newListId = Config.Client.ListCreateAsync(listName).Result; + // Add a movie + await TMDbClient.ListAddMovieAsync(listId, IdHelper.Avatar); + await TMDbClient.ListAddMovieAsync(listId, IdHelper.AGoodDayToDieHard); - Assert.False(string.IsNullOrWhiteSpace(newListId)); + Assert.True(await TMDbClient.GetListIsMoviePresentAsync(listId, IdHelper.Avatar)); - GenericList newlyAddedList = Config.Client.GetListAsync(newListId).Result; - Assert.NotNull(newlyAddedList); - Assert.Equal(listName, newlyAddedList.Name); - Assert.Equal("", newlyAddedList.Description); // "" is the default value - Assert.Equal("en", newlyAddedList.Iso_639_1); // en is the default value - Assert.Equal(0, newlyAddedList.ItemCount); - Assert.Equal(0, newlyAddedList.Items.Count); - Assert.False(string.IsNullOrWhiteSpace(newlyAddedList.CreatedBy)); + // Remove a movie + await TMDbClient.ListRemoveMovieAsync(listId, IdHelper.Avatar); - Assert.True(Config.Client.ListDeleteAsync(newListId).Result); - } - - [Fact] - public void TestListDeleteFailure() - { - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - - // Try removing a list with an incorrect id - Assert.False(Config.Client.ListDeleteAsync("bla").Result); - } - - [Fact] - public void TestListAddAndRemoveMovie() - { - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - - // Add a new movie to the list - Assert.True(Config.Client.ListAddMovieAsync(TestListId, IdHelper.EvanAlmighty).Result); - - // Try again, this time it should fail since the list already contains this movie - Assert.False(Config.Client.ListAddMovieAsync(TestListId, IdHelper.EvanAlmighty).Result); - - // Get list and check if the item was added - GenericList listAfterAdd = Config.Client.GetListAsync(TestListId).Result; - Assert.True(listAfterAdd.Items.Any(m => m.Id == IdHelper.EvanAlmighty)); - - // Remove the previously added movie from the list - Assert.True(Config.Client.ListRemoveMovieAsync(TestListId, IdHelper.EvanAlmighty).Result); - - // Get list and check if the item was removed - GenericList listAfterRemove = Config.Client.GetListAsync(TestListId).Result; - Assert.False(listAfterRemove.Items.Any(m => m.Id == IdHelper.EvanAlmighty)); - } - - [Fact] - public void TestListClear() - { - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - - // Add a new movie to the list - Assert.True(Config.Client.ListAddMovieAsync(TestListId, IdHelper.MadMaxFuryRoad).Result); - - // Get list and check if the item was added - GenericList listAfterAdd = Config.Client.GetListAsync(TestListId).Result; - Assert.True(listAfterAdd.Items.Any(m => m.Id == IdHelper.MadMaxFuryRoad)); + Assert.False(await TMDbClient.GetListIsMoviePresentAsync(listId, IdHelper.Avatar)); // Clear the list - Assert.True(Config.Client.ListClearAsync(TestListId).Result); + await TMDbClient.ListClearAsync(listId); - // Get list and check that all items were removed - GenericList listAfterRemove = Config.Client.GetListAsync(TestListId).Result; - Assert.False(listAfterRemove.Items.Any()); + Assert.False(await TMDbClient.GetListIsMoviePresentAsync(listId, IdHelper.AGoodDayToDieHard)); + + // Delete the list + Assert.True(await TMDbClient.ListDeleteAsync(listId)); + } + + [Fact] + public async Task TestListDeleteFailureAsync() + { + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); + + // Try removing a list with an incorrect id + Assert.False(await TMDbClient.ListDeleteAsync("invalid_id")); + } + + private class ListCleanupFixture : IDisposable + { + public void Dispose() + { + TestConfig config = new TestConfig(); + TMDbClient client = config.Client; + + client.SetSessionInformationAsync(config.UserSessionId, SessionType.UserSession).GetAwaiter().GetResult(); + + // Yes, this is only the first page, but that's fine. + // Eventually we'll delete all remaining lists + SearchContainer lists = client.AccountGetListsAsync().GetAwaiter().GetResult(); + + foreach (AccountList list in lists.Results.Where(s => s.Name.StartsWith(EphemeralListPrefix))) + { + client.ListDeleteAsync(list.Id.ToString()).GetAwaiter().GetResult(); + } + } + } + + [CollectionDefinition(nameof(ListFixturesCollection))] + public class ListFixturesCollection : ICollectionFixture + { + // This class has no code, and is never created. Its purpose is simply + // to be the place to apply [CollectionDefinition] and all the + // ICollectionFixture<> interfaces. } } } \ No newline at end of file diff --git a/TMDbLibTests/ClientMovieTests.cs b/TMDbLibTests/ClientMovieTests.cs index a6f7cc1..3df81d6 100644 --- a/TMDbLibTests/ClientMovieTests.cs +++ b/TMDbLibTests/ClientMovieTests.cs @@ -1,8 +1,7 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; -using System.Threading; +using System.Threading.Tasks; using Xunit; using TMDbLib.Objects.Authentication; using TMDbLib.Objects.Changes; @@ -19,11 +18,11 @@ namespace TMDbLibTests { public class ClientMovieTests : TestBase { - private static Dictionary> _methods; + private static readonly Dictionary> Methods; - public ClientMovieTests() + static ClientMovieTests() { - _methods = new Dictionary> + Methods = new Dictionary> { [MovieMethods.AlternativeTitles] = movie => movie.AlternativeTitles, [MovieMethods.Credits] = movie => movie.Credits, @@ -45,300 +44,187 @@ namespace TMDbLibTests } [Fact] - public void TestMoviesExtrasNone() + public async void TestMoviesExtrasNone() { - // We will intentionally ignore errors reg. missing JSON as we do not request it - IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / images", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", " / recommendations", " / external_ids"); + Movie movie = await TMDbClient.GetMovieAsync(IdHelper.AGoodDayToDieHard); - Movie movie = Config.Client.GetMovieAsync(IdHelper.AGoodDayToDieHard).Result; - - Assert.NotNull(movie); - - // TODO: Test all properties - Assert.Equal("A Good Day to Die Hard", movie.Title); + await Verify(movie); // Test all extras, ensure none of them exist - foreach (Func selector in _methods.Values) + foreach (Func selector in Methods.Values) { Assert.Null(selector(movie)); } } [Fact] - public void TestMoviesExtrasExclusive() + public async void TestMoviesExtrasExclusive() { - // Ignore missing json - IgnoreMissingJson("similar.results[array] / media_type"); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); - // We ignore the 'notes' field, as TMDb sometimes leaves it out - IgnoreMissingJson("release_dates.results[array].release_dates[array] / note"); - IgnoreMissingJson(" / id"); - - // We will intentionally ignore errors reg. missing JSON as we do not request it - IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / images", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", "alternative_titles / id", "credits / id", "keywords / id", "release_dates / id", "releases / id", "translations / id", "videos / id", " / recommendations"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - TestMethodsHelper.TestGetExclusive(_methods, (id, extras) => Config.Client.GetMovieAsync(id, extras).Result, IdHelper.AGoodDayToDieHard); + await TestMethodsHelper.TestGetExclusive(Methods, extras => TMDbClient.GetMovieAsync(IdHelper.AGoodDayToDieHard, extras)); } [Fact] - public void TestMoviesImdbExtrasAll() + public async Task TestMoviesImdbExtrasAllAsync() { - // Ignore missing json - IgnoreMissingJson(" / id", " / videos", "alternative_titles / id", "credits / id", "keywords / id", "release_dates / id", "releases / id", "reviews.results[array] / media_type", "translations / id", "similar.results[array] / media_type", " / recommendations"); - - Dictionary> tmpMethods = new Dictionary>(_methods); + Dictionary> tmpMethods = new Dictionary>(Methods); tmpMethods.Remove(MovieMethods.Videos); - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); + await TMDbClient.SetSessionInformationAsync(TestConfig.UserSessionId, SessionType.UserSession); // Account states will only show up if we've done something - Config.Client.MovieSetRatingAsync(IdHelper.TheDarkKnightRises, 5).Sync(); + await TMDbClient.MovieSetRatingAsync(IdHelper.TheDarkKnightRises, 5); - MovieMethods combinedEnum = tmpMethods.Keys.Aggregate((methods, movieMethods) => methods | movieMethods); - Movie item = Config.Client.GetMovieAsync(IdHelper.TheDarkKnightRisesImdb, combinedEnum).Result; - - TestMethodsHelper.TestAllNotNull(tmpMethods, item); + await TestMethodsHelper.TestGetAll(tmpMethods, combined => TMDbClient.GetMovieAsync(IdHelper.TheDarkKnightRisesImdb, combined), movie => Verify(movie)); } [Fact] - public void TestMoviesExtrasAll() + public async void TestMoviesLanguage() { - // We ignore the 'notes' field, as TMDb sometimes leaves it out - IgnoreMissingJson("release_dates.results[array].release_dates[array] / note"); - - IgnoreMissingJson("similar.results[array] / media_type"); - IgnoreMissingJson(" / id", "alternative_titles / id", "credits / id", "keywords / id", "release_dates / id", "releases / id", "translations / id", "videos / id", " / recommendations"); - - Config.Client.SetSessionInformation(Config.UserSessionId, SessionType.UserSession); - MovieMethods combinedEnum = _methods.Keys.Aggregate((methods, movieMethods) => methods | movieMethods); - Movie item = Config.Client.GetMovieAsync(IdHelper.AGoodDayToDieHard, combinedEnum).Result; - - TestMethodsHelper.TestAllNotNull(_methods, item); - } - - [Fact] - public void TestMoviesLanguage() - { - IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / images", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", " / recommendations"); - - Movie movie = Config.Client.GetMovieAsync(IdHelper.AGoodDayToDieHard).Result; - Movie movieItalian = Config.Client.GetMovieAsync(IdHelper.AGoodDayToDieHard, "it").Result; + Movie movie = await TMDbClient.GetMovieAsync(IdHelper.AGoodDayToDieHard); + Movie movieItalian = await TMDbClient.GetMovieAsync(IdHelper.AGoodDayToDieHard, "it"); Assert.NotNull(movie); Assert.NotNull(movieItalian); Assert.Equal("A Good Day to Die Hard", movie.Title); Assert.NotEqual(movie.Title, movieItalian.Title); + } - // Test all extras, ensure none of them exist - foreach (Func selector in _methods.Values) + [Fact] + public async void TestMoviesGetMovieAlternativeTitles() + { + AlternativeTitles respUs = await TMDbClient.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard, "US"); + AlternativeTitles respFrench = await TMDbClient.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard, "FR"); + + TMDbClient.DefaultCountry = "CA"; + + AlternativeTitles respCaDefault = await TMDbClient.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard); + + await Verify(new { - Assert.Null(selector(movie)); - Assert.Null(selector(movieItalian)); - } + respUs, + respFrench, + respCaDefault + }); } [Fact] - public void TestMoviesGetMovieAlternativeTitles() + public async void TestMoviesGetMovieReleaseDates() { - AlternativeTitles respUs = Config.Client.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard, "US").Result; - Assert.NotNull(respUs); + ResultContainer resp = await TMDbClient.GetMovieReleaseDatesAsync(IdHelper.AGoodDayToDieHard); - AlternativeTitles respFrench = Config.Client.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard, "FR").Result; - Assert.NotNull(respFrench); - - Assert.False(respUs.Titles.Any(s => s.Title == "Duro de matar 5")); - Assert.True(respFrench.Titles.Any(s => s.Title == "Die Hard 5 - Belle Journée Pour mourir")); - - Assert.True(respUs.Titles.All(s => s.Iso_3166_1 == "US")); - Assert.True(respFrench.Titles.All(s => s.Iso_3166_1 == "FR")); + await Verify(resp); } [Fact] - public void TestMoviesGetMovieReleaseDates() + public async void TestMoviesGetMovieCasts() { - // We ignore the 'notes' field, as TMDb sometimes leaves it out - IgnoreMissingJson("results[array].release_dates[array] / note"); - - ResultContainer resp = Config.Client.GetMovieReleaseDatesAsync(IdHelper.AGoodDayToDieHard).Result; + Credits resp = await TMDbClient.GetMovieCreditsAsync(IdHelper.AGoodDayToDieHard); Assert.NotNull(resp); - ReleaseDatesContainer releasesUs = resp.Results.SingleOrDefault(s => s.Iso_3166_1 == "US"); - Assert.NotNull(releasesUs); - Assert.Equal(1, releasesUs.ReleaseDates.Count); + Cast cast = resp.Cast.Single(s => s.CreditId == "52fe4751c3a36847f812f049"); + Crew crew = resp.Crew.Single(s => s.CreditId == "5336b04a9251417db4000c80"); - ReleaseDateItem singleRelease = releasesUs.ReleaseDates.First(); + await Verify(new + { + cast, + crew + }); - Assert.Equal("R", singleRelease.Certification); - Assert.Equal(string.Empty, singleRelease.Iso_639_1); - Assert.Equal(string.Empty, singleRelease.Note); - Assert.Equal(DateTime.Parse("2013-02-14T00:00:00.000Z").ToUniversalTime(), singleRelease.ReleaseDate); - Assert.Equal(ReleaseDateType.Theatrical, singleRelease.Type); + TestImagesHelpers.TestImagePaths(resp.Cast.Select(s => s.ProfilePath).Where(s => s != null)); + TestImagesHelpers.TestImagePaths(resp.Crew.Select(s => s.ProfilePath).Where(s => s != null)); } [Fact] - public void TestMoviesGetMovieAlternativeTitlesCountry() + public async void TestMoviesGetExternalIds() { - AlternativeTitles respUs = Config.Client.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard, "US").Result; - Assert.NotNull(respUs); + ExternalIdsMovie externalIds = await TMDbClient.GetMovieExternalIdsAsync(IdHelper.BladeRunner2049); - Config.Client.DefaultCountry = "US"; - - AlternativeTitles respUs2 = Config.Client.GetMovieAlternativeTitlesAsync(IdHelper.AGoodDayToDieHard).Result; - Assert.NotNull(respUs2); - - Assert.Equal(respUs.Titles.Count, respUs2.Titles.Count); + await Verify(externalIds); } [Fact] - public void TestMoviesGetMovieCasts() + public async void TestMoviesGetMovieImages() { - Credits resp = Config.Client.GetMovieCreditsAsync(IdHelper.AGoodDayToDieHard).Result; - Assert.NotNull(resp); + ImagesWithId resp = await TMDbClient.GetMovieImagesAsync(IdHelper.AGoodDayToDieHard); - Cast cast = resp.Cast.SingleOrDefault(s => s.Name == "Bruce Willis"); - Assert.NotNull(cast); + TestImagesHelpers.TestImagePaths(resp); - Assert.Equal(1, cast.CastId); - Assert.Equal("John McClane", cast.Character); - Assert.NotEmpty(cast.CreditId); - Assert.Equal(62, cast.Id); - Assert.Equal("Bruce Willis", cast.Name); - Assert.Equal(0, cast.Order); - Assert.True(cast.Popularity > 0); - Assert.Equal("Bruce Willis", cast.OriginalName); - Assert.Equal("Acting", cast.KnownForDepartment); - Assert.True(TestImagesHelpers.TestImagePath(cast.ProfilePath), "cast.ProfilePath was not a valid image path, was: " + cast.ProfilePath); + ImageData backdrop = resp.Backdrops.Single(s => s.FilePath == "/js3J4SBiRfLvmRzaHoTA2tpKROw.jpg"); + ImageData poster = resp.Posters.Single(s => s.FilePath == "/c4G6lW5hAWmwveThfLSqs52yHB1.jpg"); - Crew crew = resp.Crew.SingleOrDefault(s => s.Name == "Marco Beltrami"); - Assert.NotNull(crew); - - Assert.NotEmpty(crew.CreditId); - Assert.Equal("Sound", crew.Department); - Assert.Equal(7229, crew.Id); - Assert.Equal("Original Music Composer", crew.Job); - Assert.Equal("Marco Beltrami", crew.Name); - Assert.True(TestImagesHelpers.TestImagePath(crew.ProfilePath), "crew.ProfilePath was not a valid image path, was: " + crew.ProfilePath); + await Verify(new + { + backdrop, + poster + }); } [Fact] - public void TestMoviesGetExternalIds() + public async void TestMoviesGetMovieImagesWithImageLanguage() { - ExternalIdsMovie externalIds = Config.Client.GetMovieExternalIdsAsync(IdHelper.BladeRunner2049).Result; + ImagesWithId images = await TMDbClient.GetMovieImagesAsync(IdHelper.AGoodDayToDieHard, "en-US", "en"); - Assert.NotNull(externalIds); - Assert.Equal(335984, externalIds.Id); - Assert.Equal("tt1856101", externalIds.ImdbId); - Assert.Equal("BladeRunner2049", externalIds.FacebookId); - Assert.Equal("bladerunner", externalIds.TwitterId); - Assert.Equal("bladerunnermovie", externalIds.InstagramId); + TestImagesHelpers.TestImagePaths(images); + + ImageData backdrop = images.Backdrops.Single(s => s.FilePath == "/js3J4SBiRfLvmRzaHoTA2tpKROw.jpg"); + ImageData poster = images.Posters.Single(s => s.FilePath == "/9Zq88w35f1PpM22TIbf2amtjHD6.jpg"); + + await Verify(new + { + backdrop, + poster + }); } [Fact] - public void TestMoviesGetMovieImages() + public async void TestMoviesGetMovieWithImageLanguage() { - ImagesWithId resp = Config.Client.GetMovieImagesAsync(IdHelper.AGoodDayToDieHard).Result; - Assert.NotNull(resp); + Movie resp = await TMDbClient.GetMovieAsync(IdHelper.Avatar, "de-DE", "de", MovieMethods.Images); + Images images = resp.Images; - ImageData backdrop = resp.Backdrops.SingleOrDefault(s => s.FilePath == "/17zArExB7ztm6fjUXZwQWgGMC9f.jpg"); - Assert.NotNull(backdrop); + TestImagesHelpers.TestImagePaths(images); - Assert.True(Math.Abs(1.77777777777778 - backdrop.AspectRatio) < double.Epsilon); - Assert.True(TestImagesHelpers.TestImagePath(backdrop.FilePath), "backdrop.FilePath was not a valid image path, was: " + backdrop.FilePath); - Assert.Equal(1080, backdrop.Height); - Assert.Equal("xx", backdrop.Iso_639_1); - Assert.True(backdrop.VoteAverage > 0); - Assert.True(backdrop.VoteCount > 0); - Assert.Equal(1920, backdrop.Width); + ImageData backdrop = images.Backdrops.Single(s => s.FilePath == "/4U9fN2jsQ94GQfDGeLEe8UaReRO.jpg"); + ImageData poster = images.Posters.Single(s => s.FilePath == "/8VV4YUwOGxgolFZTo2SgNwsfznR.jpg"); - ImageData poster = resp.Posters.SingleOrDefault(s => s.FilePath == "/c2SQMd00CCGTiDxGXVqA2J9lmzF.jpg"); - Assert.NotNull(poster); - - Assert.True(Math.Abs(0.666666666666667 - poster.AspectRatio) < double.Epsilon); - Assert.True(TestImagesHelpers.TestImagePath(poster.FilePath), "poster.FilePath was not a valid image path, was: " + poster.FilePath); - Assert.Equal(1500, poster.Height); - Assert.Equal("en", poster.Iso_639_1); - Assert.True(poster.VoteAverage > 0); - Assert.True(poster.VoteCount > 0); - Assert.Equal(1000, poster.Width); + await Verify(new + { + backdrop, + poster + }); } [Fact] - public void TestMoviesGetMovieImagesWithImageLanguage() + public async void TestMoviesGetMovieKeywords() { - ImagesWithId resp = Config.Client.GetMovieImagesAsync(IdHelper.AGoodDayToDieHard, language: "en-US", includeImageLanguage: "en").Result; + KeywordsContainer resp = await TMDbClient.GetMovieKeywordsAsync(IdHelper.AGoodDayToDieHard); - Assert.True(resp.Backdrops.Count > 0); - Assert.True(resp.Posters.Count > 0); + await Verify(resp); } [Fact] - public void TestMoviesGetMovieWithImageLanguage() + public async void TestMoviesGetMovieReleases() { - IgnoreMissingJson(" / account_states", " / alternative_titles", " / changes", " / credits", " / keywords", " / lists", " / release_dates", " / releases", " / reviews", " / similar", " / translations", " / videos", " / recommendations", " / external_ids"); + Releases resp = await TMDbClient.GetMovieReleasesAsync(IdHelper.AGoodDayToDieHard); - Movie resp = Config.Client.GetMovieAsync(IdHelper.Avatar, language: "en-US", includeImageLanguage: "en", extraMethods: MovieMethods.Images).Result; - - Assert.True(resp.Images.Backdrops.Count > 0); - Assert.True(resp.Images.Backdrops.All(b => b.Iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase))); - Assert.True(resp.Images.Posters.Count > 0); - Assert.True(resp.Images.Posters.All(p => p.Iso_639_1.Equals("en", StringComparison.OrdinalIgnoreCase))); + await Verify(resp); } [Fact] - public void TestMoviesGetMovieKeywords() + public async void TestMoviesGetMovieVideos() { - KeywordsContainer resp = Config.Client.GetMovieKeywordsAsync(IdHelper.AGoodDayToDieHard).Result; - Assert.NotNull(resp); + ResultContainer