Reindented all source code

This commit is contained in:
Manuel Cortez 2022-01-14 11:47:24 -06:00
parent 17b9161813
commit 1aa7491624
No known key found for this signature in database
GPG Key ID: 9E0735CA15EFE790
11 changed files with 436 additions and 437 deletions

View File

@ -5,46 +5,46 @@ import enet
class client(object): class client(object):
def __init__(self, host=b"localhost", port=33333, peer_count=1, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0): def __init__(self, host=b"localhost", port=33333, peer_count=1, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
self.host = enet.Host(None, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth) self.host = enet.Host(None, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
address = enet.Address(host, port) address = enet.Address(host, port)
self.peer = self.host.connect(address, channel_limit) self.peer = self.host.connect(address, channel_limit)
def run(self): def run(self):
self.running = True self.running = True
while self.running: while self.running:
event = self.host.service(0) event = self.host.service(0)
if event.type == enet.EVENT_TYPE_CONNECT: if event.type == enet.EVENT_TYPE_CONNECT:
if hasattr(self, "connected"): if hasattr(self, "connected"):
self.connected(event.peer) self.connected(event.peer)
elif event.type == enet.EVENT_TYPE_DISCONNECT: elif event.type == enet.EVENT_TYPE_DISCONNECT:
if hasattr(self, "disconnected"): if hasattr(self, "disconnected"):
self.disconnected(event.peer) self.disconnected(event.peer)
elif event.type == enet.EVENT_TYPE_RECEIVE: elif event.type == enet.EVENT_TYPE_RECEIVE:
data = event.packet.data data = event.packet.data
data_dict = json.loads(data) data_dict = json.loads(data)
self.network(event, data_dict) self.network(event, data_dict)
time.sleep(0.001) time.sleep(0.001)
def send_data(self, channel, data, reliable=True): def send_data(self, channel, data, reliable=True):
data_str = json.dumps(data, ensure_ascii=False) data_str = json.dumps(data, ensure_ascii=False)
data_bytes = bytes(data_str, "utf-8") data_bytes = bytes(data_str, "utf-8")
if reliable: if reliable:
flags = enet.PACKET_FLAG_RELIABLE flags = enet.PACKET_FLAG_RELIABLE
else: else:
flags = enet.PACKET_FLAG_UNSEQUENCED flags = enet.PACKET_FLAG_UNSEQUENCED
packet = enet.Packet(data_bytes, flags) packet = enet.Packet(data_bytes, flags)
self.peer.send(channel, packet) self.peer.send(channel, packet)
def network(self, event, data): def network(self, event, data):
print(data) print(data)
def disconnect(self): def disconnect(self):
self.peer.disconnect() self.peer.disconnect()
def close(self): def close(self):
self.running = False self.running = False
def __del__(self): def __del__(self):
del self.host del self.host
del self.peer del self.peer

View File

@ -4,82 +4,82 @@ import json
class channel(object): class channel(object):
def __init__(self, server, peer): def __init__(self, server, peer):
self.peer = peer self.peer = peer
self.server = server self.server = server
def send_data(self, channel, data, reliable=True): def send_data(self, channel, data, reliable=True):
data_str = json.dumps(data, ensure_ascii=False) data_str = json.dumps(data, ensure_ascii=False)
data_bytes = bytes(data_str, "utf-8") data_bytes = bytes(data_str, "utf-8")
if reliable: if reliable:
flags = enet.PACKET_FLAG_RELIABLE flags = enet.PACKET_FLAG_RELIABLE
else: else:
flags = enet.PACKET_FLAG_UNSEQUENCED flags = enet.PACKET_FLAG_UNSEQUENCED
packet = enet.Packet(data_bytes, flags) packet = enet.Packet(data_bytes, flags)
self.peer.send(channel, packet) self.peer.send(channel, packet)
def network(self, event, data): def network(self, event, data):
print(data) print(data)
def disconnect(self): def disconnect(self):
self.peer.disconnect() self.peer.disconnect()
class server(object): class server(object):
def __init__(self, host=None, port=33333, peer_count=256, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0): def __init__(self, host=None, port=33333, peer_count=256, channel_limit=4, incoming_bandwidth=0, outgoing_bandwidth=0):
address = enet.Address(host, port) address = enet.Address(host, port)
self.host = enet.Host(address, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth) self.host = enet.Host(address, peer_count, channel_limit, incoming_bandwidth, outgoing_bandwidth)
self.peers = {} self.peers = {}
def run(self): def run(self):
self.running = True self.running = True
while self.running: while self.running:
event = self.host.service(0) event = self.host.service(0)
if event.type == enet.EVENT_TYPE_CONNECT: if event.type == enet.EVENT_TYPE_CONNECT:
self.connected(event.peer) self.connected(event.peer)
elif event.type == enet.EVENT_TYPE_DISCONNECT: elif event.type == enet.EVENT_TYPE_DISCONNECT:
self.disconnected(event.peer) self.disconnected(event.peer)
elif event.type == enet.EVENT_TYPE_RECEIVE: elif event.type == enet.EVENT_TYPE_RECEIVE:
channel_object = self.get_channel(event.peer) channel_object = self.get_channel(event.peer)
if channel_object == None: if channel_object == None:
print("Error receiving packet for invalid channel: %r" % (event.data)) print("Error receiving packet for invalid channel: %r" % (event.data))
return return
data = event.packet.data data = event.packet.data
data_dict = json.loads(data) data_dict = json.loads(data)
channel_object.network(event, data_dict) channel_object.network(event, data_dict)
time.sleep(0.0001) time.sleep(0.0001)
def get_channel(self, peer): def get_channel(self, peer):
for channel in self.peers: for channel in self.peers:
if peer.incomingPeerID == channel.peer.incomingPeerID: if peer.incomingPeerID == channel.peer.incomingPeerID:
return channel return channel
def connected(self, peer): def connected(self, peer):
p = channel(self, peer) p = channel(self, peer)
self.peers[p] = True self.peers[p] = True
print(len(self.peers)) print(len(self.peers))
p.send_data(0, dict(action="connected"), False) p.send_data(0, dict(action="connected"), False)
print("%s: CONNECTED" % peer.address) print("%s: CONNECTED" % peer.address)
def disconnected(self, peer): def disconnected(self, peer):
for channel in self.peers: for channel in self.peers:
if peer.incomingPeerID == channel.peer.incomingPeerID: if peer.incomingPeerID == channel.peer.incomingPeerID:
del self.peers[channel] del self.peers[channel]
print("%s: DISCONNECT" % peer.address) print("%s: DISCONNECT" % peer.address)
break break
def send_to_all(self, channel, data, reliable=True): def send_to_all(self, channel, data, reliable=True):
data_str = json.dumps(data, ensure_ascii=False) data_str = json.dumps(data, ensure_ascii=False)
data_bytes = bytes(data_str, "utf-8") data_bytes = bytes(data_str, "utf-8")
if reliable: if reliable:
flags = enet.PACKET_FLAG_RELIABLE flags = enet.PACKET_FLAG_RELIABLE
else: else:
flags = enet.PACKET_FLAG_UNSEQUENCED flags = enet.PACKET_FLAG_UNSEQUENCED
packet = enet.Packet(data_bytes, flags) packet = enet.Packet(data_bytes, flags)
self.host.broadcast(channel, packet) self.host.broadcast(channel, packet)
def close(self): def close(self):
self.running = False self.running = False
def __del__(self): def __del__(self):
del self.host del self.host

View File

@ -7,20 +7,19 @@ from pubsub import pub
class client(client.client): class client(client.client):
def network(self, event, data): def network(self, event, data):
""" This functions receives data from an enet server in the following protocol: """ This functions receives data from an enet server in the following protocol:
dict(action="some_command", **kwargs) dict(action="some_command", **kwargs)
This function will send all data to whatever listener in the pubsub stack by using the topic "response". This function will send all data to whatever listener in the pubsub stack by using the topic "response".
""" """
f = data.get("action") f = data.get("action")
if f == None: if f == None:
print("Error: Invalid data in protocol. %r" % (data)) print("Error: Invalid data in protocol. %r" % (data))
return return
pub.sendMessage("response", data=data) pub.sendMessage("response", data=data)
def connected(self, peer): def connected(self, peer):
pub.sendMessage("ask_login") pub.sendMessage("ask_login")
def disconnected(self, peer):
pub.sendMessage("disconnected")
def disconnected(self, peer):
pub.sendMessage("disconnected")

View File

@ -4,101 +4,101 @@ import wx
class loginDialog(wx.Dialog): class loginDialog(wx.Dialog):
def __init__(self, title="Login"): def __init__(self, title="Login"):
super(loginDialog, self).__init__(parent=None, id=wx.ID_ANY) super(loginDialog, self).__init__(parent=None, id=wx.ID_ANY)
self.SetTitle(title) self.SetTitle(title)
panel = wx.Panel(self) panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL) sizer = wx.BoxSizer(wx.VERTICAL)
label1 = wx.StaticText(panel, wx.ID_ANY, "Username: ") label1 = wx.StaticText(panel, wx.ID_ANY, "Username: ")
self.username = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1)) self.username = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1))
s = wx.BoxSizer(wx.HORIZONTAL) s = wx.BoxSizer(wx.HORIZONTAL)
s.Add(label1, 0, wx.ALL, 5) s.Add(label1, 0, wx.ALL, 5)
s.Add(self.username, 0, wx.ALL, 5) s.Add(self.username, 0, wx.ALL, 5)
sizer.Add(s, 0, wx.ALL, 5) sizer.Add(s, 0, wx.ALL, 5)
label1 = wx.StaticText(panel, wx.ID_ANY, "Server: ") label1 = wx.StaticText(panel, wx.ID_ANY, "Server: ")
self.server = wx.TextCtrl(panel, wx.ID_ANY, "localhost", size=(380, -1)) self.server = wx.TextCtrl(panel, wx.ID_ANY, "localhost", size=(380, -1))
s = wx.BoxSizer(wx.HORIZONTAL) s = wx.BoxSizer(wx.HORIZONTAL)
s.Add(label1, 0, wx.ALL, 5) s.Add(label1, 0, wx.ALL, 5)
s.Add(self.server, 0, wx.ALL, 5) s.Add(self.server, 0, wx.ALL, 5)
sizer.Add(s, 0, wx.ALL, 5) sizer.Add(s, 0, wx.ALL, 5)
label1 = wx.StaticText(panel, wx.ID_ANY, "Port: ") label1 = wx.StaticText(panel, wx.ID_ANY, "Port: ")
self.port = wx.SpinCtrl(panel, wx.ID_ANY, size=(380, -1)) self.port = wx.SpinCtrl(panel, wx.ID_ANY, size=(380, -1))
self.port.SetRange(1024, 65000) self.port.SetRange(1024, 65000)
self.port.SetValue(33333) self.port.SetValue(33333)
s = wx.BoxSizer(wx.HORIZONTAL) s = wx.BoxSizer(wx.HORIZONTAL)
s.Add(label1, 0, wx.ALL, 5) s.Add(label1, 0, wx.ALL, 5)
s.Add(self.port, 0, wx.ALL, 5) s.Add(self.port, 0, wx.ALL, 5)
sizer.Add(s, 0, wx.ALL, 5) sizer.Add(s, 0, wx.ALL, 5)
# label2 = wx.StaticText(panel, wx.ID_ANY, "Password: ") # label2 = wx.StaticText(panel, wx.ID_ANY, "Password: ")
# self.password = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1), style=wx.TE_PASSWORD) # self.password = wx.TextCtrl(panel, wx.ID_ANY, size=(380, -1), style=wx.TE_PASSWORD)
# ss = wx.BoxSizer(wx.HORIZONTAL) # ss = wx.BoxSizer(wx.HORIZONTAL)
# ss.Add(label2, 0, wx.ALL, 5) # ss.Add(label2, 0, wx.ALL, 5)
# ss.Add(self.password, 0, wx.ALL, 5) # ss.Add(self.password, 0, wx.ALL, 5)
# sizer.Add(ss, 0, wx.ALL, 5) # sizer.Add(ss, 0, wx.ALL, 5)
ok = wx.Button(panel, wx.ID_OK, "Log in") ok = wx.Button(panel, wx.ID_OK, "Log in")
ok.SetDefault() ok.SetDefault()
cancel = wx.Button(panel, wx.ID_CANCEL) cancel = wx.Button(panel, wx.ID_CANCEL)
self.SetEscapeId(wx.ID_CANCEL) self.SetEscapeId(wx.ID_CANCEL)
bs = wx.BoxSizer(wx.HORIZONTAL) bs = wx.BoxSizer(wx.HORIZONTAL)
bs.Add(ok, 0, wx.ALL, 5) bs.Add(ok, 0, wx.ALL, 5)
bs.Add(cancel, 0, wx.ALL, 5) bs.Add(cancel, 0, wx.ALL, 5)
sizer.Add(bs, 0, wx.ALL, 5) sizer.Add(bs, 0, wx.ALL, 5)
panel.SetSizer(sizer) panel.SetSizer(sizer)
self.SetClientSize(sizer.CalcMin()) self.SetClientSize(sizer.CalcMin())
class appFrame(wx.Frame): class appFrame(wx.Frame):
menu_items = [ menu_items = [
("create_room", "Create new room"), ("create_room", "Create new room"),
("join_room", "Join a room") ("join_room", "Join a room")
] ]
secondary_menu_items = list() secondary_menu_items = list()
def __init__(self): def __init__(self):
super(appFrame, self).__init__(parent=None, title="Chat Window") super(appFrame, self).__init__(parent=None, title="Chat Window")
self.Maximize(True) self.Maximize(True)
self.panel = wx.Panel(self) self.panel = wx.Panel(self)
self.sizer = wx.BoxSizer(wx.VERTICAL) self.sizer = wx.BoxSizer(wx.VERTICAL)
self.sb = self.CreateStatusBar() self.sb = self.CreateStatusBar()
lbl = wx.StaticText(self.panel, wx.ID_ANY, "menu") lbl = wx.StaticText(self.panel, wx.ID_ANY, "menu")
self.list = wx.ListBox(self.panel, wx.ID_ANY) self.list = wx.ListBox(self.panel, wx.ID_ANY)
self.sizer.Add(lbl, 0, wx.GROW) self.sizer.Add(lbl, 0, wx.GROW)
self.sizer.Add(self.list, 1, wx.GROW) self.sizer.Add(self.list, 1, wx.GROW)
lbl = wx.StaticText(self.panel, -1, "Chat") lbl = wx.StaticText(self.panel, -1, "Chat")
self.chat = wx.TextCtrl(self.panel, -1) self.chat = wx.TextCtrl(self.panel, -1)
self.chat.Enable(False) self.chat.Enable(False)
sizerchat = wx.BoxSizer(wx.HORIZONTAL) sizerchat = wx.BoxSizer(wx.HORIZONTAL)
sizerchat.Add(lbl, 0, wx.ALL, 5) sizerchat.Add(lbl, 0, wx.ALL, 5)
sizerchat.Add(self.chat, 0, wx.ALL, 5) sizerchat.Add(self.chat, 0, wx.ALL, 5)
self.sizer.Add(sizerchat, 0, wx.ALL, 5) self.sizer.Add(sizerchat, 0, wx.ALL, 5)
lbl1 = wx.StaticText(self.panel, wx.ID_ANY, "History") lbl1 = wx.StaticText(self.panel, wx.ID_ANY, "History")
self.history = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(500, 300)) self.history = wx.TextCtrl(self.panel, wx.ID_ANY, style=wx.TE_READONLY|wx.TE_MULTILINE, size=(500, 300))
self.history.Enable(False) self.history.Enable(False)
box = wx.BoxSizer(wx.HORIZONTAL) box = wx.BoxSizer(wx.HORIZONTAL)
box.Add(lbl1, 0, wx.ALL, 5) box.Add(lbl1, 0, wx.ALL, 5)
box.Add(self.history, 0, wx.ALL, 5) box.Add(self.history, 0, wx.ALL, 5)
self.sizer.Add(box, 0, wx.ALL, 5) self.sizer.Add(box, 0, wx.ALL, 5)
self.panel.SetSizerAndFit(self.sizer) self.panel.SetSizerAndFit(self.sizer)
def get_item(self): def get_item(self):
return self.list.GetSelection() return self.list.GetSelection()
def add_message(self, message, reverse=False): def add_message(self, message, reverse=False):
old_line = self.history.GetNumberOfLines() old_line = self.history.GetNumberOfLines()
point = self.history.GetInsertionPoint() point = self.history.GetInsertionPoint()
if reverse: if reverse:
self.history.SetValue(message+"\n"+self.history.GetValue()) self.history.SetValue(message+"\n"+self.history.GetValue())
else: else:
self.history.AppendText(message+"\n") self.history.AppendText(message+"\n")
self.history.SetInsertionPoint(point) self.history.SetInsertionPoint(point)
new_line = self.history.GetNumberOfLines()#.count("\n") new_line = self.history.GetNumberOfLines()#.count("\n")
return (old_line, new_line) return (old_line, new_line)
def enable_app(self): def enable_app(self):
for i in self.menu_items: for i in self.menu_items:
self.list.Append(i[1]) self.list.Append(i[1])
self.chat.Enable(True) self.chat.Enable(True)
self.history.Enable(True) self.history.Enable(True)
def show_connection_error(self): def show_connection_error(self):
msg = wx.MessageDialog(None, "Connection error. Try again", "error", style=wx.ICON_ERROR).ShowModal() msg = wx.MessageDialog(None, "Connection error. Try again", "error", style=wx.ICON_ERROR).ShowModal()

View File

@ -15,111 +15,111 @@ c = None
t = None t = None
class controller(object): class controller(object):
def __init__(self, window): def __init__(self, window):
super(controller, self).__init__() super(controller, self).__init__()
self.window = window self.window = window
self.connect_events() self.connect_events()
self.window.Show() self.window.Show()
self.next_action = "" self.next_action = ""
def connect_events(self): def connect_events(self):
self.window.chat.Bind(wx.EVT_CHAR_HOOK, self.on_process) self.window.chat.Bind(wx.EVT_CHAR_HOOK, self.on_process)
self.window.list.Bind(wx.EVT_LISTBOX_DCLICK, self.on_process_listbox_click) self.window.list.Bind(wx.EVT_LISTBOX_DCLICK, self.on_process_listbox_click)
self.window.list.Bind(wx.EVT_CHAR_HOOK, self.on_process_listbox) self.window.list.Bind(wx.EVT_CHAR_HOOK, self.on_process_listbox)
pub.subscribe(self.response, "response") pub.subscribe(self.response, "response")
pub.subscribe(self.ask_login, "ask_login") pub.subscribe(self.ask_login, "ask_login")
pub.subscribe(self.disconnected, "disconnected") pub.subscribe(self.disconnected, "disconnected")
def on_process(self, event): def on_process(self, event):
key = event.GetKeyCode() key = event.GetKeyCode()
if key == wx.WXK_RETURN: if key == wx.WXK_RETURN:
self.send_message() self.send_message()
event.Skip() event.Skip()
def on_process_listbox_click(self, event): def on_process_listbox_click(self, event):
selected_option = self.window.menu_items[self.window.list.GetSelection()][0] selected_option = self.window.menu_items[self.window.list.GetSelection()][0]
if selected_option == "create_room": if selected_option == "create_room":
data = dict(action="create_room") data = dict(action="create_room")
c.send_data(0, data) c.send_data(0, data)
elif selected_option == "join_room": elif selected_option == "join_room":
data = dict(action="request_room_list") data = dict(action="request_room_list")
c.send_data(0, data) c.send_data(0, data)
if event != None: if event != None:
event.Skip() event.Skip()
def on_process_listbox(self, event): def on_process_listbox(self, event):
key = event.GetKeyCode() key = event.GetKeyCode()
if key == wx.WXK_RETURN: if key == wx.WXK_RETURN:
self.on_process_listbox_click(None) self.on_process_listbox_click(None)
event.Skip() event.Skip()
def send_message(self): def send_message(self):
global c global c
message = self.window.chat.GetValue() message = self.window.chat.GetValue()
if message == "" or message == None: if message == "" or message == None:
return wx.Bell() return wx.Bell()
# Otherwise, message does exist. # Otherwise, message does exist.
data = dict(action="send_message", message=message) data = dict(action="send_message", message=message)
c.send_data(0, data) c.send_data(0, data)
self.window.chat.ChangeValue("") self.window.chat.ChangeValue("")
def response(self, data): def response(self, data):
command = data.get("action") command = data.get("action")
if hasattr(self, "cmd_"+command): if hasattr(self, "cmd_"+command):
getattr(self, "cmd_"+command)(data) getattr(self, "cmd_"+command)(data)
def cmd_connected(self, data): def cmd_connected(self, data):
self.window.enable_app() self.window.enable_app()
connected = data.get("nickname") connected = data.get("nickname")
msg = "{} has entered this platform".format(connected) msg = "{} has entered this platform".format(connected)
self.window.add_message(msg) self.window.add_message(msg)
def cmd_message(self, data): def cmd_message(self, data):
msg = data.get("message") msg = data.get("message")
nickname = data.get("nickname") nickname = data.get("nickname")
msg = "{0}: {1}".format(nickname, msg) msg = "{0}: {1}".format(nickname, msg)
output.speak(msg) output.speak(msg)
sound.sound.play("chat.ogg") sound.sound.play("chat.ogg")
self.window.add_message(msg) self.window.add_message(msg)
def cmd_create_room(self, data): def cmd_create_room(self, data):
self.window.list.Clear() self.window.list.Clear()
msg = "{} Has created a room.".format(data.get("nickname")) msg = "{} Has created a room.".format(data.get("nickname"))
self.window.add_message(msg) self.window.add_message(msg)
output.speak(msg) output.speak(msg)
def cmd_room_list(self, data): def cmd_room_list(self, data):
print(data) print(data)
def ask_login(self): def ask_login(self):
global c global c
data = dict(action="login", nickname=self.username) data = dict(action="login", nickname=self.username)
c.send_data(0, data) c.send_data(0, data)
def disconnected(self): def disconnected(self):
self.window.show_connection_error() self.window.show_connection_error()
wx.GetApp().ExitMainLoop() wx.GetApp().ExitMainLoop()
def setup(): def setup():
global c, t global c, t
output.setup() output.setup()
sound.setup() sound.setup()
app = wx.App() app = wx.App()
d = gui.loginDialog() d = gui.loginDialog()
f = gui.appFrame() f = gui.appFrame()
mainController = controller(f) mainController = controller(f)
if d.ShowModal() != wx.ID_OK: if d.ShowModal() != wx.ID_OK:
return return
username = d.username.GetValue() username = d.username.GetValue()
server = bytes(d.server.GetValue(), "utf-8") server = bytes(d.server.GetValue(), "utf-8")
port = int(d.port.GetValue()) port = int(d.port.GetValue())
mainController.username = username mainController.username = username
d.Destroy() d.Destroy()
c = client.client(host=server, port=port) c = client.client(host=server, port=port)
t = threading.Thread(target=c.run) t = threading.Thread(target=c.run)
t.start() t.start()
app.MainLoop() app.MainLoop()
c.close() c.close()
setup() setup()

View File

@ -9,23 +9,23 @@ speaker = None
retries = 0 retries = 0
def speak(text, interrupt=0): def speak(text, interrupt=0):
global speaker, retries global speaker, retries
if not speaker: if not speaker:
setup() setup()
try: try:
speaker.speak(text, interrupt) speaker.speak(text, interrupt)
except: except:
if retries < 5: if retries < 5:
retries = retries + 1 retries = retries + 1
speak(text) speak(text)
def setup (): def setup ():
global speaker global speaker
logger.debug("Initializing output subsystem.") logger.debug("Initializing output subsystem.")
try: try:
speaker = outputs.auto.Auto() speaker = outputs.auto.Auto()
except: except:
logger.exception("Output: Error during initialization.") logger.exception("Output: Error during initialization.")
def enable_sapi(): def enable_sapi():
speaker = outputs.sapi.SAPI5() speaker = outputs.sapi.SAPI5()

View File

@ -3,10 +3,10 @@ import os
from platform_utils import paths as paths_ from platform_utils import paths as paths_
def app_path(): def app_path():
return paths_.app_path() return paths_.app_path()
def locale_path(): def locale_path():
return os.path.join(app_path(), "locales") return os.path.join(app_path(), "locales")
def sound_path(): def sound_path():
return os.path.join(app_path(), "sounds") return os.path.join(app_path(), "sounds")

View File

@ -9,76 +9,76 @@ from sound_lib import recording, stream
from sound_lib import output, input from sound_lib import output, input
def recode_audio(filename, quality=10): def recode_audio(filename, quality=10):
subprocess.call(r'"%s" --downmix -q %r "%s"' % (os.path.join(paths.app_path(), 'oggenc2.exe'), quality, filename)) subprocess.call(r'"%s" --downmix -q %r "%s"' % (os.path.join(paths.app_path(), 'oggenc2.exe'), quality, filename))
def get_recording(filename): def get_recording(filename):
val = recording.WaveRecording(filename=filename) val = recording.WaveRecording(filename=filename)
return val return val
class RepeatingTimer(threading.Thread): class RepeatingTimer(threading.Thread):
"""Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds """Call a function after a specified number of seconds, it will then repeat again after the specified number of seconds
Note: If the function provided takes time to execute, this time is NOT taken from the next wait period Note: If the function provided takes time to execute, this time is NOT taken from the next wait period
t = RepeatingTimer(30.0, f, args=[], kwargs={}) t = RepeatingTimer(30.0, f, args=[], kwargs={})
t.start() t.start()
t.cancel() # stop the timer's actions t.cancel() # stop the timer's actions
""" """
def __init__(self, interval, function, daemon=True, *args, **kwargs): def __init__(self, interval, function, daemon=True, *args, **kwargs):
threading.Thread.__init__(self) threading.Thread.__init__(self)
self.daemon = daemon self.daemon = daemon
self.interval = float(interval) self.interval = float(interval)
self.function = function self.function = function
self.args = args self.args = args
self.kwargs = kwargs self.kwargs = kwargs
self.finished = threading.Event() self.finished = threading.Event()
def cancel(self): def cancel(self):
"""Stop the timer if it hasn't finished yet""" """Stop the timer if it hasn't finished yet"""
self.finished.set() self.finished.set()
stop = cancel stop = cancel
def run(self): def run(self):
while not self.finished.is_set(): while not self.finished.is_set():
self.finished.wait(self.interval) self.finished.wait(self.interval)
if not self.finished.is_set(): #In case someone has canceled while waiting if not self.finished.is_set(): #In case someone has canceled while waiting
try: try:
self.function(*self.args, **self.kwargs) self.function(*self.args, **self.kwargs)
except: except:
print("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs)) print("Execution failed. Function: %r args: %r and kwargs: %r" % (self.function, self.args, self.kwargs))
class soundSystem(object): class soundSystem(object):
def __init__(self): def __init__(self):
""" Sound Player.""" """ Sound Player."""
# Set the output and input default devices. # Set the output and input default devices.
try: try:
self.output = output.Output() self.output = output.Output()
self.input = input.Input() self.input = input.Input()
except: except:
pass pass
self.files = [] self.files = []
self.cleaner = RepeatingTimer(60, self.clear_list) self.cleaner = RepeatingTimer(60, self.clear_list)
self.cleaner.start() self.cleaner.start()
def clear_list(self): def clear_list(self):
if len(self.files) == 0: return if len(self.files) == 0: return
try: try:
for i in range(0, len(self.files)): for i in range(0, len(self.files)):
if self.files[i].is_playing == False: if self.files[i].is_playing == False:
self.files[i].free() self.files[i].free()
self.files.pop(i) self.files.pop(i)
except IndexError: except IndexError:
pass pass
def play(self, sound, argument=False): def play(self, sound, argument=False):
sound_object = stream.FileStream(file="%s/%s" % (paths.sound_path(), sound)) sound_object = stream.FileStream(file="%s/%s" % (paths.sound_path(), sound))
self.files.append(sound_object) self.files.append(sound_object)
sound_object.play() sound_object.play()
sound = None sound = None
def setup(): def setup():
global sound global sound
sound = soundSystem() sound = soundSystem()

View File

@ -4,78 +4,78 @@ from enetcomponents import server
class channel(server.channel): class channel(server.channel):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(channel, self).__init__(*args, **kwargs) super(channel, self).__init__(*args, **kwargs)
self.nickname = None self.nickname = None
def network(self, event, data): def network(self, event, data):
f = data.get("action") f = data.get("action")
if f == None: if f == None:
print("Error: Invalid data in protocol. %r" % (data)) print("Error: Invalid data in protocol. %r" % (data))
return return
if hasattr(self, "cmd_"+f) == False: if hasattr(self, "cmd_"+f) == False:
print("Error: function cmd_{} does not exist".format(f)) print("Error: function cmd_{} does not exist".format(f))
return return
getattr(self, "cmd_"+f)(data) getattr(self, "cmd_"+f)(data)
def cmd_login(self, data): def cmd_login(self, data):
nickname = data.get("nickname") nickname = data.get("nickname")
self.nickname = nickname self.nickname = nickname
self.room = "public" self.room = "public"
d = dict(action="connected", nickname=nickname) d = dict(action="connected", nickname=nickname)
self.server.send_to_all(0, d) self.server.send_to_all(0, d)
def cmd_send_message(self, data): def cmd_send_message(self, data):
data.update(nickname=self.nickname, action="message") data.update(nickname=self.nickname, action="message")
for channel in self.server.peers: for channel in self.server.peers:
if channel.room == self.room: if channel.room == self.room:
channel.send_data(0, data) channel.send_data(0, data)
def cmd_create_room(self, data): def cmd_create_room(self, data):
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10)) code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
existing = True existing = True
while existing: while existing:
existing = self.server.room_exists(code) existing = self.server.room_exists(code)
if existing == True: if existing == True:
code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10)) code = ''.join(random.choices(string.ascii_uppercase +string.digits, k = 10))
self.server.rooms.append(code) self.server.rooms.append(code)
data.update(nickname=self.nickname) data.update(nickname=self.nickname)
self.room = code self.room = code
self.send_data(0, data) self.send_data(0, data)
def cmd_request_room_list(self, data): def cmd_request_room_list(self, data):
rooms = dict() rooms = dict()
for room in self.server.rooms: for room in self.server.rooms:
players = self.server.get_players_in_room(room) players = self.server.get_players_in_room(room)
rooms[room]= players rooms[room]= players
self.send_data(0, dict(action="room_list", rooms=rooms)) self.send_data(0, dict(action="room_list", rooms=rooms))
class server(server.server): class server(server.server):
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(server, self).__init__(*args, **kwargs) super(server, self).__init__(*args, **kwargs)
self.rooms = list() self.rooms = list()
def connected(self, peer): def connected(self, peer):
p = channel(self, peer) p = channel(self, peer)
self.peers[p] = True self.peers[p] = True
def disconnected(self, peer): def disconnected(self, peer):
for channel in self.peers: for channel in self.peers:
if peer.incomingPeerID == channel.peer.incomingPeerID: if peer.incomingPeerID == channel.peer.incomingPeerID:
del self.peers[channel] del self.peers[channel]
break break
def room_exists(self, room_id): def room_exists(self, room_id):
for i in self.rooms: for i in self.rooms:
if room_id == i: if room_id == i:
return True return True
return False return False
def get_players_in_room(self, room_id): def get_players_in_room(self, room_id):
return [player.nickname for player in self.peers if player.room == room_id] return [player.nickname for player in self.peers if player.room == room_id]
if __name__ == "__main__": if __name__ == "__main__":
print("Starting chat server...") print("Starting chat server...")
s = server() s = server()
s.run() s.run()