82 lines
2.4 KiB
Python
82 lines
2.4 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_YBM_COOKIE_PATH,
|
|
DEFAULT_YAOEX_AUTH_PATH,
|
|
BrowserRuntime,
|
|
load_cookie_file,
|
|
load_dotenv,
|
|
load_secrets,
|
|
load_yaoex_auth_file,
|
|
login_yaoex,
|
|
login_ybm,
|
|
save_cookie_file,
|
|
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()
|
|
|
|
|
|
def resolve_ybm_cookies(
|
|
*,
|
|
secrets_path: Path | None = None,
|
|
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(secrets_path)
|
|
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(secrets_path, runtime=session)
|
|
save_cookie_file(cookies, cached)
|
|
return cookies
|
|
finally:
|
|
if own:
|
|
session.close()
|