52 lines
1.4 KiB
Java
52 lines
1.4 KiB
Java
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;
|
|
}
|
|
}
|