-
-
Notifications
You must be signed in to change notification settings - Fork 103
/
Quests.java
4812 lines (4680 loc) · 243 KB
/
Quests.java
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2014 PikaMug and contributors. All rights reserved.
*
* THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package me.blackvein.quests;
import com.gmail.nossr50.datatypes.skills.SkillType;
import com.herocraftonline.heroes.characters.classes.HeroClass;
import me.blackvein.quests.actions.Action;
import me.blackvein.quests.actions.ActionFactory;
import me.blackvein.quests.actions.BukkitActionFactory;
import me.blackvein.quests.actions.IAction;
import me.blackvein.quests.conditions.BukkitConditionFactory;
import me.blackvein.quests.conditions.Condition;
import me.blackvein.quests.conditions.ConditionFactory;
import me.blackvein.quests.conditions.ICondition;
import me.blackvein.quests.config.ISettings;
import me.blackvein.quests.convo.misc.MiscStringPrompt;
import me.blackvein.quests.convo.misc.NpcOfferQuestPrompt;
import me.blackvein.quests.dependencies.DenizenTrigger;
import me.blackvein.quests.dependencies.IDependencies;
import me.blackvein.quests.entity.BukkitQuestMob;
import me.blackvein.quests.entity.QuestMob;
import me.blackvein.quests.events.misc.MiscPostQuestAcceptEvent;
import me.blackvein.quests.exceptions.ActionFormatException;
import me.blackvein.quests.exceptions.ConditionFormatException;
import me.blackvein.quests.exceptions.QuestFormatException;
import me.blackvein.quests.exceptions.StageFormatException;
import me.blackvein.quests.interfaces.ReloadCallback;
import me.blackvein.quests.listeners.BlockListener;
import me.blackvein.quests.listeners.CitizensListener;
import me.blackvein.quests.listeners.CommandManager;
import me.blackvein.quests.listeners.ConvoListener;
import me.blackvein.quests.listeners.ItemListener;
import me.blackvein.quests.listeners.PartiesListener;
import me.blackvein.quests.listeners.PlayerListener;
import me.blackvein.quests.listeners.UniteListener;
import me.blackvein.quests.listeners.ZnpcsListener;
import me.blackvein.quests.logging.QuestsLog4JFilter;
import me.blackvein.quests.module.ICustomObjective;
import me.blackvein.quests.player.IQuester;
import me.blackvein.quests.quests.BukkitQuestFactory;
import me.blackvein.quests.quests.IQuest;
import me.blackvein.quests.quests.IStage;
import me.blackvein.quests.quests.Options;
import me.blackvein.quests.quests.Planner;
import me.blackvein.quests.quests.QuestFactory;
import me.blackvein.quests.quests.Requirements;
import me.blackvein.quests.quests.Rewards;
import me.blackvein.quests.statistics.Metrics;
import me.blackvein.quests.storage.Storage;
import me.blackvein.quests.storage.StorageFactory;
import me.blackvein.quests.tasks.NpcEffectThread;
import me.blackvein.quests.tasks.PlayerMoveThread;
import me.blackvein.quests.util.ConfigUtil;
import me.blackvein.quests.util.ItemUtil;
import me.blackvein.quests.util.Lang;
import me.blackvein.quests.util.MiscUtil;
import me.blackvein.quests.util.RomanNumeral;
import me.blackvein.quests.util.UpdateChecker;
import me.clip.placeholderapi.PlaceholderAPI;
import me.pikamug.localelib.LocaleManager;
import net.citizensnpcs.api.CitizensAPI;
import net.citizensnpcs.api.npc.NPC;
import net.md_5.bungee.api.chat.ClickEvent;
import net.md_5.bungee.api.chat.TextComponent;
import org.apache.logging.log4j.LogManager;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.TabExecutor;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.conversations.Conversable;
import org.bukkit.conversations.ConversationContext;
import org.bukkit.conversations.ConversationFactory;
import org.bukkit.conversations.Prompt;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Tameable;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.permissions.Permission;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import org.jetbrains.annotations.NotNull;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.StandardCharsets;
import java.util.AbstractMap;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Quests extends JavaPlugin implements QuestsAPI {
private boolean loading = true;
private String bukkitVersion = "0";
private IDependencies depends;
private ISettings settings;
private final List<ICustomObjective> customObjectives = new LinkedList<>();
private final List<CustomRequirement> customRequirements = new LinkedList<>();
private final List<CustomReward> customRewards = new LinkedList<>();
private Collection<IQuester> questers = new ConcurrentSkipListSet<>();
private final Collection<IQuest> quests = new ConcurrentSkipListSet<>();
private Collection<IAction> actions = new ConcurrentSkipListSet<>();
private Collection<ICondition> conditions = new ConcurrentSkipListSet<>();
private Collection<UUID> questNpcUuids = new ConcurrentSkipListSet<>();
private TabExecutor cmdExecutor;
private ConversationFactory conversationFactory;
private ConversationFactory npcConversationFactory;
private QuestFactory questFactory;
private ActionFactory actionFactory;
private ConditionFactory conditionFactory;
private ConvoListener convoListener;
private BlockListener blockListener;
private ItemListener itemListener;
private CitizensListener citizensListener;
private ZnpcsListener znpcsListener;
private PlayerListener playerListener;
private NpcEffectThread effectThread;
private PlayerMoveThread moveThread;
private UniteListener uniteListener;
private PartiesListener partiesListener;
private DenizenTrigger trigger;
private LocaleManager localeManager;
private Storage storage;
@Override
public void onEnable() {
/*----> WARNING: ORDER OF STEPS MATTERS <----*/
// 1 - Trigger server to initialize Legacy Material Support
try {
Material.matchMaterial("STONE", true);
} catch (final NoSuchMethodError ignored) {
}
((org.apache.logging.log4j.core.Logger) LogManager.getRootLogger()).addFilter(new QuestsLog4JFilter());
// 2 - Initialize variables
bukkitVersion = Bukkit.getServer().getBukkitVersion().split("-")[0];
settings = new Settings(this);
try {
Class.forName("me.blackvein.quests.libs.localelib.LocaleManager");
localeManager = new LocaleManager();
} catch (final Exception ignored) {
getLogger().warning("LocaleLib not present! Is this a debug environment?");
}
convoListener = new ConvoListener();
blockListener = new BlockListener(this);
itemListener = new ItemListener(this);
citizensListener = new CitizensListener(this);
znpcsListener = new ZnpcsListener(this);
playerListener = new PlayerListener(this);
uniteListener = new UniteListener();
partiesListener = new PartiesListener();
effectThread = new NpcEffectThread(this);
moveThread = new PlayerMoveThread(this);
questFactory = new BukkitQuestFactory(this);
actionFactory = new BukkitActionFactory(this);
conditionFactory = new BukkitConditionFactory(this);
depends = new Dependencies(this);
trigger = new DenizenTrigger(this);
// 3 - Load main config
settings.init();
if (settings.getLanguage().contains("-")) {
final Metrics metrics = new Metrics(this);
metrics.addCustomChart(new Metrics.SimplePie("language", () -> settings.getLanguage()));
}
// 4 - Setup language files
try {
setupLang();
} catch (final IOException | URISyntaxException e) {
e.printStackTrace();
}
// 5 - Load command executor
cmdExecutor = new CommandManager(this);
// 6 - Load soft-depends
depends.init();
// 7 - Save resources from jar
saveResourceAs("quests.yml", "quests.yml", false);
saveResourceAs("actions.yml", "actions.yml", false);
saveResourceAs("conditions.yml", "conditions.yml", false);
// 8 - Save config with any new options
getConfig().options().copyDefaults(true);
getConfig().options().header("See https://pikamug.gitbook.io/quests/setup/configuration");
saveConfig();
final StorageFactory storageFactory = new StorageFactory(this);
storage = storageFactory.getInstance();
// 9 - Setup commands
if (getCommand("quests") != null) {
Objects.requireNonNull(getCommand("quests")).setExecutor(getTabExecutor());
Objects.requireNonNull(getCommand("quests")).setTabCompleter(getTabExecutor());
}
if (getCommand("questadmin") != null) {
Objects.requireNonNull(getCommand("questadmin")).setExecutor(getTabExecutor());
Objects.requireNonNull(getCommand("questadmin")).setTabCompleter(getTabExecutor());
}
if (getCommand("quest") != null) {
Objects.requireNonNull(getCommand("quest")).setExecutor(getTabExecutor());
Objects.requireNonNull(getCommand("quest")).setTabCompleter(getTabExecutor());
}
// 10 - Build conversation factories
this.conversationFactory = new ConversationFactory(this).withModality(false)
.withPrefix(context -> ChatColor.GRAY.toString())
.withFirstPrompt(new QuestAcceptPrompt()).withTimeout(settings.getAcceptTimeout())
.thatExcludesNonPlayersWithMessage("Console may not perform this conversation!")
.addConversationAbandonedListener(convoListener);
this.npcConversationFactory = new ConversationFactory(this).withModality(false)
.withFirstPrompt(new NpcOfferQuestPrompt(this)).withTimeout(settings.getAcceptTimeout())
.withLocalEcho(false).addConversationAbandonedListener(convoListener);
// 11 - Register listeners
getServer().getPluginManager().registerEvents(getBlockListener(), this);
getServer().getPluginManager().registerEvents(getItemListener(), this);
depends.linkCitizens();
if (depends.getZnpcsPlus() != null) {
getServer().getPluginManager().registerEvents(getZnpcsListener(), this);
}
getServer().getPluginManager().registerEvents(getPlayerListener(), this);
if (settings.getStrictPlayerMovement() > 0) {
final long ticks = settings.getStrictPlayerMovement() * 20L;
getServer().getScheduler().scheduleSyncRepeatingTask(this, getPlayerMoveThread(), ticks, ticks);
}
if (depends.getPartyProvider() != null) {
getServer().getPluginManager().registerEvents(getUniteListener(), this);
} else if (depends.getPartiesApi() != null) {
getServer().getPluginManager().registerEvents(getPartiesListener(), this);
}
// 12 - Attempt to check for updates
new UpdateChecker(this, 3711).getVersion(version -> {
if (!getDescription().getVersion().split("-")[0].equalsIgnoreCase(version)) {
getLogger().info(ChatColor.DARK_GREEN + Lang.get("updateTo").replace("<version>",
version).replace("<url>", ChatColor.AQUA + getDescription().getWebsite()));
}
});
// 13 - Delay loading of quests, actions and modules
delayLoadQuestInfo();
}
@Override
public void onDisable() {
getLogger().info("Saving Quester data...");
for (final Player p : getServer().getOnlinePlayers()) {
getQuester(p.getUniqueId()).saveData();
}
Bukkit.getScheduler().cancelTasks(this);
getLogger().info("Closing storage...");
if (storage != null) {
storage.close();
}
}
public boolean isLoading() {
return loading;
}
public File getPluginDataFolder() {
return getDataFolder();
}
public Logger getPluginLogger() {
return getLogger();
}
public InputStream getPluginResource(String filename) {
return getResource(filename);
}
public String getDetectedServerSoftwareVersion() {
return bukkitVersion;
}
public Dependencies getDependencies() {
return (Dependencies) depends;
}
public Settings getSettings() {
return (Settings) settings;
}
@Override
public List<ICustomObjective> getCustomObjectives() {
return customObjectives;
}
public Optional<ICustomObjective> getCustomObjective(final String className) {
for (final ICustomObjective co : customObjectives) {
if (co.getClass().getName().equals(className)) {
return Optional.of(co);
}
}
return Optional.empty();
}
@Override
public List<CustomRequirement> getCustomRequirements() {
return customRequirements;
}
public Optional<CustomRequirement> getCustomRequirement(final String className) {
for (final CustomRequirement cr : customRequirements) {
if (cr.getClass().getName().equals(className)) {
return Optional.of(cr);
}
}
return Optional.empty();
}
@Override
public List<CustomReward> getCustomRewards() {
return customRewards;
}
public Optional<CustomReward> getCustomReward(final String className) {
for (final CustomReward cr : customRewards) {
if (cr.getClass().getName().equals(className)) {
return Optional.of(cr);
}
}
return Optional.empty();
}
/**
* Get every Quest loaded in memory
*
* @deprecated Use {@link #getLoadedQuests()}
* @return a list of all Quests
*/
@Deprecated
public LinkedList<Quest> getQuests() {
final LinkedList<Quest> list = new LinkedList<>();
for (IQuest q : quests) {
list.add((Quest) q);
}
return list;
}
/**
* Get every Quest loaded in memory
*
* @return a collection of all Quests
*/
public Collection<IQuest> getLoadedQuests() {
return quests;
}
/**
* Get every Action loaded in memory
*
* @deprecated Use {@link #getLoadedActions()}
* @return a list of all Actions
*/
@Deprecated
public LinkedList<Action> getActions() {
final LinkedList<Action> list = new LinkedList<>();
for (IAction a : actions) {
list.add((Action) a);
}
return list;
}
/**
* Get every IAction loaded in memory
*
* @return a collection of all Actions
*/
public Collection<IAction> getLoadedActions() {
return actions;
}
/**
* Set every IAction loaded in memory
*
* @deprecated Use {@link #setLoadedActions(Collection)}
*/
@Deprecated
public void setActions(final LinkedList<IAction> actions) {
this.actions = actions;
}
/**
* Set every IAction loaded in memory
*
*/
public void setLoadedActions(final Collection<IAction> actions) {
this.actions = actions;
}
/**
* Get every Condition loaded in memory
*
* @deprecated Use {@link #getLoadedConditions()}
* @return a list of all Actions
*/
@Deprecated
public LinkedList<Condition> getConditions() {
final LinkedList<Condition> list = new LinkedList<>();
for (ICondition c : conditions) {
list.add((Condition) c);
}
return list;
}
/**
* Get every ICondition loaded in memory
*
* @return a collection of all Conditions
*/
public Collection<ICondition> getLoadedConditions() {
return conditions;
}
/**
* Set every ICondition loaded in memory
*
* @deprecated Use {@link #setLoadedConditions(Collection)}
*/
@Deprecated
public void setConditions(final LinkedList<ICondition> conditions) {
this.conditions = conditions;
}
/**
* Set every ICondition loaded in memory
*
*/
public void setLoadedConditions(final Collection<ICondition> conditions) {
this.conditions = conditions;
}
/**
* Get Quester from player UUID
*
* @param id Player UUID
* @return new or existing Quester
*/
public Quester getQuester(final @NotNull UUID id) {
final ConcurrentSkipListSet<IQuester> set = (ConcurrentSkipListSet<IQuester>) questers;
for (final IQuester q : set) {
if (q != null && q.getUUID().equals(id)) {
return (Quester) q;
}
}
final Quester quester = new Quester(this, id);
if (depends.getCitizens() != null) {
if (depends.getCitizens().getNPCRegistry().getByUniqueId(id) != null) {
return quester;
}
}
final Quester q = new Quester(this, id);
questers.add(q);
return q;
}
/**
* Get every online Quester playing on this server
*
* @return a collection of all online Questers
*/
public Collection<IQuester> getOnlineQuesters() {
final Collection<IQuester> questers = new ConcurrentSkipListSet<>();
for (final IQuester q : getOfflineQuesters()) {
if (q.getOfflinePlayer().isOnline()) {
// Workaround for issues with the compass on fast join
q.findCompassTarget();
questers.add(q);
}
}
return questers;
}
/**
* Get every Quester that has ever played on this server
*
* @return a collection of all Questers
*/
public Collection<IQuester> getOfflineQuesters() {
return questers;
}
/**
* Set every Quester that has ever played on this server
*
* @param questers a collection of Questers
*/
public void setOfflineQuesters(final Collection<IQuester> questers) {
this.questers = new ConcurrentSkipListSet<>(questers);
}
/**
* Get every NPC UUID which sees use a quest giver, talk target, or kill target
*
* @return a collection of all UUIDs
*/
public Collection<UUID> getQuestNpcUuids() {
return questNpcUuids;
}
/**
* Set every NPC UUID which sees use a quest giver, talk target, or kill target
*
* @param questNpcUuids a collection of UUIDs
*/
@SuppressWarnings("unused")
public void setQuestNpcUuids(final Collection<UUID> questNpcUuids) {
this.questNpcUuids = new ConcurrentSkipListSet<>(questNpcUuids);
}
@SuppressWarnings("unused")
public CommandExecutor getCommandExecutor() {
return cmdExecutor;
}
public TabExecutor getTabExecutor() {
return cmdExecutor;
}
public ConversationFactory getConversationFactory() {
return conversationFactory;
}
public ConversationFactory getNpcConversationFactory() {
return npcConversationFactory;
}
public QuestFactory getQuestFactory() {
return questFactory;
}
public ActionFactory getActionFactory() {
return actionFactory;
}
public ConditionFactory getConditionFactory() {
return conditionFactory;
}
public ConvoListener getConvoListener() {
return convoListener;
}
public BlockListener getBlockListener() {
return blockListener;
}
public ItemListener getItemListener() {
return itemListener;
}
public CitizensListener getCitizensListener() {
return citizensListener;
}
public ZnpcsListener getZnpcsListener() {
return znpcsListener;
}
public PlayerListener getPlayerListener() {
return playerListener;
}
public UniteListener getUniteListener() {
return uniteListener;
}
public NpcEffectThread getNpcEffectThread() {
return effectThread;
}
public PlayerMoveThread getPlayerMoveThread() {
return moveThread;
}
public PartiesListener getPartiesListener() {
return partiesListener;
}
public DenizenTrigger getDenizenTrigger() {
return trigger;
}
public LocaleManager getLocaleManager() {
return localeManager;
}
public Storage getStorage() {
return storage;
}
public class QuestAcceptPrompt extends MiscStringPrompt {
private ConversationContext context;
public QuestAcceptPrompt() {
super(null);
}
public QuestAcceptPrompt(final ConversationContext context) {
super(context);
}
@Override
public ConversationContext getConversationContext() {
return context;
}
public int getSize() {
return 2;
}
public String getTitle(final ConversationContext context) {
return null;
}
@SuppressWarnings("unused")
public ChatColor getNumberColor(final ConversationContext context, final int number) {
switch (number) {
case 1:
return ChatColor.GREEN;
case 2:
return ChatColor.RED;
default:
return null;
}
}
@SuppressWarnings("unused")
public String getSelectionText(final ConversationContext context, final int number) {
switch (number) {
case 1:
return ChatColor.GREEN + Lang.get("yesWord");
case 2:
return ChatColor.RED + Lang.get("noWord");
default:
return null;
}
}
public String getQueryText(final ConversationContext context) {
return Lang.get("acceptQuest");
}
@Override
public @NotNull String getPromptText(final @NotNull ConversationContext context) {
this.context = context;
final MiscPostQuestAcceptEvent event = new MiscPostQuestAcceptEvent(context, this);
getServer().getPluginManager().callEvent(event);
if (!getSettings().canClickablePrompts()) {
return ChatColor.YELLOW + getQueryText(context) + " " + ChatColor.GREEN
+ getSelectionText(context, 1) + ChatColor.RESET + " / " + getSelectionText(context, 2);
}
final TextComponent component = new TextComponent("");
component.addExtra(ChatColor.YELLOW + getQueryText(context) + " " + ChatColor.GREEN);
final TextComponent yes = new TextComponent(getSelectionText(context, 1));
yes.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/quests choice " + Lang.get("yesWord")));
component.addExtra(yes);
component.addExtra(ChatColor.RESET + " / ");
final TextComponent no = new TextComponent(getSelectionText(context, 2));
no.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/quests choice " + Lang.get("noWord")));
component.addExtra(no);
((Player)context.getForWhom()).spigot().sendMessage(component);
return "";
}
@Override
public Prompt acceptInput(final @NotNull ConversationContext context, final String input) {
if (input == null) {
getLogger().severe("Ended conversation because input for " + getName() + "was null");
return Prompt.END_OF_CONVERSATION;
}
final Player player = (Player) context.getForWhom();
if (input.equalsIgnoreCase("1") || input.equalsIgnoreCase("y")
|| input.equalsIgnoreCase(Lang.get("yesWord"))
|| input.equalsIgnoreCase(Lang.get(player, "yesWord"))) {
final IQuester quester = getQuester(player.getUniqueId());
final String questIdToTake = quester.getQuestIdToTake();
if (getQuestByIdTemp(questIdToTake) == null) {
getLogger().warning(player.getName() + " attempted to take quest ID \"" + questIdToTake
+ "\" but something went wrong");
player.sendMessage(ChatColor.RED
+ "Something went wrong! Please report issue to an administrator.");
} else {
quester.takeQuest(getQuestByIdTemp(questIdToTake), false);
}
return Prompt.END_OF_CONVERSATION;
} else if (input.equalsIgnoreCase("2") || input.equalsIgnoreCase("n")
|| input.equalsIgnoreCase(Lang.get("noWord"))
|| input.equalsIgnoreCase(Lang.get(player, "noWord"))) {
Lang.send(player, ChatColor.YELLOW + Lang.get("cancelled"));
return Prompt.END_OF_CONVERSATION;
} else {
final String msg = Lang.get(player, "questInvalidChoice")
.replace("<yes>", Lang.get(player, "yesWord"))
.replace("<no>", Lang.get(player, "noWord"));
Lang.send(player, ChatColor.RED + msg);
return new QuestAcceptPrompt(context);
}
}
}
/**
* Transfer language files from jar to disk, then initialize default
*/
private void setupLang() throws IOException, URISyntaxException {
final String path = "lang";
final File jarFile = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
if (jarFile.isFile()) {
final JarFile jar = new JarFile(jarFile);
final Enumeration<JarEntry> entries = jar.entries();
final Set<String> results = new HashSet<>();
while (entries.hasMoreElements()) {
final String name = entries.nextElement().getName();
if (name.startsWith(path + "/") && name.contains("strings.yml")) {
results.add(name);
}
}
for (final String resourcePath : results) {
saveResourceAs(resourcePath, resourcePath, false);
saveResourceAs(resourcePath, resourcePath.replace(".yml", "_new.yml"), true);
}
jar.close();
}
try {
Lang.init(this, settings.getLanguage());
} catch (final InvalidConfigurationException e) {
e.printStackTrace();
}
}
/**
* Save a Quests plugin resource to a specific path in the filesystem
*
* @param resourcePath jar file location starting from resource folder, i.e. "lang/el-GR/strings.yml"
* @param outputPath file destination starting from Quests folder, i.e. "lang/el-GR/strings.yml"
* @param replace whether or not to replace the destination file
*/
public void saveResourceAs(String resourcePath, final String outputPath, final boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
final InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath
+ "' cannot be found in Quests jar");
}
final String outPath = outputPath.replace('/', File.separatorChar).replace('\\', File.separatorChar);
final File outFile = new File(getDataFolder(), outPath);
final File outDir = new File(outFile.getPath().replace(outFile.getName(), ""));
if (!outDir.exists()) {
if (!outDir.mkdirs()) {
getLogger().log(Level.SEVERE, "Failed to make directories for " + outFile.getName() + " (canWrite= "
+ outDir.canWrite() + ")");
}
}
try {
if (!outFile.exists() || replace) {
final OutputStream out = new FileOutputStream(outFile);
final byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
if (!outFile.exists()) {
getLogger().severe("Unable to copy " + outFile.getName() + " (canWrite= " + outFile.canWrite()
+ ")");
}
}
} catch (final IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
}
/**
* Load quests, actions, conditions, and modules
*
* At startup, this lets soft-depends (namely Citizens) fully load first
*/
private void delayLoadQuestInfo() {
getServer().getScheduler().scheduleSyncDelayedTask(this, () -> {
loadQuests();
loadActions();
loadConditions();
getLogger().log(Level.INFO, "Loaded " + quests.size() + " Quest(s), " + actions.size() + " Action(s), "
+ conditions.size() + " Condition(s) and " + Lang.size() + " Phrase(s)");
for (final Player p : getServer().getOnlinePlayers()) {
final IQuester quester = new Quester(Quests.this, p.getUniqueId());
if (!quester.hasData()) {
quester.saveData();
}
// Workaround for issues with the compass on fast join
quester.findCompassTarget();
questers.add(quester);
}
if (depends.getCitizens() != null) {
if (depends.getCitizens().getNPCRegistry() == null) {
getLogger().log(Level.SEVERE,
"Citizens was enabled but NPCRegistry was null. Disabling linkage.");
depends.unlinkCitizens();
}
}
loadModules();
importQuests();
if (getSettings().canDisableCommandFeedback()) {
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), "gamerule sendCommandFeedback false");
}
loading = false;
}, 5L);
}
private void importQuests() {
final File f = new File(this.getDataFolder(), "import");
if (f.exists() && f.isDirectory()) {
final File[] imports = f.listFiles();
if (imports != null) {
for (final File file : imports) {
if (!file.isDirectory() && file.getName().endsWith(".yml")) {
importQuest(file);
}
}
}
} else if (!f.mkdir()) {
getLogger().warning("Unable to create import directory");
}
}
private void importQuest(final File file) {
FileConfiguration config = null;
try {
config = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(file),
StandardCharsets.UTF_8));
} catch (final IOException e) {
e.printStackTrace();
}
if (config != null) {
final ConfigurationSection questsSection = config.getConfigurationSection("quests");
if (questsSection == null) {
getLogger().severe("Missing 'quests' section marker, canceled import of file " + file.getName());
return;
}
int count = 0;
for (final String questKey : questsSection.getKeys(false)) {
try {
for (final IQuest lq : getLoadedQuests()) {
if (lq.getId().equals(questKey)) {
throw new QuestFormatException("id already exists", questKey);
}
}
final IQuest quest = loadQuest(config, questKey);
if (config.contains("quests." + questKey + ".requirements")) {
loadQuestRequirements(config, questsSection, quest, questKey);
}
if (config.contains("quests." + questKey + ".planner")) {
loadQuestPlanner(config, quest, questKey);
}
if (config.contains("quests." + questKey + ".options")) {
loadQuestOptions(config, quest, questKey);
}
quest.setPlugin(this);
loadQuestStages(quest, config, questKey);
loadQuestRewards(config, quest, questKey);
quests.add(quest);
count++;
} catch (final QuestFormatException | StageFormatException | ActionFormatException
| ConditionFormatException e) {
e.printStackTrace();
}
}
if (count > 0) {
getLogger().info("Imported " + count + " Quests from " + file.getName());
}
} else {
getLogger().severe("Unable to import quest file " + file.getName());
}
}
/**
* Load modules from file
*/
public void loadModules() {
final File f = new File(this.getDataFolder(), "modules");
if (f.exists() && f.isDirectory()) {
final File[] modules = f.listFiles();
if (modules != null) {
for (final File module : modules) {
if (!module.isDirectory() && module.getName().endsWith(".jar")) {
loadModule(module);
}
}
}
} else if (!f.mkdir()) {
getLogger().warning("Unable to create module directory");
}
FileConfiguration config = null;
final File file = new File(this.getDataFolder(), "quests.yml");
try {
config = YamlConfiguration.loadConfiguration(new InputStreamReader(new FileInputStream(file),
StandardCharsets.UTF_8));
} catch (final IOException e) {
e.printStackTrace();
}
if (config != null) {
final ConfigurationSection questsSection;
if (config.contains("quests")) {
questsSection = config.getConfigurationSection("quests");
if (questsSection != null) {
for (final String questKey : questsSection.getKeys(false)) {
try {
if (config.contains("quests." + questKey)) {
loadCustomSections(getQuestByIdTemp(questKey), config, questKey);
} else {
throw new QuestFormatException("Unable to load custom sections", questKey);
}
} catch (final QuestFormatException | StageFormatException ex) {
ex.printStackTrace();
}
}
}
}
} else {
getLogger().severe("Unable to load module data from quests.yml");
}
}
/**
* Load the specified jar as a module
*
* @param jar A custom reward/requirement/objective jar
*/
public void loadModule(final File jar) {
try {
@SuppressWarnings("resource")
final JarFile jarFile = new JarFile(jar);
final Enumeration<JarEntry> entry = jarFile.entries();