383 lines
13 KiB
Python
383 lines
13 KiB
Python
"""
|
|
scripts/rpa/crane_session.py
|
|
|
|
用途:Crane AWS FootPrint Portal 登录、报表导航与 session 检测。
|
|
依赖:Playwright Page、crane_navigation;由 freight_rpa_worker._ensure_crane_session 委托调用。
|
|
逻辑:识别登录页并自动填写;登录后委托 navigate_to_crane_report 进入 On Hand Details Query。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import time
|
|
from typing import Any, Callable
|
|
from urllib.parse import urlparse
|
|
|
|
# Crane FootPrint 登录页(Bulma 表单)实测控件;用户名无 name 属性,靠 placeholder/label 定位。
|
|
_CRANE_USERNAME_SELECTORS: tuple[str, ...] = (
|
|
'input[placeholder="Enter user name..."]',
|
|
'input[placeholder*="user name" i]',
|
|
'form input.input[type="text"]',
|
|
'input[name="userName"]',
|
|
'input[name="username"]',
|
|
)
|
|
|
|
_CRANE_PASSWORD_SELECTORS: tuple[str, ...] = (
|
|
'input[placeholder="Enter password..."]',
|
|
'input.input.is-small.p-2.mt-1[type="password"]',
|
|
'input[placeholder*="password" i]',
|
|
'form input.input[type="password"]',
|
|
'input[type="password"]',
|
|
)
|
|
|
|
_CRANE_LOGIN_SUBMIT_SELECTORS: tuple[str, ...] = (
|
|
'button.button.is-primary:has-text("Sign in")',
|
|
'form button.button.is-primary',
|
|
'button.button.is-primary',
|
|
)
|
|
|
|
_CRANE_LOGIN_SUBMIT_TEXTS: tuple[str, ...] = ("Sign in", "Login", "Log in", "登录")
|
|
|
|
|
|
def _load_crane_navigation_module() -> Any:
|
|
"""运行时加载 crane_navigation,避免与 crane_session 循环 import。"""
|
|
import importlib.util
|
|
from pathlib import Path
|
|
|
|
module_path = Path(__file__).resolve().parent / "crane_navigation.py"
|
|
spec = importlib.util.spec_from_file_location("crane_navigation_runtime", module_path)
|
|
assert spec and spec.loader
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
def _visible_locator(page: Any, selector: str) -> Any | None:
|
|
"""在 page 与各 frame 中查找首个可见 locator。"""
|
|
for root in (page, *list(getattr(page, "frames", []))):
|
|
try:
|
|
locator = root.locator(selector).first
|
|
if locator.is_visible(timeout=500):
|
|
return locator
|
|
except Exception:
|
|
continue
|
|
return None
|
|
|
|
|
|
def _dispatch_input_events(locator: Any) -> None:
|
|
"""触发 input/change 事件,驱动 Vue 表单解除 Sign in 按钮 disabled。"""
|
|
try:
|
|
locator.evaluate(
|
|
"""
|
|
(node) => {
|
|
node.dispatchEvent(new Event('input', { bubbles: true }));
|
|
node.dispatchEvent(new Event('change', { bubbles: true }));
|
|
}
|
|
"""
|
|
)
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def _fill_visible_locator(locator: Any, value: str, *, browser_timeout_ms: int) -> bool:
|
|
"""向已定位控件写入文本,并触发前端校验以启用 Sign in。"""
|
|
try:
|
|
locator.fill(value, timeout=browser_timeout_ms)
|
|
_dispatch_input_events(locator)
|
|
return True
|
|
except Exception:
|
|
pass
|
|
try:
|
|
locator.click(timeout=3_000)
|
|
locator.press("Control+A")
|
|
locator.press("Backspace")
|
|
locator.type(value, delay=30)
|
|
_dispatch_input_events(locator)
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def _is_crane_button_enabled(locator: Any) -> bool:
|
|
"""Sign in 初始为 disabled,需等用户名/密码填写后解除。"""
|
|
try:
|
|
return bool(
|
|
locator.evaluate(
|
|
"""
|
|
(node) => {
|
|
if (!node) return false;
|
|
const disabled = Boolean(node.disabled);
|
|
const ariaDisabled = String(node.getAttribute('aria-disabled') || '').toLowerCase() === 'true';
|
|
const classDisabled = node.classList && node.classList.contains('is-disabled');
|
|
return !disabled && !ariaDisabled && !classDisabled;
|
|
}
|
|
"""
|
|
)
|
|
)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
return locator.is_enabled(timeout=500)
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def _find_crane_sign_in_button(
|
|
page: Any,
|
|
*,
|
|
selector_env: str,
|
|
env: Callable[[str, str], str],
|
|
browser_timeout_ms: int,
|
|
) -> Any | None:
|
|
"""
|
|
查找已启用的 Sign in 按钮。
|
|
核心逻辑:页面按钮 class 为 button is-primary,填写凭据前带 disabled 属性。
|
|
"""
|
|
selectors = tuple(
|
|
item
|
|
for item in (env(selector_env), *_CRANE_LOGIN_SUBMIT_SELECTORS, 'button[type="submit"]')
|
|
if item
|
|
)
|
|
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
|
|
|
while time.monotonic() < deadline:
|
|
for selector in selectors:
|
|
locator = _visible_locator(page, selector)
|
|
if locator is not None and _is_crane_button_enabled(locator):
|
|
return locator
|
|
|
|
for root in (page, *list(getattr(page, "frames", []))):
|
|
for text in _CRANE_LOGIN_SUBMIT_TEXTS:
|
|
try:
|
|
locator = root.get_by_role("button", name=text, exact=False).first
|
|
if locator.is_visible(timeout=500) and _is_crane_button_enabled(locator):
|
|
return locator
|
|
except Exception:
|
|
pass
|
|
time.sleep(0.25)
|
|
|
|
# 最后再试一次可见按钮(部分环境 disabled 属性更新滞后,但 click 仍有效)
|
|
for selector in selectors:
|
|
locator = _visible_locator(page, selector)
|
|
if locator is not None:
|
|
return locator
|
|
return None
|
|
|
|
|
|
def _fill_crane_field(
|
|
page: Any,
|
|
*,
|
|
selector_env: str,
|
|
value: str,
|
|
env: Callable[[str, str], str],
|
|
browser_timeout_ms: int,
|
|
fallback_selectors: tuple[str, ...],
|
|
label: str | None = None,
|
|
placeholder: str | None = None,
|
|
) -> bool:
|
|
"""
|
|
填写 Crane 登录字段。
|
|
核心逻辑:优先环境变量 selector,再试页面实测 fallback,最后用 label/placeholder 语义定位。
|
|
"""
|
|
text = str(value or "").strip()
|
|
if not text:
|
|
return False
|
|
|
|
selectors = tuple(item for item in (env(selector_env), *fallback_selectors) if item)
|
|
for selector in selectors:
|
|
locator = _visible_locator(page, selector)
|
|
if locator is not None and _fill_visible_locator(locator, text, browser_timeout_ms=browser_timeout_ms):
|
|
print(f"[crane-login] filled field via selector={selector!r}")
|
|
return True
|
|
|
|
for root in (page, *list(getattr(page, "frames", []))):
|
|
if label:
|
|
try:
|
|
locator = root.get_by_label(label, exact=False).first
|
|
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
|
locator, text, browser_timeout_ms=browser_timeout_ms
|
|
):
|
|
print(f"[crane-login] filled field via label={label!r}")
|
|
return True
|
|
except Exception:
|
|
pass
|
|
if placeholder:
|
|
try:
|
|
locator = root.get_by_placeholder(placeholder, exact=False).first
|
|
if locator.is_visible(timeout=500) and _fill_visible_locator(
|
|
locator, text, browser_timeout_ms=browser_timeout_ms
|
|
):
|
|
print(f"[crane-login] filled field via placeholder={placeholder!r}")
|
|
return True
|
|
except Exception:
|
|
pass
|
|
return False
|
|
|
|
|
|
def _click_crane_login_submit(
|
|
page: Any,
|
|
*,
|
|
selector_env: str,
|
|
env: Callable[[str, str], str],
|
|
browser_timeout_ms: int,
|
|
) -> bool:
|
|
"""
|
|
点击 Crane Sign in 按钮。
|
|
核心逻辑:等待 button.button.is-primary 解除 disabled 后再点击。
|
|
"""
|
|
locator = _find_crane_sign_in_button(
|
|
page,
|
|
selector_env=selector_env,
|
|
env=env,
|
|
browser_timeout_ms=min(browser_timeout_ms, 15_000),
|
|
)
|
|
if locator is None:
|
|
return False
|
|
|
|
try:
|
|
locator.click(timeout=browser_timeout_ms)
|
|
return True
|
|
except Exception:
|
|
pass
|
|
try:
|
|
locator.click(timeout=browser_timeout_ms, force=True)
|
|
return True
|
|
except Exception:
|
|
return False
|
|
|
|
|
|
def is_crane_login_page(page: Any) -> bool:
|
|
"""当前页是否为 Crane FootPrint 登录表单。"""
|
|
for selector in (
|
|
'input[placeholder="Enter user name..."]',
|
|
'input[placeholder="Enter password..."]',
|
|
):
|
|
if _visible_locator(page, selector) is not None:
|
|
return True
|
|
for root in (page, *list(getattr(page, "frames", []))):
|
|
try:
|
|
if root.get_by_label("User Name", exact=False).first.is_visible(timeout=500):
|
|
return True
|
|
except Exception:
|
|
pass
|
|
return False
|
|
|
|
|
|
def _crane_entry_host(entry_url: str) -> str:
|
|
"""从 entry_url 提取 host。"""
|
|
parsed = urlparse(str(entry_url or "").strip())
|
|
return (parsed.netloc or "").lower()
|
|
|
|
|
|
def is_crane_session_active(page: Any, entry_url: str) -> bool:
|
|
"""
|
|
判定浏览器是否已在 Crane portal 维持有效登录态。
|
|
核心逻辑:仍在 craneww 域且不再显示登录表单,即视为 session 有效。
|
|
"""
|
|
host = _crane_entry_host(entry_url)
|
|
if not host:
|
|
return False
|
|
try:
|
|
current_url = str(page.url or "").lower()
|
|
except Exception:
|
|
return False
|
|
if host not in current_url:
|
|
return False
|
|
if is_crane_login_page(page):
|
|
return False
|
|
return True
|
|
|
|
|
|
def wait_for_crane_app_ready(
|
|
page: Any,
|
|
entry_url: str,
|
|
*,
|
|
env: Callable[[str, str], str],
|
|
browser_timeout_ms: int,
|
|
) -> None:
|
|
"""
|
|
登录后导航并等待 Crane 报表表单就绪。
|
|
核心逻辑:先 navigate_to_crane_report(首页卡片 → 顶部菜单 → goto),再轮询表单控件。
|
|
"""
|
|
navigation = _load_crane_navigation_module()
|
|
mode = navigation.navigate_to_crane_report(
|
|
page,
|
|
entry_url,
|
|
env=env,
|
|
browser_timeout_ms=browser_timeout_ms,
|
|
)
|
|
print(f"[crane-nav] navigation mode={mode!r}")
|
|
|
|
deadline = time.monotonic() + (browser_timeout_ms / 1000)
|
|
while time.monotonic() < deadline:
|
|
if navigation.is_crane_report_form_ready(page, entry_url):
|
|
print("[crane-login] report form ready")
|
|
return
|
|
time.sleep(0.5)
|
|
|
|
raise RuntimeError("Crane report form did not become ready after navigation; check selectors or permissions")
|
|
|
|
|
|
def maybe_auto_login_crane(
|
|
page: Any,
|
|
*,
|
|
env: Callable[[str, str], str],
|
|
browser_timeout_ms: int,
|
|
) -> None:
|
|
"""
|
|
Crane FootPrint 自动登录:User Name → Password → Sign in。
|
|
核心逻辑:页面无登录框则跳过;填写后等待离开登录页并进入报表路由。
|
|
"""
|
|
username = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME")
|
|
password = env("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD")
|
|
if not username or not password:
|
|
return
|
|
|
|
if not is_crane_login_page(page):
|
|
print("[crane-login] no login form detected, skip auto login")
|
|
return
|
|
|
|
user_filled = _fill_crane_field(
|
|
page,
|
|
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR",
|
|
value=username,
|
|
env=env,
|
|
browser_timeout_ms=browser_timeout_ms,
|
|
fallback_selectors=_CRANE_USERNAME_SELECTORS,
|
|
label="User Name",
|
|
placeholder="Enter user name...",
|
|
)
|
|
password_filled = _fill_crane_field(
|
|
page,
|
|
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR",
|
|
value=password,
|
|
env=env,
|
|
browser_timeout_ms=browser_timeout_ms,
|
|
fallback_selectors=_CRANE_PASSWORD_SELECTORS,
|
|
label="Password",
|
|
placeholder="Enter password...",
|
|
)
|
|
if not user_filled and not password_filled:
|
|
print("[crane-login] login form visible but fields not filled", file=sys.stderr)
|
|
return
|
|
if user_filled != password_filled:
|
|
raise RuntimeError("CRANE login form partially detected; please configure login selectors")
|
|
|
|
if not _click_crane_login_submit(
|
|
page,
|
|
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
|
env=env,
|
|
browser_timeout_ms=browser_timeout_ms,
|
|
):
|
|
raise RuntimeError("CRANE login fields detected but Sign in button was not found")
|
|
|
|
page.wait_for_load_state("domcontentloaded", timeout=browser_timeout_ms)
|
|
if is_crane_login_page(page):
|
|
raise RuntimeError("CRANE login did not complete; MFA/SSO/manual verification may be required")
|
|
|
|
# [STEP] 登录后 Crane 常先落到 /#/ 首页,等待 SPA 壳层渲染再进入报表导航
|
|
try:
|
|
page.wait_for_load_state("networkidle", timeout=min(browser_timeout_ms, 15_000))
|
|
except Exception:
|
|
pass
|