public void Test_TraktAuthorization_IsExpired() { var origin = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime utcNow = DateTime.UtcNow; const long ticksPerSecond = TimeSpan.TicksPerSecond; long utcNowSeconds = utcNow.Ticks / ticksPerSecond; long originSeconds = origin.Ticks / ticksPerSecond; long differenceSeconds = utcNowSeconds - originSeconds; var traktAuthorization = new TraktAuthorization { CreatedAtTimestamp = (ulong)differenceSeconds }; traktAuthorization.IsExpired.Should().BeTrue(); traktAuthorization.AccessToken = string.Empty; traktAuthorization.IsExpired.Should().BeTrue(); traktAuthorization.AccessToken = "access token"; traktAuthorization.IsExpired.Should().BeTrue(); traktAuthorization.AccessToken = "accessToken"; traktAuthorization.IsExpired.Should().BeTrue(); traktAuthorization.ExpiresInSeconds = 1; traktAuthorization.IsExpired.Should().BeFalse(); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_StringWriter_Exceptions() { var traktJsonWriter = new AuthorizationObjectJsonWriter(); ITraktAuthorization traktAuthorization = new TraktAuthorization(); Func <Task <string> > action = () => traktJsonWriter.WriteObjectAsync(default(StringWriter), traktAuthorization); await action.Should().ThrowAsync <ArgumentNullException>(); }
private async Task PrepareForApiRequest(User user = null) { if (user == null && _httpContextAccessor.HttpContext != null) { user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User); } if (user != null) { var expiresAtToken = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_ExpiresAt); var access_token = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_AccessToken); var refresh_token = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_RefreshToken); _traktClient.Authorization = TraktAuthorization.CreateWith(access_token, refresh_token); var expiresAt = DateTime.Parse(expiresAtToken); if (expiresAt < DateTime.Now.AddDays(-5)) { var tokenResponse = await _traktClient.Authentication.RefreshAuthorizationAsync(); if (tokenResponse.IsSuccess) { await _userManager.SetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_ExpiresAt, tokenResponse.Value.CreatedAt.AddSeconds(Convert.ToInt32(tokenResponse.Value.ExpiresInSeconds)).ToString(CultureInfo.InvariantCulture)); await _userManager.SetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_AccessToken, tokenResponse.Value.AccessToken); await _userManager.SetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_RefreshToken, tokenResponse.Value.RefreshToken); } } } }
private async Task PrepareForApiRequest(IdentityUser user = null) { if (user == null && _httpContextAccessor.HttpContext != null) { user = await _userManager.GetUserAsync(_httpContextAccessor.HttpContext.User); } if (user != null) { var expiresAtToken = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_ExpiresAt); var access_token = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_AccessToken); var refresh_token = await _userManager.GetAuthenticationTokenAsync(user, Constants.TOKEN_LoginProvider, Constants.TOKEN_RefreshToken); var expiresAt = DateTime.Parse(expiresAtToken); if (expiresAt < DateTime.Now) { //Refresh the token } _traktClient.Authorization = TraktAuthorization.CreateWith(access_token); } }
public void AddWatchedEpisodeToTraktIfMediaLibraryAvailable(IList <MediaItem> databaseEpisodes, IList <EpisodeWatched> traktEpisodes, int?expectedEpisodesCount) { // Arrange IMediaPortalServices mediaPortalServices = GetMockMediaPortalServices(databaseEpisodes); ITraktClient traktClient = Substitute.For <ITraktClient>(); traktClient.AddCollectionItems(Arg.Any <ITraktSyncCollectionPost>()).Returns(new TraktSyncCollectionPostResponse()); traktClient.AddWatchedHistoryItems(Arg.Any <ITraktSyncHistoryPost>()).Returns( new TraktSyncHistoryPostResponse { Added = new TraktSyncPostResponseGroup { Episodes = expectedEpisodesCount } }); TraktAuthorization authorization = Substitute.For <TraktAuthorization>(); authorization.AccessToken = "ValidToken"; traktClient.TraktAuthorization.Returns(authorization); ITraktCache traktCache = Substitute.For <ITraktCache>(); traktCache.RefreshSeriesCache().Returns(new TraktEpisodes { Watched = traktEpisodes, UnWatched = new List <Episode>(), Collected = new List <EpisodeCollected>() }); IFileOperations fileOperations = Substitute.For <IFileOperations>(); ILibrarySynchronization librarySynchronization = new LibrarySynchronization(mediaPortalServices, traktClient, traktCache, fileOperations); // Act TraktSyncEpisodesResult result = librarySynchronization.SyncSeries(); // Assert Assert.Equal(expectedEpisodesCount, result.AddedToTraktWatchedHistory); }
public async Task <bool> CheckIfAccessTokenWasRevokedOrIsNotValidAsync(string accessToken, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(accessToken) || accessToken.ContainsSpace()) { throw new ArgumentException("access token must not be null, empty or contain any spaces", nameof(accessToken)); } ITraktAuthorization currentAuthorization = _client.Authorization; _client.Authorization = TraktAuthorization.CreateWith(accessToken); bool throwResponseExceptions = true; try { throwResponseExceptions = _client.Configuration.ThrowResponseExceptions; _client.Configuration.ThrowResponseExceptions = true; await _client.Sync.GetLastActivitiesAsync(cancellationToken).ConfigureAwait(false); return(false); } catch (TraktAuthorizationException) { return(true); } finally { _client.Configuration.ThrowResponseExceptions = throwResponseExceptions; _client.Authorization = currentAuthorization; } }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_StringWriter_Complete() { ITraktAuthorization traktAuthorization = new TraktAuthorization { AccessToken = "mockAccessToken", RefreshToken = "mockRefreshToken", Scope = TraktAccessScope.Public, ExpiresInSeconds = 7200, TokenType = TraktAccessTokenType.Bearer, CreatedAtTimestamp = 1506271312UL, IgnoreExpiration = true }; using (var stringWriter = new StringWriter()) { var traktJsonWriter = new AuthorizationObjectJsonWriter { CompleteSerialization = true }; string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktAuthorization); json.Should().Be(@"{""access_token"":""mockAccessToken"",""refresh_token"":""mockRefreshToken""," + @"""scope"":""public"",""expires_in"":7200,""token_type"":""bearer""," + @"""created_at"":1506271312,""ignore_expiration"":true}"); } }
public void MarkMovieAsUnwatchedIfMediaLibraryAvailable(List <MediaItem> databaseMovies, List <Movie> traktMovies, int expectedMoviesCount) { // Arrange IMediaPortalServices mediaPortalServices = GetMockMediaPortalServices(databaseMovies); ITraktClient traktClient = Substitute.For <ITraktClient>(); traktClient.AddCollectionItems(Arg.Any <ITraktSyncCollectionPost>()).Returns(new TraktSyncCollectionPostResponse()); traktClient.AddWatchedHistoryItems(Arg.Any <ITraktSyncHistoryPost>()).Returns(new TraktSyncHistoryPostResponse()); TraktAuthorization authorization = Substitute.For <TraktAuthorization>(); authorization.AccessToken = "ValidToken"; traktClient.TraktAuthorization.Returns(authorization); ITraktCache traktCache = Substitute.For <ITraktCache>(); traktCache.RefreshMoviesCache().Returns(new TraktMovies { UnWatched = traktMovies, Watched = new List <MovieWatched>(), Collected = new List <MovieCollected>() }); IFileOperations fileOperations = Substitute.For <IFileOperations>(); ILibrarySynchronization librarySynchronization = new LibrarySynchronization(mediaPortalServices, traktClient, traktCache, fileOperations); // Act TraktSyncMoviesResult result = librarySynchronization.SyncMovies(); // Assert Assert.Equal(expectedMoviesCount, result.MarkedAsUnWatchedInLibrary); }
private void SetupClient() { var client = TraktApiClient.Client; if (!client.IsValidForAuthenticationProcess) { throw new InvalidOperationException("Trakt Client not valid for authentication"); } client.Configuration.ForceAuthorization = true; Client = client; var token = GetAuthToken(); if (token != null) { var authorization = TraktAuthorization.CreateWith(token.AccessToken, token.RefreshToken); client.Authorization = authorization; RefreshAuthorization().Wait(); } else { TryToDeviceAuthenticate().Wait(); } }
public void Test_AuthorizationObjectJsonWriter_WriteObject_JsonWriter_Exceptions() { var traktJsonWriter = new AuthorizationObjectJsonWriter(); ITraktAuthorization traktAuthorization = new TraktAuthorization(); Func <Task> action = () => traktJsonWriter.WriteObjectAsync(default(JsonTextWriter), traktAuthorization); action.Should().Throw <ArgumentNullException>(); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Empty() { ITraktAuthorization traktAuthorization = new TraktAuthorization(); var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be("{}"); }
private async void new_function_test_btn_Click(object sender, EventArgs e) { try { var client = new TraktClient("ffbabf875e565204c86c845286e60cee44385da8ff211f57812ced74e2d2e198", "20445df61023171ba5a55e357a8d0fc7b23a7b1c72e181c6ad0c7963b2b986d1"); if (!client.IsValidForAuthenticationProcess) { throw new InvalidOperationException("Trakt Client not valid for authentication"); } client.Authorization = TraktAuthorization.CreateWith("883b619c865e36a089f6b68c5dc455ea80050b831f13510748b2ba17ea1e5fbf"); if (client.IsValidForUseWithAuthorization) { log("Authorization successful", msgType.success); } else { log("Authorization unsuccessful", msgType.error); } var nextEpisodes = await client.Shows.GetShowNextEpisodeAsync("the-flight-attendant"); var watchedShows = await client.Users.GetWatchedHistoryAsync("dflowd"); var episodeSearch = await client.Episodes.GetEpisodeAsync("the-flight-attendant", 1, 3); //log(episodeSearch.Value..ToString(), msgType.message); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } //var response = new RestClient("https://ww7.readmha.com/chapter/boku-no-hero-academia-chapter-353/").ExecuteAsync(new RestRequest("", Method.Get)).Result; //switch (response.Content.ToLower()) //{ // case string a when a.Contains("1.jpeg"): // log("New chapter present", msgType.message); // break; // case string b when b.Contains("404"): // log("No new chapters.", msgType.message); // break; // default: // log("No new chapters.\n" + response.Content, msgType.message); // break; //} //client.ExecuteAsync(request, response => //{ // //log(response.Content, msgType.message); // switch (response.Content.ToLower()) // { // } // //< img src = "https://cdn.dbsmanga.com/file/mangap/1069/10084000/1.jpeg" class="mb - 3 mx - auto js - page" loading="lazy" /> //}); }
public static void SaveAuthorization(TraktAuthorization authorization) { var preferences = Application.Context.GetSharedPreferences("Authorization", FileCreationMode.Private); var editor = preferences.Edit(); editor.PutString("AccessToken", authorization.AccessToken); // TODO: Use constants or Android strings editor.PutString("RefreshToken", authorization.RefreshToken); editor.Apply(); }
static void Main(string[] args) { TraktClient client = new TraktClient(CLIENT_ID, CLIENT_SECRET); TraktAuthorization fakeAuthorization = new TraktAuthorization { AccessToken = "FakeAccessToken", RefreshToken = "FakeRefreshToken", ExpiresInSeconds = 90 * 24 * 3600, AccessScope = TraktAccessScope.Public, TokenType = TraktAccessTokenType.Bearer }; Console.WriteLine("Fake Authorization:"); Console.WriteLine($"Created (UTC): {fakeAuthorization.Created}"); Console.WriteLine($"Access Scope: {fakeAuthorization.AccessScope.DisplayName}"); Console.WriteLine($"Refresh Possible: {fakeAuthorization.IsRefreshPossible}"); Console.WriteLine($"Valid: {fakeAuthorization.IsValid}"); Console.WriteLine($"Token Type: {fakeAuthorization.TokenType.DisplayName}"); Console.WriteLine($"Access Token: {fakeAuthorization.AccessToken}"); Console.WriteLine($"Refresh Token: {fakeAuthorization.RefreshToken}"); Console.WriteLine($"Token Expired: {fakeAuthorization.IsExpired}"); Console.WriteLine($"Expires in {fakeAuthorization.ExpiresInSeconds / 3600 / 24} days"); Console.WriteLine("-------------------------------------------------------------"); //string fakeAuthorizationJson = TraktSerializationService.Serialize(client.Authorization); string fakeAuthorizationJson = TraktSerializationService.Serialize(fakeAuthorization); if (!string.IsNullOrEmpty(fakeAuthorizationJson)) { Console.WriteLine("Serialized Fake Authorization:"); Console.WriteLine(fakeAuthorizationJson); Console.WriteLine("-------------------------------------------------------------"); TraktAuthorization deserializedFakeAuthorization = TraktSerializationService.DeserializeAuthorization(fakeAuthorizationJson); if (deserializedFakeAuthorization != null) { client.Authorization = deserializedFakeAuthorization; Console.WriteLine("Deserialized Fake Authorization:"); Console.WriteLine($"Created (UTC): {deserializedFakeAuthorization.Created}"); Console.WriteLine($"Access Scope: {deserializedFakeAuthorization.AccessScope.DisplayName}"); Console.WriteLine($"Refresh Possible: {deserializedFakeAuthorization.IsRefreshPossible}"); Console.WriteLine($"Valid: {deserializedFakeAuthorization.IsValid}"); Console.WriteLine($"Token Type: {deserializedFakeAuthorization.TokenType.DisplayName}"); Console.WriteLine($"Access Token: {deserializedFakeAuthorization.AccessToken}"); Console.WriteLine($"Refresh Token: {deserializedFakeAuthorization.RefreshToken}"); Console.WriteLine($"Token Expired: {deserializedFakeAuthorization.IsExpired}"); Console.WriteLine($"Expires in {deserializedFakeAuthorization.ExpiresInSeconds / 3600 / 24} days"); } } Console.ReadLine(); }
public void Test_TraktAuthorization_CreatedAt() { var traktAuthorization = new TraktAuthorization(); traktAuthorization.CreatedAt.Should().Be(default(DateTime)); traktAuthorization.CreatedAtTimestamp = 1506271312; traktAuthorization.CreatedAt.Should().Be(s_timestampOriginPlusCurrent); }
/// <summary>Deserializes a JSON string to an <see cref="TraktAuthorization" /> instance.</summary> /// <param name="authorizationJson">The JSON string, which should be deserialized.</param> /// <returns> /// An <see cref="TraktAuthorization" /> instance, containing the information from the JSON string, if successful. /// If the JSON string could not be parsed, null will be returned. /// </returns> /// <exception cref="ArgumentException">Thrown, if the given authorizationJson is null or empty.</exception> public static TraktAuthorization DeserializeAuthorization(string authorizationJson) { if (string.IsNullOrEmpty(authorizationJson)) { throw new ArgumentException("authorization JSON is invalid", nameof(authorizationJson)); } var authorizationWrapper = new { AccessToken = string.Empty, RefreshToken = string.Empty, ExpiresIn = 0, Scope = string.Empty, TokenType = string.Empty, CreatedAtTicks = 0L, IgnoreExpiration = false }; var anonymousAuthorization = JsonConvert.DeserializeAnonymousType(authorizationJson, authorizationWrapper); if (anonymousAuthorization != null) { var accessToken = anonymousAuthorization.AccessToken; var refreshToken = anonymousAuthorization.RefreshToken; var expiresIn = anonymousAuthorization.ExpiresIn; var scope = anonymousAuthorization.Scope; var tokenType = anonymousAuthorization.TokenType; var createdAtTicks = anonymousAuthorization.CreatedAtTicks; var ignoreExpiration = anonymousAuthorization.IgnoreExpiration; if (accessToken == null || refreshToken == null || scope == null || tokenType == null) { return(default(TraktAuthorization)); } var accessScope = scope != string.Empty ? TraktEnumeration.FromObjectName <TraktAccessScope>(scope) : TraktAccessScope.Public; var accessTokenType = tokenType != string.Empty ? TraktEnumeration.FromObjectName <TraktAccessTokenType>(tokenType) : TraktAccessTokenType.Bearer; var createdDateTime = new DateTime(createdAtTicks, DateTimeKind.Utc); var authorization = new TraktAuthorization { AccessToken = accessToken, RefreshToken = refreshToken, ExpiresInSeconds = expiresIn, AccessScope = accessScope, TokenType = accessTokenType, IgnoreExpiration = ignoreExpiration, Created = createdDateTime }; return(authorization); } return(default(TraktAuthorization)); }
static void Main(string[] args) { TraktClient client = new TraktClient(CLIENT_ID); Console.WriteLine($"Client Id: {client.ClientId}"); Console.WriteLine($"Client Secret: {client.ClientSecret}\n"); Console.WriteLine($"Requests without Authorization possible: {client.IsValidForUseWithoutAuthorization}"); Console.WriteLine($"Authentication possible: {client.IsValidForAuthenticationProcess}"); Console.WriteLine($"Requests with Authorization possible: {client.IsValidForUseWithAuthorization}"); Console.WriteLine("-------------------------------------------------------"); client.ClientSecret = CLIENT_SECRET; Console.WriteLine($"Client Id: {client.ClientId}"); Console.WriteLine($"Client Secret: {client.ClientSecret}\n"); Console.WriteLine($"Requests without Authorization possible: {client.IsValidForUseWithoutAuthorization}"); Console.WriteLine($"Authentication possible: {client.IsValidForAuthenticationProcess}"); Console.WriteLine($"Requests with Authorization possible: {client.IsValidForUseWithAuthorization}"); Console.WriteLine("-------------------------------------------------------"); TraktAuthorization fakeAuthorization = new TraktAuthorization { AccessToken = "FakeAccessToken", RefreshToken = "FakeRefreshToken", ExpiresInSeconds = 90 * 24 * 3600, AccessScope = TraktAccessScope.Public, TokenType = TraktAccessTokenType.Bearer }; client.Authorization = fakeAuthorization; Console.WriteLine($"Client Id: {client.ClientId}"); Console.WriteLine($"Client Secret: {client.ClientSecret}\n"); Console.WriteLine($"Access Token: {client.Authorization.AccessToken}"); Console.WriteLine($"Refresh Token: {client.Authorization.RefreshToken}\n"); Console.WriteLine($"Requests without Authorization possible: {client.IsValidForUseWithoutAuthorization}"); Console.WriteLine($"Authentication possible: {client.IsValidForAuthenticationProcess}"); Console.WriteLine($"Requests with Authorization possible: {client.IsValidForUseWithAuthorization}"); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine($"API Version: {client.Configuration.ApiVersion}"); Console.WriteLine($"API Base Url (UseStagingUrl == false): {client.Configuration.BaseUrl}"); client.Configuration.UseSandboxEnvironment = true; Console.WriteLine($"API Base Url (UseStagingUrl == true): {client.Configuration.BaseUrl}"); Console.ReadLine(); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Only_RefreshToken_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { RefreshToken = "mockRefreshToken" }; var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be(@"{""refresh_token"":""mockRefreshToken""}"); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Only_ExpiresInSeconds_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { ExpiresInSeconds = 7200 }; var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be(@"{""expires_in"":7200}"); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Only_Scope_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { Scope = TraktAccessScope.Public }; var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be(@"{""scope"":""public""}"); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Only_TokenType_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { TokenType = TraktAccessTokenType.Bearer }; var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be(@"{""token_type"":""bearer""}"); }
private async Task RefreshAuthorization() { TraktAuthorization newAuthorization = await Client.DeviceAuth.RefreshAuthorizationAsync(); if (newAuthorization != null && newAuthorization.IsValid) { SaveAuthToken(new TraktToken { AccessToken = newAuthorization.AccessToken, RefreshToken = newAuthorization.RefreshToken }); Console.WriteLine("-------------- Authorization refreshed successfully --------------"); } }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_Object_Only_CreatedAtTimestamp_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { CreatedAtTimestamp = 1506271312UL }; var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktAuthorization); json.Should().Be(@"{""created_at"":1506271312}"); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_JsonWriter_Empty() { ITraktAuthorization traktAuthorization = new TraktAuthorization(); using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new AuthorizationObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktAuthorization); 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}"; }
public void TestTraktAuthorizationCreateWithAccessToken() { var accessToken = "accessToken"; var authorization = TraktAuthorization.CreateWith(accessToken); authorization.Should().NotBeNull(); authorization.AccessToken.Should().Be(accessToken); authorization.RefreshToken.Should().NotBeNull().And.BeEmpty(); authorization.AccessScope.Should().Be(TraktAccessScope.Public); authorization.TokenType.Should().Be(TraktAccessTokenType.Bearer); authorization.IgnoreExpiration.Should().BeTrue(); authorization.ExpiresInSeconds.Should().Be(0); }
public void Test_TraktAuthorization_Default_Constructor() { var traktAuthorization = new TraktAuthorization(); traktAuthorization.AccessToken.Should().BeNull(); traktAuthorization.RefreshToken.Should().BeNull(); traktAuthorization.Scope.Should().BeNull(); traktAuthorization.ExpiresInSeconds.Should().Be(0U); traktAuthorization.TokenType.Should().BeNull(); traktAuthorization.CreatedAtTimestamp.Should().Be(0UL); traktAuthorization.IsExpired.Should().BeTrue(); traktAuthorization.IsValid.Should().BeFalse(); traktAuthorization.IsRefreshPossible.Should().BeFalse(); traktAuthorization.CreatedAt.Should().Be(default);
public void Test_TraktAuthorization_IsRefreshPossible() { var traktAuthorization = new TraktAuthorization(); traktAuthorization.IsRefreshPossible.Should().BeFalse(); traktAuthorization.RefreshToken = string.Empty; traktAuthorization.IsRefreshPossible.Should().BeFalse(); traktAuthorization.RefreshToken = "refresh token"; traktAuthorization.IsRefreshPossible.Should().BeFalse(); traktAuthorization.RefreshToken = "refreshToken"; traktAuthorization.IsRefreshPossible.Should().BeTrue(); }
public void Test_TraktAuthorization_IsValid() { var traktAuthorization = new TraktAuthorization(); traktAuthorization.IsValid.Should().BeFalse(); traktAuthorization.AccessToken = string.Empty; traktAuthorization.IsValid.Should().BeFalse(); traktAuthorization.AccessToken = "access token"; traktAuthorization.IsValid.Should().BeFalse(); traktAuthorization.AccessToken = "accessToken"; traktAuthorization.IsValid.Should().BeTrue(); }
public async Task Test_AuthorizationObjectJsonWriter_WriteObject_StringWriter_Only_AccessToken_Property() { ITraktAuthorization traktAuthorization = new TraktAuthorization { AccessToken = "mockAccessToken" }; using (var stringWriter = new StringWriter()) { var traktJsonWriter = new AuthorizationObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktAuthorization); json.Should().Be(@"{""access_token"":""mockAccessToken""}"); } }