<?php
// app/Http/Controllers/ConvertController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
class ConvertController extends Controller
{
public function convert(Request $request)
{
$request->validate(["file" => "required|file|max:12288"]);
$file = $request->file("file");
$apiUrl = config("services.flash_md.url");
$apiKey = config("services.flash_md.key");
$response = Http::timeout(300)
->withHeaders([
"x-api-key" => $apiKey,
"content-type" => $file->getMimeType(),
])
->withBody($file->getContent(), $file->getMimeType())
->post("{$apiUrl}/convert/raw?filename=" . urlencode($file->getClientOriginalName()) . "&mode=fast");
if ($response->status() === 200) {
return response($response->body(), 200)
->header("Content-Type", "text/markdown; charset=utf-8");
}
if ($response->status() === 202) {
$job = $response->json();
$markdown = $this->pollJob($apiUrl, $apiKey, $job["job_id"]);
return response($markdown, 200)
->header("Content-Type", "text/markdown; charset=utf-8");
}
return response($response->body(), $response->status());
}
private function pollJob(string $apiUrl, string $apiKey, string $jobId): string
{
while (true) {
sleep(5);
$res = Http::timeout(30)
->withHeaders(["x-api-key" => $apiKey])
->get("{$apiUrl}/jobs/{$jobId}");
$data = $res->json();
if ($data["status"] === "completed") {
return $data["body"];
}
if ($data["status"] === "failed") {
abort(502, $data["error"] ?? "Job failed");
}
}
}
}