Files
soft_usite/pkg/services/soporte_imap_service.go
T
Lizandro GuarnizoandClaude Opus 5 8c3ab79e88 feat(soporte): leer el buzón por IMAP, no solo esperar el webhook
Los clientes escriben a soporte@ desde su correo de siempre. Hasta ahora eso
solo llegaba si un proveedor (SendGrid/Mailgun) nos hacía POST; si nadie lo
configuraba, los correos quedaban sin leer en el buzón.

Ahora el cron entra al buzón cada 2 minutos, baja los no leídos, abre ticket
(o los engancha al hilo si son respuesta) y los marca como leídos. La lógica
de ingesta se movió a services para que webhook e IMAP se comporten igual.

La contraseña del buzón se guarda cifrada (AES-GCM con APP_KEY) y no vuelve
al navegador.

De paso, dos bugs que impedían guardar la configuración: el formulario mandaba
id=0 (gorm.Model serializa "ID"), así que cada guardado creaba una fila nueva
en vez de editar la que se usa; y Updates con struct ignoraba los booleanos en
false, así que desactivar algo no tenía efecto.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 18:36:08 -05:00

278 lines
7.5 KiB
Go

package services
import (
"encoding/base64"
"fmt"
"io"
"log"
"mime"
"mime/multipart"
"mime/quotedprintable"
"net/mail"
"strings"
"sync"
"github.com/emersion/go-imap/v2"
"github.com/emersion/go-imap/v2/imapclient"
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
)
// El poller corre por cron; este lock evita que dos corridas se pisen si una
// tarda más que el intervalo (buzón grande, servidor lento).
var imapEnCurso sync.Mutex
// RevisarBuzonSoporte lee los correos sin leer del buzón configurado y los
// convierte en tickets. Cada correo procesado se marca como \Seen, que es lo
// que evita volver a leerlo; la deduplicación por Message-Id es el segundo
// cinturón por si el marcado falla.
func RevisarBuzonSoporte() {
cfg, err := models.GetSoporteWebhookActivo()
if err != nil || cfg == nil || !cfg.ImapActivo || cfg.ImapHost == "" {
return
}
if !imapEnCurso.TryLock() {
log.Printf("[SoporteIMAP] corrida anterior todavía en curso, se salta esta")
return
}
defer imapEnCurso.Unlock()
n, err := revisarBuzon(cfg)
if err != nil {
log.Printf("[SoporteIMAP] %v", err)
return
}
if n > 0 {
log.Printf("[SoporteIMAP] %d correo(s) procesado(s)", n)
}
}
// ProbarConexionImap valida credenciales sin procesar nada — lo usa el botón
// "Probar" de la vista de configuración.
func ProbarConexionImap(cfg *models.SoporteWebhookConfig) error {
c, err := conectarImap(cfg)
if err != nil {
return err
}
defer c.Close()
carpeta := cfg.ImapCarpeta
if carpeta == "" {
carpeta = "INBOX"
}
if _, err := c.Select(carpeta, &imap.SelectOptions{ReadOnly: true}).Wait(); err != nil {
return fmt.Errorf("no se pudo abrir la carpeta %q: %w", carpeta, err)
}
_ = c.Logout().Wait()
return nil
}
func conectarImap(cfg *models.SoporteWebhookConfig) (*imapclient.Client, error) {
pass, err := DescifrarSecretoUmind(cfg.ImapPasswordEnc)
if err != nil || pass == "" {
return nil, fmt.Errorf("no hay contraseña IMAP guardada")
}
port := cfg.ImapPort
if port == 0 {
port = 993
}
addr := fmt.Sprintf("%s:%d", cfg.ImapHost, port)
var c *imapclient.Client
if strings.EqualFold(cfg.ImapEncryption, "starttls") {
c, err = imapclient.DialStartTLS(addr, nil)
} else {
c, err = imapclient.DialTLS(addr, nil)
}
if err != nil {
return nil, fmt.Errorf("no se pudo conectar a %s: %w", addr, err)
}
if err := c.Login(cfg.ImapUsername, pass).Wait(); err != nil {
c.Close()
return nil, fmt.Errorf("login IMAP rechazado para %s: %w", cfg.ImapUsername, err)
}
return c, nil
}
func revisarBuzon(cfg *models.SoporteWebhookConfig) (int, error) {
c, err := conectarImap(cfg)
if err != nil {
return 0, err
}
defer c.Close()
carpeta := cfg.ImapCarpeta
if carpeta == "" {
carpeta = "INBOX"
}
if _, err := c.Select(carpeta, nil).Wait(); err != nil {
return 0, fmt.Errorf("no se pudo abrir la carpeta %q: %w", carpeta, err)
}
buscados, err := c.Search(&imap.SearchCriteria{
NotFlag: []imap.Flag{imap.FlagSeen},
}, &imap.SearchOptions{ReturnAll: true}).Wait()
if err != nil {
return 0, fmt.Errorf("búsqueda de no leídos falló: %w", err)
}
uids := buscados.AllUIDs()
if len(uids) == 0 {
return 0, nil
}
// ponytail: tope por corrida para no atragantarse con un buzón que nunca
// se leyó. Los que sobran quedan sin leer y entran en la corrida siguiente.
const maxPorCorrida = 50
if len(uids) > maxPorCorrida {
uids = uids[:maxPorCorrida]
}
msgs, err := c.Fetch(imap.UIDSetNum(uids...), &imap.FetchOptions{
BodySection: []*imap.FetchItemBodySection{{}},
}).Collect()
if err != nil {
return 0, fmt.Errorf("descarga de correos falló: %w", err)
}
procesados := 0
for _, m := range msgs {
var crudo []byte
for _, b := range m.BodySection {
crudo = b.Bytes
break
}
if len(crudo) == 0 {
continue
}
correo, err := parsearCorreo(crudo)
if err != nil {
log.Printf("[SoporteIMAP] no se pudo leer un correo (uid=%v): %v", m.UID, err)
continue
}
if IngestarCorreoSoporte(cfg, correo) {
procesados++
}
// Se marca leído aunque se haya ignorado por duplicado: si no, se
// vuelve a bajar en cada corrida para siempre.
if err := c.Store(imap.UIDSetNum(m.UID), &imap.StoreFlags{
Op: imap.StoreFlagsAdd,
Silent: true,
Flags: []imap.Flag{imap.FlagSeen},
}, nil).Close(); err != nil {
log.Printf("[SoporteIMAP] no se pudo marcar leído el uid=%v: %v", m.UID, err)
}
}
return procesados, nil
}
// parsearCorreo saca remitente, asunto y cuerpo de texto de un mensaje RFC822.
func parsearCorreo(crudo []byte) (CorreoSoporte, error) {
msg, err := mail.ReadMessage(strings.NewReader(string(crudo)))
if err != nil {
return CorreoSoporte{}, err
}
dec := new(mime.WordDecoder)
decodificar := func(s string) string {
if out, err := dec.DecodeHeader(s); err == nil {
return out
}
return s
}
from := decodificar(msg.Header.Get("From"))
nombre := ExtraerNombre(from)
if dir, err := mail.ParseAddress(from); err == nil && dir.Name != "" {
nombre = dir.Name
}
cuerpo, err := cuerpoDeTexto(msg.Header.Get("Content-Type"), msg.Body)
if err != nil {
return CorreoSoporte{}, err
}
return CorreoSoporte{
From: from,
FromName: nombre,
Subject: decodificar(msg.Header.Get("Subject")),
Texto: limpiarCitas(cuerpo),
MessageID: strings.TrimSpace(msg.Header.Get("Message-Id")),
}, nil
}
// cuerpoDeTexto devuelve el text/plain del correo; si es multipart baja por las
// partes hasta encontrarlo y cae al HTML solo si no hay texto plano.
func cuerpoDeTexto(contentType string, cuerpo io.Reader) (string, error) {
medio, params, err := mime.ParseMediaType(contentType)
if err != nil {
medio = "text/plain"
params = map[string]string{}
}
if !strings.HasPrefix(medio, "multipart/") {
b, err := io.ReadAll(io.LimitReader(cuerpo, 1<<20))
if err != nil {
return "", err
}
return string(b), nil
}
frontera := params["boundary"]
if frontera == "" {
return "", fmt.Errorf("multipart sin boundary")
}
lector := multipart.NewReader(cuerpo, frontera)
var html string
for {
parte, err := lector.NextPart()
if err == io.EOF {
break
}
if err != nil {
return "", err
}
tipoParte, _, _ := mime.ParseMediaType(parte.Header.Get("Content-Type"))
if strings.HasPrefix(tipoParte, "multipart/") {
anidado, err := cuerpoDeTexto(parte.Header.Get("Content-Type"), parte)
if err == nil && anidado != "" {
return anidado, nil
}
continue
}
if tipoParte != "text/plain" && tipoParte != "text/html" {
continue
}
var lect io.Reader = io.LimitReader(parte, 1<<20)
switch strings.ToLower(parte.Header.Get("Content-Transfer-Encoding")) {
case "quoted-printable":
lect = quotedprintable.NewReader(lect)
case "base64":
lect = base64.NewDecoder(base64.StdEncoding, lect)
}
b, err := io.ReadAll(lect)
if err != nil {
continue
}
if tipoParte == "text/plain" {
return string(b), nil
}
html = string(b)
}
return html, nil
}
// limpiarCitas corta el correo en la primera línea citada o en el separador
// típico de respuesta, para que el ticket no repita todo el hilo anterior.
func limpiarCitas(texto string) string {
lineas := strings.Split(strings.ReplaceAll(texto, "\r\n", "\n"), "\n")
var out []string
for _, l := range lineas {
t := strings.TrimSpace(l)
if strings.HasPrefix(t, ">") ||
strings.HasPrefix(t, "-----Original Message-----") ||
strings.HasPrefix(t, "-----Mensaje original-----") ||
(strings.HasPrefix(t, "El ") && strings.HasSuffix(t, "escribió:")) ||
(strings.HasPrefix(t, "On ") && strings.HasSuffix(t, "wrote:")) {
break
}
out = append(out, l)
}
return strings.TrimSpace(strings.Join(out, "\n"))
}