Skip to content

Commit

Permalink
Fix API calls involving provider exchangerate.host
Browse files Browse the repository at this point in the history
  • Loading branch information
guidospadavecchia committed Dec 18, 2023
1 parent 5ce67a8 commit 780ef3d
Show file tree
Hide file tree
Showing 10 changed files with 47 additions and 72 deletions.
6 changes: 3 additions & 3 deletions src/DolarBot.API/DolarBot.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Version>3.2.5</Version>
<Nullable>enable</Nullable>
</PropertyGroup>

Expand Down
15 changes: 8 additions & 7 deletions src/DolarBot.API/Services/DolarBotApi/DolarBotApiService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -149,23 +149,24 @@ internal DolarBotApiService(IConfiguration configuration, ResponseCache cache, A
/// Queries the API and returns the historical values for a particular <paramref name="currencyCode"/>.
/// </summary>
/// <param name="currencyCode">The currency 3-digit code.</param>
/// <param name="date">The historical rate date.</param>
/// <returns>A task that contains a collection of normalized <see cref="WorldCurrencyResponse"/> objects.</returns>
public async Task<List<WorldCurrencyResponse>?> GetWorldCurrencyHistoricalValues(string currencyCode)
public async Task<WorldCurrencyResponse?> GetWorldCurrencyHistoricalValue(string currencyCode, DateTime date)
{
string endpoint = $"{WorldCurrencyEndpoints.Historical.GetDescription()}/{currencyCode.ToUpper()}";
List<WorldCurrencyResponse>? cachedResponse = Cache.GetObject<List<WorldCurrencyResponse>>(endpoint);
string endpoint = $"{WorldCurrencyEndpoints.Historical.GetDescription()}/{currencyCode.ToUpper()}/{date:yyyy-MM-dd}";
WorldCurrencyResponse? cachedResponse = Cache.GetObject<WorldCurrencyResponse>(endpoint);
if (cachedResponse != null)
{
return cachedResponse;
}
else
{
RestRequest request = new(endpoint);
RestResponse<List<WorldCurrencyResponse>> response = await Client.ExecuteGetAsync<List<WorldCurrencyResponse>>(request);
if (response.IsSuccessful && response.Data != null && response.Data.Count > 0)
RestResponse<WorldCurrencyResponse> response = await Client.ExecuteGetAsync<WorldCurrencyResponse>(request);
if (response.IsSuccessful && response.Data != null)
{
List<WorldCurrencyResponse> data = response.Data;
data.ForEach(x => x.Code = currencyCode.ToUpper().Trim());
WorldCurrencyResponse data = response.Data;
data.Code = currencyCode.ToUpper().Trim();
Cache.SaveObject(endpoint, data, Cache.GetCurrencyListExpiration());
return data;
}
Expand Down
6 changes: 3 additions & 3 deletions src/DolarBot.Addons/DolarBot.Addons.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.5</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Authors>Guido Spadavecchia</Authors>
<PackageId>DolarBot.Addons</PackageId>
<PackageProjectUrl>https://github.com/PassiveModding/Discord.Addons.Interactive</PackageProjectUrl>
Expand Down
6 changes: 3 additions & 3 deletions src/DolarBot.Modules/DolarBot.Modules.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Version>3.2.5</Version>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ public override async Task<AutocompletionResult> GenerateSuggestionsAsync(IInter
currencyCodes = currencyCodes.Take(MAX_AUTOCOMPLETE_RESULTS).ToList();
}

IEnumerable<AutocompleteResult> autocompletionCollection = currencyCodes.Select(x => new AutocompleteResult($"[{x.Symbol.ToUpper()}] {x.Name}", x.Code)).OrderBy(x => x.Name);
IEnumerable<AutocompleteResult> autocompletionCollection = currencyCodes.Select(x => new AutocompleteResult($"[{x.Symbol?.ToUpper()}] {x.Name}", x.Code)).OrderBy(x => x.Name);
return AutocompletionResult.FromSuccess(autocompletionCollection);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Discord.Interactions;
using DolarBot.API;
using DolarBot.API.Models;
using DolarBot.API.Models.Base;
using DolarBot.API.Services.DolarBotApi;
using DolarBot.Modules.Attributes;
using DolarBot.Modules.InteractiveCommands.Autocompletion.FiatCurrency;
Expand Down Expand Up @@ -63,23 +64,13 @@ private async Task SendInvalidCurrencyCodeAsync(string userInput)
}

/// <summary>
/// Replies with a message indicating one of the date parameters was not correcly specified.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
private async Task SendInvalidDateRangeParametersAsync(DateTime startDate, DateTime endDate)
{
await FollowupAsync($"La {Format.Bold("fecha desde")} ({Format.Code(startDate.ToString("dd/MM/yyyy"))}) debe ser {Format.Bold("menor o igual")} a la {Format.Bold("fecha hasta")} ({Format.Code(endDate.ToString("dd/MM/yyyy"))}) y el rango debe ser {Format.Bold("menor")} a {Format.Code("1 año")}.");
}

/// <summary>
/// Replies with a message indicating one of the date parameters was not correcly specified.
/// Replies with a message indicating that the date parameter was not correcly specified.
/// </summary>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
private async Task SendNoDataForRangeAsync(DateTime startDate, DateTime endDate)
private async Task SendNoDataForDateAsync(DateTime date)
{
await FollowupAsync($"No hay datos históricos para el rango de fechas {Format.Code(startDate.ToString("dd/MM/yyyy"))} - {Format.Code(endDate.ToString("dd/MM/yyyy"))}.");
await FollowupAsync($"No hay datos históricos para la fecha {Format.Code(date.ToString("dd/MM/yyyy"))}.");
}

/// <summary>
Expand Down Expand Up @@ -182,10 +173,8 @@ public async Task GetHistoricalCurrencyValuesAsync(
[Summary("moneda", "Código de la moneda.")]
[Autocomplete(typeof(FiatCurrencyCodeAutocompleteHandler))]
string codigo,
[Summary("desde", "Fecha desde.")]
string startDate,
[Summary("hasta", "Fecha hasta.")]
string endDate
[Summary("fecha", "Fecha de la cotización.")]
string date
)
{
await DeferAsync().ContinueWith(async (task) =>
Expand All @@ -197,30 +186,20 @@ await DeferAsync().ContinueWith(async (task) =>
WorldCurrencyCodeResponse worldCurrencyCodeResponse = historicalCurrencyCodeList.FirstOrDefault(x => x.Code.Equals(currencyCode, StringComparison.OrdinalIgnoreCase));
if (worldCurrencyCodeResponse != null)
{
TimeSpan oneYear = TimeSpan.FromDays(366);
bool validStartDate = FiatCurrencyService.ParseDate(startDate, out DateTime? startDateResult) && startDateResult.HasValue;
bool validEndDate = FiatCurrencyService.ParseDate(endDate, out DateTime? endDateResult) && endDateResult.HasValue;
if (validStartDate && validEndDate)
if (FiatCurrencyService.ParseDate(date, out DateTime? dateResult) && dateResult.HasValue)
{
DateTime dateFrom = startDateResult.Value;
DateTime dateTo = endDateResult.Value;
if (dateFrom <= dateTo && (dateTo.Subtract(dateFrom) <= oneYear))
DateTime date = dateResult.Value;
WorldCurrencyResponse historicalValue = await FiatCurrencyService.GetHistoricalCurrencyValue(currencyCode, date);
if (historicalValue != null)
{
List<WorldCurrencyResponse> historicalCurrencyValues = await FiatCurrencyService.GetHistoricalCurrencyValues(currencyCode, dateFrom, dateTo);
if (historicalCurrencyValues != null && historicalCurrencyValues.Count > 0)
{
List<EmbedBuilder> embeds = FiatCurrencyService.CreateHistoricalValuesEmbedsAsync(historicalCurrencyValues, worldCurrencyCodeResponse.Name, dateFrom, dateTo);
await FollowUpWithPaginatedEmbedAsync(embeds);
}
else
{
await SendNoDataForRangeAsync(dateFrom, dateTo);
}
EmbedBuilder embed = await FiatCurrencyService.CreateWorldCurrencyEmbedAsync(historicalValue, worldCurrencyCodeResponse.Name, date: date);
await FollowupAsync(embed: embed.Build(), components: new CalculatorComponentBuilder(currencyCode, CalculatorTypes.FiatCurrency, Configuration).Build());
}
else
{
await SendInvalidDateRangeParametersAsync(dateFrom, dateTo);
await SendNoDataForDateAsync(date);
}

}
else
{
Expand Down
17 changes: 6 additions & 11 deletions src/DolarBot.Services/Currencies/FiatCurrencyService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,11 @@ public async Task<WorldCurrencyResponse> GetCurrencyValue(string currencyCode)
/// Fetches a collection of historical currency values between two dates.
/// </summary>
/// <param name="currencyCode">The currency 3-digit code.</param>
/// <param name="startDate">The start date.</param>
/// <param name="endDate">The end date.</param>
/// <param name="date">The rate date.</param>
/// <returns>A collection of <see cref="WorldCurrencyResponse"/> objects.</returns>
public async Task<List<WorldCurrencyResponse>> GetHistoricalCurrencyValues(string currencyCode, DateTime? startDate = null, DateTime? endDate = null)
public async Task<WorldCurrencyResponse> GetHistoricalCurrencyValue(string currencyCode, DateTime date)
{
List<WorldCurrencyResponse> historicalCurrencyValues = await Api.DolarBot.GetWorldCurrencyHistoricalValues(currencyCode);
if ((startDate != null && startDate.Value.Date <= DateTime.Now.Date) || (endDate != null && endDate.Value.Date <= DateTime.Now.Date))
{
historicalCurrencyValues = historicalCurrencyValues.Where(x => (!startDate.HasValue || x.Fecha.Date >= startDate.Value.Date) && (!endDate.HasValue || x.Fecha.Date <= endDate.Value.Date)).ToList();
}
return historicalCurrencyValues;
return await Api.DolarBot.GetWorldCurrencyHistoricalValue(currencyCode, date);
}

#endregion
Expand All @@ -93,7 +87,7 @@ public async Task<List<WorldCurrencyResponse>> GetHistoricalCurrencyValues(strin
/// <param name="currencyName">The currency name.</param>
/// <param name="amount">The amount to rate against.</param>
/// <returns>An <see cref="EmbedBuilder"/> object ready to be built.</returns>
public async Task<EmbedBuilder> CreateWorldCurrencyEmbedAsync(WorldCurrencyResponse worldCurrencyResponse, string currencyName, decimal amount = 1)
public async Task<EmbedBuilder> CreateWorldCurrencyEmbedAsync(WorldCurrencyResponse worldCurrencyResponse, string currencyName, decimal amount = 1, DateTime? date = null)
{
var emojis = Configuration.GetSection("customEmojis");
Emoji currencyEmoji = Emoji.Parse(":flag_ar:");
Expand All @@ -111,10 +105,11 @@ public async Task<EmbedBuilder> CreateWorldCurrencyEmbedAsync(WorldCurrencyRespo
decimal? valuePrice = decimal.TryParse(worldCurrencyResponse?.Valor, NumberStyles.Any, DolarBotApiService.GetApiCulture(), out decimal v) ? v * amount : null;
string value = valuePrice.HasValue ? valuePrice.Value.ToString("N2", GlobalConfiguration.GetLocalCultureInfo()) : "?";

string description = date.HasValue ? $"Cotización de {Format.Bold($"{currencyName} ({worldCurrencyResponse.Code})")} para el día {Format.Code(date.Value.Date.ToString("dd/MM/yyyy"))} expresada en {Format.Bold("pesos argentinos")}." : $"Cotización de {Format.Bold($"{currencyName} ({worldCurrencyResponse.Code})")} expresada en {Format.Bold("pesos argentinos")}.";
string shareText = $"*{currencyName} ({worldCurrencyResponse.Code})*{Environment.NewLine}{Environment.NewLine}*{amount} {worldCurrencyResponse.Code}*{Environment.NewLine}Valor: \t$ *{value}*{Environment.NewLine}Hora: \t{lastUpdated} (UTC {utcOffset})";
EmbedBuilder embed = new EmbedBuilder().WithColor(GlobalConfiguration.Colors.Currency)
.WithTitle($"{currencyName} ({worldCurrencyResponse.Code})")
.WithDescription($"Cotización de {Format.Bold($"{currencyName} ({worldCurrencyResponse.Code})")} expresada en {Format.Bold("pesos argentinos")}.".AppendLineBreak())
.WithDescription(description.AppendLineBreak())
.WithThumbnailUrl(currencyImageUrl)
.WithFooter(new EmbedFooterBuilder()
{
Expand Down
6 changes: 3 additions & 3 deletions src/DolarBot.Services/DolarBot.Services.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Version>3.2.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions src/DolarBot.Util/DolarBot.Util.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>10.0</LangVersion>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Version>3.2.5</Version>
</PropertyGroup>

<ItemGroup>
Expand Down
6 changes: 3 additions & 3 deletions src/DolarBot/DolarBot.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
<TargetFramework>net6.0</TargetFramework>
<ApplicationIcon>dolarbot-logo.ico</ApplicationIcon>
<LangVersion>10.0</LangVersion>
<AssemblyVersion>3.2.4.0</AssemblyVersion>
<FileVersion>3.2.4.0</FileVersion>
<Version>3.2.4</Version>
<AssemblyVersion>3.2.5.0</AssemblyVersion>
<FileVersion>3.2.5.0</FileVersion>
<Version>3.2.5</Version>
<DockerDefaultTargetOS>Linux</DockerDefaultTargetOS>
</PropertyGroup>

Expand Down

0 comments on commit 780ef3d

Please sign in to comment.