Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make code slightly more Pythonic #16

Closed
wants to merge 19 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
87 changes: 39 additions & 48 deletions gamespy/gs_query.py
@@ -1,18 +1,22 @@
'''
Provides functions for creating GameSpy messages out of different structure types

GameSpy messages are \-seperated sets of key-value pairs separated by \ .

'''
import copy

def parse_gamespy_message(message):
def parse_gamespy_message(msg):
stack = []
messages = {}
msg = message

while len(msg) > 0 and "\\final\\" in msg:
while "\\final\\" in msg:
# Find the command
# Don't search for more commands if there isn't a \final\, save the left over for the next packet
found_command = False
while len(msg) > 0 and msg[0] == '\\':
keyEnd = msg[1:].index('\\') + 1
key = msg[1:keyEnd]
msg = msg[keyEnd + 1:]
messages = {}
while msg and msg[0] == '\\':

key, msg = msg[1:].split('\\', 1)

if key == "final":
break
Expand All @@ -21,9 +25,8 @@ def parse_gamespy_message(message):
if msg[0] == '\\':
value = ""
else:
valueEnd = msg[1:].index('\\')
value = msg[:valueEnd + 1]
msg = msg[valueEnd + 1:]
value, msg = msg.split('\\')
msg = '\\' + msg
else:
value = msg

Expand All @@ -35,85 +38,73 @@ def parse_gamespy_message(message):
messages[key] = value

stack.append(messages)
messages = {}

# Return msg so we can prepend any leftover commands to the next packet.
return stack, msg

def prepare_kv(key, value):
return r'\{0}\{1}'.format(key, value)

# Generate a list based on the input dictionary.
# The main command must also be stored in __cmd__ for it to put the parameter at the beginning.
def create_gamespy_message_from_dict(messages_orig):
# Deep copy the dictionary because we don't want the original to be modified
messages = copy.deepcopy(messages_orig)

cmd = ""
cmd_val = ""

if "__cmd__" in messages:
cmd = messages['__cmd__']
messages.pop('__cmd__', None)

if "__cmd_val__" in messages:
cmd_val = messages['__cmd_val__']
messages.pop('__cmd_val__', None)
cmd = messages.pop('__cmd__', "")
cmd_val = messages.pop('__cmd_val__', "")

if cmd in messages:
messages.pop(cmd, None)

l = []
l.append(("__cmd__", cmd))
l.append(("__cmd_val__", cmd_val))

for message in messages:
l.append((message, messages[message]))
l = [
("__cmd__", cmd),
("__cmd_val__", cmd_val),
]

l.extend((key, val) for key, val in messages.items())
return l


def create_gamespy_message_from_list(messages):
d = {}
cmd = ""
cmd_val = ""
cmd, cmdval = "", ""

query = ""
for message in messages:
if message[0] == "__cmd__":
cmd = message[1]
elif message[0] == "__cmd_val__":
cmd_val = message[1]
for key, val in messages:
if key == "__cmd__":
cmd = val
elif key == "__cmd_val__":
cmd_val = val
else:
query += "\\%s\\%s" % (message[0], message[1])
query += prepare_kv(key, val)

if cmd != "":
if cmd:
# Prepend the main command if one was found.
query = "\\%s\\%s%s" % (cmd, cmd_val, query)
query = r"\%s\%s%s" % (cmd, cmd_val, query)

return query


# Create a message based on a dictionary (or list) of parameters.
def create_gamespy_message(messages, id=None):
def create_gamespy_message(messages, i=None):
query = ""

if isinstance(messages, dict):
messages = create_gamespy_message_from_dict(messages)

# Check for an id if the id needs to be updated.
# If it already exists in the list then update it, else add it
if id != None:
if i != None:
for message in messages:
if message[0] == "id":
messages.pop(messages.index(message))
messages.append(("id", str(id)))
id = None # Updated id, so don't add it to the query later
messages.append(("id", str(i)))
i = None # Updated id, so don't add it to the query later
break # Found id, stop searching list

query = create_gamespy_message_from_list(messages)

if id != None:
query += create_gamespy_message_from_list([("id", id)])
if i != None:
query += create_gamespy_message_from_list([("id", i)])

query += "\\final\\"

return query
return query + "\\final\\"
10 changes: 4 additions & 6 deletions gamespy/gs_utility.py
Expand Up @@ -18,14 +18,12 @@ def generate_secret_keys(filename="gslist.cfg"):
return secret_key_list

# GameSpy uses a slightly modified version of base64 which replaces +/= with []_
def base64_encode(input):
output = base64.b64encode(input).replace('+', '[').replace('/', ']').replace('=', '_')
return output
def base64_encode(inp):
return base64.b64encode(inp).replace('+', '[').replace('/', ']').replace('=', '_')


def base64_decode(input):
output = base64.b64decode(input.replace('[', '+').replace('/', ']').replace('_', '='))
return output
def base64_decode(inp):
return base64.b64decode(inp.replace('[', '+').replace('/', ']').replace('_', '='))

# Tetris DS overlay 10 @ 0216E9B8
def rc4_encrypt(_key, _data):
Expand Down