public async Task <TraktResponse <ITraktDevice> > GetDeviceAsync(DeviceRequest request, CancellationToken cancellationToken = default) { try { request.Validate(); ExtendedHttpRequestMessage requestMessage = await _requestMessageBuilder.Reset(request) .WithRequestBody(request.RequestBody) .DisableAPIVersionHeader() .DisableAPIClientIdHeader() .Build().ConfigureAwait(false); HttpResponseMessage responseMessage = await _client.HttpClientProvider.GetHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); if (!responseMessage.IsSuccessStatusCode) { await ResponseErrorHandler.HandleErrorsAsync(requestMessage, responseMessage, isDeviceRequest : true, cancellationToken : cancellationToken).ConfigureAwait(false); } DebugAsserter.AssertResponseMessageIsNotNull(responseMessage); DebugAsserter.AssertHttpResponseCodeIsExpected(responseMessage.StatusCode, HttpStatusCode.OK, DebugAsserter.SINGLE_ITEM_RESPONSE_PRECONDITION_INVALID_STATUS_CODE); Stream responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); IObjectJsonReader <ITraktDevice> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktDevice>(); ITraktDevice device = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var response = new TraktResponse <ITraktDevice>() { Value = device, HasValue = device != null, IsSuccess = device != null }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } _client.Authentication.Device = device; return(response); } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <ITraktDevice> { IsSuccess = false, Exception = ex }); } }
private async Task <TraktResponse <TResponseContentType> > QuerySingleItemAsync <TResponseContentType>(ExtendedHttpRequestMessage requestMessage, bool isCheckinRequest = false, CancellationToken cancellationToken = default) { HttpResponseMessage responseMessage = null; try { responseMessage = await ExecuteRequestAsync(requestMessage, isCheckinRequest, cancellationToken).ConfigureAwait(false); DebugAsserter.AssertResponseMessageIsNotNull(responseMessage); DebugAsserter.AssertHttpResponseCodeIsNotExpected(responseMessage.StatusCode, HttpStatusCode.NoContent, DebugAsserter.SINGLE_ITEM_RESPONSE_PRECONDITION_INVALID_STATUS_CODE); Stream responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); DebugAsserter.AssertResponseContentStreamIsNotNull(responseContentStream); IObjectJsonReader <TResponseContentType> objectJsonReader = JsonFactoryContainer.CreateObjectReader <TResponseContentType>(); DebugAsserter.AssertObjectJsonReaderIsNotNull(objectJsonReader); TResponseContentType contentObject = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); bool hasValue = !EqualityComparer <TResponseContentType> .Default.Equals(contentObject, default); var response = new TraktResponse <TResponseContentType> { IsSuccess = true, HasValue = hasValue, Value = contentObject }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } return(response); } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <TResponseContentType> { IsSuccess = false, Exception = ex }); } finally { responseMessage?.Dispose(); } }
public static Task <TObjectType> DeserializeAsync <TObjectType>(string json, CancellationToken cancellationToken = default) { if (json == null) { throw new ArgumentNullException(nameof(json), "json string must not be null"); } if (json.Length == 0) { throw new ArgumentException(nameof(json), "json string must not be empty"); } IObjectJsonReader <TObjectType> objectJsonReader = JsonFactoryContainer.CreateObjectReader <TObjectType>(); return(objectJsonReader.ReadObjectAsync(json, cancellationToken)); }
private static async Task HandleRateLimitErrorAsync(ResponseErrorParameters errorParameters, CancellationToken cancellationToken = default) { string requestUrl = errorParameters.Url; string requestBody = errorParameters.RequestBody; string responseBody = errorParameters.ResponseBody; string reasonPhrase = errorParameters.ServerReasonPhrase; if (errorParameters.IsInAuthorizationPolling) { // Authorization Polling - Slow Down throw new TraktAuthenticationDeviceException("Slow Down - your app is polling too quickly") { StatusCode = (HttpStatusCode)429, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; } ITraktRateLimitInfo rateLimitInfo = null; try { if (!string.IsNullOrEmpty(errorParameters.Headers.RateLimit)) { IObjectJsonReader <ITraktRateLimitInfo> rateLimitInfoReader = JsonFactoryContainer.CreateObjectReader <ITraktRateLimitInfo>(); rateLimitInfo = await rateLimitInfoReader.ReadObjectAsync(errorParameters.Headers.RateLimit, cancellationToken).ConfigureAwait(false); } } catch (Exception ex) { throw new TraktException("json convert exception", ex); } throw new TraktRateLimitException { RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase, RateLimitInfo = rateLimitInfo, RetryAfter = errorParameters.Headers.RetryAfter }; }
public static Task <ITraktAuthorization> DeserializeAsync(string authorizationJson, CancellationToken cancellationToken = default) { if (authorizationJson == null) { throw new ArgumentNullException(nameof(authorizationJson), "authorization json string must not be null"); } if (authorizationJson.Length == 0) { throw new ArgumentException(nameof(authorizationJson), "authorization json string must not be empty"); } IObjectJsonReader <ITraktAuthorization> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktAuthorization>(); AuthorizationObjectJsonReader authorizationObjectJsonReader = (objectJsonReader as AuthorizationObjectJsonReader); authorizationObjectJsonReader.CompleteDeserialization = true; return(authorizationObjectJsonReader.ReadObjectAsync(authorizationJson, cancellationToken)); }
private async Task <TraktResponse <ITraktAuthorization> > ExecuteAuthorizationRequestAsync <TRequestBodyType>(IPostRequest <ITraktAuthorization, TRequestBodyType> request, bool isRefreshRequest, CancellationToken cancellationToken = default) where TRequestBodyType : IRequestBody { try { request.Validate(); ExtendedHttpRequestMessage requestMessage = await _requestMessageBuilder.Reset(request) .WithRequestBody(request.RequestBody) .DisableAPIVersionHeader() .DisableAPIClientIdHeader() .Build().ConfigureAwait(false); HttpResponseMessage responseMessage = await _client.HttpClientProvider.GetHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); HttpStatusCode responseCode = responseMessage.StatusCode; Stream responseContentStream; if (responseCode == HttpStatusCode.OK) { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); IObjectJsonReader <ITraktAuthorization> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktAuthorization>(); ITraktAuthorization traktAuthorization = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var response = new TraktResponse <ITraktAuthorization>() { Value = traktAuthorization, HasValue = traktAuthorization != null, IsSuccess = traktAuthorization != null }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } _client.Authentication.Authorization = traktAuthorization; return(response); } else if (responseCode == HttpStatusCode.Unauthorized) // Invalid code { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); IObjectJsonReader <ITraktError> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktError>(); ITraktError traktError = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var errorMessage = traktError != null ? ($"error on {(isRefreshRequest ? "refreshing" : "retrieving")} oauth access token\nerror: {traktError.Error}\ndescription: {traktError.Description}") : "unknown error"; throw new TraktAuthenticationOAuthException(errorMessage) { StatusCode = responseCode, RequestUrl = requestMessage.Url, RequestBody = requestMessage.RequestBodyJson, ServerReasonPhrase = responseMessage.ReasonPhrase }; } await ResponseErrorHandler.HandleErrorsAsync(requestMessage, responseMessage, isAuthorizationRequest : true, cancellationToken : cancellationToken).ConfigureAwait(false); } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <ITraktAuthorization> { IsSuccess = false, Exception = ex }); } return(new TraktResponse <ITraktAuthorization>()); }
public async Task <TraktResponse <ITraktAuthorization> > PollForAuthorizationAsync(AuthorizationPollRequest request, CancellationToken cancellationToken = default) { try { request.Validate(); ExtendedHttpRequestMessage requestMessage = await _requestMessageBuilder.Reset(request) .WithRequestBody(request.RequestBody) .DisableAPIVersionHeader() .DisableAPIClientIdHeader() .Build().ConfigureAwait(false); HttpResponseMessage responseMessage; Stream responseContentStream; HttpStatusCode responseCode; string reasonPhrase = string.Empty; uint totalExpiredSeconds = 0; ITraktDevice device = request.RequestBody.Device; IObjectJsonReader <ITraktAuthorization> objectJsonReader = JsonFactoryContainer.CreateObjectReader <ITraktAuthorization>(); while (totalExpiredSeconds < device.ExpiresInSeconds) { responseMessage = await _client.HttpClientProvider.GetHttpClient().SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); responseCode = responseMessage.StatusCode; reasonPhrase = responseMessage.ReasonPhrase; if (responseCode == HttpStatusCode.OK) // Success { responseContentStream = await ResponseMessageHelper.GetResponseContentStreamAsync(responseMessage).ConfigureAwait(false); ITraktAuthorization traktAuthorization = await objectJsonReader.ReadObjectAsync(responseContentStream, cancellationToken).ConfigureAwait(false); var response = new TraktResponse <ITraktAuthorization>() { Value = traktAuthorization, HasValue = traktAuthorization != null, IsSuccess = traktAuthorization != null }; if (responseMessage.Headers != null) { ResponseHeaderParser.ParseResponseHeaderValues(response, responseMessage.Headers); } _client.Authentication.Authorization = traktAuthorization; return(response); } else if (responseCode == HttpStatusCode.BadRequest) // Pending { await Task.Delay((int)device.IntervalInMilliseconds).ConfigureAwait(false); totalExpiredSeconds += device.IntervalInSeconds; requestMessage = await _requestMessageBuilder.Reset(request).WithRequestBody(request.RequestBody).Build().ConfigureAwait(false); continue; } await ResponseErrorHandler.HandleErrorsAsync(requestMessage, responseMessage, isInAuthorizationPolling : true, cancellationToken : cancellationToken).ConfigureAwait(false); break; } throw new TraktAuthenticationDeviceException("unknown exception") { RequestUrl = requestMessage.Url, RequestBody = requestMessage.RequestBodyJson, ServerReasonPhrase = reasonPhrase }; } catch (Exception ex) { if (_client.Configuration.ThrowResponseExceptions) { throw; } return(new TraktResponse <ITraktAuthorization> { IsSuccess = false, Exception = ex }); } }
private static async Task HandleUnknownErrorAsync(ResponseErrorParameters errorParameters, CancellationToken cancellationToken = default) { string requestUrl = errorParameters.Url; string requestBody = errorParameters.RequestBody; string responseBody = errorParameters.ResponseBody; string reasonPhrase = errorParameters.ServerReasonPhrase; if (errorParameters.IsDeviceRequest || errorParameters.IsInAuthorizationPolling) { throw new TraktAuthenticationDeviceException("unknown exception") { StatusCode = errorParameters.StatusCode, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; } else if (errorParameters.IsAuthorizationRequest) { throw new TraktAuthenticationOAuthException("unknown exception") { StatusCode = errorParameters.StatusCode, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; } else if (errorParameters.IsAuthorizationRevoke) { throw new TraktAuthenticationException("unknown exception") { StatusCode = errorParameters.StatusCode, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; } ITraktError error = null; try { IObjectJsonReader <ITraktError> errorReader = JsonFactoryContainer.CreateObjectReader <ITraktError>(); error = await errorReader.ReadObjectAsync(responseBody, cancellationToken).ConfigureAwait(false); } catch (Exception ex) { throw new TraktException("json convert exception", ex); } var errorMessage = (error == null || string.IsNullOrEmpty(error.Description)) ? $"Trakt API error without content. Response status code was {(int)errorParameters.StatusCode}" : error.Description; throw new TraktException(errorMessage) { StatusCode = errorParameters.StatusCode, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; }
private static async Task HandleConflictErrorAsync(ResponseErrorParameters errorParameters, CancellationToken cancellationToken = default) { string requestUrl = errorParameters.Url; string requestBody = errorParameters.RequestBody; string responseBody = errorParameters.ResponseBody; string reasonPhrase = errorParameters.ServerReasonPhrase; if (errorParameters.IsCheckinRequest) { ITraktCheckinPostErrorResponse errorResponse = null; if (!string.IsNullOrEmpty(errorParameters.ResponseBody)) { IObjectJsonReader <ITraktCheckinPostErrorResponse> errorResponseReader = JsonFactoryContainer.CreateObjectReader <ITraktCheckinPostErrorResponse>(); errorResponse = await errorResponseReader.ReadObjectAsync(errorParameters.ResponseBody, cancellationToken).ConfigureAwait(false); } throw new TraktCheckinException("checkin is already in progress") { RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase, ExpiresAt = errorResponse?.ExpiresAt }; } else if (errorParameters.IsInAuthorizationPolling) { // Authorization Polling - Already Used throw new TraktAuthenticationDeviceException("Already Used - user already approved this code") { StatusCode = errorParameters.StatusCode, RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; } throw new TraktConflictException { RequestUrl = requestUrl, RequestBody = requestBody, Response = responseBody, ServerReasonPhrase = reasonPhrase }; }