package app.updates; import app.entities.Stats; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.annotation.PostConstruct; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import org.springframework.web.client.RestTemplate; import java.io.IOException; import java.net.URL; import java.time.Instant; @Component public class SocialUpdater extends BaseUpdater{ RestTemplate restTemplate; ObjectMapper objectMapper; Stats stats; private final Logger logger = LoggerFactory.getLogger(SocialUpdater.class); @Value("${backend.social.discord}") private String discord_url = ""; @Value("${backend.social.vk}") private String vk_url; @Autowired public SocialUpdater(Stats stats) { restTemplate = new RestTemplate(); objectMapper = new ObjectMapper(); this.stats = stats; } @PostConstruct public void SetUpdater(){ if(!discord_url.isEmpty()) { logger.warn("Discord count updater enabled"); CreateTaskUpdater(this::UpdateDiscordCount, 5 * 60 * 1000, getClass().getName() + "_discord"); } if(!vk_url.isEmpty()){ logger.warn("VK count updater enabled"); CreateTaskUpdater(this::UpdateVKCount, 5 * 60 * 1000, getClass().getName() + "_vk"); } } public boolean UpdateDiscordCount(){ try { logger.info("Request discord count users"); stats.setDiscord_users(objectMapper.readTree(new URL(discord_url)).get("approximate_member_count").asInt()); stats.getUpdates().merge("discord_count", Instant.now().getEpochSecond(), (x, y) -> y); } catch (IOException err) {} return true; } public boolean UpdateVKCount() { logger.info("Request vk group count users"); try { int count = 0; String response = restTemplate.getForEntity(vk_url, String.class).getBody(); int k_start = response.indexOf("

") + "

".length(); int k_end = response.indexOf("<", k_start); count += Integer.valueOf(response.substring(k_start, k_end)) * 1000; int s_start = response.indexOf("", k_end) + "".length(); int s_end = response.indexOf(" ", s_start); count += Integer.valueOf(response.substring(s_start, s_end)); stats.setVk_users(count); stats.getUpdates().merge("vk_count", Instant.now().getEpochSecond(), (x, y) -> y); } catch (NumberFormatException nfe) { logger.error("Cannot update vk group count"); } return true; } }