<commit_before>import copy
import json
import threading
import time

from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

from authclient import AuthClient, AuthException
from config import Config
from gameclient import GameClient, GameException, MessageType, RelMessageType, ObjDataType, GameState
from item import Item
from messagebuf import MessageBuf
from resource import ResLoader
from simplelogger import SimpleLogger


class WSServer(WebSocket, SimpleLogger):
    config = Config()

    @staticmethod
    def serve(config_path):
        WSServer.config.load(config_path)
        server = SimpleWebSocketServer(
            WSServer.config.mafen_host,
            WSServer.config.mafen_port,
            WSServer
        )
        server.serveforever()

    def handleMessage(self):
        msg = json.loads(self.data)
        action = msg['action']
        data = msg['data']
        if action == 'connect':
            self.handle_connect_message(data)
        elif action == 'play':
            self.handle_play_message(data)
        elif action == 'transfer':
            self.handle_transfer_message(data)
        else:
            self.error('Unknown message received: ' + action)

    def handleConnected(self):
        SimpleLogger.__init__(self)
        self.info('{} connected'.format(self.address))
        self.gs_lock = threading.Lock()
        self.set_gs(GameState.CONN)

    def handleClose(self):
        self.info('{} closed'.format(self.address))
        self.set_gs(GameState.CLOSE)

    def handle_connect_message(self, data):
        self.username = data['username']
        self.password = data['password']
        try:
            ac = AuthClient(WSServer.config.verbose)
            ac.connect(
                WSServer.config.auth_host,
                WSServer.config.auth_port,
                WSServer.config.cert_path
            )
            ac.login(self.username, self.password)
            self.cookie = ac.get_cookie()
            self.sendMessage(
                unicode(json.dumps({
                    'action': 'connect',
                    'success': True
                }))
            )

            self.charlist_wdg_id = -1
            self.gameui_wdg_id = -1
            self.chr_wdg_id = -1
            self.inv_wdg_id = -1
            self.study_wdg_id = -1
            self.rseq = 0
            self.wseq = 0
            self.rmsgs = []
            self.rmsgs_lock = threading.Lock()
            self.items = []
            self.items_lock = threading.Lock()

            self.gc = GameClient(
                WSServer.config.game_host,
                WSServer.config.game_port,
                WSServer.config.verbose
            )

            self.rworker_th = threading.Thread(target=self.rworker)
            self.rworker_th.daemon = True
            self.rworker_th.start()

            self.sworker_th = threading.Thread(target=self.sworker)
            self.sworker_th.daemon = True
            self.sworker_th.start()
        except AuthException as e:
            self.sendMessage(
                unicode(json.dumps({
                    'action': 'connect',
                    'success': False,
                    'reason': str(e)
                }))
            )

    def set_gs(self, gs):
        with self.gs_lock:
            self.gs = gs
            if self.gs == GameState.CLOSE:
                self.sendMessage(
                    unicode(json.dumps({
                        'action': 'close'
                    }))
                )

    def get_gs(self):
        with self.gs_lock:
            return self.gs

    def handle_play_message(self, data):
        if self.charlist_wdg_id == -1:
            return

        char_name = data['char_name']<commit_msg>Close websocket instead of sending a "close" message<commit_after>import copy
import json
import threading
import time

from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

from authclient import AuthClient, AuthException
from config import Config
from gameclient import GameClient, GameException, MessageType, RelMessageType, ObjDataType, GameState
from item import Item
from messagebuf import MessageBuf
from resource import ResLoader
from simplelogger import SimpleLogger


class WSServer(WebSocket, SimpleLogger):
    config = Config()

    @staticmethod
    def serve(config_path):
        WSServer.config.load(config_path)
        server = SimpleWebSocketServer(
            WSServer.config.mafen_host,
            WSServer.config.mafen_port,
            WSServer
        )
        server.serveforever()

    def handleMessage(self):
        msg = json.loads(self.data)
        action = msg['action']
        data = msg['data']
        if action == 'connect':
            self.handle_connect_message(data)
        elif action == 'play':
            self.handle_play_message(data)
        elif action == 'transfer':
            self.handle_transfer_message(data)
        else:
            self.error('Unknown message received: ' + action)

    def handleConnected(self):
        SimpleLogger.__init__(self)
        self.info('{} connected'.format(self.address))
        self.gs_lock = threading.Lock()
        self.set_gs(GameState.CONN)

    def handleClose(self):
        self.info('{} closed'.format(self.address))
        self.set_gs(GameState.CLOSE)

    def handle_connect_message(self, data):
        self.username = data['username']
        self.password = data['password']
        try:
            ac = AuthClient(WSServer.config.verbose)
            ac.connect(
                WSServer.config.auth_host,
                WSServer.config.auth_port,
                WSServer.config.cert_path
            )
            ac.login(self.username, self.password)
            self.cookie = ac.get_cookie()
            self.sendMessage(
                unicode(json.dumps({
                    'action': 'connect',
                    'success': True
                }))
            )

            self.charlist_wdg_id = -1
            self.gameui_wdg_id = -1
            self.chr_wdg_id = -1
            self.inv_wdg_id = -1
            self.study_wdg_id = -1
            self.rseq = 0
            self.wseq = 0
            self.rmsgs = []
            self.rmsgs_lock = threading.Lock()
            self.items = []
            self.items_lock = threading.Lock()

            self.gc = GameClient(
                WSServer.config.game_host,
                WSServer.config.game_port,
                WSServer.config.verbose
            )

            self.rworker_th = threading.Thread(target=self.rworker)
            self.rworker_th.daemon = True
            self.rworker_th.start()

            self.sworker_th = threading.Thread(target=self.sworker)
            self.sworker_th.daemon = True
            self.sworker_th.start()
        except AuthException as e:
            self.sendMessage(
                unicode(json.dumps({
                    'action': 'connect',
                    'success': False,
                    'reason': str(e)
                }))
            )

    def set_gs(self, gs):
        with self.gs_lock:
            self.gs = gs
            if self.gs == GameState.CLOSE:
                self.close()  # TODO: Add reason

    def get_gs(self):
        with self.gs_lock:
            return self.gs

    def handle_play_message(self, data):
        if self.charlist_wdg_id == -1:
            return

        char_name = data['char_name']
{'fraction_non_alphanumeric': 0.09153133807542611, 'fraction_numerical': 0.0021473627700979736, 'mean_word_length': 1.6912242686890575, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '468238', 'n_tokens_mistral': 2143, 'n_tokens_neox': 2046, 'n_words': 406}