public async Task Test_TraktDevice_Equals() { var traktDevice1 = new TraktDevice(); var traktDevice2 = new TraktDevice(); traktDevice1.Equals(traktDevice2).Should().BeTrue(); var jsonReader = new DeviceObjectJsonReader(); var traktDeviceFromJson = await jsonReader.ReadObjectAsync(JSON) as TraktDevice; traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice2 = CopyTraktDevice(traktDeviceFromJson); traktDevice2.Equals(traktDevice1).Should().BeTrue(); traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice1.DeviceCode = null; traktDevice2.Equals(traktDevice1).Should().BeFalse(); traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice1.UserCode = null; traktDevice2.Equals(traktDevice1).Should().BeFalse(); traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice1.VerificationUrl = null; traktDevice2.Equals(traktDevice1).Should().BeFalse(); traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice1.ExpiresInSeconds = 0; traktDevice2.Equals(traktDevice1).Should().BeFalse(); traktDevice1 = CopyTraktDevice(traktDeviceFromJson); traktDevice1.IntervalInSeconds = 0; traktDevice2.Equals(traktDevice1).Should().BeFalse(); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Exceptions() { var traktJsonWriter = new DeviceObjectJsonWriter(); ITraktDevice traktDevice = new TraktDevice(); Func <Task <string> > action = () => traktJsonWriter.WriteObjectAsync(default(ITraktDevice)); await action.Should().ThrowAsync <ArgumentNullException>(); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Empty() { ITraktDevice traktDevice = new TraktDevice(); var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be("{}"); }
public void Test_DeviceObjectJsonWriter_WriteObject_StringWriter_Exceptions() { var traktJsonWriter = new DeviceObjectJsonWriter(); ITraktDevice traktDevice = new TraktDevice(); Func <Task <string> > action = () => traktJsonWriter.WriteObjectAsync(default(StringWriter), traktDevice); action.Should().Throw <ArgumentNullException>(); }
public void Test_TraktDevice_IsExpiredUnused() { var traktDevice = new TraktDevice(); traktDevice.IsExpiredUnused.Should().BeTrue(); traktDevice.ExpiresInSeconds = 600; traktDevice.IsExpiredUnused.Should().BeFalse(); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Only_VerificationUrl_Property() { ITraktDevice traktDevice = new TraktDevice { VerificationUrl = "mockUrl" }; var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be(@"{""verification_url"":""mockUrl""}"); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Only_ExpiresInSeconds_Property() { ITraktDevice traktDevice = new TraktDevice { ExpiresInSeconds = 7200 }; var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be(@"{""expires_in"":7200}"); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_StringWriter_Empty() { ITraktDevice traktDevice = new TraktDevice(); using (var stringWriter = new StringWriter()) { var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktDevice); json.Should().Be("{}"); } }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Only_UserCode_Property() { ITraktDevice traktDevice = new TraktDevice { UserCode = "mockUserCode" }; var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be(@"{""user_code"":""mockUserCode""}"); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Only_IntervalInSeconds_Property() { ITraktDevice traktDevice = new TraktDevice { IntervalInSeconds = 600 }; var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be(@"{""interval"":600}"); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_JsonWriter_Empty() { ITraktDevice traktDevice = new TraktDevice(); using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new DeviceObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktDevice); stringWriter.ToString().Should().Be("{}"); } }
public void Test_TraktDevice_ToString() { var traktDevice = new TraktDevice(); traktDevice.ToString().Should().Be("no valid device code (expired unused)"); traktDevice.DeviceCode = "deviceCode"; traktDevice.ToString().Should().Be($"{traktDevice.DeviceCode} (expired unused)"); traktDevice.ExpiresInSeconds = 600; traktDevice.IsExpiredUnused.Should().BeFalse(); traktDevice.ToString().Should().Be($"{traktDevice.DeviceCode} (valid until {traktDevice.CreatedAt.AddSeconds(traktDevice.ExpiresInSeconds)})"); }
public void Test_TraktDevice_Default_Constructor() { var traktDevice = new TraktDevice(); traktDevice.DeviceCode.Should().BeNull(); traktDevice.UserCode.Should().BeNull(); traktDevice.VerificationUrl.Should().BeNull(); traktDevice.ExpiresInSeconds.Should().Be(0U); traktDevice.IntervalInSeconds.Should().Be(0U); traktDevice.IntervalInMilliseconds.Should().Be(0U); traktDevice.IsValid.Should().BeFalse(); traktDevice.IsExpiredUnused.Should().BeTrue(); traktDevice.CreatedAt.Should().BeCloseTo(DateTime.UtcNow, TimeSpan.FromMilliseconds(1000)); }
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}"; }
/// <summary>Deserializes a JSON string to an <see cref="TraktDevice" /> instance.</summary> /// <param name="deviceJson">The JSON string, which should be deserialized.</param> /// <returns> /// An <see cref="TraktDevice" /> 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 deviceJson is null or empty.</exception> public static TraktDevice DeserializeDevice(string deviceJson) { if (string.IsNullOrEmpty(deviceJson)) { throw new ArgumentException("device JSON is invalid", nameof(deviceJson)); } var deviceWrapper = new { UserCode = string.Empty, DeviceCode = string.Empty, VerificationUrl = string.Empty, ExpiresInSeconds = 0, IntervalInSeconds = 0, CreatedAtTicks = 0L }; var anonymousDevice = JsonConvert.DeserializeAnonymousType(deviceJson, deviceWrapper); if (anonymousDevice != null) { var userCode = anonymousDevice.UserCode; var deviceCode = anonymousDevice.DeviceCode; var verificationUrl = anonymousDevice.VerificationUrl; var expiresInSeconds = anonymousDevice.ExpiresInSeconds; var intervalInSeconds = anonymousDevice.IntervalInSeconds; var createdAtTicks = anonymousDevice.CreatedAtTicks; if (userCode == null || deviceCode == null || verificationUrl == null) { return(default(TraktDevice)); } var createdDateTime = new DateTime(createdAtTicks, DateTimeKind.Utc); var device = new TraktDevice { UserCode = userCode, DeviceCode = deviceCode, VerificationUrl = verificationUrl, ExpiresInSeconds = expiresInSeconds, IntervalInSeconds = intervalInSeconds, Created = createdDateTime }; return(device); } return(default(TraktDevice)); }
public void TestTraktDeviceDefaultConstructor() { var dtNowUtc = DateTime.UtcNow; var device = new TraktDevice(); device.DeviceCode.Should().BeNullOrEmpty(); device.UserCode.Should().BeNullOrEmpty(); device.VerificationUrl.Should().BeNullOrEmpty(); device.ExpiresInSeconds.Should().Be(0); device.IntervalInSeconds.Should().Be(0); device.IsExpiredUnused.Should().BeTrue(); device.IsValid.Should().BeFalse(); device.Created.Should().BeCloseTo(dtNowUtc); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_StringWriter_Only_DeviceCode_Property() { ITraktDevice traktDevice = new TraktDevice { DeviceCode = "mockDeviceCode" }; using (var stringWriter = new StringWriter()) { var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(stringWriter, traktDevice); json.Should().Be(@"{""device_code"":""mockDeviceCode""}"); } }
public async Task Test_DeviceObjectJsonWriter_WriteObject_JsonWriter_Only_UserCode_Property() { ITraktDevice traktDevice = new TraktDevice { UserCode = "mockUserCode" }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new DeviceObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktDevice); stringWriter.ToString().Should().Be(@"{""user_code"":""mockUserCode""}"); } }
public async Task Test_DeviceObjectJsonWriter_WriteObject_JsonWriter_Only_VerificationUrl_Property() { ITraktDevice traktDevice = new TraktDevice { VerificationUrl = "mockUrl" }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new DeviceObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktDevice); stringWriter.ToString().Should().Be(@"{""verification_url"":""mockUrl""}"); } }
public async Task Test_DeviceObjectJsonWriter_WriteObject_JsonWriter_Only_ExpiresInSeconds_Property() { ITraktDevice traktDevice = new TraktDevice { ExpiresInSeconds = 7200 }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new DeviceObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktDevice); stringWriter.ToString().Should().Be(@"{""expires_in"":7200}"); } }
public async Task Test_DeviceObjectJsonWriter_WriteObject_Object_Complete() { ITraktDevice traktDevice = new TraktDevice { DeviceCode = "mockDeviceCode", UserCode = "mockUserCode", VerificationUrl = "mockUrl", ExpiresInSeconds = 7200, IntervalInSeconds = 600 }; var traktJsonWriter = new DeviceObjectJsonWriter(); string json = await traktJsonWriter.WriteObjectAsync(traktDevice); json.Should().Be(@"{""device_code"":""mockDeviceCode"",""user_code"":""mockUserCode""," + @"""verification_url"":""mockUrl"",""expires_in"":7200,""interval"":600}"); }
/// <summary>Serializes an <see cref="TraktDevice" /> instance to a JSON string.</summary> /// <param name="device">The device information, which should be serialized.</param> /// <returns>A Json string, containing all properties of the given device.</returns> /// <exception cref="ArgumentNullException">Thrown, if the given device is null.</exception> public static string Serialize(TraktDevice device) { if (device == null) { throw new ArgumentNullException(nameof(device), "device must not be null"); } var deviceWrapper = new { UserCode = device.UserCode ?? string.Empty, DeviceCode = device.DeviceCode ?? string.Empty, VerificationUrl = device.VerificationUrl ?? string.Empty, ExpiresInSeconds = device.ExpiresInSeconds, IntervalInSeconds = device.IntervalInSeconds, CreatedAtTicks = device.Created.Ticks }; return(Json.Serialize(deviceWrapper)); }
public async Task Test_DeviceObjectJsonWriter_WriteObject_JsonWriter_Complete() { ITraktDevice traktDevice = new TraktDevice { DeviceCode = "mockDeviceCode", UserCode = "mockUserCode", VerificationUrl = "mockUrl", ExpiresInSeconds = 7200, IntervalInSeconds = 600 }; using (var stringWriter = new StringWriter()) using (var jsonWriter = new JsonTextWriter(stringWriter)) { var traktJsonWriter = new DeviceObjectJsonWriter(); await traktJsonWriter.WriteObjectAsync(jsonWriter, traktDevice); stringWriter.ToString().Should().Be(@"{""device_code"":""mockDeviceCode"",""user_code"":""mockUserCode""," + @"""verification_url"":""mockUrl"",""expires_in"":7200,""interval"":600}"); } }
static async Task TryToDeviceAuthenticate() { try { TraktDevice device = await _client.DeviceAuth.GenerateDeviceAsync(); if (device != null && device.IsValid) { Console.WriteLine("-------------- Device created successfully --------------"); Console.WriteLine($"Device Created (UTC): {device.Created}"); Console.WriteLine($"Device Code: {device.DeviceCode}"); Console.WriteLine($"Device expires in {device.ExpiresInSeconds} seconds"); Console.WriteLine($"Device Interval: {device.IntervalInSeconds} seconds"); Console.WriteLine($"Device Expired Unused: {device.IsExpiredUnused}"); Console.WriteLine($"Device Valid: {device.IsValid}"); Console.WriteLine("-------------------------------------------------------"); Console.WriteLine("You have to authenticate this application."); Console.WriteLine($"Please visit the following webpage: {device.VerificationUrl}"); Console.WriteLine($"Sign in or sign up on that webpage and enter the following code: {device.UserCode}"); TraktAuthorization authorization = await _client.DeviceAuth.PollForAuthorizationAsync(); if (authorization != null && authorization.IsValid) { Console.WriteLine("-------------- Authentication successful --------------"); WriteAuthorizationInformation(authorization); Console.WriteLine("-------------------------------------------------------"); } } } catch (TraktException ex) { PrintTraktException(ex); } catch (Exception ex) { PrintException(ex); } }
private async Task TryToDeviceAuthenticate() { TraktDevice device = await Client.DeviceAuth.GenerateDeviceAsync(); if (device != null && device.IsValid) { Console.WriteLine("You have to authenticate this application."); Console.WriteLine($"Please visit the following webpage: {device.VerificationUrl}"); Console.WriteLine($"Sign in or sign up on that webpage and enter the following code: {device.UserCode}"); TraktAuthorization authorization = await Client.DeviceAuth.PollForAuthorizationAsync(); if (authorization != null && authorization.IsValid) { SaveAuthToken(new TraktToken { AccessToken = authorization.AccessToken, RefreshToken = authorization.RefreshToken }); Console.WriteLine("-------------- Authentication successful --------------"); } } }
public void Test_TraktDevice_IsValid() { var traktDevice = new TraktDevice(); traktDevice.IsValid.Should().BeFalse(); traktDevice.DeviceCode = "deviceCode"; traktDevice.IsValid.Should().BeFalse(); traktDevice.UserCode = "userCode"; traktDevice.IsValid.Should().BeFalse(); traktDevice.VerificationUrl = "verificationUrl"; traktDevice.IsValid.Should().BeFalse(); traktDevice.IntervalInSeconds = 1; traktDevice.IsValid.Should().BeFalse(); traktDevice.ExpiresInSeconds = 600; traktDevice.IsExpiredUnused.Should().BeFalse(); traktDevice.IsValid.Should().BeTrue(); }
public void TestTraktSerializationServiceSerializeEmptyTraktDevice() { var emptyDevice = new TraktDevice(); string emptyDeviceJson = "{" + $"\"UserCode\":\"\"," + $"\"DeviceCode\":\"\"," + $"\"VerificationUrl\":\"\"," + $"\"ExpiresInSeconds\":0," + $"\"IntervalInSeconds\":0," + $"\"CreatedAtTicks\":{emptyDevice.Created.Ticks}" + "}"; Action act = () => TraktSerializationService.Serialize(emptyDevice); act.ShouldNotThrow(); var jsonDevice = TraktSerializationService.Serialize(emptyDevice); jsonDevice.Should().NotBeNullOrEmpty(); jsonDevice.Should().Be(emptyDeviceJson); }
/// <summary> /// Generates access token for trakt client. /// </summary> /// <returns></returns> private async Task generateAccessTokenAsync() { // Get access token from Trakt TraktDevice device = await this.traktClient.DeviceAuth.GenerateDeviceAsync(); Console.WriteLine("Please go to {0} and enter code {1} on the page.", device.VerificationUrl, device.UserCode); TraktAuthorization authorization = await this.traktClient.DeviceAuth.PollForAuthorizationAsync(); // Write access token to file Console.WriteLine("Successfully received access token: {0}", authorization.AccessToken); try { using (StreamWriter sw = new StreamWriter(this.accessTokenPathWithName)) { sw.WriteLine(authorization.AccessToken); // TODO: Save refresh token as well } } catch (Exception e) { Console.WriteLine(e); throw; } }
public override async Task <ITraktDevice> ReadObjectAsync(JsonTextReader jsonReader, CancellationToken cancellationToken = default) { if (jsonReader == null) { return(await Task.FromResult(default(ITraktDevice))); } if (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.StartObject) { ITraktDevice traktAuthorization = new TraktDevice(); while (await jsonReader.ReadAsync(cancellationToken) && jsonReader.TokenType == JsonToken.PropertyName) { var propertyName = jsonReader.Value.ToString(); switch (propertyName) { case JsonProperties.DEVICE_PROPERTY_NAME_DEVICE_CODE: traktAuthorization.DeviceCode = await jsonReader.ReadAsStringAsync(cancellationToken); break; case JsonProperties.DEVICE_PROPERTY_NAME_USER_CODE: traktAuthorization.UserCode = await jsonReader.ReadAsStringAsync(cancellationToken); break; case JsonProperties.DEVICE_PROPERTY_NAME_VERIFICATION_URL: traktAuthorization.VerificationUrl = await jsonReader.ReadAsStringAsync(cancellationToken); break; case JsonProperties.DEVICE_PROPERTY_NAME_EXPIRES_IN: { var value = await JsonReaderHelper.ReadUnsignedIntegerValueAsync(jsonReader, cancellationToken); if (value.First) { traktAuthorization.ExpiresInSeconds = value.Second; } break; } case JsonProperties.DEVICE_PROPERTY_NAME_INTERVAL: { var value = await JsonReaderHelper.ReadUnsignedIntegerValueAsync(jsonReader, cancellationToken); if (value.First) { traktAuthorization.IntervalInSeconds = value.Second; } break; } default: await JsonReaderHelper.ReadAndIgnoreInvalidContentAsync(jsonReader, cancellationToken); break; } } return(traktAuthorization); } return(await Task.FromResult(default(ITraktDevice))); }