forked from EssentialsX/Essentials
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKeywordReplacer.java
More file actions
418 lines (385 loc) · 18.2 KB
/
KeywordReplacer.java
File metadata and controls
418 lines (385 loc) · 18.2 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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package com.earth2me.essentials.textreader;
import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.ExecuteTimer;
import com.earth2me.essentials.PlayerList;
import com.earth2me.essentials.User;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.DescParseTickFormat;
import com.earth2me.essentials.utils.EnumUtil;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import net.ess3.api.IEssentials;
import org.bukkit.Location;
import org.bukkit.Statistic;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
//When adding a keyword here, you also need to add the implementation above
enum KeywordType {
PLAYER(KeywordCachable.CACHEABLE),
DISPLAYNAME(KeywordCachable.CACHEABLE),
USERNAME(KeywordCachable.NOTCACHEABLE),
NICKNAME(KeywordCachable.CACHEABLE),
PREFIX(KeywordCachable.CACHEABLE),
SUFFIX(KeywordCachable.CACHEABLE),
GROUP(KeywordCachable.CACHEABLE),
BALANCE(KeywordCachable.CACHEABLE),
MAILS(KeywordCachable.CACHEABLE),
PLAYTIME(KeywordCachable.CACHEABLE),
WORLD(KeywordCachable.CACHEABLE),
WORLDNAME(KeywordCachable.CACHEABLE),
ONLINE(KeywordCachable.CACHEABLE),
UNIQUE(KeywordCachable.CACHEABLE),
WORLDS(KeywordCachable.CACHEABLE),
PLAYERLIST(KeywordCachable.SUBVALUE, true),
TIME(KeywordCachable.CACHEABLE),
DATE(KeywordCachable.CACHEABLE),
WORLDTIME12(KeywordCachable.CACHEABLE),
WORLDTIME24(KeywordCachable.CACHEABLE),
WORLDDATE(KeywordCachable.CACHEABLE),
COORDS(KeywordCachable.CACHEABLE),
TPS(KeywordCachable.CACHEABLE),
UPTIME(KeywordCachable.CACHEABLE),
IP(KeywordCachable.CACHEABLE, true),
ADDRESS(KeywordCachable.CACHEABLE, true),
PLUGINS(KeywordCachable.CACHEABLE, true),
VERSION(KeywordCachable.CACHEABLE, true);
private final KeywordCachable type;
private final boolean isPrivate;
KeywordType(final KeywordCachable type) {
this.type = type;
this.isPrivate = false;
}
KeywordType(final KeywordCachable type, final boolean isPrivate) {
this.type = type;
this.isPrivate = isPrivate;
}
public KeywordCachable getType() {
return type;
}
public boolean isPrivate() {
return isPrivate;
}
}
enum KeywordCachable {
CACHEABLE, // This keyword can be cached as a string
SUBVALUE, // This keyword can be cached as a map
NOTCACHEABLE // This keyword should never be cached
}
public class KeywordReplacer implements IText {
private static final Statistic PLAY_ONE_TICK = EnumUtil.getStatistic("PLAY_ONE_MINUTE", "PLAY_ONE_TICK");
private static final Pattern KEYWORD = Pattern.compile("\\{([^\\{\\}]+)\\}");
private static final Pattern KEYWORDSPLIT = Pattern.compile("\\:");
private final transient IText input;
private final transient List<String> replaced;
private final transient IEssentials ess;
private final transient boolean includePrivate;
private final transient boolean replaceSpacesWithUnderscores;
private final EnumMap<KeywordType, Object> keywordCache = new EnumMap<>(KeywordType.class);
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess) {
this.input = input;
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = true;
this.replaceSpacesWithUnderscores = false;
replaceKeywords(sender);
}
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate) {
this.input = input;
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = showPrivate;
this.replaceSpacesWithUnderscores = false;
replaceKeywords(sender);
}
public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate,
final boolean replaceSpacesWithUnderscores) {
this.input = input;
this.replaced = new ArrayList<>(this.input.getLines().size());
this.ess = ess;
this.includePrivate = showPrivate;
this.replaceSpacesWithUnderscores = replaceSpacesWithUnderscores;
replaceKeywords(sender);
}
private void replaceKeywords(final CommandSource sender) {
final ExecuteTimer execTimer = new ExecuteTimer();
execTimer.start();
User user = null;
if (sender.isPlayer()) {
user = ess.getUser(sender.getPlayer());
}
execTimer.mark("User Grab");
for (int i = 0; i < input.getLines().size(); i++) {
String line = input.getLines().get(i);
// Skip processing b64 encoded items, they will not have keywords in them.
if (line.startsWith("@")) {
replaced.add(line);
continue;
}
final Matcher matcher = KEYWORD.matcher(line);
while (matcher.find()) {
final String fullMatch = matcher.group(0);
final String keywordMatch = matcher.group(1);
final String[] matchTokens = KEYWORDSPLIT.split(keywordMatch);
line = replaceLine(line, fullMatch, matchTokens, user);
}
replaced.add(line);
}
execTimer.mark("Text Replace");
final String timeroutput = execTimer.end();
if (ess.getSettings().isDebug()) {
ess.getLogger().log(Level.INFO, "Keyword Replacer " + timeroutput);
}
}
private String replaceLine(String line, final String fullMatch, final String[] matchTokens, final User user) {
final String keyword = matchTokens[0];
try {
String replacer = null;
final KeywordType validKeyword = KeywordType.valueOf(keyword);
if (validKeyword.getType().equals(KeywordCachable.CACHEABLE) && keywordCache.containsKey(validKeyword)) {
replacer = keywordCache.get(validKeyword).toString();
} else if (validKeyword.getType().equals(KeywordCachable.SUBVALUE)) {
String subKeyword = "";
if (matchTokens.length > 1) {
subKeyword = matchTokens[1].toLowerCase(Locale.ENGLISH);
}
if (keywordCache.containsKey(validKeyword)) {
final Map<String, String> values = (Map<String, String>) keywordCache.get(validKeyword);
if (values.containsKey(subKeyword)) {
replacer = values.get(subKeyword);
}
}
}
if (validKeyword.isPrivate() && !includePrivate) {
replacer = "";
}
if (replacer == null) {
replacer = "";
switch (validKeyword) {
case PLAYER:
case DISPLAYNAME:
if (user != null) {
replacer = user.getDisplayName();
}
break;
case USERNAME:
if (user != null) {
replacer = user.getName();
}
break;
case NICKNAME:
if (user != null) {
final String nickname = user.getFormattedNickname();
replacer = nickname == null ? user.getName() : nickname;
}
break;
case PREFIX:
if (user != null) {
final String prefix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getPrefix(user.getBase()));
replacer = prefix == null ? "" : prefix;
}
break;
case SUFFIX:
if (user != null) {
final String suffix = FormatUtil.replaceFormat(ess.getPermissionsHandler().getSuffix(user.getBase()));
replacer = suffix == null ? "" : suffix;
}
break;
case GROUP:
if (user != null) {
replacer = user.getGroup();
}
break;
case BALANCE:
if (user != null) {
replacer = ess.getAdventureFacet().miniToLegacy(NumberUtil.displayCurrency(user.getMoney(), ess));
}
break;
case MAILS:
if (user != null) {
replacer = Integer.toString(user.getMailAmount());
}
break;
case PLAYTIME:
if (user != null) {
final long playtimeMs = System.currentTimeMillis() - (user.getBase().getStatistic(PLAY_ONE_TICK) * 50L);
replacer = DateUtil.formatDateDiff(playtimeMs);
}
break;
case WORLD:
case WORLDNAME:
if (user != null) {
final Location location = user.getLocation();
replacer = location == null || location.getWorld() == null ? "" : location.getWorld().getName();
}
break;
case ONLINE:
int playerHidden = 0;
for (final User u : ess.getOnlineUsers()) {
if (u.isHidden()) {
playerHidden++;
}
}
replacer = Integer.toString(ess.getOnlinePlayers().size() - playerHidden);
break;
case UNIQUE:
replacer = NumberFormat.getInstance().format(ess.getUsers().getUserCount());
break;
case WORLDS:
final StringBuilder worldsBuilder = new StringBuilder();
for (final World w : ess.getServer().getWorlds()) {
if (worldsBuilder.length() > 0) {
worldsBuilder.append(", ");
}
worldsBuilder.append(w.getName());
}
replacer = worldsBuilder.toString();
break;
case PLAYERLIST:
final Map<String, String> outputList;
if (keywordCache.containsKey(validKeyword)) {
outputList = (Map<String, String>) keywordCache.get(validKeyword);
} else {
final boolean showHidden;
if (user == null) {
showHidden = true;
} else {
showHidden = user.isAuthorized("essentials.list.hidden") || user.canInteractVanished();
}
//First lets build the per group playerlist
final Map<String, List<User>> playerList = PlayerList.getPlayerLists(ess, user, showHidden);
outputList = new HashMap<>();
for (final String groupName : playerList.keySet()) {
final List<User> groupUsers = playerList.get(groupName);
if (groupUsers != null && !groupUsers.isEmpty()) {
outputList.put(groupName, PlayerList.listUsers(ess, groupUsers, " "));
}
}
//Now lets build the all user playerlist
final StringBuilder playerlistBuilder = new StringBuilder();
for (final Player p : ess.getOnlinePlayers()) {
if (ess.getUser(p).isHidden()) {
continue;
}
if (playerlistBuilder.length() > 0) {
playerlistBuilder.append(", ");
}
playerlistBuilder.append(p.getDisplayName());
}
outputList.put("", playerlistBuilder.toString());
keywordCache.put(validKeyword, outputList);
}
//Now thats all done, output the one we want and cache the rest.
if (matchTokens.length == 1) {
replacer = outputList.get("");
} else if (outputList.containsKey(matchTokens[1].toLowerCase(Locale.ENGLISH))) {
replacer = outputList.get(matchTokens[1].toLowerCase(Locale.ENGLISH));
} else if (matchTokens.length > 2) {
replacer = matchTokens[2];
}
keywordCache.put(validKeyword, outputList);
break;
case TIME:
replacer = DateFormat.getTimeInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
break;
case DATE:
replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(new Date());
break;
case WORLDTIME12:
if (user != null) {
replacer = DescParseTickFormat.format12(user.getWorld() == null ? 0 : user.getWorld().getTime());
}
break;
case WORLDTIME24:
if (user != null) {
replacer = DescParseTickFormat.format24(user.getWorld() == null ? 0 : user.getWorld().getTime());
}
break;
case WORLDDATE:
if (user != null) {
replacer = DateFormat.getDateInstance(DateFormat.MEDIUM, ess.getI18n().getCurrentLocale()).format(DescParseTickFormat.ticksToDate(user.getWorld() == null ? 0 : user.getWorld().getFullTime()));
}
break;
case COORDS:
if (user != null) {
final Location location = user.getLocation();
replacer = user.playerTl("coordsKeyword", location.getBlockX(), location.getBlockY(), location.getBlockZ());
}
break;
case TPS:
replacer = NumberUtil.formatDouble(ess.getTimer().getAverageTPS());
break;
case UPTIME:
replacer = DateUtil.formatDateDiff(ManagementFactory.getRuntimeMXBean().getStartTime());
break;
case IP:
if (user != null) {
replacer = user.getBase().getAddress() == null || user.getBase().getAddress().getAddress() == null ? "" : user.getBase().getAddress().getAddress().toString();
}
break;
case ADDRESS:
if (user != null) {
replacer = user.getBase().getAddress() == null ? "" : user.getBase().getAddress().toString();
}
break;
case PLUGINS:
final StringBuilder pluginlistBuilder = new StringBuilder();
for (final Plugin p : ess.getServer().getPluginManager().getPlugins()) {
if (pluginlistBuilder.length() > 0) {
pluginlistBuilder.append(", ");
}
pluginlistBuilder.append(p.getDescription().getName());
}
replacer = pluginlistBuilder.toString();
break;
case VERSION:
replacer = ess.getServer().getVersion();
break;
default:
replacer = "N/A";
break;
}
if (this.replaceSpacesWithUnderscores) {
// Don't replace spaces with underscores in commands, and skip escaping
// for USERNAME since Minecraft names never contain spaces but can
// contain underscores that must stay literal (e.g. player:{USERNAME}).
if (!line.startsWith("/") && validKeyword != KeywordType.USERNAME) {
replacer = replacer.replace("_", "\\_").replaceAll("\\s", "_");
}
}
//If this is just a regular keyword, lets throw it into the cache
if (validKeyword.getType().equals(KeywordCachable.CACHEABLE)) {
keywordCache.put(validKeyword, replacer);
}
}
line = line.replace(fullMatch, replacer);
} catch (final IllegalArgumentException ignored) {
}
return line;
}
@Override
public List<String> getLines() {
return replaced;
}
@Override
public List<String> getChapters() {
return input.getChapters();
}
@Override
public Map<String, Integer> getBookmarks() {
return input.getBookmarks();
}
}