124 lines
4.0 KiB
Python
124 lines
4.0 KiB
Python
"""
|
|
Script para desensamblar los emails y generar un archivo de texto con la cronología de los mensajes.
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from utils.email_parser import procesar_eml
|
|
from utils.markdown_handler import cargar_cronologia_existente
|
|
from utils.beautify import BeautifyProcessor
|
|
import json
|
|
|
|
# Forzar UTF-8 en la salida estándar
|
|
sys.stdout.reconfigure(encoding="utf-8")
|
|
|
|
|
|
def generar_indice(mensajes):
|
|
"""
|
|
Genera una lista de mensajes usando el formato de Obsidian
|
|
"""
|
|
indice = "# Índice de Mensajes\n\n"
|
|
|
|
for mensaje in mensajes:
|
|
indice += mensaje.get_index_entry() + "\n"
|
|
|
|
indice += "\n---\n\n"
|
|
return indice
|
|
|
|
|
|
def main():
|
|
# Cargar configuraciones del entorno
|
|
configs = json.loads(os.environ.get("SCRIPT_CONFIGS", "{}"))
|
|
|
|
# Obtener working directory
|
|
working_directory = configs.get("working_directory", ".")
|
|
|
|
# Obtener configuraciones de nivel 2 (grupo)
|
|
group_config = configs.get("level2", {})
|
|
cronologia_file = group_config.get("cronologia_file", "cronologia.md")
|
|
attachments_dir = group_config.get("attachments_dir", "adjuntos")
|
|
|
|
work_config = configs.get("level3", {})
|
|
outpu_directory = work_config.get("output_directory", ".")
|
|
|
|
# Construir rutas absolutas
|
|
input_dir = (
|
|
working_directory # El directorio de trabajo es el directorio de entrada
|
|
)
|
|
output_file = os.path.join(outpu_directory, cronologia_file)
|
|
attachments_path = os.path.join(working_directory, attachments_dir)
|
|
|
|
# Debug prints
|
|
print(f"Working directory: {working_directory}")
|
|
print(f"Input directory: {input_dir}")
|
|
print(f"Output directory: {outpu_directory}")
|
|
print(f"Cronologia file: {output_file}")
|
|
print(f"Attachments directory: {attachments_path}")
|
|
|
|
# Obtener el directorio donde está el script actual
|
|
script_dir = os.path.dirname(os.path.abspath(__file__))
|
|
beautify_rules = os.path.join(script_dir, "config", "beautify_rules.json")
|
|
beautifier = BeautifyProcessor(beautify_rules)
|
|
print(f"Beautify rules file: {beautify_rules}")
|
|
|
|
# Ensure directories exist
|
|
os.makedirs(attachments_path, exist_ok=True)
|
|
|
|
# Check if input directory exists and has files
|
|
input_path = Path(input_dir)
|
|
if not input_path.exists():
|
|
print(f"Error: Input directory {input_path} does not exist")
|
|
return
|
|
|
|
eml_files = list(input_path.glob("*.eml"))
|
|
print(f"Found {len(eml_files)} .eml files")
|
|
|
|
mensajes = []
|
|
print(f"Loaded {len(mensajes)} existing messages")
|
|
mensajes_hash = {msg.hash for msg in mensajes}
|
|
|
|
total_procesados = 0
|
|
total_nuevos = 0
|
|
mensajes_duplicados = 0
|
|
|
|
for archivo in eml_files:
|
|
print(f"\nProcessing {archivo}")
|
|
nuevos_mensajes = procesar_eml(archivo, attachments_path)
|
|
total_procesados += len(nuevos_mensajes)
|
|
|
|
# Verificar duplicados y aplicar beautify solo a los mensajes nuevos
|
|
for msg in nuevos_mensajes:
|
|
if msg.hash not in mensajes_hash:
|
|
# Aplicar beautify solo si el mensaje es nuevo
|
|
msg.contenido = beautifier.process_text(msg.contenido)
|
|
mensajes.append(msg)
|
|
mensajes_hash.add(msg.hash)
|
|
total_nuevos += 1
|
|
else:
|
|
mensajes_duplicados += 1
|
|
|
|
print("\nEstadísticas de procesamiento:")
|
|
print("- Total mensajes encontrados:", total_procesados)
|
|
print("- Mensajes únicos añadidos:", total_nuevos)
|
|
print("- Mensajes duplicados ignorados:", mensajes_duplicados)
|
|
|
|
# Ordenar mensajes de más reciente a más antiguo
|
|
mensajes.sort(key=lambda x: x.fecha, reverse=True)
|
|
|
|
# Generar el índice
|
|
indice = generar_indice(mensajes)
|
|
|
|
# Escribir el archivo con el índice y los mensajes
|
|
print(f"\nWriting {len(mensajes)} messages to {output_file}")
|
|
with open(output_file, "w", encoding="utf-8") as f:
|
|
# Primero escribir el índice
|
|
f.write(indice)
|
|
# Luego escribir todos los mensajes
|
|
for msg in mensajes:
|
|
f.write(msg.to_markdown())
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|