"""Session store + run loop for MassHealth eligibility (persistent browser, OTP via app or browser).""" import os import time import asyncio from typing import Dict, Any from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import WebDriverException, TimeoutException from selenium_MH_eligibilityCheckWorker import AutomationMHEligibilityCheck, MH_BASE_URL from helpers_email_otp import fetch_otp_from_email, looks_like_email # Text that identifies the MassHealth / DentaQuest OTP email MH_OTP_EMAIL_KEYWORDS = ("masshealth-dental.org", "masshealth dental program") MH_MEMBERS_URL = MH_BASE_URL + "members" # 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 -> otp_submitted -> completed / error "created_at": time.time(), "last_activity": time.time(), "bot": None, # worker instance "driver": None, # selenium webdriver "otp_event": asyncio.Event(), "otp_value": None, "result": None, "message": None, "type": None, } return sid async def cleanup_session(sid: str, message: str | None = None): """ Set final error state and wake OTP waiter. Schedules session removal after a delay so the backend can read the actual error message before the session disappears. """ 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 except Exception: pass try: ev = s.get("otp_event") if ev and not ev.is_set(): ev.set() except Exception: pass # Keep session for 30s so backend can read the error, then remove asyncio.create_task(_remove_session_later(sid, 30)) async def _remove_session_later(sid: str, delay: int = 30): await asyncio.sleep(delay) sessions.pop(sid, None) async def start_mh_run(sid: str, data: dict, url: str, worker_cls=None): """ Run the MassHealth eligibility workflow for a session (WITHOUT managing semaphore/counters). Called by agent.py inside a wrapper that handles queue/counters. """ s = sessions.get(sid) if not s: return {"status": "error", "message": "session not found"} s["status"] = "running" s["last_activity"] = time.time() try: # worker_cls lets Check PreAuth reuse this flow with its own worker bot = (worker_cls or AutomationMHEligibilityCheck)({"data": data}) bot.config_driver() s["bot"] = bot s["driver"] = bot.driver s["last_activity"] = time.time() # Navigate to login URL try: if not url: raise ValueError("URL not provided for MH run") bot.driver.maximize_window() bot.driver.get(url) await asyncio.sleep(1) except Exception as e: s["status"] = "error" s["message"] = f"Navigation failed: {e}" await cleanup_session(sid) return {"status": "error", "message": s["message"]} # Login (remember when, so only OTP emails sent after this are used) login_started_at = time.time() - 60 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"]} # Already logged in - session persisted from profile, skip to step1 if isinstance(login_result, str) and login_result == "ALREADY_LOGGED_IN": s["status"] = "running" s["message"] = "Session persisted" # Continue to step1 below # OTP required path - POLL THE BROWSER to detect when user enters OTP elif isinstance(login_result, str) and login_result == "OTP_REQUIRED": s["status"] = "waiting_for_otp" s["message"] = "OTP required for login - please enter OTP in browser" s["last_activity"] = time.time() driver = s["driver"] # Read the code from the OTP email inbox automatically, if one is saved. # The app / browser entry below still works as a fallback. otp_email = (data.get("otpEmail") or "").strip() otp_email_password = data.get("otpEmailPassword") or "" if looks_like_email(otp_email) and otp_email_password: s["message"] = f"Reading the verification code from {otp_email} automatically... You can also type it here." async def _auto_fill_otp_from_email(): code = await asyncio.to_thread( fetch_otp_from_email, otp_email, otp_email_password, login_started_at, MH_OTP_EMAIL_KEYWORDS, SESSION_OTP_TIMEOUT - 10, 5, lambda: s.get("status") != "waiting_for_otp", ) if code and s.get("status") == "waiting_for_otp" and not s.get("otp_value"): print("[MH OTP] Code read from email, submitting") s["otp_value"] = code s["message"] = "OTP read from email - verifying..." elif not code and s.get("status") == "waiting_for_otp": s["message"] = "Could not read the OTP from email - please enter it manually" asyncio.create_task(_auto_fill_otp_from_email()) # Poll the browser to detect when OTP is completed (user enters it directly) # We check every 1 second for up to SESSION_OTP_TIMEOUT seconds (faster response) max_polls = SESSION_OTP_TIMEOUT login_success = False print(f"[MH OTP] Waiting for user to enter OTP (polling browser for {SESSION_OTP_TIMEOUT}s)...") for poll in range(max_polls): await asyncio.sleep(1) s["last_activity"] = time.time() try: # Check if OTP was submitted via API (from app) otp_value = s.get("otp_value") if otp_value: print(f"[MH OTP] OTP received from app: {otp_value}") try: otp_input = driver.find_element(By.XPATH, "//input[@data-testid='passcode'] | " "//input[contains(@name,'otp') or contains(@name,'code') or @type='tel' or contains(@aria-label,'Verification') or contains(@placeholder,'verification code')]" ) otp_input.click() otp_input.send_keys(Keys.CONTROL, "a") otp_input.send_keys(Keys.DELETE) otp_input.send_keys(otp_value) await asyncio.sleep(0.5) # Click "Verify" in the popup (the text is inside a ) try: verify_btn = driver.find_element(By.XPATH, "//button[normalize-space(.)='Verify'] | //button[@aria-label='Verify']") driver.execute_script("arguments[0].click();", verify_btn) print("[MH OTP] Clicked Verify") except Exception: otp_input.send_keys(Keys.ENTER) print("[MH OTP] Verify button not found, pressed Enter") print("[MH OTP] OTP typed and submitted via app") s["otp_value"] = None # Clear so we don't submit again await asyncio.sleep(3) # Wait for verification except Exception as type_err: print(f"[MH OTP] Failed to type OTP from app: {type_err}") # Check current URL - if we're on dashboard/member page, login succeeded current_url = driver.current_url.lower() print(f"[MH OTP Poll {poll+1}/{max_polls}] URL: {current_url[:60]}...") # Logged in once the member search box shows (home page has it at any URL) if driver.find_elements(By.XPATH, '//input[@data-testid="member-search_member-id_input" or @placeholder="Search by member ID"]'): print("[MH OTP] Member search box found - login successful!") login_success = True break # Check if we've navigated away from login/OTP pages if "member" in current_url or "dashboard" in current_url or "eligibility" in current_url: # Verify by checking for member search input try: member_search = WebDriverWait(driver, 5).until( EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]')) ) print("[MH OTP] Member search input found - login successful!") login_success = True break except TimeoutException: print("[MH OTP] On member page but search input not found, continuing to poll...") # Also check if OTP input is still visible try: otp_input = driver.find_element(By.XPATH, "//input[@data-testid='passcode'] | " "//input[contains(@name,'otp') or contains(@name,'code') or @type='tel' or contains(@aria-label,'Verification') or contains(@placeholder,'code') or contains(@placeholder,'Code')]" ) # OTP input still visible - user hasn't entered OTP yet print(f"[MH OTP Poll {poll+1}] OTP input still visible - waiting...") except: # OTP input not found - might mean login is in progress or succeeded # Try navigating to members page (like Delta MA) if "onboarding" in current_url or "start" in current_url or "login" in current_url: print("[MH OTP] OTP input gone, trying to navigate to members page...") try: driver.get(MH_MEMBERS_URL) await asyncio.sleep(2) except: pass except Exception as poll_err: print(f"[MH OTP Poll {poll+1}] Error: {poll_err}") if not login_success: # Final attempt - navigate to members page and check (like Delta MA) try: print("[MH OTP] Final attempt - navigating to members page...") driver.get(MH_MEMBERS_URL) await asyncio.sleep(3) member_search = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.XPATH, '//input[@placeholder="Search by member ID"]')) ) print("[MH OTP] Member search input found - login successful!") login_success = True except TimeoutException: s["status"] = "error" s["message"] = "OTP timeout - login not completed" await cleanup_session(sid) return {"status": "error", "message": "OTP not completed in time"} 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 login_success: s["status"] = "running" s["message"] = "Login successful after OTP" print("[MH OTP] Proceeding to step1...") elif isinstance(login_result, str) and login_result.startswith("ERROR"): s["status"] = "error" s["message"] = login_result await cleanup_session(sid) return {"status": "error", "message": login_result} # Login succeeded without OTP (SUCCESS) elif isinstance(login_result, str) and login_result == "SUCCESS": print("[start_mh_run] Login succeeded without OTP") s["status"] = "running" s["message"] = "Login succeeded" # Continue to step1 below # Step 1 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 (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 else: 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: import traceback print(f"[start_mh_run] EXCEPTION: {e}") traceback.print_exc() 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]: """Set OTP for a session and wake waiting runner.""" 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, }