forked from Ghost-chu/QuickShop-Reremake
-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathQuickShop.java
More file actions
2398 lines (2287 loc) · 107 KB
/
QuickShop.java
File metadata and controls
2398 lines (2287 loc) · 107 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
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
/*
* This file is a part of project QuickShop, the name is QuickShop.java
* Copyright (C) PotatoCraft Studio and contributors
*
* This program is free software: you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.maxgamer.quickshop;
import com.sk89q.worldedit.bukkit.WorldEditPlugin;
import de.leonhard.storage.LightningBuilder;
import de.leonhard.storage.Yaml;
import de.leonhard.storage.internal.settings.ConfigSettings;
import de.leonhard.storage.internal.settings.ReloadSettings;
import de.tr7zw.nbtapi.plugin.NBTAPI;
import lombok.Getter;
import lombok.Setter;
import me.minebuilders.clearlag.listeners.ItemMergeListener;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.PluginCommand;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.HandlerList;
import org.bukkit.event.entity.ItemSpawnEvent;
import org.bukkit.plugin.InvalidDescriptionException;
import org.bukkit.plugin.InvalidPluginException;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.RegisteredListener;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.java.JavaPluginLoader;
import org.bukkit.scheduler.BukkitRunnable;
import org.bukkit.scheduler.BukkitTask;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.maxgamer.quickshop.api.QuickShopAPI;
import org.maxgamer.quickshop.api.chat.QuickChat;
import org.maxgamer.quickshop.api.command.CommandManager;
import org.maxgamer.quickshop.api.compatibility.CompatibilityManager;
import org.maxgamer.quickshop.api.database.DatabaseHelper;
import org.maxgamer.quickshop.api.economy.AbstractEconomy;
import org.maxgamer.quickshop.api.economy.EconomyType;
import org.maxgamer.quickshop.api.event.QSConfigurationReloadEvent;
import org.maxgamer.quickshop.api.integration.IntegrateStage;
import org.maxgamer.quickshop.api.integration.IntegrationManager;
import org.maxgamer.quickshop.api.localization.text.TextManager;
import org.maxgamer.quickshop.api.shop.AbstractDisplayItem;
import org.maxgamer.quickshop.api.shop.DisplayType;
import org.maxgamer.quickshop.api.shop.ItemMatcher;
import org.maxgamer.quickshop.api.shop.Shop;
import org.maxgamer.quickshop.api.shop.ShopManager;
import org.maxgamer.quickshop.chat.platform.minedown.BungeeQuickChat;
import org.maxgamer.quickshop.command.SimpleCommandManager;
import org.maxgamer.quickshop.database.AbstractDatabaseCore;
import org.maxgamer.quickshop.database.DatabaseManager;
import org.maxgamer.quickshop.database.MySQLCore;
import org.maxgamer.quickshop.database.SQLiteCore;
import org.maxgamer.quickshop.database.SimpleDatabaseHelper;
import org.maxgamer.quickshop.economy.Economy_GemsEconomy;
import org.maxgamer.quickshop.economy.Economy_TNE;
import org.maxgamer.quickshop.economy.Economy_Vault;
import org.maxgamer.quickshop.integration.SimpleIntegrationManager;
import org.maxgamer.quickshop.integration.worldguard.WorldGuardIntegration;
import org.maxgamer.quickshop.listener.BlockListener;
import org.maxgamer.quickshop.listener.ChatListener;
import org.maxgamer.quickshop.listener.ChunkListener;
import org.maxgamer.quickshop.listener.ClearLaggListener;
import org.maxgamer.quickshop.listener.CustomInventoryListener;
import org.maxgamer.quickshop.listener.DisplayProtectionListener;
import org.maxgamer.quickshop.listener.EconomySetupListener;
import org.maxgamer.quickshop.listener.InternalListener;
import org.maxgamer.quickshop.listener.LockListener;
import org.maxgamer.quickshop.listener.PlayerListener;
import org.maxgamer.quickshop.listener.PluginListener;
import org.maxgamer.quickshop.listener.ShopProtectionListener;
import org.maxgamer.quickshop.listener.SignListener;
import org.maxgamer.quickshop.listener.WorldListener;
import org.maxgamer.quickshop.listener.worldedit.WorldEditAdapter;
import org.maxgamer.quickshop.localization.text.SimpleTextManager;
import org.maxgamer.quickshop.nonquickshopstuff.com.rylinaux.plugman.util.PluginUtil;
import org.maxgamer.quickshop.permission.PermissionManager;
import org.maxgamer.quickshop.shop.ShopLoader;
import org.maxgamer.quickshop.shop.ShopPurger;
import org.maxgamer.quickshop.shop.SimpleShopManager;
import org.maxgamer.quickshop.shop.VirtualDisplayItem;
import org.maxgamer.quickshop.util.GameVersion;
import org.maxgamer.quickshop.util.HttpUtil;
import org.maxgamer.quickshop.util.JsonUtil;
import org.maxgamer.quickshop.util.MsgUtil;
import org.maxgamer.quickshop.util.PermissionChecker;
import org.maxgamer.quickshop.util.PlayerFinder;
import org.maxgamer.quickshop.util.ReflectFactory;
import org.maxgamer.quickshop.util.Timer;
import org.maxgamer.quickshop.util.Util;
import org.maxgamer.quickshop.util.compatibility.SimpleCompatibilityManager;
import org.maxgamer.quickshop.util.config.ConfigCommentUpdater;
import org.maxgamer.quickshop.util.config.ConfigProvider;
import org.maxgamer.quickshop.util.config.ConfigurationFixer;
import org.maxgamer.quickshop.util.envcheck.CheckResult;
import org.maxgamer.quickshop.util.envcheck.EnvCheckEntry;
import org.maxgamer.quickshop.util.envcheck.EnvironmentChecker;
import org.maxgamer.quickshop.util.envcheck.ResultContainer;
import org.maxgamer.quickshop.util.envcheck.ResultReport;
import org.maxgamer.quickshop.util.matcher.item.BukkitItemMatcherImpl;
import org.maxgamer.quickshop.util.matcher.item.QuickShopItemMatcherImpl;
import org.maxgamer.quickshop.util.reload.ReloadManager;
import org.maxgamer.quickshop.util.reporter.error.EmptyErrorReporter;
import org.maxgamer.quickshop.util.reporter.error.IErrorReporter;
import org.maxgamer.quickshop.util.reporter.error.RollbarErrorReporter;
import org.maxgamer.quickshop.watcher.CalendarWatcher;
import org.maxgamer.quickshop.watcher.DisplayAutoDespawnWatcher;
import org.maxgamer.quickshop.watcher.DisplayDupeRemoverWatcher;
import org.maxgamer.quickshop.watcher.DisplayWatcher;
import org.maxgamer.quickshop.watcher.LogWatcher;
import org.maxgamer.quickshop.watcher.OngoingFeeWatcher;
import org.maxgamer.quickshop.watcher.ShopContainerWatcher;
import org.maxgamer.quickshop.watcher.SignUpdateWatcher;
import org.maxgamer.quickshop.watcher.TpsWatcher;
import org.maxgamer.quickshop.watcher.UpdateWatcher;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.StringJoiner;
import java.util.UUID;
import java.util.logging.Level;
public class QuickShop extends JavaPlugin implements QuickShopAPI {
/**
* The active instance of QuickShop
* You shouldn't use this if you really need it.
*/
@Deprecated
private static QuickShop instance;
/**
* The manager to check permissions.
*/
private static PermissionManager permissionManager;
private static boolean loaded = false;
/**
* If running environment test
*/
@Getter
private static volatile boolean testing = false;
/* Public QuickShop API */
private final SimpleCompatibilityManager compatibilityTool = new SimpleCompatibilityManager(this);
private final Map<String, Integer> limits = new HashMap<>(15);
private GameVersion gameVersion;
/**
* The shop limites.
*/
private final ConfigProvider configProvider = new ConfigProvider(this, new File(getDataFolder(), "config.yml"));
private final List<BukkitTask> timerTaskList = new ArrayList<>(3);
@Getter
private final ReloadManager reloadManager = new ReloadManager();
/* Public QuickShop API End */
@Getter
private final QuickChat quickChat = new BungeeQuickChat(this);
@Getter
private final TpsWatcher tpsWatcher = new TpsWatcher();
boolean onLoadCalled = false;
private SimpleIntegrationManager integrationHelper;
private SimpleDatabaseHelper databaseHelper;
private SimpleCommandManager commandManager;
private ItemMatcher itemMatcher;
private SimpleShopManager shopManager;
private SimpleTextManager textManager;
private boolean priceChangeRequiresFee = false;
/**
* The BootError, if it not NULL, plugin will stop loading and show setted errors when use /qs
*/
@Nullable
@Getter
@Setter
private BootError bootError;
/**
* Queued database manager
*/
@Getter
private DatabaseManager databaseManager;
/**
* Default database prefix, can overwrite by config
* <p>
* Deprecated: use manager#getDatabase#getTableprefix instead
*/
@Getter
@Deprecated
private String dbPrefix = "";
/**
* Whether we should use display items or not
*/
private boolean display = true;
@Getter
private int displayItemCheckTicks;
@Getter
@Deprecated
private DisplayWatcher displayWatcher;
/**
* The economy we hook into for transactions
*/
@Getter
@Nullable
private AbstractEconomy economy;
/**
* Whether to limit players shop amounts
*/
private boolean limit = false;
@Nullable
@Getter
private LogWatcher logWatcher;
/**
* bStats, good helper for metrics.
*/
private Metrics metrics;
/**
* The plugin OpenInv (null if not present)
*/
@Getter
private Plugin openInvPlugin;
/**
* The plugin PlaceHolderAPI(null if not present)
*/
@Getter
private Plugin placeHolderAPI;
/**
* A util to call to check some actions permission
*/
@Getter
private PermissionChecker permissionChecker;
/**
* The error reporter to help devs report errors to Sentry.io
*/
@Getter
private IErrorReporter sentryErrorReporter = new EmptyErrorReporter();
/**
* The server UniqueID, use to the ErrorReporter
*/
@Getter
private UUID serverUniqueID;
private boolean setupDBonEnableding = false;
/**
* Rewrited shoploader, more faster.
*/
@Getter
private ShopLoader shopLoader;
@Getter
private DisplayAutoDespawnWatcher displayAutoDespawnWatcher;
@Getter
private OngoingFeeWatcher ongoingFeeWatcher;
@Getter
private SignUpdateWatcher signUpdateWatcher;
@Getter
private ShopContainerWatcher shopContainerWatcher;
@Getter
private @Deprecated
DisplayDupeRemoverWatcher displayDupeRemoverWatcher;
@Getter
@Deprecated
private boolean enabledAsyncDisplayDespawn;
@Getter
private Plugin blocksHubPlugin;
@Getter
private Plugin lwcPlugin;
@Getter
private Cache shopCache;
@Getter
private boolean allowStack;
@Getter
private boolean includeOfflinePlayer;
@Getter
private EnvironmentChecker environmentChecker;
@Getter
@Nullable
private UpdateWatcher updateWatcher;
@Getter
private BuildInfo buildInfo;
@Getter
@Nullable
private String currency = null;
@Getter
private CalendarWatcher calendarWatcher;
@Getter
private Plugin worldEditPlugin;
@Getter
private WorldEditAdapter worldEditAdapter;
@Getter
private ShopPurger shopPurger;
@Getter
@Nullable
private NBTAPI nbtapi = null;
private int loggingLocation = 0;
public void disableNBTAPI() {
nbtapi = null;
}
/**
* Use for mock bukkit
*/
public QuickShop() {
super();
}
/**
* Use for mock bukkit
*/
protected QuickShop(JavaPluginLoader loader, PluginDescriptionFile description, File dataFolder, File file) {
super(loader, description, dataFolder, file);
}
@NotNull
public static QuickShop getInstance() {
return instance;
}
/**
* Returns QS version, this method only exist on QuickShop forks If running other QuickShop forks,, result
* may not is "Reremake x.x.x" If running QS official, Will throw exception.
*
* @return Plugin Version
*/
public static String getVersion() {
return QuickShop.instance.getDescription().getVersion();
}
/**
* Get the permissionManager as static
*
* @return the permission Manager.
*/
public static PermissionManager getPermissionManager() {
return permissionManager;
}
/**
* Return the QSRR's fork edition name, you can modify this if you want create yourself fork.
*
* @return The fork name.
*/
public static String getFork() {
return "Reremake";
}
public IntegrationManager getIntegrationHelper() {
return integrationHelper;
}
@Deprecated
private Yaml configurationForCompatibility = null;
/**
* Get the Player's Shop limit.
*
* @param p The player you want get limit.
* @return int Player's shop limit
*/
public int getShopLimit(@NotNull Player p) {
int max = getConfig().getInt("limits.default");
for (Entry<String, Integer> entry : limits.entrySet()) {
if (entry.getValue() > max && getPermissionManager().hasPermission(p, entry.getKey())) {
max = entry.getValue();
}
}
return max;
}
/**
* Load 3rdParty plugin support module.
*/
private void load3rdParty() {
// added for compatibility reasons with OpenInv - see
// https://github.com/KaiKikuchi/QuickShop/issues/139
if (getConfig().getBoolean("plugin.OpenInv")) {
this.openInvPlugin = Bukkit.getPluginManager().getPlugin("OpenInv");
if (this.openInvPlugin != null && openInvPlugin.isEnabled()) {
try {
if (Util.verifyClassLoader(openInvPlugin) &&
//To avoid class conflict, we load the class from its class loader
openInvPlugin.getClass().getClassLoader().loadClass("com.lishid.openinv.IOpenInv").isInstance(openInvPlugin)) {
getLogger().info("Successfully loaded OpenInv support!");
} else {
getLogger().info("Failed to load OpenInv support, this version is unsupported!");
}
} catch (ClassNotFoundException e) {
getLogger().info("Failed to find IOpenInv interface, this version is unsupported!");
}
}
}
if (getConfig().getBoolean("plugin.PlaceHolderAPI")) {
this.placeHolderAPI = Bukkit.getPluginManager().getPlugin("PlaceholderAPI");
if (this.placeHolderAPI != null && placeHolderAPI.isEnabled()) {
if (Util.verifyClassLoader(placeHolderAPI) && Util.loadClassAndCheckName(placeHolderAPI, "me.clip.placeholderapi.PlaceholderAPIPlugin")) {
getLogger().info("Successfully loaded PlaceHolderAPI support!");
} else {
getLogger().info("Failed to load PlaceHolderAPI support, this version is unsupported!");
}
}
}
if (getConfig().getBoolean("plugin.BlockHub.enable")) {
this.blocksHubPlugin = Bukkit.getPluginManager().getPlugin("BlocksHub");
if (this.blocksHubPlugin != null && blocksHubPlugin.isEnabled()) {
if (Util.verifyClassLoader(blocksHubPlugin) && Util.loadClassAndCheckName(blocksHubPlugin, "org.primesoft.blockshub.BlocksHubBukkit")) {
getLogger().info("Successfully loaded BlockHub support!");
} else {
getLogger().info("Failed to load BlockHub support, this version is unsupported!");
}
}
}
if (getConfig().getBoolean("plugin.WorldEdit")) {
// GameVersion gameVersion = GameVersion.get(nmsVersion);
this.worldEditPlugin = Bukkit.getPluginManager().getPlugin("WorldEdit");
if (this.worldEditPlugin != null && worldEditPlugin.isEnabled()) {
if (Util.verifyClassLoader(worldEditPlugin) && Util.loadClassAndCheckName(worldEditPlugin, "com.sk89q.worldedit.bukkit.WorldEditPlugin")) {
this.worldEditAdapter = new WorldEditAdapter(this, (WorldEditPlugin) this.worldEditPlugin);
this.worldEditAdapter.register();
getLogger().info("Successfully loaded WorldEdit support!");
} else {
getLogger().info("Failed to load WorldEdit support, this version is unsupported!");
}
}
}
if (getConfig().getBoolean("plugin.LWC")) {
this.lwcPlugin = Bukkit.getPluginManager().getPlugin("LWC");
if (this.lwcPlugin != null && lwcPlugin.isEnabled()) {
if (Util.verifyClassLoader(lwcPlugin) && Util.loadClassAndCheckName(lwcPlugin, "com.griefcraft.lwc.LWCPlugin") && Util.isMethodAvailable("com.griefcraft.lwc.LWC", "findProtection", org.bukkit.Location.class)) {
getLogger().info("Successfully loaded LWC support!");
} else {
getLogger().warning("Unsupported LWC version, please make sure you are using the modern version of LWC!");
this.lwcPlugin = null;
}
}
}
if (getConfig().getBoolean("plugin.NBTAPI")) {
Plugin nbtapi = Bukkit.getPluginManager().getPlugin("NBTAPI");
if (nbtapi != null && nbtapi.isEnabled()) {
if (Util.verifyClassLoader(nbtapi) && Util.loadClassAndCheckName(nbtapi, "de.tr7zw.nbtapi.plugin.NBTAPI") &&
Util.isMethodAvailable(nbtapi.getClass(), "isCompatible")) {
this.nbtapi = (NBTAPI) nbtapi;
if (!this.nbtapi.isCompatible()) {
getLogger().warning("NBTAPI plugin failed to loading, QuickShop NBTAPI support module has been disabled. Try update NBTAPI version to resolve the issue. (" + nbtapi.getDescription().getVersion() + ")");
this.nbtapi = null;
} else {
getLogger().info("Successfully loaded NBTAPI support!");
}
} else {
getLogger().warning("NBTAPI plugin is invalid, QuickShop NBTAPI support module has been disabled. Try update NBTAPI version to resolve the issue.");
}
}
}
Bukkit.getPluginManager().registerEvents(this.compatibilityTool, this);
compatibilityTool.searchAndRegisterPlugins();
if (this.display) {
//VirtualItem support
if (AbstractDisplayItem.getNowUsing() == DisplayType.VIRTUALITEM) {
getLogger().info("Using Virtual Item display, loading ProtocolLib support...");
Plugin protocolLibPlugin = Bukkit.getPluginManager().getPlugin("ProtocolLib");
if (protocolLibPlugin != null && Util.verifyClassLoader(protocolLibPlugin) && protocolLibPlugin.isEnabled()) {
getLogger().info("Successfully loaded ProtocolLib support!");
} else {
getLogger().warning("Failed to load ProtocolLib support, fallback to real item display");
getConfig().set("shop.display-type", 0);
saveConfiguration();
}
}
if (AbstractDisplayItem.getNowUsing() == DisplayType.REALITEM) {
getLogger().warning("You're using Real Display system and that may cause your server lagg, switch to Virtual Display system if you can! (Checkout display-type option in config.yml)");
Plugin clearLagPlugin = Bukkit.getPluginManager().getPlugin("ClearLag");
if (clearLagPlugin != null && Util.verifyClassLoader(clearLagPlugin)) {
try {
for (RegisteredListener clearLagListener : ItemSpawnEvent.getHandlerList().getRegisteredListeners()) {
if (!clearLagListener.getPlugin().equals(clearLagPlugin)) {
continue;
}
if (clearLagListener.getListener().getClass().equals(ItemMergeListener.class)) {
ItemSpawnEvent.getHandlerList().unregister(clearLagListener.getListener());
getLogger().warning("+++++++++++++++++++++++++++++++++++++++++++");
getLogger().severe("Detected incompatible module of ClearLag-ItemMerge module, it will broken the QuickShop display, we already unregister this module listener!");
getLogger().severe("Please turn off it in the ClearLag config.yml or turn off the QuickShop display feature!");
getLogger().severe("If you didn't do that, this message will keep spam in your console every times you server boot up!");
getLogger().warning("+++++++++++++++++++++++++++++++++++++++++++");
}
}
} catch (Exception ignored) {
}
}
}
}
}
// /**
// * Logs the given string to qs.log, if QuickShop is configured to do so.
// *
// * @param s The string to log. It will be prefixed with the date and time.
// */
// public void log(@NotNull String s) {
// Util.debugLog("[SHOP LOG] " + s);
// if (this.getLogWatcher() == null) {
// return;
// }
// this.getLogWatcher().log(s);
// }
public void logEvent(@NotNull Object eventObject) {
if (this.getLogWatcher() == null) {
return;
}
if (loggingLocation == 0) {
this.getLogWatcher().log(JsonUtil.getGson().toJson(eventObject));
} else {
getDatabaseHelper().insertHistoryRecord(eventObject);
}
}
/**
* Tries to load the economy and its core. If this fails, it will try to use vault. If that fails,
* it will return false.
*
* @return true if successful, false if the core is invalid or is not found, and vault cannot be
* used.
*/
public boolean loadEcon() {
try {
// EconomyCore core = new Economy_Vault();
switch (EconomyType.fromID(getConfig().getInt("economy-type"))) {
case UNKNOWN:
setupBootError(new BootError(this.getLogger(), "Can't load the Economy provider, invaild value in config.yml."), true);
return false;
case VAULT:
economy = new Economy_Vault(this);
Util.debugLog("Now using the Vault economy system.");
if (getConfig().getDouble("tax", 0.0d) > 0) {
try {
String taxAccount = getConfig().getString("tax-account", "tax");
if (!taxAccount.isEmpty()) {
OfflinePlayer tax;
if (Util.isUUID(taxAccount)) {
tax = PlayerFinder.findOfflinePlayerByUUID(UUID.fromString(taxAccount));
} else {
tax = PlayerFinder.findOfflinePlayerByUUID(PlayerFinder.findUUIDByName(Objects.requireNonNull(taxAccount), true, true));
}
Economy_Vault vault = (Economy_Vault) economy;
if (vault.isValid()) {
if (!Objects.requireNonNull(vault.getVault()).hasAccount(tax)) {
try {
Util.debugLog("Tax account not exists! Creating...");
getLogger().warning("QuickShop detected tax account not exists, we're trying to create one. If you see any errors, please change tax-account in config.yml to server owner in-game username");
if (vault.getVault().createPlayerAccount(tax)) {
getLogger().info("Tax account created.");
} else {
getLogger().warning("Cannot to create tax-account, please change tax-account in config.yml to server owner in-game username");
}
} catch (Exception ignored) {
}
if (!vault.getVault().hasAccount(tax)) {
getLogger().warning("Tax account's player never played this server before and failed to create one, that may cause server lagg or economy system error, you should change that name. But if this warning not cause any issues, you can safety ignore this.");
}
}
}
}
} catch (Exception ignored) {
Util.debugLog("Failed to fix account issue.");
}
}
break;
case GEMS_ECONOMY:
economy = new Economy_GemsEconomy(this);
Util.debugLog("Now using the GemsEconomy economy system.");
break;
case TNE:
economy = new Economy_TNE(this);
Util.debugLog("Now using the TNE economy system.");
break;
default:
Util.debugLog("No any economy provider selected.");
break;
}
if (economy == null) {
return false;
}
if (!economy.isValid()) {
setupBootError(BuiltInSolution.econError(), false);
return false;
}
economy = ServiceInjector.getEconomy(economy);
} catch (Throwable e) {
this.getSentryErrorReporter().ignoreThrow();
getLogger().log(Level.WARNING, "Something going wrong when loading up economy system", e);
getLogger().severe("QuickShop could not hook into a economy/Not found Vault or Reserve!");
getLogger().severe("QuickShop CANNOT start!");
setupBootError(BuiltInSolution.econError(), false);
getLogger().severe("Plugin listeners was disabled, please fix the economy issue.");
return false;
}
return true;
}
@Override
public @NotNull FileConfiguration getConfig() throws UnsupportedOperationException {
return configProvider.get();
}
@Deprecated
public @NotNull Yaml getConfiguration() {
return configurationForCompatibility == null ? configurationForCompatibility = LightningBuilder
.fromFile(new File(getDataFolder(), "config.yml"))
.addInputStreamFromResource("config.yml")
.setReloadSettings(ReloadSettings.MANUALLY)
.setConfigSettings(ConfigSettings.PRESERVE_COMMENTS)
.createYaml() : configurationForCompatibility;
}
@ApiStatus.ScheduledForRemoval
@Override
@Deprecated
public void saveConfig() {
this.saveConfiguration();
//configProvider.save();
}
public void saveConfiguration() {
this.configProvider.save();
}
/**
* Reloads QuickShops config
*/
@Override
@Deprecated
public void reloadConfig() {
this.reloadConfiguration();
}
public void reloadConfiguration() {
configProvider.reload();
// Load quick variables
this.display = this.getConfig().getBoolean("shop.display-items");
this.priceChangeRequiresFee = this.getConfig().getBoolean("shop.price-change-requires-fee");
this.displayItemCheckTicks = this.getConfig().getInt("shop.display-items-check-ticks");
this.allowStack = this.getConfig().getBoolean("shop.allow-stacks");
this.includeOfflinePlayer = this.getConfig().getBoolean("include-offlineplayer-for-command");
this.currency = this.getConfig().getString("currency");
this.loggingLocation = this.getConfig().getInt("logging.location");
if (StringUtils.isEmpty(this.currency)) {
this.currency = null;
}
if (this.getConfig().getBoolean("logging.enable")) {
logWatcher = new LogWatcher(this, new File(getDataFolder(), "qs.log"));
} else {
logWatcher = null;
}
Bukkit.getPluginManager().callEvent(new QSConfigurationReloadEvent(this));
}
/**
* Early than onEnable, make sure instance was loaded in first time.
*/
@Override
public final void onLoad() {
instance = this;
Util.setPlugin(this);
this.onLoadCalled = true;
getLogger().info("QuickShop " + getFork() + " - Early boot step - Booting up");
//BEWARE THESE ONLY RUN ONCE
this.buildInfo = new BuildInfo(getResource("BUILDINFO"));
runtimeCheck(EnvCheckEntry.Stage.ON_LOAD);
getLogger().info("Reading the configuration...");
this.initConfiguration();
this.bootError = null;
getLogger().info("Loading messages translation over-the-air (this may need take a while).");
this.textManager = new SimpleTextManager(this);
textManager.load();
getLogger().info("Loading up integration modules.");
this.integrationHelper = new SimpleIntegrationManager(this);
this.integrationHelper.callIntegrationsLoad(IntegrateStage.onLoadBegin);
if (getConfig().getBoolean("integration.worldguard.enable")) {
Plugin wg = Bukkit.getPluginManager().getPlugin("WorldGuard");
// WG require register flags when onLoad called.
if (wg != null) {
this.integrationHelper.register(new WorldGuardIntegration(this));
}
}
this.integrationHelper.callIntegrationsLoad(IntegrateStage.onLoadAfter);
getLogger().info("QuickShop " + getFork() + " - Early boot step - Complete");
}
@Override
public final void onDisable() {
getLogger().info("QuickShop is finishing remaining work, this may need a while...");
if (sentryErrorReporter != null) {
sentryErrorReporter.unregister();
}
if (this.integrationHelper != null) {
this.integrationHelper.callIntegrationsUnload(IntegrateStage.onUnloadBegin);
}
Util.debugLog("Unloading all shops...");
try {
if (getShopManager() != null) {
getShopManager().getLoadedShops().forEach(Shop::onUnload);
}
} catch (Exception ignored) {
}
Util.debugLog("Unregister hooks...");
if (worldEditAdapter != null) {
worldEditAdapter.unregister();
}
Util.debugLog("Calling integrations...");
if (integrationHelper != null) {
integrationHelper.callIntegrationsUnload(IntegrateStage.onUnloadAfter);
integrationHelper.unregisterAll();
}
compatibilityTool.unregisterAll();
Util.debugLog("Cleaning up resources and unloading all shops...");
/* Remove all display items, and any dupes we can find */
if (shopManager != null) {
shopManager.clear();
}
if (AbstractDisplayItem.getNowUsing() == DisplayType.VIRTUALITEM) {
VirtualDisplayItem.VirtualDisplayItemManager.unload();
}
Util.debugLog("Cleaning up database queues...");
if (this.getDatabaseManager() != null) {
this.getDatabaseManager().unInit();
}
Util.debugLog("Unregistering tasks...");
if (logWatcher != null) {
logWatcher.close();
}
Iterator<BukkitTask> taskIterator = timerTaskList.iterator();
while (taskIterator.hasNext()) {
BukkitTask task = taskIterator.next();
if (!task.isCancelled()) {
task.cancel();
}
taskIterator.remove();
}
if (calendarWatcher != null) {
calendarWatcher.stop();
}
try {
tpsWatcher.cancel();
} catch (IllegalStateException ignored) {
}
/* Unload UpdateWatcher */
if (this.updateWatcher != null) {
this.updateWatcher.uninit();
}
Util.debugLog("Cleanup tasks...");
try {
Bukkit.getScheduler().cancelTasks(this);
} catch (Throwable ignored) {
}
Util.debugLog("Cleanup listeners...");
HandlerList.unregisterAll(this);
Util.debugLog("Unregistering plugin services...");
getServer().getServicesManager().unregisterAll(this);
Util.debugLog("Shutdown okhttp client...");
HttpUtil.shutdown();
Util.debugLog("Cleanup...");
Util.debugLog("All shutdown work is finished.");
}
public void reload() {
PluginManager pluginManager = getServer().getPluginManager();
try {
File file = Paths.get(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).toFile();
//When quickshop was updated, we need to stop reloading
if (getUpdateWatcher() != null) {
File updatedJar = getUpdateWatcher().getUpdater().getUpdatedJar();
if (updatedJar != null) {
throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Plugin was updated)");
}
}
if (!file.exists()) {
throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Failed to find plugin jar)");
}
Throwable throwable = PluginUtil.unload(this);
if (throwable != null) {
throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Plugin unloading has failed)", throwable);
}
Plugin plugin = pluginManager.loadPlugin(file);
if (plugin != null) {
plugin.onLoad();
pluginManager.enablePlugin(plugin);
} else {
throw new IllegalStateException("Failed to reload QuickShop! Please consider restarting the server. (Plugin loading has failed)");
}
} catch (URISyntaxException | InvalidDescriptionException | InvalidPluginException e) {
throw new RuntimeException("Failed to reload QuickShop! Please consider restarting the server.", e);
}
}
private void initConfiguration() {
/* Process the config */
//noinspection ResultOfMethodCallIgnored
getDataFolder().mkdirs();
try {
saveDefaultConfig();
} catch (IllegalArgumentException resourceNotFoundException) {
getLogger().severe("Failed to save config.yml from jar, The binary file of QuickShop may corrupted. Please re-download from our website.");
}
reloadConfiguration();
if (getConfig().getInt("config-version", 0) == 0) {
getConfig().set("config-version", 1);
}
/* It will generate a new UUID above updateConfig */
this.serverUniqueID = UUID.fromString(Objects.requireNonNull(getConfig().getString("server-uuid", String.valueOf(UUID.randomUUID()))));
try {
updateConfig(getConfig().getInt("config-version"));
} catch (IOException exception) {
getLogger().log(Level.WARNING, "Failed to update configuration", exception);
}
}
private void runtimeCheck(@NotNull EnvCheckEntry.Stage stage) {
testing = true;
environmentChecker = new org.maxgamer.quickshop.util.envcheck.EnvironmentChecker(this);
ResultReport resultReport = environmentChecker.run(stage);
StringJoiner joiner = new StringJoiner("\n", "", "");
if (resultReport.getFinalResult().ordinal() > CheckResult.WARNING.ordinal()) {
for (Entry<EnvCheckEntry, ResultContainer> result : resultReport.getResults().entrySet()) {
if (result.getValue().getResult().ordinal() > CheckResult.WARNING.ordinal()) {
joiner.add(String.format("- [%s/%s] %s", result.getValue().getResult().getDisplay(), result.getKey().name(), result.getValue().getResultMessage()));
}
}
}
// Check If we need kill the server or disable plugin
switch (resultReport.getFinalResult()) {
case DISABLE_PLUGIN:
Bukkit.getPluginManager().disablePlugin(this);
break;
case STOP_WORKING:
setupBootError(new BootError(this.getLogger(), joiner.toString()), true);
PluginCommand command = getCommand("qs");
if (command != null) {
Util.mainThreadRun(() -> command.setTabCompleter(this)); //Disable tab completer
}
break;
case KILL_SERVER:
getLogger().severe("[Security Risk Detected] QuickShop forcing crash the server for security, contact the developer for details.");
String result = environmentChecker.getReportMaker().bake();
File reportFile = writeSecurityReportToFile();
URI uri = null;
if (reportFile != null) {
uri = reportFile.toURI();
}
if (uri != null) {
getLogger().warning("[Security Risk Detected] To get more details, please check: " + uri);
try {
if (java.awt.Desktop.isDesktopSupported()) {
java.awt.Desktop dp = java.awt.Desktop.getDesktop();
if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
dp.browse(uri);
getLogger().warning("[Security Risk Detected] A browser already open for you. ");
}
}
} catch (Throwable ignored) {
//If failed, write directly to console
getLogger().severe(result);
}
} else {
//If write failed, write directly to console
getLogger().severe(result);
}
//Wait for a while for user and logger outputting
try {
//10 seconds
Thread.yield();
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// Halt the process, kill the server
Runtime.getRuntime().halt(-1);
default:
break;
}
testing = false;
}
private File writeSecurityReportToFile() {
File file = new File(getDataFolder(), UUID.randomUUID() + ".security.letter.txt");
try {
Files.write(new File(getDataFolder(), UUID.randomUUID() + ".security.letter.txt").toPath(), environmentChecker.getReportMaker().bake().getBytes(StandardCharsets.UTF_8));
file = file.getCanonicalFile();
} catch (IOException e) {
getLogger().log(Level.SEVERE, "Failed to write security report!", e);
return null;
}
return file;
}
@Override
public final void onEnable() {
if (!this.onLoadCalled) {
getLogger().severe("FATAL: onLoad not called and QuickShop trying patching them... Some Integrations will won't work or work incorrectly!");
try {
onLoad();
} catch (Throwable ignored) {
}
}
Timer enableTimer = new Timer(true);
this.integrationHelper.callIntegrationsLoad(IntegrateStage.onEnableBegin);
getLogger().info("QuickShop " + getFork());
/* Check the running envs is support or not. */
getLogger().info("Starting plugin self-test, please wait...");
runtimeCheck(EnvCheckEntry.Stage.ON_ENABLE);
getLogger().info("Reading the configuration...");
this.initConfiguration();
getLogger().info("Developers: " + Util.list2String(this.getDescription().getAuthors()));
getLogger().info("Original author: Netherfoam, Timtower, KaiNoMood");
getLogger().info("Let's start loading the plugin");
getLogger().info("Chat processor selected: Hardcoded BungeeChat Lib");
/* Process Metrics and Sentry error reporter. */
metrics = new Metrics(this, 3320);
try {
if (!getConfig().getBoolean("auto-report-errors")) {
Util.debugLog("Error reporter was disabled!");
} else {
sentryErrorReporter = new RollbarErrorReporter(this);
}
} catch (Throwable th) {
getLogger().warning("Cannot load the Sentry Error Reporter: " + th.getMessage());
getLogger().warning("Because our error reporter doesn't work, please report this error to developer, thank you!");
}
/* Initalize the Utils */
this.loadItemMatcher();
Util.initialize();
try {
MsgUtil.loadI18nFile();
} catch (Exception e) {
getLogger().log(Level.WARNING, "Error when loading translation", e);
}
MsgUtil.loadItemi18n();
MsgUtil.loadEnchi18n();
MsgUtil.loadPotioni18n();
/* Load 3rd party supports */
load3rdParty();
//Load the database
setupDBonEnableding = true;