127 lines
4.0 KiB
Python
127 lines
4.0 KiB
Python
|
|||
|
|
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:
|
||
|
|
|
||
|
|
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:
|
||
|
|
email['adjuntos'] = adjuntos
|
||
|
|
|
||
|
|
return emails
|
||
|
|
|
||
|
|
except Exception as ex:
|
||
|
|
print(f" ❌ Error procesando {email['id'][:10]}: {ex}")
|
||
|
|
|
||
|
|
return []
|
||
|
|
|
||
|
|
########################################################
|
||
|
|
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)
|
||
|
|
|
||
|
|
# descargar todos los adjuntos de cada mail
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
# si el correo tiene archivos zip, se descomprimen y se agregan a
|
||
|
|
# la lista de archivos adjuntos
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
# se evalua los adjuntos del correo:
|
||
|
|
# 1. se quita de la lista el correo si no tiene adjunto
|
||
|
|
# 2. se quita de la lista el correo si no tiene
|
||
|
|
|
||
|
|
for e in emails:
|
||
|
|
print(f"\n📬 [{e['fecha']}] {e['subject'][:80]}...")
|
||
|
|
archivos_adjuntos = descargar_adjunto_de_correo(outlook_token, e['id'], CONFIG.client.ruta_descarga)
|
||
|
|
|
||
|
|
########################################################
|
||
|
|
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)
|