package com.alttd.webinterface.web_interact; import com.alttd.webinterface.config.Config; import jakarta.servlet.http.HttpServletResponse; import lombok.extern.slf4j.Slf4j; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.util.Optional; import java.util.concurrent.CompletableFuture; /** * Service for downloading files from the configured download endpoint. */ @Slf4j public class FileDownloadService { /** * Asynchronously downloads a file from the configured download endpoint. * * @param fileName The name of the file to download * @return A CompletableFuture containing an Optional with the file content if successful, * or an empty Optional otherwise */ public static CompletableFuture> downloadFileAsync(String fileName) { String downloadUrl = Config.DOWNLOAD_ENDPOINT; if (!downloadUrl.endsWith("/")) { downloadUrl += "/"; } downloadUrl += fileName; log.debug("Downloading file from {}", downloadUrl); HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(downloadUrl)) .header("Authorization", "SECRET " + Config.SECRET) .GET() .build(); return client.sendAsync(request, HttpResponse.BodyHandlers.ofByteArray()) .thenApply(response -> { if (response.statusCode() == HttpServletResponse.SC_OK) { log.debug("Successfully downloaded file: {}", fileName); return Optional.of(response.body()); } else { log.error("Failed to download file: {}. Status code: {}", fileName, response.statusCode()); return Optional.empty(); } }) .exceptionally(e -> { log.error("Exception occurred while downloading file: {}", fileName, e); return Optional.empty(); }); } }