Files
orderPRO/clients/windows/OrderPROPrint/Services/PrintApiClient.cs
2026-04-09 00:51:24 +02:00

62 lines
1.9 KiB
C#

using System.Net.Http.Json;
using System.Text.Json;
using OrderPROPrint.Models;
namespace OrderPROPrint.Services;
public class PrintApiClient : IDisposable
{
private readonly HttpClient _httpClient;
public PrintApiClient(string apiUrl, string apiKey)
{
_httpClient = new HttpClient
{
BaseAddress = new Uri(apiUrl.TrimEnd('/') + "/"),
Timeout = TimeSpan.FromSeconds(30)
};
_httpClient.DefaultRequestHeaders.Add("X-Api-Key", apiKey);
}
public async Task<List<PrintJob>> GetPendingJobsAsync(CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync("api/print/jobs/pending", cancellationToken);
response.EnsureSuccessStatusCode();
var json = await response.Content.ReadAsStringAsync(cancellationToken);
var result = JsonSerializer.Deserialize<PendingJobsResponse>(json);
return result?.Jobs ?? new List<PrintJob>();
}
public async Task<byte[]> DownloadLabelAsync(int jobId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.GetAsync($"api/print/jobs/{jobId}/download", cancellationToken);
response.EnsureSuccessStatusCode();
return await response.Content.ReadAsByteArrayAsync(cancellationToken);
}
public async Task<bool> MarkCompleteAsync(int jobId, CancellationToken cancellationToken = default)
{
var response = await _httpClient.PostAsync($"api/print/jobs/{jobId}/complete", null, cancellationToken);
return response.IsSuccessStatusCode;
}
public async Task<bool> TestConnectionAsync()
{
try
{
var response = await _httpClient.GetAsync("api/print/jobs/pending");
return response.IsSuccessStatusCode;
}
catch
{
return false;
}
}
public void Dispose()
{
_httpClient.Dispose();
}
}