sockets funcionais

This commit is contained in:
JotaChina committed 2025-11-10 16:16:59 -03:00
1 parent d38cd9e60f
commit 509c51b783
7 files changed
+1044 -134

No files matched your search

+64 -21
View File
@@ -8,6 +8,9 @@ from werkzeug.utils import secure_filename
from flask_cors import CORS
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import requests
NODE_SERVER_URL = "https://127.0.0.1:33001"
# --- Configurações (sem alterações) ---
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
@@ -27,13 +30,16 @@ CONFIGS = [
}
]
UPLOAD_FOLDER = os.path.join(PROJECT_ROOT, "src", "samples", "samples")
WATCH_FOLDER = os.path.join(PROJECT_ROOT, "src", "samples") # Pasta a ser vigiada
UPLOAD_FOLDER_SAMPLE = os.path.join(PROJECT_ROOT, "src", "samples", "samples")
WATCH_FOLDER_SAMPLE = UPLOAD_FOLDER_SAMPLE # Pasta a ser vigiada
UPLOAD_FOLDER_PROJECT = os.path.join(PROJECT_ROOT, "src", "samples", "projects")
WATCH_FOLDER_PROJECT = os.path.join(PROJECT_ROOT, "src", "upload_projects") # Pasta a ser vigiada
ALLOWED_EXTENSIONS = {'wav', 'ogg', 'flac', 'mp3'}
app = Flask(__name__)
CORS(app, origins=["https://alice.ufsj.edu.br", "http://localhost:8000", "http://127.0.0.1:5500"])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
CORS(app, origins=["https://alice.ufsj.edu.br", "https://alice.ufsj.edu.br:33002"])
app.config['UPLOAD_FOLDER_SAMPLE'] = UPLOAD_FOLDER_SAMPLE
# --- Funções do Gerador de Manifesto (sem alterações) ---
def scan_directory_tree(path):
@@ -75,9 +81,27 @@ def run_jekyll_build():
except Exception as e:
print(f"ERRO inesperado durante o Jekyll build: {e}")
def notify_node_server(update_type):
"""Envia uma notificação HTTP para o servidor Node.js."""
try:
url = f"{NODE_SERVER_URL}/notify-update"
headers = {'Content-Type': 'application/json'}
payload = {"updateType": update_type}
# O argumento 'verify=False' é geralmente necessário ao usar 127.0.0.1
# com certificados Let's Encrypt (ou autoassinados) para evitar erros de SSL.
response = requests.post(url, json=payload, headers=headers, verify=False)
if response.status_code == 200:
print(f"[Notificação] Sucesso ao notificar Node.js: {update_type}")
else:
print(f"[Notificação] ERRO ao notificar Node.js ({response.status_code}): {response.text}")
except Exception as e:
print(f"[Notificação] ERRO de conexão com o Node.js em {NODE_SERVER_URL}: {e}")
def generate_manifests():
print("\nIniciando geração de arquivos de manifesto...")
# ... (lógica interna sem alterações) ...
for config in CONFIGS:
source_dir_abs = os.path.join(PROJECT_ROOT, config["source_dir"])
output_file_abs = os.path.join(PROJECT_ROOT, config["output_file"])
@@ -93,8 +117,10 @@ def generate_manifests():
print(f"SUCESSO: Arquivo '{output_file_abs}' gerado!")
print("\nGeração de manifestos concluída.")
run_jekyll_build()
# 2. NOTIFICA O SERVIDOR NODE.JS (NOVO PASSO)
notify_node_server("samples")
# --- Lógica do Servidor Flask (sem alterações) ---
# --- Servidor Flask ---
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@@ -105,41 +131,58 @@ def upload_file():
if file.filename == '': return jsonify({"error": "Nenhum arquivo selecionado"}), 400
if file and allowed_file(file.filename):
filename = secure_filename(file.filename)
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
save_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
os.makedirs(app.config['UPLOAD_FOLDER_SAMPLE'], exist_ok=True)
save_path = os.path.join(app.config['UPLOAD_FOLDER_SAMPLE'], filename)
try:
file.save(save_path)
generate_manifests()
return jsonify({"success": True, "message": f"Arquivo '{filename}' salvo e site atualizado!"}), 200
file.save(save_path)
return jsonify({"success": True, "message": f"Arquivo '{filename}' salvo!"}), 200
except Exception as e:
return jsonify({"error": str(e)}), 500
return jsonify({"error": "Tipo de arquivo não permitido"}), 400
# --- NOVO: LÓGICA DO "VIGIA" DE ARQUIVOS (WATCHDOG) ---
# --- LÓGICA DO "VIGIA" DE ARQUIVOS (WATCHDOG) ---
class ManifestEventHandler(FileSystemEventHandler):
"""Um manipulador de eventos que gera os manifestos quando um arquivo muda."""
def __init__(self):
# Inicializa o timestamp da última execução
self.last_triggered = 0
# Define o intervalo mínimo entre execuções (5 segundos)
self.debounce_interval = 5
def on_any_event(self, event):
# Desconsidera eventos em diretórios
if event.is_directory:
# Ignora eventos em diretórios ou no arquivo de manifesto de saída (evita loop)
if event.is_directory or "manifest" in event.src_path:
return
# Mecanismo simples para evitar múltiplas execuções seguidas (debounce)
current_time = time.time()
if current_time - self.last_triggered > 5: # Espera 5 segundos entre as atualizações
# Verifica se passou tempo suficiente desde o último acionamento
if current_time - self.last_triggered > self.debounce_interval:
print(f"\n[VIGIA] Mudança detectada: {event.src_path}")
generate_manifests()
# Executa a geração de manifestos (e o Jekyll build, se descomentado)
# É crucial que generate_manifests() seja rápido ou executado em outra thread separada
# para não bloquear o Watchdog por muito tempo.
Thread(target=generate_manifests).start()
self.last_triggered = current_time
else:
print(f"[VIGIA] Mudança ignorada devido ao debounce (Intervalo de {self.debounce_interval}s).")
def start_file_watcher():
"""Inicia o observador de arquivos em uma thread separada."""
print(f"\n[VIGIA] Iniciando monitoramento da pasta: {WATCH_FOLDER}")
"""Inicia o observador de arquivos para ambas as pastas em uma thread separada."""
event_handler = ManifestEventHandler()
observer = Observer()
observer.schedule(event_handler, WATCH_FOLDER, recursive=True)
# 1. Monitorar a pasta de Samples
print(f"\n[VIGIA] Monitorando Samples: {WATCH_FOLDER_SAMPLE}")
observer.schedule(event_handler, WATCH_FOLDER_SAMPLE, recursive=True)
# 2. Monitorar a pasta de Projetos
print(f"[VIGIA] Monitorando Projetos: {WATCH_FOLDER_PROJECT}")
observer.schedule(event_handler, WATCH_FOLDER_PROJECT, recursive=True)
observer.start()
try:
while True:
@@ -160,4 +203,4 @@ if __name__ == '__main__':
# Inicia o servidor Flask (thread principal)
print("\n[FLASK] Iniciando servidor de upload...")
app.run(host='0.0.0.0', port=5000, debug=False) # Debug mode deve ser False para evitar que rode duas vezes
app.run(host='0.0.0.0', port=33002, debug=True) # Debug mode deve ser False para evitar que rode duas vezes