Files
no-copy/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java
T
vladp c60aeec6f5
Test Workflow / test (push) Successful in 3s
dev add geo country service
2026-04-15 10:25:25 +07:00

66 lines
1.9 KiB
Java

package ru.soune.nocopy.service.geo;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
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 getCountryName(String input) {
try {
CountryResponse response = extractCountry(input);
return response.getCountry().getName();
} catch (Exception e) {
log.error("Failed for input: {}", input, e);
return "UNKNOWN";
}
}
public String getCountryCode(String input) {
try {
CountryResponse response = extractCountry(input);
return response.getCountry().getIsoCode();
} catch (Exception e) {
log.error("Failed for input: {}", input, e);
return "UNKNOWN";
}
}
private CountryResponse extractCountry(String input) throws IOException, GeoIp2Exception {
String domain = extractDomain(input);
InetAddress ip = InetAddress.getByName(domain);
return dbReader.country(ip);
}
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;
}
}