diff --git "a/oracle_context_cache_v3/MarshalX__atproto.json" "b/oracle_context_cache_v3/MarshalX__atproto.json" new file mode 100644--- /dev/null +++ "b/oracle_context_cache_v3/MarshalX__atproto.json" @@ -0,0 +1 @@ +{"repo": "MarshalX/atproto", "n_pairs": 200, "version": "v3_compressed", "max_tokens": 6000, "contexts": {"tests/test_atproto_client/client/test_client.py::59": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client"], "enclosing_function": "test_client_clone", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26227, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_chars_compressed": 26227, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::70": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_algs_p256.py::7": {"resolved_imports": ["packages/atproto_crypto/algs/p256.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["InvalidCompressedPubkeyError", "P256", "pytest"], "enclosing_function": "test_decompress_pubkey_invalid_compression", "extracted_code": "# Source: packages/atproto_crypto/algs/p256.py\nclass P256(AlgBase):\n \"\"\"P256 algorithm AKA ES256 AKA secp256r1.\"\"\"\n\n NAME = P256_JWT_ALG\n\n def __init__(self) -> None:\n super().__init__(SECP256R1(), P256_CURVE_ORDER)\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass InvalidCompressedPubkeyError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 338, "extracted_code_full": "# Source: packages/atproto_crypto/algs/p256.py\nclass P256(AlgBase):\n \"\"\"P256 algorithm AKA ES256 AKA secp256r1.\"\"\"\n\n NAME = P256_JWT_ALG\n\n def __init__(self) -> None:\n super().__init__(SECP256R1(), P256_CURVE_ORDER)\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass InvalidCompressedPubkeyError(AtProtocolError): ...", "n_chars_compressed": 338, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::122": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_iter", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::49": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["ModelError", "dataclass", "get_or_create", "pytest"], "enclosing_function": "test_get_or_create_works_with_dataclasses", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::39": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_make", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::42": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidNotFoundError", "DidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_unknown_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1269, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...", "n_chars_compressed": 1269, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::20": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver", "UnsupportedDidWebPathError", "pytest"], "enclosing_function": "test_did_resolver_with_invalid_did_web", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass UnsupportedDidWebPathError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1279, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass UnsupportedDidWebPathError(AtProtocolError): ...", "n_chars_compressed": 1279, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::46": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "CID", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_from_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 4324, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 4324, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::77": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_type_bytes", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::68": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::24": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["parse_jwt"], "enclosing_function": "test_parse_jwt", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1605, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_chars_compressed": 1605, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::15": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_old_format_migration", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::37": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::62": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_to_ipld", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2964, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2964, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_extended_like_record.py::17": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_extended_like_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_atproto_data.py::13": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["DidResolver"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_changed_lexicon_compatability.py::50": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/exceptions.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_added_new_fields_as_optional", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::16": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::193": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["BaseModel", "ModelError", "get_or_create", "pytest", "string_formats"], "enclosing_function": "test_at_identifier_type", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_is_record_type.py::23": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "is_record_type", "models"], "enclosing_function": "test_is_record_type", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::30": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_equal", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::13": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["load_json", "pytest"], "enclosing_function": "test_load_json", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 284, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_chars_compressed": 284, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::116": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink"], "enclosing_function": "test_blob_ref_to_json_representation", "extracted_code": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2275, "extracted_code_full": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2275, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_extended_post_record.py::17": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_extended_post_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver_cache.py::25": {"resolved_imports": ["packages/atproto_identity/cache/in_memory_cache.py", "packages/atproto_identity/did/resolver.py"], "used_names": ["AsyncDidInMemoryCache", "AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_cache_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass AsyncDidInMemoryCache(AsyncDidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._in_memory_cache = DidInMemoryCache(*args, **kwargs)\n\n async def set(self, did: str, document: DidDocument) -> None:\n self._in_memory_cache.set(did, document)\n\n async def refresh(self, did: str, get_doc_callback: 'AsyncGetDocCallback') -> None:\n doc = await get_doc_callback()\n if doc:\n await self.set(did, doc)\n\n async def delete(self, did: str) -> None:\n self._in_memory_cache.delete(did)\n\n async def clear(self) -> None:\n self._in_memory_cache.clear()\n\n async def get(self, did: str) -> t.Optional[CachedDidResult]:\n return self._in_memory_cache.get(did)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2100, "extracted_code_full": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass AsyncDidInMemoryCache(AsyncDidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._in_memory_cache = DidInMemoryCache(*args, **kwargs)\n\n async def set(self, did: str, document: DidDocument) -> None:\n self._in_memory_cache.set(did, document)\n\n async def refresh(self, did: str, get_doc_callback: 'AsyncGetDocCallback') -> None:\n doc = await get_doc_callback()\n if doc:\n await self.set(did, doc)\n\n async def delete(self, did: str) -> None:\n self._in_memory_cache.delete(did)\n\n async def clear(self) -> None:\n self._in_memory_cache.clear()\n\n async def get(self, did: str) -> t.Optional[CachedDidResult]:\n return self._in_memory_cache.get(did)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 2100, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_unknown_union_model.py::25": {"resolved_imports": ["packages/atproto_client/models/base.py"], "used_names": ["UnknownUnionModel", "ValidationError", "pytest"], "enclosing_function": "test_unknown_union_model", "extracted_code": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 124, "extracted_code_full": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_chars_compressed": 124, "compression_ratio": 1.0}, "tests/test_atproto_core/test_nsid.py::10": {"resolved_imports": ["packages/atproto_core/nsid/nsid.py"], "used_names": ["NSID"], "enclosing_function": "test_nsid_from_str", "extracted_code": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1182, "extracted_code_full": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 1182, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_thread_view_post_with_embed_media.py::18": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_thread_view_post_with_embed_media_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_core/test_nsid.py::16": {"resolved_imports": ["packages/atproto_core/nsid/nsid.py"], "used_names": ["get_test_cases", "pytest", "validate_nsid"], "enclosing_function": "test_nsid_validation_with_valid", "extracted_code": "# Source: packages/atproto_core/nsid/nsid.py\ndef validate_nsid(nsid: str, *, soft_fail: bool = False) -> bool:\n \"\"\"Validate NSID.\n\n Args:\n nsid: NSID to validate.\n soft_fail: enable to return False on fall instead of exception\n\n Returns:\n :obj:`bool`: Validation result.\n\n Raises:\n :class:`atproto.exceptions.InvalidNsidError`: Invalid NSID exception.\n \"\"\"\n try:\n return _validate_nsid(nsid)\n except InvalidNsidError as e:\n if soft_fail:\n return False\n\n raise e", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 542, "extracted_code_full": "# Source: packages/atproto_core/nsid/nsid.py\ndef validate_nsid(nsid: str, *, soft_fail: bool = False) -> bool:\n \"\"\"Validate NSID.\n\n Args:\n nsid: NSID to validate.\n soft_fail: enable to return False on fall instead of exception\n\n Returns:\n :obj:`bool`: Validation result.\n\n Raises:\n :class:`atproto.exceptions.InvalidNsidError`: Invalid NSID exception.\n \"\"\"\n try:\n return _validate_nsid(nsid)\n except InvalidNsidError as e:\n if soft_fail:\n return False\n\n raise e", "n_chars_compressed": 542, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::66": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_to_ipld", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2964, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2964, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_extended_post_record.py::22": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_extended_post_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::41": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["TokenExpiredSignatureError", "get_jwt_payload", "pytest", "validate_jwt_payload"], "enclosing_function": "test_validate_jwt_payload_expired", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)\n\ndef validate_jwt_payload(payload: JwtPayload, leeway: int = 0) -> None:\n \"\"\"Validate the given JWT payload.\n\n Args:\n payload: The JWT payload to validate.\n leeway: The leeway in seconds to accept when verifying time claims (exp, iat).\n\n Returns:\n :obj:`None`: The payload is valid.\n\n Raises:\n TokenDecodeError: If the given JWT is invalid.\n TokenExpiredSignatureError: If the given JWT is expired.\n TokenImmatureSignatureError: If the given JWT is immature.\n TokenInvalidIssuedAtError: If the given JWT has invalid issued at.\n \"\"\"\n now = datetime.now(tz=timezone.utc).timestamp()\n\n if payload.exp is not None:\n _validate_exp(payload.exp, now, leeway)\n if payload.iat is not None:\n _validate_iat(payload.iat, now, leeway)\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenExpiredSignatureError(InvalidTokenError):\n pass", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1263, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)\n\ndef validate_jwt_payload(payload: JwtPayload, leeway: int = 0) -> None:\n \"\"\"Validate the given JWT payload.\n\n Args:\n payload: The JWT payload to validate.\n leeway: The leeway in seconds to accept when verifying time claims (exp, iat).\n\n Returns:\n :obj:`None`: The payload is valid.\n\n Raises:\n TokenDecodeError: If the given JWT is invalid.\n TokenExpiredSignatureError: If the given JWT is expired.\n TokenImmatureSignatureError: If the given JWT is immature.\n TokenInvalidIssuedAtError: If the given JWT has invalid issued at.\n \"\"\"\n now = datetime.now(tz=timezone.utc).timestamp()\n\n if payload.exp is not None:\n _validate_exp(payload.exp, now, leeway)\n if payload.iat is not None:\n _validate_iat(payload.iat, now, leeway)\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenExpiredSignatureError(InvalidTokenError):\n pass", "n_chars_compressed": 1263, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::13": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_old_format_migration", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_base.py::7": {"resolved_imports": ["packages/atproto_client/client/base.py"], "used_names": ["_BASE_API_URL", "_handle_base_url"], "enclosing_function": "test_handle_base_url", "extracted_code": "# Source: packages/atproto_client/client/base.py\n_BASE_API_URL = 'https://bsky.social/xrpc'\n\ndef _handle_base_url(base_url: t.Optional[str] = None) -> str:\n if base_url is None:\n return _BASE_API_URL\n\n if not base_url.endswith('/xrpc'):\n return f'{base_url.rstrip(\"/\")}/xrpc'\n\n return base_url", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 316, "extracted_code_full": "# Source: packages/atproto_client/client/base.py\n_BASE_API_URL = 'https://bsky.social/xrpc'\n\ndef _handle_base_url(base_url: t.Optional[str] = None) -> str:\n if base_url is None:\n return _BASE_API_URL\n\n if not base_url.endswith('/xrpc'):\n return f'{base_url.rstrip(\"/\")}/xrpc'\n\n return base_url", "n_chars_compressed": 316, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver_cache.py::22": {"resolved_imports": ["packages/atproto_identity/cache/in_memory_cache.py", "packages/atproto_identity/did/resolver.py"], "used_names": ["AsyncDidInMemoryCache", "AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_cache_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass AsyncDidInMemoryCache(AsyncDidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._in_memory_cache = DidInMemoryCache(*args, **kwargs)\n\n async def set(self, did: str, document: DidDocument) -> None:\n self._in_memory_cache.set(did, document)\n\n async def refresh(self, did: str, get_doc_callback: 'AsyncGetDocCallback') -> None:\n doc = await get_doc_callback()\n if doc:\n await self.set(did, doc)\n\n async def delete(self, did: str) -> None:\n self._in_memory_cache.delete(did)\n\n async def clear(self) -> None:\n self._in_memory_cache.clear()\n\n async def get(self, did: str) -> t.Optional[CachedDidResult]:\n return self._in_memory_cache.get(did)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2100, "extracted_code_full": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass AsyncDidInMemoryCache(AsyncDidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._in_memory_cache = DidInMemoryCache(*args, **kwargs)\n\n async def set(self, did: str, document: DidDocument) -> None:\n self._in_memory_cache.set(did, document)\n\n async def refresh(self, did: str, get_doc_callback: 'AsyncGetDocCallback') -> None:\n doc = await get_doc_callback()\n if doc:\n await self.set(did, doc)\n\n async def delete(self, did: str) -> None:\n self._in_memory_cache.delete(did)\n\n async def clear(self) -> None:\n self._in_memory_cache.clear()\n\n async def get(self, did: str) -> t.Optional[CachedDidResult]:\n return self._in_memory_cache.get(did)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 2100, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::28": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "DidWebResolverError", "pytest"], "enclosing_function": "test_did_resolver_with_unknown_did_web", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidWebResolverError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1344, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidWebResolverError(AtProtocolError): ...", "n_chars_compressed": 1344, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::69": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::125": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink"], "enclosing_function": "test_blob_ref_to_json_representation", "extracted_code": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2275, "extracted_code_full": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2275, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::40": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::53": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["ModelError", "dataclass", "get_or_create", "pytest"], "enclosing_function": "test_get_or_create_works_with_dataclasses", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_handle_resolver.py::19": {"resolved_imports": ["packages/atproto_identity/exceptions.py", "packages/atproto_identity/handle/resolver.py"], "used_names": ["DidNotFoundError", "HandleResolver", "pytest"], "enclosing_function": "test_handle_resolver_with_invalid_handle_url", "extracted_code": "# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...\n\n\n# Source: packages/atproto_identity/handle/resolver.py\nclass HandleResolver(_HandleResolverBase):\n \"\"\"Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.resolver\n self._http_client = httpx.Client()\n\n def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = self._dns_resolver.resolve(self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout)\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2762, "extracted_code_full": "# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...\n\n\n# Source: packages/atproto_identity/handle/resolver.py\nclass HandleResolver(_HandleResolverBase):\n \"\"\"Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.resolver\n self._http_client = httpx.Client()\n\n def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = self._dns_resolver.resolve(self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout)\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_chars_compressed": 2762, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::58": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client"], "enclosing_function": "test_client_clone", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26227, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_chars_compressed": 26227, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::35": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["get_jwt_payload"], "enclosing_function": "test_get_jwt_payload", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 342, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_chars_compressed": 342, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::36": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["get_jwt_payload"], "enclosing_function": "test_get_jwt_payload", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 342, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_chars_compressed": 342, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::37": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["Multikey", "P256_JWT_ALG", "format_multikey"], "enclosing_function": "test_multikey_p256_compress_decompress", "extracted_code": "# Source: packages/atproto_crypto/consts.py\nP256_JWT_ALG = 'ES256'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 1395, "extracted_code_full": "# Source: packages/atproto_crypto/consts.py\nP256_JWT_ALG = 'ES256'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_chars_compressed": 1395, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::16": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver"], "enclosing_function": "test_did_resolver_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::167": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["BaseModel", "ModelError", "get_or_create", "pytest", "string_formats"], "enclosing_function": "test_get_or_create_with_strict_validation", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_get_follows.py::36": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_get_follows_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_thread_view_post_with_embed_media.py::19": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_thread_view_post_with_embed_media_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::49": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["Multikey", "SECP256K1_JWT_ALG", "format_multikey"], "enclosing_function": "test_multikey_secp256k1_compress_decompress", "extracted_code": "# Source: packages/atproto_crypto/consts.py\nSECP256K1_JWT_ALG = 'ES256K'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 1401, "extracted_code_full": "# Source: packages/atproto_crypto/consts.py\nSECP256K1_JWT_ALG = 'ES256K'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_chars_compressed": 1401, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_custom_record.py::19": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_custom_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::24": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["UnsupportedKeyTypeError", "get_multikey_alg", "pytest"], "enclosing_function": "test_get_multikey_alg_unsupported_key_type", "extracted_code": "# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass UnsupportedKeyTypeError(DidKeyError): ...", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 721, "extracted_code_full": "# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass UnsupportedKeyTypeError(DidKeyError): ...", "n_chars_compressed": 721, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_get_follows.py::39": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_get_follows_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::41": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_resolve_handle.py::30": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_resolve_handle_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::30": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["is_json", "load_json", "pytest"], "enclosing_function": "test_is_json", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef is_json(json_data: t.Union[str, bytes]) -> bool:\n return load_json(json_data, strict=False) is not None\n\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 396, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef is_json(json_data: t.Union[str, bytes]) -> bool:\n return load_json(json_data, strict=False) is not None\n\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_chars_compressed": 396, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::20": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_decode_bytes", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::27": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_relative_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::158": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_mapping_protocol", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::17": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["TokenDecodeError", "parse_jwt", "pytest"], "enclosing_function": "test_parse_jwt_empty", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenDecodeError(InvalidTokenError):\n pass", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1707, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenDecodeError(InvalidTokenError):\n pass", "n_chars_compressed": 1707, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::39": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_copy", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::28": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_relative_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::69": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri", "InvalidAtUriError", "pytest"], "enclosing_function": "test_at_uri_constructor", "extracted_code": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3961, "extracted_code_full": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3961, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_handle_resolver.py::21": {"resolved_imports": ["packages/atproto_identity/exceptions.py", "packages/atproto_identity/handle/resolver.py"], "used_names": ["AsyncHandleResolver", "DidNotFoundError", "pytest"], "enclosing_function": "test_handle_resolver_with_invalid_handle_url", "extracted_code": "# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...\n\n\n# Source: packages/atproto_identity/handle/resolver.py\nclass AsyncHandleResolver(_HandleResolverBase):\n \"\"\"Asynchronous Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.asyncresolver\n self._http_client = httpx.AsyncClient()\n\n async def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = await self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = await self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n async def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = await self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n async def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = await self._dns_resolver.resolve(\n self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout\n )\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n async def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = await self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2874, "extracted_code_full": "# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...\n\n\n# Source: packages/atproto_identity/handle/resolver.py\nclass AsyncHandleResolver(_HandleResolverBase):\n \"\"\"Asynchronous Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.asyncresolver\n self._http_client = httpx.AsyncClient()\n\n async def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = await self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = await self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n async def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = await self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n async def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = await self._dns_resolver.resolve(\n self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout\n )\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n async def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = await self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_chars_compressed": 2874, "compression_ratio": 1.0}, "tests/test_atproto_client/models/test_alias_generator.py::17": {"resolved_imports": ["packages/atproto_client/models/base.py", "packages/atproto_client/models/utils.py"], "used_names": ["get_model_as_dict"], "enclosing_function": "test_model_base_aliases", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef get_model_as_dict(model: t.Union[DotDict, BlobRef, ModelBase]) -> t.Dict[str, t.Any]:\n if isinstance(model, DotDict):\n return model.to_dict()\n\n return model.model_dump(exclude_none=True, by_alias=True)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 268, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef get_model_as_dict(model: t.Union[DotDict, BlobRef, ModelBase]) -> t.Dict[str, t.Any]:\n if isinstance(model, DotDict):\n return model.to_dict()\n\n return model.model_dump(exclude_none=True, by_alias=True)", "n_chars_compressed": 268, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_handle_resolver.py::13": {"resolved_imports": ["packages/atproto_identity/exceptions.py", "packages/atproto_identity/handle/resolver.py"], "used_names": ["HandleResolver"], "enclosing_function": "test_handle_resolver", "extracted_code": "# Source: packages/atproto_identity/handle/resolver.py\nclass HandleResolver(_HandleResolverBase):\n \"\"\"Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.resolver\n self._http_client = httpx.Client()\n\n def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = self._dns_resolver.resolve(self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout)\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2665, "extracted_code_full": "# Source: packages/atproto_identity/handle/resolver.py\nclass HandleResolver(_HandleResolverBase):\n \"\"\"Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.resolver\n self._http_client = httpx.Client()\n\n def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = self._dns_resolver.resolve(self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout)\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_chars_compressed": 2665, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::34": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["get_jwt_payload"], "enclosing_function": "test_get_jwt_payload", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 342, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef get_jwt_payload(jwt: str) -> JwtPayload:\n \"\"\"Return the payload of the given JWT.\n\n Args:\n jwt: The JWT to get the payload from.\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n \"\"\"\n payload, *_ = parse_jwt(jwt)\n return decode_jwt_payload(payload)", "n_chars_compressed": 342, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::25": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver", "DidWebResolverError", "pytest"], "enclosing_function": "test_did_resolver_with_unknown_did_web", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidWebResolverError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1272, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidWebResolverError(AtProtocolError): ...", "n_chars_compressed": 1272, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::12": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["SECP256K1_JWT_ALG", "get_multikey_alg"], "enclosing_function": "test_get_multikey_alg_secp256k1", "extracted_code": "# Source: packages/atproto_crypto/consts.py\nSECP256K1_JWT_ALG = 'ES256K'\n\n\n# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 698, "extracted_code_full": "# Source: packages/atproto_crypto/consts.py\nSECP256K1_JWT_ALG = 'ES256K'\n\n\n# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')", "n_chars_compressed": 698, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::12": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["load_json", "pytest"], "enclosing_function": "test_load_json", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 284, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_chars_compressed": 284, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_resolve_handle.py::19": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_resolve_handle_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::16": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_old_format_migration", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_post_record.py::23": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_post_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::83": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_headers_override_with_additional_headers", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::14": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_old_format_migration", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::17": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::20": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_feed_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_atproto_data.py::14": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["DidResolver"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::89": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session", "SessionEvent"], "enclosing_function": "async_callback", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 612, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_chars_compressed": 612, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_thread_view_post_with_embed_media.py::33": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_thread_view_post_with_embed_media_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::120": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["TypeAdapter", "_OPT_IN_KEY", "pytest"], "enclosing_function": "test_string_format_validation_with_valid", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/test_atproto_core/test_uri.py::57": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri", "InvalidAtUriError", "pytest"], "enclosing_function": "test_at_uri_constructor", "extracted_code": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3961, "extracted_code_full": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3961, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::62": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client"], "enclosing_function": "test_client_clone", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26227, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_chars_compressed": 26227, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_post_record.py::27": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_post_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::54": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::26": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_relative_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::15": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client", "_ATPROTO_PROXY_HEADER"], "enclosing_function": "test_client_with_bsky_chat_proxy", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26335, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_chars_compressed": 26335, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::94": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["dot_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_model_strict_mode", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::36": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_copy", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::63": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client"], "enclosing_function": "test_client_clone", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26227, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post", "n_chars_compressed": 26227, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::29": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["IncorrectMultikeyPrefixError", "get_multikey_alg", "pytest"], "enclosing_function": "test_get_multikey_alg_wrong_multibase", "extracted_code": "# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass IncorrectMultikeyPrefixError(DidKeyError): ...", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 726, "extracted_code_full": "# Source: packages/atproto_crypto/did.py\ndef get_multikey_alg(multikey: str) -> str:\n \"\"\"Get JWT alg for multikey.\n\n Args:\n multikey: Multikey.\n\n Returns:\n str: JWT alg.\n \"\"\"\n if not multikey.startswith(BASE58_MULTIBASE_PREFIX):\n raise IncorrectMultikeyPrefixError(f'Incorrect prefix for multikey {multikey}')\n\n prefixed_bytes = multibase_to_bytes(multikey)\n if prefixed_bytes.startswith(P256_DID_PREFIX):\n return P256_JWT_ALG\n if prefixed_bytes.startswith(SECP256K1_DID_PREFIX):\n return SECP256K1_JWT_ALG\n\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n\n# Source: packages/atproto_crypto/exceptions.py\nclass IncorrectMultikeyPrefixError(DidKeyError): ...", "n_chars_compressed": 726, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::27": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client", "_ATPROTO_ACCEPT_LABELERS_HEADER"], "enclosing_function": "test_client_with_bsky_labeler", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_ACCEPT_LABELERS_HEADER = 'atproto-accept-labelers'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26355, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_ACCEPT_LABELERS_HEADER = 'atproto-accept-labelers'", "n_chars_compressed": 26355, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_like_record.py::23": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_like_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_verify.py::32": {"resolved_imports": ["packages/atproto_crypto/verify.py"], "used_names": ["pytest", "verify_signature"], "enclosing_function": "test_verify_signature", "extracted_code": "# Source: packages/atproto_crypto/verify.py\ndef verify_signature(did_key: str, signing_input: bytes, signature: bytes) -> bool:\n \"\"\"Verify signature.\n\n Args:\n did_key: DID key.\n signing_input: Signing input (data).\n signature: Signature.\n\n Returns:\n bool: True if signature is valid, False otherwise.\n \"\"\"\n parsed_did_key = parse_did_key(did_key)\n if parsed_did_key.jwt_alg not in ALGORITHM_TO_CLASS:\n raise UnsupportedSignatureAlgorithmError('Unsupported signature alg')\n\n algorithm_class = ALGORITHM_TO_CLASS[parsed_did_key.jwt_alg]\n return algorithm_class().verify_signature(parsed_did_key.key_bytes, signing_input, signature)", "n_imports_parsed": 5, "n_files_resolved": 1, "n_chars_extracted": 688, "extracted_code_full": "# Source: packages/atproto_crypto/verify.py\ndef verify_signature(did_key: str, signing_input: bytes, signature: bytes) -> bool:\n \"\"\"Verify signature.\n\n Args:\n did_key: DID key.\n signing_input: Signing input (data).\n signature: Signature.\n\n Returns:\n bool: True if signature is valid, False otherwise.\n \"\"\"\n parsed_did_key = parse_did_key(did_key)\n if parsed_did_key.jwt_alg not in ALGORITHM_TO_CLASS:\n raise UnsupportedSignatureAlgorithmError('Unsupported signature alg')\n\n algorithm_class = ALGORITHM_TO_CLASS[parsed_did_key.jwt_alg]\n return algorithm_class().verify_signature(parsed_did_key.key_bytes, signing_input, signature)", "n_chars_compressed": 688, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::71": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["get_did_key"], "enclosing_function": "test_get_did_key_with_secp256k1", "extracted_code": "# Source: packages/atproto_crypto/did.py\ndef get_did_key(key_type: str, key: str) -> t.Optional[str]:\n \"\"\"Get DID key.\n\n Args:\n key_type: Key type.\n key: Key.\n\n Returns:\n :obj:`str`: DID key or ``None`` if a key type is not supported.\n \"\"\"\n did_key = None\n if key_type == 'EcdsaSecp256r1VerificationKey2019':\n key_bytes = multibase_to_bytes(key)\n did_key = format_did_key(P256_JWT_ALG, key_bytes)\n elif key_type == 'EcdsaSecp256k1VerificationKey2019':\n key_bytes = multibase_to_bytes(key)\n did_key = format_did_key(SECP256K1_JWT_ALG, key_bytes)\n elif key_type == 'Multikey':\n # Multikey is compressed already\n did_key = format_did_key_multikey(key)\n\n return did_key", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 755, "extracted_code_full": "# Source: packages/atproto_crypto/did.py\ndef get_did_key(key_type: str, key: str) -> t.Optional[str]:\n \"\"\"Get DID key.\n\n Args:\n key_type: Key type.\n key: Key.\n\n Returns:\n :obj:`str`: DID key or ``None`` if a key type is not supported.\n \"\"\"\n did_key = None\n if key_type == 'EcdsaSecp256r1VerificationKey2019':\n key_bytes = multibase_to_bytes(key)\n did_key = format_did_key(P256_JWT_ALG, key_bytes)\n elif key_type == 'EcdsaSecp256k1VerificationKey2019':\n key_bytes = multibase_to_bytes(key)\n did_key = format_did_key(SECP256K1_JWT_ALG, key_bytes)\n elif key_type == 'Multikey':\n # Multikey is compressed already\n did_key = format_did_key_multikey(key)\n\n return did_key", "n_chars_compressed": 755, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_custom_record.py::20": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_custom_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::45": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "CID", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_from_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 4324, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 4324, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::51": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_type_str", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::17": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_input_mutation", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::65": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": [], "enclosing_function": "get_signing_key", "extracted_code": "", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 0}, "tests/test_atproto_client/client/test_session.py::35": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_copy", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::66": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_set_additional_headers_case_insensitivity", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::19": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_decode_bytes", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::72": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session", "SessionEvent"], "enclosing_function": "sync_callback", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 612, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_chars_compressed": 612, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::15": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver"], "enclosing_function": "test_did_resolver_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_get_follows.py::54": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_get_follows_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::9": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_input_mutation", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::53": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_core/test_nsid.py::21": {"resolved_imports": ["packages/atproto_core/nsid/nsid.py"], "used_names": ["get_test_cases", "pytest", "validate_nsid"], "enclosing_function": "test_nsid_validation_with_invalid", "extracted_code": "# Source: packages/atproto_core/nsid/nsid.py\ndef validate_nsid(nsid: str, *, soft_fail: bool = False) -> bool:\n \"\"\"Validate NSID.\n\n Args:\n nsid: NSID to validate.\n soft_fail: enable to return False on fall instead of exception\n\n Returns:\n :obj:`bool`: Validation result.\n\n Raises:\n :class:`atproto.exceptions.InvalidNsidError`: Invalid NSID exception.\n \"\"\"\n try:\n return _validate_nsid(nsid)\n except InvalidNsidError as e:\n if soft_fail:\n return False\n\n raise e", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 542, "extracted_code_full": "# Source: packages/atproto_core/nsid/nsid.py\ndef validate_nsid(nsid: str, *, soft_fail: bool = False) -> bool:\n \"\"\"Validate NSID.\n\n Args:\n nsid: NSID to validate.\n soft_fail: enable to return False on fall instead of exception\n\n Returns:\n :obj:`bool`: Validation result.\n\n Raises:\n :class:`atproto.exceptions.InvalidNsidError`: Invalid NSID exception.\n \"\"\"\n try:\n return _validate_nsid(nsid)\n except InvalidNsidError as e:\n if soft_fail:\n return False\n\n raise e", "n_chars_compressed": 542, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_atproto_data.py::17": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::44": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "CID", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_from_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 4324, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 4324, "compression_ratio": 1.0}, "tests/test_atproto_core/test_nsid.py::9": {"resolved_imports": ["packages/atproto_core/nsid/nsid.py"], "used_names": ["NSID"], "enclosing_function": "test_nsid_from_str", "extracted_code": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1182, "extracted_code_full": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 1182, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_custom_record.py::25": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_custom_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::34": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_copy", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_did_doc.py::33": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_did_doc_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::37": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "CID", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_from_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 4324, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)\n\n\n# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 4324, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::56": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_to_ipld", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2964, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2964, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_changed_lexicon_compatability.py::67": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/exceptions.py"], "used_names": ["ModelError", "get_or_create", "models", "pytest"], "enclosing_function": "test_removed_non_optional_field", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 472, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...", "n_chars_compressed": 472, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::25": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["parse_jwt"], "enclosing_function": "test_parse_jwt", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1605, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_chars_compressed": 1605, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_thread_view_post_with_embed_media.py::20": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_thread_view_post_with_embed_media_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::21": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_get_headers_case_insensitivity", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::131": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_mapping_protocol", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_atproto_data.py::15": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["DidResolver"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::25": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_roundtrip", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/models/test_alias_generator.py::18": {"resolved_imports": ["packages/atproto_client/models/base.py", "packages/atproto_client/models/utils.py"], "used_names": ["get_model_as_dict"], "enclosing_function": "test_model_base_aliases", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef get_model_as_dict(model: t.Union[DotDict, BlobRef, ModelBase]) -> t.Dict[str, t.Any]:\n if isinstance(model, DotDict):\n return model.to_dict()\n\n return model.model_dump(exclude_none=True, by_alias=True)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 268, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef get_model_as_dict(model: t.Union[DotDict, BlobRef, ModelBase]) -> t.Dict[str, t.Any]:\n if isinstance(model, DotDict):\n return model.to_dict()\n\n return model.model_dump(exclude_none=True, by_alias=True)", "n_chars_compressed": 268, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::10": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_input_mutation", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::33": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_equal", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::22": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["load_json", "pytest"], "enclosing_function": "test_load_json", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 284, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_chars_compressed": 284, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::35": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_equal", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::38": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_make", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::165": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["BaseModel", "ModelError", "get_or_create", "pytest", "string_formats"], "enclosing_function": "test_get_or_create_with_strict_validation", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::16": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_get_headers_case_insensitivity", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::48": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_type_str", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::42": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/test_alias_generator.py::6": {"resolved_imports": ["packages/atproto_client/models/base.py", "packages/atproto_client/models/utils.py"], "used_names": ["_alias_generator"], "enclosing_function": "test_alias_generator", "extracted_code": "# Source: packages/atproto_client/models/base.py\ndef _alias_generator(name: str) -> str:\n camel_name = alias_generators.to_camel(name)\n\n if camel_name.endswith('_'):\n camel_name = camel_name[:-1]\n\n return camel_name", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 231, "extracted_code_full": "# Source: packages/atproto_client/models/base.py\ndef _alias_generator(name: str) -> str:\n camel_name = alias_generators.to_camel(name)\n\n if camel_name.endswith('_'):\n camel_name = camel_name[:-1]\n\n return camel_name", "n_chars_compressed": 231, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::106": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session", "SessionDispatcher", "SessionEvent"], "enclosing_function": "test_session_not_modified", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'\n\nclass SessionDispatcher:\n def __init__(self, session: t.Optional['Session'] = None) -> None:\n self._session: t.Optional['Session'] = session\n\n self._on_session_change_callbacks: t.List[SessionChangeCallback] = []\n self._on_session_change_async_callbacks: t.List[AsyncSessionChangeCallback] = []\n\n def set_session(self, session: 'Session') -> None:\n self._session = session\n\n def on_session_change(self, callback: t.Union['AsyncSessionChangeCallback', 'SessionChangeCallback']) -> None:\n if inspect.iscoroutinefunction(callback):\n self._on_session_change_async_callbacks.append(callback)\n elif inspect.isfunction(callback):\n self._on_session_change_callbacks.append(callback)\n\n def dispatch_session_change(self, event: SessionEvent) -> None:\n self._call_on_session_change_callbacks(event)\n\n async def dispatch_session_change_async(self, event: SessionEvent) -> None:\n self._call_on_session_change_callbacks(event) # Allow synchronous callbacks in the async client\n await self._call_on_session_change_callbacks_async(event)\n\n def _call_on_session_change_callbacks(self, event: SessionEvent) -> None:\n assert _session_exists(self._session)\n session_copy = self._session.copy() # Avoid modifying the original session\n\n for on_session_change_callback in self._on_session_change_callbacks:\n on_session_change_callback(event, session_copy)\n\n async def _call_on_session_change_callbacks_async(self, event: SessionEvent) -> None:\n assert _session_exists(self._session)\n session_copy = self._session.copy() # Avoid modifying the original session\n\n coroutines: t.List[t.Coroutine[t.Any, t.Any, None]] = []\n for on_session_change_async_callback in self._on_session_change_async_callbacks:\n coroutines.append(on_session_change_async_callback(event, session_copy))\n\n await asyncio.gather(*coroutines)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'\n\nclass SessionDispatcher:\n def __init__(self, session: t.Optional['Session'] = None) -> None:\n self._session: t.Optional['Session'] = session\n\n self._on_session_change_callbacks: t.List[SessionChangeCallback] = []\n self._on_session_change_async_callbacks: t.List[AsyncSessionChangeCallback] = []\n\n def set_session(self, session: 'Session') -> None:\n self._session = session\n\n def on_session_change(self, callback: t.Union['AsyncSessionChangeCallback', 'SessionChangeCallback']) -> None:\n if inspect.iscoroutinefunction(callback):\n self._on_session_change_async_callbacks.append(callback)\n elif inspect.isfunction(callback):\n self._on_session_change_callbacks.append(callback)\n\n def dispatch_session_change(self, event: SessionEvent) -> None:\n self._call_on_session_change_callbacks(event)\n\n async def dispatch_session_change_async(self, event: SessionEvent) -> None:\n self._call_on_session_change_callbacks(event) # Allow synchronous callbacks in the async client\n await self._call_on_session_change_callbacks_async(event)\n\n def _call_on_session_change_callbacks(self, event: SessionEvent) -> None:\n assert _session_exists(self._session)\n session_copy = self._session.copy() # Avoid modifying the original session\n\n for on_session_change_callback in self._on_session_change_callbacks:\n on_session_change_callback(event, session_copy)\n\n async def _call_on_session_change_callbacks_async(self, event: SessionEvent) -> None:\n assert _session_exists(self._session)\n session_copy = self._session.copy() # Avoid modifying the original session\n\n coroutines: t.List[t.Coroutine[t.Any, t.Any, None]] = []\n for on_session_change_async_callback in self._on_session_change_async_callbacks:\n coroutines.append(on_session_change_async_callback(event, session_copy))\n\n await asyncio.gather(*coroutines)", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::100": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["TypeAdapter", "ValidationError", "_OPT_IN_KEY", "pytest"], "enclosing_function": "test_string_format_validation_with_invalid", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/test_atproto_client/client/test_client.py::18": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client", "_ATPROTO_PROXY_HEADER"], "enclosing_function": "test_client_with_bsky_chat_proxy", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26335, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_chars_compressed": 26335, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_did_doc.py::32": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_did_doc_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_extended_post_record.py::24": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_extended_post_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::29": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_equal", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::18": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::89": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_to_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2964, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2964, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_utils.py::27": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/utils.py"], "used_names": ["is_json", "load_json", "pytest"], "enclosing_function": "test_is_json", "extracted_code": "# Source: packages/atproto_client/models/utils.py\ndef is_json(json_data: t.Union[str, bytes]) -> bool:\n return load_json(json_data, strict=False) is not None\n\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 396, "extracted_code_full": "# Source: packages/atproto_client/models/utils.py\ndef is_json(json_data: t.Union[str, bytes]) -> bool:\n return load_json(json_data, strict=False) is not None\n\ndef load_json(json_data: t.Union[str, bytes], strict: bool = True) -> t.Optional[t.Dict[str, t.Any]]:\n try:\n return from_json(json_data)\n except ValueError as e:\n if strict:\n raise e\n\n return None", "n_chars_compressed": 396, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_base.py::9": {"resolved_imports": ["packages/atproto_client/client/base.py"], "used_names": ["_BASE_API_URL", "_handle_base_url"], "enclosing_function": "test_handle_base_url", "extracted_code": "# Source: packages/atproto_client/client/base.py\n_BASE_API_URL = 'https://bsky.social/xrpc'\n\ndef _handle_base_url(base_url: t.Optional[str] = None) -> str:\n if base_url is None:\n return _BASE_API_URL\n\n if not base_url.endswith('/xrpc'):\n return f'{base_url.rstrip(\"/\")}/xrpc'\n\n return base_url", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 316, "extracted_code_full": "# Source: packages/atproto_client/client/base.py\n_BASE_API_URL = 'https://bsky.social/xrpc'\n\ndef _handle_base_url(base_url: t.Optional[str] = None) -> str:\n if base_url is None:\n return _BASE_API_URL\n\n if not base_url.endswith('/xrpc'):\n return f'{base_url.rstrip(\"/\")}/xrpc'\n\n return base_url", "n_chars_compressed": 316, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::22": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "UnsupportedDidWebPathError", "pytest"], "enclosing_function": "test_did_resolver_with_invalid_did_web", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass UnsupportedDidWebPathError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1351, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass UnsupportedDidWebPathError(AtProtocolError): ...", "n_chars_compressed": 1351, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::36": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_is_record_type.py::22": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "is_record_type", "models"], "enclosing_function": "test_is_record_type", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::33": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_copy", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::40": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_make", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::9": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_decode_str", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_core/test_car.py::10": {"resolved_imports": ["packages/atproto_core/car/car.py"], "used_names": ["CAR"], "enclosing_function": "test_car", "extracted_code": "# Source: packages/atproto_core/car/car.py\nclass CAR:\n \"\"\"CAR file.\"\"\"\n\n def __init__(self, root: CID, blocks: Blocks) -> None:\n self._root = root\n self._blocks = blocks\n\n @property\n def root(self) -> CID:\n \"\"\"Get root.\"\"\"\n return self._root\n\n @property\n def blocks(self) -> Blocks:\n \"\"\"Get blocks.\"\"\"\n return self._blocks\n\n @classmethod\n def from_bytes(cls, data: bytes) -> 'CAR':\n \"\"\"Decode CAR file.\n\n Note:\n You could pass as `data` response of `client.com.atproto.sync.get_repo`, for example.\n And other responses of methods in the `sync` namespace.\n\n Example:\n >>> from atproto import CAR, Client\n >>> client = Client()\n >>> client.login('my-handle', 'my-password')\n >>> repo = client.com.atproto.sync.get_repo({'did': client.me.did})\n >>> car_file = CAR.from_bytes(repo)\n >>> print(car_file.root)\n >>> print(car_file.blocks)\n\n Args:\n data: Content of the CAR file.\n\n Returns:\n :obj:`atproto.CAR`: Parsed CAR file.\n \"\"\"\n header, blocks = libipld.decode_car(data)\n\n roots = header.get('roots')\n if isinstance(roots, list) and len(roots):\n # The first element of the CAR roots metadata array must be the CID of the most relevant Commit object.\n # For a generic export, this is the current (most recent) commit.\n # Additional CIDs may also be present in the roots array, with (for now) undefined meaning or order.\n root: CID = CID.decode(roots[0])\n else:\n raise InvalidCARFile('Invalid CAR file. Expected at least one root.')\n\n blocks = {CID.decode(cid): block for cid, block in blocks.items()}\n return cls(root=root, blocks=blocks)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1861, "extracted_code_full": "# Source: packages/atproto_core/car/car.py\nclass CAR:\n \"\"\"CAR file.\"\"\"\n\n def __init__(self, root: CID, blocks: Blocks) -> None:\n self._root = root\n self._blocks = blocks\n\n @property\n def root(self) -> CID:\n \"\"\"Get root.\"\"\"\n return self._root\n\n @property\n def blocks(self) -> Blocks:\n \"\"\"Get blocks.\"\"\"\n return self._blocks\n\n @classmethod\n def from_bytes(cls, data: bytes) -> 'CAR':\n \"\"\"Decode CAR file.\n\n Note:\n You could pass as `data` response of `client.com.atproto.sync.get_repo`, for example.\n And other responses of methods in the `sync` namespace.\n\n Example:\n >>> from atproto import CAR, Client\n >>> client = Client()\n >>> client.login('my-handle', 'my-password')\n >>> repo = client.com.atproto.sync.get_repo({'did': client.me.did})\n >>> car_file = CAR.from_bytes(repo)\n >>> print(car_file.root)\n >>> print(car_file.blocks)\n\n Args:\n data: Content of the CAR file.\n\n Returns:\n :obj:`atproto.CAR`: Parsed CAR file.\n \"\"\"\n header, blocks = libipld.decode_car(data)\n\n roots = header.get('roots')\n if isinstance(roots, list) and len(roots):\n # The first element of the CAR roots metadata array must be the CID of the most relevant Commit object.\n # For a generic export, this is the current (most recent) commit.\n # Additional CIDs may also be present in the roots array, with (for now) undefined meaning or order.\n root: CID = CID.decode(roots[0])\n else:\n raise InvalidCARFile('Invalid CAR file. Expected at least one root.')\n\n blocks = {CID.decode(cid): block for cid, block in blocks.items()}\n return cls(root=root, blocks=blocks)", "n_chars_compressed": 1861, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::59": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri", "InvalidAtUriError", "pytest"], "enclosing_function": "test_at_uri_constructor", "extracted_code": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3961, "extracted_code_full": "# Source: packages/atproto_core/exceptions.py\nclass InvalidAtUriError(AtProtocolError): ...\n\n\n# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3961, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_extended_like_record.py::19": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_extended_like_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver_cache.py::20": {"resolved_imports": ["packages/atproto_identity/cache/in_memory_cache.py", "packages/atproto_identity/did/resolver.py"], "used_names": ["DidInMemoryCache", "DidResolver"], "enclosing_function": "test_did_resolver_cache_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass DidInMemoryCache(DidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._cache: t.Dict[str, CachedDid] = {}\n\n def set(self, did: str, document: DidDocument) -> None:\n self._cache[did] = CachedDid(document, _datetime_now())\n\n def refresh(self, did: str, get_doc_callback: 'GetDocCallback') -> None:\n doc = get_doc_callback()\n if doc:\n self.set(did, doc)\n\n def delete(self, did: str) -> None:\n del self._cache[did]\n\n def clear(self) -> None:\n self._cache.clear()\n\n def get(self, did: str) -> t.Optional[CachedDidResult]:\n val = self._cache.get(did)\n if not val:\n return None\n\n now = _datetime_now().timestamp()\n expired = now > val.updated_at.timestamp() + self.max_ttl\n stale = now > val.updated_at.timestamp() + self.stale_ttl\n\n return CachedDidResult(did, val.document, val.updated_at, stale, expired)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2237, "extracted_code_full": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass DidInMemoryCache(DidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._cache: t.Dict[str, CachedDid] = {}\n\n def set(self, did: str, document: DidDocument) -> None:\n self._cache[did] = CachedDid(document, _datetime_now())\n\n def refresh(self, did: str, get_doc_callback: 'GetDocCallback') -> None:\n doc = get_doc_callback()\n if doc:\n self.set(did, doc)\n\n def delete(self, did: str) -> None:\n del self._cache[did]\n\n def clear(self) -> None:\n self._cache.clear()\n\n def get(self, did: str) -> t.Optional[CachedDidResult]:\n val = self._cache.get(did)\n if not val:\n return None\n\n now = _datetime_now().timestamp()\n expired = now > val.updated_at.timestamp() + self.max_ttl\n stale = now > val.updated_at.timestamp() + self.stale_ttl\n\n return CachedDidResult(did, val.document, val.updated_at, stale, expired)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 2237, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::76": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["ValidationError", "get_or_create", "models", "pytest"], "enclosing_function": "test_feed_record_py_type_frozen", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::17": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_did_resolver_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::64": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_post_record.py::53": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_post_record_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::13": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_input_mutation", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::116": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_iter", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_atproto_data.py::16": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_thread_view_post_with_embed_media.py::25": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_thread_view_post_with_embed_media_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_unknown_union_model.py::11": {"resolved_imports": ["packages/atproto_client/models/base.py"], "used_names": ["UnknownUnionModel", "ValidationError", "pytest"], "enclosing_function": "test_unknown_union_model", "extracted_code": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 124, "extracted_code_full": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_chars_compressed": 124, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::67": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["BlobRef", "get_model_as_dict", "get_or_create", "models"], "enclosing_function": "test_feed_record_avatar_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 2475, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2475, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::14": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_dot_dict.py::155": {"resolved_imports": ["packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict"], "enclosing_function": "test_dot_dict_mapping_protocol", "extracted_code": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 3811, "extracted_code_full": "# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 3811, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver.py::38": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["DidResolver"], "enclosing_function": "test_did_resolver_with_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1172, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1172, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::48": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session", "get_session_pds_endpoint"], "enclosing_function": "test_get_session_pds_endpoint", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\ndef get_session_pds_endpoint(session: 'SessionResponse') -> t.Optional[str]:\n \"\"\"Return the PDS endpoint of the given session.\n\n Note:\n Return :obj:`None` for self-hosted PDSs.\n \"\"\"\n if isinstance(session, Session):\n return session.pds_endpoint\n\n if session.did_doc and is_valid_did_doc(session.did_doc):\n doc = DidDocument.from_dict(session.did_doc)\n return doc.get_pds_endpoint()\n\n return None", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 960, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\ndef get_session_pds_endpoint(session: 'SessionResponse') -> t.Optional[str]:\n \"\"\"Return the PDS endpoint of the given session.\n\n Note:\n Return :obj:`None` for self-hosted PDSs.\n \"\"\"\n if isinstance(session, Session):\n return session.pds_endpoint\n\n if session.did_doc and is_valid_did_doc(session.did_doc):\n doc = DidDocument.from_dict(session.did_doc)\n return doc.get_pds_endpoint()\n\n return None", "n_chars_compressed": 960, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::15": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_get_headers_case_insensitivity", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::74": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["TokenInvalidAudienceError", "pytest", "verify_jwt"], "enclosing_function": "test_verify_jwt_aud_validation", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef verify_jwt(\n jwt: str, get_signing_key_callback: GetSigningKeyCallback, own_did: t.Optional[str] = None, leeway: int = 0\n) -> JwtPayload:\n \"\"\"Verify the given JWT.\n\n Args:\n jwt: The JWT to verify.\n get_signing_key_callback: The callback to get the signing key.\n own_did: The DID of the service (aud).\n leeway: The leeway in seconds to accept when verifying time claims (exp, iat).\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n\n Raises:\n TokenDecodeError: If the given JWT is invalid.\n TokenExpiredSignatureError: If the given JWT is expired.\n TokenImmatureSignatureError: If the given JWT is immature.\n TokenInvalidAudienceError: If the given JWT has invalid audience.\n TokenInvalidIssuedAtError: If the given JWT has invalid issued at.\n TokenInvalidSignatureError: If the given JWT has invalid signature.\n \"\"\"\n plain_payload, signing_input, _, signature = parse_jwt(jwt)\n\n payload = decode_jwt_payload(plain_payload)\n validate_jwt_payload(payload, leeway)\n\n if own_did and payload.aud != own_did:\n raise TokenInvalidAudienceError('Invalid subject')\n\n if payload.iss is None:\n raise TokenDecodeError('Invalid payload. Expected not None iss')\n\n signing_key = get_signing_key_callback(payload.iss, False)\n if _verify_signature(signing_key, signing_input, signature):\n return payload\n\n fresh_signing_key = get_signing_key_callback(payload.iss, True) # get signing key without a cache\n if fresh_signing_key == signing_key:\n raise TokenInvalidSignatureError('Invalid signature even with fresh signing key it is equal to the old one)')\n\n if _verify_signature(fresh_signing_key, signing_input, signature):\n return payload\n\n # this code should be unreachable\n # verifying methods must raise exception before\n raise TokenInvalidSignatureError('Invalid signature')\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenInvalidAudienceError(InvalidTokenError):\n pass", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 2101, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef verify_jwt(\n jwt: str, get_signing_key_callback: GetSigningKeyCallback, own_did: t.Optional[str] = None, leeway: int = 0\n) -> JwtPayload:\n \"\"\"Verify the given JWT.\n\n Args:\n jwt: The JWT to verify.\n get_signing_key_callback: The callback to get the signing key.\n own_did: The DID of the service (aud).\n leeway: The leeway in seconds to accept when verifying time claims (exp, iat).\n\n Returns:\n :obj:`JwtPayload`: The payload of the given JWT.\n\n Raises:\n TokenDecodeError: If the given JWT is invalid.\n TokenExpiredSignatureError: If the given JWT is expired.\n TokenImmatureSignatureError: If the given JWT is immature.\n TokenInvalidAudienceError: If the given JWT has invalid audience.\n TokenInvalidIssuedAtError: If the given JWT has invalid issued at.\n TokenInvalidSignatureError: If the given JWT has invalid signature.\n \"\"\"\n plain_payload, signing_input, _, signature = parse_jwt(jwt)\n\n payload = decode_jwt_payload(plain_payload)\n validate_jwt_payload(payload, leeway)\n\n if own_did and payload.aud != own_did:\n raise TokenInvalidAudienceError('Invalid subject')\n\n if payload.iss is None:\n raise TokenDecodeError('Invalid payload. Expected not None iss')\n\n signing_key = get_signing_key_callback(payload.iss, False)\n if _verify_signature(signing_key, signing_input, signature):\n return payload\n\n fresh_signing_key = get_signing_key_callback(payload.iss, True) # get signing key without a cache\n if fresh_signing_key == signing_key:\n raise TokenInvalidSignatureError('Invalid signature even with fresh signing key it is equal to the old one)')\n\n if _verify_signature(fresh_signing_key, signing_input, signature):\n return payload\n\n # this code should be unreachable\n # verifying methods must raise exception before\n raise TokenInvalidSignatureError('Invalid signature')\n\n\n# Source: packages/atproto_server/exceptions.py\nclass TokenInvalidAudienceError(InvalidTokenError):\n pass", "n_chars_compressed": 2101, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::103": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["TypeAdapter", "ValidationError", "_OPT_IN_KEY", "pytest"], "enclosing_function": "test_string_format_validation_with_invalid", "extracted_code": "", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 0}, "tests/test_atproto_core/test_nsid.py::11": {"resolved_imports": ["packages/atproto_core/nsid/nsid.py"], "used_names": ["NSID"], "enclosing_function": "test_nsid_from_str", "extracted_code": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 1182, "extracted_code_full": "# Source: packages/atproto_core/nsid/nsid.py\nclass NSID:\n \"\"\"NameSpaced IDs (NSIDs).\n\n Examples:\n com.example.status\n\n io.social.getFeed\n\n net.users.bob.ping\n \"\"\"\n\n segments: Segments = field(default_factory=list)\n\n @classmethod\n def from_str(cls, nsid: str) -> 'NSID':\n \"\"\"Create `NSID` instance from string.\"\"\"\n validate_nsid(nsid)\n return cls(segments=get_nsid_segments(nsid))\n\n @property\n def authority(self) -> str:\n \"\"\"Get authority of NSID.\n\n com.example.thing\n ^^^^^^^^^^^--------> example.com\n\n delim joined self.segments[:-1][::-1]\n \"\"\"\n segments_without_name = self.segments[:-1]\n segments_without_name.reverse()\n\n return _NSID_DELIM.join(segments_without_name)\n\n @property\n def name(self) -> str:\n \"\"\"Get name.\"\"\"\n return self.segments[-1]\n\n def __str__(self) -> str:\n return _NSID_DELIM.join(self.segments)\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, NSID):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 1182, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_custom_record.py::22": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_custom_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_like_record.py::27": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_like_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::71": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session", "SessionEvent"], "enclosing_function": "sync_callback", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 612, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/client/session.py\nclass SessionEvent(Enum):\n IMPORT = 'import'\n CREATE = 'create'\n REFRESH = 'refresh'", "n_chars_compressed": 612, "compression_ratio": 1.0}, "tests/test_atproto_server/auth/test_jwt.py::29": {"resolved_imports": ["packages/atproto_server/auth/jwt.py", "packages/atproto_server/exceptions.py"], "used_names": ["parse_jwt"], "enclosing_function": "test_parse_jwt", "extracted_code": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 1605, "extracted_code_full": "# Source: packages/atproto_server/auth/jwt.py\ndef parse_jwt(jwt: t.Union[str, bytes]) -> t.Tuple[bytes, bytes, t.Dict[str, t.Any], bytes]:\n \"\"\"Parse the given JWT.\n\n Args:\n jwt: The JWT to parse.\n\n Returns:\n :obj:`tuple` of :obj:`bytes`, :obj:`bytes`, :obj:`dict`, :obj:`bytes`:\n The parsed JWT: payload, signing input, header, signature.\n \"\"\"\n if isinstance(jwt, str):\n jwt = jwt.encode('UTF-8')\n\n try:\n signing_input, crypto_segment = jwt.rsplit(b'.', 1)\n header_segment, payload_segment = signing_input.split(b'.', 1)\n except ValueError as e:\n raise TokenDecodeError('Not enough segments') from e\n\n try:\n header_data = base64url_decode(header_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid header padding') from e\n\n try:\n header = from_json(header_data)\n except ValueError as e:\n raise TokenDecodeError(f'Invalid header string: {e}') from e\n\n if not isinstance(header, dict):\n raise TokenDecodeError('Invalid header string: must be a json object')\n\n header = t.cast('t.Dict[str, t.Any]', from_json(header_data)) # we expect an object in header\n\n try:\n payload = base64url_decode(payload_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid payload padding') from e\n\n try:\n signature = base64url_decode(crypto_segment)\n except (TypeError, binascii.Error) as e:\n raise TokenDecodeError('Invalid crypto padding') from e\n\n return payload, signing_input, header, signature", "n_chars_compressed": 1605, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_did_doc.py::35": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py"], "used_names": ["DotDict", "get_or_create", "models"], "enclosing_function": "test_did_doc_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 4197, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n\n# Source: packages/atproto_client/models/dot_dict.py\nclass DotDict(UnknownDict):\n \"\"\"Dot notation for dictionaries.\n\n Note:\n If the record is out of the official lexicon, it`s impossible to deserialize it to a proper data model.\n Such models will fall back to dictionaries.\n All unknown \"Union\" types will also be caught as dicts.\n This class exists to provide an ability to use such fallbacks as “real” data models.\n\n Example:\n >>> test_data = {'a': 1, 'b': {'c': 2}, 'd': [{'e': 3}, 4, 5]}\n >>> model = DotDict(test_data)\n >>> assert isinstance(model, DotDict)\n >>> assert model.nonExistingField is None\n >>> assert model.a == 1\n >>> assert model['a'] == 1\n >>> assert model['b']['c'] == 2\n >>> assert model.b.c == 2\n >>> assert model.b['c'] == 2\n >>> assert model['b'].c == 2\n >>> assert model.d[0].e == 3\n >>> assert model['d'][0]['e'] == 3\n >>> assert model['d'][0].e == 3\n >>> assert model['d'][1] == 4\n >>> assert model['d'][2] == 5\n >>> model['d'][0]['e'] = 6\n >>> assert model['d'][0]['e'] == 6\n >>> assert DotDict(test_data) == DotDict(test_data)\n >>> assert model.to_dict() == test_data\n \"\"\"\n\n def __init__(self, data: t.Dict[str, t.Any]) -> None:\n self._data = deepcopy(data)\n for k, v in self._data.items():\n self.__setitem__(k, v)\n\n def to_dict(self) -> t.Dict[str, t.Any]:\n \"\"\"Unwrap DotDict to Python built-in dict.\"\"\"\n return deepcopy(self._data)\n\n def __getitem__(self, item: str) -> t.Optional[t.Any]:\n value = self._data.get(item)\n if value is not None:\n return value\n\n return self._data.get(_convert_to_opposite_case(item))\n\n __getattr__ = __getitem__\n\n def __setitem__(self, key: str, value: t.Any) -> None:\n if key == '_data':\n super().__setattr__(key, value)\n return\n\n # we store the field in case that was firstly meet to not create duplicates\n if key not in self._data and _is_snake_case(key):\n key = _convert_snake_case_to_camel_case(key)\n\n self._data.__setitem__(key, DotDict.__convert(value))\n\n __setattr__ = __setitem__\n\n def __iter__(self) -> t.Iterator[t.Any]:\n yield from iter(self._data)\n\n def keys(self) -> abc.KeysView:\n return self._data.keys()\n\n def values(self) -> abc.ValuesView:\n return self._data.values()\n\n def items(self) -> abc.ItemsView:\n return self._data.items()\n\n def __len__(self) -> int:\n return len(self._data)\n\n def __contains__(self, item: t.Any) -> bool:\n return item in self._data\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, DotDict):\n return self._data == other._data\n if isinstance(other, dict):\n return self._data == other\n\n raise NotImplementedError\n\n def __str__(self) -> str:\n return str(self._data)\n\n def __repr__(self) -> str:\n return repr(self._data)\n\n def __reduce_ex__(self, protocol: te.SupportsIndex): # noqa: ANN204\n return self._data.__reduce_ex__(protocol)\n\n def __reduce__(self): # noqa: ANN204\n return self._data.__reduce__()\n\n @staticmethod\n def __convert(obj: t.Any) -> t.Any:\n if isinstance(obj, dict):\n return DotDict(t.cast('t.Dict[str, t.Any]', obj))\n if isinstance(obj, list):\n return [DotDict.__convert(v) for v in t.cast('t.List[t.Any]', obj)]\n if isinstance(obj, set):\n return {DotDict.__convert(v) for v in t.cast('t.Set[t.Any]', obj)}\n if isinstance(obj, tuple):\n return tuple(DotDict.__convert(v) for v in t.cast('t.Tuple[t.Any]', obj))\n return obj", "n_chars_compressed": 4197, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::152": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink"], "enclosing_function": "test_blob_ref_to_bytes_representation", "extracted_code": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2275, "extracted_code_full": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2275, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_changed_lexicon_compatability.py::30": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/exceptions.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_model_serialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_session.py::17": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/client/session.py"], "used_names": ["Session"], "enclosing_function": "test_session_old_format_migration", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 464, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]\n\n 'Client',\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 464, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_unknown_union_model.py::13": {"resolved_imports": ["packages/atproto_client/models/base.py"], "used_names": ["UnknownUnionModel", "ValidationError", "pytest"], "enclosing_function": "test_unknown_union_model", "extracted_code": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_imports_parsed": 3, "n_files_resolved": 1, "n_chars_extracted": 124, "extracted_code_full": "# Source: packages/atproto_client/models/base.py\nclass UnknownUnionModel(ModelBase):\n py_type: str = Field(alias='$type')", "n_chars_compressed": 124, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_did_resolver.py::47": {"resolved_imports": ["packages/atproto_identity/did/resolver.py", "packages/atproto_identity/exceptions.py"], "used_names": ["AsyncDidResolver", "DidNotFoundError", "pytest"], "enclosing_function": "test_did_resolver_with_unknown_did_plc", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 1341, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)\n\n\n# Source: packages/atproto_identity/exceptions.py\nclass DidNotFoundError(AtProtocolError): ...", "n_chars_compressed": 1341, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::48": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_hostname_with_digits", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_request.py::65": {"resolved_imports": ["packages/atproto_client/request.py"], "used_names": ["RequestBase"], "enclosing_function": "test_set_additional_headers_case_insensitivity", "extracted_code": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 2587, "extracted_code_full": "# Source: packages/atproto_client/request.py\nclass RequestBase:\n _MANDATORY_HEADERS: t.ClassVar[t.Dict[str, str]] = {'User-Agent': _ATPROTO_SDK_USER_AGENT}\n\n def __init__(self) -> None:\n self._additional_headers: t.Dict[str, str] = {}\n self._additional_header_sources: t.List[t.Callable[[], t.Dict[str, str]]] = []\n\n def get_headers(self, additional_headers: t.Optional[t.Dict[str, str]] = None) -> t.Dict[str, str]:\n \"\"\"Get headers for the request.\n\n Args:\n additional_headers: Additional headers.\n Overrides existing headers with the same name.\n\n Returns:\n Headers for the request.\n \"\"\"\n # The order of calling `.update()` matters. It defines the priority of overriding.\n headers_lower = {\n **_normalize_headers(RequestBase._MANDATORY_HEADERS),\n **_normalize_headers(self._additional_headers),\n }\n\n for header_source in self._additional_header_sources:\n headers_lower.update(_normalize_headers(header_source()))\n\n if additional_headers:\n headers_lower.update(_normalize_headers(additional_headers))\n\n return _denormalize_headers(headers_lower)\n\n def set_additional_headers(self, headers: t.Dict[str, str]) -> None:\n \"\"\"Set additional headers for the request.\n\n Args:\n headers: Additional headers.\n \"\"\"\n self._additional_headers = headers.copy()\n\n def add_additional_headers_source(self, callback: t.Callable[[], t.Dict[str, str]]) -> None:\n \"\"\"Add additional headers for the request.\n\n Args:\n callback: Function to get additional headers.\n \"\"\"\n self._additional_header_sources.append(callback)\n\n def add_additional_header(self, header_name: str, header_value: str) -> None:\n \"\"\"Add additional headers for the request.\n\n Note:\n This method overrides the existing header with the same name.\n\n Args:\n header_name: Header name.\n header_value: Header value.\n \"\"\"\n self._additional_headers[header_name] = header_value\n\n def clone(self) -> te.Self:\n \"\"\"Clone the client instance.\n\n Used to customize atproto proxy and set of labeler services.\n\n Returns:\n Cloned client instance.\n \"\"\"\n cloned_request = type(self)()\n\n cloned_request._additional_headers = self._additional_headers.copy()\n cloned_request._additional_header_sources = self._additional_header_sources.copy()\n\n return cloned_request", "n_chars_compressed": 2587, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_string_formats.py::162": {"resolved_imports": ["packages/atproto_client/exceptions.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/string_formats.py", "packages/atproto_client/models/utils.py"], "used_names": ["BaseModel", "ModelError", "get_or_create", "pytest", "string_formats"], "enclosing_function": "test_get_or_create_with_strict_validation", "extracted_code": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_imports_parsed": 8, "n_files_resolved": 4, "n_chars_extracted": 2314, "extracted_code_full": "# Source: packages/atproto_client/exceptions.py\nclass ModelError(AtProtocolError): ...\n\n\n# Source: packages/atproto_client/models/utils.py\ndef get_or_create(\n model_data: ModelData[M],\n model: t.Optional[t.Type[M]] = None,\n *,\n strict: bool = True,\n strict_string_format: bool = False,\n) -> t.Optional[t.Union[M, UnknownRecordType, DotDict]]:\n \"\"\"Get model instance from raw data.\n\n Note:\n The record could have additional fields and be completely custom.\n For example, third-party bsky clients add a \"via\"\n field to indicate that it was posted using a not official client.\n Such records are corresponding to the lexicon, but have additional fields.\n This is called \"extended record\".\n Extended records will be decoded to proper models with extra, non-typehinted fields available only in runtime.\n Unknown record types will be decoded to :obj:`atproto.xrpc_client.models.base.DotDict`.\n\n Note:\n By default, the method raises an exception on custom models if you have passed the expected model.\n To fall back to a :obj:`atproto.xrpc_client.models.base.DotDict` type, disable strict mode using the argument.\n\n Note:\n Model auto-resolve works only with a Record type for now.\n\n Args:\n model_data: Raw data.\n model: Class of the model or any another type. If None, it will be resolved automatically.\n strict: Disable fallback to dictionary (:obj:`atproto.xrpc_client.models.base.DotDict`)\n if it can't be properly deserialized in provided `model`. Will raise the exception instead.\n strict_string_format: Enable strict string format validation.\n\n Returns:\n Instance of :obj:`model` or :obj:`None` or\n :obj:`atproto.xrpc_client.models.dot_dict.DotDict` if `strict` is disabled.\n \"\"\"\n try:\n model_instance = _get_or_create(model_data, model, strict=strict, strict_string_format=strict_string_format)\n if strict and model_instance is not None and (not model or not isinstance(model_instance, model)):\n raise ModelError(f\"Can't properly parse model of type {model}\")\n\n return model_instance\n except Exception as e:\n if strict or not isinstance(model_data, dict):\n raise e\n\n return DotDict(model_data)", "n_chars_compressed": 2314, "compression_ratio": 1.0}, "tests/test_atproto_client/client/test_client.py::14": {"resolved_imports": ["packages/atproto_client/client/client.py", "packages/atproto_client/client/methods_mixin/headers.py"], "used_names": ["Client", "_ATPROTO_PROXY_HEADER"], "enclosing_function": "test_client_with_bsky_chat_proxy", "extracted_code": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 26335, "extracted_code_full": "# Source: packages/atproto_client/client/client.py\nclass Client(SessionDispatchMixin, SessionMethodsMixin, TimeMethodsMixin, HeadersConfigurationMethodsMixin, ClientRaw):\n \"\"\"High-level client for XRPC of ATProto.\"\"\"\n\n def __init__(self, base_url: t.Optional[str] = None, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(base_url, *args, **kwargs)\n\n self._refresh_lock = Lock()\n\n self.me: t.Optional['models.AppBskyActorDefs.ProfileViewDetailed'] = None\n\n def _invoke(self, invoke_type: 'InvokeType', **kwargs: t.Any) -> 'Response':\n ignore_session_check = kwargs.pop('ignore_session_check', False)\n if ignore_session_check:\n return super()._invoke(invoke_type, **kwargs)\n\n with self._refresh_lock:\n if self._session and self._session.access_jwt and self._should_refresh_session():\n self._refresh_and_set_session()\n\n return super()._invoke(invoke_type, **kwargs)\n\n def _set_session(self, event: SessionEvent, session: SessionResponse) -> None:\n self._set_session_common(session, self._base_url)\n self._call_on_session_change_callbacks(event)\n\n def _get_and_set_session(\n self, login: str, password: str, auth_factor_token: t.Optional[str] = None\n ) -> 'models.ComAtprotoServerCreateSession.Response':\n session = self.com.atproto.server.create_session(\n models.ComAtprotoServerCreateSession.Data(\n identifier=login, password=password, auth_factor_token=auth_factor_token\n ),\n ignore_session_check=True,\n )\n self._set_session(SessionEvent.CREATE, session)\n return session\n\n def _refresh_and_set_session(self) -> 'models.ComAtprotoServerRefreshSession.Response':\n if not self._session or not self._session.refresh_jwt:\n raise LoginRequiredError\n\n refresh_session = self.com.atproto.server.refresh_session(\n headers=self._get_refresh_auth_headers(), ignore_session_check=True\n )\n self._set_session(SessionEvent.REFRESH, refresh_session)\n\n return refresh_session\n\n def _import_session_string(self, session_string: str) -> Session:\n import_session = Session.decode(session_string)\n self._set_session(SessionEvent.IMPORT, import_session)\n\n return import_session\n\n def login(\n self,\n login: t.Optional[str] = None,\n password: t.Optional[str] = None,\n session_string: t.Optional[str] = None,\n auth_factor_token: t.Optional[str] = None,\n ) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Authorize a client and get profile info.\n\n Args:\n login: Handle/username of the account.\n password: Main or app-specific password of the account.\n session_string: Session string (use :py:attr:`~export_session_string` to get it).\n auth_factor_token: Auth factor token (for Email 2FA).\n\n Note:\n Either `session_string` or `login` and `password` should be provided.\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile information.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if session_string:\n session = self._import_session_string(session_string)\n elif login and password:\n session = self._get_and_set_session(login, password, auth_factor_token)\n else:\n raise ValueError('Either session_string or login and password should be provided.')\n\n self.me = self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=session.handle))\n return self.me\n\n def send_post(\n self,\n text: t.Union[str, TextBuilder],\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n embed: t.Optional[\n t.Union[\n 'models.AppBskyEmbedImages.Main',\n 'models.AppBskyEmbedExternal.Main',\n 'models.AppBskyEmbedRecord.Main',\n 'models.AppBskyEmbedRecordWithMedia.Main',\n 'models.AppBskyEmbedVideo.Main',\n ]\n ] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n The default language is ``en``.\n Available languages are defined in :py:mod:`atproto.xrpc_client.models.languages`.\n\n Args:\n text: Text of the post.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n embed: Embed models that should be attached to the post.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if isinstance(text, TextBuilder):\n facets = text.build_facets()\n text = text.build_text()\n\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n if not langs:\n langs = [DEFAULT_LANGUAGE_CODE1]\n\n record = models.AppBskyFeedPost.Record(\n created_at=self.get_current_time_iso(),\n text=text,\n reply=reply_to,\n embed=embed,\n langs=langs,\n facets=facets,\n )\n return self.app.bsky.feed.post.create(repo, record)\n\n def delete_post(self, post_uri: str) -> bool:\n \"\"\"Delete post.\n\n Args:\n post_uri: AT URI of the post.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(post_uri)\n return self.app.bsky.feed.post.delete(uri.hostname, uri.rkey)\n\n def send_images(\n self,\n text: t.Union[str, TextBuilder],\n images: t.List[bytes],\n image_alts: t.Optional[t.List[str]] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratios: t.Optional[t.List['models.AppBskyEmbedDefs.AspectRatio']] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with multiple attached images (up to 4 images).\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n images: List of binary images to attach. The length must be less than or equal to 4.\n image_alts: List of text version of the images.\n The length should be shorter than or equal to the length of `images`.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratios: List of aspect ratios of the images.\n The length should be shorter than or equal to the length of `images`.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if image_alts is None:\n image_alts = [''] * len(images)\n else:\n # padding with empty string if len is insufficient\n diff = len(images) - len(image_alts)\n image_alts = image_alts + [''] * diff # [''] * (minus) => []\n\n if image_aspect_ratios is None:\n aligned_image_aspect_ratios = [None] * len(images)\n else:\n # padding with None if len is insufficient\n diff = len(images) - len(image_aspect_ratios)\n aligned_image_aspect_ratios = image_aspect_ratios + [None] * diff\n\n uploads = [self.upload_blob(image) for image in images]\n embed_images = [\n models.AppBskyEmbedImages.Image(alt=alt, image=upload.blob, aspect_ratio=aspect_ratio)\n for alt, upload, aspect_ratio in zip(image_alts, uploads, aligned_image_aspect_ratios)\n ]\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedImages.Main(images=embed_images),\n langs=langs,\n facets=facets,\n )\n\n def send_image(\n self,\n text: t.Union[str, TextBuilder],\n image: bytes,\n image_alt: str,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n image_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached image.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n image: Binary image to attach.\n image_alt: Text version of the image.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n image_aspect_ratio: Aspect ratio of the image.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n image_aspect_ratios = None\n if image_aspect_ratio:\n image_aspect_ratios = [image_aspect_ratio]\n\n return self.send_images(\n text,\n images=[image],\n image_alts=[image_alt],\n profile_identify=profile_identify,\n reply_to=reply_to,\n langs=langs,\n facets=facets,\n image_aspect_ratios=image_aspect_ratios,\n )\n\n def send_video(\n self,\n text: t.Union[str, TextBuilder],\n video: bytes,\n video_alt: t.Optional[str] = None,\n profile_identify: t.Optional[str] = None,\n reply_to: t.Optional['models.AppBskyFeedPost.ReplyRef'] = None,\n langs: t.Optional[t.List[str]] = None,\n facets: t.Optional[t.List['models.AppBskyRichtextFacet.Main']] = None,\n video_aspect_ratio: t.Optional['models.AppBskyEmbedDefs.AspectRatio'] = None,\n ) -> 'models.AppBskyFeedPost.CreateRecordResponse':\n \"\"\"Send post with attached video.\n\n Note:\n If `profile_identify` is not provided will be sent to the current profile.\n\n Args:\n text: Text of the post.\n video: Binary video to attach.\n video_alt: Text version of the video.\n profile_identify: Handle or DID. Where to send post.\n reply_to: Root and parent of the post to reply to.\n langs: List of used languages in the post.\n facets: List of facets (rich text items).\n video_aspect_ratio: Aspect ratio of the video.\n\n Returns:\n :obj:`models.AppBskyFeedPost.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n if video_alt is None:\n video_alt = ''\n\n upload = self.upload_blob(video)\n\n return self.send_post(\n text,\n profile_identify=profile_identify,\n reply_to=reply_to,\n embed=models.AppBskyEmbedVideo.Main(video=upload.blob, alt=video_alt, aspect_ratio=video_aspect_ratio),\n langs=langs,\n facets=facets,\n )\n\n def get_post(\n self, post_rkey: str, profile_identify: t.Optional[str] = None, cid: t.Optional[str] = None\n ) -> 'models.AppBskyFeedPost.GetRecordResponse':\n \"\"\"Get post.\n\n Args:\n post_rkey: ID (slug) of the post.\n profile_identify: Handler or DID. Who created the post.\n cid: The CID of the version of the post.\n\n Returns:\n :obj:`models.AppBskyFeedPost.GetRecordResponse`: Post.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if profile_identify:\n repo = profile_identify\n\n if not repo:\n raise LoginRequiredError\n\n return self.app.bsky.feed.post.get(repo, post_rkey, cid)\n\n def get_posts(self, uris: t.List[str]) -> 'models.AppBskyFeedGetPosts.Response':\n \"\"\"Get posts.\n\n Args:\n uris: Uris (AT URI).\n\n Example:\n .. code-block:: python\n\n client.get_posts(['at://did:plc:kvwvcn5iqfooopmyzvb4qzba/app.bsky.feed.post/3k2yihcrp6f2c'])\n\n Returns:\n :obj:`models.AppBskyFeedGetPosts.Response`: Posts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_posts(\n models.AppBskyFeedGetPosts.Params(\n uris=uris,\n )\n )\n\n def get_post_thread(\n self, uri: str, depth: t.Optional[int] = None, parent_height: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetPostThread.Response':\n \"\"\"Get post thread.\n\n Args:\n uri: AT URI.\n depth: Depth of the thread.\n parent_height: Height of the parent post.\n\n Returns:\n :obj:`models.AppBskyFeedGetPostThread.Response`: Post thread.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_post_thread(\n models.AppBskyFeedGetPostThread.Params(\n uri=uri,\n depth=depth,\n parent_height=parent_height,\n )\n )\n\n def get_likes(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetLikes.Response':\n \"\"\"Get likes.\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetLikes.Response`: Likes.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_likes(\n models.AppBskyFeedGetLikes.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_reposted_by(\n self, uri: str, cid: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetRepostedBy.Response':\n \"\"\"Get reposted by (reposts).\n\n Args:\n uri: AT URI.\n cid: CID.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetRepostedBy.Response`: Reposts.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_reposted_by(\n models.AppBskyFeedGetRepostedBy.Params(uri=uri, cid=cid, cursor=cursor, limit=limit)\n )\n\n def get_timeline(\n self, algorithm: t.Optional[str] = None, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyFeedGetTimeline.Response':\n \"\"\"Get home timeline.\n\n Args:\n algorithm: Algorithm.\n cursor: Cursor of the last like in the previous page.\n limit: Limit count of likes to return.\n\n Returns:\n :obj:`models.AppBskyFeedGetTimeline.Response`: Home timeline.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_timeline(\n models.AppBskyFeedGetTimeline.Params(algorithm=algorithm, cursor=cursor, limit=limit)\n )\n\n def get_author_feed(\n self,\n actor: str,\n cursor: t.Optional[str] = None,\n filter: t.Optional[str] = None,\n limit: t.Optional[int] = None,\n include_pins: bool = False,\n ) -> 'models.AppBskyFeedGetAuthorFeed.Response':\n \"\"\"Get author (profile) feed.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the last like in the previous page.\n filter: Filter.\n limit: Limit count of likes to return.\n include_pins: Include pins.\n\n Returns:\n :obj:`models.AppBskyFeedGetAuthorFeed.Response`: Feed.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.feed.get_author_feed(\n models.AppBskyFeedGetAuthorFeed.Params(\n actor=actor, cursor=cursor, filter=filter, include_pins=include_pins, limit=limit\n )\n )\n\n def like(self, uri: str, cid: str) -> 'models.AppBskyFeedLike.CreateRecordResponse':\n \"\"\"Like the record.\n\n Args:\n cid: The CID of the record.\n uri: The URI of the record.\n\n Note:\n Record could be post, custom feed, etc.\n\n Returns:\n :obj:`models.AppBskyFeedLike.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedLike.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.like.create(repo, record)\n\n def unlike(self, like_uri: str) -> bool:\n \"\"\"Unlike the post.\n\n Args:\n like_uri: AT URI of the like.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(like_uri)\n return self.app.bsky.feed.like.delete(uri.hostname, uri.rkey)\n\n def repost(self, uri: str, cid: str) -> 'models.AppBskyFeedRepost.CreateRecordResponse':\n \"\"\"Repost post.\n\n Args:\n cid: The CID of the post.\n uri: The URI of the post.\n\n Returns:\n :obj:`models.AppBskyFeedRepost.CreateRecordResponse`: Reference to the reposted record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n subject_obj = models.ComAtprotoRepoStrongRef.Main(cid=cid, uri=uri)\n\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyFeedRepost.Record(created_at=self.get_current_time_iso(), subject=subject_obj)\n return self.app.bsky.feed.repost.create(repo, record)\n\n def unrepost(self, repost_uri: str) -> bool:\n \"\"\"Unrepost the post (delete repost).\n\n Args:\n repost_uri: AT URI of the repost.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(repost_uri)\n return self.app.bsky.feed.repost.delete(uri.hostname, uri.rkey)\n\n def follow(self, subject: str) -> 'models.AppBskyGraphFollow.CreateRecordResponse':\n \"\"\"Follow the profile.\n\n Args:\n subject: DID of the profile.\n\n Returns:\n :obj:`models.AppBskyGraphFollow.CreateRecordResponse`: Reference to the created record.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n repo = self.me and self.me.did\n if not repo:\n raise LoginRequiredError\n\n record = models.AppBskyGraphFollow.Record(created_at=self.get_current_time_iso(), subject=subject)\n return self.app.bsky.graph.follow.create(repo, record)\n\n def unfollow(self, follow_uri: str) -> bool:\n \"\"\"Unfollow the profile.\n\n Args:\n follow_uri: AT URI of the follow.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n uri = AtUri.from_str(follow_uri)\n return self.app.bsky.graph.follow.delete(uri.hostname, uri.rkey)\n\n def get_follows(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollows.Response':\n \"\"\"Get follows of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of follows to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollows.Response`: Follows.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_follows(\n models.AppBskyGraphGetFollows.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_followers(\n self, actor: str, cursor: t.Optional[str] = None, limit: t.Optional[int] = None\n ) -> 'models.AppBskyGraphGetFollowers.Response':\n \"\"\"Get followers of the profile.\n\n Args:\n actor: Actor (handle or DID).\n cursor: Cursor of the next page.\n limit: Limit count of followers to return.\n\n Returns:\n :obj:`models.AppBskyGraphGetFollowers.Response`: Followers.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.get_followers(\n models.AppBskyGraphGetFollowers.Params(actor=actor, cursor=cursor, limit=limit)\n )\n\n def get_profile(self, actor: str) -> 'models.AppBskyActorDefs.ProfileViewDetailed':\n \"\"\"Get profile.\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`models.AppBskyActorDefs.ProfileViewDetailed`: Profile.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profile(models.AppBskyActorGetProfile.Params(actor=actor))\n\n def get_profiles(self, actors: t.List[str]) -> 'models.AppBskyActorGetProfiles.Response':\n \"\"\"Get profiles.\n\n Args:\n actors: List of actors (handles or DIDs).\n\n Returns:\n :obj:`models.AppBskyActorGetProfiles.Response`: Profiles.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.actor.get_profiles(models.AppBskyActorGetProfiles.Params(actors=actors))\n\n def mute(self, actor: str) -> bool:\n \"\"\"Mute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.mute_actor(models.AppBskyGraphMuteActor.Data(actor=actor))\n\n def unmute(self, actor: str) -> bool:\n \"\"\"Unmute actor (profile).\n\n Args:\n actor: Actor (handle or DID).\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.app.bsky.graph.unmute_actor(models.AppBskyGraphUnmuteActor.Data(actor=actor))\n\n def resolve_handle(self, handle: str) -> 'models.ComAtprotoIdentityResolveHandle.Response':\n \"\"\"Resolve the handle.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`models.ComAtprotoIdentityResolveHandle.Response`: Resolved handle (DID).\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.resolve_handle(models.ComAtprotoIdentityResolveHandle.Params(handle=handle))\n\n def update_handle(self, handle: str) -> bool:\n \"\"\"Update the handle.\n\n Args:\n handle: New handle.\n\n Returns:\n :obj:`bool`: Success status.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.identity.update_handle(models.ComAtprotoIdentityUpdateHandle.Data(handle=handle))\n\n def upload_blob(self, data: bytes) -> 'models.ComAtprotoRepoUploadBlob.Response':\n \"\"\"Upload blob.\n\n Args:\n data: Binary data.\n\n Returns:\n :obj:`models.ComAtprotoRepoUploadBlob.Response`: Uploaded blob reference.\n\n Raises:\n :class:`atproto.exceptions.AtProtocolError`: Base exception.\n \"\"\"\n return self.com.atproto.repo.upload_blob(data)\n\n #: Alias for :attr:`unfollow`\n delete_follow = unfollow\n #: Alias for :attr:`unlike`\n delete_like = unlike\n #: Alias for :attr:`unrepost`\n delete_repost = unrepost\n #: Alias for :attr:`send_post`\n post = send_post\n #: Alias for :attr:`delete_post`\n unsend = delete_post\n\n\n# Source: packages/atproto_client/client/methods_mixin/headers.py\n_ATPROTO_PROXY_HEADER = 'atproto-proxy'", "n_chars_compressed": 26335, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_feed_record.py::22": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/models/dot_dict.py", "packages/atproto_client/models/blob_ref.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_feed_record_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 6, "n_files_resolved": 4, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_core/test_uri.py::16": {"resolved_imports": ["packages/atproto_core/exceptions.py", "packages/atproto_core/uri/uri.py"], "used_names": ["AtUri"], "enclosing_function": "test_at_uri_from_str", "extracted_code": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 3867, "extracted_code_full": "# Source: packages/atproto_core/uri/uri.py\nclass AtUri:\n \"\"\"ATP URI Scheme.\n\n Examples:\n Repository: at://alice.host.com\n\n Repository: at://did:plc:bv6ggog3tya2z3vxsub7hnal\n\n Collection: at://alice.host.com/io.example.song\n\n Record: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a\n\n Record Field: at://alice.host.com/io.example.song/3yI5-c1z-cc2p-1a#/title\n \"\"\"\n\n def __init__(\n self,\n host: str,\n pathname: str = '',\n hash_: str = '',\n search_params: t.Optional[t.List[t.Tuple[str, t.Any]]] = None,\n ) -> None:\n if search_params is None:\n search_params = []\n\n if hash_ and not pathname:\n raise InvalidAtUriError('`hash_` cannot be set without `pathname`')\n if search_params and not pathname:\n raise InvalidAtUriError('`search_params` cannot be set without `pathname`')\n\n self.host = host\n self.pathname = pathname\n self.hash = hash_\n self.search_params = search_params\n\n @property\n def protocol(self) -> str:\n \"\"\"Get protocol.\"\"\"\n return 'at://'\n\n @property\n def origin(self) -> str:\n \"\"\"Get origin.\"\"\"\n return f'at://{self.host}'\n\n @property\n def hostname(self) -> str:\n \"\"\"Get hostname.\"\"\"\n return self.host\n\n @property\n def collection(self) -> str:\n \"\"\"Get collection name.\"\"\"\n for part in self.pathname.split('/'):\n if part:\n return part\n\n return ''\n\n @property\n def rkey(self) -> str:\n \"\"\"Get record key (rkey).\"\"\"\n parts = [p for p in self.pathname.split('/') if p]\n if len(parts) > 1:\n return parts[1]\n\n return ''\n\n @property\n def http(self) -> str:\n \"\"\"Convert instance to HTTP URI.\"\"\"\n return str(self)\n\n @property\n def search(self) -> str:\n \"\"\"Get search params.\"\"\"\n return urlencode(self.search_params)\n\n @classmethod\n def make(cls, handle_or_did: str, collection: t.Optional[str] = None, rkey: t.Optional[str] = None) -> 'AtUri':\n \"\"\"Create `AtUri` instance from handle or DID.\"\"\"\n uri = handle_or_did\n\n if collection:\n uri = f'{handle_or_did}/{collection}'\n if rkey:\n uri = f'{uri}/{rkey}'\n\n return cls.from_str(uri)\n\n @classmethod\n def from_str(cls, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from URI.\"\"\"\n groups = re.findall(_ATP_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[3] or '')\n return cls(host=group[1] or '', pathname=group[2] or '', hash_=group[4] or '', search_params=search_params)\n\n @classmethod\n def from_relative_str(cls, base: str, uri: str) -> 'AtUri':\n \"\"\"Create `AtUri` instance from relative URI.\"\"\"\n groups = re.findall(_ATP_RELATIVE_URI_REGEX, uri, re.IGNORECASE)\n if not groups:\n raise InvalidAtUriError\n\n group = groups[0]\n search_params = urlparse.parse_qsl(group[1] or '')\n return cls(host=base, pathname=group[0] or '', hash_=group[2] or '', search_params=search_params)\n\n def __str__(self) -> str:\n path = self.pathname or '/'\n if not path.startswith('/'):\n path = f'/{path}'\n\n query = urlencode(self.search_params)\n if query:\n query = f'?{query}'\n\n hash_ = self.hash\n if hash_ and not hash_.startswith('#'):\n hash_ = f'#{hash_}'\n\n return f'at://{self.host}{path}{query}{hash_}'\n\n def __hash__(self) -> int:\n return hash(str(self))\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, AtUri):\n return hash(self) == hash(other)\n\n return False", "n_chars_compressed": 3867, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_handle_resolver.py::14": {"resolved_imports": ["packages/atproto_identity/exceptions.py", "packages/atproto_identity/handle/resolver.py"], "used_names": ["AsyncHandleResolver", "pytest"], "enclosing_function": "test_handle_resolver", "extracted_code": "# Source: packages/atproto_identity/handle/resolver.py\nclass AsyncHandleResolver(_HandleResolverBase):\n \"\"\"Asynchronous Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.asyncresolver\n self._http_client = httpx.AsyncClient()\n\n async def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = await self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = await self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n async def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = await self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n async def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = await self._dns_resolver.resolve(\n self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout\n )\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n async def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = await self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_imports_parsed": 3, "n_files_resolved": 2, "n_chars_extracted": 2777, "extracted_code_full": "# Source: packages/atproto_identity/handle/resolver.py\nclass AsyncHandleResolver(_HandleResolverBase):\n \"\"\"Asynchronous Handle Resolver.\n\n Args:\n timeout: Request timeout.\n backup_nameservers: Backup nameservers (for DNS resolve).\n \"\"\"\n\n def __init__(\n self,\n timeout: t.Optional[float] = None,\n backup_nameservers: t.Optional[t.List[str]] = None,\n ) -> None:\n self._timeout = timeout\n self._backup_nameservers = backup_nameservers # TODO(MarshalX): implement\n\n self._dns_resolver = dns.asyncresolver\n self._http_client = httpx.AsyncClient()\n\n async def resolve(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID.\n\n Uses DNS and HTTP to resolve handle to DID. The first successful result will be returned.\n\n Resolve order: DNS -> HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n dns_resolve = await self.resolve_dns(handle)\n if dns_resolve:\n return dns_resolve\n\n http_resolve = await self.resolve_http(handle)\n if http_resolve:\n return http_resolve\n\n # TODO(MarshalX): add resolve DNS backup nameservers\n return None\n\n async def ensure_resolve(self, handle: str) -> str:\n \"\"\"Ensure handle is resolved to DID.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID.\n\n Raises:\n :obj:`DidNotFoundError`: Handle not found.\n \"\"\"\n did = await self.resolve(handle)\n if not did:\n raise DidNotFoundError(f'Unable to resolve handle: {handle}')\n\n return did\n\n async def resolve_dns(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using DNS.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n answers = await self._dns_resolver.resolve(\n self._get_qname(handle), _ATPROTO_RECORD_TYPE, lifetime=self._timeout\n )\n except DNSException:\n return None\n\n return self._find_text_record(answers)\n\n async def resolve_http(self, handle: str) -> t.Optional[str]:\n \"\"\"Resolve handle to DID using HTTP.\n\n Args:\n handle: Handle.\n\n Returns:\n :obj:`str`: DID or ``None`` if handle not found.\n \"\"\"\n try:\n response = await self._http_client.get(f'https://{handle}{_ATPROTO_WELL_KNOWN_PATH}', timeout=self._timeout)\n response.raise_for_status()\n return self._get_did_from_text_response(response.text)\n except httpx.HTTPError:\n return None", "n_chars_compressed": 2777, "compression_ratio": 1.0}, "tests/test_atproto_core/test_car.py::9": {"resolved_imports": ["packages/atproto_core/car/car.py"], "used_names": ["CAR"], "enclosing_function": "test_car", "extracted_code": "# Source: packages/atproto_core/car/car.py\nclass CAR:\n \"\"\"CAR file.\"\"\"\n\n def __init__(self, root: CID, blocks: Blocks) -> None:\n self._root = root\n self._blocks = blocks\n\n @property\n def root(self) -> CID:\n \"\"\"Get root.\"\"\"\n return self._root\n\n @property\n def blocks(self) -> Blocks:\n \"\"\"Get blocks.\"\"\"\n return self._blocks\n\n @classmethod\n def from_bytes(cls, data: bytes) -> 'CAR':\n \"\"\"Decode CAR file.\n\n Note:\n You could pass as `data` response of `client.com.atproto.sync.get_repo`, for example.\n And other responses of methods in the `sync` namespace.\n\n Example:\n >>> from atproto import CAR, Client\n >>> client = Client()\n >>> client.login('my-handle', 'my-password')\n >>> repo = client.com.atproto.sync.get_repo({'did': client.me.did})\n >>> car_file = CAR.from_bytes(repo)\n >>> print(car_file.root)\n >>> print(car_file.blocks)\n\n Args:\n data: Content of the CAR file.\n\n Returns:\n :obj:`atproto.CAR`: Parsed CAR file.\n \"\"\"\n header, blocks = libipld.decode_car(data)\n\n roots = header.get('roots')\n if isinstance(roots, list) and len(roots):\n # The first element of the CAR roots metadata array must be the CID of the most relevant Commit object.\n # For a generic export, this is the current (most recent) commit.\n # Additional CIDs may also be present in the roots array, with (for now) undefined meaning or order.\n root: CID = CID.decode(roots[0])\n else:\n raise InvalidCARFile('Invalid CAR file. Expected at least one root.')\n\n blocks = {CID.decode(cid): block for cid, block in blocks.items()}\n return cls(root=root, blocks=blocks)", "n_imports_parsed": 1, "n_files_resolved": 1, "n_chars_extracted": 1861, "extracted_code_full": "# Source: packages/atproto_core/car/car.py\nclass CAR:\n \"\"\"CAR file.\"\"\"\n\n def __init__(self, root: CID, blocks: Blocks) -> None:\n self._root = root\n self._blocks = blocks\n\n @property\n def root(self) -> CID:\n \"\"\"Get root.\"\"\"\n return self._root\n\n @property\n def blocks(self) -> Blocks:\n \"\"\"Get blocks.\"\"\"\n return self._blocks\n\n @classmethod\n def from_bytes(cls, data: bytes) -> 'CAR':\n \"\"\"Decode CAR file.\n\n Note:\n You could pass as `data` response of `client.com.atproto.sync.get_repo`, for example.\n And other responses of methods in the `sync` namespace.\n\n Example:\n >>> from atproto import CAR, Client\n >>> client = Client()\n >>> client.login('my-handle', 'my-password')\n >>> repo = client.com.atproto.sync.get_repo({'did': client.me.did})\n >>> car_file = CAR.from_bytes(repo)\n >>> print(car_file.root)\n >>> print(car_file.blocks)\n\n Args:\n data: Content of the CAR file.\n\n Returns:\n :obj:`atproto.CAR`: Parsed CAR file.\n \"\"\"\n header, blocks = libipld.decode_car(data)\n\n roots = header.get('roots')\n if isinstance(roots, list) and len(roots):\n # The first element of the CAR roots metadata array must be the CID of the most relevant Commit object.\n # For a generic export, this is the current (most recent) commit.\n # Additional CIDs may also be present in the roots array, with (for now) undefined meaning or order.\n root: CID = CID.decode(roots[0])\n else:\n raise InvalidCARFile('Invalid CAR file. Expected at least one root.')\n\n blocks = {CID.decode(cid): block for cid, block in blocks.items()}\n return cls(root=root, blocks=blocks)", "n_chars_compressed": 1861, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_changed_lexicon_compatability.py::55": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py", "packages/atproto_client/exceptions.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_added_new_fields_as_optional", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_core/test_cid.py::65": {"resolved_imports": ["packages/atproto_core/cid/cid.py"], "used_names": ["CID"], "enclosing_function": "test_cid_type_str", "extracted_code": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1357, "extracted_code_full": "# Source: packages/atproto_core/cid/cid.py\nclass CID:\n version: int\n codec: int\n hash: Multihash\n\n _stringified_form: t.Optional[str] = None\n _raw_byte_form: t.Optional[str] = None\n\n @classmethod\n def decode(cls, value: t.Union[str, bytes]) -> 'CID':\n cid = libipld.decode_cid(value)\n\n multihash = Multihash(\n code=cid['hash']['code'],\n size=cid['hash']['size'],\n digest=cid['hash']['digest'],\n )\n\n instance = cls(\n version=cid['version'],\n codec=cid['codec'],\n hash=multihash,\n )\n\n if isinstance(value, str):\n instance._stringified_form = value\n else:\n instance._raw_byte_form = value\n\n return instance\n\n def encode(self) -> str:\n if self._stringified_form is not None:\n return self._stringified_form\n\n self._stringified_form = libipld.encode_cid(self._raw_byte_form)\n return self._stringified_form\n\n def __str__(self) -> str:\n return self.encode()\n\n def __hash__(self) -> int:\n return hash(self.encode())\n\n def __eq__(self, other: t.Any) -> bool:\n if isinstance(other, str):\n return self.encode() == other\n\n if isinstance(other, CID):\n return self.encode() == other.encode()\n\n return False", "n_chars_compressed": 1357, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::83": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink", "get_model_as_dict", "get_or_create"], "enclosing_function": "test_blob_ref_to_ipld_json", "extracted_code": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2964, "extracted_code_full": "# Source: packages/atproto_client/models/__init__.py\nfrom atproto_client.models.utils import (\n create_strong_ref,\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n\n get_model_as_dict,\n get_model_as_json,\n get_or_create,\n is_record_type,\n)\n\n\nclass _Ids:\n AppBskyActorDefs: str = 'app.bsky.actor.defs'\n AppBskyActorGetPreferences: str = 'app.bsky.actor.getPreferences'\n AppBskyActorGetProfile: str = 'app.bsky.actor.getProfile'\n AppBskyActorGetProfiles: str = 'app.bsky.actor.getProfiles'\n\n\n# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2964, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_get_follows.py::38": {"resolved_imports": ["packages/atproto_client/__init__.py", "packages/atproto_client/models/__init__.py"], "used_names": ["get_or_create", "models"], "enclosing_function": "test_get_follows_deserialization", "extracted_code": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_imports_parsed": 4, "n_files_resolved": 2, "n_chars_extracted": 383, "extracted_code_full": "# Source: packages/atproto_client/__init__.py\nfrom atproto_client import models\nfrom atproto_client.client.async_client import AsyncClient\nfrom atproto_client.client.client import Client\nfrom atproto_client.client.session import Session, SessionEvent\n\n__all__ = [\n 'AsyncClient',\n 'Client',\n 'Session',\n 'SessionEvent',\n\n 'Session',\n 'SessionEvent',\n 'models',\n]", "n_chars_compressed": 383, "compression_ratio": 1.0}, "tests/test_atproto_crypto/test_did.py::41": {"resolved_imports": ["packages/atproto_crypto/consts.py", "packages/atproto_crypto/did.py", "packages/atproto_crypto/exceptions.py"], "used_names": ["Multikey", "P256_JWT_ALG", "format_multikey"], "enclosing_function": "test_multikey_p256_compress_decompress", "extracted_code": "# Source: packages/atproto_crypto/consts.py\nP256_JWT_ALG = 'ES256'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_imports_parsed": 4, "n_files_resolved": 3, "n_chars_extracted": 1395, "extracted_code_full": "# Source: packages/atproto_crypto/consts.py\nP256_JWT_ALG = 'ES256'\n\n\n# Source: packages/atproto_crypto/did.py\nclass Multikey:\n jwt_alg: str\n key_bytes: bytes\n\n @staticmethod\n def from_str(multikey: str) -> 'Multikey':\n \"\"\"Create multikey from string.\n\n Args:\n multikey: Multikey.\n\n Returns:\n :obj:`Multikey`: Multikey.\n \"\"\"\n return parse_multikey(multikey)\n\n def to_str(self) -> str:\n \"\"\"Format multikey.\n\n Returns:\n str: Multikey.\n \"\"\"\n return format_multikey(self.jwt_alg, self.key_bytes)\n\ndef format_multikey(jwt_alg: str, key: bytes) -> str:\n \"\"\"Format multikey to multibase.\n\n Compress pubkey and encode with base58btc.\n\n Args:\n jwt_alg: JWT alg.\n key: Key bytes.\n\n Returns:\n str: Multikey in multibase.\n\n Raises:\n :obj:`UnsupportedKeyTypeError`: Unsupported key type.\n \"\"\"\n if jwt_alg == P256_JWT_ALG:\n prefix = P256_DID_PREFIX\n compressed_key_bytes = P256().compress_pubkey(key)\n elif jwt_alg == SECP256K1_JWT_ALG:\n prefix = SECP256K1_DID_PREFIX\n compressed_key_bytes = Secp256k1().compress_pubkey(key)\n else:\n raise UnsupportedKeyTypeError('Unsupported key type')\n\n prefixed_bytes = prefix + compressed_key_bytes\n return bytes_to_multibase(BASE58_MULTIBASE_PREFIX, prefixed_bytes)", "n_chars_compressed": 1395, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_async_atproto_data.py::15": {"resolved_imports": ["packages/atproto_identity/did/resolver.py"], "used_names": ["AsyncDidResolver", "pytest"], "enclosing_function": "test_atproto_data_resolve_atproto_data", "extracted_code": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_imports_parsed": 2, "n_files_resolved": 1, "n_chars_extracted": 1244, "extracted_code_full": "# Source: packages/atproto_identity/did/resolver.py\nclass AsyncDidResolver(_DidResolverBase, AsyncBaseResolver):\n \"\"\"Asynchronous DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['AsyncDidBaseCache'] = None,\n ) -> None:\n super().__init__()\n AsyncBaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': AsyncDidPlcResolver(plc_url, timeout, cache), 'web': AsyncDidWebResolver(timeout)}\n\n async def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n async_base_resolver = t.cast('AsyncBaseResolver', self._get_resolver_method(did))\n return await async_base_resolver.resolve_without_validation(did)", "n_chars_compressed": 1244, "compression_ratio": 1.0}, "tests/test_atproto_client/models/tests/test_blob_ref.py::115": {"resolved_imports": ["packages/atproto_client/models/__init__.py", "packages/atproto_client/models/blob_ref.py", "packages/atproto_core/cid/cid.py"], "used_names": ["BlobRef", "IpldLink"], "enclosing_function": "test_blob_ref_to_json_representation", "extracted_code": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_imports_parsed": 3, "n_files_resolved": 3, "n_chars_extracted": 2275, "extracted_code_full": "# Source: packages/atproto_client/models/blob_ref.py\nclass IpldLink(BaseModel):\n \"\"\"CID representation in JSON.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n link: str = Field(alias='$link')\n\nclass BlobRef(BaseModel):\n \"\"\"Blob reference.\"\"\"\n\n model_config = ConfigDict(extra='allow', populate_by_name=True, strict=True)\n\n mime_type: str = Field(alias='mimeType') #: Mime type.\n size: int #: Size in bytes.\n ref: t.Union[str, bytes, IpldLink] #: CID.\n\n py_type: te.Literal['blob'] = Field(default='blob', alias='$type')\n\n @property\n def cid(self) -> 'CID':\n \"\"\"Get CID.\"\"\"\n if self.is_bytes_representation:\n return CID.decode(self.ref)\n\n return CID.decode(self.ref.link)\n\n @property\n def is_json_representation(self) -> bool:\n \"\"\"Check if it is JSON representation.\n\n Returns:\n True if it is JSON representation.\n \"\"\"\n return isinstance(self.ref, IpldLink)\n\n @property\n def is_bytes_representation(self) -> bool:\n \"\"\"Check if it is bytes representation.\n\n Returns:\n True if it is bytes representation.\n \"\"\"\n return isinstance(self.ref, (str, bytes))\n\n def to_json_representation(self) -> 'BlobRef':\n \"\"\"Get JSON representation.\n\n Note:\n Used in XRPC, etc. where JSON is used.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in JSON representation.\n \"\"\"\n if self.is_json_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref.link))\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=IpldLink(link=self.ref))\n\n def to_bytes_representation(self) -> 'BlobRef':\n \"\"\"Get bytes representation.\n\n Note:\n Used in Firehose, CAR, etc. where bytes are possible.\n\n Warning:\n It returns new instance.\n\n Returns:\n BlobRef in bytes representation.\n \"\"\"\n if self.is_bytes_representation:\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref)\n\n return BlobRef(mime_type=self.mime_type, size=self.size, ref=self.ref.link)", "n_chars_compressed": 2275, "compression_ratio": 1.0}, "tests/test_atproto_identity/test_did_resolver_cache.py::23": {"resolved_imports": ["packages/atproto_identity/cache/in_memory_cache.py", "packages/atproto_identity/did/resolver.py"], "used_names": ["DidInMemoryCache", "DidResolver"], "enclosing_function": "test_did_resolver_cache_with_web_feed", "extracted_code": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass DidInMemoryCache(DidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._cache: t.Dict[str, CachedDid] = {}\n\n def set(self, did: str, document: DidDocument) -> None:\n self._cache[did] = CachedDid(document, _datetime_now())\n\n def refresh(self, did: str, get_doc_callback: 'GetDocCallback') -> None:\n doc = get_doc_callback()\n if doc:\n self.set(did, doc)\n\n def delete(self, did: str) -> None:\n del self._cache[did]\n\n def clear(self) -> None:\n self._cache.clear()\n\n def get(self, did: str) -> t.Optional[CachedDidResult]:\n val = self._cache.get(did)\n if not val:\n return None\n\n now = _datetime_now().timestamp()\n expired = now > val.updated_at.timestamp() + self.max_ttl\n stale = now > val.updated_at.timestamp() + self.stale_ttl\n\n return CachedDidResult(did, val.document, val.updated_at, stale, expired)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_imports_parsed": 2, "n_files_resolved": 2, "n_chars_extracted": 2237, "extracted_code_full": "# Source: packages/atproto_identity/cache/in_memory_cache.py\nclass DidInMemoryCache(DidBaseCache):\n def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:\n super().__init__(*args, **kwargs)\n\n self._cache: t.Dict[str, CachedDid] = {}\n\n def set(self, did: str, document: DidDocument) -> None:\n self._cache[did] = CachedDid(document, _datetime_now())\n\n def refresh(self, did: str, get_doc_callback: 'GetDocCallback') -> None:\n doc = get_doc_callback()\n if doc:\n self.set(did, doc)\n\n def delete(self, did: str) -> None:\n del self._cache[did]\n\n def clear(self) -> None:\n self._cache.clear()\n\n def get(self, did: str) -> t.Optional[CachedDidResult]:\n val = self._cache.get(did)\n if not val:\n return None\n\n now = _datetime_now().timestamp()\n expired = now > val.updated_at.timestamp() + self.max_ttl\n stale = now > val.updated_at.timestamp() + self.stale_ttl\n\n return CachedDidResult(did, val.document, val.updated_at, stale, expired)\n\n\n# Source: packages/atproto_identity/did/resolver.py\nclass DidResolver(_DidResolverBase, BaseResolver):\n \"\"\"DID Resolver.\n\n Supported DID methods: PLC, Web.\n\n Args:\n plc_url: PLC directory URL.\n timeout: Request timeout.\n cache: DID cache.\n \"\"\"\n\n def __init__(\n self,\n plc_url: t.Optional[str] = None,\n timeout: t.Optional[float] = None,\n cache: t.Optional['DidBaseCache'] = None,\n ) -> None:\n super().__init__()\n BaseResolver.__init__(self, cache)\n\n if plc_url is None:\n plc_url = _BASE_PLC_URL\n\n if timeout is None:\n timeout = _DEFAULT_TIMEOUT\n\n self._methods = {'plc': DidPlcResolver(plc_url, timeout, cache), 'web': DidWebResolver(timeout)}\n\n def resolve_without_validation(self, did: str) -> t.Optional[t.Dict[str, t.Any]]:\n \"\"\"Resolve DID without validation.\n\n Args:\n did: DID.\n\n Returns:\n :obj:`dict`: DID document or ``None`` if DID not found.\n \"\"\"\n base_resolver = t.cast('BaseResolver', self._get_resolver_method(did))\n return base_resolver.resolve_without_validation(did)", "n_chars_compressed": 2237, "compression_ratio": 1.0}}} \ No newline at end of file