# ========================================================== # terminal chat standaard user = test passwd = test # edit port at the comment with a arrow # you have to ask the port of the srver at ben@de-roo.org or # directly to me. # have fun! (I guess) # ========================================================== import socket import os import shutil import hashlib import json import getpass from pathlib import Path import time import re import threading # kleuren wit = "\x1b[97m" blauw_bg = "\x1b[44m" groen = "\x1b[92m" rood = "\x1b[91m" reset = "\x1b[0m" # terminal helpers def clear(): os.system("cls" if os.name == "nt" else "clear") def term_size(): size = shutil.get_terminal_size() return size.columns, size.lines def print_white(text=""): print(wit + text + reset) # login def login(): base_dir = Path(__file__).parent passwd_file = base_dir / "passwd.json" if not passwd_file.exists(): print_white("Geen gebruikers.") input(wit + "druk op een knop..." + reset) return None try: with passwd_file.open("r", encoding="utf-8") as f: data = json.load(f) except: data = {} user = input(wit + "Gebruikersnaam: " + reset) password = getpass.getpass(wit + "Wachtwoord: " + reset) password_hash = hashlib.sha256(password.encode("utf-8")).hexdigest() if user in data and data[user] == password_hash: print(groen + "Login succesvol!" + reset) return user print(rood + "Ongeldige gebruikersnaam of wachtwoord." + reset) input(wit + "druk op een knop..." + reset) return None # signup def signup(): base_dir = Path(__file__).parent passwd_file = base_dir / "passwd.json" if passwd_file.exists(): try: with passwd_file.open("r", encoding="utf-8") as f: data = json.load(f) except: data = {} else: data = {} print_white("Nieuwe gebruiker") user = input(wit + "Gebruiker: " + reset) if user in data: print(rood + "Bestaat al." + reset) input(wit + "druk op een knop..." + reset) return password = getpass.getpass(wit + "Wachtwoord: " + reset) data[user] = hashlib.sha256(password.encode("utf-8")).hexdigest() with passwd_file.open("w", encoding="utf-8") as f: json.dump(data, f, indent=4) print(groen + "Succes!" + reset) input(wit + "druk op een knop..." + reset) # strip kleuren def strip_ansi(s): return re.sub(r'\x1b\[.*?m', '', s) # login/signup loop current_user = None while not current_user: clear() w, _ = term_size() print(blauw_bg + wit + " Terminal Chat ".center(w) + reset) print_white("Welkom bij Python Terminal Chat!") print_white("1. inloggen") print_white("2. nieuw account") keuze = input(wit + " > " + reset) if keuze == "1": current_user = login() elif keuze == "2": signup() # connect host = "192.168.254.138" port = 44703 # <---- edit port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: s.connect((host, port)) except: print(rood + "Connectie mislukt" + reset) exit() # stuur username try: s.sendall(current_user.encode("utf-8")) except: print(rood + "Verbinding verloren" + reset) exit() # ontvang chatlijst try: while True: data = s.recv(4096) if data: chat_names = json.loads(data.decode("utf-8")) break except: print(rood + "Verbinding verloren" + reset) exit() chat_messages = [] # teken chatwindow def draw_chat_window(messages, chatname): clear() w, h = term_size() print(blauw_bg + wit + chatname.center(w) + reset) # chat header available_lines = h - 3 to_display = messages[-available_lines:] for msg in to_display: user = msg["user"] text = msg["message"] if user == current_user: print(wit + f" {text} [you]".rjust(w) + reset) else: print_white(f"[{user}] {text}") print("-" * w) # chat session def chat_session(chatkeuze): global chat_messages # open chat s.sendall(json.dumps({"action": "openchat", "chat_name": chatkeuze}).encode("utf-8")) data = s.recv(4096) try: chat_data = json.loads(data.decode("utf-8")) if chat_data: chat_messages = list(chat_data[chatkeuze]["messages"]) except: chat_messages = [] # ontvang berichten def receive_messages(sock): global chat_messages while True: try: data = sock.recv(4096) if not data: continue try: messages = json.loads(data.decode("utf-8")) chat_messages.extend(messages) draw_chat_window(chat_messages, chatkeuze) print(wit + "Typ je bericht (/break om terug te gaan): " + reset, end="", flush=True) except: continue except: break threading.Thread(target=receive_messages, args=(s,), daemon=True).start() while True: draw_chat_window(chat_messages, chatkeuze) bericht = input(wit + "Typ je bericht (/break om terug te gaan): " + reset) if bericht.lower() == "/quit": # sluit exit() elif bericht.lower() == "/break": # terug break elif bericht.lower().startswith("/add "): # add user target_user = bericht.split(" ", 1)[1] s.sendall(json.dumps({ "action": "add_user", "chat": chatkeuze, "user": target_user, "by": current_user }).encode("utf-8")) else: # verstuur s.sendall(json.dumps({ "action": "message", "chat_name": chatkeuze, "message": bericht }).encode("utf-8")) # chat_messages.append({"user": current_user, "message": bericht}) # main loop while True: print_white("Beschikbare chats:") for i, chat in enumerate(chat_names, start=1): print_white(f"{i}. {chat}") print_white(f"{len(chat_names)+1}. Nieuwe chat aanmaken") keuze = input(wit + " > " + reset) if keuze.isdigit() and int(keuze) == len(chat_names)+1: # #chataanmaken nieuwe_chat = input("Naam van nieuwe chat: ") s.sendall(json.dumps({"action": "new_chat", "chat_name": nieuwe_chat}).encode("utf-8")) data = s.recv(4096) if data: chat_names = json.loads(data.decode("utf-8")) elif keuze.isdigit() and 1 <= int(keuze) <= len(chat_names): # #chat openen chatkeuze = chat_names[int(keuze)-1] chat_session(chatkeuze)