ProyectoPSP/chat_logic.py

67 lines
2.2 KiB
Python

import os
import json
import time
import threading
CHAT_FILE = "global_chat.json"
class ChatNetwork:
def __init__(self, ui_callback):
self.ui_callback = ui_callback
self.my_pid = os.getpid()
self.is_running = True
self.last_read_index = 0
if not os.path.exists(CHAT_FILE):
with open(CHAT_FILE, 'w') as f:
json.dump([], f)
def start_server(self):
"""Inicia el hilo que lee el chat constantemente."""
threading.Thread(target=self._monitor_chat, daemon=True).start()
def _monitor_chat(self):
"""Lee el archivo global y muestra solo los mensajes nuevos."""
while self.is_running:
try:
if os.path.exists(CHAT_FILE):
with open(CHAT_FILE, 'r') as f:
messages = json.load(f)
if len(messages) > self.last_read_index:
new_msgs = messages[self.last_read_index:]
for msg in new_msgs:
mi_prefijo = f"PID {self.my_pid}:"
if msg.startswith(mi_prefijo):
mensaje_visual = msg.replace(mi_prefijo, "Yo:")
else:
mensaje_visual = msg
self.ui_callback(mensaje_visual)
self.last_read_index = len(messages)
except Exception:
pass
time.sleep(0.5)
def send_message(self, message):
"""Añade un mensaje al archivo global."""
try:
if os.path.exists(CHAT_FILE):
with open(CHAT_FILE, 'r') as f:
data = json.load(f)
else:
data = []
data.append(f"PID {self.my_pid}: {message}")
with open(CHAT_FILE, 'w') as f:
json.dump(data, f)
return True
except Exception:
return False
def stop(self):
self.is_running = False