-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathAbstractChatHandler.java
More file actions
339 lines (282 loc) · 13.4 KB
/
AbstractChatHandler.java
File metadata and controls
339 lines (282 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package com.earth2me.essentials.chat.processing;
import com.earth2me.essentials.ChargeException;
import com.earth2me.essentials.Essentials;
import com.earth2me.essentials.Trade;
import com.earth2me.essentials.User;
import com.earth2me.essentials.chat.EssentialsChat;
import com.earth2me.essentials.utils.AdventureUtil;
import com.earth2me.essentials.utils.FormatUtil;
import net.ess3.api.events.LocalChatSpyEvent;
import net.essentialsx.api.v2.ChatType;
import net.essentialsx.api.v2.events.chat.ChatEvent;
import net.essentialsx.api.v2.events.chat.GlobalChatEvent;
import net.essentialsx.api.v2.events.chat.LocalChatEvent;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.Server;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import org.bukkit.scoreboard.Team;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import java.util.logging.Level;
import static com.earth2me.essentials.I18n.tlLiteral;
public abstract class AbstractChatHandler {
protected final Essentials ess;
protected final EssentialsChat essChat;
protected final Server server;
protected final ChatProcessingCache cache;
protected AbstractChatHandler(Essentials ess, EssentialsChat essChat) {
this.ess = ess;
this.essChat = essChat;
this.server = ess.getServer();
this.cache = new ChatProcessingCache();
}
/**
* Apply chat formatting from config and from translations according to chat type.
* <p>
* Handled at {@link org.bukkit.event.EventPriority#LOWEST} on both preview and chat events.
*/
protected void handleChatFormat(AsyncPlayerChatEvent event) {
if (isAborted(event)) {
return;
}
final User user = ess.getUser(event.getPlayer());
if (user == null) {
event.setCancelled(true);
return;
}
// Ensure we're getting the latest display name
user.setDisplayNick();
// Reuse cached IntermediateChat if available
ChatProcessingCache.ProcessedChat chat = cache.getProcessedChat(event.getPlayer());
if (chat == null) {
chat = new ChatProcessingCache.ProcessedChat(user, getChatType(user, event.getMessage()), event.getMessage());
cache.setProcessedChat(event.getPlayer(), chat);
}
final long configRadius = ess.getSettings().getChatRadius();
chat.setRadius(Math.max(configRadius, 0));
// This listener should apply the general chat formatting only...then return control back the event handler
event.setMessage(FormatUtil.formatMessage(user, "essentials.chat", event.getMessage()));
if (ChatColor.stripColor(event.getMessage()).length() == 0) {
event.setCancelled(true);
return;
}
final String group = user.getGroup();
final String world = user.getWorld().getName();
final String username = user.getName();
final String nickname = user.getFormattedNickname();
final Player player = user.getBase();
final String prefix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(player));
final String suffix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(player));
final Team team = player.getScoreboard().getPlayerTeam(player);
String format = ess.getSettings().getChatFormat(group);
format = format.replace("{0}", group);
format = format.replace("{1}", ess.getSettings().getWorldAlias(world));
format = format.replace("{2}", world.substring(0, 1).toUpperCase(Locale.ENGLISH));
format = format.replace("{3}", team == null ? "" : team.getPrefix());
format = format.replace("{4}", team == null ? "" : team.getSuffix());
format = format.replace("{5}", team == null ? "" : team.getDisplayName());
format = format.replace("{6}", team == null ? "" : ("" + ChatColor.COLOR_CHAR + team.getColor().getChar()));
format = format.replace("{7}", prefix);
format = format.replace("{8}", suffix);
format = format.replace("{9}", username);
format = format.replace("{10}", nickname == null ? username : nickname);
// Local, shout and question chat types are only enabled when there's a valid radius
if (chat.getRadius() > 0 && event.getMessage().length() > 0) {
if (event.getMessage().length() > 1 && ((chat.getType() == ChatType.SHOUT && event.getMessage().charAt(0) == ess.getSettings().getChatShout()) || (chat.getType() == ChatType.QUESTION && event.getMessage().charAt(0) == ess.getSettings().getChatQuestion()))) {
event.setMessage(event.getMessage().substring(1));
}
if (chat.getType() == ChatType.UNKNOWN) {
format = AdventureUtil.miniToLegacy(tlLiteral("chatTypeLocal")).concat(format);
} else {
format = AdventureUtil.miniToLegacy(tlLiteral(chat.getType().key() + "Format", format));
}
}
// Long live pointless synchronized blocks!
synchronized (format) {
event.setFormat(format);
}
}
/**
* Handle the recipient filtering and permissions checks for local chat, if enabled.
* <p>
* Runs at {@link org.bukkit.event.EventPriority#NORMAL} priority on submitted chat events only.
*/
protected void handleChatRecipients(AsyncPlayerChatEvent event) {
if (isAborted(event)) {
return;
}
final ChatProcessingCache.Chat chat = cache.getProcessedChat(event.getPlayer());
// If local chat is enabled, handle the recipients here; else we have nothing to do
if (chat.getRadius() < 1) {
return;
}
final long radiusSquared = chat.getRadius() * chat.getRadius();
final User user = chat.getUser();
if (event.getMessage().length() > 0) {
if (chat.getType() == ChatType.UNKNOWN) {
if (!user.isAuthorized("essentials.chat.local")) {
user.sendTl("notAllowedToLocal");
event.setCancelled(true);
return;
}
event.getRecipients().removeIf(player -> !ess.getUser(player).isAuthorized("essentials.chat.receive.local"));
} else {
final String permission = "essentials.chat." + chat.getType().key();
if (user.isAuthorized(permission)) {
event.getRecipients().removeIf(player -> !ess.getUser(player).isAuthorized("essentials.chat.receive." + chat.getType().key()));
callChatEvent(event, chat.getType(), null);
} else {
final String chatType = chat.getType().name();
user.sendTl("notAllowedTo" + chatType.charAt(0) + chatType.substring(1).toLowerCase(Locale.ENGLISH));
event.setCancelled(true);
}
return;
}
}
final Location loc = user.getLocation();
final World world = loc.getWorld();
final Set<Player> outList = event.getRecipients();
final Set<Player> spyList = new HashSet<>();
try {
outList.add(event.getPlayer());
} catch (final UnsupportedOperationException ex) {
if (ess.getSettings().isDebug()) {
essChat.getLogger().log(Level.INFO, "Plugin triggered custom chat event, local chat handling aborted.", ex);
}
return;
}
final Iterator<Player> it = outList.iterator();
while (it.hasNext()) {
final Player onlinePlayer = it.next();
final User onlineUser = ess.getUser(onlinePlayer);
if (!onlineUser.equals(user)) {
boolean abort = false;
final Location playerLoc = onlineUser.getLocation();
if (playerLoc.getWorld() != world) {
abort = true;
} else {
final double delta = playerLoc.distanceSquared(loc);
if (delta > radiusSquared) {
abort = true;
}
}
if (abort) {
if (onlineUser.isAuthorized("essentials.chat.spy")) {
spyList.add(onlinePlayer);
}
it.remove();
}
}
}
callChatEvent(event, ChatType.LOCAL, chat.getRadius());
if (event.isCancelled()) {
return;
}
if (outList.size() < 2) {
user.sendTl("localNoOne");
}
// Strip local chat prefix to preserve API behaviour
final String localPrefix = AdventureUtil.miniToLegacy(tlLiteral("chatTypeLocal"));
String baseFormat = AdventureUtil.legacyToMini(event.getFormat());
if (event.getFormat().startsWith(localPrefix)) {
baseFormat = baseFormat.substring(localPrefix.length());
}
final LocalChatSpyEvent spyEvent = new LocalChatSpyEvent(event.isAsynchronous(), event.getPlayer(), baseFormat, event.getMessage(), spyList);
server.getPluginManager().callEvent(spyEvent);
if (!spyEvent.isCancelled()) {
final String legacyString = AdventureUtil.miniToLegacy(String.format(spyEvent.getFormat(), AdventureUtil.legacyToMini(user.getDisplayName()), AdventureUtil.escapeTags(spyEvent.getMessage())));
for (final Player onlinePlayer : spyEvent.getRecipients()) {
onlinePlayer.sendMessage(legacyString);
}
}
}
/**
* Re-create type-based chat event from the base chat event, call it and mirror changes back to the base chat event.
* @param event Event based on which a type-based event will be created, and to which changes will be applied.
* @param chatType Chat type which determines which event will be created and called.
* @param radius If chat is a local chat, this is a non-squared radius used to calculate recipients, otherwise {@code null}.
*/
protected void callChatEvent(final AsyncPlayerChatEvent event, final ChatType chatType, final Long radius) {
final ChatEvent chatEvent;
if (chatType == ChatType.LOCAL) {
chatEvent = new LocalChatEvent(event.isAsynchronous(), event.getPlayer(), event.getFormat(), event.getMessage(), event.getRecipients(), radius);
} else {
chatEvent = new GlobalChatEvent(event.isAsynchronous(), chatType, event.getPlayer(), event.getFormat(), event.getMessage(), event.getRecipients());
}
server.getPluginManager().callEvent(chatEvent);
event.setFormat(chatEvent.getFormat());
event.setMessage(chatEvent.getMessage());
event.setCancelled(chatEvent.isCancelled());
}
/**
* Finalise the formatting stage of chat processing.
* <p>
* Handled at {@link org.bukkit.event.EventPriority#HIGHEST} during previews, and immediately after
* {@link #handleChatFormat(AsyncPlayerChatEvent)} when previews are not available.
*/
protected void handleChatPostFormat(AsyncPlayerChatEvent event) {
if (isAborted(event)) {
cache.clearProcessedChat(event.getPlayer());
}
}
/**
* Run costs for chat and clean up the cached {@link com.earth2me.essentials.chat.processing.ChatProcessingCache.ProcessedChat}
*/
protected void handleChatSubmit(AsyncPlayerChatEvent event) {
if (isAborted(event)) {
return;
}
// This file should handle charging the user for the action before returning control back
charge(event, cache.getProcessedChat(event.getPlayer()));
cache.clearProcessedChat(event.getPlayer());
}
boolean isAborted(final AsyncPlayerChatEvent event) {
return event.isCancelled();
}
ChatType getChatType(final User user, final String message) {
if (message.length() == 0) {
//Ignore empty chat events generated by plugins
return ChatType.UNKNOWN;
}
final char shoutPrefix = ess.getSettings().getChatShout();
final char questionPrefix = ess.getSettings().getChatQuestion();
final char prefix = message.charAt(0);
final boolean singleChar = message.length() == 1;
if (singleChar) {
if (user.isToggleShout()) {
return ChatType.SHOUT;
}
return ChatType.UNKNOWN;
}
if (prefix == questionPrefix && ess.getSettings().isChatQuestionEnabled()) {
return ChatType.QUESTION;
} else if (prefix == shoutPrefix || user.isToggleShout()) {
return ChatType.SHOUT;
} else {
return ChatType.UNKNOWN;
}
}
private void charge(final User user, final Trade charge) throws ChargeException {
charge.charge(user);
}
boolean charge(final AsyncPlayerChatEvent event, final ChatProcessingCache.ProcessedChat chat) {
try {
charge(chat.getUser(), chat.getCharge());
} catch (final ChargeException e) {
ess.showError(chat.getUser().getSource(), e, "\\ chat " + chat.getLongType());
event.setCancelled(true);
return false;
}
return true;
}
protected interface ChatListener extends Listener {
@SuppressWarnings("unused")
void onPlayerChat(AsyncPlayerChatEvent event);
}
}