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

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