-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLicenseManagementClient.cs
More file actions
473 lines (390 loc) · 19.9 KB
/
LicenseManagementClient.cs
File metadata and controls
473 lines (390 loc) · 19.9 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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
using System.Net;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using LicenseManagement.Client.Exceptions;
using LicenseManagement.Client.Models;
using LicenseManagement.Client.Requests;
using Microsoft.Extensions.Options;
namespace LicenseManagement.Client;
/// <summary>
/// HTTP client implementation for the License Management API.
/// </summary>
public class LicenseManagementClient : ILicenseManagementClient
{
private readonly HttpClient _httpClient;
private readonly LicenseManagementClientOptions _options;
private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true
};
// HTTP 422 Unprocessable Entity (not available in .NET Standard 2.0)
private const int UnprocessableEntityStatusCode = 422;
/// <summary>
/// Creates a new LicenseManagementClient.
/// </summary>
public LicenseManagementClient(HttpClient httpClient, IOptions<LicenseManagementClientOptions> options)
{
_httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
_options = options?.Value ?? throw new ArgumentNullException(nameof(options));
ConfigureHttpClient();
}
private void ConfigureHttpClient()
{
_httpClient.BaseAddress = new Uri(_options.BaseUrl.TrimEnd('/') + "/");
_httpClient.Timeout = TimeSpan.FromSeconds(_options.TimeoutSeconds);
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Add("X-API-KEY", _options.ApiKey);
_httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
}
#region Licenses
/// <inheritdoc />
public async Task<License?> GetLicenseAsync(string productId, string computerId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"license?product={Uri.EscapeDataString(productId)}&computer={Uri.EscapeDataString(computerId)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NoContent)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<License>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<License> CreateLicenseAsync(CreateLicenseRequest request, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsJsonAsync("license", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
// Get the created license from the Location header
if (response.Headers.Location != null)
{
var getResponse = await _httpClient.GetAsync(response.Headers.Location, cancellationToken);
await EnsureSuccessAsync(getResponse);
return (await getResponse.Content.ReadFromJsonAsync<License>(JsonOptions, cancellationToken))!;
}
return (await response.Content.ReadFromJsonAsync<License>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task UpdateLicenseAsync(UpdateLicenseRequest request, CancellationToken cancellationToken = default)
{
var response = await PatchAsJsonAsync("license", request, cancellationToken);
await EnsureSuccessAsync(response);
}
#endregion
#region Receipts
/// <inheritdoc />
public async Task<Receipt?> GetReceiptAsync(string code, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"receipt?code={Uri.EscapeDataString(code)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NoContent)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<Receipt>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<Receipt> CreateReceiptAsync(CreateReceiptRequest request, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsJsonAsync("receipt", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
// Get the created receipt from the Location header
if (response.Headers.Location != null)
{
var getResponse = await _httpClient.GetAsync(response.Headers.Location, cancellationToken);
await EnsureSuccessAsync(getResponse);
return (await getResponse.Content.ReadFromJsonAsync<Receipt>(JsonOptions, cancellationToken))!;
}
return (await response.Content.ReadFromJsonAsync<Receipt>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task UpdateReceiptAsync(UpdateReceiptRequest request, CancellationToken cancellationToken = default)
{
var response = await PatchAsJsonAsync("receipt", request, cancellationToken);
await EnsureSuccessAsync(response);
}
/// <inheritdoc />
public async Task<string> GenerateReceiptCodeAsync(string productName, string email, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"receipt/code?product={Uri.EscapeDataString(productName)}&email={Uri.EscapeDataString(email)}", cancellationToken);
await EnsureSuccessAsync(response);
#if NETSTANDARD2_0
return await response.Content.ReadAsStringAsync();
#else
return await response.Content.ReadAsStringAsync(cancellationToken);
#endif
}
/// <inheritdoc />
public async Task<string> ResetReceiptCodeAsync(string code, CancellationToken cancellationToken = default)
{
// 1. Get existing receipt
var existingReceipt = await GetReceiptAsync(code, cancellationToken)
?? throw new LicenseManagementException(
"Receipt not found",
System.Net.HttpStatusCode.NotFound,
$"No receipt exists with code: {code}");
// 2. Void the existing receipt (set qty=0, expires=now)
await UpdateReceiptAsync(new UpdateReceiptRequest
{
Id = existingReceipt.Id,
Qty = 0,
Expires = DateTime.UtcNow
}, cancellationToken);
// 3. Generate new code using modified email to avoid collision
var emailParts = existingReceipt.BuyerEmail.Split('@');
var modifiedEmail = emailParts.Length == 2
? $"{Guid.NewGuid():N}@{emailParts[1]}"
: $"{Guid.NewGuid():N}@temp.local";
var newCode = await GenerateReceiptCodeAsync(
existingReceipt.Product?.Id ?? throw new LicenseManagementException("Product ID missing from receipt", (System.Net.HttpStatusCode)422, string.Empty),
modifiedEmail,
cancellationToken);
if (string.IsNullOrEmpty(newCode))
newCode = Guid.NewGuid().ToString("N");
// 4. Create new receipt with original buyer info
await CreateReceiptAsync(new CreateReceiptRequest
{
Code = newCode,
BuyerEmail = existingReceipt.BuyerEmail,
Product = existingReceipt.Product.Id,
Expires = existingReceipt.Expires,
Qty = existingReceipt.Qty
}, cancellationToken);
return newCode;
}
/// <inheritdoc />
public async Task<IEnumerable<Receipt>> GetReceiptsAsync(string buyerEmail, string productId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"receipt/all?buyerEmail={Uri.EscapeDataString(buyerEmail)}&product={Uri.EscapeDataString(productId)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NoContent)
return Enumerable.Empty<Receipt>();
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<IEnumerable<Receipt>>(JsonOptions, cancellationToken)) ?? Enumerable.Empty<Receipt>();
}
#endregion
#region Products
/// <inheritdoc />
public async Task<Product?> GetProductAsync(string productId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"product?product={Uri.EscapeDataString(productId)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NoContent)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<Product>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<IEnumerable<Product>> GetProductsAsync(CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync("product/all", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<IEnumerable<Product>>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<Product> CreateProductAsync(CreateProductRequest request, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsJsonAsync("product", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
// Get the created product from the Location header
if (response.Headers.Location != null)
{
var getResponse = await _httpClient.GetAsync(response.Headers.Location, cancellationToken);
await EnsureSuccessAsync(getResponse);
return (await getResponse.Content.ReadFromJsonAsync<Product>(JsonOptions, cancellationToken))!;
}
return (await response.Content.ReadFromJsonAsync<Product>(JsonOptions, cancellationToken))!;
}
#endregion
#region Computers
/// <inheritdoc />
public async Task<Computer?> GetComputerAsync(string macAddress, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"computer?macAddress={Uri.EscapeDataString(macAddress)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NoContent)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<Computer>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<Computer> RegisterComputerAsync(RegisterComputerRequest request, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsJsonAsync("computer", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
// Get the created computer from the Location header
if (response.Headers.Location != null)
{
var getResponse = await _httpClient.GetAsync(response.Headers.Location, cancellationToken);
await EnsureSuccessAsync(getResponse);
return (await getResponse.Content.ReadFromJsonAsync<Computer>(JsonOptions, cancellationToken))!;
}
return (await response.Content.ReadFromJsonAsync<Computer>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<IEnumerable<Computer>> GetComputersAsync(string receiptCode, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"computer/all?receiptCode={Uri.EscapeDataString(receiptCode)}", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<IEnumerable<Computer>>(JsonOptions, cancellationToken))!;
}
#endregion
#region Signing Keys
/// <inheritdoc />
public async Task<string> GetPublicKeyAsync(string format = "xml", CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"signingkey?format={Uri.EscapeDataString(format)}", cancellationToken);
await EnsureSuccessAsync(response);
#if NETSTANDARD2_0
return await response.Content.ReadAsStringAsync();
#else
return await response.Content.ReadAsStringAsync(cancellationToken);
#endif
}
#endregion
#region Webhooks
/// <inheritdoc />
public async Task<IEnumerable<Webhook>> GetWebhooksAsync(CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync("webhook", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<IEnumerable<Webhook>>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<Webhook?> GetWebhookAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"webhook/{Uri.EscapeDataString(webhookId)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<Webhook>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<WebhookCreated> CreateWebhookAsync(CreateWebhookRequest request, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsJsonAsync("webhook", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookCreated>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task UpdateWebhookAsync(string webhookId, UpdateWebhookRequest request, CancellationToken cancellationToken = default)
{
var json = JsonSerializer.Serialize(request, JsonOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var httpRequest = new HttpRequestMessage(HttpMethod.Put, $"webhook/{Uri.EscapeDataString(webhookId)}")
{
Content = content
};
var response = await _httpClient.SendAsync(httpRequest, cancellationToken);
await EnsureSuccessAsync(response);
}
/// <inheritdoc />
public async Task DeleteWebhookAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.DeleteAsync($"webhook/{Uri.EscapeDataString(webhookId)}", cancellationToken);
await EnsureSuccessAsync(response);
}
/// <inheritdoc />
public async Task<WebhookSecretRotated> RotateWebhookSecretAsync(string webhookId, bool immediateRotation = false, CancellationToken cancellationToken = default)
{
var request = new { ImmediateRotation = immediateRotation };
var response = await _httpClient.PostAsJsonAsync($"webhook/{Uri.EscapeDataString(webhookId)}/rotate-secret", request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookSecretRotated>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task CompleteSecretRotationAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsync($"webhook/{Uri.EscapeDataString(webhookId)}/complete-rotation", null, cancellationToken);
await EnsureSuccessAsync(response);
}
/// <inheritdoc />
public async Task<IEnumerable<WebhookDelivery>> GetWebhookDeliveriesAsync(string webhookId, int limit = 50, int offset = 0, string? status = null, CancellationToken cancellationToken = default)
{
var url = $"webhook/{Uri.EscapeDataString(webhookId)}/deliveries?limit={limit}&offset={offset}";
if (!string.IsNullOrEmpty(status))
{
url += $"&status={Uri.EscapeDataString(status)}";
}
var response = await _httpClient.GetAsync(url, cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<IEnumerable<WebhookDelivery>>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<WebhookDeliveryDetail?> GetWebhookDeliveryAsync(string webhookId, string deliveryId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"webhook/{Uri.EscapeDataString(webhookId)}/deliveries/{Uri.EscapeDataString(deliveryId)}", cancellationToken);
if (response.StatusCode == HttpStatusCode.NotFound)
return null;
await EnsureSuccessAsync(response);
return await response.Content.ReadFromJsonAsync<WebhookDeliveryDetail>(JsonOptions, cancellationToken);
}
/// <inheritdoc />
public async Task<WebhookDelivery> ReplayWebhookDeliveryAsync(string webhookId, string deliveryId, string? targetUrl = null, CancellationToken cancellationToken = default)
{
var request = new { TargetUrl = targetUrl };
var response = await _httpClient.PostAsJsonAsync(
$"webhook/{Uri.EscapeDataString(webhookId)}/deliveries/{Uri.EscapeDataString(deliveryId)}/replay",
request, JsonOptions, cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookDelivery>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<WebhookHealth> GetWebhookHealthAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"webhook/{Uri.EscapeDataString(webhookId)}/health", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookHealth>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<WebhookStats> GetWebhookStatsAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"webhook/{Uri.EscapeDataString(webhookId)}/stats", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookStats>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task<WebhookEventTypes> GetWebhookEventTypesAsync(CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync("webhook/events", cancellationToken);
await EnsureSuccessAsync(response);
return (await response.Content.ReadFromJsonAsync<WebhookEventTypes>(JsonOptions, cancellationToken))!;
}
/// <inheritdoc />
public async Task TestWebhookAsync(string webhookId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsync($"webhook/{Uri.EscapeDataString(webhookId)}/test", null, cancellationToken);
await EnsureSuccessAsync(response);
}
#endregion
#region Helpers
/// <summary>
/// Sends a PATCH request with JSON body (cross-platform compatible).
/// </summary>
private async Task<HttpResponseMessage> PatchAsJsonAsync<T>(string requestUri, T value, CancellationToken cancellationToken)
{
var json = JsonSerializer.Serialize(value, JsonOptions);
var content = new StringContent(json, Encoding.UTF8, "application/json");
var request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri)
{
Content = content
};
return await _httpClient.SendAsync(request, cancellationToken);
}
private static async Task EnsureSuccessAsync(HttpResponseMessage response)
{
if (response.IsSuccessStatusCode)
return;
#if NETSTANDARD2_0
var content = await response.Content.ReadAsStringAsync();
#else
var content = await response.Content.ReadAsStringAsync();
#endif
var statusCode = (int)response.StatusCode;
var message = statusCode switch
{
400 => "Invalid request parameters",
401 => "Invalid or missing API key",
403 => "Access denied",
404 => "Resource not found",
409 => "Resource already exists",
UnprocessableEntityStatusCode => "Unable to process request",
_ => $"API request failed with status {response.StatusCode}"
};
throw new LicenseManagementException(message, response.StatusCode, content);
}
#endregion
}