from __future__ import annotations import argparse import json from datetime import datetime, timezone from .config import DEFAULT_MAX_PAGES_PER_CATEGORY, DEPARTMENT, SEED_URLS, SOURCE_NAME from .db import db_cursor from .parser import ParsedDocument, iter_notices, parse_detail def serialize_document(doc: ParsedDocument) -> dict: return { "source_name": SOURCE_NAME, "source_type": "official_website", "category": doc.category, "title": doc.title, "department": DEPARTMENT, "publish_date": doc.publish_date, "source_url": doc.url, "content": doc.content, "content_hash": doc.content_hash, "attachments": json.dumps( [{"name": item.name, "url": item.url, "text": item.text} for item in doc.attachments], ensure_ascii=False, ), } def upsert_document(doc: ParsedDocument) -> bool: record = serialize_document(doc) with db_cursor() as cur: cur.execute("select content_hash from campus_documents where source_url = %s", (doc.url,)) existing = cur.fetchone() changed = existing is None or existing["content_hash"] != doc.content_hash cur.execute( """ insert into campus_documents ( source_name, source_type, category, title, department, publish_date, source_url, content, content_hash, attachments, last_checked_at ) values ( %(source_name)s, %(source_type)s, %(category)s, %(title)s, %(department)s, %(publish_date)s, %(source_url)s, %(content)s, %(content_hash)s, %(attachments)s::jsonb, now() ) on conflict (source_url) do update set category = excluded.category, title = excluded.title, department = excluded.department, publish_date = excluded.publish_date, content = excluded.content, attachments = excluded.attachments, content_hash = excluded.content_hash, last_checked_at = now(), updated_at = case when campus_documents.content_hash is distinct from excluded.content_hash then now() else campus_documents.updated_at end """, record, ) return changed def create_sync_run() -> int: with db_cursor() as cur: cur.execute("insert into sync_runs(status) values ('running') returning id") return int(cur.fetchone()["id"]) def finish_sync_run(run_id: int, status: str, scanned: int, upserted: int, error: str | None = None) -> None: with db_cursor() as cur: cur.execute( """ update sync_runs set finished_at = now(), status = %s, scanned_count = %s, upserted_count = %s, error = %s where id = %s """, (status, scanned, upserted, error, run_id), ) def run_sync(max_pages_per_category: int = DEFAULT_MAX_PAGES_PER_CATEGORY, limit: int | None = None) -> dict: run_id = create_sync_run() scanned = 0 upserted = 0 errors: list[str] = [] try: seen_urls: set[str] = set() for category, seed_url in SEED_URLS: for notice in iter_notices(category, seed_url, max_pages_per_category): if notice.url in seen_urls: continue seen_urls.add(notice.url) if limit is not None and scanned >= limit: break scanned += 1 try: document = parse_detail(notice) if upsert_document(document): upserted += 1 except Exception as exc: errors.append(f"{notice.url}: {exc}") if limit is not None and scanned >= limit: break status = "partial_success" if errors else "success" finish_sync_run(run_id, status, scanned, upserted, "\n".join(errors) if errors else None) return { "run_id": run_id, "status": status, "scanned_count": scanned, "upserted_count": upserted, "errors": errors, "finished_at": datetime.now(timezone.utc).isoformat(), } except Exception as exc: finish_sync_run(run_id, "failed", scanned, upserted, str(exc)) raise def main() -> None: parser = argparse.ArgumentParser(description="Sync MYCC academic affairs public notices.") parser.add_argument("--max-pages", type=int, default=DEFAULT_MAX_PAGES_PER_CATEGORY) parser.add_argument("--limit", type=int, default=None) args = parser.parse_args() print(json.dumps(run_sync(max_pages_per_category=args.max_pages, limit=args.limit), ensure_ascii=False, indent=2)) if __name__ == "__main__": main()