// FlashMdService.cs
using System.Net.Http.Headers;
using System.Text.Json;
public class FlashMdService
{
private readonly HttpClient _http;
private readonly string _apiUrl;
private readonly string _apiKey;
public FlashMdService(HttpClient http, IConfiguration config)
{
_http = http;
_apiUrl = config["FlashMd:ApiUrl"]!;
_apiKey = config["FlashMd:ApiKey"]!;
}
public async Task<string> ConvertAsync(Stream fileStream, string filename, string contentType)
{
var content = new StreamContent(fileStream);
content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
var request = new HttpRequestMessage(HttpMethod.Post,
$"{_apiUrl}/convert/raw?filename={Uri.EscapeDataString(filename)}&mode=fast");
request.Headers.Add("x-api-key", _apiKey);
request.Content = content;
var res = await _http.SendAsync(request);
if (res.StatusCode == System.Net.HttpStatusCode.OK)
return await res.Content.ReadAsStringAsync();
if ((int)res.StatusCode == 202)
{
var json = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
var jobId = json.RootElement.GetProperty("job_id").GetString()!;
return await PollJobAsync(jobId);
}
res.EnsureSuccessStatusCode();
return "";
}
private async Task<string> PollJobAsync(string jobId)
{
while (true)
{
await Task.Delay(5000);
var request = new HttpRequestMessage(HttpMethod.Get, $"{_apiUrl}/jobs/{jobId}");
request.Headers.Add("x-api-key", _apiKey);
var res = await _http.SendAsync(request);
var json = JsonDocument.Parse(await res.Content.ReadAsStringAsync());
var status = json.RootElement.GetProperty("status").GetString();
if (status == "completed")
return json.RootElement.GetProperty("body").GetString()!;
if (status == "failed")
throw new Exception(json.RootElement.GetProperty("error").GetString());
}
}
}