Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172"""Handle <-> DID resolution against the public atproto directory services.
DIDs are the product's identity key (topics, votes); handles are what peopletype and what the UI shows. Resolution is a public read — bsky.social's`com.atproto.identity.resolveHandle` for handle -> DID, and the PLC directoryfor DID -> handle — cached in memory so a feed of many posts resolves eachcreator once. Leaf code, urllib only."""
import jsonimport urllib.errorimport urllib.parseimport urllib.request
BSKY = "https://bsky.social/xrpc"PLC = "https://plc.directory"TIMEOUT = 15
_handle_to_did: dict[str, str] = {}_did_to_handle: dict[str, str] = {}
class IdentityError(RuntimeError): """A failed resolution. The message is safe to print."""
def handle_to_did(handle: str) -> str: """Resolve a handle (e.g. `alice.bsky.social`) to its DID. Cached.""" handle = handle.strip().lower().lstrip("@") if not handle: raise IdentityError("a handle is needed to log in") if handle in _handle_to_did: return _handle_to_did[handle] url = f"{BSKY}/com.atproto.identity.resolveHandle?{urllib.parse.urlencode({'handle': handle})}" try: with urllib.request.urlopen(url, timeout=TIMEOUT) as r: body = json.loads(r.read()) except urllib.error.HTTPError as e: raise IdentityError(f"unknown handle {handle!r} ({e.code})") from None except OSError as e: raise IdentityError(f"cannot reach bsky.social ({e})") from None did = body.get("did") or "" if did: _handle_to_did[handle] = did _did_to_handle[did] = handle return did
def resolve_handle(did: str) -> str: """The handle for a DID, or the DID itself when it cannot be resolved. Cached, and never throws — a feed must not fail because one creator's directory entry is unreachable.""" if not did: return "?" if did in _did_to_handle: return _did_to_handle[did] handle = _fetch_handle(did) _did_to_handle[did] = handle return handle
def _fetch_handle(did: str) -> str: try: with urllib.request.urlopen(f"{PLC}/{urllib.parse.quote(did)}", timeout=TIMEOUT) as r: doc = json.loads(r.read()) except (urllib.error.HTTPError, OSError, json.JSONDecodeError): return did for aka in doc.get("alsoKnownAs") or []: if aka.startswith("at://"): return aka[5:] return did