Example #1
0
 public async Task Test_ErrorObjectJsonWriter_WriteObject_JsonWriter_Exceptions()
 {
     var         traktJsonWriter = new ErrorObjectJsonWriter();
     ITraktError traktError      = new TraktError();
     Func <Task> action          = () => traktJsonWriter.WriteObjectAsync(default(JsonTextWriter), traktError);
     await action.Should().ThrowAsync <ArgumentNullException>();
 }
Example #2
0
        public void Test_TraktError_Default_Constructor()
        {
            var traktError = new TraktError();

            traktError.Error.Should().BeNull();
            traktError.Description.Should().BeNull();
        }
Example #3
0
        public void TestTraktErrorDefaultConstructor()
        {
            var error = new TraktError();

            error.Error.Should().BeNullOrEmpty();
            error.Description.Should().BeNullOrEmpty();
        }
Example #4
0
        public void Test_ErrorObjectJsonWriter_WriteObject_StringWriter_Exceptions()
        {
            var                   traktJsonWriter = new ErrorObjectJsonWriter();
            ITraktError           traktError      = new TraktError();
            Func <Task <string> > action          = () => traktJsonWriter.WriteObjectAsync(default(StringWriter), traktError);

            action.Should().Throw <ArgumentNullException>();
        }
        public async Task Test_ErrorObjectJsonWriter_WriteObject_Object_Empty()
        {
            ITraktError traktError = new TraktError();

            var traktJsonWriter = new ErrorObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktError);
            json.Should().Be("{}");
        }
        public async Task Test_ErrorObjectJsonWriter_WriteObject_Object_Only_Description_Property()
        {
            ITraktError traktError = new TraktError
            {
                Description = "error description"
            };

            var traktJsonWriter = new ErrorObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktError);
            json.Should().Be(@"{""error_description"":""error description""}");
        }
Example #7
0
        public async Task Test_ErrorObjectJsonWriter_WriteObject_StringWriter_Empty()
        {
            ITraktError traktError = new TraktError();

            using (var stringWriter = new StringWriter())
            {
                var    traktJsonWriter = new ErrorObjectJsonWriter();
                string json            = await traktJsonWriter.WriteObjectAsync(stringWriter, traktError);

                json.Should().Be("{}");
            }
        }
        public async Task Test_ErrorObjectJsonWriter_WriteObject_Object_Complete()
        {
            ITraktError traktError = new TraktError
            {
                Error = "error",
                Description = "error description"
            };

            var traktJsonWriter = new ErrorObjectJsonWriter();
            string json = await traktJsonWriter.WriteObjectAsync(traktError);
            json.Should().Be(@"{""error"":""error"",""error_description"":""error description""}");
        }
Example #9
0
        public async Task Test_ErrorObjectJsonWriter_WriteObject_JsonWriter_Empty()
        {
            ITraktError traktError = new TraktError();

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    var traktJsonWriter = new ErrorObjectJsonWriter();
                    await traktJsonWriter.WriteObjectAsync(jsonWriter, traktError);

                    stringWriter.ToString().Should().Be("{}");
                }
        }
        public TraktAuthenticationModule_Tests()
        {
            MockDevice = new TraktDevice
            {
                DeviceCode        = MOCK_DEVICE_CODE,
                UserCode          = MOCK_DEVICE_USER_CODE,
                VerificationUrl   = DEVICE_VERIFICATION_URL,
                ExpiresInSeconds  = DEVICE_EXPIRES_IN_SECONDS,
                IntervalInSeconds = DEVICE_INTERVAL_IN_SECONDS
            };

            MockAuthorization = new TraktAuthorization
            {
                CreatedAtTimestamp = TestUtility.CalculateTimestamp(TestConstants.CREATED_AT),
                AccessToken        = TestConstants.MOCK_ACCESS_TOKEN,
                TokenType          = TraktAccessTokenType.Bearer,
                ExpiresInSeconds   = 7200,
                RefreshToken       = TestConstants.MOCK_REFRESH_TOKEN,
                Scope = TraktAccessScope.Public
            };

            TraktClientId     = TestConstants.TRAKT_CLIENT_ID;
            TraktClientSecret = TestConstants.TRAKT_CLIENT_SECRET;
            TraktRedirectUri  = TestConstants.DEFAULT_REDIRECT_URI;

            MockAuthorizationPostContent = $"{{ \"code\": \"{MOCK_AUTH_CODE}\", \"client_id\": \"{TraktClientId}\", " +
                                           $"\"client_secret\": \"{TraktClientSecret}\", \"redirect_uri\": " +
                                           $"\"{TraktRedirectUri}\", \"grant_type\": \"authorization_code\" }}";

            MockAuthorizationRefreshPostContent = $"{{ \"refresh_token\": \"{TestConstants.MOCK_REFRESH_TOKEN}\", \"client_id\": \"{TraktClientId}\", " +
                                                  $"\"client_secret\": \"{TraktClientSecret}\", \"redirect_uri\": " +
                                                  $"\"{TraktRedirectUri}\", \"grant_type\": \"refresh_token\" }}";

            MockAuthorizationRevokePostContent = $"{{ \"token\": \"{TestConstants.MOCK_ACCESS_TOKEN}\", \"client_id\": \"{TraktClientId}\"," +
                                                 $" \"client_secret\": \"{TraktClientSecret}\" }}";

            MockAuthorizationPollingPostContent = $"{{ \"code\": \"{MOCK_DEVICE_CODE}\", \"client_id\": \"{TraktClientId}\", \"client_secret\": \"{TraktClientSecret}\" }}";

            MockAuthorizationError = new TraktError
            {
                Error       = "invalid_grant",
                Description = "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
            };

            MockAuthorizationErrorMessage = $"error on retrieving oauth access token\nerror: {MockAuthorizationError.Error}\n" +
                                            $"description: {MockAuthorizationError.Description}";

            MockAuthorizationRefreshErrorMessage = $"error on refreshing oauth access token\nerror: {MockAuthorizationError.Error}\n" +
                                                   $"description: {MockAuthorizationError.Description}";
        }
Example #11
0
        public async Task Test_ErrorObjectJsonWriter_WriteObject_StringWriter_Only_Error_Property()
        {
            ITraktError traktError = new TraktError
            {
                Error = "error"
            };

            using (var stringWriter = new StringWriter())
            {
                var    traktJsonWriter = new ErrorObjectJsonWriter();
                string json            = await traktJsonWriter.WriteObjectAsync(stringWriter, traktError);

                json.Should().Be(@"{""error"":""error""}");
            }
        }
Example #12
0
        public async Task Test_ErrorObjectJsonWriter_WriteObject_JsonWriter_Only_Description_Property()
        {
            ITraktError traktError = new TraktError
            {
                Description = "error description"
            };

            using (var stringWriter = new StringWriter())
                using (var jsonWriter = new JsonTextWriter(stringWriter))
                {
                    var traktJsonWriter = new ErrorObjectJsonWriter();
                    await traktJsonWriter.WriteObjectAsync(jsonWriter, traktError);

                    stringWriter.ToString().Should().Be(@"{""error_description"":""error description""}");
                }
        }
Example #13
0
        public override async Task <ITraktError> ReadObjectAsync(JsonTextReader jsonReader, CancellationToken cancellationToken = default)
        {
            if (jsonReader == null)
            {
                return(await Task.FromResult(default(ITraktError)));
            }

            if (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.StartObject)
            {
                ITraktError traktError = new TraktError();

                while (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.PropertyName)
                {
                    var propertyName = jsonReader.Value.ToString();

                    switch (propertyName)
                    {
                    case JsonProperties.ERROR_PROPERTY_NAME_ERROR:
                        traktError.Error = await jsonReader.ReadAsStringAsync(cancellationToken);

                        break;

                    case JsonProperties.ERROR_PROPERTY_NAME_ERROR_DESCRIPTION:
                        traktError.Description = await jsonReader.ReadAsStringAsync(cancellationToken);

                        break;

                    default:
                        await JsonReaderHelper.ReadAndIgnoreInvalidContentAsync(jsonReader, cancellationToken);

                        break;
                    }
                }

                return(traktError);
            }

            return(await Task.FromResult(default(ITraktError)));
        }
Example #14
0
        private async Task ErrorHandling(HttpResponseMessage response)
        {
            var responseContent = string.Empty;

            if (response.Content != null)
            {
                responseContent = await response.Content.ReadAsStringAsync();
            }

            var code = response.StatusCode;

            switch (code)
            {
            case HttpStatusCode.NotFound:
            {
                if (RequestObjectType.HasValue)
                {
                    switch (RequestObjectType.Value)
                    {
                    case TraktRequestObjectType.Episodes:
                        throw new TraktEpisodeNotFoundException(Id, Season, Episode)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Seasons:
                        throw new TraktSeasonNotFoundException(Id, Season)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Shows:
                        throw new TraktShowNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Movies:
                        throw new TraktMovieNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.People:
                        throw new TraktPersonNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Comments:
                        throw new TraktCommentNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Lists:
                        throw new TraktListNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };

                    case TraktRequestObjectType.Unspecified:
                    default:
                        throw new TraktObjectNotFoundException(Id)
                              {
                                  RequestUrl         = Url,
                                  RequestBody        = RequestBodyJson,
                                  Response           = responseContent,
                                  ServerReasonPhrase = response.ReasonPhrase
                              };
                    }
                }

                throw new TraktNotFoundException($"Resource not found - Reason Phrase: {response.ReasonPhrase}");
            }

            case HttpStatusCode.BadRequest:
                throw new TraktBadRequestException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.Unauthorized:
                throw new TraktAuthorizationException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.Forbidden:
                throw new TraktForbiddenException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.MethodNotAllowed:
                throw new TraktMethodNotFoundException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.Conflict:
                if (IsCheckinRequest)
                {
                    TraktCheckinPostErrorResponse errorResponse = null;

                    if (!string.IsNullOrEmpty(responseContent))
                    {
                        errorResponse = Json.Deserialize <TraktCheckinPostErrorResponse>(responseContent);
                    }

                    throw new TraktCheckinException("checkin is already in progress")
                          {
                              RequestUrl         = Url,
                              RequestBody        = RequestBodyJson,
                              Response           = responseContent,
                              ServerReasonPhrase = response.ReasonPhrase,
                              ExpiresAt          = errorResponse?.ExpiresAt
                          };
                }

                throw new TraktConflictException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.InternalServerError:
                throw new TraktServerException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case HttpStatusCode.BadGateway:
                throw new TraktBadGatewayException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case (HttpStatusCode)412:
                throw new TraktPreconditionFailedException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case (HttpStatusCode)422:
                throw new TraktValidationException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case (HttpStatusCode)429:
                throw new TraktRateLimitException()
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case (HttpStatusCode)503:
            case (HttpStatusCode)504:
                throw new TraktServerUnavailableException("Service Unavailable - server overloaded (try again in 30s)")
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          StatusCode         = HttpStatusCode.ServiceUnavailable,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };

            case (HttpStatusCode)520:
            case (HttpStatusCode)521:
            case (HttpStatusCode)522:
                throw new TraktServerUnavailableException("Service Unavailable - Cloudflare error")
                      {
                          RequestUrl         = Url,
                          RequestBody        = RequestBodyJson,
                          StatusCode         = HttpStatusCode.ServiceUnavailable,
                          Response           = responseContent,
                          ServerReasonPhrase = response.ReasonPhrase
                      };
            }

            TraktError error = null;

            try
            {
                error = Json.Deserialize <TraktError>(responseContent);
            }
            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)code}"
                                    : error.Description;

            throw new TraktException(errorMessage)
                  {
                      RequestUrl         = Url,
                      RequestBody        = RequestBodyJson,
                      Response           = responseContent,
                      ServerReasonPhrase = response.ReasonPhrase
                  };
        }