dev add geo country service
Test Workflow / test (push) Successful in 3s

This commit is contained in:
vladp
2026-04-15 09:59:38 +07:00
parent eb43621b74
commit 684888aa2c
@@ -2,50 +2,61 @@ package ru.soune.nocopy.service.geo;
import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse; import com.maxmind.geoip2.model.CountryResponse;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.IOException;
import java.net.InetAddress; import java.net.InetAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@Service @Service
@Slf4j @Slf4j
public class GeoCountryService { public class GeoCountryService {
private DatabaseReader dbReader;
private final DatabaseReader dbReader; private final Map<String, String> cache = new ConcurrentHashMap<>();
public GeoCountryService() throws IOException { @PostConstruct
Resource resource = new ClassPathResource("geo/GeoLite2-Country.mmdb"); public void init() {
try {
var resource = new ClassPathResource("geo/GeoLite2-Country.mmdb");
this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build(); this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build();
log.info("Geo DB loaded");
} catch (Exception e) {
log.error("Failed to load Geo DB", e);
throw new RuntimeException(e);
}
}
public String getCountry(String url) {
if (url == null || url.isBlank()) {
return null;
}
String host = extractHost(url);
if (cache.containsKey(host)) {
return cache.get(host);
} }
public String getCountry(String input) {
try { try {
String domain = extractDomain(input); InetAddress ip = InetAddress.getByName(host);
InetAddress ip = InetAddress.getByName(domain);
CountryResponse response = dbReader.country(ip); CountryResponse response = dbReader.country(ip);
String country = response.getCountry().getIsoCode();
return response.getCountry().getIsoCode(); cache.put(host, country);
return country;
} catch (Exception e) { } catch (Exception e) {
log.error("Failed for input: {}", input, e); log.debug("Cannot determine country for: {}", host);
return "UNKNOWN"; cache.put(host, null);
return null;
} }
} }
private String extractDomain(String input) { private String extractHost(String url) {
if (input == null || input.isEmpty()) { String cleaned = url.replaceFirst("^https?://", "");
throw new IllegalArgumentException("Input is empty"); return cleaned.split("[/:]")[0];
}
String cleaned = input.replaceAll("^https?://", "");
cleaned = cleaned.split("/")[0];
cleaned = cleaned.split(":")[0];
return cleaned;
} }
} }