|
7 | 7 | import net.dv8tion.jda.api.events.guild.voice.GuildVoiceUpdateEvent;
|
8 | 8 | import org.apache.commons.lang3.tuple.Pair;
|
9 | 9 | import org.jetbrains.annotations.NotNull;
|
| 10 | +import org.slf4j.Logger; |
| 11 | +import org.slf4j.LoggerFactory; |
10 | 12 |
|
11 | 13 | import org.togetherjava.tjbot.config.Config;
|
12 | 14 | import org.togetherjava.tjbot.features.VoiceReceiverAdapter;
|
|
19 | 21 | import java.util.Optional;
|
20 | 22 | import java.util.Queue;
|
21 | 23 | import java.util.concurrent.CompletableFuture;
|
| 24 | +import java.util.concurrent.Executor; |
| 25 | +import java.util.concurrent.TimeUnit; |
22 | 26 | import java.util.concurrent.atomic.AtomicBoolean;
|
23 | 27 | import java.util.function.Predicate;
|
24 | 28 | import java.util.regex.Matcher;
|
|
41 | 45 | */
|
42 | 46 | public class DynamicVoiceListener extends VoiceReceiverAdapter {
|
43 | 47 |
|
| 48 | + private final Logger logger = LoggerFactory.getLogger(DynamicVoiceListener.class); |
| 49 | + |
44 | 50 | private final Map<String, Predicate<String>> channelPredicates = new HashMap<>();
|
45 | 51 | private static final Pattern channelTopicPattern = Pattern.compile("(\\s+\\d+)$");
|
46 | 52 |
|
47 | 53 | /** Map of event queues for each channel topic. */
|
48 |
| - private static final Map<String, Queue<GuildVoiceUpdateEvent>> eventQueues = new HashMap<>(); |
| 54 | + private final Map<String, Queue<GuildVoiceUpdateEvent>> eventQueues = new HashMap<>(); |
49 | 55 |
|
50 | 56 | /** Map to track if an event queue is currently being processed for each channel topic. */
|
51 |
| - private static final Map<String, AtomicBoolean> activeQueuesMap = new HashMap<>(); |
| 57 | + private final Map<String, AtomicBoolean> activeQueuesMap = new HashMap<>(); |
| 58 | + |
| 59 | + /** Boolean to track if events from all queues should be handled at a slower rate. */ |
| 60 | + private final AtomicBoolean slowmode = new AtomicBoolean(false); |
| 61 | + private final Executor eventQueueExecutor = |
| 62 | + CompletableFuture.delayedExecutor(1L, TimeUnit.SECONDS); |
| 63 | + private static final int SLOWMODE_THRESHOLD = 5; |
52 | 64 |
|
53 | 65 | /**
|
54 | 66 | * Initializes a new {@link DynamicVoiceListener} with the specified configuration.
|
@@ -85,11 +97,19 @@ private void insertEventToQueue(GuildVoiceUpdateEvent event, String channelTopic
|
85 | 97 | }
|
86 | 98 |
|
87 | 99 | eventQueue.add(event);
|
| 100 | + slowmode.set(eventQueue.size() >= SLOWMODE_THRESHOLD); |
88 | 101 |
|
89 | 102 | if (activeQueuesMap.get(channelTopic).get()) {
|
90 | 103 | return;
|
91 | 104 | }
|
92 | 105 |
|
| 106 | + if (slowmode.get()) { |
| 107 | + logger.info("Running with slowmode"); |
| 108 | + CompletableFuture.runAsync(() -> processEventFromQueue(channelTopic), |
| 109 | + eventQueueExecutor); |
| 110 | + return; |
| 111 | + } |
| 112 | + |
93 | 113 | processEventFromQueue(channelTopic);
|
94 | 114 | }
|
95 | 115 |
|
|
0 commit comments