summaryrefslogtreecommitdiffstats
path: root/Essentials/src/com/earth2me/essentials/MetaItemStack.java
blob: c3902862796bdf61f4220ac90a26dac7827ff8ed (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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
package com.earth2me.essentials;

import static com.earth2me.essentials.I18n.tl;
import com.earth2me.essentials.textreader.BookInput;
import com.earth2me.essentials.textreader.BookPager;
import com.earth2me.essentials.textreader.IText;
import com.earth2me.essentials.utils.FormatUtil;
import com.earth2me.essentials.utils.NumberUtil;
import java.util.*;
import java.util.regex.Pattern;

import com.google.common.base.Joiner;
import java.util.logging.Level;
import net.ess3.api.IEssentials;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.FireworkEffect;
import org.bukkit.Material;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.*;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;


public class MetaItemStack
{
	private static final Map<String, DyeColor> colorMap = new HashMap<String, DyeColor>();
	private static final Map<String, FireworkEffect.Type> fireworkShape = new HashMap<String, FireworkEffect.Type>();

	static
	{
		for (DyeColor color : DyeColor.values())
		{
			colorMap.put(color.name(), color);
		}
		for (FireworkEffect.Type type : FireworkEffect.Type.values())
		{
			fireworkShape.put(type.name(), type);
		}
	}
	private final transient Pattern splitPattern = Pattern.compile("[:+',;.]");
	private ItemStack stack;
	private FireworkEffect.Builder builder = FireworkEffect.builder();
	private PotionEffectType pEffectType;
	private PotionEffect pEffect;
	private boolean validFirework = false;
	private boolean validPotionEffect = false;
	private boolean validPotionDuration = false;
	private boolean validPotionPower = false;
	private boolean completePotion = false;
	private int power = 1;
	private int duration = 120;

	public MetaItemStack(final ItemStack stack)
	{
		this.stack = stack.clone();
	}

	public ItemStack getItemStack()
	{
		return stack;
	}

	public boolean isValidFirework()
	{
		return validFirework;
	}

	public boolean isValidPotion()
	{
		return validPotionEffect && validPotionDuration && validPotionPower;
	}

	public FireworkEffect.Builder getFireworkBuilder()
	{
		return builder;
	}

	public PotionEffect getPotionEffect()
	{
		return pEffect;
	}

	public boolean completePotion()
	{
		return completePotion;
	}

	private void resetPotionMeta()
	{
		pEffect = null;
		pEffectType = null;
		validPotionEffect = false;
		validPotionDuration = false;
		validPotionPower = false;
		completePotion = true;
	}

	public boolean canSpawn(final IEssentials ess)
	{
		try
		{
			ess.getServer().getUnsafe().modifyItemStack(stack, "{}");
			return true;
		}
		catch (NullPointerException npe)
		{
			if (ess.getSettings().isDebug())
			{
				ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
			}
			return false;
		}
		catch (NoSuchMethodError nsme)
		{
			return true;
		}
		catch (Throwable throwable)
		{
			if (ess.getSettings().isDebug())
			{
				ess.getLogger().log(Level.INFO, "Itemstack is invalid", throwable);
			}
			return false;
		}
	}

	public void parseStringMeta(final CommandSource sender, final boolean allowUnsafe, String[] string, int fromArg, final IEssentials ess) throws Exception
	{
		if (string[fromArg].startsWith("{") && hasMetaPermission(sender, "vanilla", false, true, ess))
		{
			try
			{
				stack = ess.getServer().getUnsafe().modifyItemStack(stack, Joiner.on(' ').join(Arrays.asList(string).subList(fromArg, string.length)));
			}
			catch (NullPointerException npe)
			{
				if (ess.getSettings().isDebug())
				{
					ess.getLogger().log(Level.INFO, "Itemstack is invalid", npe);
				}
			}
			catch (NoSuchMethodError nsme)
			{
				throw new Exception(tl("noMetaJson"), nsme);
			}
			catch (Throwable throwable)
			{
				throw new Exception(throwable.getMessage(), throwable);
			}
		}
		else
		{
			for (int i = fromArg; i < string.length; i++)
			{
				addStringMeta(sender, allowUnsafe, string[i], ess);
			}
			if (validFirework)
			{
				if (!hasMetaPermission(sender, "firework", true, true, ess))
				{
					throw new Exception(tl("noMetaFirework"));
				}
				FireworkEffect effect = builder.build();
				FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta();
				fmeta.addEffect(effect);
				if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess))
				{
					throw new Exception(tl("multipleCharges"));
				}
				stack.setItemMeta(fmeta);
			}
		}
	}

	public void addStringMeta(final CommandSource sender, final boolean allowUnsafe, final String string, final IEssentials ess) throws Exception
	{
		final String[] split = splitPattern.split(string, 2);
		if (split.length < 1)
		{
			return;
		}

		if (split.length > 1 && split[0].equalsIgnoreCase("name") && hasMetaPermission(sender, "name", false, true, ess))
		{
			final String displayName = FormatUtil.replaceFormat(split[1].replace('_', ' '));
			final ItemMeta meta = stack.getItemMeta();
			meta.setDisplayName(displayName);
			stack.setItemMeta(meta);
		}
		else if (split.length > 1 && (split[0].equalsIgnoreCase("lore") || split[0].equalsIgnoreCase("desc")) && hasMetaPermission(sender, "lore", false, true, ess))
		{
			final List<String> lore = new ArrayList<String>();
			for (String line : split[1].split("\\|"))
			{
				lore.add(FormatUtil.replaceFormat(line.replace('_', ' ')));
			}
			final ItemMeta meta = stack.getItemMeta();
			meta.setLore(lore);
			stack.setItemMeta(meta);
		}
		else if (split.length > 1 && (split[0].equalsIgnoreCase("player") || split[0].equalsIgnoreCase("owner")) && stack.getType() == Material.SKULL_ITEM && hasMetaPermission(sender, "head", false, true, ess))
		{
			if (stack.getDurability() == 3)
			{
				final String owner = split[1];
				final SkullMeta meta = (SkullMeta)stack.getItemMeta();
				meta.setOwner(owner);
				stack.setItemMeta(meta);
			}
			else
			{
				throw new Exception(tl("onlyPlayerSkulls"));
			}
		}
		else if (split.length > 1 && split[0].equalsIgnoreCase("book") && stack.getType() == Material.WRITTEN_BOOK
				 && (hasMetaPermission(sender, "book", true, true, ess) || hasMetaPermission(sender, "chapter-" + split[1].toLowerCase(Locale.ENGLISH), true, true, ess)))
		{
			final BookMeta meta = (BookMeta)stack.getItemMeta();
			final IText input = new BookInput("book", true, ess);
			final BookPager pager = new BookPager(input);

			List<String> pages = pager.getPages(split[1]);
			meta.setPages(pages);
			stack.setItemMeta(meta);
		}
		else if (split.length > 1 && split[0].equalsIgnoreCase("author") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "author", false, true, ess))
		{
			final String author = FormatUtil.replaceFormat(split[1]);
			final BookMeta meta = (BookMeta)stack.getItemMeta();
			meta.setAuthor(author);
			stack.setItemMeta(meta);
		}
		else if (split.length > 1 && split[0].equalsIgnoreCase("title") && stack.getType() == Material.WRITTEN_BOOK && hasMetaPermission(sender, "title", false, true, ess))
		{
			final String title = FormatUtil.replaceFormat(split[1].replace('_', ' '));
			final BookMeta meta = (BookMeta)stack.getItemMeta();
			meta.setTitle(title);
			stack.setItemMeta(meta);
		}
		else if (split.length > 1 && split[0].equalsIgnoreCase("power") && stack.getType() == Material.FIREWORK && hasMetaPermission(sender, "firework-power", false, true, ess))
		{
			final int power = NumberUtil.isInt(split[1]) ? Integer.parseInt(split[1]) : 0;
			final FireworkMeta meta = (FireworkMeta)stack.getItemMeta();
			meta.setPower(power > 3 ? 4 : power);
			stack.setItemMeta(meta);
		}
		else if (stack.getType() == Material.FIREWORK) //WARNING - Meta for fireworks will be ignored after this point.
		{
			addFireworkMeta(sender, false, string, ess);
		}
		else if (stack.getType() == Material.POTION) //WARNING - Meta for potions will be ignored after this point.
		{
			addPotionMeta(sender, false, string, ess);
		}
		else if (split.length > 1 && (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour"))
				 && (stack.getType() == Material.LEATHER_BOOTS
					 || stack.getType() == Material.LEATHER_CHESTPLATE
					 || stack.getType() == Material.LEATHER_HELMET
					 || stack.getType() == Material.LEATHER_LEGGINGS))
		{
			final String[] color = split[1].split("(\\||,)");
			if (color.length == 3)
			{
				final int red = NumberUtil.isInt(color[0]) ? Integer.parseInt(color[0]) : 0;
				final int green = NumberUtil.isInt(color[1]) ? Integer.parseInt(color[1]) : 0;
				final int blue = NumberUtil.isInt(color[2]) ? Integer.parseInt(color[2]) : 0;
				final LeatherArmorMeta meta = (LeatherArmorMeta)stack.getItemMeta();
				meta.setColor(Color.fromRGB(red, green, blue));
				stack.setItemMeta(meta);
			}
			else
			{
				throw new Exception(tl("leatherSyntax"));
			}
		}
		else
		{
			parseEnchantmentStrings(sender, allowUnsafe, split, ess);
		}
	}

	public void addFireworkMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception
	{
		if (stack.getType() == Material.FIREWORK)
		{
			final String[] split = splitPattern.split(string, 2);

			if (split.length < 2)
			{
				return;
			}

			if (split[0].equalsIgnoreCase("color") || split[0].equalsIgnoreCase("colour") || (allowShortName && split[0].equalsIgnoreCase("c")))
			{
				if (validFirework)
				{
					if (!hasMetaPermission(sender, "firework", true, true, ess))
					{
						throw new Exception(tl("noMetaFirework"));
					}
					FireworkEffect effect = builder.build();
					FireworkMeta fmeta = (FireworkMeta)stack.getItemMeta();
					fmeta.addEffect(effect);
					if (fmeta.getEffects().size() > 1 && !hasMetaPermission(sender, "firework-multiple", true, true, ess))
					{
						throw new Exception(tl("multipleCharges"));
					}
					stack.setItemMeta(fmeta);
					builder = FireworkEffect.builder();
				}

				List<Color> primaryColors = new ArrayList<Color>();
				String[] colors = split[1].split(",");
				for (String color : colors)
				{
					if (colorMap.containsKey(color.toUpperCase()))
					{
						validFirework = true;
						primaryColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
					}
					else
					{
						throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
					}
				}
				builder.withColor(primaryColors);
			}
			else if (split[0].equalsIgnoreCase("shape") || split[0].equalsIgnoreCase("type") || (allowShortName && (split[0].equalsIgnoreCase("s") || split[0].equalsIgnoreCase("t"))))
			{
				FireworkEffect.Type finalEffect = null;
				split[1] = (split[1].equalsIgnoreCase("large") ? "BALL_LARGE" : split[1]);
				if (fireworkShape.containsKey(split[1].toUpperCase()))
				{
					finalEffect = fireworkShape.get(split[1].toUpperCase());
				}
				else
				{
					throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
				}
				if (finalEffect != null)
				{
					builder.with(finalEffect);
				}
			}
			else if (split[0].equalsIgnoreCase("fade") || (allowShortName && split[0].equalsIgnoreCase("f")))
			{
				List<Color> fadeColors = new ArrayList<Color>();
				String[] colors = split[1].split(",");
				for (String color : colors)
				{
					if (colorMap.containsKey(color.toUpperCase()))
					{
						fadeColors.add(colorMap.get(color.toUpperCase()).getFireworkColor());
					}
					else
					{
						throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
					}
				}
				if (!fadeColors.isEmpty())
				{
					builder.withFade(fadeColors);
				}
			}
			else if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e")))
			{
				String[] effects = split[1].split(",");
				for (String effect : effects)
				{
					if (effect.equalsIgnoreCase("twinkle"))
					{
						builder.flicker(true);
					}
					else if (effect.equalsIgnoreCase("trail"))
					{
						builder.trail(true);
					}
					else
					{
						throw new Exception(tl("invalidFireworkFormat", split[1], split[0]));
					}
				}
			}
		}
	}

	public void addPotionMeta(final CommandSource sender, final boolean allowShortName, final String string, final IEssentials ess) throws Exception
	{
		if (stack.getType() == Material.POTION)
		{
			final String[] split = splitPattern.split(string, 2);

			if (split.length < 2)
			{
				return;
			}

			if (split[0].equalsIgnoreCase("effect") || (allowShortName && split[0].equalsIgnoreCase("e")))
			{
				pEffectType = Potions.getByName(split[1]);
				if (pEffectType != null && pEffectType.getName() != null)
				{
					if (hasMetaPermission(sender, "potions." + pEffectType.getName().toLowerCase(Locale.ENGLISH), true, false, ess))
					{
						validPotionEffect = true;
					}
					else
					{
						throw new Exception(tl("noPotionEffectPerm", pEffectType.getName().toLowerCase(Locale.ENGLISH)));
					}
				}
				else
				{
					throw new Exception(tl("invalidPotionMeta", split[1]));
				}
			}
			else if (split[0].equalsIgnoreCase("power") || (allowShortName && split[0].equalsIgnoreCase("p")))
			{
				if (NumberUtil.isInt(split[1]))
				{
					validPotionPower = true;
					power = Integer.parseInt(split[1]);
					if (power > 0 && power < 4)
					{
						power -= 1;
					}
				}
				else
				{
					throw new Exception(tl("invalidPotionMeta", split[1]));
				}
			}
			else if (split[0].equalsIgnoreCase("duration") || (allowShortName && split[0].equalsIgnoreCase("d")))
			{
				if (NumberUtil.isInt(split[1]))
				{
					validPotionDuration = true;
					duration = Integer.parseInt(split[1]) * 20; //Duration is in ticks by default, converted to seconds
				}
				else
				{
					throw new Exception(tl("invalidPotionMeta", split[1]));
				}
			}

			if (isValidPotion())
			{
				PotionMeta pmeta = (PotionMeta)stack.getItemMeta();
				pEffect = pEffectType.createEffect(duration, power);
				if (pmeta.getCustomEffects().size() > 1 && !hasMetaPermission(sender, "potions.multiple", true, false, ess))
				{
					throw new Exception(tl("multiplePotionEffects"));
				}
				pmeta.addCustomEffect(pEffect, true);
				stack.setItemMeta(pmeta);
				resetPotionMeta();
			}
		}
	}

	private void parseEnchantmentStrings(final CommandSource sender, final boolean allowUnsafe, final String[] split, final IEssentials ess) throws Exception
	{
		final Enchantment enchantment = Enchantments.getByName(split[0]);
		if (enchantment == null || !hasMetaPermission(sender, "enchantments." + enchantment.getName().toLowerCase(Locale.ENGLISH), false, false, ess))
		{
			return;
		}

		int level = -1;
		if (split.length > 1)
		{
			try
			{
				level = Integer.parseInt(split[1]);
			}
			catch (NumberFormatException ex)
			{
				level = -1;
			}
		}

		if (level < 0 || (!allowUnsafe && level > enchantment.getMaxLevel()))
		{
			level = enchantment.getMaxLevel();
		}
		addEnchantment(sender, allowUnsafe, enchantment, level);
	}

	public void addEnchantment(final CommandSource sender, final boolean allowUnsafe, final Enchantment enchantment, final int level) throws Exception
	{
		if (enchantment == null)
		{
			throw new Exception(tl("enchantmentNotFound"));
		}
		try
		{
			if (stack.getType().equals(Material.ENCHANTED_BOOK))
			{
				EnchantmentStorageMeta meta = (EnchantmentStorageMeta)stack.getItemMeta();
				if (level == 0)
				{
					meta.removeStoredEnchant(enchantment);
				}
				else
				{
					meta.addStoredEnchant(enchantment, level, allowUnsafe);
				}
				stack.setItemMeta(meta);
			}
			else // all other material types besides ENCHANTED_BOOK
			{
				if (level == 0)
				{
					stack.removeEnchantment(enchantment);
				}
				else
				{
					if (allowUnsafe)
					{
						stack.addUnsafeEnchantment(enchantment, level);
					}
					else
					{
						stack.addEnchantment(enchantment, level);
					}
				}
			}
		}
		catch (Exception ex)
		{
			throw new Exception("Enchantment " + enchantment.getName() + ": " + ex.getMessage(), ex);
		}
	}

	public Enchantment getEnchantment(final User user, final String name) throws Exception
	{
		final Enchantment enchantment = Enchantments.getByName(name);
		if (enchantment == null)
		{
			return null;
		}

		final String enchantmentName = enchantment.getName().toLowerCase(Locale.ENGLISH);

		if (!hasMetaPermission(user, "enchantments." + enchantmentName, true, false))
		{
			throw new Exception(tl("enchantmentPerm", enchantmentName));
		}
		return enchantment;
	}

	private boolean hasMetaPermission(final CommandSource sender, final String metaPerm, final boolean graceful, final boolean includeBase, final IEssentials ess) throws Exception
	{
		final User user = sender != null && sender.isPlayer() ? ess.getUser(sender.getPlayer()) : null;
		return hasMetaPermission(user, metaPerm, graceful, includeBase);
	}

	private boolean hasMetaPermission(final User user, final String metaPerm, final boolean graceful, final boolean includeBase) throws Exception
	{
		final String permBase = includeBase ? "essentials.itemspawn.meta-" : "essentials.";
		if (user == null || user.isAuthorized(permBase + metaPerm))
		{
			return true;
		}

		if (graceful)
		{
			return false;
		}
		else
		{
			throw new Exception(tl("noMetaPerm", metaPerm));
		}
	}
}