2026-06-01 16:31:24 -05:00
|
|
|
|
|
|
|
|
import sys
|
|
|
|
|
import json
|
|
|
|
|
import os
|
|
|
|
|
import email_utilities
|
|
|
|
|
import outlook_utilities
|
|
|
|
|
import database_utilities
|
|
|
|
|
import logger_utilities
|
|
|
|
|
from datetime import datetime, timedelta
|
|
|
|
|
from config_loader import CONFIG
|
|
|
|
|
|
|
|
|
|
########################################################
|
|
|
|
|
def obtener_token():
|
|
|
|
|
try:
|
|
|
|
|
print("Intentando obtener token de acceso...")
|
|
|
|
|
outlook_token = outlook_utilities.get_access_token()
|
|
|
|
|
print("✅ Token obtenido exitosamente.")
|
|
|
|
|
print(f"Token prefix: {outlook_token[:25]}...")
|
|
|
|
|
return outlook_token
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"❌ Error: {e}")
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
########################################################
|
|
|
|
|
def descargar_correos(outlook_token, fecha_inicio, fecha_fin):
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
print("\n" + "="*60)
|
|
|
|
|
print(f"[MAIL] {CONFIG.client.email}")
|
|
|
|
|
|
|
|
|
|
emails = outlook_utilities.get_emails(CONFIG.client.email, outlook_token, fecha_inicio, fecha_fin)
|
|
|
|
|
print(f"Se encontraron {len(emails)} correos.")
|
|
|
|
|
|
|
|
|
|
return emails
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
print(f"❌ Error: {e}")
|
|
|
|
|
sys.exit(1)
|
|
|
|
|
|
|
|
|
|
return []
|
|
|
|
|
|
|
|
|
|
########################################################
|
|
|
|
|
def descargar_adjuntos_de_correos(outlook_token, emails, ruta_descarga):
|
|
|
|
|
try:
|
2026-06-01 18:05:44 -05:00
|
|
|
emails_con_adjuntos = []
|
2026-06-01 16:31:24 -05:00
|
|
|
for email in emails:
|
|
|
|
|
# Guardar lista original para el log
|
|
|
|
|
adjuntos = outlook_utilities.download_attachments(
|
|
|
|
|
CONFIG.client.email,
|
|
|
|
|
email['id'],
|
|
|
|
|
outlook_token,
|
|
|
|
|
ruta_descarga)
|
|
|
|
|
if adjuntos:
|
2026-06-01 18:05:44 -05:00
|
|
|
email['adjuntos'] = adjuntos
|
|
|
|
|
emails_con_adjuntos.append(email)
|
2026-06-01 16:31:24 -05:00
|
|
|
|
2026-06-01 18:05:44 -05:00
|
|
|
return emails_con_adjuntos
|
2026-06-01 16:31:24 -05:00
|
|
|
|
|
|
|
|
except Exception as ex:
|
|
|
|
|
print(f" ❌ Error procesando {email['id'][:10]}: {ex}")
|
|
|
|
|
|
|
|
|
|
return []
|
|
|
|
|
|
2026-06-01 18:05:44 -05:00
|
|
|
########################################################
|
|
|
|
|
def dejar_mail_si_tiene_adjunto_pdf_o_xml(emails):
|
|
|
|
|
"""
|
|
|
|
|
Recorre los adjuntos de cada email y elimina los que no tengan extensión pdf o xml
|
|
|
|
|
actualiza la lista de adjuntos del correo
|
|
|
|
|
si el mail no tiene pdf ni xml también se elimina
|
|
|
|
|
"""
|
|
|
|
|
emails_con_pdf_o_xml = []
|
|
|
|
|
for email in emails:
|
|
|
|
|
adjuntos_validos = [adjunto for adjunto in email['adjuntos'] if adjunto.lower().endswith(('.pdf', '.xml'))]
|
|
|
|
|
if adjuntos_validos:
|
|
|
|
|
email['adjuntos'] = adjuntos_validos
|
|
|
|
|
emails_con_pdf_o_xml.append(email)
|
|
|
|
|
return emails_con_pdf_o_xml
|
|
|
|
|
|
2026-06-01 16:31:24 -05:00
|
|
|
########################################################
|
|
|
|
|
def main():
|
|
|
|
|
|
|
|
|
|
# Inicializar Base de Datos
|
|
|
|
|
database_utilities.init_db()
|
|
|
|
|
|
|
|
|
|
# Calcular fechas
|
|
|
|
|
hoy = datetime.now()
|
|
|
|
|
ayer = hoy - timedelta(days=25)
|
|
|
|
|
|
|
|
|
|
fecha_inicio = ayer.strftime("%Y-%m-%d")
|
|
|
|
|
fecha_fin = hoy.strftime("%Y-%m-%d")
|
|
|
|
|
|
|
|
|
|
print(f"Rango de búsqueda: {fecha_inicio} al {fecha_fin}")
|
|
|
|
|
|
|
|
|
|
outlook_token = obtener_token()
|
|
|
|
|
# se descarga todos los correos en el rango de fecha ingresado
|
|
|
|
|
# tengan o no adjuntos
|
|
|
|
|
emails = descargar_correos(outlook_token, fecha_inicio, fecha_fin)
|
|
|
|
|
|
|
|
|
|
# se verifica si estos correos ya estan en la base de datos
|
|
|
|
|
# si ya esta registrado, se quita del listado
|
|
|
|
|
# si no esta se inserta en la base de datos
|
|
|
|
|
emails = email_utilities.quitar_correos_ya_registrados_en_base_de_datos(emails)
|
|
|
|
|
|
2026-06-01 18:05:44 -05:00
|
|
|
# descargar adjuntos de cada correo y agregar
|
|
|
|
|
emails = descargar_adjuntos_de_correos(outlook_token, emails, CONFIG.client.ruta_descarga)
|
2026-06-01 16:31:24 -05:00
|
|
|
|
2026-06-01 18:05:44 -05:00
|
|
|
# with open("correos_con_adjuntos.json", "w", encoding="utf-8") as f:
|
|
|
|
|
# json.dump(emails, f, ensure_ascii=False, indent=4)
|
2026-06-01 16:31:24 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
# si el correo tiene archivos zip, se descomprimen y se agregan a
|
|
|
|
|
# la lista de archivos adjuntos
|
2026-06-01 18:05:44 -05:00
|
|
|
emails = email_utilities.descomprimir_adjuntos(emails, CONFIG.client.ruta_descarga)
|
|
|
|
|
|
|
|
|
|
# se eliminan mails que no tengan adjunto pdf o xml
|
|
|
|
|
# también se eliminar los adjuntos no que sean xml y pdf
|
|
|
|
|
emails = dejar_mail_si_tiene_adjunto_pdf_o_xml(emails)
|
2026-06-01 16:31:24 -05:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
for e in emails:
|
|
|
|
|
print(f"\n📬 [{e['fecha']}] {e['subject'][:80]}...")
|
2026-06-01 18:05:44 -05:00
|
|
|
|
|
|
|
|
#adjuntos originales
|
|
|
|
|
print(f" ├── 📂 Adjuntos originales:")
|
|
|
|
|
for idx, a in enumerate(e['adjuntos']):
|
|
|
|
|
prefijo = " │ └── " if idx == len(e['adjuntos'])-1 else " │ ├── "
|
|
|
|
|
print(f"{prefijo}{a}")
|
|
|
|
|
|
2026-06-01 16:31:24 -05:00
|
|
|
########################################################
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
# Configurar Logger (Redirige stdout a archivo y consola)
|
|
|
|
|
log_path = logger_utilities.setup_logger()
|
|
|
|
|
logger_utilities.limpiar_logs_antiguos(dias=30)
|
|
|
|
|
|
|
|
|
|
inicio_ejecucion = datetime.now()
|
|
|
|
|
print("="*60)
|
|
|
|
|
print(f"🚀 INICIO DE EJECUCIÓN: {inicio_ejecucion.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
|
print(f"📄 Log guardado en: {log_path}")
|
|
|
|
|
print("="*60)
|
|
|
|
|
|
|
|
|
|
main()
|
|
|
|
|
|
|
|
|
|
fin_ejecucion = datetime.now()
|
|
|
|
|
duracion = fin_ejecucion - inicio_ejecucion
|
|
|
|
|
print("\n" + "="*60)
|
|
|
|
|
print(f"🏁 FIN DE EJECUCIÓN: {fin_ejecucion.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
|
|
|
print(f"⏱️ Duración total: {str(duracion).split('.')[0]}") # Sin microsegundos
|
|
|
|
|
print("="*60)
|