import os import time import asyncio from typing import Dict, Any from selenium.common.exceptions import WebDriverException from selenium_MetLife_eligibilityCheckWorker import AutomationMetLifeEligibilityCheck, METLIFE_HOME_URL # In-memory session store sessions: Dict[str, Dict[str, Any]] = {} SESSION_OTP_TIMEOUT = int(os.getenv("SESSION_OTP_TIMEOUT", "120")) # seconds def make_session_entry() -> str: """Create a new session entry and return its ID.""" import uuid sid = str(uuid.uuid4()) sessions[sid] = { "status": "created", # created → running → waiting_for_otp → completed / error "created_at": time.time(), "last_activity": time.time(), "bot": None, # AutomationMetLifeEligibilityCheck instance "driver": None, # selenium webdriver "otp_event": asyncio.Event(), "otp_value": None, # OTP submitted from the app "result": None, "message": None, "type": None, } return sid async def cleanup_session(sid: str, message: str | None = None): """ Wake any OTP waiter, set final state, and remove the session entry. Safe to call multiple times (idempotent). NOTE: Does NOT quit the browser driver — the persistent browser stays alive. """ s = sessions.get(sid) if not s: return try: if s.get("status") not in ("completed", "error", "not_found"): s["status"] = "error" if message: s["message"] = message ev = s.get("otp_event") if ev and not ev.is_set(): ev.set() finally: sessions.pop(sid, None) print(f"[helpers_metlife] cleaned session {sid}") async def _remove_session_later(sid: str, delay: int = 20): await asyncio.sleep(delay) await cleanup_session(sid) async def start_metlife_run(sid: str, data: dict, url: str): """ Run the full MetLife eligibility workflow for one session. Called by agent.py inside a wrapper that manages the semaphore/counters. OTP handling uses two complementary strategies: 1. Accept OTP submitted from the app (via /submit-otp endpoint → otp_value field) 2. Poll the browser directly to detect when the user completes MFA themselves """ s = sessions.get(sid) if not s: return {"status": "error", "message": "session not found"} s["status"] = "running" s["last_activity"] = time.time() try: bot = AutomationMetLifeEligibilityCheck({"data": data}) bot.config_driver() s["bot"] = bot s["driver"] = bot.driver s["last_activity"] = time.time() try: if not url: raise ValueError("URL not provided for MetLife run") bot.driver.maximize_window() except Exception as e: s["status"] = "error" s["message"] = f"Navigation failed: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} # Login try: login_result = bot.login(url) except WebDriverException as wde: s["status"] = "error" s["message"] = f"Selenium driver error during login: {wde}" await cleanup_session(sid, s["message"]) return {"status": "error", "message": s["message"]} except Exception as e: s["status"] = "error" s["message"] = f"Unexpected error during login: {e}" await cleanup_session(sid, s["message"]) return {"status": "error", "message": s["message"]} # ── Path: already logged in (persistent session) ────────────────────── if login_result == "ALREADY_LOGGED_IN": print("[start_metlife_run] Session persisted - skipping OTP") s["status"] = "running" s["message"] = "Session persisted" # ── Path: OTP required ──────────────────────────────────────────────── elif login_result == "OTP_REQUIRED": s["status"] = "waiting_for_otp" s["message"] = "OTP required for login - please enter OTP" s["last_activity"] = time.time() driver = s["driver"] login_success = False print(f"[MetLife OTP] Polling for OTP completion (up to {SESSION_OTP_TIMEOUT}s)...") for poll in range(SESSION_OTP_TIMEOUT): await asyncio.sleep(1) s["last_activity"] = time.time() try: # a) App submitted OTP via /submit-otp endpoint otp_value = s.get("otp_value") if otp_value: print(f"[MetLife OTP poll {poll+1}] OTP received from app, typing it in...") s["otp_value"] = None # Clear so we don't re-submit if bot.submit_otp_code(otp_value): print("[MetLife OTP] OTP typed and submitted via app") await asyncio.sleep(3) else: print("[MetLife OTP] OTP input not found — enter it in the browser window") # b) Back on the portal with the search form → login completed if bot.is_logged_in(timeout=2): print("[MetLife OTP] Search form found — login successful!") login_success = True break print(f"[MetLife OTP poll {poll+1}/{SESSION_OTP_TIMEOUT}] URL: {driver.current_url[:70]}...") except Exception as poll_err: print(f"[MetLife OTP poll {poll+1}] Error: {poll_err}") if not login_success: # Final check — navigate directly to the portal home page try: print("[MetLife OTP] Final attempt - navigating to home page...") driver.get(METLIFE_HOME_URL) await asyncio.sleep(3) login_success = bot.is_logged_in(timeout=10) except Exception as final_err: s["status"] = "error" s["message"] = f"OTP verification failed: {final_err}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} if not login_success: s["status"] = "error" s["message"] = "OTP timeout - login not completed" await cleanup_session(sid) return {"status": "error", "message": "OTP not completed in time"} s["status"] = "running" s["message"] = "Login successful after OTP" print("[MetLife OTP] Proceeding to step1...") # ── Path: login succeeded without OTP ───────────────────────────────── elif login_result == "SUCCESS": print("[start_metlife_run] Login succeeded without OTP") s["status"] = "running" s["message"] = "Login succeeded" # ── Path: login error ───────────────────────────────────────────────── else: msg = login_result if isinstance(login_result, str) else "ERROR: unknown login result" s["status"] = "error" s["message"] = msg await cleanup_session(sid) return {"status": "error", "message": msg} # ── Step 1: search ──────────────────────────────────────────────────── step1_result = bot.step1() if isinstance(step1_result, str) and step1_result.startswith("ERROR"): s["status"] = "error" s["message"] = step1_result await cleanup_session(sid) return {"status": "error", "message": step1_result} # ── Step 2: patient selection + PDF ─────────────────────────────────── step2_result = bot.step2() if isinstance(step2_result, dict) and step2_result.get("status") == "success": s["status"] = "completed" s["result"] = step2_result s["message"] = "completed" asyncio.create_task(_remove_session_later(sid, 30)) return step2_result s["status"] = "error" if isinstance(step2_result, dict): s["message"] = step2_result.get("message", "unknown error") else: s["message"] = str(step2_result) await cleanup_session(sid) return {"status": "error", "message": s["message"]} except Exception as e: s["status"] = "error" s["message"] = f"worker exception: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} def submit_otp(sid: str, otp: str) -> Dict[str, Any]: """ Called when the app sends an OTP via POST /submit-otp. Sets otp_value on the session so the polling loop picks it up. """ s = sessions.get(sid) if not s: return {"status": "error", "message": "session not found"} if s.get("status") != "waiting_for_otp": return {"status": "error", "message": f"session not waiting for OTP (state={s.get('status')})"} s["otp_value"] = otp s["last_activity"] = time.time() try: s["otp_event"].set() except Exception: pass return {"status": "ok", "message": "otp accepted"} def get_session_status(sid: str) -> Dict[str, Any]: s = sessions.get(sid) if not s: return {"status": "not_found"} return { "session_id": sid, "status": s.get("status"), "message": s.get("message"), "created_at": s.get("created_at"), "last_activity": s.get("last_activity"), "result": s.get("result") if s.get("status") == "completed" else None, }