新增招聘公告同步与Word和Markdown导出
This commit is contained in:
@@ -0,0 +1,221 @@
|
||||
"""招聘公告同步、浏览和 Word / Markdown 导出。"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import io
|
||||
from datetime import datetime
|
||||
from html.parser import HTMLParser
|
||||
from typing import Literal
|
||||
|
||||
import httpx
|
||||
from docx import Document
|
||||
from docx.shared import Pt
|
||||
from fastapi import Depends, HTTPException, Query
|
||||
from fastapi.responses import Response
|
||||
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"
|
||||
|
||||
|
||||
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 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):
|
||||
response = await client.get(LIST_ENDPOINT, params={"pageNum": page, "pageSize": page_size, "keyword": "", "timeRange": ""})
|
||||
response.raise_for_status()
|
||||
payload = response.json()
|
||||
if payload.get("code") != 0:
|
||||
raise RuntimeError(payload.get("msg") or "招聘公告接口返回异常")
|
||||
return payload
|
||||
|
||||
|
||||
async def sync_all(db, client: httpx.AsyncClient | None = None) -> dict:
|
||||
owns_client = client is None
|
||||
if owns_client:
|
||||
client = httpx.AsyncClient(timeout=20)
|
||||
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}
|
||||
|
||||
|
||||
def docx_bytes(rows) -> bytes:
|
||||
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 line in html_to_text(row["content_html"]).splitlines():
|
||||
document.add_paragraph(line)
|
||||
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)}")
|
||||
body = html_to_text(row["content_html"])
|
||||
if body:
|
||||
lines.extend([body, ""])
|
||||
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):
|
||||
@app.post("/api/recruit/sync")
|
||||
async def sync(viewer=Depends(current_user)):
|
||||
async for db in get_db():
|
||||
return await sync_all(db)
|
||||
|
||||
@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":
|
||||
body, extension, media_type = docx_bytes(rows), "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)),
|
||||
})
|
||||
Reference in New Issue
Block a user