WebInterface/src/main/java/com/alttd/webinterface/web_interact/FileDownloadService.java
akastijn d4359bf480 Add notification server and file download service implementation
- Introduce `NotificationServer` for handling HTTP notifications.
- Register `ProxyShutdownEvent` to stop the notification server on shutdown.
- Add `FileDownloadService` for asynchronous file downloads using the configured endpoint.
- Update `Config` to include `download-endpoint`.
- Add Javalin and SLF4J dependencies for the HTTP server.
2025-06-23 23:06:47 +02:00

59 lines
2.1 KiB
Java

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<Optional<byte[]>> 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.<byte[]>empty();
}
})
.exceptionally(e -> {
log.error("Exception occurred while downloading file: {}", fileName, e);
return Optional.empty();
});
}
}