Files

423 lines
16 KiB
Python

"""
backend/app/services/fixed_asset_image.py
用途:为固资管理提供“资产图片”检索与预览能力,按资产编号登录外部文档库并定位对应图片附件。
依赖:requests、app.core.config.settings.Config、chat.py 的预览代理会复用这里的已登录会话去抓取图片二进制。
逻辑:聊天表格点击“图片 -> 查看” -> chat API 调用本服务登录文档库并搜索固定资产图片 -> 前端继续走既有 FilePreviewModal 在站内预览。
"""
from __future__ import annotations
import threading
import time
from dataclasses import dataclass
from typing import Any
from urllib.parse import parse_qs, urlencode, urlparse, urlunparse
import requests
from flask import current_app, has_app_context
from app.core.config.settings import Config
from app.core.errors import NotFoundError, ServiceUnavailableError
_SESSION_LOCK = threading.Lock()
_SESSION_TTL_SECONDS = 20 * 60.0
_SESSION_CACHE: dict[str, Any] = {
"session": None,
"created_at": 0.0,
}
@dataclass(slots=True)
class AssetImageMatch:
"""固定资产图片最佳命中结果。"""
item_id: str
version_id: str
attachment_id: str
name: str
actual_ext: str
relative_path: str
size_bytes: int
url: str
def to_dict(self) -> dict[str, object]:
return {
"item_id": self.item_id,
"version_id": self.version_id,
"attachment_id": self.attachment_id,
"name": self.name,
"actual_ext": self.actual_ext,
"relative_path": self.relative_path,
"size_bytes": self.size_bytes,
"url": self.url,
}
class FixedAssetImageService:
"""
固资图片检索服务。
AI 触发时机:
- 当聊天结果表格里用户点击“图片 -> 查看”,希望直接预览该资产照片时调用;
- 输入必须至少带资产编号,资产名称仅作为兜底排序辅助;
- 输出返回同资产的全部命中图片(按最佳匹配优先排序),不把文档库账号暴露给前端。
"""
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"}
@classmethod
def _get_runtime_setting(cls, key: str, default: str = "") -> str:
if has_app_context():
try:
value = current_app.config.get(key)
if value is not None:
return str(value)
except Exception:
pass
return str(getattr(Config, key, default) or default)
@classmethod
def _get_base_url(cls) -> str:
raw_value = cls._get_runtime_setting("FIXED_ASSET_IMAGE_BASE_URL").strip()
if not raw_value:
return ""
parsed = urlparse(raw_value)
if parsed.scheme and parsed.netloc:
return f"{parsed.scheme}://{parsed.netloc}".rstrip("/")
return raw_value.rstrip("/")
@classmethod
def _build_url(cls, path: str) -> str:
return f"{cls._get_base_url()}{path}"
@classmethod
def is_enabled(cls) -> bool:
return all([
cls._get_base_url(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_USERNAME").strip(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_PASSWORD"),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_LIBRARY_ID").strip(),
cls._get_runtime_setting("FIXED_ASSET_IMAGE_FOLDER_ID").strip(),
])
@classmethod
def is_managed_asset_image_url(cls, file_url: str) -> bool:
base_url = cls._get_base_url()
if not base_url or not file_url:
return False
base = urlparse(base_url)
target = urlparse(file_url)
return (
target.scheme in ("http", "https")
and target.netloc.lower() == base.netloc.lower()
and (target.path or "").startswith("/Api/_api/DMS/Public/Attachment/Embed")
)
@classmethod
def resolve_images(cls, *, asset_id: str, asset_name: str = "") -> dict[str, object]:
"""
按资产编号解析文档库中的全部命中图片。
[STEP 1] 使用固定资产图片专用账号登录文档库,并缓存会话,避免每次点击都重复登录。
[STEP 2] 进入“文档库 > 总务 > 固定资产”目录按资产编号检索图片文件,仅保留常见图片扩展名。
[STEP 3] 选出全部有效命中并按相关度排序,回填图片 Embed URL,让前端支持单图或多图浏览。
"""
normalized_asset_id = str(asset_id or "").strip()
normalized_asset_name = str(asset_name or "").strip()
if not normalized_asset_id and not normalized_asset_name:
raise NotFoundError("当前资产缺少图片检索所需的编号或名称")
if not cls.is_enabled():
raise ServiceUnavailableError("固定资产图片文档库未配置,请联系管理员处理")
payload = {
"LibraryID": cls._get_runtime_setting("FIXED_ASSET_IMAGE_LIBRARY_ID").strip(),
"ParentFolderID": cls._get_runtime_setting("FIXED_ASSET_IMAGE_FOLDER_ID").strip(),
"Keywords": "",
"Page": {
"Size": 50,
"Index": 1,
},
"Total": 0,
"Recursion": True,
"OrderBy": [],
"FieldQuery": [],
"LeafName": normalized_asset_id or normalized_asset_name,
}
response = cls._request_json("POST", "/Api/_api/APS/Public/Item/Page", json=payload)
data_section = response.get("Data", {}) or {}
rows = (
data_section.get("Rows")
or data_section.get("Items")
or (data_section.get("Page") or {}).get("Items")
or []
)
matches = cls._pick_matches(rows, normalized_asset_id, normalized_asset_name)
if not matches:
display_name = normalized_asset_id or normalized_asset_name
raise NotFoundError(f"未找到资产 {display_name} 对应的图片文件")
primary_match = matches[0]
cls._record_browse(primary_match.item_id, primary_match.version_id)
return {
"item": primary_match.to_dict(),
"items": [match.to_dict() for match in matches],
"total": len(matches),
}
@classmethod
def resolve_image(cls, *, asset_id: str, asset_name: str = "") -> dict[str, object]:
"""兼容旧调用:仍返回最佳命中单图元数据。"""
result = cls.resolve_images(asset_id=asset_id, asset_name=asset_name)
return result["item"]
@classmethod
def fetch_preview_bytes(
cls,
file_url: str,
*,
max_size: int | None = 15 * 1024 * 1024,
) -> tuple[bytes | None, str | None, tuple[str, int] | None]:
"""
使用文档库登录态抓取图片二进制,供 `/preview-file-raw` 复用。
参数约束:仅处理本服务生成的 Embed URL;其余 URL 一律返回 None,让 chat.py 继续走默认拉取逻辑。
"""
if not cls.is_managed_asset_image_url(file_url):
return (None, None, None)
response = cls._request("GET", file_url, stream=True)
if response.status_code == 404:
return (None, None, ("asset image file not found", 404))
if response.status_code >= 400:
return (None, None, (f"asset image upstream returned {response.status_code}", 502))
content_length = response.headers.get("content-length")
if max_size is not None and content_length:
try:
if int(content_length) > max_size:
return (None, None, ("file too large for online preview", 413))
except ValueError:
pass
content = response.content
if max_size is not None and len(content) > max_size:
return (None, None, ("file too large for online preview", 413))
return (content, (response.headers.get("content-type") or "").strip().lower(), None)
@classmethod
def _pick_matches(
cls,
items: list[dict[str, Any]],
asset_id: str,
asset_name: str,
) -> list[AssetImageMatch]:
scored_matches: list[tuple[int, AssetImageMatch]] = []
for item in items:
match = cls._build_match(item, asset_id, asset_name)
if not match:
continue
score = cls._score_item(match.name, asset_id, asset_name, match.relative_path)
scored_matches.append((score, match))
if not scored_matches:
return []
scored_matches.sort(key=lambda pair: (-pair[0], pair[1].name.lower(), pair[1].attachment_id))
deduplicated: list[AssetImageMatch] = []
seen_attachment_ids: set[str] = set()
for _score, match in scored_matches:
if match.attachment_id in seen_attachment_ids:
continue
seen_attachment_ids.add(match.attachment_id)
deduplicated.append(match)
return deduplicated
@classmethod
def _build_match(
cls,
item: dict[str, Any],
asset_id: str,
asset_name: str,
) -> AssetImageMatch | None:
main_attachment = item.get("MainFileAttachment") or {}
extension = str(main_attachment.get("Extension") or "").strip().lower()
if extension not in cls.IMAGE_EXTENSIONS:
return None
attachment_id = str(main_attachment.get("ID") or "").strip()
item_id = str(item.get("ID") or "").strip()
version_id = str(item.get("VersionID") or "").strip()
if not attachment_id or not item_id or not version_id:
return None
raw_name = str(item.get("LeafName") or "").strip().rstrip(".")
normalized_name = cls._normalize_match_text(raw_name)
normalized_asset_id = cls._normalize_match_text(asset_id)
if normalized_asset_id and normalized_asset_id not in normalized_name:
return None
file_name = f"{raw_name or attachment_id}{extension}"
return AssetImageMatch(
item_id=item_id,
version_id=version_id,
attachment_id=attachment_id,
name=file_name,
actual_ext=extension.lstrip("."),
relative_path=str(item.get("Path") or "").strip(),
size_bytes=int(main_attachment.get("FileSize") or 0),
url=cls._build_embed_url(attachment_id),
)
@classmethod
def _score_item(cls, file_name: str, asset_id: str, asset_name: str, relative_path: str) -> int:
normalized_file_name = cls._normalize_match_text(file_name)
normalized_asset_id = cls._normalize_match_text(asset_id)
normalized_asset_name = cls._normalize_match_text(asset_name)
normalized_path = cls._normalize_match_text(relative_path)
score = 0
if normalized_asset_id:
if normalized_file_name == normalized_asset_id:
score += 200
elif normalized_file_name.startswith(normalized_asset_id):
score += 150
elif normalized_asset_id in normalized_file_name:
score += 120
elif normalized_asset_id in normalized_path:
score += 80
if normalized_asset_name:
if normalized_asset_name in normalized_file_name:
score += 60
elif normalized_asset_name in normalized_path:
score += 30
if file_name.lower().endswith(".jpg"):
score += 20
return score
@classmethod
def _build_embed_url(cls, attachment_id: str) -> str:
parsed = urlparse(cls._build_url("/Api/_api/DMS/Public/Attachment/Embed"))
query = parse_qs(parsed.query, keep_blank_values=True)
query["attachmentID"] = [attachment_id]
return urlunparse(parsed._replace(query=urlencode(query, doseq=True)))
@classmethod
def _normalize_match_text(cls, value: str) -> str:
return str(value or "").strip().lower().replace(" ", "").replace(".", "")
@classmethod
def _record_browse(cls, item_id: str, version_id: str) -> None:
"""
记录外部文档库浏览行为。
用途:与外部系统正常用户操作保持一致;失败不阻断图片预览主链路。
"""
if not item_id or not version_id:
return
try:
cls._request_json(
"POST",
"/Api/_api/DMS/Public/Item/AddItemBrowse",
json={
"ItemID": item_id,
"VersionID": version_id,
"AttachmentType": 1,
},
)
except Exception as exc:
if has_app_context():
current_app.logger.warning("[fixed-asset-image] failed to record browse item_id=%s err=%s", item_id, exc)
@classmethod
def _request_json(
cls,
method: str,
url_or_path: str,
*,
json: dict[str, Any] | None = None,
timeout: int = 20,
) -> dict[str, Any]:
try:
response = cls._request(method, url_or_path, json=json, timeout=timeout)
response.raise_for_status()
payload = response.json()
except requests.RequestException as exc:
raise ServiceUnavailableError(f"固定资产图片文档库请求失败:{exc}") from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(payload.get("Msg") or "固定资产图片文档库返回异常")
return payload
@classmethod
def _request(
cls,
method: str,
url_or_path: str,
*,
json: dict[str, Any] | None = None,
timeout: int = 20,
stream: bool = False,
) -> requests.Response:
target_url = url_or_path if url_or_path.startswith("http") else cls._build_url(url_or_path)
session = cls._get_logged_session()
response = session.request(
method.upper(),
target_url,
json=json,
timeout=timeout,
stream=stream,
allow_redirects=True,
)
if cls._looks_like_login_response(response):
session = cls._get_logged_session(force_refresh=True)
response = session.request(
method.upper(),
target_url,
json=json,
timeout=timeout,
stream=stream,
allow_redirects=True,
)
return response
@classmethod
def _looks_like_login_response(cls, response: requests.Response) -> bool:
final_url = (response.url or "").lower()
content_type = (response.headers.get("content-type") or "").lower()
return (
response.status_code in (401, 403)
or "/login" in final_url
or ("text/html" in content_type and "login" in final_url)
)
@classmethod
def _get_logged_session(cls, *, force_refresh: bool = False) -> requests.Session:
with _SESSION_LOCK:
current_session = _SESSION_CACHE.get("session")
created_at = float(_SESSION_CACHE.get("created_at") or 0.0)
if (
not force_refresh
and isinstance(current_session, requests.Session)
and time.time() - created_at < _SESSION_TTL_SECONDS
):
return current_session
session = requests.Session()
try:
login_response = session.post(
cls._build_url("/Login/_api/Login"),
json={
"LoginName": cls._get_runtime_setting("FIXED_ASSET_IMAGE_USERNAME").strip(),
"Pwd": cls._get_runtime_setting("FIXED_ASSET_IMAGE_PASSWORD"),
},
headers={
"Content-Type": "application/json;charset=utf-8",
"Accept": "application/json, text/plain, */*",
},
timeout=20,
)
login_response.raise_for_status()
payload = login_response.json()
except requests.RequestException as exc:
raise ServiceUnavailableError(f"固定资产图片文档库登录失败:{exc}") from exc
if int(payload.get("Code") or 0) != 0:
raise ServiceUnavailableError(payload.get("Msg") or "固定资产图片文档库登录失败")
_SESSION_CACHE["session"] = session
_SESSION_CACHE["created_at"] = time.time()
return session