Assembly64Client.java

package ui.assembly64;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import ui.common.util.InternetUtil;
import ui.entities.config.Configuration;

import java.io.IOException;
import java.io.InputStream;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.time.Duration;
import java.util.*;
import java.util.stream.Collectors;

import static java.nio.charset.StandardCharsets.UTF_8;
import static server.restful.common.IServletSystemProperties.JSIDPlay2Server.CONNECTION_TIMEOUT;
import static ui.entities.config.OnlineSection.ASSEMBLY64_HEADERS;

/**
 * A selected Assembly64 server. Never switch servers partway through a release/download.
 */
public final class Assembly64Client {
    private record Servers(String registry, long fetched, List<HomeServer> values) {
    }

    private static final Map<Configuration, Servers> SERVERS = new WeakHashMap<>();
    private static final ObjectMapper MAPPER = new ObjectMapper().registerModule(new JavaTimeModule());
    private static final Authenticator UPSTREAM_AUTHENTICATOR = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            // Only explicitly configured Assembly64 headers may supply upstream credentials.
            return null;
        }
    };

    private final Configuration configuration;
    private final HomeServer server;
    private final boolean adminAccess;

    public Assembly64Client(Configuration configuration, Integer serverId) throws IOException {
        this(configuration, serverId, false);
    }

    public Assembly64Client(Configuration configuration, Integer serverId, boolean adminAccess) throws IOException {
        this(configuration, resolveServer(configuration, serverId, adminAccess), adminAccess);
    }

    public Assembly64Client(Configuration configuration, HomeServer server) {
        this(configuration, server, false);
    }

    private Assembly64Client(Configuration configuration, HomeServer server, boolean adminAccess) {
        this.configuration = configuration;
        this.server = server;
        this.adminAccess = adminAccess;
    }

    private static HomeServer configuredServer(Configuration configuration) {
        return new HomeServer(HomeServer.CONFIGURED_SERVER, configuration.getOnlineSection().getAssembly64Url(),
                "Assembly64 (CSDB)");
    }

    public static void requireAccess(Integer serverId, boolean adminAccess) throws IOException {
        Assembly64Credentials.load().requireAccess(serverId, adminAccess);
    }

    private static HomeServer resolveServer(Configuration configuration, Integer serverId, boolean adminAccess) throws IOException {
        requireAccess(serverId, adminAccess);
        // Existing links without a server selector continue to use the configured Assembly64 service.
        if (serverId == null || serverId == HomeServer.CONFIGURED_SERVER) return configuredServer(configuration);
        return fetchServers(configuration, false).stream().filter(s -> serverId.equals(s.getId())).findFirst()
                .orElseThrow(() -> new IOException("Assembly64 server is no longer available: " + serverId));
    }

    public static List<HomeServer> getServers(Configuration configuration, boolean refresh) throws IOException {
        return getServers(configuration, refresh, false);
    }

    public static List<HomeServer> getServers(Configuration configuration, boolean refresh, boolean adminAccess) throws IOException {
        Assembly64Credentials credentials = Assembly64Credentials.load();
        List<HomeServer> servers = fetchServers(configuration, refresh);
        if (adminAccess || servers.stream().noneMatch(server -> credentials.isProtected(server.getId())))
            return servers;
        return servers.stream().filter(server -> !credentials.isProtected(server.getId())).toList();
    }

    private static synchronized List<HomeServer> fetchServers(Configuration configuration, boolean refresh) throws IOException {
        String registry = configuration.getOnlineSection().getAssembly64Url();
        Servers cached = SERVERS.get(configuration);
        if (!refresh && cached != null && Objects.equals(registry, cached.registry())
                && System.currentTimeMillis() - cached.fetched() < Duration.ofMinutes(5).toMillis()) {
            return cached.values();
        }
        Assembly64Client client = new Assembly64Client(configuration, configuredServer(configuration));
        JsonNode response = client.read("/leet/homeserver/all-public-servers");
        if (!response.isArray()) throw new IOException("Invalid Assembly64 server list");
        List<HomeServer> servers = new ArrayList<>();
        servers.add(configuredServer(configuration));
        Set<Integer> ids = new HashSet<>();
        ids.add(HomeServer.CONFIGURED_SERVER);
        for (JsonNode node : response) {
            if (!node.isObject() || !node.path("id").isIntegralNumber() || !node.path("id").canConvertToInt()
                    || !node.path("url").isTextual()) continue;
            HomeServer server = new HomeServer(node.get("id").intValue(), node.get("url").textValue(),
                    node.path("descr").isTextual() ? node.get("descr").textValue() : null);
            try {
                URI uri = new URI(server.getUrl());
                if (server.getId() != null && uri.getHost() != null && uri.getUserInfo() == null
                        && ("http".equalsIgnoreCase(uri.getScheme()) || "https".equalsIgnoreCase(uri.getScheme()))
                        && uri.getQuery() == null && uri.getFragment() == null && ids.add(server.getId())) {
                    servers.add(server);
                }
            } catch (URISyntaxException | NullPointerException ignored) {
                // One broken registration must not hide the remaining servers.
            }
        }
        servers.sort(Comparator.comparing(HomeServer::toString, String.CASE_INSENSITIVE_ORDER));
        List<HomeServer> result = List.copyOf(servers);
        SERVERS.put(configuration, new Servers(registry, System.currentTimeMillis(), result));
        return result;
    }

    public List<Presets> getPresets() throws IOException {
        JsonNode response = read("/leet/search/aql/presets");
        if (!response.isArray()) throw new IOException("Invalid Assembly64 presets");
        return MAPPER.readerForListOf(Presets.class).readValue(response);
    }

    private static Optional<Presets> categoryPreset(Collection<Presets> presets) {
        if (presets == null) return Optional.empty();
        for (String type : List.of("subcat", "category")) {
            Optional<Presets> result = presets.stream().filter(Objects::nonNull)
                    .filter(p -> type.equals(p.getType()) && p.getValues() != null)
                    .filter(p -> p.getValues().stream().anyMatch(Assembly64Client::validCategory)).findFirst();
            if (result.isPresent()) return result;
        }
        return Optional.empty();
    }

    private static boolean validCategory(PresetEntry entry) {
        return entry != null && entry.getId() != null && entry.getAqlKey() != null && !entry.getAqlKey().isBlank()
                && entry.getName() != null && !entry.getName().isBlank();
    }

    public static String categoryType(Collection<Presets> presets) {
        return categoryPreset(presets).map(Presets::getType).orElse("category");
    }

    public static List<Category> categories(Collection<Presets> presets) {
        return categoryPreset(presets).map(Presets::getValues).orElse(Collections.emptyList()).stream()
                .filter(Assembly64Client::validCategory).map(Category::new)
                .sorted(Comparator.comparing(Category::getName)).collect(Collectors.toList());
    }

    public JsonNode search(String query, int offset, int limit) throws IOException {
        if (offset < 0 || limit < 1 || limit > 500) throw new IllegalArgumentException("Invalid Assembly64 page");
        JsonNode result = read("/leet/search/aql/" + offset + "/" + limit + "?query=" + segment(query));
        if (!result.isArray()) throw new IOException("Invalid Assembly64 search results");
        return result;
    }

    public ContentEntrySearchResult entries(String itemId, String categoryId) throws IOException {
        JsonNode response = read("/leet/search/entries/" + segment(itemId) + "/" + segment(categoryId));
        if (!response.path("contentEntry").isArray()) throw new IOException("Invalid Assembly64 entries");
        ContentEntrySearchResult result = MAPPER.treeToValue(response, ContentEntrySearchResult.class);
        result.getContentEntry().removeIf(entry -> entry == null || entry.getId() == null
                || entry.getPath() == null || entry.getPath().isBlank());
        return result;
    }

    public InputStream download(String itemId, String categoryId, ContentEntry entry) throws IOException {
        return open("/leet/search/bin/" + segment(itemId) + "/" + segment(categoryId) + "/" + segment(entry.getId()))
                .getInputStream();
    }

    private JsonNode read(String path) throws IOException {
        try (InputStream input = open(path).getInputStream()) {
            JsonNode result = MAPPER.readTree(input);
            if (result == null || result.isNull()) throw new IOException("Empty Assembly64 response");
            return result;
        }
    }

    private URLConnection open(String path) throws IOException {
        try {
            Map<String, String> headers = new HashMap<>(ASSEMBLY64_HEADERS);
            headers.putAll(Assembly64Credentials.load().headers(server, adminAccess));
            URLConnection connection = InternetUtil.openConnection(
                    new URI(server.getUrl().replaceAll("/+$", "") + path).toURL(),
                    configuration.getSidplay2Section(), headers, CONNECTION_TIMEOUT, UPSTREAM_AUTHENTICATOR);
            return connection;
        } catch (URISyntaxException | IllegalArgumentException e) {
            throw new IOException("Invalid Assembly64 server URL", e);
        }
    }

    private static String segment(String value) {
        return URLEncoder.encode(Objects.requireNonNull(value), UTF_8).replace("+", "%20");
    }
}