-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.py
2523 lines (1891 loc) · 88.1 KB
/
server.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
from bottle import route, run, static_file, template, request, abort, redirect, error
from bottle import ERROR_PAGE_TEMPLATE
from websocket_server import WebsocketServer, WebSocketHandler
from threading import Thread, Lock
from time import sleep
from json import loads, dumps
from json.decoder import JSONDecodeError
from datetime import datetime, timedelta
from os import urandom, listdir, mkdir, getcwd, chdir
from os.path import exists
from base64 import b64encode
from typing import List, Dict, Tuple
if 'server' in listdir('.'):
chdir('server')
class Debug:
Debug = 1
PythonAndJSConnections = 0
ClientTriesToLogin = 0
SpectatorInit = 0
JSClientRestore = 0
GameEngineMessage = 0
JSResittingRestore = 0
MessageFromPythonToJS = 0
MessageFromTableToSpectator = 0
MessageReceivedFromJS = 0
MessageReceivedFromSpectator = 0
KotlinDebug = 0
Send = 0
ClientLeft = 0
Errors = 1
if PythonAndJSConnections:
@staticmethod
def connect(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def connect(*args, **kwargs):
pass
if ClientTriesToLogin:
@staticmethod
def login(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def login(*args, **kwargs):
pass
if SpectatorInit:
@staticmethod
def spectator_init(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def spectator_init(*args, **kwargs):
pass
if JSClientRestore:
@staticmethod
def js_restore(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def js_restore(*args, **kwargs):
pass
if GameEngineMessage:
@staticmethod
def engine_msg(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def engine_msg(*args, **kwargs):
pass
if JSResittingRestore:
@staticmethod
def resitting(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def resitting(*args, **kwargs):
pass
if MessageFromPythonToJS:
@staticmethod
def py_to_js(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def py_to_js(*args, **kwargs):
pass
if MessageFromTableToSpectator:
@staticmethod
def tb_to_sp(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def tb_to_sp(*args, **kwargs):
pass
if MessageReceivedFromJS:
@staticmethod
def from_js(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def from_js(*args, **kwargs):
pass
if MessageReceivedFromSpectator:
@staticmethod
def from_sp(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def from_sp(*args, **kwargs):
pass
if KotlinDebug:
@staticmethod
def from_kt(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def from_kt(*args, **kwargs):
pass
if Send:
@staticmethod
def send(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def send(*args, **kwargs):
pass
if ClientLeft:
@staticmethod
def client_left(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def client_left(*args, **kwargs):
pass
if Errors:
@staticmethod
def error(*args, **kwargs):
print(*args, **kwargs)
else:
@staticmethod
def error(*args, **kwargs):
pass
class AbstractClient:
class ID:
Unregistered = 'un'
Python = 'py'
JavaScript = 'js'
Kotlin = 'kt'
Replay = 'rp'
Table = 'tb'
Spectator = 'sp'
GameHandler = 'gh'
GameEngine = 'ge'
def __init__(self, _id: int, name: str, handler: WebSocketHandler):
self.id: int = _id # Это внутренний ID клиента, присваиваемый сервером
self.name: str = name
self.handler: WebSocketHandler = handler
def finish(self):
try:
self.handler.finish()
except KeyError:
Debug.error(f'Key error possibly double deleting id = {self.id}, name = {self.name}')
def send_raw(self, message: str) -> None:
try:
Debug.send(f'Send to {self.id}: {message}')
self.handler.send_message(message)
except BrokenPipeError:
Debug.error(f'Broken pipe error send raw id = {self.id}, name = {self.name}')
def send(self, obj: dict) -> None:
try:
msg = dumps(obj)
Debug.send(f'Send to {self.id}: {msg}')
self.handler.send_message(msg)
except BrokenPipeError:
Debug.error(f'Broken pipe error send id = {self.id}, name = {self.name}')
def receive(self, srv: 'Server', message: str, client: dict) -> None:
raise NotImplementedError('Method "receive" is not implemented in derived class')
def left(self, srv: 'Server') -> None:
raise NotImplementedError('Method "left" is not implemented in derived class')
class GameEngineClient(AbstractClient):
OnlyClient = None
def __init__(self, _id: int, handler: WebSocketHandler):
super().__init__(_id, AbstractClient.ID.GameEngine, handler)
if GameEngineClient.OnlyClient is not None:
raise ValueError("Game engine already exists")
GameEngineClient.OnlyClient = self
def receive(self, srv: 'Server', message: str, client: dict):
pass
def left(self, srv: 'Server') -> None:
del srv.game_engine
srv.game_engine = None
GameEngineClient.OnlyClient = None
Debug.client_left('DEL GAME ENGINE')
class GameHandlerClient(AbstractClient):
def __init__(self, _id: int, json_message: dict, handler: WebSocketHandler):
super().__init__(_id, AbstractClient.ID.GameHandler, handler)
self.game_id = json_message['id']
self.quick_game_name = ''
if json_message['game type'] == 'tournament':
self.is_tournament = True
self.name = json_message['name']
self.total_players = json_message['total players']
self.initial_stack = json_message['initial stack']
self.table_seats = json_message['table seats']
self.password = json_message['password']
self.players_left = json_message['players left']
elif json_message['game type'] == 'quick':
self.is_tournament = False
self.name = json_message['name'] # name of the player who plays this quick game
self.is_registration_started: bool = False
self.is_game_started: bool = False
self.started_time: datetime = datetime.now()
self.replays = []
self.tb_clients: Dict[str, TableClient] = dict()
self.waiting_js_clients: Dict[str, JavaScriptClient] = dict()
def receive(self, srv: 'Server', message: str, client: dict) -> None:
Debug.engine_msg(f'GameHandler {self.game_id} said: {message}')
json_message = loads(message)
if json_message['type'] == 'start registration':
self.is_registration_started = True
elif json_message['type'] == 'start game':
self.is_game_started = True
self.is_registration_started = False
self.started_time = datetime.now()
elif json_message['type'] == 'end game':
self.is_game_started = False
self.is_registration_started = False
if self.is_tournament:
total_tables = len(self.replays)
total_players = self.total_players
name = self.name
total_hands = sum(rep[1] for rep in self.replays)
if name == '':
game_path = (str(self.started_time)[:-7].replace(' ', '_').replace(':', '-') +
' %s %s %s' % (total_tables, total_players, total_hands))
else:
game_path = (str(self.started_time)[:-7].replace(' ', '_').replace(':', '-') +
' %s %s %s %s' % (total_tables, total_players, total_hands, name))
tournament_path = 'files/replay/poker/games/' + game_path
chat_messages_path = 'files/replay/poker/chat/' + game_path
mkdir(tournament_path)
mkdir(chat_messages_path)
for table_num, hands, hands_history, chat_history in self.replays:
table_folder = '/%s %s' % (table_num, hands)
table_path = tournament_path + table_folder
chat_path = chat_messages_path + table_folder
mkdir(table_path)
open(chat_path, 'w').write(ReplayClient.dump_replay(chat_history))
for num, hand in enumerate(hands_history):
open(table_path + '/%s' % (num,), 'w').write(ReplayClient.dump_replay(hand))
self.replays = []
self.finish_all_clients()
self.finish()
elif json_message['type'] == 'broken':
self.is_game_started = False
self.is_registration_started = False
self.replays = []
self.finish_all_clients()
self.finish()
elif json_message['type'] == 'update players':
self.players_left = json_message['left']
def has_player(self, name: str) -> bool:
for table in self.tb_clients.values():
table: TableClient
for player in table.players:
if player.name == name:
return True
return False
def finish_all_clients(self):
for curr in list(self.tb_clients.values()):
for curr_sp in curr.spectators:
curr_sp.finish()
for curr_py in curr.players:
if curr_py.connected_js is not None:
curr_py.connected_js.finish()
curr_py.finish()
curr.finish()
self.tb_clients = dict()
def left(self, srv: 'Server') -> None:
del srv.gh_clients[self.game_id]
Debug.client_left('DEL GAME HANDLER')
self.finish_all_clients()
class UnregisteredClient(AbstractClient):
def __init__(self, _id: int, handler: WebSocketHandler):
super().__init__(_id, AbstractClient.ID.Unregistered, handler)
def receive(self, srv: 'Server', message: str, client: dict) -> None:
Debug.login(f'Unregistered client {self.id} said: {message}')
try:
json_message = loads(message)
client_id = json_message['type']
name = ''
if client_id != AbstractClient.ID.Kotlin:
name = json_message['name']
game_id = ''
if (client_id == AbstractClient.ID.JavaScript or
client_id == AbstractClient.ID.Table or
client_id == AbstractClient.ID.Spectator):
game_id = json_message['id']
if client_id == AbstractClient.ID.Python:
game_id = json_message['game id']
except JSONDecodeError:
self.send(dumps({'type': 'bad login'}))
return
if client_id == AbstractClient.ID.Replay:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as replay client')
rp_client = ReplayClient(self.id, name, self.handler)
client['client'] = rp_client
srv.rp_clients += [rp_client]
elif client_id == AbstractClient.ID.Kotlin:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as kotlin client')
kt_client = KotlinClient(self.id, name, self.handler)
client['client'] = kt_client
srv.kt_clients += [kt_client]
elif client_id != AbstractClient.ID.GameEngine and srv.game_engine is None:
Debug.login(f'Unregistered client {self.id} classified not as game engine client')
self.send({'type': 'finish', 'msg': 'Game server is offline.'})
self.finish()
elif client_id == AbstractClient.ID.GameHandler:
Debug.login(f'Unregistered client {self.id} classified as game handler client')
gh_client = GameHandlerClient(self.id, json_message, self.handler)
client['client'] = gh_client
srv.gh_clients[json_message['id']] = gh_client
if not gh_client.is_tournament:
for kt_client in srv.kt_clients:
if kt_client.name == gh_client.name:
kt_client.send({'type': 'quick game is ready'})
break
elif client_id == AbstractClient.ID.JavaScript and name in srv.js_clients:
Debug.login(f'Unregistered client {self.id} classified as already exist javascript client')
self.send({'type': 'finish', 'msg': 'Player with this name already exists.'})
self.finish()
elif client_id == AbstractClient.ID.Python:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as python client')
js_client = srv.js_clients[name]
tournament_id = json_message['id']
py_client = PythonClient(self.id, tournament_id, game_id, js_client, self.handler)
client['client'] = py_client
srv.py_clients[name] = py_client
elif client_id == AbstractClient.ID.Table:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as table client')
tb_client = TableClient(self.id, name, srv.gh_clients[game_id], self.handler)
client['client'] = tb_client
elif client_id == AbstractClient.ID.Spectator and name in srv.gh_clients[game_id].tb_clients:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as spectator client')
sp_client = SpectatorClient(self.id, name, self.handler)
client['client'] = sp_client
srv.sp_clients += [sp_client]
srv.gh_clients[game_id].tb_clients[name].connect_spectator(sp_client)
elif client_id == AbstractClient.ID.Spectator:
Debug.login(f'Unregistered client {self.id} classified as spectator client trying to watch wrong table')
self.send({'type': 'finish', 'msg': 'Table is not active.'})
self.finish()
elif client_id == AbstractClient.ID.JavaScript and game_id == -1 and \
name in [game.name for game in srv.gh_clients.values() if not game.is_tournament]:
Debug.login(f'Unregistered client {self.id} classified as javascript client connected to quick game')
game = max([game for game in srv.gh_clients.values() if not game.is_tournament and name == game.name])
del srv.unregistered_clients[self.id]
js_client = JavaScriptClient(self.id, name, self.handler)
client['client'] = js_client
game.waiting_js_clients[name] = js_client
srv.js_clients[name] = js_client
game.send({'type': 'add player', 'name': json_message['name']})
elif client_id == AbstractClient.ID.JavaScript and \
not srv.gh_clients[game_id].is_game_started and srv.gh_clients[game_id].is_registration_started:
Debug.login(f'Unregistered client {self.id} classified as javascript client')
game = srv.gh_clients[game_id]
if game.is_tournament and game.password == json_message['password']:
del srv.unregistered_clients[self.id]
js_client = JavaScriptClient(self.id, name, self.handler)
client['client'] = js_client
game.waiting_js_clients[name] = js_client
srv.js_clients[name] = js_client
game.send({'type': 'add player', 'name': json_message['name']})
else:
self.send({'type': 'error', 'msg': 'bad id or password'})
elif client_id == AbstractClient.ID.JavaScript and srv.gh_clients[game_id].is_game_started and \
name in srv.py_clients and srv.py_clients[name].is_disconnected:
Debug.login(f'Unregistered client {self.id} classified as reconnected javascript client')
if json_message['password'] == srv.gh_clients[game_id].password:
del srv.unregistered_clients[self.id]
py_client = srv.py_clients[name]
js_client = JavaScriptClient.restore(self.id, py_client, self.handler)
client['client'] = js_client
srv.js_clients[name] = js_client
else:
self.send({'type': 'error', 'msg': 'bad id or password'})
elif client_id == AbstractClient.ID.GameEngine and srv.game_engine is None:
del srv.unregistered_clients[self.id]
Debug.login(f'Unregistered client {self.id} classified as game engine client')
game_client = GameEngineClient(self.id, self.handler)
client['client'] = game_client
srv.game_engine = game_client
else:
Debug.login(f'Unregistered client {self.id} classified as something wrong')
self.send({'type': 'finish', 'msg': 'You are not in the game.'})
self.finish()
def left(self, srv: 'Server') -> None:
del srv.unregistered_clients[self.id]
Debug.client_left('DEL UNR')
class JavaScriptClient(AbstractClient):
def __init__(self, _id: int, name: str, handler: WebSocketHandler):
super().__init__(_id, name, handler)
self.connected_python: PythonClient = None
@staticmethod
def restore(_id: int, py_client: 'PythonClient', handler: WebSocketHandler) -> 'JavaScriptClient':
new_js = JavaScriptClient(_id, py_client.name, handler)
py_client.reconnect_js(new_js)
return new_js
def receive(self, srv: 'Server', message: str, client: dict) -> None:
Debug.from_js(f'Message from js {self.name}: {message}')
try:
json_message = loads(message)
except JSONDecodeError:
Debug.from_js(f'JSON decode error msg from js {self.name} {message}')
else:
if json_message['type'] == 'decision' and 'text' in json_message:
if self.connected_python.in_decision:
self.connected_python.in_decision = False
self.connected_python.send_raw(json_message['text'])
elif json_message['type'] == 'chat' and 'text' in json_message:
json_message['text'] = f'[Player {self.name}]: {json_message["text"]}'
self.connected_python.connected_table.chat_message(dumps(json_message))
def left(self, srv: 'Server') -> None:
del srv.js_clients[self.name]
if not self.connected_python.connected_table.connected_game.is_tournament:
self.connected_python.connected_table.connected_game.send({'type': 'break'})
elif self.connected_python.connected_table.connected_game.is_game_started:
self.connected_python.connected_js = None
if not self.connected_python.is_busted:
self.connected_python.is_disconnected = True
disconnected_message = dumps({'type': 'disconnected',
'id': self.connected_python.game_id})
self.connected_python.connected_table.cast(disconnected_message)
self.connected_python.connected_table.chat_message(dumps({'type': 'chat',
'text': f'{self.name} disconnected'}))
for msg in reversed(self.connected_python.history):
if loads(msg)['type'] == 'set decision':
self.connected_python.in_decision = False
self.connected_python.send_raw('1')
break
elif loads(msg)['type'] == 'switch decision':
break
elif self.name in [cl.name for cl in srv.py_clients.values()]:
Debug.client_left('SEND HTTP DELETE ' + self.name)
self.connected_python.connected_table.connected_game.send({'type': 'delete', 'name': self.name})
Debug.client_left('DEL JS')
class PythonClient(AbstractClient):
def __init__(self, _id: int, game_id: int, game_handler_id: int,
js_client: JavaScriptClient, handler: WebSocketHandler):
super().__init__(_id, js_client.name, handler)
self.game_id = game_id
self.game_handler_id = game_handler_id
self.history: List[str] = []
self.is_disconnected: bool = False
self.in_decision: bool = False
self.is_busted: bool = False
self.lock: Lock = Lock()
self.connected_table: TableClient = None
self.thinking_time: int = Server.MAX_THINKING_TIME
self.back_counting: int = Server.START_COUNTING_TIME
self.kicked_thinking_time: int = Server.MAX_THINKING_TIME_AFTER_KICK
self.connected_js: JavaScriptClient = js_client
js_client.connected_python = self
Debug.connect(f'connected py and js {self.name}')
def reconnect_js(self, js_client: JavaScriptClient) -> None:
if self.connected_js is not None:
raise ValueError(f'Python client {self.name} already has js client')
if not self.is_disconnected:
raise ValueError(f'Python client {self.name} is not disconnected')
self.connected_js = js_client
js_client.connected_python = self
Debug.js_restore(f'Start restore client {js_client.name} js to py')
with self.lock:
js_client.send({'type': 'reconnect start'})
for msg in self.history:
js_client.send_raw(msg)
Debug.js_restore(f'Restore js client {js_client.name} {msg}')
for chat_msg in self.connected_table.get_last_chat_messages():
js_client.send_raw(chat_msg)
Debug.js_restore(f'Restore chat js client {js_client.name} {msg}')
Debug.js_restore(f'End restore js client {js_client.name}')
js_client.send({'type': 'reconnect end'})
self.is_disconnected = False
self.connected_table.cast(dumps({'type': 'connected', 'id': self.game_id}))
self.connected_table.chat_message(dumps({'type': 'chat', 'text': f'{self.name} connected'}))
def send_to_js(self, message: str, need_to_save: bool = False) -> None:
if self.connected_js is not None:
Debug.py_to_js(f'To js client {self.name} {message}')
try:
self.connected_js.send_raw(message)
except AttributeError:
pass
if need_to_save:
self.history += [message]
def thinking(self):
self.in_decision = True
end_thinking_time = datetime.now() + timedelta(seconds=self.thinking_time)
back_counting = self.back_counting + 1
while datetime.now() < end_thinking_time:
sleep(0.01)
if not self.in_decision:
break
if (end_thinking_time - datetime.now()).seconds < back_counting:
back_counting -= 1
self.connected_table.cast(dumps({'type': 'back counting', 'time': back_counting, 'id': self.game_id}))
else:
self.send_to_js(dumps({'type': 'kick'}))
self.thinking_time = self.kicked_thinking_time
if self.connected_js is not None:
self.connected_js.finish()
def receive(self, srv: 'Server', message: str, client: dict):
if message.startswith('new_hand'):
self.history = []
_, message = message.split(' ', 1)
message = self.connected_table.inject_disconnections(message)
with self.lock:
self.send_to_js(message, True)
elif message.startswith('decision'):
if self.is_disconnected:
self.send_raw('1')
else:
_, message = message.split(' ', 1)
json_message = loads(message)
json_message['time'] = self.thinking_time
message = dumps(json_message)
with self.lock:
self.send_to_js(message, True)
Thread(target=lambda: self.thinking(), name=f'Thinking {self.name}').start()
elif message == 'busted':
self.is_busted = True
elif message.startswith('resit'):
_, game_id, table_num, message = message.split(' ', 3)
gh_client: GameHandlerClient = srv.gh_clients[int(game_id)]
new_table: TableClient = gh_client.tb_clients[table_num]
if self.connected_table is not None:
self.connected_table.players.remove(self)
self.history = new_table.history[:]
need_reconnection = True
else:
need_reconnection = False
self.connected_table = new_table
self.connected_table.players += [self]
if need_reconnection:
with self.lock:
Debug.resitting(f'Start resitting restore to client {self.name} {message}')
self.send_to_js(self.connected_table.inject_disconnections(message))
self.send_to_js(dumps({'type': 'reconnect start'}))
for msg in self.history:
self.send_to_js(msg)
Debug.resitting(f'Restore when resit {self.name} {msg}')
self.send_to_js(dumps({'type': 'reconnect end'}))
Debug.resitting(f'Reconnected when resit {self.name}')
else:
with self.lock:
self.send_to_js(message, True)
def left(self, srv: 'Server'):
del srv.py_clients[self.name]
if self.connected_js is not None and not self.is_busted:
self.send_to_js(dumps({'type': 'finish', 'msg': 'Game was broken.'}))
self.connected_js.finish()
Debug.client_left('DEL PY')
class SpectatorClient(AbstractClient):
def __init__(self, _id: int, name: str, handler: WebSocketHandler):
super().__init__(_id, name, handler)
self.connected_table: TableClient = None
self.nick: str = None
def receive(self, srv: 'Server', message: str, client: dict) -> None:
Debug.from_sp(f'Message from spectator {self.name}: {message}')
try:
json_message = loads(message)
except JSONDecodeError:
Debug.from_sp(f'JSON decode error msg from spectator {self.name} {message}')
else:
if json_message['type'] == 'chat' and 'text' in json_message:
if self.nick is None:
self.nick = Server.DEFAULT_NICK
json_message['text'] = f'[Watcher {self.nick}]: {json_message["text"]}'
self.connected_table.chat_message(dumps(json_message))
elif json_message['type'] == 'nick' and 'nick' in json_message:
if self.nick is None:
if 0 < len(json_message['nick']) <= Server.MAX_NICK_LENGTH:
self.nick = json_message['nick']
else:
self.nick = Server.DEFAULT_NICK
def left(self, srv: 'Server') -> None:
del srv.sp_clients[srv.sp_clients.index(self)]
del self.connected_table.spectators[self.connected_table.spectators.index(self)]
Debug.client_left('DEL SP')
class TableClient(AbstractClient):
def __init__(self, _id: int, name: str, game: GameHandlerClient, handler: WebSocketHandler):
super().__init__(_id, name, handler)
self.spectators: List[SpectatorClient] = []
self.players: List[PythonClient] = []
self.connected_game: GameHandlerClient = game
game.tb_clients[name] = self
self.history: List[str] = []
self.chat_history: List[Tuple[datetime, str]] = []
self.replay: List[Tuple[datetime, str]] = []
self.hands_history: List[List[Tuple[datetime, str]]] = []
self.lock: Lock = Lock()
self.is_first_hand: bool = True
self.hands: int = 0
def connect_spectator(self, spectator: SpectatorClient) -> None:
with self.lock:
spectator.send({'type': 'reconnect start'})
Debug.spectator_init(f'Spectator {spectator.name} reconnect start')
for msg in self.history:
spectator.send_raw(msg)
Debug.spectator_init(f'Start spectate {spectator.name} {msg}')
for chat_msg in self.get_last_chat_messages():
spectator.send_raw(chat_msg)
Debug.spectator_init(f'Restore chat {spectator.name} {chat_msg}')
Debug.spectator_init(f'Spectator {spectator.name} reconnect end')
spectator.send({'type': 'reconnect end'})
self.spectators += [spectator]
spectator.connected_table = self
def cast_to_spectators(self, message: str):
with self.lock:
for spectator in self.spectators:
Debug.tb_to_sp(f'Table {self.name} to spectator {spectator.id} {message}')
spectator.send_raw(message)
def cast_to_javascript(self, message: str):
with self.lock:
for curr in self.players:
curr.send_to_js(message, True)
def cast(self, message: str, is_chat_message: bool = False):
if not is_chat_message:
# because chat messages restored separately with self.chat_history
self.history += [message]
self.replay += [(datetime.now(), message)]
self.cast_to_spectators(message)
self.cast_to_javascript(message)
def chat_message(self, message: str):
self.chat_history += [(datetime.now(), message)]
self.cast(message, True)
def get_last_chat_messages(self) -> List[str]:
return [message[1] for message in self.chat_history[-Server.MAX_CHAT_LENGTH:]]
def inject_disconnections(self, message: str) -> str:
with self.lock:
json_message = loads(message)
players_ids = [curr.game_id for curr in self.players]
for curr in json_message['players']:
if curr['id'] in players_ids:
pl = max(pl for pl in self.players if pl.game_id == curr['id'])
curr['disconnected'] = pl.is_disconnected
else:
curr['disconnected'] = False
return dumps(json_message)
def receive(self, srv: 'Server', message: str, client: dict) -> None:
print("TABLE RECIEVE", message)
if message.startswith('new_hand'):
_, message = message.split(' ', 1)
if self.replay:
self.hands_history += [self.replay]
self.history = []
self.replay = []
self.hands += 1
message = self.inject_disconnections(message)
self.history += [message]
self.replay += [(datetime.now(), message)]
self.cast_to_spectators(message)
elif message.startswith('player_hand'):
_, player_id, message = message.split(' ', 2)
for pl in self.players:
pl: PythonClient
print('PLAYER HAND', pl.name, pl.game_id, pl.game_handler_id)
# todo : very bad hack
new_players = []
names = []
for pl in self.players:
if pl.name not in names:
names += [pl.name]
new_players += [pl]
self.players = new_players
# endtodo : very bad hack
player = max(pl for pl in self.players if pl.game_id == int(player_id))
player.receive(srv, f'new_hand {message}', client)
elif message == 'end':
self.finish()
elif message.startswith('add_player'):
_, message = message.split(' ', 1)
json_message = loads(message)
curr_id = json_message['id']
py_cl = None
print('ADD PLAYERS', self.connected_game.waiting_js_clients)
for js_cl in self.connected_game.waiting_js_clients.values():
py_cl = js_cl.connected_python
print('TESTING ID', py_cl.game_id, curr_id, py_cl.game_id == curr_id)
if py_cl.game_id == curr_id:
self.players += [py_cl]
break
py_cl = None
if py_cl is not None:
del self.connected_game.waiting_js_clients[py_cl.connected_js.name]
# todo : very bad hack
new_players = []
names = []
for pl in self.players:
if pl.name not in names:
names += [pl.name]
new_players += [pl]
self.players = new_players
# endtodo : very bad hack
if curr_id in [curr.game_id for curr in self.players]:
pl = max(pl for pl in self.players if pl.game_id == curr_id)
json_message['disconnected'] = pl.is_disconnected
message = dumps(json_message)
self.cast(message)
elif message.startswith('for_replay'):
_, message = message.split(' ', 1)
deal_message = dumps({'type': 'deal cards'})
init_time = self.replay[0][0]
self.replay[1:1] = [(init_time, deal_message), (init_time, message)]
self.history += [deal_message]
self.cast_to_spectators(deal_message)
elif message.startswith('give_cards'):
_, player_id, message = message.split(' ', 2)
player = max(pl for pl in self.players if pl.game_id == int(player_id))
player.send_to_js(message, True)
else:
self.cast(message)
def left(self, srv: 'Server') -> None:
del self.connected_game.tb_clients[self.name]
if self.replay:
self.hands_history += [self.replay]
self.connected_game.replays += [(self.name, self.hands, self.hands_history, self.chat_history)]
for curr_client in self.spectators:
curr_client.send({'type': 'finish', 'msg': 'Table is closed.'})
curr_client.finish()
for curr_client in self.players:
curr_client.send({'type': 'finish', 'msg': 'Table is closed.'})
curr_client.finish()
Debug.client_left('DEL TB')
class ReplayClient(AbstractClient):
def __init__(self, _id: int, name: str, handler: WebSocketHandler):
super().__init__(_id, name, handler)
self.loop: bool = True
self.message: str = None
self.thread: Thread = Thread(target=lambda: self.handle_replay())
self.thread.start()
@staticmethod
def dump_replay(obj):
output = ''
for d, s in obj:
output += '%s %s %s %s %s %s %s' % (d.year, d.month, d.day, d.hour, d.minute, d.second, d.microsecond)
output += '\n'