|
| 1 | +import asyncio |
| 2 | +from typing import Optional, Dict, Any |
| 3 | +import httpx |
| 4 | +import logging |
| 5 | +import os |
| 6 | + |
| 7 | +from .config import settings, reload_settings |
| 8 | + |
| 9 | +logger = logging.getLogger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class SinchFaxService: |
| 13 | + """ |
| 14 | + Sinch Fax API v3 integration ("Phaxio by Sinch"). |
| 15 | +
|
| 16 | + Flow: |
| 17 | + 1) POST /v3/projects/{projectId}/files (multipart/form-data) → returns file id |
| 18 | + 2) POST /v3/projects/{projectId}/faxes { to, file } → returns fax object (id/status) |
| 19 | + 3) GET /v3/projects/{projectId}/faxes/{id} → poll status (optional) |
| 20 | + """ |
| 21 | + |
| 22 | + DEFAULT_BASES = ( |
| 23 | + "https://fax.api.sinch.com/v3", |
| 24 | + "https://us.fax.api.sinch.com/v3", |
| 25 | + "https://eu.fax.api.sinch.com/v3", |
| 26 | + ) |
| 27 | + |
| 28 | + def __init__(self, project_id: str, api_key: str, api_secret: str, base_url: Optional[str] = None): |
| 29 | + self.project_id = project_id |
| 30 | + self.api_key = api_key |
| 31 | + self.api_secret = api_secret |
| 32 | + self.base_url = base_url or os.getenv("SINCH_BASE_URL") or self.DEFAULT_BASES[0] |
| 33 | + |
| 34 | + def is_configured(self) -> bool: |
| 35 | + return bool(self.project_id and self.api_key and self.api_secret) |
| 36 | + |
| 37 | + def _auth(self) -> tuple[str, str]: |
| 38 | + return (self.api_key, self.api_secret) |
| 39 | + |
| 40 | + async def upload_file(self, file_path: str) -> int: |
| 41 | + if not os.path.exists(file_path): |
| 42 | + raise FileNotFoundError(file_path) |
| 43 | + urls = [self.base_url] + [b for b in self.DEFAULT_BASES if b != self.base_url] |
| 44 | + last = None |
| 45 | + for base in urls: |
| 46 | + url = f"{base}/projects/{self.project_id}/files" |
| 47 | + try: |
| 48 | + async with httpx.AsyncClient(timeout=60.0) as client: |
| 49 | + files = {"file": (os.path.basename(file_path), open(file_path, "rb"), "application/pdf")} |
| 50 | + resp = await client.post(url, files=files, auth=self._auth()) |
| 51 | + if resp.status_code < 400: |
| 52 | + data = resp.json() |
| 53 | + file_id = data.get("id") or data.get("data", {}).get("id") |
| 54 | + if file_id is None: |
| 55 | + raise RuntimeError(f"Unexpected Sinch upload response: {data}") |
| 56 | + return int(file_id) |
| 57 | + last = (url, resp.status_code, resp.text) |
| 58 | + except Exception as e: # pragma: no cover |
| 59 | + last = (url, "exception", str(e)) |
| 60 | + continue |
| 61 | + raise RuntimeError(f"Sinch file upload failed: {last}") |
| 62 | + files = {"file": (os.path.basename(file_path), open(file_path, "rb"), "application/pdf")} |
| 63 | + async with httpx.AsyncClient(timeout=60.0) as client: |
| 64 | + resp = await client.post(url, files=files, auth=self._auth()) |
| 65 | + if resp.status_code >= 400: |
| 66 | + raise RuntimeError(f"Sinch file upload error {resp.status_code}: {resp.text}") |
| 67 | + data = resp.json() |
| 68 | + file_id = data.get("id") or data.get("data", {}).get("id") |
| 69 | + if file_id is None: |
| 70 | + raise RuntimeError(f"Unexpected Sinch upload response: {data}") |
| 71 | + return int(file_id) |
| 72 | + |
| 73 | + async def send_fax(self, to_number: str, file_id: int) -> Dict[str, Any]: |
| 74 | + # Normalize number to E.164 if possible |
| 75 | + to = to_number |
| 76 | + if not to.startswith('+'): |
| 77 | + digits = ''.join(c for c in to if c.isdigit()) |
| 78 | + if len(digits) >= 10: |
| 79 | + to = f"+{digits}" |
| 80 | + url = f"{self.base_url}/projects/{self.project_id}/faxes" |
| 81 | + payload = {"to": to, "file": file_id} |
| 82 | + async with httpx.AsyncClient(timeout=30.0) as client: |
| 83 | + resp = await client.post(url, json=payload, auth=self._auth()) |
| 84 | + if resp.status_code >= 400: |
| 85 | + raise RuntimeError(f"Sinch create fax error {resp.status_code}: {resp.text}") |
| 86 | + return resp.json() |
| 87 | + |
| 88 | + async def get_fax_status(self, fax_id: str) -> Dict[str, Any]: |
| 89 | + url = f"{self.BASE_URL}/projects/{self.project_id}/faxes/{fax_id}" |
| 90 | + async with httpx.AsyncClient(timeout=15.0) as client: |
| 91 | + resp = await client.get(url, auth=self._auth()) |
| 92 | + resp.raise_for_status() |
| 93 | + return resp.json() |
| 94 | + |
| 95 | + async def send_fax_file(self, to_number: str, file_path: str) -> Dict[str, Any]: |
| 96 | + """Create a fax by posting the file directly as multipart/form-data. |
| 97 | +
|
| 98 | + This mirrors what the Sinch console does and avoids a separate /files upload. |
| 99 | + """ |
| 100 | + if not os.path.exists(file_path): |
| 101 | + raise FileNotFoundError(file_path) |
| 102 | + to = to_number |
| 103 | + if not to.startswith('+'): |
| 104 | + digits = ''.join(c for c in to if c.isdigit()) |
| 105 | + if len(digits) >= 10: |
| 106 | + to = f"+{digits}" |
| 107 | + url = f"{self.base_url}/projects/{self.project_id}/faxes" |
| 108 | + async with httpx.AsyncClient(timeout=60.0) as client: |
| 109 | + files = { |
| 110 | + "file": (os.path.basename(file_path), open(file_path, "rb"), "application/pdf"), |
| 111 | + "to": (None, to), |
| 112 | + } |
| 113 | + resp = await client.post(url, files=files, auth=self._auth()) |
| 114 | + if resp.status_code >= 400: |
| 115 | + raise RuntimeError(f"Sinch create fax error {resp.status_code}: {resp.text}") |
| 116 | + return resp.json() |
| 117 | + |
| 118 | + |
| 119 | +_sinch_service: Optional[SinchFaxService] = None |
| 120 | + |
| 121 | + |
| 122 | +def get_sinch_service() -> Optional[SinchFaxService]: |
| 123 | + global _sinch_service |
| 124 | + reload_settings() |
| 125 | + if not (settings.sinch_project_id and settings.sinch_api_key and settings.sinch_api_secret): |
| 126 | + _sinch_service = None |
| 127 | + return None |
| 128 | + if _sinch_service is None: |
| 129 | + _sinch_service = SinchFaxService( |
| 130 | + project_id=settings.sinch_project_id, |
| 131 | + api_key=settings.sinch_api_key, |
| 132 | + api_secret=settings.sinch_api_secret, |
| 133 | + base_url=os.getenv("SINCH_BASE_URL") or None, |
| 134 | + ) |
| 135 | + return _sinch_service |
0 commit comments