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;
|
2026-04-15 09:59:38 +07:00
|
|
|
import jakarta.annotation.PostConstruct;
|
2026-04-15 09:34:32 +07:00
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
|
|
import org.springframework.core.io.ClassPathResource;
|
|
|
|
|
import org.springframework.stereotype.Service;
|
|
|
|
|
|
|
|
|
|
import java.net.InetAddress;
|
2026-04-15 09:59:38 +07:00
|
|
|
import java.util.Map;
|
|
|
|
|
import java.util.concurrent.ConcurrentHashMap;
|
2026-04-15 09:34:32 +07:00
|
|
|
|
|
|
|
|
@Service
|
|
|
|
|
@Slf4j
|
|
|
|
|
public class GeoCountryService {
|
|
|
|
|
|
2026-04-15 10:10:46 +07:00
|
|
|
private DatabaseReader dbReader;
|
2026-04-15 09:59:38 +07:00
|
|
|
private final Map<String, String> cache = new ConcurrentHashMap<>();
|
2026-04-15 09:34:32 +07:00
|
|
|
|
2026-04-15 09:59:38 +07:00
|
|
|
@PostConstruct
|
|
|
|
|
public void init() {
|
|
|
|
|
try {
|
|
|
|
|
var 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);
|
|
|
|
|
}
|
2026-04-15 09:34:32 +07:00
|
|
|
}
|
|
|
|
|
|
2026-04-15 10:10:46 +07:00
|
|
|
public String getCountry(String input) {
|
|
|
|
|
if (input == null || input.isBlank()) {
|
2026-04-15 09:59:38 +07:00
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-15 10:10:46 +07:00
|
|
|
String host = extractHost(input);
|
|
|
|
|
|
2026-04-15 09:59:38 +07:00
|
|
|
if (cache.containsKey(host)) {
|
|
|
|
|
return cache.get(host);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-15 09:34:32 +07:00
|
|
|
try {
|
2026-04-15 09:59:38 +07:00
|
|
|
InetAddress ip = InetAddress.getByName(host);
|
2026-04-15 09:34:32 +07:00
|
|
|
CountryResponse response = dbReader.country(ip);
|
2026-04-15 09:59:38 +07:00
|
|
|
String country = response.getCountry().getIsoCode();
|
2026-04-15 09:34:32 +07:00
|
|
|
|
2026-04-15 10:10:46 +07:00
|
|
|
cache.put(host, country != null ? country : "");
|
|
|
|
|
log.debug("{} → {}", host, country);
|
2026-04-15 09:59:38 +07:00
|
|
|
return country;
|
2026-04-15 09:34:32 +07:00
|
|
|
|
|
|
|
|
} catch (Exception e) {
|
2026-04-15 10:10:46 +07:00
|
|
|
cache.put(host, "");
|
2026-04-15 09:59:38 +07:00
|
|
|
return null;
|
2026-04-15 09:34:32 +07:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-15 10:10:46 +07:00
|
|
|
private String extractHost(String input) {
|
|
|
|
|
String s = input.replaceFirst("^https?://", "");
|
|
|
|
|
s = s.split("/")[0];
|
|
|
|
|
s = s.split(":")[0];
|
|
|
|
|
|
|
|
|
|
return s;
|
2026-04-15 09:34:32 +07:00
|
|
|
}
|
2026-04-15 10:10:46 +07:00
|
|
|
}
|