|
| 1 | +""" |
| 2 | +Freemail 邮箱服务实现 |
| 3 | +基于自部署 Cloudflare Worker 临时邮箱服务 (https://github.com/idinging/freemail) |
| 4 | +""" |
| 5 | + |
| 6 | +import re |
| 7 | +import time |
| 8 | +import logging |
| 9 | +import random |
| 10 | +import string |
| 11 | +from typing import Optional, Dict, Any, List |
| 12 | + |
| 13 | +from .base import BaseEmailService, EmailServiceError, EmailServiceType |
| 14 | +from ..core.http_client import HTTPClient, RequestConfig |
| 15 | +from ..config.constants import OTP_CODE_PATTERN |
| 16 | + |
| 17 | +logger = logging.getLogger(__name__) |
| 18 | + |
| 19 | + |
| 20 | +class FreemailService(BaseEmailService): |
| 21 | + """ |
| 22 | + Freemail 邮箱服务 |
| 23 | + 基于自部署 Cloudflare Worker 的临时邮箱 |
| 24 | + """ |
| 25 | + |
| 26 | + def __init__(self, config: Dict[str, Any] = None, name: str = None): |
| 27 | + """ |
| 28 | + 初始化 Freemail 服务 |
| 29 | +
|
| 30 | + Args: |
| 31 | + config: 配置字典,支持以下键: |
| 32 | + - base_url: Worker 域名地址 (必需) |
| 33 | + - admin_token: Admin Token,对应 JWT_TOKEN (必需) |
| 34 | + - domain: 邮箱域名,如 example.com |
| 35 | + - timeout: 请求超时时间,默认 30 |
| 36 | + - max_retries: 最大重试次数,默认 3 |
| 37 | + name: 服务名称 |
| 38 | + """ |
| 39 | + super().__init__(EmailServiceType.FREEMAIL, name) |
| 40 | + |
| 41 | + required_keys = ["base_url", "admin_token"] |
| 42 | + missing_keys = [key for key in required_keys if not (config or {}).get(key)] |
| 43 | + if missing_keys: |
| 44 | + raise ValueError(f"缺少必需配置: {missing_keys}") |
| 45 | + |
| 46 | + default_config = { |
| 47 | + "timeout": 30, |
| 48 | + "max_retries": 3, |
| 49 | + } |
| 50 | + self.config = {**default_config, **(config or {})} |
| 51 | + self.config["base_url"] = self.config["base_url"].rstrip("/") |
| 52 | + |
| 53 | + http_config = RequestConfig( |
| 54 | + timeout=self.config["timeout"], |
| 55 | + max_retries=self.config["max_retries"], |
| 56 | + ) |
| 57 | + self.http_client = HTTPClient(proxy_url=None, config=http_config) |
| 58 | + |
| 59 | + # 缓存 domain 列表 |
| 60 | + self._domains = [] |
| 61 | + |
| 62 | + def _get_headers(self) -> Dict[str, str]: |
| 63 | + """构造 admin 请求头""" |
| 64 | + return { |
| 65 | + "Authorization": f"Bearer {self.config['admin_token']}", |
| 66 | + "Content-Type": "application/json", |
| 67 | + "Accept": "application/json", |
| 68 | + } |
| 69 | + |
| 70 | + def _make_request(self, method: str, path: str, **kwargs) -> Any: |
| 71 | + """ |
| 72 | + 发送请求并返回 JSON 数据 |
| 73 | +
|
| 74 | + Args: |
| 75 | + method: HTTP 方法 |
| 76 | + path: 请求路径(以 / 开头) |
| 77 | + **kwargs: 传递给 http_client.request 的额外参数 |
| 78 | +
|
| 79 | + Returns: |
| 80 | + 响应 JSON 数据 |
| 81 | +
|
| 82 | + Raises: |
| 83 | + EmailServiceError: 请求失败 |
| 84 | + """ |
| 85 | + url = f"{self.config['base_url']}{path}" |
| 86 | + kwargs.setdefault("headers", {}) |
| 87 | + kwargs["headers"].update(self._get_headers()) |
| 88 | + |
| 89 | + try: |
| 90 | + response = self.http_client.request(method, url, **kwargs) |
| 91 | + |
| 92 | + if response.status_code >= 400: |
| 93 | + error_msg = f"请求失败: {response.status_code}" |
| 94 | + try: |
| 95 | + error_data = response.json() |
| 96 | + error_msg = f"{error_msg} - {error_data}" |
| 97 | + except Exception: |
| 98 | + error_msg = f"{error_msg} - {response.text[:200]}" |
| 99 | + self.update_status(False, EmailServiceError(error_msg)) |
| 100 | + raise EmailServiceError(error_msg) |
| 101 | + |
| 102 | + try: |
| 103 | + return response.json() |
| 104 | + except Exception: |
| 105 | + return {"raw_response": response.text} |
| 106 | + |
| 107 | + except Exception as e: |
| 108 | + self.update_status(False, e) |
| 109 | + if isinstance(e, EmailServiceError): |
| 110 | + raise |
| 111 | + raise EmailServiceError(f"请求失败: {method} {path} - {e}") |
| 112 | + |
| 113 | + def _ensure_domains(self): |
| 114 | + """获取并缓存可用域名列表""" |
| 115 | + if not self._domains: |
| 116 | + try: |
| 117 | + domains = self._make_request("GET", "/api/domains") |
| 118 | + if isinstance(domains, list): |
| 119 | + self._domains = domains |
| 120 | + except Exception as e: |
| 121 | + logger.warning(f"获取 Freemail 域名列表失败: {e}") |
| 122 | + |
| 123 | + def create_email(self, config: Dict[str, Any] = None) -> Dict[str, Any]: |
| 124 | + """ |
| 125 | + 通过 API 创建临时邮箱 |
| 126 | +
|
| 127 | + Returns: |
| 128 | + 包含邮箱信息的字典: |
| 129 | + - email: 邮箱地址 |
| 130 | + - service_id: 同 email(用作标识) |
| 131 | + """ |
| 132 | + self._ensure_domains() |
| 133 | + |
| 134 | + req_config = config or {} |
| 135 | + domain_index = 0 |
| 136 | + target_domain = req_config.get("domain") or self.config.get("domain") |
| 137 | + |
| 138 | + if target_domain and self._domains: |
| 139 | + for i, d in enumerate(self._domains): |
| 140 | + if d == target_domain: |
| 141 | + domain_index = i |
| 142 | + break |
| 143 | + |
| 144 | + prefix = req_config.get("name") |
| 145 | + try: |
| 146 | + if prefix: |
| 147 | + body = { |
| 148 | + "local": prefix, |
| 149 | + "domainIndex": domain_index |
| 150 | + } |
| 151 | + resp = self._make_request("POST", "/api/create", json=body) |
| 152 | + else: |
| 153 | + params = {"domainIndex": domain_index} |
| 154 | + length = req_config.get("length") |
| 155 | + if length: |
| 156 | + params["length"] = length |
| 157 | + resp = self._make_request("GET", "/api/generate", params=params) |
| 158 | + |
| 159 | + email = resp.get("email") |
| 160 | + if not email: |
| 161 | + raise EmailServiceError(f"创建邮箱失败,未返回邮箱地址: {resp}") |
| 162 | + |
| 163 | + email_info = { |
| 164 | + "email": email, |
| 165 | + "service_id": email, |
| 166 | + "id": email, |
| 167 | + "created_at": time.time(), |
| 168 | + } |
| 169 | + |
| 170 | + logger.info(f"成功创建 Freemail 邮箱: {email}") |
| 171 | + self.update_status(True) |
| 172 | + return email_info |
| 173 | + |
| 174 | + except Exception as e: |
| 175 | + self.update_status(False, e) |
| 176 | + if isinstance(e, EmailServiceError): |
| 177 | + raise |
| 178 | + raise EmailServiceError(f"创建邮箱失败: {e}") |
| 179 | + |
| 180 | + def get_verification_code( |
| 181 | + self, |
| 182 | + email: str, |
| 183 | + email_id: str = None, |
| 184 | + timeout: int = 120, |
| 185 | + pattern: str = OTP_CODE_PATTERN, |
| 186 | + otp_sent_at: Optional[float] = None, |
| 187 | + ) -> Optional[str]: |
| 188 | + """ |
| 189 | + 从 Freemail 邮箱获取验证码 |
| 190 | +
|
| 191 | + Args: |
| 192 | + email: 邮箱地址 |
| 193 | + email_id: 未使用,保留接口兼容 |
| 194 | + timeout: 超时时间(秒) |
| 195 | + pattern: 验证码正则 |
| 196 | + otp_sent_at: OTP 发送时间戳(暂未使用) |
| 197 | +
|
| 198 | + Returns: |
| 199 | + 验证码字符串,超时返回 None |
| 200 | + """ |
| 201 | + logger.info(f"正在从 Freemail 邮箱 {email} 获取验证码...") |
| 202 | + |
| 203 | + start_time = time.time() |
| 204 | + seen_mail_ids: set = set() |
| 205 | + |
| 206 | + while time.time() - start_time < timeout: |
| 207 | + try: |
| 208 | + mails = self._make_request("GET", "/api/emails", params={"mailbox": email, "limit": 20}) |
| 209 | + if not isinstance(mails, list): |
| 210 | + time.sleep(3) |
| 211 | + continue |
| 212 | + |
| 213 | + for mail in mails: |
| 214 | + mail_id = mail.get("id") |
| 215 | + if not mail_id or mail_id in seen_mail_ids: |
| 216 | + continue |
| 217 | + |
| 218 | + seen_mail_ids.add(mail_id) |
| 219 | + |
| 220 | + sender = str(mail.get("sender", "")).lower() |
| 221 | + subject = str(mail.get("subject", "")) |
| 222 | + preview = str(mail.get("preview", "")) |
| 223 | + |
| 224 | + content = f"{sender}\n{subject}\n{preview}" |
| 225 | + |
| 226 | + if "openai" not in content.lower(): |
| 227 | + continue |
| 228 | + |
| 229 | + # 尝试直接使用 Freemail 提取的验证码 |
| 230 | + v_code = mail.get("verification_code") |
| 231 | + if v_code: |
| 232 | + logger.info(f"从 Freemail 邮箱 {email} 找到验证码: {v_code}") |
| 233 | + self.update_status(True) |
| 234 | + return v_code |
| 235 | + |
| 236 | + # 如果没有直接提供,通过正则匹配 preview |
| 237 | + match = re.search(pattern, content) |
| 238 | + if match: |
| 239 | + code = match.group(1) |
| 240 | + logger.info(f"从 Freemail 邮箱 {email} 找到验证码: {code}") |
| 241 | + self.update_status(True) |
| 242 | + return code |
| 243 | + |
| 244 | + # 如果依然未找到,获取邮件详情进行匹配 |
| 245 | + try: |
| 246 | + detail = self._make_request("GET", f"/api/email/{mail_id}") |
| 247 | + full_content = str(detail.get("content", "")) + "\n" + str(detail.get("html_content", "")) |
| 248 | + match = re.search(pattern, full_content) |
| 249 | + if match: |
| 250 | + code = match.group(1) |
| 251 | + logger.info(f"从 Freemail 邮箱 {email} 找到验证码: {code}") |
| 252 | + self.update_status(True) |
| 253 | + return code |
| 254 | + except Exception as e: |
| 255 | + logger.debug(f"获取 Freemail 邮件详情失败: {e}") |
| 256 | + |
| 257 | + except Exception as e: |
| 258 | + logger.debug(f"检查 Freemail 邮件时出错: {e}") |
| 259 | + |
| 260 | + time.sleep(3) |
| 261 | + |
| 262 | + logger.warning(f"等待 Freemail 验证码超时: {email}") |
| 263 | + return None |
| 264 | + |
| 265 | + def list_emails(self, **kwargs) -> List[Dict[str, Any]]: |
| 266 | + """ |
| 267 | + 列出邮箱 |
| 268 | +
|
| 269 | + Args: |
| 270 | + **kwargs: 额外查询参数 |
| 271 | +
|
| 272 | + Returns: |
| 273 | + 邮箱列表 |
| 274 | + """ |
| 275 | + try: |
| 276 | + params = { |
| 277 | + "limit": kwargs.get("limit", 100), |
| 278 | + "offset": kwargs.get("offset", 0) |
| 279 | + } |
| 280 | + resp = self._make_request("GET", "/api/mailboxes", params=params) |
| 281 | + |
| 282 | + emails = [] |
| 283 | + if isinstance(resp, list): |
| 284 | + for mail in resp: |
| 285 | + address = mail.get("address") |
| 286 | + if address: |
| 287 | + emails.append({ |
| 288 | + "id": address, |
| 289 | + "service_id": address, |
| 290 | + "email": address, |
| 291 | + "created_at": mail.get("created_at"), |
| 292 | + "raw_data": mail |
| 293 | + }) |
| 294 | + self.update_status(True) |
| 295 | + return emails |
| 296 | + except Exception as e: |
| 297 | + logger.warning(f"列出 Freemail 邮箱失败: {e}") |
| 298 | + self.update_status(False, e) |
| 299 | + return [] |
| 300 | + |
| 301 | + def delete_email(self, email_id: str) -> bool: |
| 302 | + """ |
| 303 | + 删除邮箱 |
| 304 | + """ |
| 305 | + try: |
| 306 | + self._make_request("DELETE", "/api/mailboxes", params={"address": email_id}) |
| 307 | + logger.info(f"已删除 Freemail 邮箱: {email_id}") |
| 308 | + self.update_status(True) |
| 309 | + return True |
| 310 | + except Exception as e: |
| 311 | + logger.warning(f"删除 Freemail 邮箱失败: {e}") |
| 312 | + self.update_status(False, e) |
| 313 | + return False |
| 314 | + |
| 315 | + def check_health(self) -> bool: |
| 316 | + """检查服务健康状态""" |
| 317 | + try: |
| 318 | + self._make_request("GET", "/api/domains") |
| 319 | + self.update_status(True) |
| 320 | + return True |
| 321 | + except Exception as e: |
| 322 | + logger.warning(f"Freemail 健康检查失败: {e}") |
| 323 | + self.update_status(False, e) |
| 324 | + return False |
0 commit comments