|
| 1 | +""" |
| 2 | +HumbleFax IMAP polling scaffold (Phase 5): |
| 3 | +
|
| 4 | +- Disabled by default; enable with HUMBLEFAX_IMAP_ENABLED=true |
| 5 | +- Offloads blocking IMAP ops to a thread to avoid blocking the event loop |
| 6 | +- PDF-only attachments; sanitize filenames; cap count and total bytes |
| 7 | +- No PHI in logs; records inbound faxes with minimal canonical fields |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import imaplib |
| 13 | +import email |
| 14 | +from email.message import Message |
| 15 | +import os |
| 16 | +import time |
| 17 | +import hashlib |
| 18 | +from pathlib import Path |
| 19 | +from typing import List, Tuple, Optional |
| 20 | + |
| 21 | +import anyio |
| 22 | + |
| 23 | +from ..config import settings |
| 24 | +from ..db import SessionLocal |
| 25 | +from ..audit import audit_event |
| 26 | + |
| 27 | + |
| 28 | +def _env_bool(name: str, default: bool = False) -> bool: |
| 29 | + v = os.getenv(name, str(default).lower()) |
| 30 | + return str(v).lower() in {"1", "true", "yes", "on"} |
| 31 | + |
| 32 | + |
| 33 | +def _sanitize_filename(name: str) -> str: |
| 34 | + base = name.replace("\\", "/").split("/")[-1] |
| 35 | + # keep alnum, dash, underscore, dot |
| 36 | + safe = "".join(ch for ch in base if ch.isalnum() or ch in {"-", "_", "."}) |
| 37 | + if not safe: |
| 38 | + safe = "attachment.pdf" |
| 39 | + return safe[:128] |
| 40 | + |
| 41 | + |
| 42 | +class HumbleFaxImapWorker: |
| 43 | + def __init__(self) -> None: |
| 44 | + self.enabled = _env_bool("HUMBLEFAX_IMAP_ENABLED", False) |
| 45 | + self.server = os.getenv("HUMBLEFAX_IMAP_SERVER", "") |
| 46 | + self.username = os.getenv("HUMBLEFAX_IMAP_USERNAME", "") |
| 47 | + self.password = os.getenv("HUMBLEFAX_IMAP_PASSWORD", "") |
| 48 | + self.port = int(os.getenv("HUMBLEFAX_IMAP_PORT", "993") or "993") |
| 49 | + self.use_ssl = _env_bool("HUMBLEFAX_IMAP_SSL", True) |
| 50 | + self.poll_seconds = max(30, int(os.getenv("HUMBLEFAX_IMAP_POLL_INTERVAL", "300") or "300")) |
| 51 | + self.max_attach_count = max(1, int(os.getenv("HUMBLEFAX_IMAP_MAX_ATTACH_COUNT", "3") or "3")) |
| 52 | + self.max_attach_mb = max(1, int(os.getenv("HUMBLEFAX_IMAP_MAX_ATTACH_MB", "25") or "25")) |
| 53 | + self._stop = False |
| 54 | + |
| 55 | + def configured(self) -> bool: |
| 56 | + return bool(self.server and self.username and self.password) |
| 57 | + |
| 58 | + async def run_forever(self) -> None: |
| 59 | + if not self.enabled or not self.configured(): |
| 60 | + return |
| 61 | + while not self._stop: |
| 62 | + try: |
| 63 | + await anyio.to_thread.run_sync(self._poll_once) |
| 64 | + except Exception: |
| 65 | + # Swallow errors; back off briefly |
| 66 | + await anyio.sleep(5) |
| 67 | + # Jittered backoff around poll interval (±10%) |
| 68 | + jitter = max(1, int(self.poll_seconds * 0.1)) |
| 69 | + await anyio.sleep(self.poll_seconds - jitter) |
| 70 | + await anyio.sleep(jitter) |
| 71 | + |
| 72 | + def stop(self) -> None: |
| 73 | + self._stop = True |
| 74 | + |
| 75 | + def _connect(self) -> imaplib.IMAP4: |
| 76 | + if self.use_ssl: |
| 77 | + return imaplib.IMAP4_SSL(self.server, self.port) |
| 78 | + return imaplib.IMAP4(self.server, self.port) |
| 79 | + |
| 80 | + def _poll_once(self) -> None: |
| 81 | + """Blocking IMAP poll — runs in a worker thread.""" |
| 82 | + try: |
| 83 | + imap = self._connect() |
| 84 | + except Exception: |
| 85 | + return |
| 86 | + try: |
| 87 | + imap.login(self.username, self.password) |
| 88 | + imap.select("INBOX") |
| 89 | + typ, data = imap.search(None, 'UNSEEN') |
| 90 | + if typ != 'OK': |
| 91 | + return |
| 92 | + uids = (data[0].decode().split() if data and data[0] else []) |
| 93 | + for uid in uids: |
| 94 | + try: |
| 95 | + self._process_message(imap, uid) |
| 96 | + # Mark seen |
| 97 | + try: |
| 98 | + imap.store(uid, '+FLAGS', '(\\Seen)') |
| 99 | + except Exception: |
| 100 | + pass |
| 101 | + except Exception: |
| 102 | + # Skip on error, continue with next message |
| 103 | + continue |
| 104 | + finally: |
| 105 | + try: |
| 106 | + imap.logout() |
| 107 | + except Exception: |
| 108 | + pass |
| 109 | + |
| 110 | + def _process_message(self, imap: imaplib.IMAP4, uid: str) -> None: |
| 111 | + typ, msg_data = imap.fetch(uid, '(RFC822)') |
| 112 | + if typ != 'OK' or not msg_data: |
| 113 | + return |
| 114 | + raw = None |
| 115 | + for part in msg_data: |
| 116 | + if isinstance(part, tuple): |
| 117 | + raw = part[1] |
| 118 | + break |
| 119 | + if not raw: |
| 120 | + return |
| 121 | + msg: Message = email.message_from_bytes(raw) |
| 122 | + attach_saved = 0 |
| 123 | + total_bytes = 0 |
| 124 | + for part in msg.walk(): |
| 125 | + if part.get_content_disposition() != 'attachment': |
| 126 | + continue |
| 127 | + filename = part.get_filename() or 'attachment.pdf' |
| 128 | + safe_name = _sanitize_filename(filename) |
| 129 | + ctype = (part.get_content_type() or '').lower() |
| 130 | + if not safe_name.lower().endswith('.pdf') and 'pdf' not in ctype: |
| 131 | + continue |
| 132 | + payload = part.get_payload(decode=True) or b'' |
| 133 | + size = len(payload) |
| 134 | + # Enforce caps |
| 135 | + if attach_saved >= self.max_attach_count: |
| 136 | + break |
| 137 | + if (total_bytes + size) > (self.max_attach_mb * 1024 * 1024): |
| 138 | + break |
| 139 | + |
| 140 | + # Persist safely into fax data dir |
| 141 | + job_id = email.utils.make_msgid().strip('<>') or str(int(time.time())) |
| 142 | + out_dir = Path(settings.fax_data_dir) / 'inbound' / 'humblefax' |
| 143 | + out_dir.mkdir(parents=True, exist_ok=True) |
| 144 | + out_path = out_dir / f"{job_id}-{safe_name}" |
| 145 | + with open(out_path, 'wb') as f: |
| 146 | + f.write(payload) |
| 147 | + sha256_hex = hashlib.sha256(payload).hexdigest() |
| 148 | + |
| 149 | + # Record in DB (minimal canonical fields) |
| 150 | + from ..db import InboundFax # type: ignore |
| 151 | + from datetime import datetime |
| 152 | + with SessionLocal() as db: |
| 153 | + fx = InboundFax( |
| 154 | + id=job_id, |
| 155 | + from_number=None, |
| 156 | + to_number=None, |
| 157 | + status='received', |
| 158 | + backend='humblefax', |
| 159 | + inbound_backend='humblefax', |
| 160 | + provider_sid=uid, |
| 161 | + pages=None, |
| 162 | + size_bytes=size, |
| 163 | + sha256=sha256_hex, |
| 164 | + pdf_path=str(out_path), |
| 165 | + tiff_path=None, |
| 166 | + mailbox_label='imap', |
| 167 | + retention_until=None, |
| 168 | + pdf_token=None, |
| 169 | + pdf_token_expires_at=None, |
| 170 | + created_at=datetime.utcnow(), |
| 171 | + received_at=datetime.utcnow(), |
| 172 | + updated_at=datetime.utcnow(), |
| 173 | + ) |
| 174 | + try: |
| 175 | + db.add(fx) |
| 176 | + db.commit() |
| 177 | + except Exception: |
| 178 | + db.rollback() |
| 179 | + try: |
| 180 | + audit_event('inbound_received', job_id=job_id, backend='humblefax') |
| 181 | + except Exception: |
| 182 | + pass |
| 183 | + |
| 184 | + attach_saved += 1 |
| 185 | + total_bytes += size |
| 186 | + |
0 commit comments