Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ru.mralexeimk.minecraft.islandia.services;
- import lombok.Getter;
- import org.bukkit.entity.Player;
- import org.springframework.scheduling.annotation.Scheduled;
- import org.springframework.stereotype.Service;
- import ru.mralexeimk.minecraft.islandia.builders.MessageConstructor;
- import ru.mralexeimk.minecraft.islandia.services.additional.LogService;
- import java.util.HashMap;
- import java.util.Map;
- import java.util.UUID;
- import java.util.concurrent.ConcurrentHashMap;
- @Service
- public class CooldownService {
- private final ConfigService configService;
- private final LogService logService;
- @Getter
- private final ConcurrentHashMap<UUID, Map<String, Long>> playersCooldowns = new ConcurrentHashMap<>();
- public CooldownService(ConfigService configService, LogService logService) {
- this.configService = configService;
- this.logService = logService;
- }
- private void add(Player p, String tag, long periodSeconds) {
- Map<String, Long> cd = playersCooldowns.getOrDefault(p.getUniqueId(),
- new HashMap<>());
- cd.put(tag, System.currentTimeMillis() / 1000 + periodSeconds);
- playersCooldowns.put(p.getUniqueId(), cd);
- }
- /**
- * Clear 'playersCooldowns' every 30 minutes
- */
- @Scheduled(fixedDelay = 1000*60*30)
- public void clear() {
- if(playersCooldowns.isEmpty()) return;
- for(UUID uuid : playersCooldowns.keySet()) {
- if(!playersCooldowns.containsKey(uuid)) continue;
- for(String tag : playersCooldowns.get(uuid).keySet()) {
- long curTime = System.currentTimeMillis() / 1000;
- Long endTime = playersCooldowns.get(uuid).get(tag);
- if(endTime == null || curTime >= endTime) {
- playersCooldowns.get(uuid).remove(tag);
- }
- }
- if(playersCooldowns.get(uuid).isEmpty()) {
- playersCooldowns.remove(uuid);
- }
- }
- }
- /**
- * Set cooldown for player at this line of code
- * @return next lines of code will be run?
- */
- public boolean cooldown(Player p, String tag, long periodSeconds) {
- if(p.hasPermission("islandia.admin")) return true;
- if(!playersCooldowns.containsKey(p.getUniqueId()) ||
- !playersCooldowns.get(p.getUniqueId()).containsKey(tag)) {
- add(p, tag, periodSeconds);
- return true;
- }
- long curTime = System.currentTimeMillis() / 1000;
- long endTime = playersCooldowns.get(p.getUniqueId()).get(tag);
- if(curTime >= endTime) {
- add(p, tag, periodSeconds);
- return true;
- }
- MessageConstructor
- .of(configService.getMessage(p, "cooldown"))
- .replace("%cooldown%", String.valueOf(endTime - curTime))
- .send(p);
- return false;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment