Files
no-copy/src/main/java/ru/soune/nocopy/service/geo/GeoCountryService.java
T

50 lines
1.4 KiB
Java
Raw Normal View History

2026-04-15 09:34:32 +07:00
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;
2026-04-15 10:17:47 +07:00
import org.springframework.core.io.Resource;
2026-04-15 09:34:32 +07:00
import org.springframework.stereotype.Service;
2026-04-15 10:17:47 +07:00
import java.io.IOException;
2026-04-15 09:34:32 +07:00
import java.net.InetAddress;
@Service
@Slf4j
public class GeoCountryService {
2026-04-15 10:17:47 +07:00
private final DatabaseReader dbReader;
2026-04-15 09:34:32 +07:00
2026-04-15 10:17:47 +07:00
public GeoCountryService() throws IOException {
Resource resource = new ClassPathResource("geo/GeoLite2-Country.mmdb");
this.dbReader = new DatabaseReader.Builder(resource.getInputStream()).build();
2026-04-15 09:34:32 +07:00
}
2026-04-15 10:10:46 +07:00
public String getCountry(String input) {
2026-04-15 09:34:32 +07:00
try {
2026-04-15 10:17:47 +07:00
String domain = extractDomain(input);
InetAddress ip = InetAddress.getByName(domain);
2026-04-15 09:34:32 +07:00
CountryResponse response = dbReader.country(ip);
2026-04-15 10:17:47 +07:00
return response.getCountry().getName();
2026-04-15 09:34:32 +07:00
} catch (Exception e) {
2026-04-15 10:17:47 +07:00
log.error("Failed for input: {}", input, e);
return "UNKNOWN";
2026-04-15 09:34:32 +07:00
}
}
2026-04-15 10:17:47 +07:00
private String extractDomain(String input) {
if (input == null || input.isEmpty()) {
throw new IllegalArgumentException("Input is empty");
}
2026-04-15 10:10:46 +07:00
2026-04-15 10:17:47 +07:00
String cleaned = input.replaceAll("^https?://", "");
cleaned = cleaned.split("/")[0];
cleaned = cleaned.split(":")[0];
return cleaned;
2026-04-15 09:34:32 +07:00
}
2026-04-15 10:10:46 +07:00
}