2009-08-20 12:51:47 -06:00
|
|
|
#! /usr/bin/env python3
|
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
import asyncore
|
|
|
|
import socket
|
2009-08-20 12:51:47 -06:00
|
|
|
import struct
|
|
|
|
import points
|
|
|
|
import time
|
|
|
|
|
2009-09-01 09:34:15 -06:00
|
|
|
house = 'dirtbags'
|
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
class MyHandler(asyncore.dispatcher):
|
2009-09-01 09:34:15 -06:00
|
|
|
def __init__(self, port=6667):
|
2009-08-31 16:27:57 -06:00
|
|
|
asyncore.dispatcher.__init__(self)
|
|
|
|
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
|
|
self.bind(('', port))
|
2009-09-25 13:27:37 -06:00
|
|
|
self.store = points.Storage()
|
2009-09-01 09:34:15 -06:00
|
|
|
self.acked = set()
|
2009-08-31 16:27:57 -06:00
|
|
|
self.outq = []
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def writable(self):
|
|
|
|
return bool(self.outq)
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def handle_write(self):
|
|
|
|
dgram, peer = self.outq.pop(0)
|
|
|
|
self.socket.sendto(dgram, peer)
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-08-31 16:27:57 -06:00
|
|
|
def handle_read(self):
|
2009-08-20 12:51:47 -06:00
|
|
|
now = int(time.time())
|
2009-09-01 09:34:15 -06:00
|
|
|
dgram, peer = self.socket.recvfrom(4096)
|
2009-08-20 12:51:47 -06:00
|
|
|
try:
|
2009-09-01 09:34:15 -06:00
|
|
|
id, when, cat, team, score = points.decode_request(dgram)
|
2009-08-20 12:51:47 -06:00
|
|
|
except ValueError as e:
|
2009-09-01 09:34:15 -06:00
|
|
|
return self.respond(peer, now, str(e))
|
|
|
|
team = team or house
|
2009-08-20 12:51:47 -06:00
|
|
|
|
|
|
|
# Replays can happen legitimately.
|
2009-09-02 10:15:54 -06:00
|
|
|
if not ((peer, id) in self.acked):
|
2009-08-20 16:20:44 -06:00
|
|
|
if not (now - 2 < when <= now):
|
2009-09-01 09:34:15 -06:00
|
|
|
return self.respond(peer, id, 'Your clock is off')
|
|
|
|
self.store.add((when, cat, team, score))
|
2009-09-02 10:15:54 -06:00
|
|
|
self.acked.add((peer, id))
|
2009-08-20 12:51:47 -06:00
|
|
|
|
2009-09-01 09:34:15 -06:00
|
|
|
self.respond(peer, id, 'OK')
|
2009-08-31 16:27:57 -06:00
|
|
|
|
2009-09-01 09:34:15 -06:00
|
|
|
def respond(self, peer, id, txt):
|
|
|
|
resp = points.encode_response(id, txt)
|
2009-08-31 16:27:57 -06:00
|
|
|
self.outq.append((resp, peer))
|
2009-08-20 12:51:47 -06:00
|
|
|
|
|
|
|
|
2009-09-01 09:34:15 -06:00
|
|
|
def start():
|
|
|
|
return MyHandler()
|
|
|
|
|
2009-08-20 12:51:47 -06:00
|
|
|
if __name__ == "__main__":
|
2009-09-01 09:34:15 -06:00
|
|
|
h = start()
|
2009-08-31 16:27:57 -06:00
|
|
|
asyncore.loop()
|