-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathCraftIRC.java
More file actions
1345 lines (1196 loc) · 49.2 KB
/
Copy pathCraftIRC.java
File metadata and controls
1345 lines (1196 loc) · 49.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
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
package com.ensifera.animosity.craftirc;
import com.ensifera.animosity.craftirc.libs.com.sk89q.util.config.Configuration;
import com.ensifera.animosity.craftirc.libs.com.sk89q.util.config.ConfigurationNode;
import com.ensifera.animosity.craftirc.libs.org.jibble.pircbot.Colors;
import net.milkbowl.vault.chat.Chat;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.plugin.java.JavaPlugin;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* @author Animosity
* @author ricin
* @author Protected
* @author mbaxter
* @author dequis
*/
public class CraftIRC extends JavaPlugin {
private Configuration configuration;
// Misc class attributes
private List<Minebot> instances;
private boolean debug;
private Timer holdTimer = new Timer();
private Timer retryTimer = new Timer();
private Map<HoldType, Boolean> hold;
private String firstChannelTag;
private boolean derpFakeExceptionSent = false;
// Bots and channels config storage
private List<ConfigurationNode> bots;
private List<ConfigurationNode> colormap;
private Map<Integer, List<ConfigurationNode>> channodes;
private Map<Path, ConfigurationNode> paths;
// Endpoints
private Map<String, EndPoint> endpoints;
private Map<EndPoint, String> tags;
private Map<String, CommandEndPoint> irccmds;
private Map<String, List<String>> taggroups;
private Chat vault;
// Replacement Filters
private Map<String, Map<String, String>> replaceFilters;
private boolean cancelChat;
void log(String message) {
this.getLogger().info(message);
}
void logWarn(String message) {
this.getLogger().warning(message);
}
private void logDerp(String message) {
this.getLogger().severe(message);
if (!this.derpFakeExceptionSent) {
// show a fake exception, and get the users to hopefully notice this poor error
(new Throwable("You made a mistake with your config. This is an error to get your attention. Don't report bugs for this.")).printStackTrace();
this.derpFakeExceptionSent = true;
}
}
/***************************
* Bukkit stuff
***************************/
@Override
public void onEnable() {
try {
// Checking if the configuration file exists and imports the default one from the .jar if it doesn't
final File configFile = new File(this.getDataFolder(), "config.yml");
if (!configFile.exists()) {
this.saveDefaultConfig();
this.autoDisable();
return;
}
this.derpFakeExceptionSent = false;
this.configuration = new Configuration(configFile);
this.configuration.load();
this.cancelChat = this.configuration.getBoolean("settings.cancel-chat", false);
this.endpoints = new HashMap<>();
this.tags = new HashMap<>();
this.irccmds = new HashMap<>();
this.taggroups = new HashMap<>();
this.bots = new ArrayList<>(this.configuration.getNodeList("bots", null));
this.channodes = new HashMap<>();
for (int botID = 0; botID < this.bots.size(); botID++) {
this.channodes.put(botID, new ArrayList<>(this.bots.get(botID).getNodeList("channels", null)));
}
this.colormap = new ArrayList<>(this.configuration.getNodeList("colormap", null));
this.paths = new HashMap<>();
for (final ConfigurationNode path : this.configuration.getNodeList("paths", new LinkedList<ConfigurationNode>())) {
final Path identifier = new Path(path.getString("source"), path.getString("target"));
if (!identifier.getSourceTag().equals(identifier.getTargetTag()) && !this.paths.containsKey(identifier)) {
this.paths.put(identifier, path);
}
}
if (this.cAutoPaths() && this.paths.size() > 0) {
this.logDerp("Auto-paths are enabled but there are paths defined in the paths section of the config - this may cause unexpected behavior!");
}
// Replace filters
this.replaceFilters = new HashMap<>();
try {
for (String key : this.configuration.getNode("filters").getKeys()) {
// Map key to regex pattern, value to replacement.
Map<String, String> replaceMap = new HashMap<>();
this.replaceFilters.put(key, replaceMap);
for (ConfigurationNode fieldNode : this.configuration.getNodeList("filters." + key, null)) {
Map<String, Object> patterns = fieldNode.getAll();
if (patterns != null)
for (String pattern : patterns.keySet())
replaceMap.put(pattern, patterns.get(pattern).toString());
}
// Also supports non-map entries.
for (String unMappedEntry : this.configuration.getStringList("filters." + key, null))
if (unMappedEntry.length() > 0 && unMappedEntry.charAt(0) != '{') // mapped toString() begins with {, but regex can't begin with {.
replaceMap.put(unMappedEntry, "");
}
} catch (NullPointerException ignored) {
}
// Retry timers
this.retryTimer = new Timer();
// Event listeners
this.getServer().getPluginManager().registerEvents(new CraftIRCListener(this), this);
this.getServer().getPluginManager().registerEvents(new ConsoleListener(this), this);
// Native endpoints!
if ((this.cMinecraftTag() != null) && !this.cMinecraftTag().equals("")) {
this.registerEndPoint(this.cMinecraftTag(), new MinecraftPoint(this, this.getServer())); // The minecraft server, no bells and whistles
for (final String cmd : this.cCmdWordSay(null)) {
this.registerCommand(this.cMinecraftTag(), cmd);
}
for (final String cmd : this.cCmdWordPlayers(null)) {
this.registerCommand(this.cMinecraftTag(), cmd);
}
if (!this.cMinecraftTagGroup().equals("")) {
this.groupTag(this.cMinecraftTag(), this.cMinecraftTagGroup());
}
} else {
this.logDerp("No minecraft tag defined in the config file (settings.minecraft-tag)");
}
if ((this.cCancelledTag() != null) && !this.cCancelledTag().equals("")) {
this.registerEndPoint(this.cCancelledTag(), new MinecraftPoint(this, this.getServer())); // Handles cancelled chat
if (!this.cMinecraftTagGroup().equals("")) {
this.groupTag(this.cCancelledTag(), this.cMinecraftTagGroup());
}
}
if ((this.cConsoleTag() != null) && !this.cConsoleTag().equals("")) {
this.registerEndPoint(this.cConsoleTag(), new ConsolePoint(this, this.getServer())); // The minecraft console
for (final String cmd : this.cCmdWordCmd(null)) {
this.registerCommand(this.cConsoleTag(), cmd);
}
if (!this.cMinecraftTagGroup().equals("")) {
this.groupTag(this.cConsoleTag(), this.cMinecraftTagGroup());
}
}
// Create bots
if (this.bots.size() == 0) {
this.logDerp("No bots defined in the 'bots' section of the config file");
}
this.firstChannelTag = null;
this.instances = new ArrayList<>();
for (int i = 0; i < this.bots.size(); i++) {
this.instances.add(new Minebot(this, i, this.cDebug()));
if (this.channodes.get(i).size() == 0) {
this.logDerp("No channels defined for bot '" + this.cBotNickname(i) + "'. Check the config.");
} else if (this.firstChannelTag == null) {
this.firstChannelTag = this.channodes.get(i).get(0).getString("tag");
}
}
this.loadTagGroups();
// Give these default values if they aren't defined
// Ugly but there is no better way with this non-bukkit config
this.configuration.getString("settings.formatting.from-game.players-list", "Online (%playerCount%/%maxPlayers%): %message%");
this.configuration.getString("settings.formatting.from-game.players-nobody", "Nobody is minecrafting right now.");
this.configuration.getString("settings.formatting.from-game.command-reply",
this.configuration.getString("settings.formatting.from-game.generic", "%message%"));
this.configuration.getBoolean("default-attributes.notices.admin", true);
this.configuration.getBoolean("default-attributes.notices.private", true);
if (this.configuration.getBoolean("default-attributes.disable", false)) {
this.logDerp("All communication paths disabled because the 'disable' attribute was found. Check the config.");
} else {
this.log("Enabled.");
}
// Hold timers
this.hold = new HashMap<>();
this.holdTimer = new Timer();
if (this.cHold("chat") > 0) {
this.hold.put(HoldType.CHAT, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.CHAT), this.cHold("chat"));
} else {
this.hold.put(HoldType.CHAT, false);
}
if (this.cHold("joins") > 0) {
this.hold.put(HoldType.JOINS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.JOINS), this.cHold("joins"));
} else {
this.hold.put(HoldType.JOINS, false);
}
if (this.cHold("quits") > 0) {
this.hold.put(HoldType.QUITS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.QUITS), this.cHold("quits"));
} else {
this.hold.put(HoldType.QUITS, false);
}
if (this.cHold("kicks") > 0) {
this.hold.put(HoldType.KICKS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.KICKS), this.cHold("kicks"));
} else {
this.hold.put(HoldType.KICKS, false);
}
if (this.cHold("bans") > 0) {
this.hold.put(HoldType.BANS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.BANS), this.cHold("bans"));
} else {
this.hold.put(HoldType.BANS, false);
}
if (this.cHold("deaths") > 0) {
this.hold.put(HoldType.DEATHS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.DEATHS), this.cHold("deaths"));
} else {
this.hold.put(HoldType.DEATHS, false);
}
if (this.cHold("advancements") > 0) {
this.hold.put(HoldType.ADVANCEMENTS, true);
this.holdTimer.schedule(new RemoveHoldTask(this, HoldType.ADVANCEMENTS), this.cHold("advancements"));
} else {
this.hold.put(HoldType.ADVANCEMENTS, false);
}
if (CraftIRC.this.getServer().getPluginManager().isPluginEnabled("Vault")) {
this.loadVault();
}
this.setDebug(this.cDebug());
} catch (final Exception e) {
e.printStackTrace();
}
try {
new Metrics(this).start();
} catch (final IOException e) {
// Meh.
}
}
private void loadVault() {
RegisteredServiceProvider<Chat> rsp = CraftIRC.this.getServer().getServicesManager().getRegistration(Chat.class);
if (rsp != null) {
this.vault = rsp.getProvider();
}
}
private void autoDisable() {
this.log("Auto-disabling...");
this.getServer().getPluginManager().disablePlugin(this);
}
@Override
public void onDisable() {
try {
this.retryTimer.cancel();
this.holdTimer.cancel();
// Disconnect bots
if (this.bots != null) {
for (int i = 0; i < this.bots.size(); i++) {
this.instances.get(i).disconnect();
this.instances.get(i).dispose();
}
}
this.log("Disabled.");
} catch (final Exception e) {
e.printStackTrace();
}
}
/***************************
* Minecraft command handling
***************************/
@Override
public boolean onCommand(CommandSender sender, Command command, String commandLabel, String[] args) {
final String commandName = command.getName().toLowerCase();
try {
if (commandName.equals("ircsay")) {
return sender.hasPermission("craftirc." + commandName) && this.cmdMsgSay(sender, args);
}
switch (commandName) {
case "ircmsg":
return sender.hasPermission("craftirc." + commandName) && this.cmdMsgToTag(sender, args);
case "ircmsguser":
return sender.hasPermission("craftirc." + commandName) && this.cmdMsgToUser(sender, args);
case "ircusers":
return sender.hasPermission("craftirc." + commandName) && this.cmdGetUserList(sender, args);
case "admins!":
return sender.hasPermission("craftirc.admins") && this.cmdNotifyIrcAdmins(sender, args);
case "ircraw":
return sender.hasPermission("craftirc." + commandName) && this.cmdRawIrcCommand(sender, args);
case "ircreload":
if (!sender.hasPermission("craftirc." + commandName)) {
return false;
}
this.getServer().getPluginManager().disablePlugin(this);
this.getServer().getPluginManager().enablePlugin(this);
return true;
default:
return false;
}
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdMsgSay(CommandSender sender, String[] args) {
if (args.length == 0) {
return false;
}
try {
RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "chat");
if (msg == null) {
return false;
}
String senderName = sender.getName();
String world = "";
String prefix = "";
String suffix = "";
if (sender instanceof Player) {
Player player = (Player) sender;
senderName = player.getDisplayName();
world = player.getWorld().getName();
prefix = this.getPrefix(player);
suffix = this.getSuffix(player);
}
msg.setField("sender", senderName);
msg.setField("message", Util.combineSplit(0, args, " "));
msg.setField("world", world);
msg.setField("realSender", sender.getName());
msg.setField("prefix", prefix);
msg.setField("suffix", suffix);
msg.doNotColor("message");
msg.post();
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdMsgToTag(CommandSender sender, String[] args) {
try {
if (this.isDebug()) {
this.log("CraftIRCListener cmdMsgToAll()");
}
if (args.length < 2) {
return false;
}
final String msgToSend = Util.combineSplit(1, args, " ");
final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "chat");
if (msg == null) {
return true;
}
if (sender instanceof Player) {
msg.setField("sender", ((Player) sender).getDisplayName());
} else {
msg.setField("sender", sender.getName());
}
msg.setField("message", msgToSend);
msg.doNotColor("message");
msg.post();
sender.sendMessage("Message sent.");
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdMsgToUser(CommandSender sender, String[] args) {
try {
if (args.length < 3) {
return false;
}
final String msgToSend = Util.combineSplit(2, args, " ");
final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), this.getEndPoint(args[0]), "private");
if (msg == null) {
return true;
}
if (sender instanceof Player) {
msg.setField("sender", ((Player) sender).getDisplayName());
} else {
msg.setField("sender", sender.getName());
}
msg.setField("message", msgToSend);
msg.doNotColor("message");
boolean sameEndPoint = this.getEndPoint(this.cMinecraftTag()).equals(this.getEndPoint(args[0]));
// Don't actually deliver the message if the user is invisible to the sender.
if (sameEndPoint && sender instanceof Player) {
Player recipient = getServer().getPlayer(args[1]);
if (recipient != null && recipient.isOnline() && ((Player) sender).canSee(recipient))
msg.postToUser(args[1]);
} else
msg.postToUser(args[1]);
sender.sendMessage("Message sent.");
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdGetUserList(CommandSender sender, String[] args) {
try {
final String tag = (args.length == 0) ? this.firstChannelTag : args[0];
final List<String> userlists = this.ircUserLists(tag);
if (userlists == null) {
sender.sendMessage("Unknown tag");
return false;
}
sender.sendMessage("Users in " + tag + " (" + userlists.size() + "):");
StringBuilder builder = new StringBuilder();
boolean first = true;
for (final String string : userlists) {
if (!first) {
builder.append(", ");
}
builder.append(string);
first = false;
}
sender.sendMessage(builder.toString());
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdNotifyIrcAdmins(CommandSender sender, String[] args) {
try {
if (this.isDebug()) {
this.log("CraftIRCListener cmdNotifyIrcAdmins()");
}
if ((args.length == 0) || !(sender instanceof Player)) {
if (this.isDebug()) {
this.log("CraftIRCListener cmdNotifyIrcAdmins() - args.length == 0 or Sender != player ");
}
return false;
}
final RelayedMessage msg = this.newMsg(this.getEndPoint(this.cMinecraftTag()), null, "admin");
if (msg == null) {
return true;
}
msg.setField("sender", ((Player) sender).getDisplayName());
msg.setField("message", Util.combineSplit(0, args, " "));
msg.setField("world", ((Player) sender).getWorld().getName());
msg.doNotColor("message");
msg.post(true);
sender.sendMessage("Admin notice sent.");
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
private boolean cmdRawIrcCommand(CommandSender sender, String[] args) {
try {
if (this.isDebug()) {
this.log("cmdRawIrcCommand(sender=" + sender.toString() + ", args=" + Util.combineSplit(0, args, " "));
}
if (args.length < 2) {
return false;
}
this.sendRawToBot(Util.combineSplit(1, args, " "), Integer.parseInt(args[0]));
return true;
} catch (final Exception e) {
e.printStackTrace();
return false;
}
}
/***************************
* Endpoint and message interface (to be used by CraftIRC and external plugins)
***************************/
/**
* Null target: Sends message through all possible paths.
*
* @param source source endpoint
* @param target target endpoint
* @param eventType type of event
* @return the message to send
*/
public RelayedMessage newMsg(EndPoint source, EndPoint target, String eventType) {
if (source == null) {
return null;
}
if ((target == null) || this.cPathExists(this.getTag(source), this.getTag(target))) {
return new RelayedMessage(this, source, target, eventType);
} else {
if (this.isDebug()) {
this.log("Failed to prepare message: " + this.getTag(source) + " -> " + this.getTag(target) + " (missing path)");
}
return null;
}
}
public RelayedMessage newMsgToTag(EndPoint source, String target, String eventType) {
if (source == null) {
return null;
}
EndPoint targetpoint = null;
if (target != null) {
if (this.cPathExists(this.getTag(source), target)) {
targetpoint = this.getEndPoint(target);
if (targetpoint == null) {
this.log("The requested target tag '" + target + "' isn't registered.");
}
} else {
return null;
}
}
return new RelayedMessage(this, source, targetpoint, eventType);
}
public RelayedCommand newCmd(EndPoint source, String command) {
if (source == null) {
return null;
}
final CommandEndPoint target = this.irccmds.get(command);
if (target == null) {
return null;
}
if (!this.cPathExists(this.getTag(source), this.getTag(target))) {
return null;
}
final RelayedCommand cmd = new RelayedCommand(this, source, target);
cmd.setField("command", command);
return cmd;
}
public boolean registerEndPoint(String tag, EndPoint ep) {
if (!this.isEnabled()) {
this.getLogger().log(Level.WARNING, "CraftIRC EndPoints cannot be registered while CraftIRC is disabled", new Throwable());
return false;
}
if (this.isDebug()) {
this.log("Registering endpoint: " + tag);
}
if (tag == null) {
this.log("Failed to register endpoint - No tag!");
return false;
}
if ((this.endpoints.get(tag) != null) || (this.tags.get(ep) != null)) {
this.log("Couldn't register an endpoint tagged '" + tag + "' because either the tag or the endpoint already exist.");
return false;
}
if (tag.equals("*")) {
this.log("Couldn't register an endpoint - the character * can't be used as a tag.");
return false;
}
this.endpoints.put(tag, ep);
this.tags.put(ep, tag);
return true;
}
public boolean endPointRegistered(String tag) {
return this.endpoints.get(tag) != null;
}
public EndPoint getEndPoint(String tag) {
return this.endpoints.get(tag);
}
public String getTag(EndPoint ep) {
return this.tags.get(ep);
}
public boolean registerCommand(String tag, String command) {
if (this.isDebug()) {
this.log("Registering command: " + command + " to endpoint:" + tag);
}
final EndPoint ep = this.getEndPoint(tag);
if (ep == null) {
this.log("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because there is no such tag.");
return false;
}
if (!(ep instanceof CommandEndPoint)) {
this.log("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because it's not capable of handling commands.");
return false;
}
if (this.irccmds.containsKey(command)) {
this.log("Couldn't register the command '" + command + "' at the endpoint tagged '" + tag + "' because that command is already registered.");
return false;
}
this.irccmds.put(command, (CommandEndPoint) ep);
return true;
}
public boolean unregisterCommand(String command) {
if (!this.irccmds.containsKey(command)) {
return false;
}
if (this.isDebug()) {
this.log("Unregistering command: " + command);
}
this.irccmds.remove(command);
return true;
}
public boolean unregisterEndPoint(String tag) {
final EndPoint ep = this.getEndPoint(tag);
if (ep == null) {
return false;
}
if (this.isDebug()) {
this.log("Unregistering endpoint: " + tag);
}
this.endpoints.remove(tag);
this.tags.remove(ep);
this.ungroupTag(tag);
if (ep instanceof CommandEndPoint) {
final CommandEndPoint cep = (CommandEndPoint) ep;
for (final String cmd : this.irccmds.keySet()) {
if (this.irccmds.get(cmd) == cep) {
this.irccmds.remove(cmd);
}
}
}
return true;
}
public boolean groupTag(String tag, String group) {
if (this.getEndPoint(tag) == null) {
return false;
}
List<String> tags = this.taggroups.get(group);
if (tags == null) {
tags = new ArrayList<>();
this.taggroups.put(group, tags);
}
tags.add(tag);
return true;
}
public void ungroupTag(String tag) {
for (final String group : this.taggroups.keySet()) {
this.taggroups.get(group).remove(tag);
}
}
public void clearGroup(String group) {
this.taggroups.remove(group);
}
public boolean checkTagsGrouped(String tagA, String tagB) {
for (final String group : this.taggroups.keySet()) {
if (this.taggroups.get(group).contains(tagA) && this.taggroups.get(group).contains(tagB)) {
return true;
}
}
return false;
}
/**
* Only successful if all known targets (or if there is none at least one possible target) are successful!
*
* @param msg message to send
* @param knownDestinations destinations
* @param username username
* @param dm method of delivery
* @return true if successful
*/
boolean delivery(RelayedMessage msg, List<EndPoint> knownDestinations, String username, RelayedMessage.DeliveryMethod dm) {
final String sourceTag = this.getTag(msg.getSource());
msg.setField("source", sourceTag);
List<EndPoint> destinations;
if (this.isDebug()) {
this.log("X->" + (knownDestinations.size() > 0 ? knownDestinations.toString() : "*") + ": " + msg.toString());
}
// If we weren't explicitly given a recipient for the message, let's try to find one (or more)
if (knownDestinations.size() < 1) {
// Use all possible destinations (auto-targets)
destinations = new LinkedList<>();
for (final String targetTag : this.cPathsFrom(sourceTag)) {
final EndPoint ep = this.getEndPoint(targetTag);
if (ep == null) {
continue;
}
if ((ep instanceof SecuredEndPoint) && SecuredEndPoint.Security.REQUIRE_TARGET.equals(((SecuredEndPoint) ep).getSecurity())) {
continue;
}
if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) {
continue;
}
if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) {
continue;
}
destinations.add(ep);
}
// Default paths to unsecured destinations (auto-paths)
if (this.cAutoPaths()) {
for (final EndPoint ep : this.endpoints.values()) {
if (ep == null) {
continue;
}
if (msg.getSource().equals(ep) || destinations.contains(ep)) {
continue;
}
if ((ep instanceof SecuredEndPoint) && !SecuredEndPoint.Security.UNSECURED.equals(((SecuredEndPoint) ep).getSecurity())) {
continue;
}
final String targetTag = this.getTag(ep);
if (this.checkTagsGrouped(sourceTag, targetTag)) {
continue;
}
if (!this.cPathAttribute(sourceTag, targetTag, "attributes." + msg.getEvent())) {
continue;
}
if ((dm == RelayedMessage.DeliveryMethod.ADMINS) && !this.cPathAttribute(sourceTag, targetTag, "attributes.admin")) {
continue;
}
if (this.cPathAttribute(sourceTag, targetTag, "disable")) {
continue;
}
destinations.add(ep);
}
}
} else {
destinations = new LinkedList<>(knownDestinations);
}
if (destinations.size() < 1) {
return false;
}
// Deliver the message
boolean success = true;
for (final EndPoint destination : destinations) {
final String targetTag = this.getTag(destination);
if (targetTag.equals(this.cCancelledTag())) {
continue;
}
msg.setField("target", targetTag);
// Whether the event should be sent as a NOTICE on irc endpoints or not (Ignored in others)
msg.setFlag("notice", this.cPathAttribute(sourceTag, targetTag, "notices." + msg.getEvent()));
// Check against path filters
if (this.matchesFilter(msg, this.cPathFilters(sourceTag, targetTag))) {
success = false;
continue;
}
// Finally deliver!
if (this.isDebug()) {
this.log("-->X: " + msg.toString());
}
if (username != null) {
success = success && destination.userMessageIn(username, msg);
} else if (dm == RelayedMessage.DeliveryMethod.ADMINS) {
success = destination.adminMessageIn(msg);
} else if (dm == RelayedMessage.DeliveryMethod.COMMAND) {
if (!(destination instanceof CommandEndPoint)) {
continue;
}
((CommandEndPoint) destination).commandIn((RelayedCommand) msg);
} else {
destination.messageIn(msg);
}
}
return success;
}
private boolean matchesFilter(RelayedMessage msg, List<ConfigurationNode> filters) {
if (filters == null) {
return false;
}
newFilter:
for (final ConfigurationNode filter : filters) {
for (final String key : filter.getKeys()) {
final Pattern condition;
try {
condition = Pattern.compile(filter.getString(key, ""));
} catch (PatternSyntaxException e) {
continue newFilter;
}
final String subject = msg.getField(key);
if (subject == null) {
continue newFilter;
}
final Matcher check = condition.matcher(subject);
if (!check.find()) {
continue newFilter;
}
}
return true;
}
return false;
}
/***************************
* Auxiliary methods
***************************/
public Minebot getBot(int bot) {
return this.instances.get(bot);
}
public int getNumBots() {
return this.instances.size();
}
public void sendRawToBot(String rawMessage, int bot) {
if (this.isDebug()) {
this.log("sendRawToBot(bot=" + bot + ", message=" + rawMessage);
}
final Minebot targetBot = this.instances.get(bot);
targetBot.sendRawLineViaQueue(rawMessage);
}
public void sendMsgToTargetViaBot(String message, String target, int bot) {
final Minebot targetBot = this.instances.get(bot);
targetBot.sendMessage(target, message);
}
public List<String> ircUserLists(String tag) {
final EndPoint endpoint = this.getEndPoint(tag);
if (endpoint != null) {
return endpoint.listDisplayUsers();
} else {
return null;
}
}
private void setDebug(boolean d) {
this.debug = d;
for (int i = 0; i < this.bots.size(); i++) {
this.instances.get(i).setVerbose(d);
}
this.log("DEBUG [" + (d ? "ON" : "OFF") + "]");
}
public String getPrefix(Player p) {
String result = "";
if (this.vault != null) {
try {
result = this.vault.getPlayerPrefix(p);
} catch (final Exception ignored) {
}
}
return result;
}
public String getSuffix(Player p) {
String result = "";
if (this.vault != null) {
try {
result = this.vault.getPlayerSuffix(p);
} catch (final Exception ignored) {
}
}
return result;
}
public boolean isDebug() {
return this.debug;
}
/**
* If the channel is null it's a reconnect, otherwise a rejoin
*
* @param bot bot
* @param channel channel
*/
void scheduleForRetry(Minebot bot, String channel) {
this.retryTimer.schedule(new RetryTask(this, bot, channel), this.cRetryDelay());
}
/***************************
* Read stuff from config
***************************/
private ConfigurationNode getChanNode(int bot, String channel) {
for (final ConfigurationNode chan : this.channodes.get(bot)) {
if (chan.getString("name").equalsIgnoreCase(channel)) {
return chan;
}
}
return Configuration.getEmptyNode();
}
public boolean cLog() {
return this.configuration.getBoolean("settings.log", true);
}
public List<ConfigurationNode> cChannels(int bot) {
return this.channodes.get(bot);
}
private ConfigurationNode getPathNode(String source, String target) {
ConfigurationNode result = this.paths.get(new Path(source, target));
if (result == null) {
return this.configuration.getNode("default-attributes");
}
ConfigurationNode basepath;
if (result.getKeys().contains("base") && ((basepath = result.getNode("base")) != null)) {
final ConfigurationNode basenode = this.paths.get(new Path(basepath.getString("source", ""), basepath.getString("target", "")));
if (basenode != null) {
result = basenode;
}
}
return result;
}
public String cMinecraftTag() {
return this.configuration.getString("settings.minecraft-tag", "minecraft");
}
public String cCancelledTag() {
return this.configuration.getString("settings.cancelled-tag", "cancelled");
}
public String cConsoleTag() {
return this.configuration.getString("settings.console-tag", "console");
}
public String cMinecraftTagGroup() {
return this.configuration.getString("settings.minecraft-group-name", "minecraft");
}
public String cIrcTagGroup() {
return this.configuration.getString("settings.irc-group-name", "irc");
}
public boolean cAutoPaths() {
return this.configuration.getBoolean("settings.auto-paths", false);
}
public boolean cCancelChat() {
return cancelChat;
}
public boolean cDebug() {
return this.configuration.getBoolean("settings.debug", false);
}
public String cStoppedRespondingMessage() {
return this.configuration.getString("settings.stopped-responding-message", "The server appears to have stopped responding.");
}
public ArrayList<String> cConsoleCommands() {
return new ArrayList<>(this.configuration.getStringList("settings.console-commands", null));
}
public int cHold(String eventType) {
return this.configuration.getInt("settings.hold-after-enable." + eventType, 0);
}
public String cFormatting(String eventType, RelayedMessage msg) {
return this.cFormatting(eventType, msg, null);
}
public String cFormatting(String eventType, RelayedMessage msg, EndPoint realTarget) {
final String source = this.getTag(msg.getSource()), target = this.getTag(realTarget != null ? realTarget : msg.getTarget());
if ((source == null) || (target == null)) {