Esempio n. 1
0
    def save_server_file(self, filename):
        if not filename:
            logfile("save_server_file: No filepath given")
            return

        for server in self.Servers:
            delete_temp_keys_from_server(server)

        json_file = open(filename, 'w')
        json.dump({'fs_basepath': self.fs_basepath, 'fs_homepath': self.fs_homepath, 'ETPath': self.ETPath,
                   'parameters': self.parameters, 'Servers': self.Servers}, json_file, skipkeys=False, allow_nan=False,
                  sort_keys=True, indent=4)
        logfile("save_server_file: Saved %d servers" % len(self.Servers))
Esempio n. 2
0
 def load_server_file(self, filename):
     if not filename:
         logfile("load_server_file: No filepath given")
         return
     if not isfile(filename):
         logfile("load_server_file: %s is not a file" % filename)
         return
     with open(filename) as jsonfile:
         serversjson = json.load(jsonfile)
     if not serversjson or "Servers" not in serversjson or not serversjson[
             'Servers']:
         logfile("load_server_file: No servers loaded from file")
         self.Servers = []
         return
     self.Servers = serversjson['Servers']
     for server in self.Servers:
         create_server_from_data(server)
     self.fs_basepath = serversjson[
         'fs_basepath'] if 'fs_basepath' in serversjson else ''
     self.fs_homepath = serversjson[
         'fs_homepath'] if 'fs_homepath' in serversjson else ''
     self.ETPath = serversjson['ETPath'] if 'ETPath' in serversjson else ''
     self.parameters = serversjson[
         'parameters'] if 'parameters' in serversjson else ''
     logfile("load_server_file: Loaded %d servers" % len(self.Servers))
Esempio n. 3
0
def get_ip_port_from_address(address):
    if not address:
        logfile("get_ip_port_from_address: no address given")
        return None
    ip = address
    port = "27960"
    if ":" in ip:
        ip = address.split(':')[0].strip()
        port = address.split(':')[1].strip()
    if not ip_match.match(ip):
        ip = get_ip(ip)
    ip = ip.replace('\"', '').replace('\'', '')  # Idk why i need this
    port = int(port)
    if not ip:
        logfile("get_ip_port_from_address: %s was not a valid ip" % str(ip))
        return None
    if not port:
        logfile("get_ip_port_from_address: %s was not a valid port" %
                str(port))
        return None

    logfile("get_ip_port_from_address: %s resolved to ( %s , %d )" %
            (address, ip, port))
    tmp_address = (ip, port)
    return tmp_address
Esempio n. 4
0
def get_player_data(server, players):
    if server is None:
        logfile("get_player_data: server is invalid")
        return
    if not players:
        logfile("get_player_data: players is empty")
        return
    for player_string in players:
        player_string = player_string.strip()
        if not player_string:
            continue
        m = player_match.match(player_string)
        if not m:
            continue
        server['playerlist'].append({'name': m.group(3), 'ping': int(m.group(2)), 'score': int(m.group(1))})
Esempio n. 5
0
    def getstatus_all(self):
        logfile("getstatus_all: creating thread dispatcher")
        dispatcher = ThreadDispatcher()
        dispatcher.sd = self
        logfile("getstatus_all: adding getstatus requests to dispatcher")
        for server in self.Servers:
            dispatcher.add_task(server)

        logfile("getstatus_all: starting thread dispatcher")
        dispatcher.start()
        logfile("getstatus_all: completed thread dispatcher")
Esempio n. 6
0
    def getstatus_all(self):
        logfile("getstatus_all: creating thread dispatcher")
        dispatcher = ThreadDispatcher()
        dispatcher.sd = self
        logfile("getstatus_all: adding getstatus requests to dispatcher")
        for server in self.Servers:
            dispatcher.add_task(server)

        logfile("getstatus_all: starting thread dispatcher")
        dispatcher.start()
        logfile("getstatus_all: completed thread dispatcher")
Esempio n. 7
0
def get_player_data(server, players):
    if server is None:
        logfile("get_player_data: server is invalid")
        return
    if not players:
        logfile("get_player_data: players is empty")
        return
    for player_string in players:
        player_string = player_string.strip()
        if not player_string:
            continue
        m = player_match.match(player_string)
        if not m:
            continue
        server['playerlist'].append({
            'name': m.group(3),
            'ping': int(m.group(2)),
            'score': int(m.group(1))
        })
Esempio n. 8
0
    def save_server_file(self, filename):
        if not filename:
            logfile("save_server_file: No filepath given")
            return

        for server in self.Servers:
            delete_temp_keys_from_server(server)

        json_file = open(filename, 'w')
        json.dump(
            {
                'fs_basepath': self.fs_basepath,
                'fs_homepath': self.fs_homepath,
                'ETPath': self.ETPath,
                'parameters': self.parameters,
                'Servers': self.Servers
            },
            json_file,
            skipkeys=False,
            allow_nan=False,
            sort_keys=True,
            indent=4)
        logfile("save_server_file: Saved %d servers" % len(self.Servers))
Esempio n. 9
0
def rcon_response(server, buffer=""):
    if server is None:
        logfile("rcon_response: server is missing")
        return
    buffer = buffer.replace("print\n", '')
    if not buffer:
        logfile("rcon_response: buffer is empty")
        return
    logfile("rcon_response: %s" % buffer.replace('\n', '/'))
    server['rcon_lines'] += buffer
Esempio n. 10
0
def rcon_response(server, buffer=""):
    if server is None:
        logfile("rcon_response: server is missing")
        return
    buffer = buffer.replace("print\n", '')
    if not buffer:
        logfile("rcon_response: buffer is empty")
        return
    logfile("rcon_response: %s" % buffer.replace('\n', '/'))
    server['rcon_lines'] += buffer
Esempio n. 11
0
 def load_server_file(self, filename):
     if not filename:
         logfile("load_server_file: No filepath given")
         return
     if not isfile(filename):
         logfile("load_server_file: %s is not a file" % filename)
         return
     with open(filename) as jsonfile:
         serversjson = json.load(jsonfile)
     if not serversjson or "Servers" not in serversjson or not serversjson['Servers']:
         logfile("load_server_file: No servers loaded from file")
         self.Servers = []
         return
     self.Servers = serversjson['Servers']
     for server in self.Servers:
         create_server_from_data(server)
     self.fs_basepath = serversjson['fs_basepath'] if 'fs_basepath' in serversjson else ''
     self.fs_homepath = serversjson['fs_homepath'] if 'fs_homepath' in serversjson else ''
     self.ETPath = serversjson['ETPath'] if 'ETPath' in serversjson else ''
     self.parameters = serversjson['parameters'] if 'parameters' in serversjson else ''
     logfile("load_server_file: Loaded %d servers" % len(self.Servers))
Esempio n. 12
0
def get_ip_port_from_address(address):
    if not address:
        logfile("get_ip_port_from_address: no address given")
        return None
    ip = address
    port = "27960"
    if ":" in ip:
        ip = address.split(':')[0].strip()
        port = address.split(':')[1].strip()
    if not ip_match.match(ip):
        ip = get_ip(ip)
    ip = ip.replace('\"', '').replace('\'', '')  # Idk why i need this
    port = int(port)
    if not ip:
        logfile("get_ip_port_from_address: %s was not a valid ip" % str(ip))
        return None
    if not port:
        logfile("get_ip_port_from_address: %s was not a valid port" % str(port))
        return None

    logfile("get_ip_port_from_address: %s resolved to ( %s , %d )" % (address, ip, port))
    tmp_address = (ip, port)
    return tmp_address
Esempio n. 13
0
    def rcon_message(self, server, command=""):
        if not server['rcon']:
            logfile("rcon_message: no rcon password is set")
            return
        command = command.strip()
        if not command:
            logfile("rcon_message: command is empty")
            return
        logfile("rcon_message_send: %s" % command)

        # noinspection PyUnusedLocal
        lock = threading.Lock()

        def tmp_task_worker():
            self.send_message(server, "rcon %s %s" % (server['rcon'], command), rcon_response, 256, 2.0, True)

        t = threading.Thread(target=tmp_task_worker)
        t.daemon = True
        t.start()
Esempio n. 14
0
def getstatus_response(server, buffer=""):
    if server is None:
        logfile("getstatus_response: server is missing")
        return
    buffer = buffer.strip().replace("statusResponse\n", '')
    if not buffer:
        logfile("getstatus_response: buffer is empty")
        return

    game_data = buffer.split('\\')
    if not game_data:
        logfile("getstatus_response: invalid response from %s" %
                server['address'])
        return

    server['cvar'] = {}
    server['playerlist'] = []
    server['players'] = "-"
    server['map'] = ""
    server['fs_game'] = 'etmain'
    is_cvar_name = True
    cvar_name = ""
    # noinspection PyUnusedLocal
    cvar_value = ""
    for key in game_data:
        key = key.strip()
        if not key:
            continue
        if is_cvar_name:
            cvar_name = key.lower()
            is_cvar_name = False
        else:
            if '\n' in key:
                players = key.split('\n')
                server['cvar'][cvar_name] = players[0]
                del players[0]
                get_player_data(server, players)
                break
            cvar_value = key
            server['cvar'][cvar_name] = cvar_value
            is_cvar_name = True
    if "mapname" in server['cvar']:
        server['map'] = server['cvar']['mapname']
Esempio n. 15
0
def getstatus_response(server, buffer=""):
    if server is None:
        logfile("getstatus_response: server is missing")
        return
    buffer = buffer.strip().replace("statusResponse\n", '')
    if not buffer:
        logfile("getstatus_response: buffer is empty")
        return

    game_data = buffer.split('\\')
    if not game_data:
        logfile("getstatus_response: invalid response from %s" % server['address'])
        return

    server['cvar'] = {}
    server['playerlist'] = []
    server['players'] = "-"
    server['map'] = ""
    server['fs_game'] = 'etmain'
    is_cvar_name = True
    cvar_name = ""
    # noinspection PyUnusedLocal
    cvar_value = ""
    for key in game_data:
        key = key.strip()
        if not key:
            continue
        if is_cvar_name:
            cvar_name = key.lower()
            is_cvar_name = False
        else:
            if '\n' in key:
                players = key.split('\n')
                server['cvar'][cvar_name] = players[0]
                del players[0]
                get_player_data(server, players)
                break
            cvar_value = key
            server['cvar'][cvar_name] = cvar_value
            is_cvar_name = True
    if "mapname" in server['cvar']:
        server['map'] = server['cvar']['mapname']
Esempio n. 16
0
    def rcon_message(self, server, command=""):
        if not server['rcon']:
            logfile("rcon_message: no rcon password is set")
            return
        command = command.strip()
        if not command:
            logfile("rcon_message: command is empty")
            return
        logfile("rcon_message_send: %s" % command)

        # noinspection PyUnusedLocal
        lock = threading.Lock()

        def tmp_task_worker():
            self.send_message(server, "rcon %s %s" % (server['rcon'], command),
                              rcon_response, 256, 2.0, True)

        t = threading.Thread(target=tmp_task_worker)
        t.daemon = True
        t.start()
Esempio n. 17
0
    def check(self):
        logfile("WolfStarterUpdater: Getting version from %s%s" % (UPDATE_RAWSRC_URL, self.version_path))
        try:
            self.str_version = urlopen("%s%s" % (UPDATE_RAWSRC_URL, self.version_path), timeout=0.5).read().decode()
        except (URLError, HTTPError):
            logfile("WolfStarterUpdater: Error contacting update server")
            return False
        except timeout:
            logfile("WolfStarterUpdater: Update server timed out")
            return False
        self.version = version_to_int(self.str_version)
        if not self.version:
            logfile("WolfStarterUpdater: Invalid data received from update server")
            return False

        logfile("WolfStarterUpdater: Found version %s (%d)" % (self.str_version, self.version))

        int_current_version = version_to_int(WOLFSTARTER_VERSION)
        if not int_current_version:
            logfile("WolfStarterUpdater: No version found ?")
            return False  # Do I want to update here?

        # Updater version is old, proceed to update
        if int_current_version < self.version:
            return True
Esempio n. 18
0
    def send_message(self, server, message, receive_callback, buff_length=4096, timeout_length=1.0,
                     wait_for_multiple=False):
        server = self.get_server(server)
        if server is None:
            logfile("send_message: server is not valid")
            return
        if not message:
            logfile("send_message: message empty")
            return
        try:
            message = b'\xff\xff\xff\xff' + message.encode()
        except UnicodeError:
            logfile("send_message: error converting message to bytes")
            return

        address = get_ip_port_from_address(server['address'])

        if address is None:
            return None

        # Create socket
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.settimeout(timeout_length)
        except OSError as e:
            logfile("send_message: Error creating socket for %s:%d\n\t%s" % (address[0], address[1], str(e)))
            return
        # Send the message
        if not wait_for_multiple:
            current_time_msec = time.time()  # Get time of response
            server['laststatus'] = current_time_msec
        logfile("send_message: sending message %s" % message.decode(errors="ignore"))  # Display message somehow
        try:
            bytes_sent = s.sendto(message, address)
        except socket.timeout:
            s.close()
            logfile("send_message: send connection to %s:%d timed out(500ms)" % (address[0], address[1]))
            return
        except OSError as e:
            s.close()
            logfile("send_message: error sending message to %s:%d\n\t%s" % (address[0], address[1], str(e)))
            return

        logfile("send_message: %d bytes sent to %s:%d" % (bytes_sent, address[0], address[1]))
        total_buf = ""

        # Just a little confused if I have done this correctly
        # On very large messages (Example switching maps, where it displays all the map loading information)
        # It will only show 1 message
        while True:
            try:
                recv = s.recvfrom(buff_length)
            except socket.timeout:
                logfile("send_message: Receive connection timed out(%dms) %s:%d" % (timeout_length*1000, address[0],
                                                                                    address[1]))
                s.close()
                if total_buf:
                    break
                else:
                    return
            except OSError as e:
                logfile("send_message: Error receiving data %s:%d\n\t%s" % (address[0], address[1], str(e)))
                return
            if recv:
                try:
                    tmp_buf = recv[0][4:].decode()
                    total_buf += tmp_buf  # truncate the first 4 bytes
                except UnicodeError as uni_error:
                    logfile("send_message: can not decode buffer response\n\t%s" % uni_error)
                    return
                logfile("send_message: received %d bytes from %s:%d" % (len(recv[0]), recv[1][0], recv[1][1]))
                receive_callback(server, tmp_buf)
                if not wait_for_multiple:
                    break
            else:
                break  # Did not receive
        s.close()
        if not wait_for_multiple:
            # noinspection PyUnboundLocalVariable
            server['ping'] = int((time.time() - current_time_msec) * 1000)
            logfile("send_message: received %d total bytes buffer" % len(total_buf))
            receive_callback(server, total_buf)
Esempio n. 19
0
    def add_server(self, server):
        if not server:
            logfile("add_server: No serverdata given")
            return
        if not type(server) is dict:
            logfile("add_server: Serverdata was not valid type")
            return
        if 'title' not in server:
            logfile("add_server: Server requires title")
            return
        if 'address' not in server:
            logfile("add_server: Server requires address")
            return
        if any(s['title'] == server['title'] for s in self.Servers):
            logfile("add_server: %s title already exists" % server['title'])
            return
        if any(s['address'] == server['address'] for s in self.Servers):
            logfile("add_server: %s address already exists" % server['address'])
            return

        create_server_from_data(server)

        self.Servers.append(server)
        logfile("add_server: %s(%s) server was added" % (server['title'], server['address']))
Esempio n. 20
0
    def check(self):
        logfile("WolfStarterUpdater: Getting version from %s%s" %
                (UPDATE_RAWSRC_URL, self.version_path))
        try:
            self.str_version = urlopen("%s%s" %
                                       (UPDATE_RAWSRC_URL, self.version_path),
                                       timeout=0.5).read().decode()
        except (URLError, HTTPError):
            logfile("WolfStarterUpdater: Error contacting update server")
            return False
        except timeout:
            logfile("WolfStarterUpdater: Update server timed out")
            return False
        self.version = version_to_int(self.str_version)
        if not self.version:
            logfile(
                "WolfStarterUpdater: Invalid data received from update server")
            return False

        logfile("WolfStarterUpdater: Found version %s (%d)" %
                (self.str_version, self.version))

        int_current_version = version_to_int(WOLFSTARTER_VERSION)
        if not int_current_version:
            logfile("WolfStarterUpdater: No version found ?")
            return False  # Do I want to update here?

        # Updater version is old, proceed to update
        if int_current_version < self.version:
            return True
Esempio n. 21
0
from zelly.window import Window
from zelly.constants import logfile
from sys import exc_info
from traceback import format_exception
from sys import argv

if __name__ == '__main__':
    logfile(argv)

    logfile("PROGRAM START".center(50, "-"))
    try:
        Window()
    except:
        e1, e2, e3 = exc_info()
        lines = format_exception(e1, e2, e3)
        logfile(''.join('' + line for line in lines))
        raise
    logfile("PROGRAM END".center(50, "-"))
Esempio n. 22
0
    def add_server(self, server):
        if not server:
            logfile("add_server: No serverdata given")
            return
        if not type(server) is dict:
            logfile("add_server: Serverdata was not valid type")
            return
        if 'title' not in server:
            logfile("add_server: Server requires title")
            return
        if 'address' not in server:
            logfile("add_server: Server requires address")
            return
        if any(s['title'] == server['title'] for s in self.Servers):
            logfile("add_server: %s title already exists" % server['title'])
            return
        if any(s['address'] == server['address'] for s in self.Servers):
            logfile("add_server: %s address already exists" %
                    server['address'])
            return

        create_server_from_data(server)

        self.Servers.append(server)
        logfile("add_server: %s(%s) server was added" %
                (server['title'], server['address']))
Esempio n. 23
0
    def send_message(self,
                     server,
                     message,
                     receive_callback,
                     buff_length=4096,
                     timeout_length=1.0,
                     wait_for_multiple=False):
        server = self.get_server(server)
        if server is None:
            logfile("send_message: server is not valid")
            return
        if not message:
            logfile("send_message: message empty")
            return
        try:
            message = b'\xff\xff\xff\xff' + message.encode()
        except UnicodeError:
            logfile("send_message: error converting message to bytes")
            return

        address = get_ip_port_from_address(server['address'])

        if address is None:
            return None

        # Create socket
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.settimeout(timeout_length)
        except OSError as e:
            logfile("send_message: Error creating socket for %s:%d\n\t%s" %
                    (address[0], address[1], str(e)))
            return
        # Send the message
        if not wait_for_multiple:
            current_time_msec = time.time()  # Get time of response
            server['laststatus'] = current_time_msec
        logfile("send_message: sending message %s" %
                message.decode(errors="ignore"))  # Display message somehow
        try:
            bytes_sent = s.sendto(message, address)
        except socket.timeout:
            s.close()
            logfile("send_message: send connection to %s:%d timed out(500ms)" %
                    (address[0], address[1]))
            return
        except OSError as e:
            s.close()
            logfile("send_message: error sending message to %s:%d\n\t%s" %
                    (address[0], address[1], str(e)))
            return

        logfile("send_message: %d bytes sent to %s:%d" %
                (bytes_sent, address[0], address[1]))
        total_buf = ""

        # Just a little confused if I have done this correctly
        # On very large messages (Example switching maps, where it displays all the map loading information)
        # It will only show 1 message
        while True:
            try:
                recv = s.recvfrom(buff_length)
            except socket.timeout:
                logfile(
                    "send_message: Receive connection timed out(%dms) %s:%d" %
                    (timeout_length * 1000, address[0], address[1]))
                s.close()
                if total_buf:
                    break
                else:
                    return
            except OSError as e:
                logfile("send_message: Error receiving data %s:%d\n\t%s" %
                        (address[0], address[1], str(e)))
                return
            if recv:
                try:
                    tmp_buf = recv[0][4:].decode()
                    total_buf += tmp_buf  # truncate the first 4 bytes
                except UnicodeError as uni_error:
                    logfile(
                        "send_message: can not decode buffer response\n\t%s" %
                        uni_error)
                    return
                logfile("send_message: received %d bytes from %s:%d" %
                        (len(recv[0]), recv[1][0], recv[1][1]))
                receive_callback(server, tmp_buf)
                if not wait_for_multiple:
                    break
            else:
                break  # Did not receive
        s.close()
        if not wait_for_multiple:
            # noinspection PyUnboundLocalVariable
            server['ping'] = int((time.time() - current_time_msec) * 1000)
            logfile("send_message: received %d total bytes buffer" %
                    len(total_buf))
            receive_callback(server, total_buf)