1
1
package net .discordjug .javabot .systems .staff_activity ;
2
2
3
+ import java .time .Duration ;
4
+ import java .time .Instant ;
5
+ import java .time .temporal .ChronoUnit ;
3
6
import java .time .temporal .TemporalAccessor ;
4
7
import java .util .Iterator ;
5
8
import java .util .List ;
9
+ import java .util .Map ;
10
+ import java .util .concurrent .ConcurrentHashMap ;
6
11
7
12
import org .springframework .stereotype .Service ;
8
13
29
34
public class StaffActivityService {
30
35
private final BotConfig botConfig ;
31
36
private final StaffActivityMessageRepository repository ;
37
+ private final Map <StaffActivityKey , Instant > lastActivities = new ConcurrentHashMap <>();
32
38
33
39
/**
34
40
* Updates the staff activity message or creates it if necessary.
@@ -43,6 +49,17 @@ public void updateStaffActivity(StaffActivityType type, TemporalAccessor timesta
43
49
if (staffActivityChannel == null ) {
44
50
return ;
45
51
}
52
+ Instant now = Instant .now ();
53
+ Instant merged = lastActivities .merge (new StaffActivityKey (member .getGuild ().getIdLong (), member .getIdLong (), type ), now , (oldValue , currentInstant ) -> {
54
+ if (timeDifferenceIsBelowRateLimit (oldValue , currentInstant )) {
55
+ // less than 5 minutes since insertion
56
+ return oldValue ;
57
+ }
58
+ return currentInstant ;
59
+ });
60
+ if (!merged .equals (now )) {
61
+ return ;
62
+ }
46
63
Long msgId = repository .getMessageId (staffActivityChannel .getGuild ().getIdLong (), member .getIdLong ());
47
64
if (msgId != null ) {
48
65
staffActivityChannel
@@ -53,6 +70,12 @@ public void updateStaffActivity(StaffActivityType type, TemporalAccessor timesta
53
70
} else {
54
71
createNewMessage (staffActivityChannel , member , type , timestamp );
55
72
}
73
+ lastActivities .entrySet ()
74
+ .removeIf (e -> !timeDifferenceIsBelowRateLimit (e .getValue (),now ));
75
+ }
76
+
77
+ private boolean timeDifferenceIsBelowRateLimit (Instant oldValue , Instant currentInstant ) {
78
+ return Duration .between (oldValue , currentInstant ).minus (Duration .of (5 , ChronoUnit .MINUTES )).isNegative ();
56
79
}
57
80
58
81
private void replaceActivityMessage (StaffActivityType type , TemporalAccessor timestamp , Message activityMessage , Member member ) {
@@ -96,4 +119,6 @@ private MessageEmbed createEmptyStaffActivityEmbed(Member member) {
96
119
.setFooter (member .getId ())
97
120
.build ();
98
121
}
122
+
123
+ private record StaffActivityKey (long guildId , long memberId , StaffActivityType type ) {}
99
124
}
0 commit comments