summaryrefslogtreecommitdiffstats
path: root/Essentials/src/com/earth2me/essentials/textreader/KeywordReplacer.java
blob: 3395a4b7fc9eb1a98b83e25d8d2a5bdba9547242 (plain)
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
419
package com.earth2me.essentials.textreader;

import com.earth2me.essentials.CommandSource;
import com.earth2me.essentials.ExecuteTimer;
import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.PlayerList;
import com.earth2me.essentials.User;
import static com.earth2me.essentials.textreader.KeywordType.DISPLAYNAME;
import static com.earth2me.essentials.textreader.KeywordType.PLAYER;
import com.earth2me.essentials.utils.DateUtil;
import com.earth2me.essentials.utils.DescParseTickFormat;
import com.earth2me.essentials.utils.NumberUtil;
import java.lang.management.ManagementFactory;
import java.text.DateFormat;
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;
import net.ess3.api.IEssentials;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;


public class KeywordReplacer implements IText
{
	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 transient ExecuteTimer execTimer;
	private final EnumMap<KeywordType, Object> keywordCache = new EnumMap<KeywordType, Object>(KeywordType.class);

	public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess)
	{
		this.input = input;
		this.replaced = new ArrayList<String>(this.input.getLines().size());
		this.ess = ess;
		this.includePrivate = true;
		replaceKeywords(sender);
	}

	public KeywordReplacer(final IText input, final CommandSource sender, final IEssentials ess, final boolean showPrivate)
	{
		this.input = input;
		this.replaced = new ArrayList<String>(this.input.getLines().size());
		this.ess = ess;
		this.includePrivate = showPrivate;
		replaceKeywords(sender);
	}

	private void replaceKeywords(final CommandSource sender)
	{
		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);
			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;
			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))
				{
					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 BALANCE:
					if (user != null)
					{
						replacer = NumberUtil.displayCurrency(user.getMoney(), ess);
					}
					break;
				case MAILS:
					if (user != null)
					{
						replacer = Integer.toString(user.getMails().size());
					}
					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 (User u : ess.getOnlineUsers())
					{
						if (u.isHidden())
						{
							playerHidden++;
						}
					}
					replacer = Integer.toString(ess.getOnlinePlayers().size() - playerHidden);
					break;
				case UNIQUE:
					replacer = Integer.toString(ess.getUserMap().getUniqueUsers());
					break;
				case WORLDS:
					final StringBuilder worldsBuilder = new StringBuilder();
					for (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<String, String>();
						for (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 (Player p : ess.getServer().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 = tl("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 (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 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 (IllegalArgumentException ex)
		{
		}

		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();
	}
}

//When adding a keyword here, you also need to add the implementation above
enum KeywordType
{
	PLAYER(KeywordCachable.CACHEABLE),
	DISPLAYNAME(KeywordCachable.CACHEABLE),
	USERNAME(KeywordCachable.NOTCACHEABLE),
	BALANCE(KeywordCachable.CACHEABLE),
	MAILS(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(KeywordCachable type)
	{
		this.type = type;
		this.isPrivate = false;
	}

	KeywordType(KeywordCachable type, 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
}