Various changes

This commit is contained in:
Firepup Sixfifty 2024-07-13 08:28:37 +00:00
parent 53b0665411
commit 4bccdcfc24
Signed by: Firepup650
SSH key fingerprint: SHA256:U0Zp8EhEe3CMqFSrC79CqatzaEiL4sjta80/RSX2XrY

View file

@ -17,6 +17,7 @@ G.remoteID = "firepi"
G.event = asyncio.Event() G.event = asyncio.Event()
G.loop = asyncio.get_event_loop() G.loop = asyncio.get_event_loop()
G.interruptCount = 0 G.interruptCount = 0
saveLogs = True
# Try to load a message log, if one exists # Try to load a message log, if one exists
try: try:
G.msgs = __import__("cache").msgs G.msgs = __import__("cache").msgs
@ -40,6 +41,9 @@ try:
elif arg in ["-?", "-h", "--help"]: elif arg in ["-?", "-h", "--help"]:
print("TODO: Help menu soon") print("TODO: Help menu soon")
exit(0) exit(0)
elif arg in ["-l", "--no-logs"]:
log("Disabling saving of logs!")
saveLogs = False
except Exception: except Exception:
sys.tracebacklimit = 0 sys.tracebacklimit = 0
raise ValueError("Invalid arguments. Please refer to -? for usage.") from None raise ValueError("Invalid arguments. Please refer to -? for usage.") from None
@ -47,7 +51,12 @@ except Exception:
def raw(string: str) -> str: def raw(string: str) -> str:
s = string.strip() s = string.strip()
return f"{s!r}"[1:-1].replace("\\\\", "\\") s = f"{s!r}"[1:-1].replace("\\\\", "\\")
if '"' in s:
return s.replace("\\'", "'")
else:
return s
def fmt(msg: str, name: str = "", action: bool = False) -> str: def fmt(msg: str, name: str = "", action: bool = False) -> str:
if action: if action:
@ -55,6 +64,7 @@ def fmt(msg: str, name: str = "", action: bool = False) -> str:
else: else:
return f" {name}{' '*(20-len(name))}: {msg}" return f" {name}{' '*(20-len(name))}: {msg}"
async def handle_client(reader, writer): async def handle_client(reader, writer):
try: try:
global G global G
@ -68,7 +78,7 @@ async def handle_client(reader, writer):
try: try:
await asyncio.wait_for( await asyncio.wait_for(
reader.read(), 0.01 reader.read(), 0.01
) # Silently consume the excess useename data ) # Silently consume the excess username data
except asyncio.TimeoutError: except asyncio.TimeoutError:
pass pass
if not name: if not name:
@ -102,6 +112,13 @@ async def handle_client(reader, writer):
await writer.drain() await writer.drain()
elif request.startswith("/quit"): elif request.startswith("/quit"):
break break
elif request.startswith("/afk"):
if len(request) > 5:
response = log(f"* {name} is afk to {request[4:]}")
else:
response = log(f"* {name} is afk")
elif request.startswith("/back"):
response = log(f"* {name} is back")
elif request: elif request:
response = log(f" {name}: {request}") response = log(f" {name}: {request}")
if response: if response:
@ -110,12 +127,17 @@ async def handle_client(reader, writer):
pass pass
if msgIndex < len(G.msgs): if msgIndex < len(G.msgs):
writer.writelines(G.msgs[msgIndex:]) writer.writelines(G.msgs[msgIndex:])
await writer.drain()
msgIndex = len(G.msgs) msgIndex = len(G.msgs)
if name in G.killList and G.killList[name]:
writer.write(b"Your client has been killed by the server\n")
G.killList[name] = False
break
await writer.drain() await writer.drain()
writer.close() writer.close()
await writer.wait_closed() await writer.wait_closed()
G.uniqueClients -= 1 G.uniqueClients -= 1
G.msgs.extend([log(f"{name} has disconnected from the server.")]) G.msgs.append(log(f"{name} has disconnected from the server."))
G.clientsConnected.remove(name) G.clientsConnected.remove(name)
else: # This is... probably a server? else: # This is... probably a server?
sName = name[4:] # Trim off the S2S label sName = name[4:] # Trim off the S2S label
@ -127,7 +149,12 @@ async def handle_client(reader, writer):
client = raw((await reader.read(967)).decode("utf8")) client = raw((await reader.read(967)).decode("utf8"))
if client == f"END OF CLIENT LISTING FROM {sName}": if client == f"END OF CLIENT LISTING FROM {sName}":
break break
G.msgs.extend([log(f"{client} has connected from {sName}")]) if name in G.servers[sName] or name in G.clientsConnected:
writer.write(b"K Client rejected: Already exists\n")
await writer.drain()
writer.write(b"I Added client.\n")
await writer.drain()
G.msgs.append(log(f"{client} has connected from {sName}"))
G.servers[sName].append(client) G.servers[sName].append(client)
G.clientsConnected.extend(G.servers[sName]) G.clientsConnected.extend(G.servers[sName])
while 1: while 1:
@ -143,60 +170,80 @@ async def handle_client(reader, writer):
pass pass
case "+": case "+":
cName = buffer[2:] cName = buffer[2:]
G.msgs.extend([log(f"{cName} has connected from {sName}")]) if cName not in G.clientsConnected:
G.clientsConnected.extend([cName]) G.msgs.append(
log(f"{cName} has connected from {sName}")
)
G.servers[sName].append(cName)
G.clientsConnected.append(cName)
writer.write(b"I Mmm... Pineapples\n") writer.write(b"I Mmm... Pineapples\n")
await writer.drain() await writer.drain()
else:
writer.write(b"K Nick Collision")
await writer.drain()
case "-": case "-":
cName = buffer[2:] cName = buffer[2:]
G.msgs.extend([log(f"{cName} has dissconected from {sName}")]) G.msgs.append(log(f"{cName} has disconnected from {sName}"))
G.servers[sName].remove(cName)
G.clientsConnected.remove(cName) G.clientsConnected.remove(cName)
writer.write(b"I Mmm... Bananas\n") writer.write(b"I Mmm... Bananas\n")
await writer.drain() await writer.drain()
case "M": case "M":
cName = buffer[2:].split("|", 1)[0] cName = buffer[2:].split("|", 1)[0]
message = buffer[2:].split("|", 1)[1] message = buffer[2:].split("|", 1)[1]
G.msgs.extend([log(f" {cName}: {message}")]) G.msgs.append(log(f" {cName}: {message}"))
writer.write(b'I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace.') writer.write(
b"I Get these damn heretic ghost clients out of my store so i can buy my cult candles in peace."
)
await writer.drain() await writer.drain()
case "A": case "A":
cName = buffer[2:].split("|", 1)[0] cName = buffer[2:].split("|", 1)[0]
message = buffer[2:].split("|", 1)[1] message = buffer[2:].split("|", 1)[1]
G.msgs.extend([log(f"* {cName} {message}")]) G.msgs.append(log(f"* {cName} {message}"))
writer.write(b'I Mmm... Strawberries\n') writer.write(b"I Mmm... Strawberries\n")
await writer.drain() await writer.drain()
case "Q": case "Q":
break break
case "K":
cName = buffer[2:]
G.killList[cName] = True
writer.write(b"I Mmm... Blood\n")
await writer.drain()
case _: case _:
writer.write(b'S Your server is doing drugs over here, sending me bullshit messages man - A fellow server\n') writer.write(
b"S Your server is doing drugs over here, sending me bullshit messages man - A fellow server\n"
)
await writer.drain() await writer.drain()
except TimeoutError: except TimeoutError:
pass pass
for cName in G.serverLinks[sName]: for cName in G.serverLinks[sName]:
G.msgs.extend([log(f"{cName}'s server is going down")]) G.msgs.append(log(f"{cName}'s server is going down"))
G.clientsConnected.remove(cName) G.clientsConnected.remove(cName)
G.serverLinks -= 1 G.serverLinks -= 1
G.servers.remove(sName) G.servers.remove(sName)
G.msgs.extend([log(f"{sName} has de-linked from the network")]) G.msgs.append(log(f"{sName} has de-linked from the network"))
except ConnectionResetError: except [ConnectionResetError, BrokenPipeError]:
if not name.startswith("S2S-"): if not name.startswith("S2S-"):
G.uniqueClients -= 1 G.uniqueClients -= 1
G.msgs.extend([log(f"{name} has disconnected from the server.")]) G.msgs.append(log(f"{name} has disconnected from the server."))
G.clientsConnected.remove(name) G.clientsConnected.remove(name)
else: else:
for cName in G.serverLinks[name[4:]]: for cName in G.serverLinks[name[4:]]:
G.msgs.extend([log(f"{cName}'s server is going down")]) G.msgs.append(log(f"{cName}'s server is going down"))
try:
G.clientsConnected.remove(cName) G.clientsConnected.remove(cName)
except Exception: # Crash during connection sequence?
pass
G.serverLinks -= 1 G.serverLinks -= 1
G.servers.remove(name[4:]) G.servers.remove(name[4:])
G.msgs.extend([log(f"{name[4:]} has de-linked from the network")]) G.msgs.append(log(f"{name[4:]} has de-linked from the network"))
async def run_server(port): async def run_server(port):
global G global G
server = await asyncio.start_server(handle_client, "0.0.0.0", port) server = await asyncio.start_server(handle_client, "0.0.0.0", port)
log(f"Listening on port {port}...") log(f"Listening on port {port}...")
G.msgs.extend([log("Server startup")]) G.msgs.append(log("Server startup"))
crash = False crash = False
try: try:
log("Waiting on the Interrupt Event to be set...") log("Waiting on the Interrupt Event to be set...")
@ -213,9 +260,12 @@ async def run_server(port):
log("Kicking all clients as we go down") log("Kicking all clients as we go down")
server.close() server.close()
# server.abort_clients() # server.abort_clients()
if saveLogs:
with open("cache.py", "w") as cache: with open("cache.py", "w") as cache:
cache.write(f"msgs = {G.msgs}\n") cache.write(f"msgs = {G.msgs}\n")
log("Saved logs, exiting now.") log("Saved logs, exiting now.")
else:
log("Not saving logs, exiting now.")
class ServerInterruptException(KeyboardInterrupt): ... class ServerInterruptException(KeyboardInterrupt): ...