hotmail_helper.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. import email
  2. import html
  3. import imaplib
  4. import json
  5. import os
  6. import re
  7. import threading
  8. import time
  9. import traceback
  10. from datetime import datetime, timezone
  11. from email.header import decode_header
  12. from email.utils import getaddresses, parseaddr, parsedate_to_datetime
  13. from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
  14. from urllib.error import HTTPError, URLError
  15. from urllib.parse import urlencode
  16. from urllib.request import Request, urlopen
  17. HOST = os.environ.get("HOTMAIL_HELPER_HOST", "127.0.0.1").strip() or "127.0.0.1"
  18. try:
  19. PORT = int(os.environ.get("HOTMAIL_HELPER_PORT", "17373") or 17373)
  20. except Exception:
  21. PORT = 17373
  22. LIVE_TOKEN_URL = "https://login.live.com/oauth20_token.srf"
  23. ENTRA_COMMON_TOKEN_URL = "https://login.microsoftonline.com/common/oauth2/v2.0/token"
  24. ENTRA_CONSUMERS_TOKEN_URL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/token"
  25. GRAPH_API_ORIGIN = "https://graph.microsoft.com"
  26. OUTLOOK_API_ORIGIN = "https://outlook.office.com"
  27. GRAPH_SCOPES = "offline_access https://graph.microsoft.com/Mail.Read https://graph.microsoft.com/User.Read"
  28. GRAPH_DEFAULT_SCOPE = "https://graph.microsoft.com/.default"
  29. TOKEN_ENDPOINTS = {
  30. "live": {
  31. "name": "live",
  32. "url": LIVE_TOKEN_URL,
  33. "extra_data": {},
  34. },
  35. "entra-consumers-delegated": {
  36. "name": "entra-consumers-delegated",
  37. "url": ENTRA_CONSUMERS_TOKEN_URL,
  38. "extra_data": {
  39. "scope": GRAPH_SCOPES,
  40. },
  41. },
  42. "entra-common-delegated": {
  43. "name": "entra-common-delegated",
  44. "url": ENTRA_COMMON_TOKEN_URL,
  45. "extra_data": {
  46. "scope": GRAPH_SCOPES,
  47. },
  48. },
  49. "entra-common-default": {
  50. "name": "entra-common-default",
  51. "url": ENTRA_COMMON_TOKEN_URL,
  52. "extra_data": {
  53. "scope": GRAPH_DEFAULT_SCOPE,
  54. },
  55. },
  56. "entra-common-outlook": {
  57. "name": "entra-common-outlook",
  58. "url": ENTRA_COMMON_TOKEN_URL,
  59. "extra_data": {},
  60. },
  61. }
  62. IMAP_HOST = "outlook.office365.com"
  63. IMAP_PORT = 993
  64. REQUEST_TIMEOUT_SECONDS = 45
  65. FETCH_LIMIT_DEFAULT = 5
  66. BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
  67. ACCOUNT_LOG_PATH = os.path.join(BASE_DIR, "data", "account-run-history.txt")
  68. ACCOUNT_RECORDS_SNAPSHOT_PATH = os.path.join(BASE_DIR, "data", "account-run-history.json")
  69. A4SKY_IMAP_CONFIG_PATH = os.path.join(BASE_DIR, "data", "a4sky-imap.local.json")
  70. ACCOUNT_RECORDS_LOCK = threading.Lock()
  71. def json_response(handler, status, payload):
  72. body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
  73. handler.send_response(status)
  74. handler.send_header("Content-Type", "application/json; charset=utf-8")
  75. handler.send_header("Content-Length", str(len(body)))
  76. handler.send_header("Access-Control-Allow-Origin", "*")
  77. handler.send_header("Access-Control-Allow-Headers", "Content-Type")
  78. handler.send_header("Access-Control-Allow-Methods", "POST, OPTIONS")
  79. handler.end_headers()
  80. handler.wfile.write(body)
  81. def read_json_payload(handler):
  82. length = int(handler.headers.get("Content-Length", "0") or 0)
  83. raw = handler.rfile.read(length) if length > 0 else b"{}"
  84. try:
  85. return json.loads(raw.decode("utf-8"))
  86. except Exception as exc:
  87. raise RuntimeError(f"Invalid JSON payload: {exc}") from exc
  88. def post_form(url, data):
  89. encoded = urlencode(data).encode("utf-8")
  90. request = Request(url, data=encoded, headers={"Content-Type": "application/x-www-form-urlencoded"})
  91. with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
  92. return json.loads(response.read().decode("utf-8"))
  93. def get_json(url, headers=None):
  94. request = Request(url, headers=headers or {})
  95. with urlopen(request, timeout=REQUEST_TIMEOUT_SECONDS) as response:
  96. return response.getcode(), json.loads(response.read().decode("utf-8"))
  97. def mask_secret(value, keep=6):
  98. raw = str(value or "")
  99. if not raw:
  100. return ""
  101. if len(raw) <= keep:
  102. return "*" * len(raw)
  103. return raw[:keep] + "..." + raw[-keep:]
  104. def compact_text(value, limit=400):
  105. text = str(value or "").replace("\r", " ").replace("\n", " ").strip()
  106. return text[:limit]
  107. def log_info(message):
  108. print(f"[HotmailHelper] {message}", flush=True)
  109. def append_account_log(email_addr, password, status, recorded_at="", reason=""):
  110. normalized_email = str(email_addr or "").strip()
  111. normalized_password = str(password or "").strip()
  112. normalized_status = str(status or "").strip().lower()
  113. normalized_recorded_at = str(recorded_at or "").strip() or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  114. normalized_reason = str(reason or "").strip().replace("\r", " ").replace("\n", " ")
  115. if not normalized_email or not normalized_password or not normalized_status:
  116. raise RuntimeError("Missing email/password/status for account log append")
  117. os.makedirs(os.path.dirname(ACCOUNT_LOG_PATH), exist_ok=True)
  118. line = f"{normalized_recorded_at}\t{normalized_email}\t{normalized_password}\t{normalized_status}\t{normalized_reason}\n"
  119. with ACCOUNT_RECORDS_LOCK:
  120. with open(ACCOUNT_LOG_PATH, "a", encoding="utf-8") as handle:
  121. handle.write(line)
  122. return ACCOUNT_LOG_PATH
  123. def normalize_account_run_snapshot_record(record):
  124. if not isinstance(record, dict):
  125. return None
  126. email_addr = str(record.get("email") or "").strip()
  127. password = str(record.get("password") or "").strip()
  128. final_status = str(record.get("finalStatus") or "").strip().lower()
  129. if not email_addr or not password or final_status not in {"success", "failed", "stopped"}:
  130. return None
  131. finished_at = str(record.get("finishedAt") or "").strip() or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")
  132. retry_count = max(0, int(record.get("retryCount") or 0))
  133. failed_step_raw = record.get("failedStep")
  134. try:
  135. failed_step = int(failed_step_raw)
  136. except (TypeError, ValueError):
  137. failed_step = None
  138. if failed_step is not None and failed_step <= 0:
  139. failed_step = None
  140. auto_run_context = record.get("autoRunContext") if isinstance(record.get("autoRunContext"), dict) else None
  141. normalized_auto_run_context = None
  142. if auto_run_context:
  143. normalized_auto_run_context = {
  144. "currentRun": max(0, int(auto_run_context.get("currentRun") or 0)),
  145. "totalRuns": max(0, int(auto_run_context.get("totalRuns") or 0)),
  146. "attemptRun": max(0, int(auto_run_context.get("attemptRun") or 0)),
  147. }
  148. if not any(normalized_auto_run_context.values()):
  149. normalized_auto_run_context = None
  150. source = "auto" if str(record.get("source") or "").strip().lower() == "auto" else "manual"
  151. return {
  152. "recordId": str(record.get("recordId") or email_addr).strip() or email_addr,
  153. "email": email_addr,
  154. "password": password,
  155. "finalStatus": final_status,
  156. "finishedAt": finished_at,
  157. "retryCount": retry_count,
  158. "failureLabel": str(record.get("failureLabel") or "").strip(),
  159. "failureDetail": str(record.get("failureDetail") or "").strip(),
  160. "failedStep": failed_step,
  161. "source": source,
  162. "autoRunContext": normalized_auto_run_context,
  163. }
  164. def summarize_account_run_snapshot(records):
  165. summary = {
  166. "total": 0,
  167. "success": 0,
  168. "failed": 0,
  169. "retryTotal": 0,
  170. }
  171. for item in records:
  172. summary["total"] += 1
  173. if item.get("finalStatus") == "success":
  174. summary["success"] += 1
  175. elif item.get("finalStatus") == "failed":
  176. summary["failed"] += 1
  177. summary["retryTotal"] += max(0, int(item.get("retryCount") or 0))
  178. return summary
  179. def normalize_account_run_snapshot_payload(payload):
  180. if not isinstance(payload, dict):
  181. raise RuntimeError("Invalid account run snapshot payload")
  182. normalized_records = []
  183. for item in payload.get("records") if isinstance(payload.get("records"), list) else []:
  184. normalized = normalize_account_run_snapshot_record(item)
  185. if normalized:
  186. normalized_records.append(normalized)
  187. return {
  188. "generatedAt": str(payload.get("generatedAt") or "").strip() or datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
  189. "summary": summarize_account_run_snapshot(normalized_records),
  190. "records": normalized_records,
  191. }
  192. def sync_account_run_records(payload):
  193. normalized_payload = normalize_account_run_snapshot_payload(payload)
  194. os.makedirs(os.path.dirname(ACCOUNT_RECORDS_SNAPSHOT_PATH), exist_ok=True)
  195. with ACCOUNT_RECORDS_LOCK:
  196. with open(ACCOUNT_RECORDS_SNAPSHOT_PATH, "w", encoding="utf-8") as handle:
  197. json.dump(normalized_payload, handle, ensure_ascii=False, indent=2)
  198. handle.write("\n")
  199. return ACCOUNT_RECORDS_SNAPSHOT_PATH
  200. def try_refresh_access_token(endpoint, client_id, refresh_token):
  201. request_data = {
  202. "client_id": client_id,
  203. "refresh_token": refresh_token,
  204. "grant_type": "refresh_token",
  205. **(endpoint.get("extra_data") or {}),
  206. }
  207. started_at = time.monotonic()
  208. try:
  209. payload = post_form(endpoint["url"], request_data)
  210. except HTTPError as exc:
  211. detail = exc.read().decode("utf-8", errors="ignore")
  212. return {
  213. "ok": False,
  214. "endpoint": endpoint["name"],
  215. "url": endpoint["url"],
  216. "status": getattr(exc, "code", None),
  217. "error": compact_text(detail or str(exc)),
  218. "elapsed_ms": int((time.monotonic() - started_at) * 1000),
  219. }
  220. except URLError as exc:
  221. return {
  222. "ok": False,
  223. "endpoint": endpoint["name"],
  224. "url": endpoint["url"],
  225. "status": None,
  226. "error": compact_text(f"Token request failed: {exc}"),
  227. "elapsed_ms": int((time.monotonic() - started_at) * 1000),
  228. }
  229. access_token = str(payload.get("access_token") or "").strip()
  230. if not access_token:
  231. return {
  232. "ok": False,
  233. "endpoint": endpoint["name"],
  234. "url": endpoint["url"],
  235. "status": 200,
  236. "error": compact_text(payload.get("error_description") or payload.get("error") or json.dumps(payload, ensure_ascii=False)),
  237. "elapsed_ms": int((time.monotonic() - started_at) * 1000),
  238. }
  239. return {
  240. "ok": True,
  241. "endpoint": endpoint["name"],
  242. "url": endpoint["url"],
  243. "elapsed_ms": int((time.monotonic() - started_at) * 1000),
  244. "payload": {
  245. "access_token": access_token,
  246. "next_refresh_token": str(payload.get("refresh_token") or "").strip(),
  247. },
  248. }
  249. def refresh_access_token(client_id, refresh_token, strategy_names=None):
  250. errors = []
  251. selected_endpoints = [
  252. TOKEN_ENDPOINTS[name]
  253. for name in (strategy_names or ["live", "entra-consumers-delegated", "entra-common-delegated"])
  254. if name in TOKEN_ENDPOINTS
  255. ]
  256. log_info(
  257. "token refresh start "
  258. f"clientId={mask_secret(client_id)} "
  259. f"refreshToken={mask_secret(refresh_token)} "
  260. f"strategies={[item['name'] for item in selected_endpoints]}"
  261. )
  262. for endpoint in selected_endpoints:
  263. result = try_refresh_access_token(endpoint, client_id, refresh_token)
  264. if result["ok"]:
  265. log_info(
  266. "token refresh success "
  267. f"endpoint={result['endpoint']} "
  268. f"elapsedMs={result['elapsed_ms']}"
  269. )
  270. return {
  271. "access_token": result["payload"]["access_token"],
  272. "next_refresh_token": result["payload"]["next_refresh_token"],
  273. "token_endpoint": result["endpoint"],
  274. "token_url": result["url"],
  275. }
  276. errors.append(result)
  277. log_info(
  278. "token refresh failed "
  279. f"endpoint={result['endpoint']} "
  280. f"status={result['status']} "
  281. f"elapsedMs={result['elapsed_ms']} "
  282. f"detail={result['error']}"
  283. )
  284. details = " | ".join(
  285. f"{item['endpoint']}({item['status']}): {item['error']}"
  286. for item in errors
  287. )
  288. raise RuntimeError(f"Token refresh failed on all endpoints: {details}")
  289. def load_local_imap_config():
  290. if not os.path.exists(A4SKY_IMAP_CONFIG_PATH):
  291. return {}
  292. try:
  293. with open(A4SKY_IMAP_CONFIG_PATH, "r", encoding="utf-8") as handle:
  294. payload = json.load(handle)
  295. return payload if isinstance(payload, dict) else {}
  296. except Exception as exc:
  297. raise RuntimeError(f"Invalid local IMAP config: {exc}") from exc
  298. def resolve_basic_imap_settings(payload):
  299. local_config = load_local_imap_config()
  300. host = str(payload.get("host") or local_config.get("host") or "").strip()
  301. username = str(payload.get("username") or local_config.get("username") or "").strip()
  302. password = str(payload.get("password") or local_config.get("password") or "").strip()
  303. port_raw = payload.get("port") if payload.get("port") is not None else local_config.get("port")
  304. try:
  305. port = int(port_raw or 993)
  306. except Exception as exc:
  307. raise RuntimeError(f"Invalid IMAP port: {exc}") from exc
  308. if not host or not username or not password:
  309. raise RuntimeError("Missing IMAP host/username/password. Please fill data/a4sky-imap.local.json or pass credentials explicitly.")
  310. return {
  311. "host": host,
  312. "port": max(1, port),
  313. "username": username,
  314. "password": password,
  315. }
  316. def open_basic_imap_mailbox(host, port, username, password):
  317. client = imaplib.IMAP4_SSL(host, port)
  318. client.login(username, password)
  319. return client
  320. def build_xoauth2(email_addr, access_token):
  321. return f"user={email_addr}\x01auth=Bearer {access_token}\x01\x01".encode("utf-8")
  322. def open_mailbox(email_addr, access_token):
  323. client = imaplib.IMAP4_SSL(IMAP_HOST, IMAP_PORT)
  324. client.authenticate("XOAUTH2", lambda _: build_xoauth2(email_addr, access_token))
  325. return client
  326. def decode_mime_header(value):
  327. if not value:
  328. return ""
  329. parts = []
  330. for chunk, charset in decode_header(value):
  331. if isinstance(chunk, bytes):
  332. parts.append(chunk.decode(charset or "utf-8", errors="ignore"))
  333. else:
  334. parts.append(str(chunk))
  335. return "".join(parts).strip()
  336. def extract_text_part(message):
  337. if message.is_multipart():
  338. for part in message.walk():
  339. if part.get_content_maintype() == "multipart":
  340. continue
  341. if "attachment" in str(part.get("Content-Disposition") or "").lower():
  342. continue
  343. payload = part.get_payload(decode=True) or b""
  344. charset = part.get_content_charset() or "utf-8"
  345. text = payload.decode(charset, errors="ignore").strip()
  346. if part.get_content_type() == "text/plain" and text:
  347. return text
  348. if part.get_content_type() == "text/html" and text:
  349. return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html.unescape(text))).strip()
  350. return ""
  351. payload = message.get_payload(decode=True) or b""
  352. charset = message.get_content_charset() or "utf-8"
  353. text = payload.decode(charset, errors="ignore").strip()
  354. if message.get_content_type() == "text/html":
  355. return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html.unescape(text))).strip()
  356. return text
  357. def mailbox_candidates(mailbox):
  358. normalized = str(mailbox or "INBOX").strip().lower()
  359. if normalized in {"junk", "junk email", "junk e-mail", "junkemail"}:
  360. return ["Junk", "Junk Email", "Junk E-Mail"]
  361. return ["INBOX"]
  362. def normalize_mailbox_label(mailbox):
  363. normalized = str(mailbox or "INBOX").strip().lower()
  364. if normalized in {"junk", "junk email", "junk e-mail", "junkemail"}:
  365. return "Junk"
  366. return "INBOX"
  367. def normalize_mailbox_id(mailbox):
  368. normalized = str(mailbox or "INBOX").strip().lower()
  369. if normalized in {"junk", "junk email", "junk e-mail", "junkemail"}:
  370. return "junkemail"
  371. return "inbox"
  372. def select_mailbox(client, mailbox):
  373. for candidate in mailbox_candidates(mailbox):
  374. status, _ = client.select(candidate)
  375. if status == "OK":
  376. return candidate
  377. raise RuntimeError(f"Mailbox not found: {mailbox}")
  378. def to_timestamp_ms(raw_date):
  379. if not raw_date:
  380. return 0
  381. try:
  382. parsed = parsedate_to_datetime(raw_date)
  383. if parsed.tzinfo is None:
  384. parsed = parsed.replace(tzinfo=timezone.utc)
  385. return int(parsed.timestamp() * 1000)
  386. except Exception:
  387. return 0
  388. def to_iso_string(timestamp_ms):
  389. if not timestamp_ms:
  390. return ""
  391. return datetime.fromtimestamp(timestamp_ms / 1000, tz=timezone.utc).isoformat().replace("+00:00", "Z")
  392. def normalize_message(message_id, raw_bytes, mailbox):
  393. parsed = email.message_from_bytes(raw_bytes)
  394. sender_name, sender_addr = parseaddr(parsed.get("From", ""))
  395. subject = decode_mime_header(parsed.get("Subject", ""))
  396. body = extract_text_part(parsed)
  397. timestamp_ms = to_timestamp_ms(parsed.get("Date"))
  398. recipient_headers = []
  399. for header_name in ["To", "Delivered-To", "Envelope-To", "X-Original-To", "Cc"]:
  400. recipient_headers.extend(parsed.get_all(header_name, []))
  401. recipient_items = []
  402. recipient_addresses = []
  403. for recipient_name, recipient_addr in getaddresses(recipient_headers):
  404. normalized_addr = str(recipient_addr or "").strip().lower()
  405. if not normalized_addr:
  406. continue
  407. recipient_addresses.append(normalized_addr)
  408. recipient_items.append({
  409. "emailAddress": {
  410. "address": normalized_addr,
  411. "name": str(recipient_name or "").strip(),
  412. }
  413. })
  414. return {
  415. "id": str(message_id),
  416. "mailbox": mailbox,
  417. "subject": subject,
  418. "from": {
  419. "emailAddress": {
  420. "address": sender_addr.strip(),
  421. "name": sender_name.strip(),
  422. }
  423. },
  424. "toRecipients": recipient_items,
  425. "recipientAddresses": recipient_addresses,
  426. "bodyPreview": body[:500],
  427. "receivedDateTime": to_iso_string(timestamp_ms),
  428. "receivedTimestamp": timestamp_ms,
  429. }
  430. def fetch_messages(email_addr, access_token, mailbox="INBOX", top=FETCH_LIMIT_DEFAULT):
  431. client = None
  432. logical_mailbox = normalize_mailbox_label(mailbox)
  433. try:
  434. client = open_mailbox(email_addr, access_token)
  435. select_mailbox(client, mailbox)
  436. status, data = client.search(None, "ALL")
  437. if status != "OK" or not data or not data[0]:
  438. return {"mailbox": logical_mailbox, "messages": [], "count": 0}
  439. message_ids = data[0].split()
  440. selected_ids = list(reversed(message_ids[-max(1, min(int(top or FETCH_LIMIT_DEFAULT), 30)):]))
  441. messages = []
  442. for message_id in selected_ids:
  443. fetch_status, fetch_data = client.fetch(message_id, "(RFC822)")
  444. if fetch_status != "OK" or not fetch_data:
  445. continue
  446. raw_bytes = b""
  447. for item in fetch_data:
  448. if isinstance(item, tuple) and len(item) >= 2:
  449. raw_bytes = item[1]
  450. break
  451. if not raw_bytes:
  452. continue
  453. messages.append(normalize_message(message_id.decode("utf-8", errors="ignore"), raw_bytes, logical_mailbox))
  454. return {"mailbox": logical_mailbox, "messages": messages, "count": len(messages)}
  455. finally:
  456. if client is not None:
  457. try:
  458. client.logout()
  459. except Exception:
  460. pass
  461. def fetch_messages_for_mailboxes(email_addr, access_token, mailboxes, top):
  462. mailbox_results = []
  463. all_messages = []
  464. for mailbox in mailboxes or ["INBOX"]:
  465. result = fetch_messages(email_addr, access_token, mailbox=mailbox, top=top)
  466. mailbox_results.append(result)
  467. all_messages.extend(result["messages"])
  468. all_messages.sort(key=lambda item: int(item.get("receivedTimestamp") or 0), reverse=True)
  469. return {"mailboxResults": mailbox_results, "messages": all_messages}
  470. def fetch_basic_imap_messages(host, port, username, password, mailbox="INBOX", top=FETCH_LIMIT_DEFAULT):
  471. client = None
  472. logical_mailbox = normalize_mailbox_label(mailbox)
  473. try:
  474. client = open_basic_imap_mailbox(host, port, username, password)
  475. select_mailbox(client, mailbox)
  476. status, data = client.search(None, "ALL")
  477. if status != "OK" or not data or not data[0]:
  478. return {"mailbox": logical_mailbox, "messages": [], "count": 0}
  479. message_ids = data[0].split()
  480. selected_ids = list(reversed(message_ids[-max(1, min(int(top or FETCH_LIMIT_DEFAULT), 30)):]))
  481. messages = []
  482. for message_id in selected_ids:
  483. fetch_status, fetch_data = client.fetch(message_id, "(RFC822)")
  484. if fetch_status != "OK" or not fetch_data:
  485. continue
  486. raw_bytes = b""
  487. for item in fetch_data:
  488. if isinstance(item, tuple) and len(item) >= 2:
  489. raw_bytes = item[1]
  490. break
  491. if not raw_bytes:
  492. continue
  493. messages.append(normalize_message(message_id.decode("utf-8", errors="ignore"), raw_bytes, logical_mailbox))
  494. return {"mailbox": logical_mailbox, "messages": messages, "count": len(messages)}
  495. finally:
  496. if client is not None:
  497. try:
  498. client.logout()
  499. except Exception:
  500. pass
  501. def fetch_basic_imap_messages_for_mailboxes(host, port, username, password, mailboxes, top):
  502. mailbox_results = []
  503. all_messages = []
  504. for mailbox in mailboxes or ["INBOX"]:
  505. result = fetch_basic_imap_messages(host, port, username, password, mailbox=mailbox, top=top)
  506. mailbox_results.append(result)
  507. all_messages.extend(result["messages"])
  508. all_messages.sort(key=lambda item: int(item.get("receivedTimestamp") or 0), reverse=True)
  509. return {"mailboxResults": mailbox_results, "messages": all_messages}
  510. def collect_basic_imap_messages(payload, mailboxes, top):
  511. settings = resolve_basic_imap_settings(payload)
  512. result = fetch_basic_imap_messages_for_mailboxes(
  513. settings["host"],
  514. settings["port"],
  515. settings["username"],
  516. settings["password"],
  517. mailboxes,
  518. top,
  519. )
  520. result["transport"] = "imap-basic"
  521. result["settings"] = {
  522. "host": settings["host"],
  523. "port": settings["port"],
  524. "username": settings["username"],
  525. }
  526. return result
  527. def normalize_graph_message(message, mailbox):
  528. sender = message.get("from", {}) or {}
  529. email_addr = sender.get("emailAddress", {}) if isinstance(sender, dict) else {}
  530. received = str(message.get("receivedDateTime") or "").strip()
  531. return {
  532. "id": str(message.get("id") or message.get("internetMessageId") or "").strip(),
  533. "mailbox": mailbox,
  534. "subject": str(message.get("subject") or "").strip(),
  535. "from": {
  536. "emailAddress": {
  537. "address": str(email_addr.get("address") or "").strip(),
  538. "name": str(email_addr.get("name") or "").strip(),
  539. }
  540. },
  541. "bodyPreview": str(message.get("bodyPreview") or "").strip(),
  542. "receivedDateTime": received,
  543. "receivedTimestamp": int(datetime.fromisoformat(received.replace("Z", "+00:00")).timestamp() * 1000) if received else 0,
  544. }
  545. def normalize_outlook_message(message, mailbox):
  546. sender = message.get("From", {}) or message.get("from", {}) or {}
  547. email_addr = sender.get("EmailAddress", {}) if isinstance(sender, dict) else {}
  548. if isinstance(sender, dict) and not email_addr:
  549. email_addr = sender.get("emailAddress", {}) if isinstance(sender, dict) else {}
  550. received = str(message.get("ReceivedDateTime") or message.get("receivedDateTime") or "").strip()
  551. return {
  552. "id": str(message.get("Id") or message.get("id") or "").strip(),
  553. "mailbox": mailbox,
  554. "subject": str(message.get("Subject") or message.get("subject") or "").strip(),
  555. "from": {
  556. "emailAddress": {
  557. "address": str(email_addr.get("Address") or email_addr.get("address") or "").strip(),
  558. "name": str(email_addr.get("Name") or email_addr.get("name") or "").strip(),
  559. }
  560. },
  561. "bodyPreview": str(message.get("BodyPreview") or message.get("bodyPreview") or "").strip(),
  562. "receivedDateTime": received,
  563. "receivedTimestamp": int(datetime.fromisoformat(received.replace("Z", "+00:00")).timestamp() * 1000) if received else 0,
  564. }
  565. def fetch_graph_messages(access_token, mailbox="INBOX", top=FETCH_LIMIT_DEFAULT):
  566. mailbox_id = normalize_mailbox_id(mailbox)
  567. url = (
  568. f"{GRAPH_API_ORIGIN}/v1.0/me/mailFolders/{mailbox_id}/messages"
  569. f"?$top={max(1, min(int(top or FETCH_LIMIT_DEFAULT), 30))}"
  570. f"&$select=id,internetMessageId,subject,from,bodyPreview,receivedDateTime"
  571. f"&$orderby=receivedDateTime desc"
  572. )
  573. try:
  574. _, payload = get_json(url, headers={
  575. "Accept": "application/json",
  576. "Authorization": f"Bearer {access_token}",
  577. })
  578. except HTTPError as exc:
  579. detail = exc.read().decode("utf-8", errors="ignore")
  580. raise RuntimeError(f"Graph request failed: {detail or exc}") from exc
  581. except URLError as exc:
  582. raise RuntimeError(f"Graph request failed: {exc}") from exc
  583. messages = [normalize_graph_message(item, normalize_mailbox_label(mailbox)) for item in (payload.get("value") or [])]
  584. return {"mailbox": normalize_mailbox_label(mailbox), "messages": messages, "count": len(messages)}
  585. def fetch_outlook_api_messages(access_token, mailbox="INBOX", top=FETCH_LIMIT_DEFAULT):
  586. mailbox_id = normalize_mailbox_id(mailbox)
  587. url = (
  588. f"{OUTLOOK_API_ORIGIN}/api/v2.0/me/mailfolders/{mailbox_id}/messages"
  589. f"?$top={max(1, min(int(top or FETCH_LIMIT_DEFAULT), 30))}"
  590. f"&$select=Id,Subject,From,BodyPreview,ReceivedDateTime"
  591. f"&$orderby=ReceivedDateTime desc"
  592. )
  593. try:
  594. _, payload = get_json(url, headers={
  595. "Accept": "application/json",
  596. "Authorization": f"Bearer {access_token}",
  597. })
  598. except HTTPError as exc:
  599. detail = exc.read().decode("utf-8", errors="ignore")
  600. raise RuntimeError(f"Outlook API request failed: {detail or exc}") from exc
  601. except URLError as exc:
  602. raise RuntimeError(f"Outlook API request failed: {exc}") from exc
  603. messages = [normalize_outlook_message(item, normalize_mailbox_label(mailbox)) for item in (payload.get("value") or [])]
  604. return {"mailbox": normalize_mailbox_label(mailbox), "messages": messages, "count": len(messages)}
  605. def collect_imap_messages(email_addr, client_id, refresh_token, mailboxes, top):
  606. token_payload = refresh_access_token(client_id, refresh_token, [
  607. "live",
  608. "entra-consumers-delegated",
  609. "entra-common-delegated",
  610. ])
  611. result = fetch_messages_for_mailboxes(email_addr, token_payload["access_token"], mailboxes, top)
  612. result["transport"] = "imap"
  613. result["token_payload"] = token_payload
  614. return result
  615. def collect_graph_messages(email_addr, client_id, refresh_token, mailboxes, top):
  616. token_payload = refresh_access_token(client_id, refresh_token, [
  617. "entra-common-delegated",
  618. "entra-consumers-delegated",
  619. "entra-common-default",
  620. ])
  621. mailbox_results = [fetch_graph_messages(token_payload["access_token"], mailbox=mailbox, top=top) for mailbox in mailboxes]
  622. messages = []
  623. for item in mailbox_results:
  624. messages.extend(item["messages"])
  625. messages.sort(key=lambda item: int(item.get("receivedTimestamp") or 0), reverse=True)
  626. return {
  627. "transport": "graph",
  628. "token_payload": token_payload,
  629. "mailboxResults": mailbox_results,
  630. "messages": messages,
  631. }
  632. def collect_outlook_messages(email_addr, client_id, refresh_token, mailboxes, top):
  633. token_payload = refresh_access_token(client_id, refresh_token, [
  634. "entra-common-outlook",
  635. "entra-common-delegated",
  636. ])
  637. mailbox_results = [fetch_outlook_api_messages(token_payload["access_token"], mailbox=mailbox, top=top) for mailbox in mailboxes]
  638. messages = []
  639. for item in mailbox_results:
  640. messages.extend(item["messages"])
  641. messages.sort(key=lambda item: int(item.get("receivedTimestamp") or 0), reverse=True)
  642. return {
  643. "transport": "outlook",
  644. "token_payload": token_payload,
  645. "mailboxResults": mailbox_results,
  646. "messages": messages,
  647. }
  648. def collect_messages(email_addr, client_id, refresh_token, mailboxes, top):
  649. errors = []
  650. collectors = [
  651. ("imap", collect_imap_messages),
  652. ("graph", collect_graph_messages),
  653. ("outlook", collect_outlook_messages),
  654. ]
  655. for transport_name, collector in collectors:
  656. try:
  657. log_info(f"message collection start transport={transport_name}")
  658. result = collector(email_addr, client_id, refresh_token, mailboxes, top)
  659. log_info(
  660. f"message collection success transport={transport_name} "
  661. f"tokenEndpoint={result['token_payload'].get('token_endpoint', '')}"
  662. )
  663. return result
  664. except Exception as exc:
  665. message = compact_text(str(exc), 600)
  666. errors.append(f"{transport_name}: {message}")
  667. log_info(f"message collection failed transport={transport_name} detail={message}")
  668. raise RuntimeError(f"Message collection failed on all transports: {' | '.join(errors)}")
  669. def extract_code(text):
  670. source = str(text or "")
  671. patterns = [
  672. r"(?:代码为|验证码[^0-9]*?)[\s::]*(\d{6})",
  673. r"code(?:\s+is|[\s:])+(\d{6})",
  674. r"\b(\d{6})\b",
  675. ]
  676. for pattern in patterns:
  677. match = re.search(pattern, source, flags=re.IGNORECASE)
  678. if match:
  679. return match.group(1)
  680. return ""
  681. def select_latest_code(messages, sender_filters, subject_filters, exclude_codes, filter_after_timestamp, target_email=""):
  682. sender_keywords = [str(item).strip().lower() for item in sender_filters or [] if str(item).strip()]
  683. subject_keywords = [str(item).strip().lower() for item in subject_filters or [] if str(item).strip()]
  684. excluded = {str(item).strip() for item in exclude_codes or [] if str(item).strip()}
  685. normalized_target_email = str(target_email or "").strip().lower()
  686. def match_message(message, apply_time_filter):
  687. timestamp = int(message.get("receivedTimestamp") or 0)
  688. if apply_time_filter and filter_after_timestamp and timestamp and timestamp < int(filter_after_timestamp):
  689. return None
  690. sender = str(message.get("from", {}).get("emailAddress", {}).get("address", "")).lower()
  691. subject = str(message.get("subject", ""))
  692. preview = str(message.get("bodyPreview", ""))
  693. recipient_addresses = [
  694. str(item or "").strip().lower()
  695. for item in message.get("recipientAddresses", [])
  696. if str(item or "").strip()
  697. ]
  698. recipient_text = " ".join(recipient_addresses)
  699. combined = " ".join([sender, subject.lower(), preview.lower(), recipient_text])
  700. if normalized_target_email and recipient_addresses and normalized_target_email not in recipient_addresses:
  701. return None
  702. code = extract_code(" ".join([subject, preview, sender]))
  703. if not code or code in excluded:
  704. return None
  705. sender_ok = not sender_keywords or any(keyword in combined for keyword in sender_keywords)
  706. subject_ok = not subject_keywords or any(keyword in combined for keyword in subject_keywords)
  707. if not sender_ok and not subject_ok:
  708. return None
  709. return {"code": code, "message": message}
  710. for use_time_fallback in [False, True]:
  711. matched = []
  712. for message in messages:
  713. result = match_message(message, apply_time_filter=not use_time_fallback)
  714. if result:
  715. matched.append(result)
  716. if matched:
  717. matched.sort(key=lambda item: int(item["message"].get("receivedTimestamp") or 0), reverse=True)
  718. best = matched[0]
  719. return {
  720. "code": best["code"],
  721. "message": best["message"],
  722. "usedTimeFallback": use_time_fallback,
  723. }
  724. return {"code": "", "message": None, "usedTimeFallback": False}
  725. class HotmailHelperHandler(BaseHTTPRequestHandler):
  726. def do_OPTIONS(self):
  727. self.send_response(204)
  728. self.send_header("Access-Control-Allow-Origin", "*")
  729. self.send_header("Access-Control-Allow-Headers", "Content-Type")
  730. self.send_header("Access-Control-Allow-Methods", "POST, OPTIONS")
  731. self.end_headers()
  732. def do_POST(self):
  733. try:
  734. payload = read_json_payload(self)
  735. if self.path == "/sync-account-run-records":
  736. file_path = sync_account_run_records(payload)
  737. json_response(self, 200, {
  738. "ok": True,
  739. "filePath": file_path,
  740. })
  741. return
  742. if self.path == "/append-account-log":
  743. file_path = append_account_log(
  744. payload.get("email"),
  745. payload.get("password"),
  746. payload.get("status"),
  747. payload.get("recordedAt"),
  748. payload.get("reason"),
  749. )
  750. json_response(self, 200, {
  751. "ok": True,
  752. "filePath": file_path,
  753. })
  754. return
  755. top = max(1, min(int(payload.get("top") or FETCH_LIMIT_DEFAULT), 30))
  756. mailboxes = payload.get("mailboxes") if isinstance(payload.get("mailboxes"), list) else [payload.get("mailbox") or "INBOX"]
  757. if self.path == "/imap-messages":
  758. result = collect_basic_imap_messages(payload, mailboxes, top)
  759. json_response(self, 200, {
  760. "ok": True,
  761. "messages": result["messages"],
  762. "mailboxResults": result["mailboxResults"],
  763. "transport": result.get("transport") or "",
  764. "settings": result.get("settings") or {},
  765. })
  766. return
  767. if self.path == "/imap-code":
  768. result = collect_basic_imap_messages(payload, mailboxes, top)
  769. selected = select_latest_code(
  770. result["messages"],
  771. payload.get("senderFilters") or [],
  772. payload.get("subjectFilters") or [],
  773. payload.get("excludeCodes") or [],
  774. int(payload.get("filterAfterTimestamp") or 0),
  775. payload.get("targetEmail") or payload.get("email") or "",
  776. )
  777. json_response(self, 200, {
  778. "ok": True,
  779. "code": selected["code"],
  780. "message": selected["message"],
  781. "usedTimeFallback": selected["usedTimeFallback"],
  782. "transport": result.get("transport") or "",
  783. "settings": result.get("settings") or {},
  784. })
  785. return
  786. email_addr = str(payload.get("email") or "").strip()
  787. client_id = str(payload.get("clientId") or "").strip()
  788. refresh_token = str(payload.get("refreshToken") or "").strip()
  789. if not email_addr or not client_id or not refresh_token:
  790. raise RuntimeError("Missing email/clientId/refreshToken")
  791. if self.path == "/messages":
  792. result = collect_messages(email_addr, client_id, refresh_token, mailboxes, top)
  793. json_response(self, 200, {
  794. "ok": True,
  795. "messages": result["messages"],
  796. "mailboxResults": result["mailboxResults"],
  797. "nextRefreshToken": result["token_payload"].get("next_refresh_token") or "",
  798. "tokenEndpoint": result["token_payload"].get("token_endpoint") or "",
  799. "transport": result.get("transport") or "",
  800. })
  801. return
  802. if self.path == "/code":
  803. result = collect_messages(email_addr, client_id, refresh_token, mailboxes, top)
  804. selected = select_latest_code(
  805. result["messages"],
  806. payload.get("senderFilters") or [],
  807. payload.get("subjectFilters") or [],
  808. payload.get("excludeCodes") or [],
  809. int(payload.get("filterAfterTimestamp") or 0),
  810. payload.get("targetEmail") or "",
  811. )
  812. json_response(self, 200, {
  813. "ok": True,
  814. "code": selected["code"],
  815. "message": selected["message"],
  816. "usedTimeFallback": selected["usedTimeFallback"],
  817. "nextRefreshToken": result["token_payload"].get("next_refresh_token") or "",
  818. "tokenEndpoint": result["token_payload"].get("token_endpoint") or "",
  819. "transport": result.get("transport") or "",
  820. })
  821. return
  822. json_response(self, 404, {"ok": False, "error": f"Unsupported path: {self.path}"})
  823. except Exception as exc:
  824. traceback.print_exc()
  825. json_response(self, 500, {"ok": False, "error": str(exc)})
  826. def main():
  827. server = ThreadingHTTPServer((HOST, PORT), HotmailHelperHandler)
  828. print(f"Hotmail helper listening on http://{HOST}:{PORT}", flush=True)
  829. print(f"Account log file: {ACCOUNT_LOG_PATH}", flush=True)
  830. print(f"Account snapshot file: {ACCOUNT_RECORDS_SNAPSHOT_PATH}", flush=True)
  831. try:
  832. server.serve_forever()
  833. except KeyboardInterrupt:
  834. pass
  835. finally:
  836. server.server_close()
  837. if __name__ == "__main__":
  838. main()