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

This commit is contained in:
vladp
2026-04-15 09:34:32 +07:00
parent 40cb53a3b0
commit a7939845c7
5 changed files with 76 additions and 4 deletions
@@ -0,0 +1,51 @@
package ru.soune.nocopy.service.geo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CountryResponse;
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;
@Service
@Slf4j
public class GeoCountryService {
private final DatabaseReader dbReader;
public GeoCountryService() throws IOException {
Resource resource = new ClassPathResource("geo/GeoLite2-Country.mmdb");
this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build();
}
public String getCountry(String input) {
try {
String domain = extractDomain(input);
InetAddress ip = InetAddress.getByName(domain);
CountryResponse response = dbReader.country(ip);
return response.getCountry().getIsoCode();
} catch (Exception e) {
log.error("Failed for input: {}", input, e);
return "UNKNOWN";
}
}
private String extractDomain(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Input is empty");
}
String cleaned = input.replaceAll("^https?://", "");
cleaned = cleaned.split("/")[0];
cleaned = cleaned.split(":")[0];
return cleaned;
}
}