95 lines
3.4 KiB
Python
95 lines
3.4 KiB
Python
import os
|
|
from flask import Flask, request, jsonify
|
|
from flask_cors import CORS
|
|
from werkzeug.utils import secure_filename
|
|
|
|
# Importa suas funções e configurações existentes
|
|
from main import process_single_file, rebuild_indexes
|
|
from utils import MMP_FOLDER, MMPZ_FOLDER
|
|
|
|
app = Flask(__name__)
|
|
CORS(app) # Permite que o HTML converse com o servidor
|
|
|
|
# Configurações de extensão
|
|
ALLOWED_EXTENSIONS = {"mmp", "mmpz"}
|
|
|
|
|
|
def allowed_file(filename):
|
|
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
|
|
|
|
|
@app.route("/api/upload", methods=["POST"])
|
|
def upload_file():
|
|
# 1. Verificações Básicas
|
|
if "project_file" not in request.files:
|
|
return jsonify({"error": "Nenhum arquivo enviado"}), 400
|
|
|
|
file = request.files["project_file"]
|
|
|
|
if file.filename == "":
|
|
return jsonify({"error": "Nome do arquivo vazio"}), 400
|
|
|
|
if file and allowed_file(file.filename):
|
|
filename = secure_filename(file.filename)
|
|
|
|
# 2. Define onde salvar (MMP ou MMPZ)
|
|
if filename.endswith(".mmpz"):
|
|
save_path = os.path.join(MMPZ_FOLDER, filename)
|
|
else:
|
|
save_path = os.path.join(MMP_FOLDER, filename)
|
|
|
|
# Salva o arquivo físico
|
|
try:
|
|
file.save(save_path)
|
|
print(f"Arquivo salvo em: {save_path}")
|
|
except Exception as e:
|
|
return jsonify({"error": f"Falha ao salvar disco: {str(e)}"}), 500
|
|
|
|
# 3. DISPARA SEU PIPELINE (Processamento)
|
|
# Chama a função do seu main.py para gerar WAV e extrair dados
|
|
result = process_single_file(filename)
|
|
|
|
if result["success"]:
|
|
# 4. Atualiza o site.data.all (all.json)
|
|
rebuild_indexes()
|
|
|
|
return jsonify(
|
|
{"message": "Projeto processado com sucesso!", "data": result["data"]}
|
|
), 200
|
|
else:
|
|
return jsonify({"error": f"Erro no processamento: {result['error']}"}), 500
|
|
|
|
return jsonify({"error": "Tipo de arquivo não permitido"}), 400
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("Iniciando Servidor de Upload MMP...")
|
|
|
|
# Tenta localizar os certificados reais do servidor (Comum em servidores Linux/Apache/Nginx)
|
|
# Ajuste esses caminhos se souber onde os certificados do alice.ufsj.edu.br estão
|
|
cert_path = "/etc/letsencrypt/live/alice.ufsj.edu.br/fullchain.pem"
|
|
key_path = "/etc/letsencrypt/live/alice.ufsj.edu.br/privkey.pem"
|
|
|
|
# Opção 1: Usar certificado real (O ideal - Navegador aceita de primeira)
|
|
if os.path.exists(cert_path) and os.path.exists(key_path):
|
|
print("Certificados encontrados! Rodando HTTPS seguro na porta 33002.")
|
|
context = (cert_path, key_path)
|
|
# Use host='0.0.0.0' para garantir que escute externamente
|
|
app.run(host="0.0.0.0", port=33002, ssl_context=context, debug=True)
|
|
|
|
# Opção 2: Modo 'adhoc' (Certificado temporário gerado na hora)
|
|
else:
|
|
print(
|
|
"Certificados reais não encontrados. Usando modo 'adhoc' (Auto-assinado)."
|
|
)
|
|
print(
|
|
"ATENÇÃO: O navegador vai avisar que 'Não é seguro'. Você precisará autorizar."
|
|
)
|
|
# Requer: pip install pyopenssl
|
|
try:
|
|
app.run(host="0.0.0.0", port=33002, ssl_context="adhoc", debug=True)
|
|
except Exception as e:
|
|
print(f"Erro ao iniciar SSL adhoc: {e}")
|
|
print("Tentando rodar em HTTP simples (pode dar erro de Mixed Content)...")
|
|
app.run(host="0.0.0.0", port=33002, debug=True)
|