package app.updates; import app.entities.server.Server; import app.services.io.GeoIP; import app.entities.Stats; import com.maxmind.geoip2.exception.GeoIp2Exception; import jakarta.annotation.PostConstruct; import jakarta.persistence.EntityManager; import jakarta.persistence.PersistenceContext; import org.jobrunr.jobs.annotations.Job; import org.jobrunr.scheduling.JobScheduler; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.io.IOException; import java.net.UnknownHostException; import java.util.Map; @Component public class CountriesUpdater { Stats stats; GeoIP geoIP; JobScheduler jobScheduler; @PersistenceContext EntityManager entityManager; @Value("${backend.updates.countries}") private boolean update; private final String countries_in_current_year = "SELECT DISTINCT `connect_ip` FROM `%s`.`user_connections` WHERE connection_type LIKE 'connect' AND `timestamp` > CAST(DATE_FORMAT(NOW() ,'%%Y-01-01') as DATE) UNION\n"; @Autowired public CountriesUpdater(Stats stats, GeoIP geoIP, JobScheduler jobScheduler) { this.stats = stats; this.geoIP = geoIP; this.jobScheduler = jobScheduler; } @PostConstruct public void UpdateCountries(){ if (update) { jobScheduler.enqueue(() -> UpdateCountriesStatistic()); jobScheduler.scheduleRecurrently("backend.stats.countries.update", "*/15 * * * *", () -> UpdateCountriesStatistic()); } } @Job(name = "Update countries statistic", retries = 0) public void UpdateCountriesStatistic() { stats.getCountries().clear(); String query = ""; for (Map.Entry stringServerEntry : stats.getServers().entrySet()) { query += countries_in_current_year.formatted(stringServerEntry.getValue().getDb()); } query = query.substring(0, query.length()-7) + ";"; for(Object ip:entityManager.createNativeQuery(query).getResultList()) { try { stats.getCountries().merge(geoIP.GetCountry(String.valueOf(ip)), 1, (x, y) -> x+y); } catch (UnknownHostException e) { } catch (IOException e) { } catch (GeoIp2Exception e) { } } } }