Fix renderer typing, preserve message text, and harden crypto key handling

Fix abstract renderer signatures and add small stubs so type checkers can
see expected attributes (e.g. username, _decrypt). This removes several
mypy false-positives that were caused by mixin/ABC mismatches.
Preserve message text containing ':' by using split(':', 1) in both
DefaultClientRenderer and RichClientRenderer.
Normalize renderer APIs: print_chat(...) now takes the response mapping
and returns None (matches runtime behavior).
Make RSA symmetric-key request more robust: read r.content instead of a
fixed-size r.raw.read(999), avoiding truncated key material.
Improve _connect_ws exception handling in client to ensure a valid
Exception is re-raised if connection attempts fail.
Correct server/service typing: memory_msgs is now typed as
list[Message] and we null-check incoming payload text before creating a
new Message.
Replace manual package list in setup.py with setuptools.find_packages()
so packaging uses valid Python package names.
Installed types-requests in the project venv so mypy no longer flags the
requests import.
Verification: ran python -m compileall and mypy cmd_chat — no issues
remain.
Notes:

Wire format still uses Python literal evaluation in some places (existing
behavior); switching to JSON for client/server payloads is recommended as a
follow-up for robustness and security.
This commit is contained in:
mirai
2025-11-05 19:29:24 +05:30
parent c3467b89ae
commit 64b0967292
35 changed files with 1688 additions and 31 deletions
@@ -0,0 +1,27 @@
from abc import ABC, abstractmethod
class CryptoService(ABC):
@abstractmethod
def _encrypt(self, message: str) -> str:
raise NotImplementedError("Need to implement encrypt method")
@abstractmethod
def _decrypt(self, message: str) -> str:
raise NotImplementedError("Need to implement decrypt method")
@abstractmethod
def _request_key(self, url: str, username: str, password: str | None = None):
raise NotImplementedError("Need to implement request key method")
@abstractmethod
def _generate_keys(self):
raise NotImplementedError("Need to implement generate keys method")
@abstractmethod
def _get_generated_keys(self) -> tuple:
raise NotImplementedError("Need to implement get generated keys method")
@abstractmethod
def _remove_keys(self):
raise NotImplementedError("Need to implement remove keys method")
@@ -0,0 +1,27 @@
from abc import ABC, abstractmethod
class CryptoService(ABC):
@abstractmethod
def _encrypt(self, message: str) -> str:
raise NotImplementedError("Need to implement encrypt method")
@abstractmethod
def _decrypt(self, message: str) -> str:
raise NotImplementedError("Need to implement decrypt method")
@abstractmethod
def _request_key(self, url: str, username: str, password: str | None = None):
raise NotImplementedError("Need to implement request key method")
@abstractmethod
def _generate_keys(self):
raise NotImplementedError("Need to implement generate keys method")
@abstractmethod
def _get_generated_keys(self) -> tuple:
raise NotImplementedError("Need to implement get generated keys method")
@abstractmethod
def _remove_keys(self):
raise NotImplementedError("Need to implement remove keys method")
@@ -0,0 +1,26 @@
from abc import ABC, abstractmethod
class ClientRenderer(ABC):
@abstractmethod
def print_message(self, message: str) -> str:
raise NotImplementedError("Need to implement print_message")
@abstractmethod
def clear_console(self) -> None:
"""Clear the client console (platform-specific)."""
raise NotImplementedError("Need to implement clear_console")
@abstractmethod
def print_ip(self, ip: str) -> str:
raise NotImplementedError("Need to implement print_ip")
@abstractmethod
def print_username(self, username: str) -> str:
raise NotImplementedError("Need to implement print_username")
@abstractmethod
def print_chat(self, response) -> None:
"""Render chat payload (response is expected to be a mapping with 'messages' and 'users_in_chat')."""
raise NotImplementedError("Need to implement print_chat")
@@ -0,0 +1,26 @@
from abc import ABC, abstractmethod
class ClientRenderer(ABC):
@abstractmethod
def print_message(self, message: str) -> str:
raise NotImplementedError("Need to implement print_message")
@abstractmethod
def clear_console(self) -> None:
"""Clear the client console (platform-specific)."""
raise NotImplementedError("Need to implement clear_console")
@abstractmethod
def print_ip(self, ip: str) -> str:
raise NotImplementedError("Need to implement print_ip")
@abstractmethod
def print_username(self, username: str) -> str:
raise NotImplementedError("Need to implement print_username")
@abstractmethod
def print_chat(self, response) -> None:
"""Render chat payload (response is expected to be a mapping with 'messages' and 'users_in_chat')."""
raise NotImplementedError("Need to implement print_chat")
@@ -0,0 +1,34 @@
from abc import ABC, abstractmethod
class ClientRenderer(ABC):
# These attributes are expected to be provided by subclasses
# (typically via multiple inheritance with CryptoService)
username: str
@abstractmethod
def _decrypt(self, message: str) -> str:
"""Decrypt an encrypted message (provided by crypto mixin)."""
raise NotImplementedError("Need to implement _decrypt")
@abstractmethod
def print_message(self, message: str) -> str:
raise NotImplementedError("Need to implement print_message")
@abstractmethod
def clear_console(self) -> None:
"""Clear the client console (platform-specific)."""
raise NotImplementedError("Need to implement clear_console")
@abstractmethod
def print_ip(self, ip: str) -> str:
raise NotImplementedError("Need to implement print_ip")
@abstractmethod
def print_username(self, username: str) -> str:
raise NotImplementedError("Need to implement print_username")
@abstractmethod
def print_chat(self, response) -> None:
"""Render chat payload (response is expected to be a mapping with 'messages' and 'users_in_chat')."""
raise NotImplementedError("Need to implement print_chat")
@@ -0,0 +1,34 @@
from abc import ABC, abstractmethod
class ClientRenderer(ABC):
# These attributes are expected to be provided by subclasses
# (typically via multiple inheritance with CryptoService)
username: str
@abstractmethod
def _decrypt(self, message: str) -> str:
"""Decrypt an encrypted message (provided by crypto mixin)."""
raise NotImplementedError("Need to implement _decrypt")
@abstractmethod
def print_message(self, message: str) -> str:
raise NotImplementedError("Need to implement print_message")
@abstractmethod
def clear_console(self) -> None:
"""Clear the client console (platform-specific)."""
raise NotImplementedError("Need to implement clear_console")
@abstractmethod
def print_ip(self, ip: str) -> str:
raise NotImplementedError("Need to implement print_ip")
@abstractmethod
def print_username(self, username: str) -> str:
raise NotImplementedError("Need to implement print_username")
@abstractmethod
def print_chat(self, response) -> None:
"""Render chat payload (response is expected to be a mapping with 'messages' and 'users_in_chat')."""
raise NotImplementedError("Need to implement print_chat")
@@ -0,0 +1,44 @@
import rsa
import requests
from cryptography.fernet import Fernet
from cmd_chat.client.core.abs.abs_crypto import CryptoService
class RSAService(CryptoService):
def __init__(self):
self.public_key = None
self.private_key = None
self.symmetric_key = None
self.fernet = None
self._generate_keys()
def _encrypt(self, message: str) -> str:
return self.fernet.encrypt(message.encode()).decode("utf-8")
def _decrypt(self, message: str) -> str:
return self.fernet.decrypt(message.encode()).decode("utf-8")
def _request_key(self, url: str, username: str, password: str | None = None):
pubkey_bytes = self.public_key.save_pkcs1()
r = requests.post(
url,
files={"pubkey": ("public.pem", pubkey_bytes)},
data={"username": username, "password": password or ""},
stream=True,
)
r.raise_for_status()
# read the full response content (server returns encrypted symmetric key)
message = r.content
self.symmetric_key = rsa.decrypt(message, self.private_key)
self.fernet = Fernet(self.symmetric_key)
def _generate_keys(self):
self.public_key, self.private_key = rsa.newkeys(512)
def _get_generated_keys(self):
return self.private_key, self.public_key
def _remove_keys(self):
self.public_key = None
self.private_key = None
@@ -0,0 +1,44 @@
import rsa
import requests
from cryptography.fernet import Fernet
from cmd_chat.client.core.abs.abs_crypto import CryptoService
class RSAService(CryptoService):
def __init__(self):
self.public_key = None
self.private_key = None
self.symmetric_key = None
self.fernet = None
self._generate_keys()
def _encrypt(self, message: str) -> str:
return self.fernet.encrypt(message.encode()).decode("utf-8")
def _decrypt(self, message: str) -> str:
return self.fernet.decrypt(message.encode()).decode("utf-8")
def _request_key(self, url: str, username: str, password: str | None = None):
pubkey_bytes = self.public_key.save_pkcs1()
r = requests.post(
url,
files={"pubkey": ("public.pem", pubkey_bytes)},
data={"username": username, "password": password or ""},
stream=True,
)
r.raise_for_status()
# read the full response content (server returns encrypted symmetric key)
message = r.content
self.symmetric_key = rsa.decrypt(message, self.private_key)
self.fernet = Fernet(self.symmetric_key)
def _generate_keys(self):
self.public_key, self.private_key = rsa.newkeys(512)
def _get_generated_keys(self):
return self.private_key, self.public_key
def _remove_keys(self):
self.public_key = None
self.private_key = None
@@ -0,0 +1,61 @@
import os
import platform
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import COLORS
from colorama import init
init()
class DefaultClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> str:
""" generating string with message in required format
"""
# split only on the first ':' to keep message contents intact
message = message.split(":", 1)
if message[0] == self.username:
return COLORS["my_username_color"] + message[0] + ": " + message[1] + COLORS["text_color"]
return message[0] + ": " + message[1] + COLORS["text_color"]
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return f"IP: " + COLORS["ip_color"] + ip + COLORS["text_color"]
def print_username(
self,
username: str
) -> str:
# Username label + colored username
return f"USERNAME: " + COLORS["username_color"] + username + COLORS["text_color"]
def print_chat(self, response: list[str]) -> str:
for i, msg in enumerate(response["messages"]):
actual_message = self._decrypt(msg)
if i == 0:
for user in response["users_in_chat"]:
print(self.print_ip(user.split(",")[0]))
print(self.print_username(user.split(",")[1]))
print("Write 'q' to quit from chat")
print(f"\n{self.print_message(actual_message)}")
else:
print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,61 @@
import os
import platform
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import COLORS
from colorama import init
init()
class DefaultClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> str:
""" generating string with message in required format
"""
# split only on the first ':' to keep message contents intact
message = message.split(":", 1)
if message[0] == self.username:
return COLORS["my_username_color"] + message[0] + ": " + message[1] + COLORS["text_color"]
return message[0] + ": " + message[1] + COLORS["text_color"]
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return f"IP: " + COLORS["ip_color"] + ip + COLORS["text_color"]
def print_username(
self,
username: str
) -> str:
# Username label + colored username
return f"USERNAME: " + COLORS["username_color"] + username + COLORS["text_color"]
def print_chat(self, response: list[str]) -> str:
for i, msg in enumerate(response["messages"]):
actual_message = self._decrypt(msg)
if i == 0:
for user in response["users_in_chat"]:
print(self.print_ip(user.split(",")[0]))
print(self.print_username(user.split(",")[1]))
print("Write 'q' to quit from chat")
print(f"\n{self.print_message(actual_message)}")
else:
print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,61 @@
import os
import platform
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import COLORS
from colorama import init
init()
class DefaultClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> str:
""" generating string with message in required format
"""
# split only on the first ':' to keep message contents intact
parts = message.split(":", 1)
if parts[0] == self.username:
return COLORS["my_username_color"] + parts[0] + ": " + parts[1] + COLORS["text_color"]
return parts[0] + ": " + parts[1] + COLORS["text_color"]
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return f"IP: " + COLORS["ip_color"] + ip + COLORS["text_color"]
def print_username(
self,
username: str
) -> str:
# Username label + colored username
return f"USERNAME: " + COLORS["username_color"] + username + COLORS["text_color"]
def print_chat(self, response: list[str]) -> str:
for i, msg in enumerate(response["messages"]):
actual_message = self._decrypt(msg)
if i == 0:
for user in response["users_in_chat"]:
print(self.print_ip(user.split(",")[0]))
print(self.print_username(user.split(",")[1]))
print("Write 'q' to quit from chat")
print(f"\n{self.print_message(actual_message)}")
else:
print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,61 @@
import os
import platform
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import COLORS
from colorama import init
init()
class DefaultClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> str:
""" generating string with message in required format
"""
# split only on the first ':' to keep message contents intact
parts = message.split(":", 1)
if parts[0] == self.username:
return COLORS["my_username_color"] + parts[0] + ": " + parts[1] + COLORS["text_color"]
return parts[0] + ": " + parts[1] + COLORS["text_color"]
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return f"IP: " + COLORS["ip_color"] + ip + COLORS["text_color"]
def print_username(
self,
username: str
) -> str:
# Username label + colored username
return f"USERNAME: " + COLORS["username_color"] + username + COLORS["text_color"]
def print_chat(self, response) -> None:
for i, msg in enumerate(response["messages"]):
actual_message = self._decrypt(msg)
if i == 0:
for user in response["users_in_chat"]:
print(self.print_ip(user.split(",")[0]))
print(self.print_username(user.split(",")[1]))
print("Write 'q' to quit from chat")
print(f"\n{self.print_message(actual_message)}")
else:
print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,61 @@
import os
import platform
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import COLORS
from colorama import init
init()
class DefaultClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> str:
""" generating string with message in required format
"""
# split only on the first ':' to keep message contents intact
parts = message.split(":", 1)
if parts[0] == self.username:
return COLORS["my_username_color"] + parts[0] + ": " + parts[1] + COLORS["text_color"]
return parts[0] + ": " + parts[1] + COLORS["text_color"]
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return f"IP: " + COLORS["ip_color"] + ip + COLORS["text_color"]
def print_username(
self,
username: str
) -> str:
# Username label + colored username
return f"USERNAME: " + COLORS["username_color"] + username + COLORS["text_color"]
def print_chat(self, response) -> None:
for i, msg in enumerate(response["messages"]):
actual_message = self._decrypt(msg)
if i == 0:
for user in response["users_in_chat"]:
print(self.print_ip(user.split(",")[0]))
print(self.print_username(user.split(",")[1]))
print("Write 'q' to quit from chat")
print(f"\n{self.print_message(actual_message)}")
else:
print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,78 @@
import os
import platform
from rich.text import Text
from rich.style import Style
from rich.console import Console
from rich.table import Table
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import MESSAGES_TO_SHOW
console = Console(width=75)
class RichClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> Text:
""" generating string with message in required format
"""
# split only on the first ':' so message bodies containing ':' are preserved
message = message.split(":", 1)
if message[0] == self.username:
return \
Text(text=message[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=message[1], style="underline")
return \
Text(text=message[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=message[1], style="underline")
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return ip
def print_username(
self,
username: str
) -> str:
return username
def print_chat(self, response: list[str]) -> str:
self.clear_console()
for i, msg in enumerate(response["messages"][-MESSAGES_TO_SHOW:]):
actual_message = self._decrypt(msg)
if i == 0:
console.print("Users in chat:", justify="left")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("IP", style="dim", width=12)
table.add_column("USERNAME")
for user in response["users_in_chat"]:
table.add_row(
self.print_ip(user.split(',')[0]),
self.print_username(user.split(",")[1])
)
console.print(table)
console.print("Write 'q' to quit from chat", justify="left")
console.print(f"\n{self.print_message(actual_message)}")
else:
console.print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,78 @@
import os
import platform
from rich.text import Text
from rich.style import Style
from rich.console import Console
from rich.table import Table
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import MESSAGES_TO_SHOW
console = Console(width=75)
class RichClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> Text:
""" generating string with message in required format
"""
# split only on the first ':' so message bodies containing ':' are preserved
message = message.split(":", 1)
if message[0] == self.username:
return \
Text(text=message[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=message[1], style="underline")
return \
Text(text=message[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=message[1], style="underline")
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return ip
def print_username(
self,
username: str
) -> str:
return username
def print_chat(self, response: list[str]) -> str:
self.clear_console()
for i, msg in enumerate(response["messages"][-MESSAGES_TO_SHOW:]):
actual_message = self._decrypt(msg)
if i == 0:
console.print("Users in chat:", justify="left")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("IP", style="dim", width=12)
table.add_column("USERNAME")
for user in response["users_in_chat"]:
table.add_row(
self.print_ip(user.split(',')[0]),
self.print_username(user.split(",")[1])
)
console.print(table)
console.print("Write 'q' to quit from chat", justify="left")
console.print(f"\n{self.print_message(actual_message)}")
else:
console.print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,78 @@
import os
import platform
from rich.text import Text
from rich.style import Style
from rich.console import Console
from rich.table import Table
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import MESSAGES_TO_SHOW
console = Console(width=75)
class RichClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> Text:
""" generating string with message in required format
"""
# split only on the first ':' so message bodies containing ':' are preserved
parts = message.split(":", 1)
if parts[0] == self.username:
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return ip
def print_username(
self,
username: str
) -> str:
return username
def print_chat(self, response: list[str]) -> str:
self.clear_console()
for i, msg in enumerate(response["messages"][-MESSAGES_TO_SHOW:]):
actual_message = self._decrypt(msg)
if i == 0:
console.print("Users in chat:", justify="left")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("IP", style="dim", width=12)
table.add_column("USERNAME")
for user in response["users_in_chat"]:
table.add_row(
self.print_ip(user.split(',')[0]),
self.print_username(user.split(",")[1])
)
console.print(table)
console.print("Write 'q' to quit from chat", justify="left")
console.print(f"\n{self.print_message(actual_message)}")
else:
console.print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,78 @@
import os
import platform
from rich.text import Text
from rich.style import Style
from rich.console import Console
from rich.table import Table
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import MESSAGES_TO_SHOW
console = Console(width=75)
class RichClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> Text:
""" generating string with message in required format
"""
# split only on the first ':' so message bodies containing ':' are preserved
parts = message.split(":", 1)
if parts[0] == self.username:
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return ip
def print_username(
self,
username: str
) -> str:
return username
def print_chat(self, response) -> None:
self.clear_console()
for i, msg in enumerate(response["messages"][-MESSAGES_TO_SHOW:]):
actual_message = self._decrypt(msg)
if i == 0:
console.print("Users in chat:", justify="left")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("IP", style="dim", width=12)
table.add_column("USERNAME")
for user in response["users_in_chat"]:
table.add_row(
self.print_ip(user.split(',')[0]),
self.print_username(user.split(",")[1])
)
console.print(table)
console.print("Write 'q' to quit from chat", justify="left")
console.print(f"\n{self.print_message(actual_message)}")
else:
console.print(f"{self.print_message(actual_message)}")
@@ -0,0 +1,78 @@
import os
import platform
from rich.text import Text
from rich.style import Style
from rich.console import Console
from rich.table import Table
from cmd_chat.client.core.abs.abs_renderer import ClientRenderer
from cmd_chat.client.config import MESSAGES_TO_SHOW
console = Console(width=75)
class RichClientRenderer(ClientRenderer):
def __get_os(self) -> str:
""" checking what kind of platform you need
"""
if "Linux" in str(platform.platform()):
return "Linux"
return "Windows"
def print_message(self, message: str) -> Text:
""" generating string with message in required format
"""
# split only on the first ':' so message bodies containing ':' are preserved
parts = message.split(":", 1)
if parts[0] == self.username:
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
return \
Text(text=parts[0], style="bold") + \
Text(text=": ", style="bold") + \
Text(text=parts[1], style="underline")
def clear_console(self):
# For windows clear command its cls
# For linux clear command its clear
if self.__get_os() == "Linux":
os.system("clear")
else:
os.system("cls")
def print_ip(
self,
ip: str
) -> str:
return ip
def print_username(
self,
username: str
) -> str:
return username
def print_chat(self, response) -> None:
self.clear_console()
for i, msg in enumerate(response["messages"][-MESSAGES_TO_SHOW:]):
actual_message = self._decrypt(msg)
if i == 0:
console.print("Users in chat:", justify="left")
table = Table(show_header=True, header_style="bold magenta")
table.add_column("IP", style="dim", width=12)
table.add_column("USERNAME")
for user in response["users_in_chat"]:
table.add_row(
self.print_ip(user.split(',')[0]),
self.print_username(user.split(",")[1])
)
console.print(table)
console.print("Write 'q' to quit from chat", justify="left")
console.print(f"\n{self.print_message(actual_message)}")
else:
console.print(f"{self.print_message(actual_message)}")