AutoRpa/rpa_cart/yaoex_login.py

52 lines
1.5 KiB
Python

"""复用 rpa_selection 的 1 号药城登录。"""
from __future__ import annotations
import sys
from pathlib import Path
SELECTION_ROOT = Path(__file__).resolve().parent.parent / "rpa_selection"
if str(SELECTION_ROOT) not in sys.path:
sys.path.append(str(SELECTION_ROOT))
from auth_login import ( # noqa: E402
DEFAULT_YAOEX_AUTH_PATH,
BrowserRuntime,
load_dotenv,
load_secrets,
load_yaoex_auth_file,
login_yaoex,
save_yaoex_auth,
)
from search_yaoex import YaoexAuth # noqa: E402
def load_cart_dotenv() -> None:
load_dotenv(Path(__file__).resolve().parent / ".env")
load_dotenv(SELECTION_ROOT / ".env")
def resolve_yaoex_auth(
*,
secrets_path: Path | None = None,
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(secrets_path)
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(secrets_path, runtime=session)
save_yaoex_auth(auth, cached)
return auth
finally:
if own:
session.close()