Files
syops/scripts/rpa/connectors/dsv/dsv_auth.py
T
hugo 2841f4a598 feat(shipping_notice): 支持无 PO 表头的邮件分配表解析并锁定 STP 进行中的草稿
邮件分配表在无 PO 表头时,若已映射料号或预约号仍解析行以供
merge mpn_fallback,二者皆无才整表跳过;STP 等待入队/排队/执行
期间拒绝草稿内容写入并从可用动作中剥离 edit_draft/validate,
会话摘要与工作台同源认活跃 STP Job 以避免误判为待人工。
2026-09-16 10:00:19 +08:00

1254 lines
50 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
scripts/rpa/connectors/dsv/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;
方法页点击须兼容英文 “Choose a sign in method” 标题+副标题行(2026-09-16);
英文页可经 #kc_locale 尝试切「中文简体」(失败不阻断)。
"""
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 _is_dsv_password_method_label(text: str) -> bool:
"""
判断 MFA「选择登录方式」行文案是否为密码登录选项。
核心逻辑:兼容旧版精确标题(密码/Password)与新版英文行
「Password + Enter your password to sign in.」整行副标题;排除 Passkey /
Mobile App / E-Mail Code / 忘记密码等干扰行。
Args:
text: 方法行可见文案(可含换行,内部会归一化空白)。
Returns:
True 表示应点击该行进入密码输入页。
"""
normalized = " ".join(str(text or "").split()).strip()
if not normalized:
return False
lowered = normalized.lower()
exclude_needles = (
"忘记密码",
"forgot password",
"通行密钥",
"passkey",
"电子邮件验证码",
"e-mail code",
"email code",
"移动应用程序",
"mobile app",
"pingid",
"取消",
"cancel",
"返回",
)
if any(needle in normalized or needle in lowered for needle in exclude_needles):
return False
if normalized in {"密码", "Password"}:
return True
if normalized.startswith("密码") or normalized.startswith("Password"):
return True
if "输入您的密码并登录" in normalized:
return True
if "enter your password to sign in" in lowered:
return True
return False
def _dsv_switch_zh_cn_enabled() -> bool:
"""是否启用「英文登录页尝试切中文简体」加固;默认开启,可用环境变量关闭。"""
raw = str(_env("SHIPPING_NOTICE_RPA_WORKER_DSV_SWITCH_ZH_CN", "true") or "true").strip().lower()
return raw not in {"0", "false", "no", "off"}
def _read_dsv_locale_nav_label(page: Any) -> str:
"""
读取 SIMS 语言按钮 `#lanNavSel` 当前文案。
Args:
page: Playwright Page(可含 iframe)。
Returns:
归一化后的语言标签;找不到时返回空串。
"""
roots = [page, *getattr(page, "frames", [])]
for root in roots:
try:
locator = root.locator("#lanNavSel").first
locator.wait_for(state="visible", timeout=500)
return " ".join(str(locator.inner_text(timeout=500) or "").split()).strip()
except Exception:
continue
return ""
def _maybe_switch_dsv_locale_to_zh_cn(page: Any) -> bool:
"""
若登录页语言为 English,尝试切换为「中文简体」。
核心逻辑:读 `#lanNavSel`;已是中文则跳过;否则点 `#kc_locale` 打开下拉,
再点 `a.language.dropdown-item` 文案「中文简体」。整段失败只打日志,不抛异常。
Args:
page: Playwright Page(可含 iframe)。
Returns:
True 表示已是中文简体或切换成功;False 表示关闭开关/未检测到/切换失败。
"""
if not _dsv_switch_zh_cn_enabled():
return False
label = _read_dsv_locale_nav_label(page)
if not label:
return False
if "中文简体" in label or label in {"中文", "简体中文"}:
return True
if "english" not in label.lower() and "英文" not in label:
# 其他语言也尽量切到简体,避免后续文案漂移
print(f"[dsv-login] locale is {label!r}; trying 中文简体")
else:
print(f"[dsv-login] English locale detected ({label!r}); switching to 中文简体")
roots = [page, *getattr(page, "frames", [])]
try:
# [STEP 1] 打开语言下拉
opened = False
for root in roots:
try:
toggle = root.locator("#kc_locale").first
toggle.wait_for(state="visible", timeout=1_000)
toggle.click(timeout=2_000, force=True)
opened = True
break
except Exception:
continue
if not opened:
print("[dsv-login] locale switch skipped: #kc_locale not clickable")
return False
# [STEP 2] 点击「中文简体」
clicked = False
zh_selectors = (
'a.language.dropdown-item:has-text("中文简体")',
'a.dropdown-item:has-text("中文简体")',
'text="中文简体"',
)
for root in roots:
for selector in zh_selectors:
try:
item = root.locator(selector).first
item.wait_for(state="visible", timeout=2_000)
item.click(timeout=2_000, force=True)
clicked = True
break
except Exception:
continue
if clicked:
break
if not clicked:
print("[dsv-login] locale switch skipped: 中文简体 item not found")
return False
# [STEP 3] 确认标签变为中文简体(页面可能短暂重绘)
deadline = time.monotonic() + 8
while time.monotonic() < deadline:
current = _read_dsv_locale_nav_label(page)
if "中文简体" in current or current in {"中文", "简体中文"}:
print("[dsv-login] locale switched to 中文简体")
return True
time.sleep(0.3)
print(f"[dsv-login] locale switch unverified; label={_read_dsv_locale_nav_label(page)!r}")
return False
except Exception as exc:
print(f"[dsv-login] locale switch failed (non-blocking): {exc}")
return False
def _click_dsv_password_method(page: Any) -> bool:
"""
在 PingID「选择登录方式」页点击「密码」选项并确认进入密码框。
核心逻辑:先用 DOM 脚本按方法行点击(兼容 mfaForm / device-list / 泛化 listitem);
失败再按 Playwright 行选择器与精确文案 `Password`/`密码` 点击;任一路经须
`transition_confirmed`(密码框出现或离开方法页)才算成功。
Args:
page: Playwright Page(可含 iframe)。
Returns:
是否已确认进入密码阶段。
"""
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 "choose a sign in method" not in lowered
and "choose a sign-on method" 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
def try_click_locator(locator: Any) -> bool:
try:
locator.scroll_into_view_if_needed(timeout=3_000)
except Exception:
pass
try:
locator.click(timeout=3_000, force=True)
except Exception:
try:
locator.evaluate(
"""
(node) => {
if (typeof node.click === 'function') node.click();
for (const type of ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click']) {
node.dispatchEvent(new MouseEvent(type, { bubbles: true, cancelable: true, view: window }));
}
}
""",
timeout=2_000,
)
except Exception:
return False
return transition_confirmed()
# [STEP 1] DOM 脚本:放宽标题匹配 + 扩大方法行选择器(旧 mfaForm 与新英文 MFA 页)
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) => {
const lowered = (text || '').toLowerCase();
const excluded = (
text.includes('忘记密码') || lowered.includes('forgot password')
|| text.includes('通行密钥') || lowered.includes('passkey')
|| text.includes('电子邮件验证码') || lowered.includes('e-mail code') || lowered.includes('email code')
|| text.includes('移动应用程序') || lowered.includes('mobile app') || lowered.includes('pingid')
|| text.includes('取消') || lowered.includes('cancel')
|| text.includes('返回')
);
if (excluded) return false;
return (
text === '密码' || text === 'Password'
|| text.startsWith('密码') || text.startsWith('Password')
|| text.includes('输入您的密码并登录')
|| lowered.includes('enter your password to sign in')
);
};
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, li.mb-2, [role='listitem'], .device-type, button, a, [role='button']"
)).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
# [STEP 2] Playwright:按方法行选择器 + 精确文案 Password/密码 点击
row_selectors = (
"form[name='mfaForm'] li.mb-2",
"form[name='mfaForm'] .mb-2",
".device-list li.mb-2",
".device-list .mb-2",
"li.mb-2",
"[role='listitem']",
)
text_selectors = (
'text="Password"',
"text=Password",
'text="密码"',
"text=密码",
'button:has-text("Password")',
'button:has-text("密码")',
'[role="button"]:has-text("Password")',
'[role="button"]:has-text("密码")',
'a:has-text("Password")',
'a:has-text("密码")',
)
deadline = time.monotonic() + 10
while time.monotonic() < deadline:
roots = [page, *getattr(page, "frames", [])]
for root in roots:
for selector in row_selectors:
try:
rows = root.locator(selector).all()
except Exception:
rows = []
for row in rows:
try:
text = row.inner_text(timeout=1_000)
except Exception:
continue
if not _is_dsv_password_method_label(text):
continue
if try_click_locator(row):
return True
for selector in text_selectors:
try:
locator = root.locator(selector).first
locator.wait_for(state="visible", timeout=500)
except Exception:
continue
if try_click_locator(locator):
return True
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
# 含英文新版 “Choose a sign in method”(无连字符);旧版为 sign-on。
needles = (
"选择登录方法",
"密码",
"Password",
"输入您的密码并登录",
"Choose a sign-on method",
"Choose a sign in 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 or needle.lower() in lowered 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_password_method_label = _is_dsv_password_method_label
is_dsv_username_page = _is_dsv_username_page
looks_like_dsv_login_method_page = _looks_like_dsv_login_method_page
maybe_switch_dsv_locale_to_zh_cn = _maybe_switch_dsv_locale_to_zh_cn
read_dsv_locale_nav_label = _read_dsv_locale_nav_label
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