- libs: 新增 hr_sdk / hotel_report / dingtalk,更新 desktopauto - controlplane-next: SDK 管理模块(controller/entity/migrations)与前端视图 - electron-shell: 插件同步、注册表、runner 调整 - plugins: XQ0035/XQ0041/XQ0042/XQ0045_XQ0046/XQ0048/XQ0076/XQ0078 等版本更新 - tests/tools: 新增 SDK 兼容性检查与打包工具(sdk_pack.py、sdk_compat_check.py)
84 lines
2.8 KiB
Python
84 lines
2.8 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""借用会话(SessionLike)与离线 cookie 构造。
|
||
|
||
**SDK 不负责按账号登录编排**:插件里一律用宿主注入的会话::
|
||
|
||
client = HrClient(ctx.get_session("hr"))
|
||
|
||
只有壳子的登录子进程 / CLI / agent 这类「没有宿主」的场景才用
|
||
:func:`session_from_cookies`。SDK 从不 ``close()`` 借来的 session。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
from typing import Any, Optional, Protocol, runtime_checkable
|
||
|
||
import requests
|
||
|
||
from .config import USER_AGENT, cookies_file
|
||
from .errors import ConfigError
|
||
|
||
|
||
@runtime_checkable
|
||
class SessionLike(Protocol):
|
||
"""借来的会话契约(requests.Session 天然满足)。"""
|
||
|
||
cookies: Any
|
||
headers: Any
|
||
|
||
def get(self, url, **kwargs): ... # noqa: D401,E704
|
||
|
||
def post(self, url, **kwargs): ...
|
||
|
||
|
||
def session_from_cookies(path: str = "", *, domain_filter: str = "37du.co",
|
||
user_agent: str = USER_AGENT) -> requests.Session:
|
||
"""从 cookies JSON 构造会话(仅取目标域 cookies)。
|
||
|
||
兼容两种文件格式:浏览器导出的 ``[{name,value,domain,path}, ...]`` 列表,
|
||
以及 ``{"cookies": [...]}`` 包装形式。
|
||
|
||
Raises:
|
||
ConfigError: 文件不存在或没有可用 cookie
|
||
"""
|
||
cookie_path = path or cookies_file()
|
||
if not cookie_path or not os.path.exists(cookie_path):
|
||
raise ConfigError(f"未找到 HR 登录态 cookies:{cookie_path}(请先登录 HR 平台)")
|
||
try:
|
||
with open(cookie_path, encoding="utf-8") as fp:
|
||
raw = json.load(fp)
|
||
except (OSError, ValueError) as exc:
|
||
raise ConfigError(f"cookies 文件无法解析:{cookie_path}({exc})") from None
|
||
items = raw.get("cookies") if isinstance(raw, dict) else raw
|
||
if not isinstance(items, list) or not items:
|
||
raise ConfigError(f"cookies 文件为空:{cookie_path}")
|
||
|
||
session = requests.Session()
|
||
session.headers.update({
|
||
"User-Agent": user_agent,
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
})
|
||
count = 0
|
||
for c in items:
|
||
if not isinstance(c, dict) or not c.get("name"):
|
||
continue
|
||
domain = c.get("domain") or ""
|
||
if domain_filter and domain_filter not in domain:
|
||
continue
|
||
session.cookies.set(c["name"], c.get("value", ""),
|
||
domain=domain or None, path=c.get("path", "/"))
|
||
count += 1
|
||
if not count:
|
||
raise ConfigError(f"cookies 中没有 {domain_filter} 域的条目:{cookie_path}")
|
||
return session
|
||
|
||
|
||
def looks_like_login_page(text: Optional[str]) -> bool:
|
||
"""接口正常返回 JSON;登录页/错误页 → 视为登录态过期。"""
|
||
return bool(text) and not str(text).lstrip().startswith(("{", "["))
|
||
|
||
|
||
__all__ = ["SessionLike", "looks_like_login_page", "session_from_cookies"]
|