Commit b49acfe7 authored by m!nus's avatar m!nus

tidied up, moved to py3, added more callbacks

parent d11f3281
#!/usr/bin/python #!/usr/bin/env python2
from __future__ import print_function
from teeworlds import Teeworlds from teeworlds.teeworlds import Teeworlds
# set up stuff # set up stuff
tw = Teeworlds(timeout=2) tw = Teeworlds(timeout=2)
......
#!/usr/bin/python #!/usr/bin/env python2
from __future__ import print_function
from teeworlds import Teeworlds
import sys import sys
from teeworlds.teeworlds import Teeworlds
# set up stuff # set up stuff
tw = Teeworlds(timeout=2) tw = Teeworlds(timeout=2)
......
#!/usr/bin/env python2 #!/usr/bin/env python3
from __future__ import print_function
from teeworlds.teeworlds import Teeworlds
from teeworlds.teeworlds import create_masters, query_masters
from teeworlds.base import EventSocket
from teeworlds.server import Server from teeworlds.server import Server
t = Teeworlds() sock = EventSocket()
#t.socket._idle_limit = 10 #t.socket._idle_limit = 10
t.lookup_masters() masterlist = create_masters(sock)
for m in t.masterlist: for m in masterlist:
m.on_server_add = lambda s: s.request_info() m.on_server_add = lambda s: s.request_info()
t.query_masters() query_masters(masterlist)
t.run() sock.run()
# compile one big server list
servers = [] servers = []
for m in t.masterlist: for m in masterlist:
servers += m.serverlist servers += m.serverlist
......
from teeworlds.teeworlds import Teeworlds from teeworlds import query_masters_servercount, create_masters, EventSocket
t = Teeworlds() e = EventSocket()
t.lookup_masters() m = create_masters(e)
t.query_masters_servercount() query_masters_servercount(m)
#for m in t.masterlist: #for m in t.masterlist:
# m.on_server_add = lambda s: s.request_info() # m.on_server_add = lambda s: s.request_info()
#t.query_masters() #t.query_masters()
t.run() e.run()
from .teeworlds import create_masters, query_masters, query_masters_servercount
from .base import EventSocket
from .master import MasterServer
from .server import Server
from .player import Player
\ No newline at end of file
import sys import sys
import socket import socket
import select import select
import Queue as queue import queue
from struct import unpack from struct import unpack
from time import time from time import time
from collections import defaultdict from collections import defaultdict
......
...@@ -69,9 +69,11 @@ class MasterServer(object): ...@@ -69,9 +69,11 @@ class MasterServer(object):
self._request_list = self.List(self._address, self.add_from_serverlist) self._request_list = self.List(self._address, self.add_from_serverlist)
def request_list(self): def request_list(self):
self.on_list_request(self._request_list)
self._socket.send(self._request_list) self._socket.send(self._request_list)
def request_count(self): def request_count(self):
self.on_count_receive(self._request_count)
self._socket.send(self._request_count) self._socket.send(self._request_count)
def add_from_serverlist(self, data): def add_from_serverlist(self, data):
...@@ -85,13 +87,39 @@ class MasterServer(object): ...@@ -85,13 +87,39 @@ class MasterServer(object):
self.serverlist.append(server) self.serverlist.append(server)
self.on_server_add(server) self.on_server_add(server)
def on_server_add(self, server):
"""called when a new server is added by add_to_serverlist"""
pass
def _count_response(self, data): def _count_response(self, data):
self.count = unpack('!H', data[0:2])[0] self.count = unpack('!H', data[0:2])[0]
self.on_count_receive(self.count)
L.debug("Count: {}".format(self.count)) L.debug("Count: {}".format(self.count))
def __repr__(self): def __repr__(self):
return "<MasterServer name='{name}' address='{address}' servers='{server_count}'>".format(name=self.name, address=self.address, server_count=len(self.serverlist)) return "<MasterServer name='{name}' address='{address}' servers='{server_count}'>".format(name=self.name, address=self.address, server_count=len(self.serverlist))
"""
Events
replace with your own code or subclass
Example: master.on_server_add = lambda server: server.request_info()
"""
def on_server_add(self, server):
"""a new server was added by add_to_serverlist"""
pass
def on_list_request(self, request):
"""server list request is about to be send, last change to modify it"""
pass
def on_list_receive(self, partial_list):
"""a part of the server list has been received
partial_list is the binary payload (not including the header)
"""
pass
def on_count_request(self, request):
"""server count request is about to be send, last change to modify it"""
pass
def on_count_receive(self, count):
"""server count has been received"""
pass
...@@ -21,7 +21,7 @@ class Server(object): ...@@ -21,7 +21,7 @@ class Server(object):
self.token = randint(1,255) self.token = randint(1,255)
def get_data(self): def get_data(self):
return self.packet_request + chr(self.token) return self.packet_request + bytes([self.token])
def sent(self): def sent(self):
self.time_sent = time() self.time_sent = time()
...@@ -72,22 +72,22 @@ class Server(object): ...@@ -72,22 +72,22 @@ class Server(object):
self.latency = self._request.latency self.latency = self._request.latency
it = iter(pieces) it = iter(pieces)
try: try:
self.version = it.next() #.decode('utf8') self.version = next(it) #.decode('utf8')
self.name = it.next() #.decode('utf8') self.name = next(it) #.decode('utf8')
self.map = it.next() #.decode('utf8') self.map = next(it) #.decode('utf8')
self.gametype = it.next() #.decode('utf8') self.gametype = next(it) #.decode('utf8')
self.password = (it.next()=='1') self.password = (next(it)=='1')
self.players = int(it.next()) self.players = int(next(it))
self.max_players = int(it.next()) self.max_players = int(next(it))
self.clients = int(it.next()) self.clients = int(next(it))
self.max_clients = int(it.next()) self.max_clients = int(next(it))
for _ in range(self.clients): for _ in range(self.clients):
player = Player() player = Player()
player.name=it.next() #.decode('utf8') player.name=next(it) #.decode('utf8')
player.clan=it.next() #.decode('utf8') player.clan=next(it) #.decode('utf8')
player.country = int(it.next()) player.country = int(next(it))
player.score = int(it.next()) player.score = int(next(it))
player.playing = (it.next()=='1') player.playing = (next(it)=='1')
player.server = self player.server = self
self.playerlist.append(player) self.playerlist.append(player)
except StopIteration: except StopIteration:
...@@ -99,27 +99,19 @@ class Server(object): ...@@ -99,27 +99,19 @@ class Server(object):
except Exception: except Exception:
L.debug(repr(pieces)) L.debug(repr(pieces))
raise raise
self.on_info_received() self.on_info_receive(self)
def match(self, **kwargs):
if kwargs.has_key("hideInvalid") and kwargs["hideInvalid"] and self.latency == None:
return False
if kwargs.has_key("_address") and kwargs["_address"] != self._address:
return False
if kwargs.has_key("_data") and kwargs["_data"][0:len(self.data)] != self.data:
return False
if kwargs.has_key("name") and not re.search(kwargs["name"], self.name):
return False
if kwargs.has_key("address") and not re.search(kwargs["address"], self.address):
return False
if kwargs.has_key("gametype") and not re.search(kwargs["gametype"], self.gametype):
return False
if kwargs.has_key("maxping") and self.latency > kwargs["maxping"]:
return False
return True
def on_info_received(self):
pass
def __repr__(self): def __repr__(self):
return "<Server name='{name}' address='{address}' master='{master}'>".format(**self.__dict__) return "<Server name='{name}' address='{address}' master='{master}'>".format(**self.__dict__)
"""
Events
replace with your own code or subclass
Example: server.on_info_receive = lambda server: print(server)
"""
def on_info_receive(self, server):
"""Info has been received"""
# TODO: this basically gets the server passed twice
pass
#!/usr/bin/env python2
# coding: utf-8
#
# A library to get the serverlist & information for Teeworlds servers # A library to get the serverlist & information for Teeworlds servers
# Copyright (C) 2011 m!nus <m1nus@online.de> # Copyright (C) 2011 m!nus <m1nus@online.de>
# #
...@@ -25,32 +22,25 @@ import logging ...@@ -25,32 +22,25 @@ import logging
logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(funcName)s: %(message)s", level=logging.DEBUG) logging.basicConfig(format="[%(asctime)s] %(levelname)s: %(funcName)s: %(message)s", level=logging.DEBUG)
L = logging.getLogger(__name__) L = logging.getLogger(__name__)
from .base import EventSocket, get_address from .base import get_address
from .master import MasterServer from .master import MasterServer
class Teeworlds(object):
def __init__(self):
self.masterlist = []
self.socket = EventSocket()
def lookup_masters(self):
if self.masterlist:
return
for mastername in ["master{}.teeworlds.com".format(i) for i in range(1, 4+1)]:
# resolves host and picks the first address
master_addr = get_address(mastername, port=8300)
if master_addr:
L.debug("requesting {} ({})".format(mastername, master_addr))
master = MasterServer(self.socket, master_addr, mastername.partition(".")[0])
self.masterlist.append(master)
def query_masters(self):
for master in self.masterlist:
master.request_list()
def query_masters_servercount(self):
for master in self.masterlist:
master.request_count()
def run(self): def create_masters(eventsocket):
self.socket.run() masterlist = []
for mastername in ["master{}.teeworlds.com".format(i+1) for i in range(4)]:
# resolves host and picks the first address
master_addr = get_address(mastername, port=8300)
if master_addr:
L.debug("requesting {} ({})".format(mastername, master_addr))
master = MasterServer(eventsocket, master_addr, mastername.partition(".")[0])
masterlist.append(master)
return masterlist
def query_masters(masterlist):
for master in masterlist:
master.request_list()
def query_masters_servercount(masterlist):
for master in masterlist:
master.request_count()
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment