Files
syops/scripts/rpa/connectors/dsv/dsv_auth.py
T
hugo 12521489c6 refactor(rpa): 重构 scripts/rpa 目录结构与命名
按 common/connectors/inventory/receipt 分层并重命名

- common/: rpa_common, rpa_heartbeat, download_artifact_fallback,
  new_rpa_worker_secret
- connectors/dsv|crane/: 登录网站连接器,库存与收料共用
- inventory/: inventory_rpa_worker, run_inventory_batch_trigger,
  start_inventory_worker, register_inventory_worker_tasks
- receipt/: receipt_rpa_worker, receipt_crane/dbs_export,
  start_receipt_worker

保留裸 import + sys.path 引导;修正懒加载路径;
按范围命名 register_rpa_background_tasks -> register_inventory_worker_tasks;
同步 backend 测试、start_local.ps1、.env 注释、docs 与 README 路径。

(cherry picked from commit f3050164d0)
2026-08-28 17:23:39 +08:00

1017 lines
42 KiB
Python

"""
scripts/rpa/dsv_auth.py
用途:DSV 360 PingID 分步登录(邮箱 → 密码方式 → 密码 → portal)。
依赖:rpa_common、dsv_debug;登录主编排见 dsv_auth_login_flow。
逻辑:由 dsv_session / dsv_report_export 在 ensure session 时调用 maybe_auto_login_dsv。
"""
from __future__ import annotations
import sys as _sys
from pathlib import Path as _Path
_RPA_ROOT = next(
(_c for _c in _Path(__file__).resolve().parents
if (_c / "connectors").is_dir() and (_c / "common").is_dir()
and (_c / "inventory").is_dir() and (_c / "receipt").is_dir()),
None,
)
if _RPA_ROOT is not None:
for _rel in ("", "common", "connectors", "connectors/dsv", "connectors/crane", "inventory", "receipt"):
_dir = str(_RPA_ROOT) if not _rel else str(_RPA_ROOT / _rel)
if _dir not in _sys.path:
_sys.path.insert(0, _dir)
import sys
import time
from typing import Any, Callable
from rpa_common import browser_timeout_ms as _browser_timeout_ms
from rpa_common import env as _env
from rpa_common import fill_first_visible_text_input as _fill_first_visible_text_input
from rpa_common import wait_for_visible_selector as _wait_for_visible_selector
from dsv_debug import (
collect_dsv_reports_probe as _collect_dsv_reports_probe,
debug_dsv_stage as _debug_dsv_stage,
report_debug_event as _report_debug_event,
report_dsv_chain_stage as _report_dsv_chain_stage,
)
def _click_dsv_password_method(page: Any) -> bool:
def password_ready() -> bool:
"""密码输入框已出现即视为方法页切换成功;兼容轻量探测与通用等待。"""
if _find_dsv_password_locator(page, timeout_ms=250) is not None:
return True
return _wait_for_visible_selector(
page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR",
("input#userpassword", 'input[name="userpassword"]', 'input[name="password"]', 'input[type="password"]'),
timeout_ms=250,
) is not None
def transition_confirmed() -> bool:
deadline = time.monotonic() + 4
while time.monotonic() < deadline:
if password_ready():
return True
if not _looks_like_dsv_login_method_page(page):
try:
body_text = page.locator("body").inner_text(timeout=1_000)
except Exception:
body_text = ""
lowered = body_text.lower()
looks_like_password_page = (
("输入您的密码" in body_text or "忘记密码" in body_text or "password" in lowered)
and "通行密钥" not in body_text
and "passkey" not in lowered
and "验证失败" not in body_text
and "validation failed" not in lowered
)
if looks_like_password_page:
time.sleep(0.3)
continue
return False
time.sleep(0.3)
return False
script_row_click = """
() => {
const textOf = (node) => ((node && (node.innerText || node.textContent || node.value)) || '').replace(/\\s+/g, ' ').trim();
const isVisible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return !(style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0);
};
const isPasswordMethod = (text) => (
(text === '密码' || text === 'Password' || text === '输入您的密码并登录。' || text.includes('输入您的密码并登录'))
&& !text.includes('忘记密码')
&& !text.includes('取消')
&& !text.includes('返回')
&& !text.includes('通行密钥')
&& !text.includes('电子邮件验证码')
&& !text.includes('移动应用程序')
&& !text.toLowerCase().includes('cancel')
&& !text.toLowerCase().includes('back')
&& !text.toLowerCase().includes('passkey')
);
const rows = Array.from(document.querySelectorAll("form[name='mfaForm'] li.mb-2, form[name='mfaForm'] .mb-2, .device-list li.mb-2, .device-list .mb-2"))
.filter((node) => isVisible(node));
const row = rows.find((node) => isPasswordMethod(textOf(node)));
if (!row) return false;
const target = row.querySelector('.device-continue, button, a, [role="button"], input[type="submit"]') || row;
target.scrollIntoView({ block: 'center', inline: 'center' });
if (target.tagName === 'FORM') {
if (typeof target.requestSubmit === 'function') target.requestSubmit();
else target.submit();
return true;
}
if (typeof target.click === 'function') target.click();
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
return true;
}
"""
for frame in page.frames:
try:
_clicked = frame.evaluate(script_row_click)
if _clicked and transition_confirmed():
return True
except Exception:
pass
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
try:
rows = page.locator("form[name='mfaForm'] li.mb-2").all()
for row in rows:
text = row.inner_text(timeout=1_000)
lowered = text.lower()
if ("密码" in text or "Password" in text) and "忘记密码" not in text and "取消" not in text and "返回" not in text and "cancel" not in lowered and "back" not in lowered:
row.scroll_into_view_if_needed(timeout=3_000)
try:
row.click(timeout=3_000, force=True)
except Exception:
row.evaluate(
"""
(node) => {
if (typeof node.click === 'function') node.click();
node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
""",
timeout=2_000,
)
if transition_confirmed():
return True
except Exception:
pass
time.sleep(0.5)
return False
def _submit_dsv_username_form(username_locator: Any) -> bool:
try:
return bool(
username_locator.evaluate(
"""
(node) => {
const form = node.closest('form');
if (!form) return false;
if (typeof form.requestSubmit === 'function') {
form.requestSubmit();
} else {
form.submit();
}
return true;
}
""",
timeout=2_000,
)
)
except Exception:
return False
def _click_dsv_continue(page: Any, username_locator: Any | None = None) -> bool:
if username_locator is not None:
if _submit_dsv_username_form(username_locator):
return True
try:
username_locator.press("Enter", timeout=3_000)
return True
except Exception:
pass
for selector in (
'button:has-text("继续")',
'button:has-text("Continue")',
'input[value="继续"]',
'input[value="Continue"]',
'[role="button"]:has-text("继续")',
'[role="button"]:has-text("Continue")',
'a:has-text("继续")',
'a:has-text("Continue")',
'.dbs-sims-button-primary',
'button[type="submit"]',
'input[type="submit"]',
):
for frame in page.frames:
try:
locator = frame.locator(selector).first
locator.wait_for(state="attached", timeout=1_000)
try:
locator.click(timeout=1_000)
except Exception:
locator.click(timeout=1_000, force=True)
return True
except Exception:
pass
for frame in page.frames:
try:
identifier = frame.locator("input#identifier").first
identifier.wait_for(state="attached", timeout=1_000)
identifier.press("Enter", timeout=3_000)
return True
except Exception:
pass
script = """
() => {
const candidates = Array.from(document.querySelectorAll('body *')).filter((node) => {
const style = window.getComputedStyle(node);
const rect = node.getBoundingClientRect();
return style.visibility !== 'hidden' && style.display !== 'none' && rect.width > 0 && rect.height > 0;
});
const label = candidates.find((node) => {
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
return text === '继续' || text === 'Continue' || text.includes('继续') || text.includes('Continue');
});
const target = label && (label.closest('button, input, a, [role="button"], .dbs-sims-button-primary, [onclick], form') || label);
if (!target) return false;
target.scrollIntoView({ block: 'center', inline: 'center' });
if (target.tagName === 'FORM') {
if (typeof target.requestSubmit === 'function') target.requestSubmit();
else target.submit();
return true;
}
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
target.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
return true;
}
"""
for frame in page.frames:
try:
if frame.evaluate(script):
return True
except Exception:
pass
return False
def _dsv_locator_can_edit(locator: Any) -> bool:
try:
if locator.is_editable(timeout=1_000):
return True
except Exception:
pass
try:
return bool(
locator.evaluate(
"(node) => !node.disabled && !node.readOnly && node.getAttribute('aria-disabled') !== 'true'",
timeout=1_000,
)
)
except Exception:
return False
def _dsv_username_has_value(locator: Any) -> bool:
for _ in range(5):
try:
if locator.input_value(timeout=1_000).strip():
return True
except Exception:
pass
time.sleep(0.2)
return False
_DSV_MAYBE_LATER_SELECTORS: tuple[str, ...] = (
'button.dbs-sims-button-secondary:has-text("也许以后")',
'button.dbs-sims-button-secondary:has-text("Maybe later")',
'button.dbs-sims-button-secondary:has-text("Maybe Later")',
'button.dbs-sims-button-secondary:has-text("Not now")',
'button.dbs-sims-button-secondary:has-text("Not Now")',
'button:has-text("也许以后")',
'a:has-text("也许以后")',
'[role="button"]:has-text("也许以后")',
'text=也许以后',
'button:has-text("Maybe later")',
'button:has-text("Maybe Later")',
'a:has-text("Maybe later")',
'a:has-text("Maybe Later")',
'[role="button"]:has-text("Maybe later")',
'[role="button"]:has-text("Maybe Later")',
'text=Maybe later',
'text=Maybe Later',
'button:has-text("Not now")',
'button:has-text("Not Now")',
'a:has-text("Not now")',
'a:has-text("Not Now")',
'text=Not now',
'text=Not Now',
)
_DSV_PASSWORD_UPGRADE_PROMPT_MARKERS: tuple[str, ...] = (
"使用密码升级登录",
"升级登录",
"password upgrade",
"upgrade your sign-in",
"sign in with a passkey",
"passkey",
)
def _dsv_maybe_later_selector_candidates() -> tuple[str, ...]:
"""返回“也许以后 / Maybe later”按钮候选选择器;支持 SHIPPING_NOTICE_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR 覆盖。"""
selector = _env("SHIPPING_NOTICE_RPA_WORKER_DSV_MAYBE_LATER_SELECTOR")
return (selector,) if selector else _DSV_MAYBE_LATER_SELECTORS
def _is_dsv_password_upgrade_redirect(page: Any) -> bool:
"""
判断是否处在点击登录后的密码升级提示地址。
核心逻辑:只有 `auth.dbschenker.com/.../resume/as/authorization.ping` 才需要点击
“也许以后”;如果登录直接进入 s360 portal,则不做升级提示处理。
"""
try:
current_url = str(page.url or "").lower()
except Exception:
return False
return "auth.dbschenker.com" in current_url and "/resume/as/authorization.ping" in current_url
def _portal_home_nav_already_usable(page: Any) -> bool:
"""
判断 s360 portal 首页导航是否已可操作。
核心逻辑:仅在 Reports 顶栏已可用时,才跳过升级提示扫描,避免把“弹窗挡住的 portal 页”
误判为“首页已稳定”。
"""
current_url = str(getattr(page, "url", "") or "").lower()
if "s360.dbschenker.com" not in current_url or "auth.dbschenker.com" in current_url:
return False
try:
import dsv_session
return bool(dsv_session.has_dsv_report_nav_usable(page))
except Exception:
return False
def _try_click_dsv_maybe_later_via_js(root: Any) -> bool:
"""
通过 innerText 匹配点击“也许以后 / Maybe later”按钮。
核心逻辑:Playwright 选择器未命中时(class 变更、文本大小写差异),用 JS 兜底点击
secondary 按钮,并显式跳过“立即启用 / Enable now”主按钮。
"""
script = """
() => {
const labels = ['也许以后', 'maybe later', 'not now'];
const skipLabels = ['立即启用', 'enable now'];
const isVisible = (node) => {
if (!node) return false;
const style = window.getComputedStyle(node);
if (style.visibility === 'hidden' || style.display === 'none') return false;
const rect = node.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
};
const nodes = Array.from(document.querySelectorAll('button, a, [role="button"], .dbs-sims-button-secondary, .dbs-sims-button'));
for (const node of nodes) {
if (!isVisible(node)) continue;
const text = ((node.innerText || node.textContent || '') + '').replace(/\\s+/g, ' ').trim();
const lowered = text.toLowerCase();
if (skipLabels.some((label) => lowered.includes(label))) continue;
if (!labels.some((label) => lowered.includes(label))) continue;
node.scrollIntoView({ block: 'center', inline: 'center' });
if (typeof node.click === 'function') node.click();
node.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
return true;
}
return false;
}
"""
try:
return bool(root.evaluate(script, timeout=2_000))
except Exception:
return False
def _has_dsv_password_upgrade_prompt(page: Any, timeout_ms: int = 250) -> bool:
"""
快速判断 DSV 是否真的出现“也许以后 / Maybe later”升级提示。
核心逻辑:仅检查升级提示的强特征,不把 Verifying compliance 或普通 auth 跳转页
误判成升级提示;portal 首页导航已可用时才跳过扫描,弹窗挡屏时仍会继续探测。
"""
if not _is_dsv_password_upgrade_redirect(page):
return False
if _portal_home_nav_already_usable(page):
return False
candidates = _dsv_maybe_later_selector_candidates()
roots = [page, *getattr(page, "frames", [])]
for root in roots:
for candidate in candidates:
try:
if root.locator(candidate).first.is_visible(timeout=timeout_ms):
return True
except Exception:
continue
try:
body = root.locator("body").inner_text(timeout=timeout_ms).lower()
except Exception:
body = ""
if any(marker.lower() in body for marker in _DSV_PASSWORD_UPGRADE_PROMPT_MARKERS):
if any(label in body for label in ("也许以后", "maybe later", "not now")):
return True
return False
def _debug_dsv_login_method_page(page: Any) -> str:
snippets: list[str] = []
for idx, frame in enumerate(page.frames):
try:
body = frame.locator("body").inner_text(timeout=1_000).replace("\n", " ")[:500]
except Exception:
body = ""
try:
candidates = frame.evaluate(
"""
() => Array.from(document.querySelectorAll('.device-type, .device-description, li, button, a, [role="button"]'))
.map((node) => ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim())
.filter(Boolean)
.slice(0, 30)
""",
timeout=1_000,
)
except Exception:
candidates = []
if body or candidates:
snippets.append(f"frame[{idx}] body={body!r} candidates={candidates!r}")
return " | ".join(snippets)[:2000]
def _fill_dsv_password_page_fields(page: Any, username: str, password: str) -> bool:
filled_password = False
for frame in page.frames:
try:
inputs = frame.locator("input").all()
except Exception:
inputs = []
for input_locator in inputs:
try:
input_type = str(input_locator.get_attribute("type", timeout=500) or "").lower()
input_name = str(input_locator.get_attribute("name", timeout=500) or "").lower()
input_id = str(input_locator.get_attribute("id", timeout=500) or "").lower()
if not input_locator.is_visible(timeout=500):
continue
if input_type == "password" or "password" in input_name or "password" in input_id:
input_locator.fill(password, timeout=2_000)
filled_password = True
elif input_type in {"", "text", "email"} or "user" in input_name or "identifier" in input_name:
current = str(input_locator.input_value(timeout=500) or "").strip()
if not current:
input_locator.fill(username, timeout=2_000)
except Exception:
pass
return filled_password
def _is_dsv_username_page(page: Any) -> bool:
for frame in page.frames:
try:
text = frame.locator("body").inner_text(timeout=500)
except Exception:
text = ""
lowered = text.lower()
method_markers = ("选择登录方法", "choose a sign-on method", "输入您的密码并登录", "password")
if any(marker in text or marker in lowered for marker in method_markers):
continue
if ("电子邮件或SIMS ID或手机号" in text or "e-mail or sims id" in lowered) and ("继续" in text or "continue" in lowered):
return True
return False
def _submit_dsv_password_form(page: Any) -> bool:
"""
提交 DSV 密码登录页。
核心逻辑:优先直接点击可见登录按钮;如果页面使用 Vue/隐藏字段组合提交,
则退回到 DOM 脚本里触发 `pf.ok` / form submit / Enter,避免“密码已填完但未真正登录”。
"""
# 密码已填写后 DSV 也可能弹出“使用密码升级登录!”(也许以后/立即启用)遮挡登录按钮;
# 提交前先关闭,避免“DSV login password step detected but login button was not found”。
if _is_dsv_password_upgrade_redirect(page) and _has_dsv_password_upgrade_prompt(page):
_dismiss_dsv_password_upgrade_prompt(page)
selectors = (
'button[name="login"]',
'button[type="submit"]',
'input[type="submit"]',
'input[name="pf.ok"]',
'button.btn.dbs-sims-button-primary',
'button.dbs-sims-button-primary',
)
roots = [page, *getattr(page, "frames", [])]
for selector in selectors:
for root in roots:
try:
button = root.locator(selector).first
button.wait_for(state="visible", timeout=1_000)
button.click(timeout=2_000, force=True)
return True
except Exception:
pass
script = """
() => {
const visible = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
return style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 0 && rect.height > 0;
};
const password = Array.from(document.querySelectorAll('input#userpassword, input[name="userpassword"], input#password[name="pf.pass"], input[name="pf.pass"], input[type="password"]'))
.find((node) => !node.disabled);
if (!password) return false;
const form = password.closest('form');
const scope = form || document;
const submit = scope.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button.btn.dbs-sims-button-primary, button.dbs-sims-button-primary')
|| Array.from(scope.querySelectorAll('button, input[type="submit"], input[name="pf.ok"], [role="button"], .btn.dbs-sims-button-primary, .dbs-sims-button-primary, .dbs-sims-button'))
.find((node) => {
const text = ((node.innerText || node.textContent || node.value || '') + '').replace(/\\s+/g, ' ').trim();
return text === '登录' || text === 'Login' || text === 'Log in' || text === 'Sign in';
}) || (form ? form.querySelector('button[name="login"], button[type="submit"], input[type="submit"], input[name="pf.ok"], button:not([type]), .btn.dbs-sims-button-primary, .dbs-sims-button-primary') : null);
if (submit) {
if (visible(submit) && typeof submit.scrollIntoView === 'function') {
submit.scrollIntoView({ block: 'center', inline: 'center' });
}
submit.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, cancelable: true, pointerType: 'mouse' }));
submit.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, view: window }));
submit.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, cancelable: true, view: window }));
submit.click();
submit.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
return true;
}
if (form && typeof form.requestSubmit === 'function') {
form.requestSubmit();
return true;
}
if (form) {
form.submit();
return true;
}
password.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }));
return true;
}
"""
for frame in roots:
try:
if frame.evaluate(script, timeout=2_000):
return True
except Exception:
pass
return False
def _looks_like_dsv_login_method_page(page: Any) -> bool:
# 升级提示弹窗文案含“密码”(“使用密码升级登录!”),会命中“选择登录方法”的
# 宽泛 needle 造成误判(反复尝试点击“密码方式”而非关闭弹窗);命中升级提示时直接判非方法页。
if _has_dsv_password_upgrade_prompt(page):
return False
needles = ("选择登录方法", "密码", "Password", "输入您的密码并登录", "Choose a sign-on method")
for frame in page.frames:
try:
text = frame.locator("body").inner_text(timeout=300)
except Exception:
text = ""
lowered = text.lower()
if "real person" in lowered and ("rabbit" in lowered or "scale" in lowered):
continue
if any(needle in text for needle in needles):
return True
return False
def _has_dsv_human_check_prompt(page: Any) -> bool:
"""快速判断当前页是否出现真人验证提示,避免在普通登录轮询里反复触发重等待。"""
try:
text = page.locator("body").inner_text(timeout=300)
except Exception:
text = ""
lowered = text.lower()
return "real person" in lowered or "rabbit" in lowered or "scale" in lowered or "真人" in text
def _wait_for_dsv_login_method_page(page: Any, timeout_ms: int | None = None) -> bool:
wait_ms = timeout_ms if timeout_ms is not None else max(5_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_METHOD_PAGE_TIMEOUT_MS", "20000") or "20000"))
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
if "s360.dbschenker.com" in page.url and "auth.dbschenker.com" not in page.url:
return True
if _looks_like_dsv_login_method_page(page):
return True
if _has_dsv_human_check_prompt(page):
_wait_for_dsv_human_check_if_present(page, timeout_ms=2_000)
time.sleep(0.5)
return False
def _wait_for_dsv_human_check_if_present(page: Any, timeout_ms: int | None = None) -> None:
wait_ms = timeout_ms if timeout_ms is not None else 300_000
try:
text = page.locator("body").inner_text(timeout=2_000)
except Exception:
text = ""
lowered = text.lower()
if "real person" not in lowered and "rabbit" not in lowered and "scale" not in lowered and "真人" not in text:
return
print("[dsv-login] human check detected; please click the requested object in the browser")
deadline = time.monotonic() + (wait_ms / 1000)
while time.monotonic() < deadline:
try:
current = page.locator("body").inner_text(timeout=2_000)
except Exception:
current = ""
lowered_current = current.lower()
if "real person" not in lowered_current and "rabbit" not in lowered_current and "scale" not in lowered_current:
print("[dsv-login] human check passed")
return
time.sleep(2)
raise RuntimeError("DSV login human check was not completed in time")
def _dsv_login_debug_value(page: Any) -> tuple[str, dict[str, Any]]:
identifier_value = ""
button_state: dict[str, Any] = {}
for frame in page.frames:
if not identifier_value:
try:
identifier_value = frame.locator("input#identifier").first.input_value(timeout=1_000)
except Exception:
pass
if not button_state:
try:
button_state = frame.locator("button[name='login']").first.evaluate(
"(node) => ({ disabled: node.disabled, text: node.textContent, className: node.className })",
timeout=1_000,
)
except Exception:
pass
if identifier_value or button_state:
break
return identifier_value, button_state
def _find_dsv_password_locator(page: Any, timeout_ms: int = 250):
"""
轻量探测 DSV 密码输入框。
核心逻辑:登录第二/第三步切换期间只需要快速知道“密码框是否已出现”,
这里避免调用带长轮询的通用选择器等待,减少方法页阶段的有效阻塞。
"""
selectors = tuple(
item
for item in (
_env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD_SELECTOR"),
"input#userpassword",
'input[name="userpassword"]',
'input[name="password"]',
'input[type="password"]',
)
if item
)
for frame in page.frames:
for selector in selectors:
try:
locator = frame.locator(selector).first
if locator.is_visible(timeout=timeout_ms):
return locator
except Exception:
continue
return None
def _is_dsv_oauth_handshake_url(url: str) -> bool:
"""PingFederate OAuth 握手页:常见为空白 body,需等待 JS 跳转或 reload。"""
current = str(url or "").lower()
return "auth.dbschenker.com" in current and "authorization.oauth2" in current
def _is_dsv_auth_ping_url(url: str) -> bool:
"""PingFederate 密码阶段 authorization.ping:同样可能出现空白 body。"""
current = str(url or "").lower()
return "auth.dbschenker.com" in current and "authorization.ping" in current
def _is_dsv_blank_auth_transition(page: Any) -> bool:
"""auth 域 oauth2/ping 中间页中 body 为空。"""
try:
current_url = str(page.url or "").lower()
except Exception:
return False
if not (_is_dsv_oauth_handshake_url(current_url) or _is_dsv_auth_ping_url(current_url)):
return False
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").strip()
except Exception:
body = ""
return not body
def _dsv_login_ready_timeout_ms() -> int:
"""DSV 登录表单/跳转就绪的最大等待秒数。"""
return max(60_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "120000") or "120000"))
def _wait_for_dsv_auth_page_ready(page: Any, *, timeout_ms: int | None = None) -> bool:
"""
等待 DSV auth 域完成 OAuth/Ping 握手并渲染登录表单或跳回 portal。
核心逻辑:authorization.oauth2 / authorization.ping 均可能空白;
轮询用户名/密码框与 portal 导航,必要时 reload 一次触发 PingFederate 自动提交。
"""
wait_ms = timeout_ms if timeout_ms is not None else _dsv_login_ready_timeout_ms()
deadline = time.monotonic() + (wait_ms / 1000)
started_at = time.monotonic()
logged_waiting = False
reload_attempted = False
while time.monotonic() < deadline:
current_url = str(page.url or "").lower()
if "s360.dbschenker.com" in current_url and "auth.dbschenker.com" not in current_url:
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
return True
if _wait_for_visible_selector(page, "", ("#report-mega-legacy",), timeout_ms=500) is not None:
return True
if _wait_for_visible_selector(
page,
"SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME_SELECTOR",
_DSV_USERNAME_SELECTORS,
timeout_ms=500,
) is not None:
return True
if _find_dsv_password_locator(page, timeout_ms=200) is not None:
return True
if _wait_for_dsv_login_method_page(page, timeout_ms=200):
return True
if "auth.dbschenker.com" not in current_url:
return True
try:
body = str(page.locator("body").inner_text(timeout=1_000) or "").strip()
except Exception:
body = ""
if body and not _is_dsv_blank_auth_transition(page):
return True
if not logged_waiting:
print(f"[dsv-login] waiting auth page render url={page.url!r}")
logged_waiting = True
try:
page.wait_for_load_state("load", timeout=2_000)
except Exception:
pass
try:
page.wait_for_load_state("networkidle", timeout=2_000)
except Exception:
pass
if not reload_attempted and (time.monotonic() - started_at) >= 12:
reload_attempted = True
transition = "ping" if _is_dsv_auth_ping_url(current_url) else "oauth"
print(f"[dsv-login] blank auth {transition} transition, reload once")
try:
page.reload(wait_until="commit", timeout=min(wait_ms, 45_000))
except Exception as exc:
print(f"[dsv-login] auth reload failed: {exc}", file=sys.stderr)
time.sleep(0.35)
print(f"[dsv-login] auth page wait finished url={page.url!r}")
return False
def _wait_for_dsv_oauth_handshake(page: Any, *, timeout_ms: int = 45_000) -> None:
"""兼容旧调用:委托至 _wait_for_dsv_auth_page_ready。"""
_wait_for_dsv_auth_page_ready(page, timeout_ms=timeout_ms)
def _try_fill_dsv_username_locator(locator: Any, username: str) -> bool:
try:
locator.wait_for(state="visible", timeout=1_000)
locator.wait_for(state="attached", timeout=1_000)
if not locator.is_enabled(timeout=1_000):
return False
if not _dsv_locator_can_edit(locator):
return False
locator.click(timeout=2_000)
try:
locator.fill(username, timeout=3_000)
except Exception:
locator.press("Control+A")
locator.press("Backspace")
locator.type(username, delay=30)
if _dsv_username_has_value(locator):
return True
locator.evaluate(
"""
(node, value) => {
node.focus();
node.value = value;
node.dispatchEvent(new Event('input', { bubbles: true }));
node.dispatchEvent(new Event('change', { bubbles: true }));
}
""",
username,
)
return _dsv_username_has_value(locator)
except Exception:
return False
def _fill_dsv_username(page: Any, username: str, preferred_locator: Any | None = None):
"""
在 DSV 第一步邮箱页填写账号。
核心逻辑:优先复用已经探测到的输入框,避免“探测到了邮箱框,但二次扫描更窄选择器后又找不到”的失配,
若复用失败,再按完整候选选择器扫描各 frame。
"""
if preferred_locator is not None and _try_fill_dsv_username_locator(preferred_locator, username):
return preferred_locator
timeout_ms = max(5_000, int(_env("SHIPPING_NOTICE_RPA_WORKER_LOGIN_READY_TIMEOUT_MS", "300000") or "300000"))
deadline = time.monotonic() + (timeout_ms / 1000)
while time.monotonic() < deadline:
for frame in page.frames:
for selector in _DSV_USERNAME_SELECTORS:
try:
locator = frame.locator(selector).first
if _try_fill_dsv_username_locator(locator, username):
return locator
except Exception:
pass
time.sleep(0.5)
return None
def _dismiss_dsv_password_upgrade_prompt(page: Any) -> None:
"""
DSV 首次登录后可能提示升级密码登录;RPA 选择“也许以后”继续进入系统。
"""
started_at = time.monotonic()
# #region debug-point M:upgrade-prompt-entry
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:entry",
"[DEBUG] checking dsv password upgrade prompt",
{"url": page.url},
)
# #endregion
candidates = _dsv_maybe_later_selector_candidates()
def _prompt_visible() -> bool:
return _has_dsv_password_upgrade_prompt(page, timeout_ms=250)
# [STEP 1] 先做轻量探测门;没看到升级提示强特征时,直接跳过,
# 避免在 Verifying compliance / auth 跳转页里做大范围阻塞轮询。
quick_detect_deadline = time.monotonic() + 5.0
prompt_detected = _prompt_visible()
while not prompt_detected and time.monotonic() < quick_detect_deadline:
time.sleep(0.2)
prompt_detected = _prompt_visible()
if not prompt_detected:
# #region debug-point M:upgrade-prompt-skip
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip",
"[DEBUG] dsv password upgrade prompt not shown",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
# #endregion
return
deadline = time.monotonic() + 15
while time.monotonic() < deadline:
roots = [page, *getattr(page, "frames", [])]
for root in roots:
for candidate in candidates:
try:
locator = root.locator(candidate).first
locator.wait_for(state="attached", timeout=300)
try:
locator.scroll_into_view_if_needed(timeout=1_000)
except Exception:
pass
try:
locator.click(timeout=1_500, force=True)
except Exception:
locator.evaluate(
"""
(target) => {
target.click();
target.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
}
"""
)
time.sleep(1)
if not _prompt_visible():
print("[dsv-login] password upgrade prompt dismissed")
# #region debug-point M:upgrade-prompt-dismissed
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed",
"[DEBUG] dsv password upgrade prompt dismissed",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "candidate": candidate, "url": page.url},
)
# #endregion
try:
page.wait_for_load_state("domcontentloaded", timeout=10_000)
except Exception:
pass
return
except Exception:
continue
if _try_click_dsv_maybe_later_via_js(root):
time.sleep(1)
if not _prompt_visible():
print("[dsv-login] password upgrade prompt dismissed via js fallback")
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:dismissed_js",
"[DEBUG] dsv password upgrade prompt dismissed via js fallback",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
try:
page.wait_for_load_state("domcontentloaded", timeout=10_000)
except Exception:
pass
return
if not _prompt_visible():
# #region debug-point M:upgrade-prompt-skip
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:skip",
"[DEBUG] dsv password upgrade prompt disappeared before click",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
# #endregion
return
_debug_dsv_stage(page, "password-upgrade-prompt-still-visible", target_text="Maybe later")
time.sleep(0.4)
# #region debug-point M:upgrade-prompt-timeout
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt:timeout",
"[DEBUG] dsv password upgrade prompt remained visible until timeout",
{"elapsedMs": int((time.monotonic() - started_at) * 1000), "url": page.url},
)
def _dismiss_dsv_password_upgrade_prompt_after_login_redirect(page: Any) -> None:
"""
登录提交后的条件处理:仅在跳到密码升级 auth resume 页时点击“也许以后”。
"""
if not _is_dsv_password_upgrade_redirect(page):
_report_debug_event(
"M",
"freight_rpa_worker.py:_dismiss_dsv_password_upgrade_prompt_after_login_redirect:skip",
"[DEBUG] skip password upgrade prompt because login did not redirect to upgrade URL",
{"url": page.url},
)
return
try:
page.wait_for_load_state("domcontentloaded", timeout=10_000)
except Exception:
pass
_dismiss_dsv_password_upgrade_prompt(page)
_DSV_USERNAME_SELECTORS = (
"input#identifier",
'input[name="identifier"]',
'input[name="username"]',
'input[name="userName"]',
'input[name="email"]',
'input[autocomplete="username"]',
'input[placeholder="电子邮件或SIMS ID或手机号"]',
'input[type="email"]',
'input[type="text"]',
)
# 公开 API
DSV_USERNAME_SELECTORS = _DSV_USERNAME_SELECTORS
click_dsv_continue = _click_dsv_continue
click_dsv_password_method = _click_dsv_password_method
debug_dsv_login_method_page = _debug_dsv_login_method_page
dismiss_dsv_password_upgrade_prompt = _dismiss_dsv_password_upgrade_prompt
dismiss_dsv_password_upgrade_prompt_after_login_redirect = _dismiss_dsv_password_upgrade_prompt_after_login_redirect
dsv_locator_can_edit = _dsv_locator_can_edit
dsv_login_debug_value = _dsv_login_debug_value
dsv_login_ready_timeout_ms = _dsv_login_ready_timeout_ms
dsv_username_has_value = _dsv_username_has_value
fill_dsv_password_page_fields = _fill_dsv_password_page_fields
fill_dsv_username = _fill_dsv_username
find_dsv_password_locator = _find_dsv_password_locator
has_dsv_human_check_prompt = _has_dsv_human_check_prompt
has_dsv_password_upgrade_prompt = _has_dsv_password_upgrade_prompt
is_dsv_auth_ping_url = _is_dsv_auth_ping_url
is_dsv_blank_auth_transition = _is_dsv_blank_auth_transition
is_dsv_oauth_handshake_url = _is_dsv_oauth_handshake_url
is_dsv_username_page = _is_dsv_username_page
looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page
submit_dsv_password_form = _submit_dsv_password_form
submit_dsv_username_form = _submit_dsv_username_form
try_fill_dsv_username_locator = _try_fill_dsv_username_locator
wait_for_dsv_auth_page_ready = _wait_for_dsv_auth_page_ready
wait_for_dsv_human_check_if_present = _wait_for_dsv_human_check_if_present
wait_for_dsv_login_method_page = _wait_for_dsv_login_method_page
wait_for_dsv_oauth_handshake = _wait_for_dsv_oauth_handshake
from dsv_auth_login_flow import maybe_auto_login_dsv as _maybe_auto_login_dsv
maybe_auto_login_dsv = _maybe_auto_login_dsv