package de.ph87.home.tvheadend.api; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.apache.hc.client5.http.utils.Base64; import org.springframework.stereotype.Service; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URI; import java.nio.charset.StandardCharsets; @Slf4j @Service @RequiredArgsConstructor @SuppressWarnings("unused") public class TvheadendHttpHelper { private static final String URL = "http://10.0.0.50:9981/api/%s"; private final ObjectMapper objectMapper; @NonNull public T get(@NonNull final String path, @NonNull final Class clazz) throws IOException { return parse(clazz, open(false, path)); } public void post(@NonNull final String path, @NonNull final Object request) throws IOException { final HttpURLConnection connection = openPost(path, request); if (connection.getResponseCode() != 200) { throw new IOException("Response code: " + connection.getResponseCode()); } } @NonNull public T post(@NonNull final String path, @NonNull final Object request, @NonNull final Class clazz) throws IOException { return parse(clazz, openPost(path, request)); } @NonNull private static HttpURLConnection openPost(@NonNull final String path, @NonNull final Object request) throws IOException { final HttpURLConnection connection = open(true, path); connection.getOutputStream().write(request.toString().getBytes()); return connection; } @NonNull private T parse(@NonNull final Class clazz, @NonNull final HttpURLConnection connection) throws IOException { final String response = new String(connection.getInputStream().readAllBytes()); log.debug(response); try { return objectMapper.readValue(response, clazz); } catch (JsonMappingException e) { log.error("Failed to deserialize json: {}", e.getMessage()); log.error(response); throw e; } } @NonNull private static HttpURLConnection open(final boolean post, @NonNull final String path) throws IOException { final String url = URL.formatted(path); final String method = post ? "POST" : "GET"; log.debug("open {} {}", method, url); final HttpURLConnection connection = (HttpURLConnection) URI.create(url).toURL().openConnection(); connection.setRequestMethod(method); connection.setDoOutput(post); connection.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64("api:api".getBytes(StandardCharsets.UTF_8)))); return connection; } }