Plan/Plan/common/src/main/java/com/djrapitops/plan/gathering/cache/GeolocationCache.java

203 lines
7.1 KiB
Java
Raw Normal View History

/*
* This file is part of Player Analytics (Plan).
*
* Plan is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License v3 as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Plan is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Plan. If not, see <https://www.gnu.org/licenses/>.
*/
package com.djrapitops.plan.gathering.cache;
import com.djrapitops.plan.SubSystem;
Interface redesign package restructuring (#1146) * command.commands -> command.subcommands * command -> commands * commands -> system.commands * system.locale -> system.settings.locale * system.settings.changes -> system.settings.config.changes * system.settings.paths -> system.settings.config.paths * system.database -> system.storage.database * db -> system.storage.database * system.storage.database.access.queries -> system.storage.database.queries * system.storage.database.access.transactions -> system.storage.database.transactions * system.storage.database.access -> system.storage.database.operation * Moved Query classes to system.storage.database.queries * Moved Executable classes to system.storage.database.transactions * system.storage.database.patches -> system.storage.database.transactions.patches * system.file -> system.storage.file * system.settings.upkeep * system.storage.upkeep * system.server.info -> system.identification * system.importing -> system.gathering.importing * system.listeners -> system.gathering.listeners * system.gathering.timed * Removed duplicate class * data.container -> system.gathering.domain * data.plugin.PluginsConfigSection -> system.settings.config.ExtensionSettings * data.time -> system.gathering.domain * system.afk -> system.gathering.afk * system.cache -> system.gathering.cache * system.status -> system.gathering.listeners * system.export -> system.delivery.export * system.webserver -> system.delivery.webserver * system.json -> system.delivery.rendering.json * utilities.html -> system.delivery.rendering.html * system.delivery.rendering.html.graphs -> system.delivery.rendering.json.graphs * system.delivery.rendering.html.pages -> system.delivery.rendering.pages * system.delivery.upkeep * utilities.file -> system.settings.upkeep * data.store -> system.delivery.domain * system.update -> system.version * api.exceptions -> exceptions * ShutdownHook -> system.gathering * system.HtmlUtilities - > system.delivery.DeliveryUtilities * PeriodicAnalysisTask -> PeriodicServerExportTask * Deprecated APIv4 classes * Removed ServerTaskSystem (Reduces headache) * Moved & Fixed some tests
2019-08-30 11:36:38 +02:00
import com.djrapitops.plan.exceptions.EnableException;
import com.djrapitops.plan.settings.config.PlanConfig;
import com.djrapitops.plan.settings.config.paths.DataGatheringSettings;
import com.djrapitops.plan.settings.locale.Locale;
import com.djrapitops.plan.settings.locale.lang.PluginLang;
import com.djrapitops.plan.storage.file.PlanFiles;
import com.djrapitops.plugin.logging.L;
import com.djrapitops.plugin.logging.console.PluginLogger;
2019-08-31 11:31:56 +02:00
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
2017-09-03 17:09:07 +02:00
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.Country;
import javax.inject.Inject;
import javax.inject.Singleton;
2017-09-03 17:09:07 +02:00
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
2017-09-03 17:09:07 +02:00
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
2017-09-03 17:09:07 +02:00
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
2017-09-03 17:09:07 +02:00
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
2019-08-31 11:31:56 +02:00
import java.util.concurrent.TimeUnit;
2017-09-03 17:09:07 +02:00
import java.util.zip.GZIPInputStream;
/**
* This class contains the geolocation cache.
* <p>
* It caches all IPs with their matching country.
*
* @author Fuzzlemann
*/
@Singleton
public class GeolocationCache implements SubSystem {
private final Locale locale;
private final PlanFiles files;
private final PlanConfig config;
private final PluginLogger logger;
2019-08-31 11:31:56 +02:00
private final Cache<String, String> cache;
private File geolocationDB;
@Inject
public GeolocationCache(
Locale locale,
PlanFiles files,
PlanConfig config,
PluginLogger logger
) {
this.locale = locale;
this.files = files;
this.config = config;
this.logger = logger;
2019-08-31 11:31:56 +02:00
this.cache = Caffeine.newBuilder()
.expireAfterAccess(1, TimeUnit.MINUTES)
.build();
}
@Override
public void enable() throws EnableException {
geolocationDB = files.getFileFromPluginFolder("GeoIP.dat");
if (config.isTrue(DataGatheringSettings.GEOLOCATIONS)) {
try {
checkDB();
} catch (UnknownHostException e) {
logger.error(locale.getString(PluginLang.ENABLE_NOTIFY_GEOLOCATIONS_INTERNET_REQUIRED));
} catch (IOException e) {
throw new EnableException(locale.getString(PluginLang.ENABLE_FAIL_GEODB_WRITE), e);
}
} else {
logger.log(L.INFO_COLOR, "§e" + locale.getString(PluginLang.ENABLE_NOTIFY_GEOLOCATIONS_DISABLED));
}
}
/**
* Retrieves the country in full length (e.g. United States) from the IP Address.
* <p>
2018-08-12 11:21:13 +02:00
* This method uses {@code cached}, every first access is getting cached and then retrieved later.
*
* @param ipAddress The IP Address from which the country is retrieved
* @return The name of the country in full length.
* <p>
* An exception from that rule is when the country is unknown or the retrieval of the country failed in any way,
* if that happens, "Not Known" will be returned.
* @see #getUnCachedCountry(String)
*/
public String getCountry(String ipAddress) {
2019-08-31 11:31:56 +02:00
return cache.get(ipAddress, this::getUnCachedCountry);
}
/**
* Retrieves the country in full length (e.g. United States) from the IP Address.
* <p>
2017-09-03 17:09:07 +02:00
* This product includes GeoLite2 data created by MaxMind, available from
* <a href="http://www.maxmind.com">http://www.maxmind.com</a>.
*
* @param ipAddress The IP Address from which the country is retrieved
* @return The name of the country in full length.
* <p>
* An exception from that rule is when the country is unknown or the retrieval of the country failed in any way,
* if that happens, "Not Known" will be returned.
2017-09-03 17:09:07 +02:00
* @see <a href="http://maxmind.com">http://maxmind.com</a>
* @see #getCountry(String)
*/
private String getUnCachedCountry(String ipAddress) {
2017-09-26 17:28:51 +02:00
if ("127.0.0.1".equals(ipAddress)) {
return "Local Machine";
}
2017-09-03 17:09:07 +02:00
try {
checkDB();
try (
// See https://github.com/maxmind/MaxMind-DB-Reader-java#file-lock-on-windows
// for why InputStream is being used here instead.
InputStream in = Files.newInputStream(geolocationDB.toPath());
DatabaseReader reader = new DatabaseReader.Builder(in).build()
) {
2017-09-03 17:09:07 +02:00
InetAddress inetAddress = InetAddress.getByName(ipAddress);
2017-09-03 17:09:07 +02:00
CountryResponse response = reader.country(inetAddress);
Country country = response.getCountry();
String countryName = country.getName();
return countryName != null ? countryName : "Not Known";
2017-09-03 17:09:07 +02:00
}
2017-09-03 17:09:07 +02:00
} catch (IOException | GeoIp2Exception e) {
return "Not Known";
}
}
2017-09-03 17:09:07 +02:00
/**
* Checks if the DB exists, if not, it downloads it
*
2017-11-19 11:15:16 +01:00
* @throws IOException when an error at download or saving the DB happens
2017-09-03 17:09:07 +02:00
*/
private void checkDB() throws IOException {
if (geolocationDB.exists()) {
2017-09-03 17:09:07 +02:00
return;
}
URL downloadSite = new URL("http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country.mmdb.gz");
try (
InputStream in = downloadSite.openStream();
GZIPInputStream gzipIn = new GZIPInputStream(in);
ReadableByteChannel rbc = Channels.newChannel(gzipIn);
FileOutputStream fos = new FileOutputStream(geolocationDB.getAbsoluteFile());
FileChannel channel = fos.getChannel()
) {
channel.transferFrom(rbc, 0, Long.MAX_VALUE);
}
}
/**
* Checks if the IP Address is cached
*
* @param ipAddress The IP Address which is checked
* @return true if the IP Address is cached
*/
boolean isCached(String ipAddress) {
2019-08-31 11:31:56 +02:00
return cache.getIfPresent(ipAddress) != null;
2018-08-12 11:21:13 +02:00
}
@Override
public void disable() {
2019-08-31 11:31:56 +02:00
clearCache();
}
2017-09-03 17:09:07 +02:00
/**
* Clears the cache
*/
public void clearCache() {
2019-08-31 11:31:56 +02:00
cache.invalidateAll();
cache.cleanUp();
}
}