AutoRpa/rpa_cart/yaoex_login.py

85 lines
2.5 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.

# 复用 rpa_selection 的 1 号药城 / 药帮忙登录。
#
# 导入路径由 selection_path 放进 rpa_selection,这里不再改 sys.path。
from __future__ import annotations
from pathlib import Path
import selection_path # noqa: F401 先把 rpa_selection 放进导入路径
from rpa_oracle import load_job_env
from auth_login import (
DEFAULT_YBM_COOKIE_PATH,
DEFAULT_YAOEX_AUTH_PATH,
BrowserRuntime,
load_cookie_file,
load_secrets,
load_yaoex_auth_file,
login_yaoex,
login_ybm,
save_cookie_file,
save_yaoex_auth,
)
from search_yaoex import YaoexAuth
# 读加购 / 选品 / oms 的 .env,不覆盖已有非空变量。
def load_cart_dotenv() -> None:
load_job_env(Path(__file__).resolve().parent)
# 拿到 1 号药城登录态。有缓存且 token 有效则直接用,否则走浏览器登录。
def resolve_yaoex_auth(
*,
auth_path: Path | None = None,
fresh: bool = False,
runtime: BrowserRuntime | None = None,
) -> YaoexAuth:
cached = auth_path or DEFAULT_YAOEX_AUTH_PATH
if not fresh and cached.exists():
auth = load_yaoex_auth_file(cached)
if auth.token and auth.token != "t":
return auth
secrets = load_secrets()
if not secrets["yaoex"].get("username"):
raise SystemExit(
"缺少 1 号药城账号。配置 rpa_selection/.env 或环境变量 YAOEX_USERNAME / YAOEX_PASSWORD。"
)
own = runtime is None
session = runtime or BrowserRuntime(keep=False)
try:
auth = login_yaoex(runtime=session)
save_yaoex_auth(auth, cached)
return auth
finally:
if own:
session.close()
# 拿到药帮忙登录 cookie。有缓存则直接用,否则走浏览器登录。
def resolve_ybm_cookies(
*,
cookie_path: Path | None = None,
fresh: bool = False,
runtime: BrowserRuntime | None = None,
) -> dict[str, str]:
cached = cookie_path or DEFAULT_YBM_COOKIE_PATH
if not fresh and cached.exists():
cookies = load_cookie_file(cached)
if cookies:
return cookies
secrets = load_secrets()
if not secrets["ybm"].get("username"):
raise SystemExit(
"缺少药帮忙账号。配置 rpa_selection/.env 或环境变量 YBM_USERNAME / YBM_PASSWORD。"
)
own = runtime is None
session = runtime or BrowserRuntime(keep=False)
try:
cookies = login_ybm(runtime=session)
save_cookie_file(cookies, cached)
return cookies
finally:
if own:
session.close()