forked from FAForever/server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFAGamesServerThread.py
More file actions
executable file
·1791 lines (1361 loc) · 76.5 KB
/
FAGamesServerThread.py
File metadata and controls
executable file
·1791 lines (1361 loc) · 76.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#-------------------------------------------------------------------------------
# Copyright (c) 2014 Gael Honorez.
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the GNU Public License v3.0
# which accompanies this distribution, and is available at
# http://www.gnu.org/licenses/gpl.html
#
# 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.
#-------------------------------------------------------------------------------
from PySide.QtCore import SIGNAL, SLOT, QTimer, QObject
from PySide import QtCore, QtNetwork
from PySide.QtSql import *
from types import *
import string
import time
import socket
from stats import statsFunctions
from stats.playerStatContainer import *
from trueSkill.Player import *
from trueSkill.faPlayer import *
from trueSkill.Rating import *
from trueSkill.Rating import *
from trueSkill.Teams import *
from trueSkill.Team import *
from trueSkill.Player import *
from faPackets import Packet
import json
import logging
from config import config
logger = logging.getLogger(__name__)
from proxy import proxy
from functools import wraps
proxyServer = QtNetwork.QHostAddress("127.0.0.1")
def timed(f):
@wraps(f)
def wrapper(*args, **kwds):
start = time.time()
result = f(*args, **kwds)
elapsed = (time.time() - start) * 1000
if elapsed > 20 :
logger.info("%s took %s ms to finish" % (f.__name__, str(elapsed)))
return result
return wrapper
class FAGameThread(QObject):
'''
FA game server thread spawned upon every incoming connection to
prevent collisions.
'''
def __init__(self, socket, parent=None):
super(FAGameThread, self).__init__(parent)
self.log = logging.getLogger(__name__)
self.log.debug("Incoming game socket started")
self.initTime = time.time()
self.initDone = False
self.udpToServer = 0
self.connectedTo = []
self.forcedConnections = {}
self.sentConnect = {}
self.forcedJoin = None
self.proxies = {}
self.proxyNotThrough = True
self.noSocket = False
self.player = None
self.parent = parent
self.logGame = "\t"
self.tasks = None
self.game = None
self.packetCount = 0
self.proxyConnection = []
self.socket = QtNetwork.QTcpSocket(self)
self.socket.setSocketOption(QtNetwork.QTcpSocket.KeepAliveOption, 1)
self.socket.disconnected.connect(self.disconnection)
self.socket.error.connect(self.displayError)
self.socket.stateChanged.connect(self.stateChange)
if self.socket.setSocketDescriptor(socket) == False :
self.log.debug("awful error : Socket descriptor not set")
self.socket.abort()
return
if self.socket.state() == 3 and self.socket.isValid() :
self.crappyPorts={}
self.lastUdpPacket = {}
self.udpTimeout = 0
self.missedUdpFrom = {}
self.triedToConnect = []
self.dontSetMorePortPlease = False
self.JoinGameDone = False
#PINGING
self.initPing = True
self.ponged = False
self.missedPing = 0
self.pingTimer = QTimer(self)
self.pingTimer.timeout.connect(self.ping)
self.headerSizeRead = False
self.headerRead = False
self.chunkSizeRead = False
self.fieldTypeRead = False
self.fieldSizeRead = False
self.blockSize = 0
self.fieldSize = 0
self.chunkSize = 0
self.fieldType = 0
self.chunks = []
self.socket.readyRead.connect(self.readData)
self.testUdp = False
self.delaySkipped = False
if self.parent.db.isOpen() == False :
self.parent.db.open()
self.canConnectToHost = False
self.lastUpdate = None
self.gamePort = 6112
self.player = None
self.infoDelayed = False
self.connected = 1
self.data = ''
self.addData = False
self.addedData = 0
self.tryingconnect = 0
self.lobby = None
ip = 0
if self.noSocket == False :
ip = self.socket.peerAddress().toString()
# the player is not known, we search for him.
self.player = self.parent.listUsers.findByIp(ip)
if self.player != None and self.noSocket == False :
##self.log.debug("found player !")
self.player.gameThread = self
# reset the udpPacket from server state
self.player.setReceivedUdp(False)
self.player.setPort = False
self.player.connectedToHost = False
self.player.resetUdpPacket()
self.gamePort = int(self.player.getGamePort())
self.lobby = self.player.getLobbyThread()
strlog = ("%s\t" % str(self.player.getLogin()))
self.logGame = strlog
for player in self.parent.listUsers.getAllPlayers() :
if player != None :
if player.getLogin() == self.player.getLogin() :
#we check if there is already a connection socket to a game.
oldsocket = player.getGameSocket()
if oldsocket != None :
if socket.state() == 3 and socket.isValid() :
socket.abort()
player.setGameSocket(0)
# We set the curremt game Socket.
self.player.setGameSocket(self.socket)
self.player.setWantGame(False)
else :
self.log.warning("No player found for this IP : " + str(self.socket.peerAddress().toString()))
self.socket.abort()
return
if self.noSocket == False :
self.tasks = QTimer(self)
self.tasks.timeout.connect(self.doTask)
self.tasks.start(200)
else :
self.socket.abort()
def containsAny(self, str, set):
"""Check whether 'str' contains ANY of the chars in 'set'"""
return 1 in [c in str for c in set]
def sendToRelay(self, action, commands):
''' send a command to the relay server. The relay server is inside the FAF lobby. It process & relay these messages to FA itself.'''
message = {}
message["key"] = action
message["commands"] = commands
block = QtCore.QByteArray()
out = QtCore.QDataStream(block, QtCore.QIODevice.ReadWrite)
out.setVersion(QtCore.QDataStream.Qt_4_2)
out.writeUInt32(0)
out.writeQString(json.dumps(message))
out.device().seek(0)
out.writeUInt32(block.size() - 4)
self.bytesToSend = block.size() - 4
if hasattr(self, "socket") :
try:
if self.socket :
if self.socket.isValid() and self.socket.state() == 3 :
if self.socket.write(block) == -1 :
self.socket.abort()
else :
self.socket.abort()
else :
self.socket.abort()
except:
if self.tasks is not None:
self.tasks.stop()
self.pingTimer.stop()
def readData(self):
''' Our standard protocol. The FA protocol is now decoded by the lobby itself. Easier to handle that way.'''
if self.socket.isValid() :
if self.socket.bytesAvailable() == 0 :
return
ins = QtCore.QDataStream(self.socket)
ins.setVersion(QtCore.QDataStream.Qt_4_2)
while ins.atEnd() == False :
if self.noSocket == False and self.socket.isValid() :
if self.blockSize == 0:
if self.noSocket == False and self.socket.isValid() :
if self.socket.bytesAvailable() < 4:
return
self.blockSize = ins.readUInt32()
else :
return
if self.noSocket == False and self.socket.isValid() :
if self.socket.bytesAvailable() < self.blockSize:
return
else :
return
action = ins.readQString()
self.handleAction2(action)
self.blockSize = 0
else :
return
return
@timed
def doTask(self):
''' Do task run regularly to check if some stuff needs to happen when players are inside the FA lobby.'''
now = time.time()
if now - self.initTime > 60 * 60 :
self.socket.abort()
self.tasks.stop()
return
if self.forcedJoin :
if now - self.forcedJoin > 5 :
self.game.log.debug("%s going to join through proxy" % (self.player.getLogin()))
self.joinThroughProxy()
forceConnection = []
for forcedPlayer in self.forcedConnections :
if now - self.forcedConnections[forcedPlayer] > 10 :
forceConnection.append(forcedPlayer)
action = None
action = self.player.getAction()
for forcedPlayer in forceConnection :
if action != "HOST":
self.connectThroughProxy(forcedPlayer)
if self.game:
self.game.log.debug("%s must connect through proxy to %s " % (forcedPlayer.getLogin(), self.player.getLogin()))
sentConnect = []
for sentPlayer in self.sentConnect :
if now - self.sentConnect[sentPlayer] > 15 :
sentConnect.append(sentPlayer)
for sentPlayer in sentConnect:
del self.sentConnect[sentPlayer]
if action != "HOST":
self.connectThroughProxy(sentPlayer)
if self.game:
self.game.log.debug("%s must connect through proxy to %s (not connected after 10 sec of ConnectToPeer) " % (sentPlayer.getLogin(), self.player.getLogin()))
if self.noSocket == False :
# check if the player must connect to someone
if self.player != None and self.noSocket == False :
if self.game != None :
checkConnect = False
checkDisconnect = False
getUdp = False
state = ""
state = self.game.getLobbyState()
if state != "playing" :
# first we stop the timer
self.tasks.stop()
if self.player.setPort == False and now - self.initTime > 3 :
# after 3 seconds we still have nothing, we force it.
self.player.setPort = True
if self.player.setPort == False and self.dontSetMorePortPlease == False and self.initDone == True and self.packetCount <= 10:
self.sendPacketForNAT()
self.tasks.start(200)
getUdp = self.player.getReceivedUdp()
if getUdp == True and self.testUdp == False :
# we must now test both socket
address = QtNetwork.QHostAddress(str(self.player.getIp()))
if self.player.getGamePort() != self.player.getUdpPacketPort() :
self.parent.parent.udpSocket.writeDatagram("\x08PACKET_RECEIVED %i" % self.player.getGamePort(), address, self.player.getGamePort())
self.parent.parent.udpSocket.writeDatagram("\x08PACKET_RECEIVED %i" % self.player.getUdpPacketPort(), address, self.player.getUdpPacketPort())
else :
self.parent.parent.udpSocket.writeDatagram("\x08PACKET_RECEIVED %i" % self.player.getGamePort(), address, self.player.getGamePort())
self.testUdp = True
if action == "HOST" :
for playerInGame in self.game.getPlayers():
if str(playerInGame.game) != str(self.game.getuuid()):
#self.log.debug(self.logGame + "ERROR : This player is not in the game : " + playerInGame.getLogin())
self.game.addToDisconnect(playerInGame)
self.game.removePlayer(playerInGame)
self.game.removeFromAllPlayersToConnect(playerInGame)
self.game.removeTrueSkillPlayer(playerInGame)
self.player.connectedToHost = True
if self.player.setPort == True :
self.game.setGameHostPort(self.player.getGamePort())
self.game.receiveUdpHost = True
if self.canConnectToHost == True and self.player.setPort == True :
if self.game.receiveUdpHost == True and self.player.connectedToHost == False :
self.connectToHost()
if self.player.setPort == True and self.player.isConnectedToHost() :
checkConnect = self.game.isConnectRequired(self.player)
checkDisconnect = self.game.isDisconnectRequired(self.player)
if checkConnect :
self.connectToPeers()
if checkDisconnect :
self.disconnectToPeers()
# and we restart it.
self.tasks.start(200)
else :
self.tasks.stop()
else :
if self in self.parent.recorders :
if self.tasks != None :
self.tasks.stop()
else :
if self in self.parent.recorders :
if self.tasks != None :
self.tasks.stop()
def ping(self):
''' Ping the relay server to check if the player is still there.'''
if hasattr(self, "socket"):
if self.ponged is False:
if self.missedPing > 2:
self.log.debug(self.logGame + " Missed 2 ping - Removing user IP " + self.socket.peerAddress().toString())
if self.tasks is not None:
self.tasks.stop()
self.pingTimer.stop()
if self in self.parent.recorders:
self.socket.abort()
else:
self.sendToRelay("ping", [])
self.missedPing = self.missedPing + 1
else:
self.sendToRelay("ping", [])
self.ponged = False
self.missedPing = 0
def idleState(self):
''' game is waiting for init
we find in what game the player is
if he is hosting, the lobby will be in "idle" state, and we add his IP '''
action = self.player.getAction()
if action == "HOST":
self.game = self.parent.games.getGameByUuid(self.player.getGame())
if self.game is not None and str(self.game.getuuid()) == str(self.player.getGame()):
self.game.setLobbyState("Idle")
self.game.setHostIP(self.player.getIp())
self.game.setHostLocalIP(self.player.getLocalIp())
self.game.proxy = proxy.proxy()
strlog = ("%s.%s.%s\t" % (str(self.player.getLogin()), str(self.game.getuuid()), str(self.game.getGamemod())))
self.logGame = strlog
initmode = self.game.getInitMode()
self.initSupcom(initmode)
else:
# No game found. I don't know why we got a connection, but we don't want it.
if self.noSocket is False:
self.socket.abort()
self.log.debug("HOST - Can't find game")
if self.player:
if self.player.getLobbyThread():
self.player.getLobbyThread().sendJSON(dict(command="notice", style="kill"))
elif action == "JOIN":
self.game = self.parent.games.getGameByUuid(self.player.getGame())
if self.game is not None and str(self.game.getuuid()) == str(self.player.getGame()):
if self.player.getLogin() in self.game.packetReceived:
self.packetReceived[self.player.getLogin()] = []
for otherPlayer in self.game.getPlayers():
if self.player.getAddress() in otherPlayer.UDPPacket:
otherPlayer.UDPPacket[self.player.getAddress()] = 0
strlog = ("%s.%s.%s\t" % (str(self.player.getLogin()), str(self.game.getuuid()), str(self.game.getGamemod())))
self.logGame = strlog
initmode = 0
initmode = self.game.getInitMode()
self.initSupcom(initmode)
else:
# game not found, so still initialize FA to avoid "black screen" errors reports in the forum.
self.initSupcom(0)
if self.noSocket is False:
self.socket.abort()
self.log.debug("JOIN - Can't find game")
# But we tell the lobby that FA must be killed.
self.lobby.sendJSON(dict(command="notice", style="kill"))
else:
# We tell the lobby that FA must be killed.
self.lobby.sendJSON(dict(command="notice", style="kill"))
self.log.debug("QUIT - No player action :(")
def lobbyState(self):
'''Player is in lobby state. We need to tell him to connect to the host, or create the lobby itself if he is the host.'''
playeraction = ''
playeraction = self.player.getAction()
if playeraction == "HOST":
map = self.game.getMapName()
self.createLobby(str(map))
#if the player is joigning, we connect him to host.
elif playeraction == "JOIN":
plist = []
for player in self.game.getPlayers():
plist.append(player.getLogin())
self.game.addToConnect(self.player)
self.canConnectToHost = True
def handleAction2(self, action):
''' This code is starting to get messy... This function was created when the FA protocol was moved to the lobby itself. '''
message = json.loads(action)
self.handleAction(message["action"], message["chuncks"])
def handleAction(self, key, values):
''' The big code that handle everything that can happen to a game or a player in a game '''
try:
if key == 'ping':
return
elif key == 'Disconnected':
return
elif key == 'pong':
self.ponged = True
return
elif key == 'Connected' :
uid = int(values[0])
self.handleConnected(uid)
elif key == 'Score':
pass
elif key == 'Bottleneck':
pass
elif key == 'BottleneckCleared':
pass
elif key == 'Desync':
self.game.addDesync()
elif key == 'ProcessNatPacket':
self.handleNatPacket(values)
elif key == 'GameState':
state = values[0]
self.handleGameState(state)
# game Option changing !
elif key == 'GameOption':
if values[0] in self.game.gameOptions :
self.game.gameOptions[values[0]] = values[1]
if values[0] == "Slots" :
self.game.maxPlayer = values[1]
if values[0] == 'ScenarioFile' :
raw = "%r"%values[1]
path = raw.replace('\\', '/')
map = str(path.split('/')[2]).lower()
curMap = ''
curMap = self.game.getGameMap()
if curMap != map :
self.game.setGameMap(map)
self.sendGameInfo()
elif values[0] == 'Victory' :
self.game.setGameType(values[1])
elif key == 'GameMods':
# find infos about mods...
if values[0] == "activated" :
if values[1] == 0 :
self.game.mods = {}
if values[0] == "uids" :
self.game.mods = {}
query = QSqlQuery(self.parent.db)
for uid in values[1].split():
query.prepare("SELECT name FROM table_mod WHERE uid = ?")
query.addBindValue(uid)
query.exec_()
if query.size() > 0:
query.first()
self.game.mods[uid] = str(query.value(0))
else:
self.game.mods[uid] = "Unknown sim mod"
elif key == 'connectedToHost':
# player is connect to the host!
self.player.connectedToHost = True
elif key == 'PlayerOption':
action = self.player.getAction()
if action == "HOST":
self.game.clearAIs()
for i, value in enumerate(values):
atype, name, place, resultvalue = self.parsePlayerOption(value)
if action == "HOST" :
if not ":" in name :
self.game.placePlayer(name, place)
if atype == "faction" :
self.game.setPlayerFaction(place, resultvalue)
elif atype == "color" :
self.game.setPlayerColor(place, resultvalue)
elif atype == "team" :
team = resultvalue-1
if ":" in name :
self.addAi(name, place, team)
else :
self.game.assignPlayerToTeam(name, team)
self.sendGameInfo()
elif key == 'GameResult':
''' Preparing the data for recording the game result'''
playerResult = self.game.getPlayerAtPosition(int(values[0]))
if playerResult != None :
result = values[1]
faresult = None
score = 0
if result.startswith("autorecall") or result.startswith("recall") or result.startswith("defeat") or result.startswith("victory") or result.startswith("score") or result.startswith("draw"):
split = result.split(" ")
faresult = split[0]
if len(split) > 1 :
score = int(split[1])
self.game.addResultPlayer(playerResult, faresult, score)
if faresult != "score":
if hasattr(self.game, "noStats"):
if self.game.noStats == False:
self.registerTime(playerResult)
else:
self.registerTime(playerResult)
elif key == 'Stats':
# stats never worked that well...
pass
elif key == 'Chat':
# We should log that....
pass
elif key == 'OperationComplete':
# This is for coop!
self.log.debug(self.logGame + "OperationComplete: "+ str(values))
self.log.debug(self.logGame + "OperationComplete: "+ str(values[1]))
if self.game.isValid():
mission = -1
if int(values[0]) == 1:
self.log.debug(self.logGame + "Operation really Complete!")
query = QSqlQuery(self.parent.db)
query.prepare("SELECT id FROM coop_map WHERE filename LIKE '%/"+self.game.getGameMap()+".%'")
query.exec_()
if query.size() > 0:
query.first()
mission = int(query.value(0))
else:
self.log.debug(self.logGame + "can't find coop map " + str(self.game.getGameMap()))
if mission != -1:
query.prepare("INSERT INTO `coop_leaderboard`(`mission`, `gameuid`, `secondary`, `time`) VALUES (?,?,?,?);")
query.addBindValue(mission)
query.addBindValue(self.game.getuuid())
query.addBindValue(int(values[1]))
query.addBindValue(str(values[2]))
if not query.exec_():
self.log.warning(self.logGame + str(query.lastError()))
self.log.warning(self.logGame + query.executedQuery())
else:
self.log.debug(self.logGame + self.game.getInvalidReason())
elif key == 'ArmyCalled':
# this is for Galactic War!
playerResult = self.game.getPlayerAtPosition(int(values[0]))
if playerResult != None :
group = values[1]
query = QSqlQuery(self.parent.db)
query.prepare("DELETE FROM `galacticwar`.`reinforcements_groups` WHERE `userId` = (SELECT id FROM `faf_lobby`.`login` WHERE login.login = ?) AND `group` = ?")
query.addBindValue(playerResult)
query.addBindValue(group)
if query.exec_():
self.game.deleteGroup(group, playerResult)
else :
self.log.error(self.logGame + "Unknown key")
self.log.error(self.logGame + key)
except :
self.log.exception(self.logGame + "Something awful happened in a game thread !")
def handleConnected(self, uid):
''' The player is officially connected to another'''
for player in self.parent.listUsers.players:
playerUid = player.getId()
if playerUid == uid:
if self.game:
self.game.log.debug("%s Connected to : %s"% (player.getLogin(), self.player.getLogin()))
if playerUid == self.game.getHostId():
self.forcedJoin = None
if player in self.forcedConnections:
if self.game:
self.game.log.debug("Removed %s from forced connection of %s" %(player.getLogin(), self.player.getLogin()))
del self.forcedConnections[player]
if player in self.sentConnect:
if self.game:
self.game.log.debug("Removed %s from sent connection of %s" %(player.getLogin(), self.player.getLogin()))
del self.sentConnect[player]
def handleNatPacket(self, values):
''' Nat packets between players'''
state = ''
state = self.game.getLobbyState()
if state != "playing" :
if "PACKET_RECEIVED" in values[1] :
if self.dontSetMorePortPlease == False :
splits = values[1].split(" ")
port = int(splits[len(splits)-1])
if self.player.getLocalGamePort() == port and self.packetCount >= 4 :
self.dontSetMorePortPlease = True
elif self.packetCount < 2 :
self.sendPacketForNAT()
return
self.player.setGamePort(port)
self.setPort = True
self.player.setPort = True
json = {}
json["debug"] = ("port used : %i" % port)
for otherPlayer in self.game.getPlayers():
if self.player.getAddress() in otherPlayer.UDPPacket:
otherPlayer.UDPPacket[self.player.getAddress()] = 0
self.lobby.sendJSON(json)
if self.player.getAction() == "HOST" :
self.game.setGameHostPort(port)
elif "PLAYERID" in values[1] :
playerName = " ".join(values[1].split()[2:])
if hasattr(self.game, "getLoginName"):
playerName = self.game.getLoginName(playerName)
thatPlayer = self.parent.listUsers.findByName(playerName)
if thatPlayer != 0 :
hisAdress = thatPlayer.getAddress()
addressIp = values[0].split(":")[0]
address = QtNetwork.QHostAddress(addressIp)
if address.protocol() == 0 :
self.crappyPorts[playerName] = values[0]
else :
self.log.debug(self.logGame + "bad network address")
self.game.receivedPacket(playerName, self.player.getLogin())
elif "ASKREPLY" in values[1] :
playerName = " ".join(values[1].split()[1:])
if hasattr(self.game, "getLoginName"):
playerName = self.game.getLoginName(playerName)
thatPlayer = self.parent.listUsers.findByName(playerName)
if thatPlayer != 0 :
hisAdress = thatPlayer.getAddress()
if hisAdress != values[0] :
addressIp = values[0].split(":")[0]
address = QtNetwork.QHostAddress(addressIp)
if address.protocol() == 0 :
self.crappyPorts[playerName] = values[0]
else :
self.log.debug(self.logGame + "bad network address")
if self.game.hasReceivedPacketFrom(playerName, self.player.getLogin()) and self.game.hasReceivedPacketFrom(self.player.getLogin(), playerName) :
#That player ask for a reply, but he already get our id, we ignore his request.
return
now = time.time()
if not str(values[0]) in self.lastUdpPacket :
self.lastUdpPacket[str(values[0])] = now
else :
if now - self.lastUdpPacket[str(values[0])] < 1 :
return
self.lastUdpPacket[str(values[0])] = now
playerUid = self.player.getId()
playerName = self.player.getLogin()
if hasattr(self.game, "getPlayerName"):
playerName = self.game.getPlayerName(self.player)
datasUdp = "/PLAYERID " + str(playerUid) + " " + playerName
self.sendToRelay("SendNatPacket", [str(values[0]), datasUdp])
def handleGameState(self, state):
''' Handle game states - launch,....'''
if state == 'Idle':
#FA has just connected to us
self.idleState()
elif state == 'Lobby':
# waiting for command
self.lobbyState()
elif state == 'Launching':
# game launch, the user is playing !
action = self.player.getAction()
if self.tasks :
self.tasks.stop()
if self.player.getAction() == "HOST" :
self.game.numPlayers = self.game.getNumPlayer()
self.game.setLobbyState("playing")
if hasattr(self.game, "noStats"):
if self.game.noStats == False:
self.fillGameStats()
else:
self.fillGameStats()
self.game.fixPlayerPosition()
result = self.game.recombineTeams()
self.fillPlayerStats(self.game.getPlayers())
self.fillAIStats(self.game.AIs)
for player in self.game.getPlayers() :
player.setAction("PLAYING")
player.resetUdpPacket()
if not all((i.count())==self.game.finalTeams[0].count() for i in self.game.finalTeams) :
self.game.setInvalid("All Teams don't the same number of players.")
if len(self.game.finalTeams) == (len(self.game.AIs) + self.game.getNumPlayer()) :
if self.game.getNumPlayer() > 3 :
self.game.ffa = True
# ffa doesn't count for that much in rating.
self.game.partial = 0.25
self.game.setTime()
self.sendGameInfo()
if self.game.getGameType() != 0 and self.game.getGamemod() != "coop" :
self.game.setInvalid("Only assassination mode is ranked")
elif self.game.gameOptions["FogOfWar"] != "explored" :
self.game.setInvalid("Fog of war not activated")
elif self.game.gameOptions["CheatsEnabled"] != "false" :
self.game.setInvalid("Cheats were activated")
elif self.game.gameOptions["PrebuiltUnits"] != "Off" :
self.game.setInvalid("Prebuilt was activated")
elif self.game.gameOptions["NoRushOption"] != "Off" :
self.game.setInvalid("No rush games are not ranked")
elif self.game.gameOptions["RestrictedCategories"] != 0 :
self.game.setInvalid("Restricted games are not ranked")
elif len(self.game.mods) > 0 :
for uid in self.game.mods:
if not self.isModRanked(uid):
if uid == "e7846e9b-23a4-4b95-ae3a-fb69b289a585" :
if not "scca_coop_e02" in self.game.getGameMap().lower():
self.game.setInvalid("Sim mods are not ranked")
else:
self.game.setInvalid("Sim mods are not ranked")
query = QSqlQuery(self.parent.db)
query.prepare("UPDATE `table_mod` SET `played`= `played`+1 WHERE uid = ?")
query.addBindValue(uid)
query.exec_()
for playerTS in self.game.getTrueSkillPlayers() :
if playerTS.getRating().getMean() < -1000 :
self.game.setInvalid("You are playing with a smurfer.")
def doEnd(self):
''' bybye player :('''
self.player.setGameSocket(None)
try :
if hasattr(self, "game"):
if self.game != None :
#check if the game was started
if self.game.getLobbyState() == "playing" :
curplayers = self.game.getNumPlayer()
allScoreHere = False
if hasattr(self.game, "isAllScoresThere") :
allScoreHere = self.game.isAllScoresThere()
if curplayers == 0 or allScoreHere == True :
self.game.setLobbyState("closed")
self.sendGameInfo()
if hasattr(self.game, "noStats"):
if self.game.noStats == False:
query = QSqlQuery(self.parent.db)
queryStr = ("UPDATE game_stats set `EndTime` = NOW() where `id` = " + str(self.game.getuuid()))
query.exec_(queryStr)
else:
query = QSqlQuery(self.parent.db)
queryStr = ("UPDATE game_stats set `EndTime` = NOW() where `id` = " + str(self.game.getuuid()))
query.exec_(queryStr)
if self.game.getDesync() > 20 :
self.game.setInvalid("Too many desyncs")
if hasattr(self.game, "noStats"):
if self.game.noStats == False:
self.registerScore(self.game.gameResult)
else:
self.registerScore(self.game.gameResult)
self.game.specialEnding(self.log, self.parent.db, self.parent.listUsers)
for playerTS in self.game.getTrueSkillPlayers() :
name = playerTS.getPlayer()
for player in self.parent.listUsers.getAllPlayers() :
if player != None :
if str(name) == player.getLogin() :
for conn in self.parent.parent.FALobby.recorders :
conn.sendJSON(self.parent.parent.jsonPlayer(player))
self.parent.games.removeGame(self.game)
self.game = None
except :
self.log.exception("Something awful happened in a game thread (ending) !")
def ejectPlayer(self, player):
self.sendToRelay("EjectPlayer", [int(player.getId())])
def initSupcom(self, rankedMode):
''' We init FA with the right infos about the player.'''
port = None
login = None
uid = None
if self.game is None:
text = "You were unable to connect to the host because he has left the game."