o
    .j}                     @   s  d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZ ddlmZ e	r:ddlmZ ddlmZmZ d	Zd	Zd	Zd	ZzddlZdd
lmZ ddlmZ dZW n	 ey_   Y nw esz%ddlZdZdZzddlZdZW n	 ey|   Y nw G dd dejZ W n	 ey   Y nw esesz#ddlZdZzddlZdZW n	 ey   Y nw G dd dejZ W n	 ey   Y nw esesedddl!m"Z" ddl#m$Z$ ddl#m%Z& ddl'm(Z( ddl)m*Z* ddl+m,Z, ddl-m.Z. ddl/m0Z0 ddl1m2Z2m3Z3m4Z4 e5dZ6ej7dk rddl8m9Z9 nddlm9Z9 G dd de$Z:d-de;d e
d!e:fd"d#Z%				d.d$e
dB d%e
dB d&e;d e
d!d'f
d(d)Z<d e
d!d*fd+d,Z=dS )/z
Async-first DAVClient implementation for the caldav library.

This module provides the core async CalDAV/WebDAV client functionality.
For sync usage, see the davclient.py wrapper.
    N)Mapping)TracebackType)TYPE_CHECKINGAnyOptional)unquote)CalendarObjectResource)Calendar	PrincipalF)AsyncSession)CaseInsensitiveDictTc                   @   *   e Zd ZdZdeddfddZdd ZdS )	_HttpxBearerAuthz+httpx/httpxyz-compatible bearer token auth.passwordreturnNc                 C   
   || _ d S Nr   selfr    r   K/home/thesage/.local/lib/python3.10/site-packages/caldav/async_davclient.py__init__4      
_HttpxBearerAuth.__init__c                 c       d| j  |jd< |V  d S NzBearer Authorizationr   headersr   requestr   r   r   	auth_flow7      
_HttpxBearerAuth.auth_flow__name__
__module____qualname____doc__strr   r"   r   r   r   r   r   1       r   c                   @   r   )	r   z#httpx-compatible bearer token auth.r   r   Nc                 C   r   r   r   r   r   r   r   r   M   r   r   c                 c   r   r   r   r    r   r   r   r"   P   r#   r$   r%   r   r   r   r   r   J   r+   zAn async HTTP library is required for async_davclient. Install with: pip install niquests  (or: pip install httpxyz  or: pip install httpx))__version__)BaseDAVClient)get_davclient)
FeatureSet)error)to_wire)URL)HTTPBearerAuth)CalendarQueryResultDAVResponsePropfindResultcaldav)      )Selfc                %   @   s  e Zd ZU dZdZedB ed< dZeed< dZ	e
ed< 																	d{dedB dedB d	edB d
edB dedB dedB dedB de
eB deeeef B dB deeef dB de
deeB eB dB de
de
de
dB dedB dedB ddf$ddZd|ddZdefddZdedB dedB d edB ddfd!d"Zd|d#d$Ze		d}d%ed&edB d'eeef dB deeef fd(d)Z	*			+d~ded%ed,edeeef dB d-edefd.d/Z	*		dded%ed,edeeef dB def
d0d1Z			+		ddedB d,ed&edeeef dB d2e e dB defd3d4Z!			+	ddedB d,ed&edB deeef dB def
d5d6Z"		d}dedB deeef dB defd7d8Z#		dded,edeeef dB defd9d:Z$		dded,edeeef dB defd;d<Z%		dded,edeeef dB defd=d>Z&	dded,edeeef dB defd?d@Z'	dded,edeeef dB defdAdBZ(	ddedeeef dB defdCdDZ)								E	ddedB dFedB dGedB dHe
dIe
dJe
dKe
d&edeeef dB defdLdMZ*			E	ddedB dNe e dB d&edeeef dB def
dOdPZ+				E	ddedB dQedB d2e e dB d&edeeef dB defdRdSZ,dTdU Z-dVdW Z.ddXe e dB ddfdYdZZ/dd\d]Z0dd^e1d[ de d_ fd`daZ2							ddbd_dHe
dIe
dJe
dFedB dGedB dce
dB dKe
ddede de fdfdgZ3ddhedB de d[ fdidjZ4ddhedB de d[ fdkdlZ5ddmdnZ6dedB fdodpZ7de
fdqdrZ8de
fdsdtZ9dedB fdudvZ:de
fdwdxZ;de
fdydzZ<dS )AsyncDAVClienta  
    Async WebDAV/CalDAV client.

    This is the core async implementation. For sync usage, see DAVClient
    in davclient.py which provides a thin wrapper around this class.

    The recommended way to create a client is via get_davclient():
        async with await get_davclient(url="...", username="...", password="...") as client:
            principal = await client.get_principal()
    NproxyurlF	huge_tree Tusernamer   auth	auth_typetimeoutssl_verify_certssl_certr   featuresenable_rfc6764require_tlsrate_limit_handlerate_limit_default_sleeprate_limit_max_sleepr   c              	   C   s0  |
pi }
ddl m} ||}t|tr|| _nt|| _|| _d| _|| _| jdur5d| jvr5d| j | _|| _|	| _	|| _
z| jdoHtpHt| _W n ttfyY   d| _Y nw |   ddlm} ||| j|pkd	||||d
\}}|rz|sz|}t|| _d}d}| jjrt| jj}| jjrt| jj}|dur|n|| _|dur|n|| _| j | _|| _|| _| js| jr| | jg | j| _| j
| _| j| _| j	| _ ddt! i| _"| j"#|
 | jdt$}|du r|r|%drd}d|v r|d }d|v r
|d }nd}|| _&|| _'|| _(dS )ai  
        Initialize an async DAV client.

        Args:
            url: CalDAV server URL, domain, or email address.
            proxy: Proxy server (e.g. http://proxy.example.com:8080).
            username: Username for authentication.
            password: Password for authentication.
            auth: Custom auth object (httpx.Auth or niquests AuthBase).
            auth_type: Auth type ('bearer', 'digest', or 'basic').
            timeout: Request timeout in seconds.
            ssl_verify_cert: SSL certificate verification (bool or CA bundle path).
            ssl_cert: Client SSL certificate (path or (cert, key) tuple).
            headers: Additional headers for all requests.
            huge_tree: Enable XMLParser huge_tree for large events (security consideration).
            features: FeatureSet for server compatibility workarounds.
            enable_rfc6764: Enable RFC6764 DNS-based service discovery.
            require_tls: Require TLS for discovered services (security consideration).
            rate_limit_handle: When True, automatically sleep and retry on 429/503
                responses. When None (default), auto-detected from server features.
                When False, raise RateLimitError immediately.
            rate_limit_default_sleep: Fallback sleep seconds when the server's 429
                response omits a Retry-After header. None (default) means raise
                rather than sleeping when no Retry-After is provided.
            rate_limit_max_sleep: Cap on sleep duration in seconds regardless of
                server's Retry-After value. None (default) means no cap.
        r   )resolve_featuresNz://zhttp://http.multiplexingF)	_auto_url
   )rC   rD   rG   r@   rH   z
User-Agentzcaldav-async/z
rate-limitenableTdefault_sleep	max_sleep))caldav.configrL   
isinstancer/   rF   r>   _http2_proxy_ssl_verify_cert	_ssl_cert_timeoutis_supported_H2_AVAILABLE_USE_NIQUESTS	TypeErrorAttributeError_create_sessioncaldav.davclientrN   r2   	objectifyr=   r@   r   r   unauthrA   rB   build_auth_objectr<   rC   rD   rE   r,   r   updatedictgetrI   rJ   rK   )r   r=   r<   r@   r   rA   rB   rC   rD   rE   r   r>   rF   rG   rH   rI   rJ   rK   rL   rN   url_strdiscovered_usernameurl_usernameurl_password
rate_limitr   r   r   r      s   /








zAsyncDAVClient.__init__c                 C   s   t r+| jpd| jdur| jnd| j| jd}| jdur | j|d< tjdi || _dS zt	| jp1dd| _W dS  t
yE   t	 | _Y dS w )z?Create or recreate the async HTTP client with current settings.FNT)http2verifycertrC   r<   )multiplexedr   )
_USE_HTTPXrU   rW   rX   rY   rV   httpxAsyncClientsessionr   r]   )r   client_kwargsr   r   r   r_     s   

zAsyncDAVClient._create_sessionc                    s   | S )zAsync context manager entry.r   r   r   r   r   
__aenter__&  s   zAsyncDAVClient.__aenter__exc_typeexc_valexc_tbc                    s   |   I dH  dS )zAsync context manager exit.N)close)r   rw   rx   ry   r   r   r   	__aexit__*  s   zAsyncDAVClient.__aexit__c                    s<   t | drtr| j I dH  dS | j I dH  dS dS )zClose the async client.rs   N)hasattrrp   rs   acloserz   ru   r   r   r   rz   3  s   
zAsyncDAVClient.closemethoddepthextra_headersc                 C   s:   i }|durt ||d< | dv rd|d< |r|| |S )a  
        Build headers for WebDAV methods.

        Args:
            method: HTTP method name.
            depth: Depth header value (for PROPFIND/REPORT).
            extra_headers: Additional headers to merge.

        Returns:
            Dictionary of headers.
        NDepth)REPORTPROPFIND	PROPPATCH
MKCALENDARMKCOLz application/xml; charset="utf-8"Content-Type)r*   rd   )r~   r   r   r   r   r   r   _build_method_headers;  s   
z$AsyncDAVClient._build_method_headersGETr   bodyrate_limit_time_sleptc                    s   z|  ||||I dH W S  tjy[ } zA| js t|j| j| j}|r,||d 7 }|du s:| jdur;|| jkr; t	|I dH  | 
|||||| I dH W  Y d}~S d}~ww )a  
        Send an async HTTP request, with optional rate-limit sleep-and-retry.

        Catches RateLimitError from _async_request. When rate_limit_handle is
        True and a usable sleep duration is available, sleeps then retries with
        adaptive backoff (each retry adds half the already-slept time). Stops
        retrying when rate_limit_max_sleep is exceeded or no sleep duration is
        available. Otherwise re-raises immediately.
        N   )_async_requestr0   RateLimitErrorrI   compute_sleep_secondsretry_after_secondsrJ   rK   asynciosleepr!   )r   r=   r~   r   r   r   esleep_secondsr   r   r   r!   \  s.   

zAsyncDAVClient.requestc                    sf  |  ||||\}}tr!|t||rt|nd|| j| jd}n%d}| jdur.|j| ji}|t||r8t|nd|| j| j|| j| j	d	}z^| j
jdi |I dH }	trX|	jn|	j}
td|	j d|
  |	jdkrd| jdd	v r| jsd
}|	jdrdd | |	jd D }|r|dd|7 }t| t|	| }W n ty.   | js| js tr| j
jdt||| jdI dH }	n"d}| jdur|j| ji}| j
jdt||| j|| j| j	dI dH }	tr|	jn|	j}
td|	j d|
  |	jdkr'|	jdr'| |	jd }| | | j|d< | j
jdi |I dH }	t|	| }Y nw t|	jt||	jd | |	j|	jrY| |	jd  | ||||I dH S |	jdkrd|	jv r| jr| j j!ddddu r| " I dH  d| _#| $  | j %dd | t||||I dH S |j&dv r| 't|| tj(rt)||||| |S )z
        Async HTTP request implementation with auth negotiation.

        Handles connection-abort workaround, 429/503 rate-limit detection,
        and 401 auth negotiation (including HTTP/2 fallback).
        N)r~   r=   contentr   rA   rC   )	r~   r=   datar   rA   rC   proxiesrm   rn   zserver responded with    z	text/htmlr   r?   zNo authentication object was provided. HTML was returned when probing the server for supported authentication types. To avoid logging errors, consider passing the auth_type connection parameterzWWW-Authenticatec                 S   s   g | ]}|d v r|qS ))basicdigestbearerr   ).0tr   r   r   
<listcomp>  s
    z1AsyncDAVClient._async_request.<locals>.<listcomp>z#
Supported authentication types: {}z, r   )r~   r=   r   rC   )r~   r=   r   rC   r   rm   rn   z+auth type detection: server responded with rA   zRetry-AfterrM   F)return_defaults)r   i  r   )*_prepare_requestrp   r*   r1   rA   rC   r<   schemerD   rE   rs   r!   reason_phrasereasonlogdebugstatus_coder   rf   extract_auth_typesformatjoinwarningr5   	Exceptionr   rc   r0   raise_if_rate_limited_should_negotiate_auth_build_auth_from_401r   rF   rZ   rz   rU   r_   set_featurestatus_raise_authorization_errordebug_dump_communication_dump_communication)r   r=   r~   r   r   url_objcombined_headersrequest_kwargsr   rr   msg
auth_typesresponser   r   r   r     s   




	

%zAsyncDAVClient._async_requestpropsc                    sj   |dur|s|  |d}| d||}| |pt| jd||I dH }|jdv r3|jr3| |_	|S )a  
        Send a PROPFIND request.

        Args:
            url: Target URL (defaults to self.url).
            body: XML properties request (legacy, use props instead).
            depth: Maximum recursion depth.
            headers: Additional headers.
            props: List of property names to request (uses protocol layer).

        Returns:
            DAVResponse with results attribute containing parsed PropfindResult list.
        Nutf-8r         )
_build_propfind_bodydecoder   r!   r*   r=   r   _rawparse_propfindresults)r   r=   r   r   r   r   final_headersr   r   r   r   propfind  s    
zAsyncDAVClient.propfindc                    s0   |  d||}| |pt| jd||I dH S )a~  
        Send a REPORT request.

        Args:
            url: Target URL (defaults to self.url).
            body: XML report request.
            depth: Maximum recursion depth. None means don't send Depth header
                (required for calendar-multiget per RFC 4791 section 7.9).
            headers: Additional headers.

        Returns:
            DAVResponse
        r   N)r   r!   r*   r=   )r   r=   r   r   r   r   r   r   r   report-  s    zAsyncDAVClient.reportc                    s"   |  |p	t| jdd|I dH S )z
        Send an OPTIONS request.

        Args:
            url: Target URL (defaults to self.url).
            headers: Additional headers.

        Returns:
            DAVResponse
        OPTIONSr?   N)r!   r*   r=   r   r=   r   r   r   r   optionsD  s    zAsyncDAVClient.optionsc                    &   | j d|d}| |d||I dH S )z
        Send a PROPPATCH request.

        Args:
            url: Target URL (required).
            body: XML property update request.
            headers: Additional headers.

        Returns:
            DAVResponse
        r   r   Nr   r!   r   r=   r   r   r   r   r   r   	proppatchW     zAsyncDAVClient.proppatchc                    r   )a0  
        Send a MKCOL request.

        MKCOL creates a WebDAV collection. For CalDAV, use mkcalendar instead.

        Args:
            url: Target URL (required).
            body: XML request (usually empty).
            headers: Additional headers.

        Returns:
            DAVResponse
        r   r   Nr   r   r   r   r   mkcolk  s   zAsyncDAVClient.mkcolc                    r   )z
        Send a MKCALENDAR request.

        Args:
            url: Target URL (required).
            body: XML request (usually contains calendar properties).
            headers: Additional headers.

        Returns:
            DAVResponse
        r   r   Nr   r   r   r   r   
mkcalendar  r   zAsyncDAVClient.mkcalendarc                       |  |d||I dH S )z
        Send a PUT request.

        Args:
            url: Target URL (required).
            body: Request body (e.g., iCalendar data).
            headers: Additional headers.

        Returns:
            DAVResponse
        PUTNr!   r   r=   r   r   r   r   r   put     zAsyncDAVClient.putc                    r   )z
        Send a POST request.

        Args:
            url: Target URL (required).
            body: Request body.
            headers: Additional headers.

        Returns:
            DAVResponse
        POSTNr   r   r   r   r   post  r   zAsyncDAVClient.postc                    s   |  |dd|I dH S )z
        Send a DELETE request.

        Args:
            url: Target URL (required).
            headers: Additional headers.

        Returns:
            DAVResponse
        DELETEr?   Nr   r   r   r   r   delete  s   zAsyncDAVClient.delete   startendeventtodojournalexpandc
                    sn   | j ||||||d\}
}| d||	}| |pt| jd|
d|I dH }|jdv r5|jr5| |_	|S )aR  
        Execute a calendar-query REPORT to search for calendar objects.

        Args:
            url: Target calendar URL (defaults to self.url).
            start: Start of time range filter.
            end: End of time range filter.
            event: Include events (VEVENT).
            todo: Include todos (VTODO).
            journal: Include journals (VJOURNAL).
            expand: Expand recurring events.
            depth: Search depth.
            headers: Additional headers.

        Returns:
            DAVResponse with results containing List[CalendarQueryResult].
        )r   r   r   r   r   r   r   r   Nr   )
_build_calendar_query_bodyr   r!   r*   r=   r   r   r   parse_calendar_queryr   )r   r=   r   r   r   r   r   r   r   r   r   _r   r   r   r   r   calendar_query  s    
	

zAsyncDAVClient.calendar_queryhrefsc                    sb   |  |pg }| d||}| |pt| jd|d|I dH }|jdv r/|jr/| |_	|S )a  
        Execute a calendar-multiget REPORT to fetch specific calendar objects.

        Args:
            url: Target calendar URL (defaults to self.url).
            hrefs: List of object URLs to retrieve.
            depth: Search depth.
            headers: Additional headers.

        Returns:
            DAVResponse with results containing List[CalendarQueryResult].
        r   r   Nr   )
_build_calendar_multiget_bodyr   r!   r*   r=   r   r   r   r   r   )r   r=   r   r   r   r   r   r   r   r   r   calendar_multiget   s   

z AsyncDAVClient.calendar_multiget
sync_tokenc           
         sp   | j ||d}| d||}| |pt| jd|d|I dH }|jdv r6|jr6| }	|	j	|_
|	j|_|S )a  
        Execute a sync-collection REPORT for efficient synchronization.

        Args:
            url: Target calendar URL (defaults to self.url).
            sync_token: Previous sync token (None for initial sync).
            props: Properties to include in response.
            depth: Search depth.
            headers: Additional headers.

        Returns:
            DAVResponse with results containing SyncCollectionResult.
        )r   r   r   r   Nr   )_build_sync_collection_bodyr   r!   r*   r=   r   r   r   parse_sync_collectionchangedr   r   )
r   r=   r   r   r   r   r   r   r   sync_resultr   r   r   sync_collection  s   
zAsyncDAVClient.sync_collectionc                 C   s
   |  |S r   )_async_value_or_coroutiner   valuer   r   r   _value_or_coroutineB  r   z"AsyncDAVClient._value_or_coroutinec                    s   |S r   r   r   r   r   r   r   E  s   z(AsyncDAVClient._async_value_or_coroutiner   c                 C   s   |  |}|dkrtrt| j| _dS t| j| _dS |dkr<tr,t| j| j| _dS ddl	m
} || j| j| _dS |dkr]trMt| j| j| _dS ddl	m} || j| j| _dS |rgtd| dS )	a!  Build authentication object for the httpx/niquests library.

        Uses shared auth type selection logic from BaseDAVClient, then
        creates the appropriate auth object for this HTTP library.

        Args:
            auth_types: List of acceptable auth types from server.
        r   r   r   )AsyncHTTPDigestAuthr   )HTTPBasicAuthzUnsupported auth type: N)_select_auth_typerp   r   r   rA   r3   rq   
DigestAuthr@   niquests.authr   	BasicAuthr   r0   AuthorizationError)r   r   rB   r   r   r   r   r   rc   J  s$   

z AsyncDAVClient.build_auth_objectr
   c                    sx   ddl m} | jt| jdgddI dH }d}|jr-|jD ]}|jd}|r,|} nq|s4t| j}|| |d}|S )a  Get the principal (user) for this CalDAV connection.

        This method fetches the current-user-principal from the server and returns
        a Principal object that can be used to access calendars and other resources.

        Returns:
            Principal object for the authenticated user.

        Example:
            async with await get_davclient(url="...", username="...", password="...") as client:
                principal = await client.get_principal()
                calendars = await client.get_calendars(principal)
        r   )r
   z{DAV:}current-user-principalr   r   N)clientr=   )caldav.collectionr
   r   r*   r=   r   
propertiesrf   )r   r
   r   principal_urlresultcup	principalr   r   r   get_principalp  s&   

zAsyncDAVClient.get_principalr  r	   c                    s   ddl m  ddl m} ddl m} |du r I dH }jt|jjddI dH }||j	}|s6g S 
|}j|jddI dH }||j	} fdd	|D S )
a'  Get all calendars for the given principal.

        This method fetches calendars from the principal's calendar-home-set
        and returns a list of Calendar objects.

        Args:
            principal: Principal object (if None, fetches principal first)

        Returns:
            List of Calendar objects.

        Example:
            principal = await client.get_principal()
            calendars = await client.get_calendars(principal)
            for cal in calendars:
                print(f"Calendar: {cal.get_display_name()}")
        r   )r	   )'_extract_calendar_home_set_from_results)(_extract_calendars_from_propfind_resultsNr   r   c                    s"   g | ]} |j |j|jd qS ))r   r=   nameid)r=   r  cal_id)r   infor	   r   r   r   r     s    z0AsyncDAVClient.get_calendars.<locals>.<listcomp>)r   r	   r  r  r  r   r*   r=   CALENDAR_HOME_SET_PROPSr   _make_absolute_urlCALENDAR_LIST_PROPS)r   r  extract_home_setextract_calendarsr   calendar_home_urlcalendar_infosr   r  r   get_calendars  s0   


zAsyncDAVClient.get_calendarscalendarinclude_completedkwargsr   c	                    sL   ddl m}
 |
||||||d}|dur||_|j|fi |	I dH }|S )a  Search a calendar for events, todos, or journals.

        This method provides a clean interface to calendar search using the
        operations layer for building queries and processing results.

        Args:
            calendar: Calendar to search
            event: Search for events (VEVENT)
            todo: Search for todos (VTODO)
            journal: Search for journals (VJOURNAL)
            start: Start of date range
            end: End of date range
            include_completed: Include completed todos (default: False for todos)
            expand: Expand recurring events
            **kwargs: Additional search parameters

        Returns:
            List of Event/Todo/Journal objects.

        Example:
            # Get all events in January 2024
            events = await client.search_calendar(
                calendar,
                event=True,
                start=datetime(2024, 1, 1),
                end=datetime(2024, 1, 31),
            )

            # Get pending todos
            todos = await client.search_calendar(
                calendar,
                todo=True,
                include_completed=False,
            )
        r   )CalDAVSearcher)r   r   r   r   r   r   N)caldav.searchr  r  async_search)r   r  r   r   r   r   r   r  r   r  r  searcherr   r   r   r   search_calendar  s   /	zAsyncDAVClient.search_calendarr  c                    s\   |  |}| t| j|I dH }|jdkr't|j d|j d|j | 	|
 S )a=  
        Search for principals on the server.

        Instead of returning the current logged-in principal, this method
        attempts to query for all principals (or principals matching a name).
        This may or may not work depending on the permissions and
        implementation of the calendar server.

        Args:
            name: Optional name filter to search for specific principals

        Returns:
            List of Principal objects found on the server

        Raises:
            ReportError: If the server doesn't support principal search
        Ni,  r   z - )_build_principal_search_queryr   r*   r=   r   r0   ReportErrorr   raw _parse_principal_search_response_find_objects_and_props)r   r  r   r   r   r   r   search_principals  s   

 z AsyncDAVClient.search_principalsc                    s,   ddl }|jdtdd | j|dI dH S )z
        Deprecated. Use :meth:`search_principals` instead.

        This method searches for principals on the server.
        r   Nz;principals() is deprecated, use search_principals() insteadr   )
stacklevelr  )warningswarnDeprecationWarningr"  )r   r  r%  r   r   r   
principals-  s   zAsyncDAVClient.principalsc                       |   I dH S )z
        Legacy method. Use :meth:`get_principal` for new code.

        Returns the Principal object for the authenticated user.
        N)r  ru   r   r   r   r  <     zAsyncDAVClient.principalc                    s\   z|   I dH }| |jI dH }W n ty'   | t| jI dH }Y nw |jdS )z
        Check if the server supports DAV.

        Returns the DAV header from an OPTIONS request, or None if not supported.
        NDAV)r  r   r=   r   r*   r   rf   )r   r  r   r   r   r   check_dav_supportD  s   z AsyncDAVClient.check_dav_supportc                        |   I dH }|duod|v S )z
        Check if the server supports CalDAV.

        Returns True if the server indicates CalDAV support in DAV header.
        Nzcalendar-accessr,  r   
dav_headerr   r   r   check_cdav_supportQ     z!AsyncDAVClient.check_cdav_supportc                    r-  )z
        Check if the server supports RFC6638 scheduling.

        Returns True if the server indicates scheduling support in DAV header.
        Nzcalendar-auto-scheduler.  r/  r   r   r   check_scheduling_supportZ  r2  z'AsyncDAVClient.check_scheduling_supportc                    r)  )zl
        Check if the server supports DAV.

        This is an alias for :meth:`check_dav_support`.
        Nr.  ru   r   r   r   supports_davc  r*  zAsyncDAVClient.supports_davc                    r)  )zp
        Check if the server supports CalDAV.

        This is an alias for :meth:`check_cdav_support`.
        N)r1  ru   r   r   r   supports_caldavk  r*  zAsyncDAVClient.supports_caldavc                    r)  )z
        Check if the server supports RFC6638 scheduling.

        This is an alias for :meth:`check_scheduling_support`.
        N)r3  ru   r   r   r   supports_schedulings  r*  z"AsyncDAVClient.supports_scheduling)r?   NNNNNNTNNFNTTNNN)r   N)NN)r   r?   Nr   )r   r?   N)Nr?   r   NN)Nr?   r   N)r?   Nr   )	NNNFFFFr   N)NNr   N)NNNr   N)r   r
   )FFFNNNF)=r&   r'   r(   r)   r<   r*   __annotations__r=   r2   r>   boolr   inttupler   r/   re   r   r_   r:   rv   typeBaseExceptionr   r{   rz   staticmethodr   floatr5   r!   r   listr   r   r   r   r   r   r   r   r   r   r   r   r   r   rc   r  r   r  r  r"  r(  r  r,  r1  r3  r4  r5  r6  r   r   r   r   r;   p   s  
 	

 


	
#
*
 

#







	

3

!

#
&)=	

B
		r;   prober  r   c              
      s   t tfi |}|du rtd| r`z,| I dH }td|j  |jdd}|s5t	d W |S t
d|  W |S  ty_ } z| I dH  td|j d	| |d}~ww |S )
aB  
    Get an async DAV client instance with configuration from multiple sources.

    See :func:`caldav.base_client.get_davclient` for full documentation.

    Args:
        probe: Verify connectivity with OPTIONS request (default: True).
        **kwargs: All other arguments passed to base get_davclient.

    Returns:
        AsyncDAVClient instance.

    Raises:
        ValueError: If no configuration is found.

    Example::

        async with await get_davclient(url="...", username="...", password="...") as client:
            principal = await client.principal()
    NztNo configuration found. Provide connection parameters, set CALDAV_URL environment variable, or create a config file.zConnected to CalDAV server: r+  r?   z:Server did not return DAV header - may not be a DAV serverzServer DAV capabilities: z&Failed to connect to CalDAV server at : )_base_get_davclientr;   
ValueErrorr   r   r  r=   r   rf   r   r   r   rz   r0   DAVError)r@  r  r   r   r0  r   r   r   r   r.     s,   r.   calendar_urlcalendar_nameraise_errorsCalendarCollectionc                    s\  ddl m}m}  fdd}ztdddi|I dH }W n  ty= } z r( td|  | W  Y d}~S d}~ww z| I dH }	|	sS|dd	 ||d
W S g }
|| }||}|D ]G}dt|v rn|	j	|d}n|	j	|d}z|
 I dH }|dur|
| W q_ ty } ztd| d|   r W Y d}~q_d}~ww |D ]4}z|	j	|dI dH }|r|
| W q ty } ztd| d|   rӂ W Y d}~qd}~ww |
s|s|sz|	 I dH }|r|}
W n ty } ztd|   r	 W Y d}~nd}~ww ||
|d
W S  ty-   |dddI dH   w )a  
    Get calendars from a CalDAV server asynchronously.

    This is the async version of :func:`caldav.get_calendars`.

    Args:
        calendar_url: URL(s) or ID(s) of specific calendars to fetch.
        calendar_name: Name(s) of specific calendars to fetch by display name.
        raise_errors: If True, raise exceptions on errors; if False, log and skip.
        **kwargs: Connection parameters (url, username, password, etc.)

    Returns:
        :class:`~caldav.base_client.CalendarCollection` of matching calendars.
        Use as an async context manager to auto-close the connection::

            async with await aio.get_calendars() as calendars:
                for cal in calendars:
                    print(await cal.get_display_name())
    r   )rH  _normalize_to_listc                    s(   | du rt d|   rt|| S )z)Handle errors based on raise_errors flag.Nz(Problems fetching calendar information: )r   r0   rC  )coro_resulterrmsgrG  r   r   _try  s
   zget_calendars.<locals>._tryr@  TNzFailed to create async client: zgetting principalr   /)cal_url)r
  zProblems fetching calendar rA  r$  z$Problems fetching calendar by name 'z': z!Problems fetching all calendars: r   )caldav.base_clientrH  rI  r.   r   r   r0   r  r*   r  get_display_nameappendr  r{   )rE  rF  rG  r  rH  rI  rM  r   r   r  	calendarscalendar_urlscalendar_namesrP  r  display_namecal_nameall_calsr   rL  r   r    s   


r  CalendarResultc                     s@   ddl m} tdi | I dH }|r|d nd}|||jdS )a`  
    Get a single calendar from a CalDAV server asynchronously.

    This is a convenience function for the common case where only one
    calendar is needed.  Use as an async context manager to auto-close
    the connection::

        async with await aio.get_calendar() as cal:
            events = await cal.search(event=True)

    Args:
        Same as :func:`get_calendars`.

    Returns:
        :class:`~caldav.base_client.CalendarResult` wrapping the first
        matching calendar (or None).  Behaves like the calendar via
        ``__getattr__`` delegation when not used as a context manager.
    r   )rZ  NrN  r   )rQ  rZ  r  r   )r  rZ  
collectioncalr   r   r   get_calendar  s
   r]  )T)NNF)>r)   r   loggingsyscollections.abcr   typesr   typingr   r   r   urllib.parser   caldav.calendarobjectresourcer   r   r	   r
   rp   _USE_HTTPXYZr\   r[   niquestsr   niquests.structuresr   ImportErrorhttpxyzrq   h2Authr   r7   r,   rQ  r-   r.   rB  caldav.compatibility_hintsr/   
caldav.libr0   caldav.lib.python_utilitiesr1   caldav.lib.urlr2   caldav.requestsr3   caldav.responser4   r5   r6   	getLoggerr   version_infotyping_extensionsr:   r;   r8  r  r]  r   r   r   r   <module>   s   


        2
b