-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
209 lines (182 loc) · 6.81 KB
/
Program.cs
File metadata and controls
209 lines (182 loc) · 6.81 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
using System.Net.Http;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// QuickSheet Currency Conversion Extension — live exchange rates from ECB via Frankfurter API.
/// Prefix: "fx". Usage: "fx: 1000, USD, EUR" or "fx: USD, EUR" (defaults to 1 unit).
/// No API key required. Rates update daily from the European Central Bank.
/// </summary>
class Program
{
private static readonly JsonSerializerOptions JsonOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = false
};
private static readonly HttpClient Http = new()
{
Timeout = TimeSpan.FromSeconds(10)
};
// Cache: base+quote -> (rate, date, fetchedAt)
private static readonly Dictionary<string, (double rate, string date, DateTime fetchedAt)> RateCache = new();
private static readonly TimeSpan CacheTtl = TimeSpan.FromHours(1);
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
string? line;
while ((line = Console.ReadLine()) != null)
{
if (string.IsNullOrWhiteSpace(line)) continue;
try
{
using var doc = JsonDocument.Parse(line);
string? type = doc.RootElement.TryGetProperty("type", out var tp) ? tp.GetString() : null;
switch (type)
{
case "init":
HandleInit();
break;
case "activate":
HandleActivate(doc.RootElement);
break;
case "deactivate":
// No ongoing timers to stop — fx is request/response
break;
}
}
catch (Exception ex)
{
SendJson(new { type = "error", id = "", message = $"Parse error: {ex.Message}" });
}
}
}
static void HandleInit()
{
SendJson(new
{
type = "register",
prefix = "fx",
name = "Currency Converter",
version = "1.0.0"
});
SendLog("Currency Converter registered with prefix 'fx'. Rates from ECB via Frankfurter API.");
}
static void HandleActivate(JsonElement root)
{
string id = root.TryGetProperty("id", out var idProp) ? idProp.GetString() ?? "" : "";
string[] extParams = [];
if (root.TryGetProperty("params", out var paramsProp) && paramsProp.ValueKind == JsonValueKind.Array)
{
extParams = paramsProp.EnumerateArray()
.Select(p => p.GetString()?.Trim() ?? "")
.Where(p => p.Length > 0)
.ToArray();
}
// Parse: "fx: 1000, USD, EUR" or "fx: USD, EUR" or "fx: USD, EUR, GBP, CAD"
double amount = 1;
string baseCurrency;
string[] quoteCurrencies;
if (extParams.Length < 2)
{
SendCells(id, [
(0, 0, "⚠️ Usage: fx: [amount,] FROM, TO [, TO2, ...]"),
(1, 0, "Example: fx: 1000, USD, EUR")
]);
return;
}
// If first param is numeric, it's the amount
if (double.TryParse(extParams[0], System.Globalization.NumberStyles.Any,
System.Globalization.CultureInfo.InvariantCulture, out double parsedAmount))
{
amount = parsedAmount;
baseCurrency = extParams[1].ToUpperInvariant();
quoteCurrencies = extParams.Skip(2).Select(p => p.ToUpperInvariant()).ToArray();
}
else
{
baseCurrency = extParams[0].ToUpperInvariant();
quoteCurrencies = extParams.Skip(1).Select(p => p.ToUpperInvariant()).ToArray();
}
if (quoteCurrencies.Length == 0)
{
SendCells(id, [(0, 0, "⚠️ Need at least one target currency"), (1, 0, "Example: fx: 1000, USD, EUR")]);
return;
}
// Fetch rates and build output
var cells = new List<(int r, int c, string v)>();
int row = 0;
// Header
string amountStr = amount == 1 ? "" : $"{amount:N2} ";
cells.Add((row, 0, $"💱 {amountStr}{baseCurrency}"));
cells.Add((row, 1, "Rate"));
cells.Add((row, 2, "Converted"));
row++;
foreach (var quote in quoteCurrencies)
{
var result = FetchRate(baseCurrency, quote);
if (result.HasValue)
{
var (rate, date) = result.Value;
double converted = amount * rate;
cells.Add((row, 0, $"→ {quote}"));
cells.Add((row, 1, $"{rate:F4}"));
cells.Add((row, 2, $"{converted:N2} {quote}"));
}
else
{
cells.Add((row, 0, $"→ {quote}"));
cells.Add((row, 1, "error"));
cells.Add((row, 2, "fetch failed"));
}
row++;
}
// Footer with source and date
var anyResult = FetchRate(baseCurrency, quoteCurrencies[0]);
string dateStr = anyResult?.date ?? "unknown";
cells.Add((row, 0, $"ECB · {dateStr}"));
row++;
SendCells(id, cells);
}
static (double rate, string date)? FetchRate(string baseCur, string quoteCur)
{
string cacheKey = $"{baseCur}/{quoteCur}";
// Check cache
if (RateCache.TryGetValue(cacheKey, out var cached) &&
DateTime.UtcNow - cached.fetchedAt < CacheTtl)
{
return (cached.rate, cached.date);
}
// Fetch from Frankfurter
try
{
string url = $"https://api.frankfurter.dev/v2/rate/{baseCur}/{quoteCur}";
var response = Http.GetStringAsync(url).GetAwaiter().GetResult();
using var doc = JsonDocument.Parse(response);
double rate = doc.RootElement.GetProperty("rate").GetDouble();
string date = doc.RootElement.GetProperty("date").GetString() ?? "unknown";
RateCache[cacheKey] = (rate, date, DateTime.UtcNow);
return (rate, date);
}
catch (Exception ex)
{
SendLog($"Rate fetch failed for {cacheKey}: {ex.Message}");
return null;
}
}
static void SendCells(string id, List<(int r, int c, string v)> cells)
{
var cellObjects = cells.Select(c => new { r = c.r, c = c.c, v = c.v }).ToArray();
SendJson(new { type = "write", id, cells = cellObjects });
}
static void SendJson(object obj)
{
string json = JsonSerializer.Serialize(obj, JsonOpts);
Console.WriteLine(json);
Console.Out.Flush();
}
static void SendLog(string message)
{
SendJson(new { type = "log", message });
}
}