Update server.py
This commit is contained in:
105
server.py
105
server.py
@@ -30,7 +30,7 @@ server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
|||||||
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
|
||||||
host = "0.0.0.0"
|
host = "0.0.0.0"
|
||||||
port = 44703
|
port = 44704
|
||||||
|
|
||||||
server.bind((host, port))
|
server.bind((host, port))
|
||||||
server.listen()
|
server.listen()
|
||||||
@@ -41,13 +41,13 @@ log(f"[SERVER] LAN IP: {local_ip}")
|
|||||||
log(f"[SERVER] Server live at {local_ip}:{actual_port}")
|
log(f"[SERVER] Server live at {local_ip}:{actual_port}")
|
||||||
|
|
||||||
chats_file = Path("chats2.json")
|
chats_file = Path("chats2.json")
|
||||||
|
|
||||||
if not chats_file.exists():
|
if not chats_file.exists():
|
||||||
with open(chats_file, "w") as f:
|
with open(chats_file, "w") as f:
|
||||||
json.dump({"general": {"users": [], "messages": []}}, f, indent=4)
|
json.dump({"general": {"users": [], "messages": []}}, f, indent=4)
|
||||||
|
|
||||||
lock = threading.Lock()
|
lock = threading.Lock()
|
||||||
clients_lock = threading.Lock()
|
clients_lock = threading.Lock()
|
||||||
|
clients = []
|
||||||
|
|
||||||
def load_chats():
|
def load_chats():
|
||||||
with lock:
|
with lock:
|
||||||
@@ -62,23 +62,52 @@ def save_chats(data):
|
|||||||
with chats_file.open("w", encoding="utf-8") as f:
|
with chats_file.open("w", encoding="utf-8") as f:
|
||||||
json.dump(data, f, indent=4)
|
json.dump(data, f, indent=4)
|
||||||
|
|
||||||
clients = []
|
def broadcast_chats(chats):
|
||||||
chat_clients = {}
|
with clients_lock:
|
||||||
|
for client in clients[:]:
|
||||||
|
try:
|
||||||
|
client.sendall(json.dumps(chats).encode("utf-8"))
|
||||||
|
except:
|
||||||
|
try: client.close()
|
||||||
|
except: pass
|
||||||
|
clients.remove(client)
|
||||||
|
|
||||||
def handle_client(client_socket, addr):
|
def handle_client(client_socket, addr):
|
||||||
with clients_lock:
|
with clients_lock:
|
||||||
clients.append(client_socket)
|
clients.append(client_socket)
|
||||||
|
|
||||||
log(f"[SERVER] Client connected: {addr}")
|
log(f"[SERVER] Client connected: {addr}")
|
||||||
|
|
||||||
username = None
|
username = None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
username = client_socket.recv(1024).decode("utf-8").strip()
|
username = client_socket.recv(1024).decode("utf-8").strip()
|
||||||
log(f"[SERVER] User connected: {username}")
|
log(f"[SERVER] User connected: {username}")
|
||||||
|
|
||||||
|
# username = client_socket.recv(1024).decode("utf-8").strip()
|
||||||
|
# log(f"[SERVER] User connected: {username}")
|
||||||
|
|
||||||
chats = load_chats()
|
chats = load_chats()
|
||||||
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
|
||||||
|
if "general" not in chats:
|
||||||
|
chats["general"] = {"users": [], "messages": []}
|
||||||
|
save_chats(chats)
|
||||||
|
|
||||||
|
if username not in chats["general"]["users"]:
|
||||||
|
chats["general"]["users"].append(username)
|
||||||
|
save_chats(chats)
|
||||||
|
log(f"[SERVER] {username} added to general")
|
||||||
|
|
||||||
|
# if username in chats["users"]: # als je naam in het stukje ["users"] staat, stuur dat stukje <---- werkt nog niet!!
|
||||||
|
# client_socket.sendall(json.dumps(["users"]).encode("utf-8"))
|
||||||
|
|
||||||
|
user_chats = {}
|
||||||
|
|
||||||
|
for chat_name, chat_data in chats.items():
|
||||||
|
if username in chat_data["users"]:
|
||||||
|
user_chats[chat_name] = chat_data
|
||||||
|
|
||||||
|
client_socket.sendall(json.dumps(user_chats).encode("utf-8"))
|
||||||
|
|
||||||
|
# client_socket.sendall(json.dumps(load_chats()).encode("utf-8"))
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
data = client_socket.recv(4096)
|
data = client_socket.recv(4096)
|
||||||
@@ -95,104 +124,88 @@ def handle_client(client_socket, addr):
|
|||||||
|
|
||||||
if action == "new_chat":
|
if action == "new_chat":
|
||||||
chat_name = request["chat_name"]
|
chat_name = request["chat_name"]
|
||||||
users = request.get("users", [username])
|
# users = request.get("users", [username])
|
||||||
|
users = request.get("users", [])
|
||||||
|
if username not in users:
|
||||||
|
users.append(username)
|
||||||
if chat_name not in chats:
|
if chat_name not in chats:
|
||||||
chats[chat_name] = {"users": users, "messages": []}
|
chats[chat_name] = {"users": users, "messages": []}
|
||||||
save_chats(chats)
|
save_chats(chats)
|
||||||
log(f"[SERVER] New chat created: {chat_name}")
|
log(f"[SERVER] New chat created: {chat_name}")
|
||||||
|
|
||||||
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
||||||
|
|
||||||
elif action == "remove_message":
|
elif action == "remove_message":
|
||||||
chat_name = request["chat_name"]
|
chat_name = request["chat_name"]
|
||||||
if chat_name in chats:
|
if chat_name in chats:
|
||||||
# zoek het **laatste bericht van deze gebruiker dat nog niet verwijderd is**
|
|
||||||
for i in reversed(range(len(chats[chat_name]["messages"]))):
|
for i in reversed(range(len(chats[chat_name]["messages"]))):
|
||||||
msg = chats[chat_name]["messages"][i]
|
msg = chats[chat_name]["messages"][i]
|
||||||
if msg["user"] == request["by"] and msg["message"] != "[deleted]":
|
if msg["user"] == request["by"] and msg["message"] != "[deleted]":
|
||||||
chats[chat_name]["messages"][i]["message"] = "[deleted]"
|
chats[chat_name]["messages"][i]["message"] = "[deleted]"
|
||||||
# na chats[chat_name]["messages"][i]["message"] = "[deleted]"
|
|
||||||
with clients_lock:
|
|
||||||
for client in clients[:]:
|
|
||||||
try:
|
|
||||||
client.sendall(json.dumps(chats).encode("utf-8"))
|
|
||||||
except:
|
|
||||||
try: client.close()
|
|
||||||
except: pass
|
|
||||||
clients.remove(client)
|
|
||||||
save_chats(chats)
|
save_chats(chats)
|
||||||
|
broadcast_chats(chats)
|
||||||
log(f"[SERVER] {request['by']} deleted a message in {chat_name}")
|
log(f"[SERVER] {request['by']} deleted a message in {chat_name}")
|
||||||
break
|
break
|
||||||
else:
|
else:
|
||||||
# als er niets overblijft om te verwijderen
|
|
||||||
log(f"[SERVER] {request['by']} tried /rm but no messages left to delete in {chat_name}")
|
log(f"[SERVER] {request['by']} tried /rm but no messages left to delete in {chat_name}")
|
||||||
|
|
||||||
elif action == "message":
|
elif action == "message":
|
||||||
chat_name = request["chat_name"]
|
chat_name = request["chat_name"]
|
||||||
message = request["message"]
|
message = request["message"]
|
||||||
|
|
||||||
if chat_name in chats:
|
if chat_name in chats:
|
||||||
chats[chat_name]["messages"].append({
|
chats[chat_name]["messages"].append({
|
||||||
"user": username,
|
"user": username,
|
||||||
"message": message
|
"message": message,
|
||||||
|
"read_by": [username]
|
||||||
})
|
})
|
||||||
|
|
||||||
save_chats(chats)
|
save_chats(chats)
|
||||||
|
broadcast_chats(chats)
|
||||||
log(f"[SERVER] {username} in {chat_name}: {message}")
|
log(f"[SERVER] {username} in {chat_name}: {message}")
|
||||||
|
|
||||||
with clients_lock:
|
|
||||||
for client in clients[:]:
|
|
||||||
try:
|
|
||||||
client.sendall(json.dumps(chats).encode("utf-8"))
|
|
||||||
except:
|
|
||||||
try:
|
|
||||||
client.close()
|
|
||||||
except:
|
|
||||||
pass
|
|
||||||
clients.remove(client)
|
|
||||||
|
|
||||||
elif action == "add_user":
|
elif action == "add_user":
|
||||||
chat_name = request["chat"]
|
chat_name = request["chat"]
|
||||||
new_user = request["user"]
|
new_user = request["user"]
|
||||||
|
|
||||||
if chat_name in chats:
|
if chat_name in chats:
|
||||||
if new_user not in chats[chat_name]["users"]:
|
if new_user not in chats[chat_name]["users"]:
|
||||||
chats[chat_name]["users"].append(new_user)
|
chats[chat_name]["users"].append(new_user)
|
||||||
save_chats(chats)
|
save_chats(chats)
|
||||||
log(f"[SERVER] Added {new_user} to {chat_name}")
|
log(f"[SERVER] Added {new_user} to {chat_name}")
|
||||||
|
|
||||||
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
||||||
|
|
||||||
elif action == "get_users":
|
elif action == "get_users":
|
||||||
chat_name = request["chat"]
|
chat_name = request["chat"]
|
||||||
|
|
||||||
if chat_name in chats:
|
if chat_name in chats:
|
||||||
users = chats[chat_name]["users"]
|
|
||||||
|
|
||||||
client_socket.sendall(json.dumps({
|
client_socket.sendall(json.dumps({
|
||||||
"type": "users_list",
|
"type": "users_list",
|
||||||
"users": users
|
"users": chats[chat_name]["users"]
|
||||||
}).encode("utf-8"))
|
}).encode("utf-8"))
|
||||||
|
|
||||||
elif action == "openchat":
|
elif action == "openchat":
|
||||||
chat_name = request["chat_name"]
|
chat_name = request["chat_name"]
|
||||||
|
requested_user = request.get("user")
|
||||||
if chat_name in chats:
|
if chat_name in chats:
|
||||||
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
messages = chats[chat_name]["messages"]
|
||||||
else:
|
if requested_user:
|
||||||
client_socket.sendall(json.dumps(chats).encode("utf-8"))
|
messages = [msg for msg in messages if msg["user"] == requested_user]
|
||||||
|
response = {
|
||||||
|
"chat_name": chat_name,
|
||||||
|
"users": chats[chat_name]["users"],
|
||||||
|
"messages": messages
|
||||||
|
}
|
||||||
|
client_socket.sendall(json.dumps(response).encode("utf-8"))
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
log(f"[ERROR] {e}")
|
log(f"[ERROR] {e}")
|
||||||
|
|
||||||
finally:
|
finally:
|
||||||
with clients_lock:
|
with clients_lock:
|
||||||
if client_socket in clients:
|
if client_socket in clients:
|
||||||
clients.remove(client_socket)
|
clients.remove(client_socket)
|
||||||
|
try:
|
||||||
client_socket.close()
|
client_socket.close()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
log(f"[SERVER] Client disconnected: {addr}")
|
log(f"[SERVER] Client disconnected: {addr}")
|
||||||
|
|
||||||
|
|
||||||
while True:
|
while True:
|
||||||
client_sock, address = server.accept()
|
client_sock, address = server.accept()
|
||||||
threading.Thread(
|
threading.Thread(
|
||||||
|
|||||||
Reference in New Issue
Block a user