-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.py
executable file
·1650 lines (1414 loc) · 64.4 KB
/
plugin.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###
# This file is part of Soap.
#
# Soap 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, version 2.
#
# Soap 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 Soap. If not, see
# <http://www.gnu.org/licenses/>.
###
from supybot.commands import *
import supybot.conf as conf
import supybot.callbacks as callbacks
from datetime import datetime
import os.path
import Queue
import random
import socket
from subprocess import Popen, PIPE, CalledProcessError
import sys
import threading
import time
import soaputils as utils
from soapclient import SoapClient
from enums import *
from libottdadmin2.trackingclient import poll, POLLIN, POLLOUT, POLLERR, POLLHUP, POLLPRI, POLL_MOD
from libottdadmin2.constants import *
from libottdadmin2.enums import *
from libottdadmin2.packets import *
class Soap(callbacks.Plugin):
"""
This plug-in allows supybot to interface to OpenTTD via its built-in
adminport protocol
"""
def __init__(self, irc):
self.__parent = super(Soap, self)
self.__parent.__init__(irc)
self._pollObj = poll()
self.channels = self.registryValue('channels')
self.connections = {}
self.registeredConnections = {}
self.connectionIds = []
for channel in self.channels:
serverID = self.registryValue('serverID', channel)
conn = SoapClient(channel, serverID)
self._attachEvents(conn)
self._initSoapClient(conn, irc)
self.connections[channel.lower()] = conn
if self.registryValue('autoConnect', channel):
self._connectOTTD(irc, conn, channel)
self.stopPoll = threading.Event()
self.pollingThread = threading.Thread(
target = self._pollThread,
name = 'SoapPollingThread')
self.pollingThread.daemon = True
self.pollingThread.start()
def die(self):
for conn in self.connections.itervalues():
try:
if conn.connectionstate == ConnectionState.CONNECTED:
conn.connectionstate = ConnectionState.DISCONNECTING
utils.disconnect(conn, False)
except NameError:
pass
self.stopPoll.set()
self.pollingThread.join()
def doJoin(self, irc, msg):
channel = msg.args[0].lower()
conn = None
if msg.nick == irc.nick and self.channels.count(channel) >=1:
conn = self.connections.get(channel)
if not conn:
return
if conn.connectionstate == ConnectionState.CONNECTED:
text = 'Connected to %s (Version %s)' % (
conn.serverinfo.name, conn.serverinfo.version)
utils.msgChannel(conn._irc, conn.channel, text)
# Connection management
def _attachEvents(self, conn):
conn.soapEvents.connected += self._connected
conn.soapEvents.disconnected += self._disconnected
conn.soapEvents.shutdown += self._rcvShutdown
conn.soapEvents.new_game += self._rcvNewGame
conn.soapEvents.new_map += self._rcvNewMap
conn.soapEvents.clientjoin += self._rcvClientJoin
conn.soapEvents.clientupdate += self._rcvClientUpdate
conn.soapEvents.clientquit += self._rcvClientQuit
conn.soapEvents.chat += self._rcvChat
conn.soapEvents.rcon += self._rcvRcon
conn.soapEvents.rconend += self._rcvRconEnd
conn.soapEvents.console += self._rcvConsole
conn.soapEvents.cmdlogging += self._rcvCmdLogging
conn.soapEvents.pong += self._rcvPong
def _connectOTTD(self, irc, conn, source = None, text = 'Connecting...'):
utils.msgChannel(irc, conn.channel, text)
if source and not source == conn.channel:
utils.msgChannel(irc, source, text)
conn = utils.refreshConnection(
self.connections, self.registeredConnections, conn)
self._initSoapClient(conn, irc)
conn.connectionstate = ConnectionState.CONNECTING
if not conn.connect():
conn.connectionstate = ConnectionState.DISCONNECTED
text = 'Connection failed'
utils.msgChannel(irc, conn.channel, text)
def _connected(self, connChan):
conn = self.connections.get(connChan)
if not conn:
return
conn.connectionstate = ConnectionState.AUTHENTICATING
pwInterval = self.registryValue('passwordInterval', conn.channel)
if pwInterval != 0:
connectionid = utils.getConnectionID(conn)
pwThread = threading.Thread(
target = self._passwordThread,
name = 'PasswordRotation.%s' % connectionid,
args = [conn])
pwThread.daemon = True
pwThread.start()
else:
command = 'set server_password *'
conn.rconState = RconStatus.ACTIVE
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
conn.clientPassword = None
def _disconnected(self, connChan, canRetry):
conn = self.connections.get(connChan)
if not conn:
return
if conn.is_connected:
return
irc = conn.irc
fileno = conn.filenumber
try:
del self.registeredConnections[fileno]
except KeyError:
pass
try:
self._pollObj.unregister(fileno)
except KeyError:
pass
except IOError:
pass
conn.logger.debug('>>--DEBUG--<< Disconnected')
if conn.serverinfo.name:
text = 'Disconnected from %s' % (conn.serverinfo.name)
utils.msgChannel(conn.irc, conn.channel, text)
conn.serverinfo.name = None
logMessage = '<DISCONNECTED>'
conn.logger.info(logMessage)
if conn.connectionstate == ConnectionState.CONNECTED:
# We didn't disconnect on purpose, set this so we will reconnect
conn.connectionstate == ConnectionState.DISCONNECTED
text = 'Attempting to reconnect...'
self._connectOTTD(irc, conn, text = text)
else:
conn.connectionstate = ConnectionState.DISCONNECTED
def _initSoapClient(self, conn, irc):
conn.configure(
irc = irc,
ID = self.registryValue('serverID', conn.channel),
password = self.registryValue('password', conn.channel),
host = self.registryValue('host', conn.channel),
port = self.registryValue('port', conn.channel),
name = '%s-Soap' % irc.nick)
utils.initLogger(conn, self.registryValue('logdir'), self.registryValue('logHistory'))
self._pollObj.register(conn.fileno(),
POLLIN | POLLERR | POLLHUP | POLLPRI)
conn.filenumber = conn.fileno()
self.registeredConnections[conn.filenumber] = conn
# Thread functions
def _commandThread(self, conn, irc, ofsCommand, successText = None, delay = 0):
time.sleep(delay)
ofs = self.registryValue('ofslocation', conn.channel)
command = ofs.replace('{OFS}', ofsCommand)
if ofs.startswith('ssh'):
useshell = True
elif os.path.isfile(command.split()[0]):
useshell = False
else:
irc.reply('OFS location invalid. Please review plugins.Soap.ofslocation')
return
self.log.info('executing: %s' % command)
if not useshell:
command = command.split()
try:
commandObject = Popen(command, shell=useshell, stdout = PIPE)
except OSError as e:
irc.reply('Couldn\'t start %s, Please review plugins.Soap.ofslocation'
% ofsCommand.split()[0])
return
output = commandObject.stdout.read()
commandObject.stdout.close()
commandObject.wait()
for line in output.splitlines():
self.log.info('%s output: %s' % (ofsCommand.split()[0], line))
if commandObject.returncode:
ofsFile = ofsCommand.split()[0]
code = commandObject.returncode
if ofsFile == 'ofs-getsave.py':
irc.reply(utils.ofsGetsaveExitcodeToText(code))
elif ofsFile == 'ofs-start.py':
utils.msgChannel(irc, conn.channel, utils.ofsStartExitcodeToText(code))
elif ofsFile == 'ofs-svntobin.py':
irc.reply(utils.ofsSvnToBinExitcodeToText(code))
elif ofsFile == 'ofs-svnupdate.py':
irc.reply(utils.ofsSvnUpdateExitcodeToText(code))
elif ofsFile == 'ofs-transfersave.py':
irc.reply(utils.ofsTransferSaveExitcodeToText(code))
else:
irc.reply('%s reported an error, exitcode: %s. See bot-log for more information.'
% (ofsFile, code))
irc.reply('PS this message should not be seen, please thwack Taede to get a proper error message')
return
if successText:
if not ofsCommand.startswith('ofs-start.py'):
irc.reply(successText, prefixNick = False)
else:
utils.msgChannel(irc, conn.channel, successText)
if ofsCommand.startswith('ofs-svnupdate.py'):
conn.rconState = RconStatus.UPDATESAVED
rconcommand = 'save autosave/autosavesoap'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = rconcommand)
elif ofsCommand.startswith('ofs-svntobin.py'):
ofsCommand = 'ofs-start.py'
successText = 'Server is starting'
connectionid = utils.getConnectionID(conn)
cmdThread = threading.Thread(
target = self._commandThread,
name = 'Command.%s.%s' % (connectionid, ofsCommand.split()[0]),
args = [conn, irc, ofsCommand, successText])
cmdThread.daemon = True
cmdThread.start()
def _passwordThread(self, conn):
pluginDir = os.path.dirname(__file__)
pwFileName = os.path.join(pluginDir, 'passwords.txt')
# delay password changing until connection is fully established,
# abort if it takes longer than 10 seconds
for second in range(10):
if conn.connectionstate == ConnectionState.CONNECTED:
break
time.sleep(1)
if conn.connectionstate != ConnectionState.CONNECTED:
return
while True:
interval = self.registryValue('passwordInterval', conn.channel)
if conn.connectionstate != ConnectionState.CONNECTED:
break
if conn.rconState == RconStatus.IDLE:
if interval > 0:
newPassword = random.choice(list(open(pwFileName)))
newPassword = newPassword.strip()
newPassword = newPassword.lower()
command = 'set server_password %s' % newPassword
conn.rconState = RconStatus.ACTIVE
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
conn.clientPassword = newPassword
time.sleep(interval)
else:
command = 'set server_password *'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
conn.clientPassword = None
break
else:
time.sleep(interval)
def _pollThread(self):
timeout = 1.0
while True:
if len(self.registeredConnections) >= 1:
events = self._pollObj.poll(timeout * POLL_MOD)
for fileno, event in events:
conn = self.registeredConnections.get(fileno)
if not conn:
continue
if (event & POLLIN) or (event & POLLPRI):
packet = conn.recv_packet()
if packet == None:
logMessage = '>>--DEBUG--<< Received empty packet, forcing disconnect'
conn.logger.debug(logMessage)
utils.disconnect(conn, True)
else:
logMessage = '>>--DEBUG--<< Received packet: %s' % str(packet)
conn.logger.debug(logMessage)
elif (event & POLLERR) or (event & POLLHUP):
logMessage = '>>--DEBUG--<< Received POLLERR or POLLHUP, forcing disconnect'
conn.logger.debug(logMessage)
utils.disconnect(conn, True)
else:
time.sleep(0.001)
# lets not use up 100% cpu if there are no active connections
else:
time.sleep(1)
if self.stopPoll.isSet():
break
# Miscelanious functions
def _ircCommandInit(self, irc, msg, serverID, needsPermission):
source = msg.args[0].lower()
if source == irc.nick.lower():
source = msg.nick
conn = utils.getConnection(
self.connections, self.channels, source, serverID)
if not conn:
return (None, None)
allowOps = self.registryValue('allowOps', conn.channel)
if not needsPermission:
return (source, conn)
elif utils.checkPermission(irc, msg, conn.channel, allowOps):
return (source, conn)
else:
return (None, None)
def _ircRconInit(self, irc, msg, firstWord, remainder, command, needsPermission):
if not remainder:
remainder = ''
source = msg.args[0].lower()
if source == irc.nick.lower():
source = msg.nick
conn = None
for c in self.connections.itervalues():
if (firstWord.lower() == c.channel.lower()
or firstWord.lower() == c.ID.lower()):
conn = c
if command:
command += ' %s' % remainder
else:
command = remainder
if not conn:
if command:
command += ' %s %s' % (firstWord, remainder)
else:
command = '%s %s' % (firstWord, remainder)
conn = utils.getConnection(
self.connections, self.channels, source)
if not conn:
return (None, None, None)
allowOps = self.registryValue('allowOps', conn.channel)
if not needsPermission:
return (source, conn, command)
elif utils.checkPermission(irc, msg, conn.channel, allowOps):
return (source, conn, command)
else:
return (None, None, None)
# Packet Handlers
def _rcvShutdown(self, connChan):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
text = 'Server Shutting down'
utils.msgChannel(irc, conn.channel, text)
logMessage = '<SHUTDOWN> Server is shutting down'
conn.logger.info(logMessage)
conn.connectionstate = ConnectionState.SHUTDOWN
def _rcvNewGame(self, connChan):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
text = 'Starting new game'
utils.msgChannel(irc, conn.channel, text)
logMessage = '<END> End of game'
conn.logger.info(logMessage)
if not conn.logger == None and len(conn.logger.handlers):
for handler in conn.logger.handlers:
try:
handler.doRollover()
except OSError as e:
pass
logMessage = '<NEW> New log file started'
conn.logger.info(logMessage)
def _rcvNewMap(self, connChan, mapinfo, serverinfo):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
conn.connectionstate = ConnectionState.CONNECTED
text = 'Now playing on %s (Version %s)' % (
conn.serverinfo.name, conn.serverinfo.version)
utils.msgChannel(irc, conn.channel, text)
command = 'set min_active_clients %s' % self.registryValue(
'minPlayers', conn.channel)
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
logMessage = '-' * 80
conn.logger.info(logMessage)
logMessage = '<CONNECTED> Version: %s, Name: \'%s\' Mapname: \'%s\' Mapsize: %dx%d' % (
conn.serverinfo.version, conn.serverinfo.name, conn.mapinfo.name, conn.mapinfo.x, conn.mapinfo.y)
conn.logger.info(logMessage)
def _rcvClientJoin(self, connChan, client):
conn = self.connections.get(connChan)
if not conn or isinstance(client, (long, int)):
return
irc = conn.irc
text = '*** %s has joined' % client.name
logMessage = '<JOIN> Name: \'%s\' (Host: %s, ClientID: %s)' % (
client.name, client.hostname, client.id)
conn.logger.info(logMessage)
utils.msgChannel(irc, conn.channel, text)
welcome = self.registryValue('welcomeMessage', conn.channel)
if welcome:
replacements = {
'{clientname}':client.name,
'{servername}': conn.serverinfo.name,
'{serverversion}': conn.serverinfo.version}
for line in welcome:
for word, newword in replacements.iteritems():
line = line.replace(word, newword)
conn.send_packet(AdminChat,
action = Action.CHAT_CLIENT,
destType = DestType.CLIENT,
clientID = client.id,
message = line)
if not client.play_as == 255 and client.name.lower().startswith('player'):
playAsPlayer = self.registryValue('playAsPlayer', conn.channel)
if not playAsPlayer:
utils.moveToSpectators(irc, conn, client)
def _rcvClientUpdate(self, connChan, old, client, changed):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
if 'name' in changed:
text = '*** %s has changed his/her name to %s' % (
old.name, client.name)
utils.msgChannel(conn.irc, conn.channel, text)
logMessage = '<NAMECHANGE> Old name: \'%s\' New Name: \'%s\' (Host: %s)' % (
old.name, client.name, client.hostname)
conn.logger.info(logMessage)
def _rcvClientQuit(self, connChan, client, errorcode):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
if not isinstance(client, (long, int)):
if errorcode:
reason = '%s' % utils.getQuitReasonFromNumber(errorcode)
else:
reason = 'Leaving'
text = '*** %s has left the game (%s)' % (client.name, reason)
utils.msgChannel(irc, conn.channel, text)
logMessage = '<QUIT> Name: \'%s\' (Host: %s, ClientID: %s, Reason: \'%s\')' % (
client.name, client.hostname, client.id, reason)
conn.logger.info(logMessage)
def _rcvChat(self, connChan, client, action, destType, clientID, message, data):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
clientName = str(clientID)
if client != clientID:
clientName = client.name
if action == Action.CHAT:
rulesUrl = self.registryValue('rulesUrl', conn.channel)
text = '<%s> %s' % (clientName, message)
utils.msgChannel(irc, conn.channel, text)
if message.startswith('!admin'):
text = '*** %s has requested an admin. (Note: Admin will read back on irc, so please do already write down your request, no need to wait.)' % clientName
utils.msgChannel(irc, conn.channel, text)
conn.send_packet(AdminChat,
action = Action.CHAT,
destType = DestType.BROADCAST,
clientID = ClientID.SERVER,
message = text)
elif message.startswith('!nick ') or message.startswith('!name '):
newName = message.partition(' ')[2]
newName = newName.strip()
if len(newName) > 0:
command = 'client_name %s %s' % (clientID, newName)
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
elif message.startswith('!rules') and not rulesUrl.lower() == 'none':
self.log.info('should display rules now')
text = 'Server rules can be found here: %s' % rulesUrl
utils.msgChannel(irc, conn.channel, text)
conn.send_packet(AdminChat,
action = Action.CHAT,
destType = DestType.BROADCAST,
clientID = ClientID.SERVER,
message = text)
elif action == Action.COMPANY_JOIN or action == Action.COMPANY_NEW:
if not isinstance(client, (long, int)):
company = conn.companies.get(client.play_as)
if action == Action.COMPANY_JOIN:
text = ('*** %s has joined company #%d' %
(client.name, company.id+1))
joining = 'JOIN'
else:
text = ('*** %s has started a new company #%d' %
(client.name, company.id+1))
joining = 'NEW'
logMessage = '<COMPANY %s> Name: \'%s\' Company Name: \'%s\' Company ID: %s' % (
joining, clientName, company.name, company.id+1)
utils.msgChannel(irc, conn.channel, text)
conn.logger.info(logMessage)
playAsPlayer = self.registryValue('playAsPlayer', conn.channel)
if clientName.lower().startswith('player') and not playAsPlayer:
utils.moveToSpectators(irc, conn, client)
elif action == Action.COMPANY_SPECTATOR:
text = '*** %s has joined spectators' % clientName
utils.msgChannel(irc, conn.channel, text)
logMessage = '<SPECTATOR JOIN> Name: \'%s\'' % clientName
conn.logger.info(logMessage)
def _rcvRcon(self, connChan, result, colour):
conn = self.connections.get(connChan)
if not conn or conn.rconState == RconStatus.IDLE:
return
irc = conn.irc
if conn.rconNick:
resultobj = conn.rconResults.get(conn.rconNick)
if not resultobj:
return
resultobj.results.put(result)
elif conn.rconState == RconStatus.SHUTDOWNSAVED:
if result.startswith('Map successfully saved'):
utils.msgChannel(irc, conn.channel, 'Successfully saved game as autosavesoap.sav')
conn.connectionstate = ConnectionState.SHUTDOWN
command = 'quit'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
return
elif conn.rconState == RconStatus.UPDATESAVED:
if result.startswith('Map successfully saved'):
message = 'Game saved. Shutting down server to finish update. We\'ll be back shortly'
utils.msgChannel(irc, conn.channel, message)
conn.send_packet(AdminChat,
action = Action.CHAT,
destType = DestType.BROADCAST,
clientID = ClientID.SERVER,
message = message)
conn.connectionstate = ConnectionState.SHUTDOWN
command = 'quit'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
ofsCommand = 'ofs-svntobin.py'
successText = None
connectionid = utils.getConnectionID(conn)
cmdThread = threading.Thread(
target = self._commandThread,
name = 'Command.%s.%s' % (connectionid, ofsCommand.split()[0]),
args = [conn, irc, ofsCommand, successText, 15])
cmdThread.daemon = True
cmdThread.start()
return
elif conn.rconState == RconStatus.RESTARTSAVED:
if result.startswith('Map successfully saved'):
message = 'Game saved. Restarting server...'
utils.msgChannel(irc, conn.channel, message)
conn.send_packet(AdminChat,
action = Action.CHAT,
destType = DestType.BROADCAST,
clientID = ClientID.SERVER,
message = message)
conn.connectionstate = ConnectionState.SHUTDOWN
command = 'quit'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
ofsCommand = 'ofs-start.py'
successText = 'Server is starting'
connectionid = utils.getConnectionID(conn)
cmdThread = threading.Thread(
target = self._commandThread,
name = 'Command.%s.%s' % (connectionid, ofsCommand.split()[0]),
args = [conn, irc, ofsCommand, successText, 15])
cmdThread.daemon = True
cmdThread.start()
return
def _rcvRconEnd(self, connChan, command):
conn = self.connections.get(connChan)
if not conn:
return
nick = conn.rconNick
rconresult = conn.rconResults.get(nick)
if conn.rconCommands.empty():
conn.rconNick = None
conn.rconState = RconStatus.IDLE
if rconresult:
irc = rconresult.irc
for i in range(5):
if not rconresult.results.empty():
text = rconresult.results.get()
if text[3:].startswith('***') and (
command.startswith('move') or
command.startswith('kick')):
pass
else:
irc.reply(text, prefixNick = False)
else:
break
if rconresult.results.empty():
del conn.rconResults[nick]
elif rconresult.results.qsize() <= 2:
for i in range(2):
if not rconresult.results.empty():
text = rconresult.results.get()
irc.reply(text, prefixNick = False)
else:
break
else:
actionChar = conf.get(conf.supybot.reply.whenAddressedBy.chars)[:1]
text = 'You have %d more messages. Type %sless to view them' % (
rconresult.results.qsize(), actionChar)
irc.reply(text)
if rconresult.succestext:
irc.reply(rconresult.succestext)
else:
command = conn.rconCommands.get()
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
def _rcvConsole(self, connChan, origin, message):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
if (message.startswith('Game Load Failed') or
message.startswith('ERROR: Game Load Failed') or
message.startswith('Content server connection') or
message.startswith('[udp] advertising to the master server is failing') or
('reported an error' in message and not 'IRC' in message)):
ircMessage = message.replace("\n", ", ")
ircMessage = ircMessage.replace("?", ", ")
utils.msgChannel(irc, conn.channel, ircMessage)
else:
ircMessage = message[3:]
if ircMessage.startswith('***') and 'paused' in ircMessage:
utils.msgChannel(irc, conn.channel, ircMessage)
def _rcvCmdLogging(self, connChan, frame, param1, param2, tile, text, company, commandID, clientID):
conn = self.connections.get(connChan)
if not conn:
return
if clientID == 1:
name = 'Server'
else:
client = conn.clients.get(clientID)
if client:
name = client.name
else:
name = clientID
commandName = conn.commands.get(commandID)
if not commandName:
commandName = commandID
if commandName == 'CmdPause':
pass
logMessage = '<COMMAND> Frame: %s Name: \'%s\' Command: %s Tile: %s Param1: %s Param2: %s Text: \'%s\'' % (
frame, name, commandName, tile, param1, param2, text)
conn.logger.info(logMessage)
def _rcvPong(self, connChan, start, end, delta):
conn = self.connections.get(connChan)
if not conn:
return
irc = conn.irc
text = 'Dong! reply took %s' % str(delta)
utils.msgChannel(irc, conn.channel, text)
# IRC commands
def apconnect(self, irc, msg, args, serverID):
""" [Server ID or channel]
connect to AdminPort of the [specified] OpenTTD server
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate == ConnectionState.CONNECTED:
irc.reply('Already connected!!', prefixNick = False)
else:
# just in case an existing connection failed to de-register upon disconnect
try:
self._pollObj.unregister(conn.filenumber)
except KeyError:
pass
except IOError:
pass
self._connectOTTD(irc, conn, source)
apconnect = wrap(apconnect, [optional('text')])
def apdisconnect(self, irc, msg, args, serverID):
""" [Server ID or channel]
disconnect from the [specified] server
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate == ConnectionState.CONNECTED:
conn.connectionstate = ConnectionState.DISCONNECTING
utils.disconnect(conn, False)
else:
irc.reply('Not connected!!', prefixNick = False)
apdisconnect = wrap(apdisconnect, [optional('text')])
def date(self, irc, msg, args, serverID):
""" [Server ID or channel]
display the ingame date of the [specified] server
"""
source, conn = self._ircCommandInit(irc, msg, serverID, False)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
message = '%s' % conn.date.strftime('%b %d %Y')
irc.reply(message, prefixNick = False)
date = wrap(date, [optional('text')])
def rcon(self, irc, msg, args, parameters):
""" [Server ID or channel] <rcon command>
sends a rcon command to the [specified] openttd server
"""
command = ''
(firstWord, dummy, remainder) = parameters.partition(' ')
(source, conn, command) = self._ircRconInit(irc, msg, firstWord, remainder, command, True)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
if conn.rconState != RconStatus.IDLE:
message = 'Sorry, still processing previous rcon command'
irc.reply(message, prefixNick = False)
return
if len(command) >= NETWORK_RCONCOMMAND_LENGTH:
message = "RCON Command too long (%d/%d)" % (
len(command), NETWORK_RCONCOMMAND_LENGTH)
irc.reply(message, prefixNick = False)
return
logMessage = '<RCON> Nick: %s, command: %s' % (msg.nick, command)
conn.logger.info(logMessage)
conn.rconNick = msg.nick
conn.rconState = RconStatus.ACTIVE
resultdict = utils.RconResults({
'irc':irc,
'succestext':None,
'command':command,
'results':Queue.Queue()
})
conn.rconResults[conn.rconNick] = resultdict
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
rcon = wrap(rcon, ['text'])
def less(self, irc, msg, args, serverID):
""" [Server ID or channel]
outputs remaining rcon output which didn't get shown in the previous rounds
"""
source, conn = self._ircCommandInit(irc, msg, serverID, False)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
rconresult = conn.rconResults.get(msg.nick)
if rconresult:
for i in range(5):
if not rconresult.results.empty():
text = rconresult.results.get()
irc.reply(text, prefixNick = False)
else:
break
if rconresult.results.empty():
del conn.rconResults[msg.nick]
elif rconresult.results.qsize() <= 2:
for i in range(2):
if not rconresult.results.empty():
text = rconresult.results.get()
irc.reply(text, prefixNick = False)
else:
break
else:
actionChar = conf.get(conf.supybot.reply.whenAddressedBy.chars)[:1]
text = 'You have %d more messages. Type %sless to view them' % (
rconresult.results.qsize(), actionChar)
irc.reply(text)
else:
text = 'There are no more messages to display kemosabi'
irc.reply(text)
less = wrap(less, [optional('text')])
def shutdown(self, irc, msg, args, serverID):
""" [Server ID or channel]
pauses the [specified] game server
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
if conn.rconState == RconStatus.IDLE:
conn.rconCommands.put('save autosave/autosavesoap')
conn.rconState = RconStatus.SHUTDOWNSAVED
command = conn.rconCommands.get()
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
else:
message = 'Sorry, still processing previous rcon command'
irc.reply(message, prefixNick = False)
shutdown = wrap(shutdown, [optional('text')])
def restart(self, irc, msg, args, serverID):
""" [Server ID or channel]
pauses the [specified] game server
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
if conn.rconState == RconStatus.IDLE:
conn.rconState = RconStatus.RESTARTSAVED
command = 'save autosave/autosavesoap'
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
else:
message = 'Sorry, still processing previous rcon command'
irc.reply(message, prefixNick = False)
restart = wrap(restart, [optional('text')])
def contentupdate(self, irc, msg, args, serverID):
""" [Server ID or channel]
Gets the server to update its list of online contents
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
if conn.rconState == RconStatus.IDLE:
conn.rconCommands.put('content update')
conn.rconNick = msg.nick
conn.rconState = RconStatus.ACTIVE
command = conn.rconCommands.get()
resultdict = utils.RconResults({
'irc':irc,
'succestext':None,
'command':command,
'results':Queue.Queue()
})
conn.rconResults[conn.rconNick] = resultdict
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
irc.reply('Performing content update')
else:
message = 'Sorry, still processing previous rcon command'
irc.reply(message, prefixNick = False)
contentupdate = wrap(contentupdate, [optional('text')])
def content(self, irc, msg, args, serverID):
""" [Server ID or channel]
Gets the server to update the downloaded content to the latest versions
"""
source, conn = self._ircCommandInit(irc, msg, serverID, True)
if not conn:
return
if conn.connectionstate != ConnectionState.CONNECTED:
irc.reply('Not connected!!', prefixNick = False)
return
if conn.rconState == RconStatus.IDLE:
conn.rconCommands.put('content select all')
conn.rconCommands.put('content upgrade')
conn.rconCommands.put('content download')
conn.rconNick = msg.nick
conn.rconState = RconStatus.ACTIVE
command = conn.rconCommands.get()
resultdict = utils.RconResults({
'irc':irc,
'succestext':None,
'command':command,
'results':Queue.Queue()
})
conn.rconResults[conn.rconNick] = resultdict
conn.logger.debug('>>--DEBUG--<< Sending rcon: %s' % command)
conn.send_packet(AdminRcon, command = command)
else:
message = 'Sorry, still processing previous rcon command'