Files
37duAutomation/libs/hr_sdk/hr_sdk/attach.py
T
puddy 9873eb1963 restore: 恢复 11-06~11-09 本地未提交改动
- 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)
2026-11-09 17:27:10 +08:00

87 lines
2.9 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.
# -*- coding: utf-8 -*-
"""附件下载(审批单附件等)。
用法::
from hr_sdk import HrClient, attach
client = HrClient(ctx.get_session("hr"))
paths = attach.download(client, file_id, save_dir=r"D:\\out\\附件")
"""
from __future__ import annotations
import os
from typing import List, Sequence
from urllib.parse import unquote
from .config import REDSEA, USER_AGENT
from .errors import ConfigError
ATTACHMENT_URL = f"{REDSEA}/corePlatformOutUser/fjkFileDownload.mob"
def _filename_from_headers(headers: dict, fallback: str) -> str:
"""从 Content-Disposition 解析文件名(兼容 ``UTF-8''`` 与 latin-1 编码)。"""
disposition = ""
for key, value in (headers or {}).items():
if key.lower() == "content-disposition":
disposition = str(value)
break
if "filename=" not in disposition:
return fallback
raw = disposition.split("filename=")[-1].strip().strip('"')
if raw.startswith("UTF-8''"):
raw = unquote(raw.split("UTF-8''", 1)[1])
else:
try:
raw = raw.encode("latin-1").decode("utf-8")
except (UnicodeDecodeError, UnicodeEncodeError):
pass
return raw or fallback
def download(client, file_id: str, save_dir: str) -> str:
"""下载单个附件,返回本地路径。
``file_id`` 允许逗号分隔多个(与接口字段一致),此时只下第一个;批量用
:func:`download_many`。
Raises:
ConfigError: file_id / save_dir 为空
HrError: HTTP 非 200 或内容为空
"""
ids = [x.strip() for x in str(file_id or "").split(",") if x.strip()]
if not ids:
raise ConfigError("file_id 为空")
if not save_dir:
raise ConfigError("save_dir 不能为空")
fid = ids[0]
os.makedirs(save_dir, exist_ok=True)
resp = client.session.get(f"{ATTACHMENT_URL}?fileId={fid}",
headers={"User-Agent": USER_AGENT}, timeout=60)
if resp.status_code != 200 or not resp.content:
from .errors import HrError
raise HrError(f"附件下载失败:HTTP {resp.status_code}(fileId={fid})")
name = _filename_from_headers(getattr(resp, "headers", {}) or {}, f"{fid}.bin")
path = os.path.abspath(os.path.join(save_dir, name))
with open(path, "wb") as fp:
fp.write(resp.content)
client.log(f"[INFO] 附件已下载:{path}({len(resp.content)} 字节)")
return path
def download_many(client, file_ids: Sequence[str], save_dir: str) -> List[str]:
"""下载多个附件;单个失败不影响其它(失败记录 WARN 并跳过)。"""
paths: List[str] = []
for fid in file_ids or []:
try:
paths.append(download(client, fid, save_dir))
except Exception as exc: # noqa: BLE001
client.log(f"[WARN] 附件 {fid} 下载失败:{exc}")
return paths
__all__ = ["ATTACHMENT_URL", "download", "download_many"]