diff --git a/server/main.py b/server/main.py index e7a6926..922cf7c 100644 --- a/server/main.py +++ b/server/main.py @@ -771,7 +771,7 @@ app = FastAPI(title="WorkLog 活动记录", version="2.0.0", lifespan=lifespan) center.install(app, get_db, current_user, lambda: _db_path.parent / 'uploads', visible_clause) center_duty.install(app, get_db, current_user) center_export.install(app, get_db, current_user, visible_clause, lambda: _db_path.parent / 'uploads') -recruit.install(app, get_db, current_user) +recruit.install(app, get_db, current_user, _db_path.parent / 'recruit-images') def timetable_collectors(): values = os.getenv('WORKLOG_TIMETABLE_COLLECTORS') diff --git a/server/recruit.py b/server/recruit.py index ccb3f93..4f599d9 100644 --- a/server/recruit.py +++ b/server/recruit.py @@ -2,10 +2,13 @@ from __future__ import annotations import asyncio +import hashlib import io +import logging import re from datetime import datetime from html.parser import HTMLParser +from pathlib import Path from typing import Literal from urllib.parse import urljoin @@ -23,6 +26,8 @@ from .models import recruit_announcements SOURCE = "https://school.gxjy.sdei.edu.cn" LIST_ENDPOINT = SOURCE + "/sdmu/front/indexZpggList" DETAIL_ENDPOINT = SOURCE + "/sdmu/jiuye/zhaopingg/detail" +logger = logging.getLogger(__name__) +MAX_IMAGE_EDGE = 1800 class HTMLTextParser(HTMLParser): @@ -129,11 +134,19 @@ def is_image_data(body: bytes) -> bool: def normalized_image(body: bytes) -> bytes | None: try: with Image.open(io.BytesIO(body)) as image: - if image.format in {"JPEG", "PNG", "GIF", "BMP", "TIFF"}: - return body image.seek(0) + image.load() + if max(image.size) > MAX_IMAGE_EDGE: + image.thumbnail((MAX_IMAGE_EDGE, MAX_IMAGE_EDGE), Image.Resampling.LANCZOS) + if image.mode in {"RGBA", "LA", "P"}: + background = Image.new("RGB", image.size, "white") + rgba = image.convert("RGBA") + background.paste(rgba, mask=rgba.getchannel("A")) + image = background + else: + image = image.convert("RGB") output = io.BytesIO() - image.convert("RGB").save(output, format="PNG") + image.save(output, format="JPEG", quality=86, optimize=True) return output.getvalue() except Exception: return None @@ -144,14 +157,7 @@ def add_docx_picture(document, body: bytes) -> bool: document.add_picture(io.BytesIO(body), width=Cm(15)) return True except Exception: - try: - with Image.open(io.BytesIO(body)) as image: - fallback = io.BytesIO() - image.convert("RGB").save(fallback, format="PNG") - document.add_picture(io.BytesIO(fallback.getvalue()), width=Cm(15)) - return True - except Exception: - return False + return False async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None: @@ -162,20 +168,43 @@ async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None: ] for attempt, request_headers in enumerate(headers, 1): try: - response = await client.get(url, headers=request_headers) + response = await asyncio.wait_for(client.get(url, headers=request_headers), timeout=12) response.raise_for_status() body = response.content if is_image_data(body): normalized = normalized_image(body) if normalized: return normalized - except httpx.HTTPError: + except (httpx.HTTPError, asyncio.TimeoutError): pass if attempt < len(headers): await asyncio.sleep(0.4 * attempt) return None +def cache_file(cache_dir: Path | None, url: str) -> Path | None: + if cache_dir is None: + return None + return cache_dir / (hashlib.sha256(url.encode("utf-8")).hexdigest() + ".jpg") + + +async def get_image(client: httpx.AsyncClient, url: str, cache_dir: Path | None) -> bytes | None: + path = cache_file(cache_dir, url) + if path and path.exists(): + try: + return path.read_bytes() + except OSError: + pass + body = await fetch_image(client, url) + if body and path: + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(body) + except OSError: + logger.warning("招聘公告图片缓存写入失败:%s", path) + return body + + def public_row(row) -> dict: data = dict(row) data["detail_url"] = data["wailian"] if data["iswailian"] and data["wailian"] else f"{DETAIL_ENDPOINT}/{data['gonggao_id']}" @@ -237,7 +266,7 @@ async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: return {"fetched": len(rows), "added": added, "updated": updated} -async def docx_bytes(rows, client: httpx.AsyncClient | None = None) -> bytes: +async def docx_bytes(rows, client: httpx.AsyncClient | None = None, cache_dir: Path | None = None) -> bytes: owns_client = client is None if owns_client: client = httpx.AsyncClient(timeout=20, follow_redirects=True) @@ -251,7 +280,7 @@ async def docx_bytes(rows, client: httpx.AsyncClient | None = None) -> bytes: async def limited(url): async with semaphore: - return await fetch_image(client, url) + return await get_image(client, url, cache_dir) results = await asyncio.gather(*(limited(url) for url in sources)) finally: @@ -302,11 +331,14 @@ def markdown_bytes(rows) -> bytes: return ("\n\n---\n\n".join(sections) + "\n").encode("utf-8") -def install(app, get_db, current_user): +def install(app, get_db, current_user, cache_dir: Path | None = None): @app.post("/api/recruit/sync") - async def sync(viewer=Depends(current_user)): - async for db in get_db(): + async def sync(viewer=Depends(current_user), db=Depends(get_db)): + try: return await sync_all(db) + except Exception as exc: + logger.exception("招聘公告同步失败") + raise HTTPException(502, "同步失败:暂时无法连接就业平台,请稍后重试") from exc @app.get("/api/recruit/announcements") async def announcements(q: str = Query("", max_length=100), db=Depends(get_db), viewer=Depends(current_user)): @@ -355,7 +387,12 @@ def install(app, get_db, current_user): raise HTTPException(404, "没有匹配的公告") stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S") if format == "docx": - body, extension, media_type = await docx_bytes(rows), "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + try: + body = await docx_bytes(rows, cache_dir=cache_dir) + except Exception as exc: + logger.exception("招聘公告 Word 导出失败") + raise HTTPException(502, "Word 导出失败,请稍后重试;Markdown 导出仍可正常使用") from exc + extension, media_type = "docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document" else: body, extension, media_type = markdown_bytes(rows), "md", "text/markdown; charset=utf-8" scope = "recruit" if len(rows) > 1 else f"recruit-{rows[0]['gonggao_id']}"