-
Notifications
You must be signed in to change notification settings - Fork 3
/
common.d
4011 lines (3449 loc) · 127 KB
/
common.d
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
/++
+ The is not a plugin by itself but contains code common to all plugins,
+ without which they will *not* function.
+
+ It is mandatory if you plan to use any form of plugin. Indeed, the very
+ definition of an `IRCPlugin` is in here.
+/
module kameloso.plugins.common;
import kameloso.irc.common : IRCClient;
import kameloso.irc.defs;
import core.thread : Fiber;
import std.typecons : Flag, No, Yes;
//version = TwitchWarnings;
version = PrefixedCommandsFallBackToNickname;
//version = ExplainReplay;
// 2.079.0 getSymolsByUDA
/++
+ 2.079.0 has a bug that breaks plugin processing completely. It's fixed in
+ patch .1 (2.079.1), but there's no API for knowing the patch number.
+
+ Infer it by testing for the broken behaviour and warn (during compilation).
+/
private
static if (__VERSION__ == 2079L)
{
import std.traits : getSymbolsByUDA;
struct UDA_2079 {}
struct Foo_2079
{
@UDA_2079
{
int i;
void fun() {}
int n;
}
}
static if (getSymbolsByUDA!(Foo_2079, UDA_2079).length != 3)
{
pragma(msg, "WARNING: You are using a 2.079.0 compiler with a broken " ~
"crucial trait in its standard library. The program will not " ~
"function normally. Please upgrade to 2.079.1.");
}
}
// IRCPlugin
/++
+ Interface that all `IRCPlugin`s must adhere to.
+
+ Plugins may implement it manually, or mix in `IRCPluginImpl`.
+
+ This is currently shared with all `service`-class "plugins".
+/
interface IRCPlugin
{
@safe:
/++
+ Returns a reference to the current `IRCPluginState` of the plugin.
+
+ Returns:
+ Reference to an `IRCPluginState`.
+/
ref inout(IRCPluginState) state() inout pure nothrow @nogc @property;
/// Executed to let plugins modify an event mid-parse.
void postprocess(ref IRCEvent) @system;
/// Executed upon new IRC event parsed from the server.
void onEvent(const IRCEvent) @system;
/// Executed when the plugin is requested to initialise its disk resources.
void initResources() @system;
/// Executed during setup to let plugins read settings from disk.
string[][string] deserialiseConfigFrom(const string);
/// Executed when gathering things to put in the configuration file.
import std.array : Appender;
void serialiseConfigInto(ref Appender!string) const;
/++
+ Executed during start if we want to change a setting by its string name.
+
+ Returns:
+ Boolean of whether the set succeeded or not.
+/
bool setSettingByName(const string, const string);
/// Executed when connection has been established.
void start() @system;
/// Executed when we want a plugin to print its Settings struct.
void printSettings() @system const;
/// Executed during shutdown or plugin restart.
void teardown() @system;
/++
+ Returns the name of the plugin, sliced off the module name.
+
+ Returns:
+ The string name of the plugin.
+/
string name() @property const;
/++
+ Returns an array of the descriptions of the commands a plugin offers.
+
+ Returns:
+ An associative `Description[string]` array.
+/
Description[string] commands() pure nothrow @property const;
/++
+ Call a plugin to perform its periodic tasks, iff the time is equal to or
+ exceeding `nextPeriodical`.
+/
void periodically(const long) @system;
/// Reloads the plugin, where such is applicable.
void reload() @system;
/// Executed when a bus message arrives from another plugin.
import kameloso.thread : Sendable;
void onBusMessage(const string, shared Sendable content) @system;
/// Returns whether or not the plugin is enabled in its configuration section.
bool isEnabled() const @property pure nothrow @nogc;
/// Returns the UNIX timestamp of when the next timed `core.thread.Fiber` should be triggered.
long nextFiberTimestamp() const @property pure nothrow @nogc;
/// Updates the saved UNIX timestamp of when the next timed `core.thread.Fiber` should be triggered.
void updateNextFiberTimestamp() pure nothrow @nogc;
}
// TriggerRequest
/++
+ A queued event to be replayed upon a `WHOIS` request response.
+
+ It is abstract; all objects must be of a concrete `TriggerRequestImpl` type.
+/
abstract class TriggerRequest
{
/// Stored `kameloso.irc.defs.IRCEvent` to replay.
IRCEvent event;
/// `PrivilegeLevel` of the function to replay.
PrivilegeLevel privilegeLevel;
/// When this request was issued.
long when;
/// Replay the stored event.
void trigger();
/// Creates a new `TriggerRequest` with a timestamp of the current time.
this() @safe
{
import std.datetime.systime : Clock;
when = Clock.currTime.toUnixTime;
}
}
// TriggerRequestImpl
/++
+ Implementation of a queued `WHOIS` request call.
+
+ It functions like a Command pattern object in that it stores a payload and
+ a function pointer, which we queue and do a `WHOIS` call. When the response
+ returns we trigger the object and the original `kameloso.irc.defs.IRCEvent`
+ is replayed.
+
+ Params:
+ F = Some function type.
+ Payload = Optional payload type.
+/
final class TriggerRequestImpl(F, Payload = typeof(null)) : TriggerRequest
{
@safe:
/// Stored function pointer/delegate.
F fn;
static if (!is(Payload == typeof(null)))
{
/// Command payload aside from the `kameloso.irc.defs.IRCEvent`.
Payload payload;
/++
+ Create a new `TriggerRequestImpl` with the passed variables.
+
+ Params:
+ payload = Payload of templated type `Payload` to attach to this
+ `TriggerRequestImpl`.
+ event = `kameloso.irc.defs.IRCEvent` to attach to this
+ `TriggerRequestImpl`.
+ privilegeLevel = The privilege level required to trigger the
+ passed function.
+ fn = Function pointer to call with the attached payloads when
+ the request is triggered.
+/
this(Payload payload, IRCEvent event, PrivilegeLevel privilegeLevel, F fn)
{
super();
this.payload = payload;
this.event = event;
this.privilegeLevel = privilegeLevel;
this.fn = fn;
}
}
else
{
/++
+ Create a new `TriggerRequestImpl` with the passed variables.
+
+ Params:
+ payload = Payload of templated type `Payload` to attach to this
+ `TriggerRequestImpl`.
+ fn = Function pointer to call with the attached payloads when
+ the request is triggered.
+/
this(IRCEvent event, PrivilegeLevel privilegeLevel, F fn)
{
super();
this.event = event;
this.privilegeLevel = privilegeLevel;
this.fn = fn;
}
}
/++
+ Call the passed function/delegate pointer, optionally with the stored
+ `kameloso.irc.defs.IRCEvent` and/or `Payload`.
+/
override void trigger() @system
{
import std.meta : AliasSeq, staticMap;
import std.traits : Parameters, Unqual, arity;
assert((fn !is null), "null fn in TriggerRequestImpl!" ~ F.stringof);
alias Params = staticMap!(Unqual, Parameters!fn);
static if (is(Params : AliasSeq!IRCEvent))
{
fn(event);
}
else static if (is(Params : AliasSeq!(Payload, IRCEvent)))
{
fn(payload, event);
}
else static if (is(Params : AliasSeq!Payload))
{
fn(payload);
}
else static if (arity!fn == 0)
{
fn();
}
else
{
static assert(0, "Unknown function signature in TriggerRequestImpl: " ~ typeof(fn).stringof);
}
}
}
unittest
{
TriggerRequest[] queue;
IRCEvent event;
event.target.nickname = "kameloso";
event.content = "hirrpp";
event.sender.nickname = "zorael";
PrivilegeLevel pl = PrivilegeLevel.admin;
// delegate()
int i = 5;
void dg()
{
++i;
}
TriggerRequest reqdg = new TriggerRequestImpl!(void delegate())(event, pl, &dg);
queue ~= reqdg;
with (reqdg.event)
{
assert((target.nickname == "kameloso"), target.nickname);
assert((content == "hirrpp"), content);
assert((sender.nickname == "zorael"), sender.nickname);
}
assert(i == 5);
reqdg.trigger();
assert(i == 6);
// function()
static void fn() { }
auto reqfn = triggerRequest(event, pl, &fn);
queue ~= reqfn;
// delegate(ref IRCEvent)
void dg2(ref IRCEvent thisEvent)
{
thisEvent.content = "blah";
}
auto reqdg2 = triggerRequest(event, pl, &dg2);
queue ~= reqdg2;
assert((reqdg2.event.content == "hirrpp"), event.content);
reqdg2.trigger();
assert((reqdg2.event.content == "blah"), event.content);
// function(IRCEvent)
static void fn2(IRCEvent thisEvent) { }
auto reqfn2 = triggerRequest(event, pl, &fn2);
queue ~= reqfn2;
}
// triggerRequest
/++
+ Convenience function that returns a `TriggerRequestImpl` of the right type,
+ *with* a payload attached.
+
+ Params:
+ payload = Payload to attach to the `TriggerRequest`.
+ event = `kameloso.irc.defs.IRCEvent` that instigated the `WHOIS` lookup.
+ privilegeLevel = The privilege level policy to apply to the `WHOIS` results.
+ fn = Function/delegate pointer to call upon receiving the results.
+
+ Returns:
+ A `TriggerRequest` with template parameters inferred from the arguments
+ passed to this function.
+/
TriggerRequest triggerRequest(F, Payload)(Payload payload, IRCEvent event,
PrivilegeLevel privilegeLevel, F fn) @safe
{
return new TriggerRequestImpl!(F, Payload)(payload, event, privilegeLevel, fn);
}
// triggerRequest
/++
+ Convenience function that returns a `TriggerRequestImpl` of the right type,
+ *without* a payload attached.
+
+ Params:
+ event = `kameloso.irc.defs.IRCEvent` that instigated the `WHOIS` lookup.
+ privilegeLevel = The privilege level policy to apply to the `WHOIS` results.
+ fn = Function/delegate pointer to call upon receiving the results.
+
+ Returns:
+ A `TriggerRequest` with template parameters inferred from the arguments
+ passed to this function.
+/
TriggerRequest triggerRequest(F)(IRCEvent event, PrivilegeLevel privilegeLevel, F fn) @safe
{
return new TriggerRequestImpl!F(event, privilegeLevel, fn);
}
// IRCPluginState
/++
+ An aggregate of all variables that make up the common state of plugins.
+
+ This neatly tidies up the amount of top-level variables in each plugin
+ module. This allows for making more or less all functions top-level
+ functions, since any state could be passed to it with variables of this type.
+
+ Plugin-specific state should be kept inside the `IRCPlugin` itself.
+/
struct IRCPluginState
{
import kameloso.common : Labeled;
import core.thread : Fiber;
import std.concurrency : Tid;
/++
+ The current `kameloso.irc.common.IRCClient`, containing information pertaining
+ to the bot in the context of the current (alive) connection.
+/
IRCClient client;
/// Thread ID to the main thread.
Tid mainThread;
/// Hashmap of IRC user details.
IRCUser[string] users;
/// Hashmap of IRC channels.
IRCChannel[string] channels;
/++
+ Queued `WHOIS` requests and pertaining `kameloso.irc.defs.IRCEvent`s to
+ replay.
+
+ The main loop iterates this after processing all on-event functions so
+ as to know what nicks the plugin wants a `WHOIS` for. After the `WHOIS`
+ response returns, the event bundled with the `TriggerRequest` will be replayed.
+/
TriggerRequest[][string] triggerRequestQueue;
/++
+ The list of awaiting `core.thread.Fiber`s, keyed by
+ `kameloso.irc.defs.IRCEvent.Type`.
+/
Fiber[][IRCEvent.Type] awaitingFibers;
/// The list of timed `core.thread.Fiber`s, labeled by UNIX time.
Labeled!(Fiber, long)[] timedFibers;
/// The next (Unix time) timestamp at which to call `periodically`.
long nextPeriodical;
}
/++
+ The tristate results from comparing a username with the admin or whitelist lists.
+/
enum FilterResult
{
fail, /// The user is not allowed to trigger this function.
pass, /// The user is allowed to trigger this function.
/++
+ We don't know enough to say whether the user is allowed to trigger this
+ function, so do a WHOIS query and act based on the results.
+/
whois,
}
/++
+ To what extent the annotated function demands its triggering
+ `kameloso.irc.defs.IRCEvent`'s contents be prefixed with the bot's nickname.
+/
enum PrefixPolicy
{
direct, /// Message will be treated as-is without looking for prefixes.
prefixed, /// Message should begin with `kameloso.common.CoreSettings.prefix` (e.g. "`!`")
nickname, /// Message should begin with the bot's name, except in `QUERY` events.
}
/// Whether an annotated function should work in all channels or just in homes.
enum ChannelPolicy
{
/++
+ The annotated function will only trigger if the event happened in a
+ home, where applicable (not all events have channels).
+/
home,
/// The annotated function will trigger regardless of channel.
any,
}
/// What level of privilege is needed to trigger an event.
enum PrivilegeLevel
{
ignore = 0, /// Override privilege checks.
anyone = 1, /// Anyone may trigger this event.
registered = 2, /// Anyone registered with services may trigger this event.
whitelist = 3, /// Only those of the `whitelist` class may trigger this event.
admin = 4, /// Only the administrators may trigger this event.
}
// BotCommand
/++
+ Defines an IRC bot command, for people to trigger with messages.
+
+ If no `PrefixPolicy` is specified then it will default to `PrefixPolicy.prefixed`
+ and look for `kameloso.common.CoreSettings.prefix` at the beginning of
+ messages, to prefix the `string_`. (Usually "`!`", making it "`!command`".)
+/
struct BotCommand
{
/// The policy to which extent the command needs the bot's nickname.
PrefixPolicy policy;
/// The prefix string, one word with no spaces.
string string_;
/++
+ Create a new `BotCommand` with the passed `policy` and trigger `string_`.
+/
this(const PrefixPolicy policy, const string string_) pure
{
this.policy = policy;
this.string_ = string_;
}
/++
+ Create a new `BotCommand` with a default `prefixed` policy and the passed
+ trigger `string_`.
+/
this(const string string_) pure
{
this.policy = PrefixPolicy.prefixed;
this.string_ = string_;
}
}
// BotRegex
/++
+ Defines an IRC bot regular expression, for people to trigger with messages.
+
+ If no `PrefixPolicy` is specified then it will default to `PrefixPolicy.prefixed`
+ and look for `kameloso.common.CoreSettings.prefix` at the beginning of
+ messages, to prefix the `string_`. (Usually "`!`", making it "`!command`".)
+/
struct BotRegex
{
import std.regex : Regex, regex;
/// The policy to which extent the command needs the bot's nickname.
PrefixPolicy policy;
/++
+ Regex engine to match incoming messages with.
+
+ May be compile-time `ctRegex` or normal `Regex`.
+/
Regex!char engine;
/// The regular expression in string form.
string expression;
/// Creates a new `BotRegex` with the passed `policy` and regex `engine`.
this(const PrefixPolicy policy, Regex!char engine) pure
{
this.policy = policy;
this.engine = engine;
}
/++
+ Creates a new `BotRegex` with the passed `policy` and regex `expression` string.
+/
this(const PrefixPolicy policy, const string expression)
{
this.policy = policy;
this.engine = expression.regex;
this.expression = expression;
}
/// Creates a new `BotRegex` with the passed regex `engine`.
this(Regex!char engine) pure
{
this.policy = PrefixPolicy.prefixed;
this.engine = engine;
}
/// Creates a new `BotRegex` with the passed regex `expression` string.
this(const string expression)
{
this.policy = PrefixPolicy.prefixed;
this.engine = expression.regex;
this.expression = expression;
}
}
/++
+ Annotation denoting that an event-handling function let other functions in
+ the same module process after it.
+/
struct Chainable;
/++
+ Annotation denoting that an event-handling function is the end of a chain,
+ letting no other functions in the same module be triggered after it has been.
+
+ This is not strictly necessary since anything non-`Chainable` is implicitly
+ `Terminating`, but we add it to silence warnings and in hopes of the code
+ becoming more self-documenting.
+/
struct Terminating;
/++
+ Annotation denoting that we want verbose debug output of the plumbing when
+ handling events, iterating through the module's event handler functions.
+/
struct Verbose;
/++
+ Annotation denoting that a function is part of an awareness mixin, and at
+ what point it should be processed.
+/
enum Awareness
{
setup,
early,
late,
cleanup,
}
/++
+ Annotation denoting that a variable is to be as considered as settings for a
+ plugin and thus should be serialised and saved in the configuration file.
+/
struct Settings;
// Description
/++
+ Describes an `kameloso.irc.defs.IRCEvent`-annotated handler function.
+
+ This is used to describe functions triggered by `BotCommand`s, in the help
+ listing routine in `kameloso.plugins.chatbot`.
+/
struct Description
{
/// Description string.
string string_;
/// Command usage syntax help string.
string syntax;
/// Creates a new `Description` with the passed `string_` description text.
this(const string string_, const string syntax = string.init)
{
this.string_ = string_;
this.syntax = syntax;
}
}
/++
+ Annotation denoting that a variable is the basename of a *resource* file or directory.
+/
struct Resource;
/++
+ Annotation denoting that a variable is the basename of a *configuration*
+ file or directory.
+/
struct Configuration;
/++
+ Annotation denoting that a variable enables and disables a plugin.
+/
struct Enabler;
// filterUser
/++
+ Decides if a nickname is known good (whitelisted/admin), known bad (not
+ whitelisted/admin), or needs `WHOIS` (to tell if whitelisted/admin).
+
+ This is used to tell whether or not a user is allowed to use the bot's services.
+ If the user is not in the in-memory user array, return `FilterResult.whois`.
+ If the user's NickServ account is in the whitelist (or equals one of the
+ bot's admins'), return `FilterResult.pass`. Else, return `FilterResult.fail`
+ and deny use.
+
+ Params:
+ event = `kameloso.irc.defs.IRCEvent` to filter.
+ level = The `PrivilegeLevel` context in which this user should be filtered.
+
+ Returns:
+ A `FilterResult` saying the event should `pass`, `fail`, or that more
+ information about the sender is needed via a `WHOIS` call.
+/
FilterResult filterUser(const IRCEvent event, const PrivilegeLevel level) @safe
{
import kameloso.constants : Timeout;
import std.datetime.systime : Clock, SysTime;
immutable isBlacklisted = (event.sender.class_ == IRCUser.Class.blacklist);
if (isBlacklisted) return FilterResult.fail;
immutable user = event.sender;
immutable now = Clock.currTime.toUnixTime;
immutable timediff = (now - user.lastWhois);
immutable whoisExpired = (timediff > Timeout.whoisRetry);
if (user.account.length)
{
immutable isAdmin = (user.class_ == IRCUser.Class.admin); // Trust in persistence.d
immutable isWhitelisted = (user.class_ == IRCUser.Class.whitelist);
immutable isAnyone = (user.class_ == IRCUser.Class.anyone);
//immutable isSpecial = (user.class_ == IRCUser.Class.special);
if (isAdmin && (level <= PrivilegeLevel.admin))
{
return FilterResult.pass;
}
else if (isWhitelisted && (level <= PrivilegeLevel.whitelist))
{
return FilterResult.pass;
}
else if (level == PrivilegeLevel.registered)
{
return FilterResult.pass;
}
else if (isAnyone && (level == PrivilegeLevel.anyone))
{
return whoisExpired ? FilterResult.whois : FilterResult.pass;
}
else if (level == PrivilegeLevel.ignore)
{
return FilterResult.pass;
}
else
{
return FilterResult.fail;
}
}
else
{
with (PrivilegeLevel)
final switch (level)
{
case admin:
case whitelist:
case registered:
// Unknown sender; WHOIS if old result expired, otherwise fail
return whoisExpired ? FilterResult.whois : FilterResult.fail;
case anyone:
// Unknown sender; WHOIS if old result expired in mere curiosity, else just pass
return whoisExpired ? FilterResult.whois : FilterResult.pass;
case ignore:
return FilterResult.pass;
}
}
}
///
unittest
{
import kameloso.conv : Enum;
import std.datetime.systime : Clock;
IRCEvent event;
PrivilegeLevel level = PrivilegeLevel.admin;
event.type = IRCEvent.Type.CHAN;
event.sender.nickname = "zorael";
immutable res1 = filterUser(event, level);
assert((res1 == FilterResult.whois), Enum!FilterResult.toString(res1));
event.sender.class_ = IRCUser.Class.admin;
event.sender.account = "zorael";
immutable res2 = filterUser(event, level);
assert((res2 == FilterResult.pass), Enum!FilterResult.toString(res2));
event.sender.class_ = IRCUser.Class.whitelist;
immutable res3 = filterUser(event, level);
assert((res3 == FilterResult.fail), Enum!FilterResult.toString(res3));
event.sender.class_ = IRCUser.Class.anyone;
event.sender.lastWhois = Clock.currTime.toUnixTime;
immutable res4 = filterUser(event, level);
assert((res4 == FilterResult.fail), Enum!FilterResult.toString(res4));
event.sender.class_ = IRCUser.Class.blacklist;
event.sender.lastWhois = long.init;
immutable res5 = filterUser(event, level);
assert((res5 == FilterResult.fail), Enum!FilterResult.toString(res5));
}
// IRCPluginImpl
/++
+ Mixin that fully implements an `IRCPlugin`.
+
+ Uses compile-time introspection to call top-level functions to extend behaviour;
+/
version(WithPlugins)
mixin template IRCPluginImpl(bool debug_ = false, string module_ = __MODULE__)
{
private import core.thread : Fiber;
private enum hasIRCPluginImpl = true;
@safe:
/// This plugin's `IRCPluginState` structure. Has to be public for some things to work.
public IRCPluginState privateState;
/// The timestamp of when the next timed Fiber should be triggered.
private long privateNextFiberTimestamp;
/++
+ Introspects the current plugin, looking for a `Settings`-annotated struct
+ member that has a bool annotated with `Enabler`, which denotes it as the
+ bool that toggles a plugin on and off.
+
+ It then returns its value.
+
+ Returns:
+ `true` if the plugin is deemed enabled (or cannot be disabled),
+ `false` if not.
+/
public bool isEnabled() const @property pure nothrow @nogc
{
import std.traits : Unqual, getSymbolsByUDA, hasUDA;
bool retval = true;
static if (getSymbolsByUDA!(typeof(this), Settings).length)
{
top:
foreach (immutable i, immutable member; this.tupleof)
{
static if (hasUDA!(this.tupleof[i], Settings))
{
static if (getSymbolsByUDA!(typeof(this.tupleof[i]), Enabler).length)
{
foreach (immutable n, immutable submember; this.tupleof[i].tupleof)
{
static if (hasUDA!(this.tupleof[i].tupleof[n], Enabler))
{
static assert(is(typeof(this.tupleof[i].tupleof[n]) : bool),
Unqual!(typeof(this)).stringof ~ " has a non-bool Enabler");
retval = submember;
break top;
}
}
}
}
}
}
return retval;
}
// allowImpl
/++
+ Judges whether an event may be triggered, based on the event itself and
+ the annotated `PrivilegeLevel` of the handler in question.
+
+ Pass the passed arguments to `filterUser`, doing nothing otherwise.
+
+ Sadly we can't keep an `allow` around to override since calling it from
+ inside the same mixin always seems to resolve the original. So instead,
+ only have `allowImpl` and use introspection to determine whether to call
+ that or any custom-defined `allow` in `typeof(this)`.
+
+ Params:
+ event = `kameloso.irc.defs.IRCEvent` to allow, or not.
+ privilegeLevel = `PrivilegeLevel` of the handler in question.
+
+ Returns:
+ `true` if the event should be allowed to trigger, `false` if not.
+/
private FilterResult allowImpl(const IRCEvent event, const PrivilegeLevel privilegeLevel)
{
version(TwitchSupport)
{
if (privateState.client.server.daemon == IRCServer.Daemon.twitch)
{
if (privilegeLevel == PrivilegeLevel.anyone)
{
// We can't WHOIS on Twitch, and PrivilegeLevel.anyone is just
// PrivilegeLevel.ignore with an extra WHOIS for good measure.
return FilterResult.pass;
}
}
}
return filterUser(event, privilegeLevel);
}
// onEvent
/++
+ Pass on the supplied `kameloso.irc.defs.IRCEvent` to `onEventImpl`.
+
+ This is made a separate function to allow plugins to override it and
+ insert their own code, while still leveraging `onEventImpl` for the
+ actual dirty work.
+
+ Params:
+ event = Parse `kameloso.irc.defs.IRCEvent` to pass onto `onEventImpl`.
+
+ See_Also:
+ onEventImpl
+/
public void onEvent(const IRCEvent event) @system
{
return onEventImpl(event);
}
// onEventImpl
/++
+ Pass on the supplied `kameloso.irc.defs.IRCEvent` to functions annotated
+ with the right `kameloso.irc.defs.IRCEvent.Type`s.
+
+ It also does checks for `ChannelPolicy`, `PrivilegeLevel` and
+ `PrefixPolicy` where such is appropriate.
+
+ Params:
+ event = Parsed `kameloso.irc.defs.IRCEvent` to dispatch to event handlers.
+/
private void onEventImpl(const IRCEvent event) @system
{
mixin("static import thisModule = " ~ module_ ~ ";");
import kameloso.string : contains, nom;
import std.meta : Filter, templateNot, templateOr;
import std.traits : getSymbolsByUDA, isSomeFunction, getUDAs, hasUDA;
if (!isEnabled) return;
alias setupAwareness(alias T) = hasUDA!(T, Awareness.setup);
alias earlyAwareness(alias T) = hasUDA!(T, Awareness.early);
alias lateAwareness(alias T) = hasUDA!(T, Awareness.late);
alias cleanupAwareness(alias T) = hasUDA!(T, Awareness.cleanup);
alias isAwarenessFunction = templateOr!(setupAwareness, earlyAwareness,
lateAwareness, cleanupAwareness);
alias isNormalPluginFunction = templateNot!isAwarenessFunction;
alias funs = Filter!(isSomeFunction, getSymbolsByUDA!(thisModule, IRCEvent.Type));
enum Next
{
continue_,
repeat,
return_,
}
Next handle(alias fun)(const IRCEvent event)
{
enum verbose = hasUDA!(fun, Verbose) || debug_;
static if (verbose)
{
import kameloso.conv : Enum;
import std.stdio : stdout, writeln, writefln;
}
enum name = ()
{
import kameloso.conv : Enum;
import std.format : format;
string pluginName = module_; // mutable
while (pluginName.contains('.'))
{
pluginName.nom('.');
}
return "[%s] %s".format(pluginName, __traits(identifier, fun));
}();
udaloop:
foreach (immutable eventTypeUDA; getUDAs!(fun, IRCEvent.Type))
{
static if (eventTypeUDA == IRCEvent.Type.ANY)
{
// UDA is `ANY`, let pass
}
else static if (eventTypeUDA == IRCEvent.Type.PRIVMSG)
{
static assert(0, module_ ~ '.' ~ __traits(identifier, fun) ~
" is annotated IRCEvent.Type.PRIVMSG, which is not a valid event type. " ~
"Use CHAN or QUERY (or both) instead");
}