File size: 1,661 Bytes
0387a1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
from __future__ import annotations

import logging
import re
from email.header import decode_header, make_header
from typing import Optional


LOGGER_NAME = "email_assistant"


def setup_logging(level: str) -> None:
    """
    Global logging setup. FastAPI/Uvicorn will inherit this config.
    """
    logging.basicConfig(
        level=getattr(logging, level.upper(), logging.INFO),
        format="%(asctime)s %(levelname)s %(name)s - %(message)s",
    )


def get_logger(name: str = LOGGER_NAME) -> logging.Logger:
    return logging.getLogger(name)


_TAG_RE = re.compile(r"<[^>]+>")


def strip_html(html: str) -> str:
    """
    Small HTML -> text helper (keeps dependencies minimal).
    If you expect complex HTML emails, replace with BeautifulSoup.
    """
    text = _TAG_RE.sub("", html)
    text = re.sub(r"\r\n|\r", "\n", text)
    text = re.sub(r"[ \t]+\n", "\n", text)
    text = re.sub(r"\n{3,}", "\n\n", text)
    return text.strip()


def decode_mime_words(value: Optional[str]) -> str:
    if not value:
        return ""
    try:
        return str(make_header(decode_header(value)))
    except Exception:
        return value


def normalize_subject(subject: str) -> str:
    """
    Normalize for threading: remove repeated 'Re:'/'Fwd:' prefixes and trim.
    """
    s = (subject or "").strip()
    while True:
        lowered = s.lower()
        if lowered.startswith("re:"):
            s = s[3:].strip()
            continue
        if lowered.startswith("fwd:"):
            s = s[4:].strip()
            continue
        if lowered.startswith("fw:"):
            s = s[3:].strip()
            continue
        break
    return s