"""招聘公告同步、浏览和 Word / Markdown 导出。""" 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 import httpx from docx import Document from docx.shared import Cm, Pt from fastapi import Depends, HTTPException, Query from fastapi.responses import Response from PIL import Image from sqlalchemy import func, insert, select from .duty import BEIJING 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): blocks = {"p", "div", "section", "br", "tr", "li", "table"} def __init__(self): super().__init__(convert_charrefs=True) self.parts = [] self.current = [] def handle_starttag(self, tag, attrs): if tag in self.blocks: text = "".join(self.current).strip() if text: self.parts.append(text) self.current = [] def handle_endtag(self, tag): if tag in self.blocks: text = "".join(self.current).strip() if text: self.parts.append(text) self.current = [] def handle_data(self, data): self.current.append(data) def text(self): text = "".join(self.current).strip() if text: self.parts.append(text) return "\n".join(part for part in self.parts if part) def html_to_text(content: str) -> str: parser = HTMLTextParser() parser.feed(content or "") parser.close() return parser.text() def image_url(src: str) -> str: src = (src or "").strip() if not src or src.startswith(("data:", "file:")): return "" if src.startswith("//"): return "https:" + src return urljoin(SOURCE + "/", src) def content_blocks(content: str) -> list[tuple[str, str]]: """把公告 HTML 拆成按原顺序排列的文字段落和图片。""" blocks: list[tuple[str, str]] = [] buffer: list[str] = [] skip = 0 class Parser(HTMLParser): def flush(self): text = re.sub(r"[ \t\r\f\v]+", " ", "".join(buffer)).strip() if text: blocks.append(("text", text)) buffer.clear() def handle_starttag(self, tag, attrs): nonlocal skip if tag in {"script", "style"}: skip += 1 if tag == "img": self.flush() src = dict(attrs).get("src", "") source = image_url(src) if source: blocks.append(("image", source)) elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}: self.flush() def handle_endtag(self, tag): nonlocal skip if tag in {"script", "style"} and skip: skip -= 1 elif tag in {"p", "div", "section", "br", "tr", "li", "table", "h1", "h2", "h3", "h4"}: self.flush() def handle_data(self, data): if not skip: buffer.append(data) parser = Parser(convert_charrefs=True) parser.feed(content or "") parser.close() parser.flush() return blocks def is_image_data(body: bytes) -> bool: return ( body.startswith(b"\xff\xd8") or body.startswith(b"\x89PNG\r\n\x1a\n") or body.startswith((b"GIF87a", b"GIF89a", b"BM", b"II*\x00", b"MM\x00*")) or (body[:4] == b"RIFF" and body[8:12] == b"WEBP") ) def normalized_image(body: bytes) -> bytes | None: try: with Image.open(io.BytesIO(body)) as image: 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.save(output, format="JPEG", quality=86, optimize=True) return output.getvalue() except Exception: return None def add_docx_picture(document, body: bytes) -> bool: try: document.add_picture(io.BytesIO(body), width=Cm(15)) return True except Exception: return False async def fetch_image(client: httpx.AsyncClient, url: str) -> bytes | None: headers = [ {"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}, {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0 Safari/537.36"}, {"Referer": SOURCE + "/", "User-Agent": "Mozilla/5.0 WorkLog/2.0"}, ] for attempt, request_headers in enumerate(headers, 1): try: 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, 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']}" return data async def fetch_page(client: httpx.AsyncClient, page: int, page_size: int = 50): last_error: Exception | None = None for attempt in range(2): try: response = await asyncio.wait_for( client.get(LIST_ENDPOINT, params={"pageNum": page, "pageSize": page_size, "keyword": "", "timeRange": ""}), timeout=15, ) response.raise_for_status() payload = response.json() if payload.get("code") != 0: raise RuntimeError(payload.get("msg") or "招聘公告接口返回异常") return payload except (httpx.HTTPError, asyncio.TimeoutError, RuntimeError) as exc: last_error = exc if attempt == 0: await asyncio.sleep(0.4) raise RuntimeError("就业平台暂时无法访问") from last_error async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict: owns_client = client is None if owns_client: client = httpx.AsyncClient(timeout=20, trust_env=False) added = updated = 0 try: first = await fetch_page(client, 1) pages = int(first.get("extra", {}).get("pages") or 1) rows = list(first.get("rows") or []) for page in range(2, pages + 1): await asyncio.sleep(0.15) rows.extend((await fetch_page(client, page)).get("rows") or []) finally: if owns_client: await client.aclose() now = int(datetime.now(BEIJING).timestamp() * 1000) for raw in rows: try: gonggao_id = int(raw["gonggaoId"]) except (KeyError, TypeError, ValueError): continue values = { "gonggao_id": gonggao_id, "title": str(raw.get("gonggaoTitle") or "未命名公告"), "companyname": str(raw.get("companyname") or ""), "content_html": str(raw.get("gonggaoContent") or ""), "create_time": str(raw.get("createTime") or ""), "check_time": str(raw.get("checkTime") or ""), "valid_time": str(raw.get("validTime") or ""), "info_from": str(raw.get("infoFrom") or ""), "iswailian": int(raw.get("iswailian") or 0), "wailian": str(raw.get("wailian") or ""), "url": str(raw.get("url") or ""), "synced_at": now, } existing = (await db.execute(select(recruit_announcements.c.gonggao_id).where(recruit_announcements.c.gonggao_id == gonggao_id))).scalar() if existing is None: await db.execute(insert(recruit_announcements).values(**values)) added += 1 else: await db.execute(recruit_announcements.update().where(recruit_announcements.c.gonggao_id == gonggao_id).values(**values)) updated += 1 await db.commit() return {"fetched": len(rows), "added": added, "updated": updated} 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, trust_env=False) sources = [] for row in rows: for kind, value in content_blocks(row["content_html"]): if kind == "image" and value not in sources: sources.append(value) try: semaphore = asyncio.Semaphore(6) async def limited(url): async with semaphore: return await get_image(client, url, cache_dir) results = await asyncio.gather(*(limited(url) for url in sources)) finally: if owns_client: await client.aclose() images = dict(zip(sources, results)) document = Document() style = document.styles["Normal"] style.font.name = "Microsoft YaHei" style.font.size = Pt(11) for index, row in enumerate(rows, 1): document.add_heading(row["title"], level=1) meta = " · ".join(value for value in (row["companyname"], row["check_time"][:10], f"截止:{row['valid_time'][:10]}" if row["valid_time"] else "") if value) if meta: document.add_paragraph(meta) for kind, value in content_blocks(row["content_html"]): if kind == "text": document.add_paragraph(value) else: body = images.get(value) if body: if not add_docx_picture(document, body): document.add_paragraph("[公告图片格式不受支持]") else: document.add_paragraph("[公告图片未能下载]") if index < len(rows): document.add_page_break() output = io.BytesIO() document.save(output) return output.getvalue() def markdown_bytes(rows) -> bytes: sections = [] for row in rows: lines = [f"# {row['title']}"] meta = [value for value in (row["companyname"], row["check_time"], row["valid_time"]) if value] if meta: lines.append(f"- {' / '.join(meta)}") for kind, value in content_blocks(row["content_html"]): if kind == "text": lines.extend([value, ""]) else: lines.extend([f"![公告图片]({value})", ""]) link = row["wailian"] if row["iswailian"] and row["wailian"] else f"{DETAIL_ENDPOINT}/{row['gonggao_id']}" lines.append(f"原文链接:{link}") sections.append("\n".join(lines)) return ("\n\n---\n\n".join(sections) + "\n").encode("utf-8") def install(app, get_db, current_user, cache_dir: Path | None = None): @app.post("/api/recruit/sync") 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)): statement = select(recruit_announcements) if q.strip(): keyword = f"%{q.strip()}%" statement = statement.where(recruit_announcements.c.title.like(keyword) | recruit_announcements.c.companyname.like(keyword)) total = (await db.execute(select(func.count()).select_from(statement.subquery()))).scalar() statement = statement.order_by(recruit_announcements.c.check_time.desc(), recruit_announcements.c.gonggao_id.desc()).limit(500) rows = [public_row(row) for row in (await db.execute(statement)).mappings()] return {"items": rows, "total": total} @app.get("/api/recruit/announcements/{gonggao_id}") async def announcement(gonggao_id: int, db=Depends(get_db), viewer=Depends(current_user)): row = (await db.execute(select(recruit_announcements).where(recruit_announcements.c.gonggao_id == gonggao_id))).mappings().first() if row is None: raise HTTPException(404, "公告不存在,请先同步") return public_row(row) @app.get("/api/recruit/export") async def export( ids: str = Query("", max_length=5000), all_items: bool = Query(False, alias="all"), format: Literal["docx", "markdown"] = "docx", q: str = Query("", max_length=100), db=Depends(get_db), viewer=Depends(current_user), ): selected = [] if ids.strip(): try: selected = [int(value.strip()) for value in ids.split(",") if value.strip()] except ValueError: raise HTTPException(422, "公告编号格式不正确") if not selected and not all_items: raise HTTPException(422, "请选择要导出的公告,或选择全部导出") statement = select(recruit_announcements) if selected: statement = statement.where(recruit_announcements.c.gonggao_id.in_(selected)) elif q.strip(): keyword = f"%{q.strip()}%" statement = statement.where(recruit_announcements.c.title.like(keyword) | recruit_announcements.c.companyname.like(keyword)) statement = statement.order_by(recruit_announcements.c.check_time.desc(), recruit_announcements.c.gonggao_id.desc()) rows = [dict(row) for row in (await db.execute(statement)).mappings()] if not rows: raise HTTPException(404, "没有匹配的公告") stamp = datetime.now(BEIJING).strftime("%Y%m%d-%H%M%S") if format == "docx": 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']}" filename = f"{scope}-{stamp}.{extension}" return Response(body, media_type=media_type, headers={ "Content-Disposition": f'attachment; filename="{filename}"', "X-Recruit-Export-Count": str(len(rows)), })