weixin.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. """Weixin formal acquisition adapter."""
  2. from __future__ import annotations
  3. import hashlib
  4. from typing import Any
  5. from acquisition.platforms.base import PlatformCandidate, PlatformItem
  6. from acquisition.search import fetch_weixin_detail, search_weixin
  7. from core.config import Settings
  8. def _hash(value: str, n: int = 16) -> str:
  9. return hashlib.md5(value.encode("utf-8")).hexdigest()[:n]
  10. class WeixinAdapter:
  11. platform = "weixin"
  12. def search(
  13. self,
  14. query: str,
  15. *,
  16. settings: Settings,
  17. limit: int,
  18. rate_limiter: Any,
  19. ) -> list[PlatformCandidate]:
  20. rows = search_weixin(
  21. query,
  22. limit=limit,
  23. settings=settings,
  24. rate_limiter=rate_limiter,
  25. )
  26. return [
  27. PlatformCandidate(
  28. rank=i,
  29. platform=self.platform,
  30. source_id=_hash(row.get("url") or ""),
  31. url=row.get("url") or "",
  32. title=row.get("title") or "",
  33. author=row.get("nick_name") or "",
  34. cover_url=row.get("cover_url") or "",
  35. raw=row,
  36. )
  37. for i, row in enumerate(rows, start=1)
  38. ]
  39. def fetch_detail(
  40. self,
  41. candidate: PlatformCandidate,
  42. *,
  43. settings: Settings,
  44. rate_limiter: Any,
  45. ) -> PlatformItem:
  46. body_text, images = fetch_weixin_detail(
  47. candidate.url,
  48. settings=settings,
  49. rate_limiter=rate_limiter,
  50. )
  51. return PlatformItem(
  52. platform=self.platform,
  53. source_id=candidate.source_id or _hash(candidate.url),
  54. url=candidate.url,
  55. content_type="图文",
  56. title=candidate.title,
  57. author=candidate.author,
  58. body_text=body_text,
  59. image_urls=images or [candidate.cover_url],
  60. raw=candidate.raw,
  61. )