lookup.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import json
  2. import little_boxes.activitypub as ap
  3. import mf2py
  4. import requests
  5. from little_boxes.errors import NotAnActivityError
  6. from little_boxes.webfinger import get_actor_url
  7. def lookup(url: str) -> ap.BaseActivity:
  8. """Try to find an AP object related to the given URL."""
  9. try:
  10. if url.startswith("@"):
  11. actor_url = get_actor_url(url)
  12. if actor_url:
  13. return ap.fetch_remote_activity(actor_url)
  14. except NotAnActivityError:
  15. pass
  16. except requests.HTTPError:
  17. # Some websites may returns 404, 503 or others when they don't support webfinger, and we're just taking a guess
  18. # when performing the lookup.
  19. pass
  20. backend = ap.get_backend()
  21. resp = requests.get(
  22. url,
  23. timeout=15,
  24. allow_redirects=False,
  25. headers={"User-Agent": backend.user_agent()},
  26. )
  27. resp.raise_for_status()
  28. # If the page is HTML, maybe it contains an alternate link pointing to an AP object
  29. for alternate in mf2py.parse(resp.text).get("alternates", []):
  30. if alternate.get("type") == "application/activity+json":
  31. return ap.fetch_remote_activity(alternate["url"])
  32. try:
  33. # Maybe the page was JSON-LD?
  34. data = resp.json()
  35. return ap.parse_activity(data)
  36. except json.JSONDecodeError:
  37. pass
  38. # Try content negotiation (retry with the AP Accept header)
  39. return ap.fetch_remote_activity(url)