-
Notifications
You must be signed in to change notification settings - Fork 16
/
SpadsPluginApi.pm
2483 lines (1765 loc) · 91.8 KB
/
SpadsPluginApi.pm
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
# SpadsPluginApi: SPADS plugin API
#
# Copyright (C) 2013-2024 Yann Riou <yaribzh@gmail.com>
#
# 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 SpadsPluginApi;
use File::Spec::Functions qw'catdir';
use List::Util qw'any none';
use Exporter 'import';
@EXPORT=qw/$spadsVersion $spadsDir loadPythonPlugin get_flag fix_string getBosses getLobbyState getSpringPid getSpringServerType getTimestamps getUserPref getRunningBattle getConfMacros getCurrentVote getPlugin getPluginList addSpadsCommandHandler removeSpadsCommandHandler addLobbyCommandHandler removeLobbyCommandHandler addSpringCommandHandler removeSpringCommandHandler forkProcess forkCall removeProcessCallback createDetachedProcess addTimer removeTimer addSocket removeSocket getLobbyInterface getSpringInterface getSpadsConf getSpadsConfFull getPluginConf slog updateSetting secToTime secToDayAge formatList formatArray formatFloat formatInteger getDirModifTime applyPreset quit cancelQuit closeBattle rehost cancelCloseBattle getUserAccessLevel broadcastMsg sayBattleAndGame sayPrivate sayBattle sayBattleUser sayChan sayGame answer invalidSyntax queueLobbyCommand loadArchives LOBBY_STATE_DISCONNECTED LOBBY_STATE_CONNECTING LOBBY_STATE_CONNECTED LOBBY_STATE_LOGGED_IN LOBBY_STATE_SYNCHRONIZED LOBBY_STATE_OPENING_BATTLE LOBBY_STATE_BATTLE_OPENED/;
my $apiVersion='0.40';
our $spadsVersion=$::SPADS_VERSION;
our $spadsDir=$::CWD;
*LOBBY_STATE_DISCONNECTED=\&::LOBBY_STATE_DISCONNECTED;
*LOBBY_STATE_CONNECTING=\&::LOBBY_STATE_CONNECTING;
*LOBBY_STATE_CONNECTED=\&::LOBBY_STATE_CONNECTED;
*LOBBY_STATE_LOGGED_IN=\&::LOBBY_STATE_LOGGED_IN;
*LOBBY_STATE_SYNCHRONIZED=\&::LOBBY_STATE_SYNCHRONIZED;
*LOBBY_STATE_OPENING_BATTLE=\&::LOBBY_STATE_OPENING_BATTLE;
*LOBBY_STATE_BATTLE_OPENED=\&::LOBBY_STATE_BATTLE_OPENED;
sub getVersion {
return $apiVersion;
}
sub hasEvalError {
if($@) {
chomp($@);
return 1;
}else{
return 0;
}
}
*getCallerPlugin=\&SimpleEvent::getOriginPackage;
################################
# Python plugins specific
################################
my $pythonReloadPrefix;
my $inlinePythonUseByteString;
sub initPythonInterpreter {
my $spadsConf=shift;
my $inlinePythonTmpDir=catdir($spadsConf->{conf}{instanceDir},'.InlinePython.tmp');
if(! -d $inlinePythonTmpDir && ! mkdir($inlinePythonTmpDir)) {
$spadsConf->{log}->log("Unable to create temporary directory \"$inlinePythonTmpDir\" for Inline::Python used by plugin ".getCallerPlugin().": $!",1);
return 0;
}
my ($escapedPluginsDir,$escapedInlinePythonTmpDir)=map {quotemeta($_)} ($spadsConf->{conf}{pluginsDir},$inlinePythonTmpDir);
my $pythonBootstrap=<<"PYTHON_BOOTSTRAP_END";
import sys,signal,perl
sys.path.append(r'$escapedPluginsDir')
signal.signal(signal.SIGINT,signal.SIG_DFL)
PYTHON_BOOTSTRAP_END
eval "use Inline Python => \"$pythonBootstrap\", directory => \"$escapedInlinePythonTmpDir\"";
if(hasEvalError()) {
$spadsConf->{log}->log('Unable to initialize Python environement for plugin '.getCallerPlugin().": $@",1);
return 0;
}
$pythonApiFlags{can_fork}=$^O eq 'MSWin32' ? $Inline::Python::Boolean::false : $Inline::Python::Boolean::true;
$pythonApiFlags{can_add_socket}=$^O eq 'MSWin32' ? $Inline::Python::Boolean::false : $Inline::Python::Boolean::true;
$inlinePythonUseByteString=Inline::Python::py_eval('hasattr(perl.eval("$0"),"decode")',0)?$Inline::Python::Boolean::true:$Inline::Python::Boolean::false;
$spadsConf->{log}->log('The version of Inline::Python currently in use converts Perl strings to Python byte strings',2) if($inlinePythonUseByteString);
my $r_pythonVersion=Inline::Python::py_eval('[sys.version_info[i] for i in range(0,3)]',0);
if(! defined $r_pythonVersion->[0] || ! defined $r_pythonVersion->[1]) {
$spadsConf->{log}->log('Unable to initialize Python environement for plugin '.getCallerPlugin().': failed to determine Python version',1);
return 0;
}
if($r_pythonVersion->[0] > 2) {
$pythonReloadPrefix=$r_pythonVersion->[1]>3?'importlib':'imp';
Inline::Python::py_eval("import $pythonReloadPrefix");
$pythonReloadPrefix.='.';
}else{
$pythonReloadPrefix='';
}
my $pythonGetAttrSub=sub { my ($s,$a)=@_; return $s->{$a}; };
${SpadsConf::}{__getattr__}=$pythonGetAttrSub;
${SpringAutoHostInterface::}{__getattr__}=$pythonGetAttrSub;
${SpringLobbyInterface::}{__getattr__}=$pythonGetAttrSub;
$spadsConf->{log}->log('Initialized Python interpreter v'.join('.',@{$r_pythonVersion}[0,1,2]),3);
return 1;
}
sub loadPythonPlugin {
my $spadsConf=shift;
return 0 unless(defined($pythonReloadPrefix) || initPythonInterpreter($spadsConf));
my $pluginName=getCallerPlugin();
my $pythonModule=lc($pluginName);
my $pythonLoadModule=<<"PYTHON_LOADMODULE_END";
if '$pythonModule' in dir():
for attr in dir($pythonModule):
if attr not in ('__name__', '__file__'):
delattr($pythonModule, attr)
$pythonModule = ${pythonReloadPrefix}reload($pythonModule)
else:
import $pythonModule
PYTHON_LOADMODULE_END
my $escapedInlinePythonTmpDir=quotemeta(catdir($spadsConf->{conf}{instanceDir},'.InlinePython.tmp'));
eval "use Inline Python => \"$pythonLoadModule\", directory => \"$escapedInlinePythonTmpDir\", force_build => 1";
if(hasEvalError()) {
$spadsConf->{log}->log("Unable to load Python module for plugin $pluginName: $@",1);
return 0;
}
my %pythonModuleNamespace = Inline::Python::py_study_package($pythonModule);
if(! exists $pythonModuleNamespace{classes}{$pluginName}) {
$spadsConf->{log}->log("Unable to load Python module for plugin $pluginName: Python class \"$pluginName\" not found",1);
return 0;
}
foreach my $function (@{$pythonModuleNamespace{functions}}) {
next unless(any {$function eq $_} (qw'getVersion getRequiredSpadsVersion getParams getDependencies'));
Inline::Python::py_bind_func("${pluginName}::$function",$pythonModule,$function);
}
Inline::Python::py_bind_class($pluginName,$pythonModule,$pluginName,@{$pythonModuleNamespace{classes}{$pluginName}});
return 1;
}
sub get_flag {
my $flag=shift;
if($flag eq 'can_fork' || $flag eq 'can_add_socket') {
return $^O eq 'MSWin32' ? $Inline::Python::Boolean::false : $Inline::Python::Boolean::true;
}elsif($flag eq 'use_byte_string') {
return $inlinePythonUseByteString ? $Inline::Python::Boolean::true : $Inline::Python::Boolean::false;
}else{
::slog("SpadsPluginApi::get_flag() called with unknown flag: $flag",2);
return undef;
}
}
sub fix_string { map {utf8::upgrade($_)} @_; return @_ }
################################
# Accessors
################################
sub getBosses {
return \%::bosses;
}
sub getConfMacros {
return \%::confMacros;
}
sub getCurrentVote {
return \%::currentVote;
}
sub getLobbyInterface {
return $::lobby;
}
sub getLobbyState {
return $::lobbyState;
}
sub getRunningBattle {
return $::p_runningBattle;
}
sub getSpadsConf {
return \%::conf;
}
sub getSpadsConfFull {
return $::spads;
}
sub getSpringInterface {
return $::autohost;
}
sub getSpringPid {
return $::springPid;
}
sub getSpringServerType {
return $::springServerType;
}
sub getTimestamps {
return \%::timestamps;
}
sub getUserPref { ::getUserPref(@_) }
################################
# Plugin management
################################
sub getPlugin {
my $pluginName=shift;
$pluginName=getCallerPlugin() unless(defined $pluginName);
return $::plugins{$pluginName};
}
sub getPluginConf {
my $plugin=shift;
$plugin=getCallerPlugin() unless(defined $plugin);
return $::spads->{pluginsConf}->{$plugin}->{conf} if(exists $::spads->{pluginsConf}->{$plugin});
}
sub getPluginList {
return \@::pluginsOrder;
}
################################
# Handlers management
################################
sub addLobbyCommandHandler {
my ($p_handlers,$priority,$isPreCallback)=@_;
my $plugin=getCallerPlugin();
map {$_=SimpleEvent::encapsulateCallback($_,$plugin) unless(ref $_ eq 'CODE')} (values %{$p_handlers});
$priority//=$plugin;
if($isPreCallback) {
$::lobby->addPreCallbacks($p_handlers,$priority);
}else{
$::lobby->addCallbacks($p_handlers,0,$priority);
}
}
sub addSpadsCommandHandler {
my ($p_handlers,$replace)=@_;
my $plugin=getCallerPlugin();
map {$_=SimpleEvent::encapsulateCallback($_,$plugin) unless(ref $_ eq 'CODE')} (values %{$p_handlers});
$replace=0 unless(defined $replace);
foreach my $commandName (keys %{$p_handlers}) {
my $lcName=lc($commandName);
if(exists $::spadsCmdHandlers{$lcName} && (! $replace)) {
::slog("Ignoring addSpadsCommandHandler for plugin $plugin (\"$lcName\" command already exists)",2);
}else{
$::spadsCmdHandlers{$lcName}=$p_handlers->{$commandName};
}
}
}
sub addSpringCommandHandler {
my ($p_handlers,$priority)=@_;
my $plugin=getCallerPlugin();
map {$_=SimpleEvent::encapsulateCallback($_,$plugin) unless(ref $_ eq 'CODE')} (values %{$p_handlers});
$priority//=$plugin;
$::autohost->addCallbacks($p_handlers,0,$priority);
}
sub removeLobbyCommandHandler {
my ($p_commands,$priority,$isPreCallback)=@_;
$priority//=getCallerPlugin();
if($isPreCallback) {
$::lobby->removePreCallbacks($p_commands,$priority);
}else{
$::lobby->removeCallbacks($p_commands,$priority);
}
}
sub removeSpadsCommandHandler {
my $p_commands=shift;
my $plugin=getCallerPlugin();
foreach my $commandName (@{$p_commands}) {
my $lcName=lc($commandName);
delete $::spadsCmdHandlers{$lcName};
}
}
sub removeSpringCommandHandler {
my ($p_commands,$priority)=@_;
$priority//=getCallerPlugin();
$::autohost->removeCallbacks($p_commands,$priority);
}
################################
# Forking processes
################################
sub forkProcess {
my ($p_processFunction,$p_endCallback,$preventQueuing)=@_;
$preventQueuing//=1;
my ($childPid,$procHdl) = SimpleEvent::forkProcess($p_processFunction, sub { &{$p_endCallback}($_[1],$_[2],$_[3],$_[0]) },$preventQueuing);
::slog('Failed to fork process for plugin '.getCallerPlugin().' !',1) if($childPid == 0);
return wantarray() ? ($childPid,$procHdl) : $childPid;
}
sub forkCall {
my ($childPid,$procHdl) = SimpleEvent::forkCall(@_);
::slog('Failed to fork process for function call by plugin '.getCallerPlugin().' !',1) if($childPid == 0);
return wantarray() ? ($childPid,$procHdl) : $childPid;
}
sub removeProcessCallback {
my $res=SimpleEvent::removeProcessCallback(@_);
::slog('Failed to remove process callback for plugin '.getCallerPlugin().' !',1) unless($res);
return $res;
}
sub createDetachedProcess {
my $res = SimpleEvent::createDetachedProcess(@_);
::slog('Failed to create detached process for plugin '.getCallerPlugin().' !',1) unless($res);
return $res;
}
################################
# Timers management
################################
sub addTimer {
my ($name,$delay,$interval,$p_callback)=@_;
$name=getCallerPlugin().'::'.$name;
return SimpleEvent::addTimer($name,$delay,$interval,$p_callback);
}
sub removeTimer {
my $name=shift;
$name=getCallerPlugin().'::'.$name;
return SimpleEvent::removeTimer($name);
}
################################
# Sockets management
################################
sub addSocket {
if(my $rc=SimpleEvent::registerSocket(@_)) {
return $rc;
}else{
::slog('Unable to add socket for plugin '.getCallerPlugin().' !',2);
return 0;
}
}
sub removeSocket {
if(SimpleEvent::unregisterSocket(@_)) {
return 1;
}else{
::slog('Unable to remove socket for plugin '.getCallerPlugin().' !',2);
return 0;
}
}
################################
# SPADS operations
################################
sub applyPreset {
::applyPreset(@_);
}
sub cancelCloseBattle {
::cancelCloseBAttleAfterGame();
}
sub cancelQuit {
my $reason=shift;
::cancelQuitAfterGame($reason);
}
sub closeBattle {
::closeBattleAfterGame(@_);
}
sub getUserAccessLevel {
::getUserAccessLevel(@_);
}
sub loadArchives {
::loadArchives(@_);
}
sub queueLobbyCommand {
::queueLobbyCommand(@_);
}
sub quit {
my ($type,$reason,$exitCode)=@_;
$exitCode//=0;
{1 => \&::quitAfterGame,
2 => \&::restartAfterGame,
3 => \&::quitWhenOnlySpec,
4 => \&::restartWhenOnlySpec,
5 => \&::quitWhenEmpty,
6 => \&::restartWhenEmpty}->{$type}->($reason,$exitCode);
}
sub rehost {
::rehostAfterGame(@_);
}
sub slog {
my ($m,$l)=@_;
my $plugin=getCallerPlugin();
$m="<$plugin> $m";
::slog($m,$l);
}
sub updateSetting {
my ($type,$name,$value)=@_;
my $plugin=getCallerPlugin();
if(none {$type eq $_} (qw'set bSet hSet')) {
::slog("Ignoring updateSetting call from plugin $plugin: unknown setting type \"$type\"",2);
return 0;
}
if($type eq 'set') {
if(! exists $::spads->{conf}{$name}) {
::slog("Ignoring updateSetting call from plugin $plugin: unknown setting \"$name\"",2);
return 0;
}
$::spads->{conf}{$name}=$value;
%::conf=%{$::spads->{conf}};
::applySettingChange($name);
}elsif($type eq 'bSet') {
my $lcName=lc($name);
$::spads->{bSettings}{$lcName}=$value;
if($::lobbyState >= 6) {
::sendBattleSetting($lcName);
::applyMapBoxes() if($lcName eq 'startpostype');
}
}elsif($type eq 'hSet') {
if(! exists $::spads->{hSettings}{$name}) {
::slog("Ignoring updateSetting call from plugin $plugin: unknown hosting setting \"$name\"",2);
return 0;
}
$::spads->{hSettings}{$name}=$value;
::updateTargetMod() if($name eq 'modName');
}else{
return 0;
}
$::timestamps{autoRestore}=time;
return 1;
}
################################
# AutoHost messaging system
################################
sub answer {
::answer(@_);
}
sub broadcastMsg {
::broadcastMsg(@_);
}
sub invalidSyntax {
::invalidSyntax(@_);
}
sub sayBattle {
::sayBattle(@_);
}
sub sayBattleAndGame {
::sayBattleAndGame(@_);
}
sub sayBattleUser {
::sayBattleUser(@_);
}
sub sayChan {
::sayChan(@_);
}
sub sayGame {
::sayGame(@_);
}
sub sayPrivate {
::sayPrivate(@_);
}
################################
# Time utils
################################
sub getDirModifTime {
::getDirModifTime(@_);
}
sub secToDayAge {
::secToDayAge(@_);
}
sub secToTime {
::secToTime(@_);
}
################################
# Data formatting
################################
sub formatArray {
::formatArray(@_);
}
sub formatFloat {
::formatNumber(@_);
}
sub formatInteger {
::formatInteger(@_);
}
sub formatList {
::formatList(@_);
}
1;
__END__
=head1 NAME
SpadsPluginApi - SPADS Plugin API
=head1 SYNOPSIS
Perl:
package MyPlugin;
use SpadsPluginApi;
my $pluginVersion='0.1';
my $requiredSpadsVersion='0.11';
sub getVersion { return $pluginVersion; }
sub getRequiredSpadsVersion { return $requiredSpadsVersion; }
sub new {
my $class=shift;
my $self = {};
bless($self,$class);
slog("MyPlugin plugin loaded (version $pluginVersion)",3);
return $self;
}
1;
Python:
import perl
spads=perl.MyPlugin
pluginVersion = '0.1'
requiredSpadsVersion = '0.12.29'
def getVersion(pluginObject):
return pluginVersion
def getRequiredSpadsVersion(pluginName):
return requiredSpadsVersion
class MyPlugin:
def __init__(self,context):
spads.slog("MyPlugin plugin loaded (version %s)" % pluginVersion,3)
=head1 DESCRIPTION
C<SpadsPluginApi> is a Perl module implementing the plugin API for SPADS. This
API allows anyone to add new features as well as customize existing SPADS
features (such as balancing algorithms, battle status presentation, players
skills management, command aliases...).
This API relies on plugin callback functions (implemented by SPADS plugins),
which can in turn call plugin API functions (implemented by SPADS core) and
access shared SPADS data.
Plugins can be coded in Perl (since SPADS 0.11) or Python (since SPADS 0.12.29).
=head1 PYTHON SPECIFIC NOTES
=head2 How to read the documentation
This documentation was written when SPADS was only supporting plugins coded in
Perl, so types for function parameters and return values are described using
Perl terminology, with Perl sigils (C<%> for hash, C<@> for array, C<$> for
scalars). Python plugins just need to ignore these sigils and use their
equivalent internal Python types instead (Python dictionaries instead of Perl
hashes, Python lists instead of Perl arrays, Python tuples instead of Perl
lists, Python None value instead of Perl undef value...).
In order to call functions from the plugin API, Python plugin modules must first
import the special C<perl> module, and then use the global variable of this
module named after the plugin name to call the functions (refer to the SYNOPSYS
for an example of a Python plugin named C<MyPlugin> calling the C<slog> API
function).
=head2 Perl strings conversions
SPADS uses the C<Inline::Python> Perl module to interface Perl code with Python
code. Unfortunately, some versions of this module don't auto-convert Perl
strings entirely when used with Python 3 (Python 2 is unaffected): depending on
the version of Python and the version of the C<Inline::Python> Perl module used
by your system, it is possible that the Python plugin callbacks receive Python
byte strings as parameters instead of normal Python strings. In order to
mitigate this problem, the plugin API offers both a way to detect from the
Python plugin code if current system is affected (by calling the C<get_flag>
function with parameter C<'use_byte_string'>), and a way to workaround the
problem by calling a dedicated C<fix_string> function which fixes the string
values if needed. For additional information regarding these Python specific
functions of the plugin API, refer to the L<API FUNCTIONS - Python specific|/"Python specific">
section. Python plugins can also choose to implement their own pure Python function which
fixes strings coming from SPADS if needed like this for example:
def fix_spads_string(spads_string):
if hasattr(spads_string,'decode'):
return spads_string.decode('utf-8')
return spads_string
def fix_spads_strings(*spads_strings):
fixed_strings=[]
for spads_string in spads_strings:
fixed_strings.append(fix_spads_string(spads_string))
return fixed_strings
=head2 Windows limitations
On Windows systems, Perl emulates the C<fork> functionality using threads. As
the C<Inline::Python> Perl module used by SPADS to interface with Python code
isn't thread-safe, the fork functions of the plugin API (C<forkProcess> and
C<forkCall>) aren't available from Python plugins when running on a Windows
system. On Windows systems, using native Win32 processes for parallel processing
is recommended anyway. Plugins can check if the fork functions of the plugin API
are available by calling the C<get_flag> Python specific plugin API function
with parameter C<'can_fork'>, instead of checking by themselves if the current
system is Windows. Refer to the L<API FUNCTIONS - Python specific|/"Python specific">
section for more information regarding this function.
Automatic asynchronous socket management (C<addSocket> plugin API function) is
also unavailable for Python plugins on Windows systems (this is due to the file
descriptor numbers being thread-specific on Windows, preventing SPADS from
accessing sockets opened in Python interpreter scope). However, it is still
possible to manage asynchronous sockets manually, for example by hooking the
SPADS event loop (C<eventLoop> plugin callback) to perform non-blocking
C<select> with 0 timeout (refer to L<Python select documentation|https://docs.python.org/3/library/select.html#select.select>).
Plugins can check if the C<addSocket> function of the plugin API is available by
calling the C<get_flag> Python specific plugin API function with parameter
C<'can_add_socket'>, instead of checking by themselves if the current system is
Windows. Refer to the L<API FUNCTIONS - Python specific|/"Python specific">
section for more information regarding this function.
=head1 CALLBACK FUNCTIONS
The callback functions are called from SPADS core and implemented by SPADS
plugins. SPADS plugins are actually Perl or Python classes instanciated as
objects. So most callback functions are called as object methods and receive a
reference to the plugin object as first parameter. The exceptions are the
constructor (Perl: C<new> receives the class/plugin name as first parameter,
Python: C<__init__> receives the plugin object being created as first
parameter), and a few other callbacks which are called/checked before the plugin
object is actually created: C<getVersion> and C<getRequiredSpadsVersion>
(mandatory callbacks), C<getParams> and C<getDependencies> (optional callbacks).
=head2 Mandatory callbacks
To be valid, a SPADS plugin must implement at least these 3 callbacks:
=over 2
=item [Perl] C<new($pluginName,$context)> . . . . [Python] C<__init__(self,context)>
This is the plugin constructor, it is called when SPADS (re)loads the plugin.
The C<$context> parameter is a string which indicates in which context the
plugin constructor has been called: C<"autoload"> means the plugin is being
loaded automatically at startup, C<"load"> means the plugin is being loaded
manually using C<< !plugin <pluginName> load >> command, C<"reload"> means the
plugin is being reloaded manually using C<< !plugin <pluginName> reload >>
command.
=item C<getVersion($self)>
returns the plugin version number (example: C<"0.1">).
=item C<getRequiredSpadsVersion($pluginName)>
returns the required minimum SPADS version number (example: C<"0.11">).
=back
=head2 Configuration callback
SPADS plugins can use the core SPADS configuration system to manage their own
configuration parameters. This way, all configuration management tools in place
(parameter values checking, C<!reloadconf> etc.) can be reused by the plugins. To
do so, the plugin must implement following configuration callback:
=over 2
=item C<getParams($pluginName)>
This callback must return a reference to an array containing 2 elements. The
first element is a reference to a hash containing the plugin global settings
declarations, the second one is the same but for plugin preset settings
declarations. These hashes use setting names as keys, and references to array of
allowed types as values. The types must be either strings that match the keys of
the C<%paramTypes> hash defined in SpadsConf.pm file, or custom functions to
implement custom value checks. Such custom value checking functions take 2
parameters: the value to check as first parameter and a boolean specifying if
the value is the default value (i.e. first value declared in the definition, for
preset settings) as second parameter. The function must return C<true> if the
value is valid, or C<false> if it is invalid (refer to examples below).
As for global SPADS core settings, the global settings of the plugin cannot be
changed dynamically except by editing and reloading the configuration files (for
example by using the C<!reloadConf> command). The global settings are defined
before the preset definition sections in the plugin configuration file. Only one
definition is allowed for each global setting, and only one value can be
configured in each global setting definition. Global settings aren't impacted
by preset changes. Global settings should be used for the structural
parameterization of the plugin, which isn't supposed to be modified during
runtime and isn't useful from end user point of view (for example file/directory
path settings...).
As for SPADS core preset settings, the preset settings of the plugin can be
changed dynamically (using the C<< !plugin <pluginName> set <settingName> <settingValue> >>
command for example, or simply by changing current global preset). The preset
settings are defined in the preset definition sections of the plugin
configuration file, after the global plugin settings. The preset settings can be
defined multiple times (once in each preset declaration section). Multiple
values can be configured in each preset setting definition (values are separated
by pipe character C<|>, the first value is the default value applied when
loading the preset and the remaining values are the other allowed values).
Preset settings are impacted by preset changes. Preset settings should be used
for settings that need to be visible by end users and/or modifiable easily at
runtime.
Example of implementation in Perl:
my %globalPluginParams = ( MyGlobalSetting1 => ['integer'],
MyGlobalSetting2 => ['ipAddr']);
my %presetPluginParams = ( MyPresetSetting1 => ['readableDir','null'],
MyPresetSetting2 => ['bool', \&myCustomSettingValueCheck] );
sub myCustomSettingValueCheck {
my ($settingValue,$isDefault)=@_;
return $settingValue eq 'true' || $settingValue eq 'false'
}
sub getParams { return [\%globalPluginParams,\%presetPluginParams] }
Example of implementation in Python:
def myCustomSettingValueCheck(settingValue,isDefault):
return settingValue == 'true' or settingValue == 'false'
globalPluginParams = { 'MyGlobalSetting1': ['integer'],
'MyGlobalSetting2': ['ipAddr'] }
presetPluginParams = { 'MyPresetSetting1': ['readableDir','null'],
'MyPresetSetting2': ['bool', myCustomSettingValueCheck], };
def getParams(pluginName):
return [ globalPluginParams , presetPluginParams ]
In these examples, the preset setting C<MyPresetSetting2> is declared as
supporting both the values of the predefined type "bool" and the values allowed
by the custom function C<myCustomSettingValueCheck>. The predefined type "bool"
allows values C<0> and C<1>. The custom function C<myCustomSettingValueCheck>
allows values C<"true"> and C<"false">. So in the end the allowed values for the
preset setting C<MyPresetSetting2> are: C<0>, C<1>, C<"true"> and
C<"false">.
=back
=head2 Dependencies callback
SPADS plugins can use data and functions from other plugins (dependencies). But
this can only work if the plugin dependencies are loaded before the plugin
itself. That's why following callback should be used by such dependent plugins
to declare their dependencies, which will allow SPADS to perform the check for
them.
Also, SPADS will automatically unload dependent plugins when one of their
dependencies is unloaded.
=over 2
=item C<getDependencies($pluginName)>
This callback must return the plugin dependencies (list of plugin names).
Example of implementation in Perl:
sub getDependencies { return ('SpringForumInterface','MailAlerts'); }
Example of implementation in Python:
def getDependencies(pluginName):
return ('SpringForumInterface','MailAlerts')
=back
=head2 Event-based callbacks
Following callbacks are triggered by events from various sources (SPADS, Spring
lobby, Spring server...):
=over 2
=item C<onBattleClosed($self)>
This callback is called when the battle lobby of the autohost is closed.
=item C<onBattleOpened($self)>
This callback is called when the battle lobby of the autohost is opened.
=item C<onGameEnd($self,\%endGameData)>
This callback is called each time a game hosted by the autohost ends.
The C<\%endGameData> parameter is a reference to a hash containing all the data
stored by SPADS concerning the game that just ended. It is recommended to use a
data printing function (such as the C<Dumper> function from the standard
C<Data::Dumper> module included in Perl core) to check the content of this hash
for the desired data.
=item C<onJoinBattleRequest($self,$userName,$ipAddr)>
This callback is called each time a client requests to join the battle lobby
managed by the autohost.
C<$userName> is the name of the user requesting to join the battle
C<$ipAddr> is the IP address of the user requesting to join the battle
This callback must return:
C<0> if the user is allowed to join the battle
C<1> if the user isn't allowed to join the battle (without explicit reason)
C<< "<explicit reason string>" >> if the user isn't allowed to join the battle,
with explicit reason
=item C<onJoinedBattle($self,$userName)>
This callback is called each time a user joins the battle lobby of the autohost.
C<$userName> is the name of the user who just joined the battle lobby
=item C<onLeftBattle($self,$userName)>
This callback is called each time a user leaves the battle lobby of the autohost.
C<$userName> is the name of the user who just left the battle lobby
=item C<onLobbyConnected($self,$lobbyInterface)>
/!\ RENAMED TO C<onLobbySynchronized> /!\
This callback has been renamed to C<onLobbySynchronized> since SPADS v0.13.35.
It can still be used under the name C<onLobbyConnected> for the sake of backward
compatibility, however this name is misleading so its usage under this name is
not recommended (the callback is only called when the lobby connection is fully
synchronized, i.e. when all the initial commands sent by the lobby server after
successfully logging in have been received).
The C<$lobbyInterface> parameter is the instance of the
L<SpringLobbyInterface|https://github.com/Yaribz/SpringLobbyInterface> module
used by SPADS.
=item C<onLobbyDisconnected($self)>
This callback is called each time the autohost is disconnected from the lobby
server.
=item C<onLobbyLoggedIn($self,$lobbyInterface)>
This callback is called each time the autohost successfully logins on the lobby
server. It is one of the three callbacks triggered when a new connection
to the lobby server is established. These callbacks are called in following
order:
=over 4
=item * 1) C<onLobbyLogin> (called when trying to login)
=item * 2) C<onLobbyLoggedIn> (called when successfully logged in)
=item * 3) C<onLobbySynchronized> (called when state is synchronized with
server)
=back
The C<$lobbyInterface> parameter is the instance of the
L<SpringLobbyInterface|https://github.com/Yaribz/SpringLobbyInterface> module
used by SPADS.
Note: This callback is the ideal place for a plugin to register its lobby
command handlers using the C<addLobbyCommandHandler> function of the plugin API,
if this plugin needs to process the commands sent by the lobby server during the
initial lobby state synchronization phase (i.e. commands sent before the
C<LOGININFOEND> command). For plugins that do not require being called back
during the initial lobby state synchronization phase, the C<onLobbySynchronized>
callback should be used instead to register the lobby command handlers.
=item C<onLobbyLogin($self,$lobbyInterface)>
This callback is called each time the autohost tries to login on the lobby
server. It is one of the three callbacks triggered when a new connection to the
lobby server is established. These callbacks are called in following order:
=over 4
=item * 1) C<onLobbyLogin> (called when trying to login)
=item * 2) C<onLobbyLoggedIn> (called when successfully logged in)
=item * 3) C<onLobbySynchronized> (called when state is synchronized with
server)
=back
The C<$lobbyInterface> parameter is the instance of the
L<SpringLobbyInterface|https://github.com/Yaribz/SpringLobbyInterface> module
used by SPADS.
=item C<onLobbySynchronized($self,$lobbyInterface)>
This callback is called each time the autohost completes the lobby state
synchronization phase, which occurs after successfully logging in. It is one of
the three callbacks triggered when a new connection to the lobby server is
established. These callbacks are called in following order:
=over 4
=item * 1) C<onLobbyLogin> (called when trying to login)
=item * 2) C<onLobbyLoggedIn> (called when successfully logged in)
=item * 3) C<onLobbySynchronized> (called when state is synchronized with
server)
=back
The C<$lobbyInterface> parameter is the instance of the
L<SpringLobbyInterface|https://github.com/Yaribz/SpringLobbyInterface> module
used by SPADS.
Note: This callback is the ideal place for a plugin to register its lobby
command handlers using the C<addLobbyCommandHandler> function of the plugin API,
as long as this plugin does not need to process the commands sent by the lobby
server during the initial lobby state synchronization phase (i.e. commands sent
before the C<LOGININFOEND> command). For plugins that require being called back
during the initial lobby state synchronization phase, the C<onLobbyLoggedIn>
callback must be used instead to register the lobby command handlers.
=item C<onPresetApplied($self,$oldPresetName,$newPresetName)>
This callback is called each time a global preset is applied.
C<$oldPresetName> is the name of the previous global preset
C<$newPresetName> is the name of the new global preset
=item C<onPrivateMsg($self,$userName,$message)>
This callback is called each time the autohost receives a private message.
C<$userName> is the name of the user who sent a private message to the autohost
C<$message> is the private message received by the autohost
This callback must return:
C<0> if the message can be processed by other plugins and SPADS core
C<1> if the message must not be processed by other plugins and SPADS core (this
prevents logging)
=item C<onReloadConf($self,$keepSettings)>
This callback is called each time the SPADS configuration is reloaded.
C<$keepSettings> is a boolean parameter indicating if current settings must be
kept.
This callback must return:
C<0> if an error occured while reloading the plugin configuration
C<1> if the plugin configuration has been reloaded correctly