Skip to content

Commit

Permalink
Merge pull request #5 from lira92/develop
Browse files Browse the repository at this point in the history
Merge Develop to Master
  • Loading branch information
lira92 authored Sep 21, 2019
2 parents 1bd2b84 + 0588d6e commit a7b6166
Show file tree
Hide file tree
Showing 8 changed files with 104 additions and 70 deletions.
23 changes: 20 additions & 3 deletions src/NubankClient/Converters/TolerantEnumConverter.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
using Newtonsoft.Json;
using NubankClient.Model.Enums;
using System;
using System.Linq;
using System.Runtime.Serialization;

namespace NubankClient.Converters
{
Expand All @@ -21,19 +23,22 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
var enumType = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;

var names = Enum.GetNames(enumType);
var options = names.Select(n => (Enum)Enum.Parse(enumType, n));

if (reader.TokenType == JsonToken.String)
{
var enumText = reader.Value.ToString();

if (!string.IsNullOrEmpty(enumText))
{
var match = names
.FirstOrDefault(n => string.Equals(n, enumText, StringComparison.OrdinalIgnoreCase));
var match = options
.FirstOrDefault(n => {
return string.Equals(n.GetJsonValue(), enumText, StringComparison.OrdinalIgnoreCase);
});

if (match != null)
{
return Enum.Parse(enumType, match);
return match;
}
}
}
Expand Down Expand Up @@ -73,4 +78,16 @@ private static bool IsNullableType(Type t)
return (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
}
}

static class EventCategoryExtensions
{
public static string GetJsonValue(this Enum @enum)
{
var fieldInfo = @enum.GetType().GetField(@enum.ToString());

return !(Attribute.GetCustomAttribute(fieldInfo, typeof(EnumMemberAttribute)) is EnumMemberAttribute attribute)
? @enum.ToString()
: attribute.Value;
}
}
}
12 changes: 9 additions & 3 deletions src/NubankClient/Endpoints.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using NubankClient.Http;
using System.Collections.Generic;
using System.Linq;

namespace NubankClient
{
Expand All @@ -16,6 +17,7 @@ class Endpoints
public Endpoints(IHttpClient httpClient)
{
_client = httpClient;
_autenticatedUrls = new Dictionary<string, string>();
}

public string Login => GetTopLevelUrl("login");
Expand Down Expand Up @@ -57,12 +59,16 @@ private void Discover()

private void DiscoverApp()
{
var response = _client.GetAsync<Dictionary<string, string>>(DiscoveryAppUrl)
var response = _client.GetAsync<Dictionary<string, object>>(DiscoveryAppUrl)
.GetAwaiter().GetResult();
_appUrls = response;

_appUrls = response
.Where(x => x.Value is string)
.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString()))
.ToDictionary(x => x.Key, x => x.Value.ToString());
}

private string GetKey(string key, Dictionary<string, string> source)
private static string GetKey(string key, Dictionary<string, string> source)
{
if (!source.ContainsKey(key))
{
Expand Down
7 changes: 6 additions & 1 deletion src/NubankClient/Http/HttpClient.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using RestSharp;
using RestSharp.Serializers.Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
Expand All @@ -10,6 +11,10 @@ namespace NubankClient.Http
class HttpClient : IHttpClient
{
private readonly IRestClient _client = new RestClient();
public HttpClient()
{
_client.AddHandler("application/json", new NewtonsoftJsonSerializer());
}
public async Task<T> GetAsync<T>(string url) where T : new()
{
_client.BaseUrl = new Uri(url);
Expand All @@ -31,7 +36,7 @@ class HttpClient : IHttpClient
public async Task<T> PostAsync<T>(string url, object body) where T : new()
{
_client.BaseUrl = new Uri(url);
var request = new RestSharp.Serializers.Newtonsoft.Json.RestRequest();
var request = new RestRequest();
request.AddJsonBody(body);
return await _client.PostAsync<T>(request);
}
Expand Down
1 change: 1 addition & 0 deletions src/NubankClient/Model/Event.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,6 @@ public class Event
public decimal CurrencyAmount => (Amount / 100);
public DateTime Time { get; set; }
public string Title { get; set; }
public string Message { get; set; }
}
}
31 changes: 18 additions & 13 deletions src/NubankClient/Nubank.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using Newtonsoft.Json.Linq;
using NubankClient.Http;
using NubankClient.Model;
using NubankClient.Responses;
Expand All @@ -16,6 +17,7 @@ public class Nubank
private readonly IHttpClient _client;
private readonly Endpoints _endpoints;
private string AuthToken { get; set; }
private string RefreshToken { get; set; }

public Nubank(string login, string password)
{
Expand All @@ -33,9 +35,9 @@ public Nubank(IHttpClient httpClient, string login, string password)
_endpoints = new Endpoints(_client);
}

public async Task<LoginResponse> Login()
public async Task<LoginResponse> LoginAsync()
{
await GetToken();
await GetTokenAsync();

if (_endpoints.Events != null)
{
Expand All @@ -45,7 +47,7 @@ public async Task<LoginResponse> Login()
return new LoginResponse(Guid.NewGuid().ToString());
}

private async Task GetToken()
private async Task GetTokenAsync()
{
var body = new
{
Expand All @@ -57,16 +59,16 @@ private async Task GetToken()
};
var response = await _client.PostAsync<Dictionary<string, object>>(_endpoints.Login, body);

FillToken(response);
FillTokens(response);

FillAutenticatedUrls(response);
}

public async Task AutenticateWithQrCode(string code)
public async Task AutenticateWithQrCodeAsync(string code)
{
if (string.IsNullOrEmpty(AuthToken))
{
await GetToken();
await GetTokenAsync();
}

var payload = new
Expand All @@ -77,12 +79,12 @@ public async Task AutenticateWithQrCode(string code)

var response = await _client.PostAsync<Dictionary<string, object>>(_endpoints.Lift, payload, GetHeaders());

FillToken(response);
FillTokens(response);

FillAutenticatedUrls(response);
}

private void FillToken(Dictionary<string, object> response)
private void FillTokens(Dictionary<string, object> response)
{
if (!response.Keys.Any(x => x == "access_token"))
{
Expand All @@ -97,13 +99,16 @@ private void FillToken(Dictionary<string, object> response)

private void FillAutenticatedUrls(Dictionary<string, object> response)
{
var listLinks = ((Dictionary<string, object>)response["_links"]);
var listLinksConverted = listLinks
.Select(x => new KeyValuePair<string, string>(x.Key, (((Dictionary<string, object>)x.Value)["href"].ToString())));
_endpoints.AutenticatedUrls = listLinksConverted.ToDictionary(x => x.Key, x => x.Value);
var listLinks = (JObject)response["_links"];
var properties = listLinks.Properties();
var values = listLinks.Values();
_endpoints.AutenticatedUrls = listLinks
.Properties()
.Select(x => new KeyValuePair<string, string>(x.Name, (string)listLinks[x.Name]["href"]))
.ToDictionary(key => key.Key, key => key.Value);
}

public async Task<IEnumerable<Event>> GetEvents()
public async Task<IEnumerable<Event>> GetEventsAsync()
{
if (string.IsNullOrEmpty(AuthToken))
{
Expand Down
2 changes: 1 addition & 1 deletion src/NubankClient/NubankClient.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<Version>0.2.0</Version>
<Version>0.2.1</Version>
<Authors>Alan Lira</Authors>
<Description>Unoficial Nubank Api client for .Net</Description>
<PackageProjectUrl>https://github.com/lira92/nubank-dotnet</PackageProjectUrl>
Expand Down
23 changes: 17 additions & 6 deletions src/NubankClientDemo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,45 @@
using NubankClient;
using NubankClient.Model;
using System;
using System.IO;
using System.Threading.Tasks;

namespace NubankClientDemo
{
class Program
{
static async Task Main(string[] args)
static async Task Main()
{
Console.WriteLine("Nubank Client");
Console.WriteLine("Please, type your login (CPF):");
var login = Console.ReadLine().Trim();
Console.WriteLine("Type your password:");
var password = Console.ReadLine().Trim();
var nubankClient = new Nubank(login, password);
var result = await nubankClient.Login();
var result = await nubankClient.LoginAsync();
if (result.NeedsDeviceAuthorization)
{
Console.WriteLine("You must authenticate with your phone to be able to access your data.");
Console.WriteLine("Scan the QRCode below with you Nubank application on the following menu:");
Console.WriteLine("Nu(Seu Nome) > Perfil > Acesso pelo site");
Console.WriteLine();
Console.Write(result.GetQrCodeAsAscii());
Console.WriteLine();
var directory = Path.Combine(Directory.GetCurrentDirectory(), "qrcodes");
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}

var filename = Path.Combine(directory, DateTime.Now.ToString("yyyyMMddHH:mm") + ".jpg");
result
.GetQrCodeAsBitmap()
.Save(filename);

Console.WriteLine($"Open the file '{filename}' and use your phone to scan and after this press any key to continue...");
Console.ReadKey();

await nubankClient.AutenticateWithQrCode(result.Code);
await nubankClient.AutenticateWithQrCodeAsync(result.Code);
}
var events = await nubankClient.GetEvents();
var events = await nubankClient.GetEventsAsync();

ConsoleTable
.From<Event>(events)
Expand Down
Loading

0 comments on commit a7b6166

Please sign in to comment.