o
    .j                    @   sz  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	 ddl
mZ ddlmZmZmZmZ ddlmZmZmZmZmZmZ ddlZer\dd	lmZ d
dlmZ d
dlmZ ddlmZm Z m!Z!m"Z" ddlm#Z# d
dl$m%Z% d
dl&m'Z'm(Z(m)Z)m*Z*m+Z+ d
dl,m-Z- d
dl.m/Z/m0Z0 d
dl1m2Z2m3Z3 d
dl4m5Z5 d
dl6m7Z7 edddZ8e9dZ:eG dd dZ;de<de<dB fddZ=de<de<fd d!Z>d"e?e<ef de@fd#d$ZAd%eBe dB deBe; fd&d'ZCde<dB de<dB fd(d)ZDd%eBe dB de<dB fd*d+ZEG d,d- d-e-ZFG d.d/ d/e-ZGG d0d1 d1e-ZHG d2d3 d3eHZIG d4d5 d5eIZJG d6d7 d7eIZKG d8d9 d9ZLdS ):az  
I'm trying to be consistent with the terminology in the RFCs:

CalendarSet is a collection of Calendars
Calendar is a collection of CalendarObjectResources
Principal is not a collection, but holds a CalendarSet.

There are also some Mailbox classes to deal with RFC6638.

A SynchronizableCalendarObjectCollection contains a local copy of objects from a calendar on the server.
    N)	dataclass)date)datetimetimezone)sleep)TYPE_CHECKINGAnyOptionalTypeVar)ParseResultSplitResultquoteunquoteurlparse
urlunparse)vCalAddress   )	DAVClientCalDAVSearcher)	CoroutineIterableIteratorSequence)Literal)ICALH)CalendarObjectResourceEventFreeBusyJournalTodo)	DAVObject)cdavdav)errorvcal)to_wire)URL_CCr   )boundcaldavc                   @   s>   e Zd ZU dZeed< edB ed< edB ed< ee ed< dS )CalendarInfoz7Data for a calendar extracted from a PROPFIND response.urlNcal_idnameresource_types)__name__
__module____qualname____doc__str__annotations__list r7   r7   F/home/thesage/.local/lib/python3.10/site-packages/caldav/collection.pyr+   ;   s   
 r+   r,   returnc                 C   s\   zt | dd}|r|d }|r|W S W d S W d S  ty-   td|   Y d S w )N/zCalendar has unexpected url )r4   rstripsplit	Exceptionlogr$   )r,   partsr-   r7   r7   r8   _extract_calendar_id_from_urlE   s   rA   c                 C   s*   t | }tt|jdd}t|j|dS )zKQuote the path component of a URL to handle unencoded spaces (e.g. Zimbra).z/@safe)path)r   r   r   rD   r   _replace)r,   parsedquoted_pathr7   r7   r8   _quote_url_pathQ   s   rH   
propertiesc                 C   s,   |  dg }t|ts|r|gng }d|v S )N{DAV:}resourcetypez'{urn:ietf:params:xml:ns:caldav}calendar)get
isinstancer6   )rI   rtr7   r7   r8   _is_calendar_resourceX   s   
rN   resultsc                 C   sf   g }| pg D ]*}t |jsqt|j}|jd}t|}|s q|t||||jdg d q|S )zCExtract CalendarInfo objects from a list of PropfindResult objects.{DAV:}displaynamerJ   )r,   r-   r.   r/   )rN   rI   rH   hrefrK   rA   appendr+   )rO   	calendarsresultr,   r.   r-   r7   r7   r8   (_extract_calendars_from_propfind_results_   s$   

rU   c                 C   s0   | du rdS d| v rd| vrd| vrt | S | S )z6Quote @ in owncloud-style URLs that are not full URLs.N@://z%40)r   r,   r7   r7   r8   _sanitize_calendar_home_set_urlu   s
   rY   c                 C   s.   | pg D ]}|j d}|rt|  S qdS )zDExtract calendar-home-set URL from a list of PropfindResult objects.z0{urn:ietf:params:xml:ns:caldav}calendar-home-setN)rI   rK   rY   )rO   rT   home_setr7   r7   r8   '_extract_calendar_home_set_from_results~   s   r[   c                   @   s   e Zd ZdZded fddZdddZded fd	d
ZdddZ				dde	dB de	dB de
dB de	dB ddf
ddZ				dde	dB de	dB de
dB de	dB ddf
ddZdde	dB de	dB ddfddZdS )CalendarSetz.
    A CalendarSet is a set of calendars.
    r9   Calendarc                    s   t |} fdd|D S )z2Convert PropfindResult list into Calendar objects.c              	      s&   g | ]}t  j|j|j|j d qS ))clientr,   r.   idparent)r]   r^   r,   r.   r-   ).0infoselfr7   r8   
<listcomp>   s    z7CalendarSet._calendars_from_results.<locals>.<listcomp>)rU   )rd   rO   calendar_infosr7   rc   r8   _calendars_from_results   s   
z#CalendarSet._calendars_from_results4list[Calendar] | Coroutine[Any, Any, list[Calendar]]c                 C   s6   | j r|  S | jjt| j| jjdd}| |jS )a  
        List all calendar collections in this set.

        For sync clients, returns a list of Calendar objects directly.
        For async clients, returns a coroutine that must be awaited.

        Returns:
         * [Calendar(), ...]

        Example (sync):
            calendars = calendar_set.get_calendars()

        Example (async):
            calendars = await calendar_set.get_calendars()
        r   propsdepth)	is_async_client_async_get_calendarsr^   propfindr4   r,   CALENDAR_LIST_PROPSrg   rO   rd   responser7   r7   r8   get_calendars   s   zCalendarSet.get_calendarsc                    s0   | j jt| j| j jddI dH }| |jS )z(Async implementation of get_calendars().r   ri   N)r^   rn   r4   r,   ro   rg   rO   rp   r7   r7   r8   rm      s
   z CalendarSet._async_get_calendarsc                 C      |   S z
        Deprecated: Use :meth:`get_calendars` instead.

        This method is an alias kept for backwards compatibility.
        rr   rc   r7   r7   r8   rS         zCalendarSet.calendarsNr.   r-    supported_calendar_component_setmethod(Calendar | Coroutine[Any, Any, Calendar]c                 C   s2   | j r| ||||S t| j|| ||dj|dS )ax  
        Utility method for creating a new calendar.

        Args:
          name: the display name of the new calendar
          cal_id: the uuid of the new calendar
          supported_calendar_component_set: what kind of objects
           (EVENT, VTODO, VFREEBUSY, VJOURNAL) the calendar should handle.
           Should be set to ['VTODO'] when creating a task list in Zimbra -
           in most other cases the default will be OK.
          method: 'mkcalendar' or 'mkcol' - usually auto-detected

        For async clients, returns a coroutine that must be awaited.

        Returns:
          Calendar(...)-object
        r.   r`   r_   rw   rx   )rl   _async_make_calendarr]   r^   saverd   r.   r-   rw   rx   r7   r7   r8   make_calendar   s   zCalendarSet.make_calendarc                    s(   t | j|| ||d}|j|dI dH S )&Async implementation of make_calendar.rz   r{   N)r]   r^   r}   )rd   r.   r-   rw   rx   calendarr7   r7   r8   r|      s   z CalendarSet._async_make_calendarc                 C   s\  |r|s|   D ]}| }||kr|  S q|r'|s'td| d| j |s:|s:|   }|s6td|d S | jdu rCtd|du rKtdtt	|
 t| jj
 re| jj|}n?t|tsyt|tr|dsy|d	r| jdu rtd
| j|}n| jdu rtd
|du rtd| jt|d }t| j|| ||dS )ac  
        The calendar method will return a calendar object.  If it gets a cal_id
        but no name, it will not initiate any communication with the server

        Args:
          name: return the calendar with this display name
          cal_id: return the calendar with this calendar id or URL

        Returns:
          Calendar(...)-object
        zNo calendar with name z found under zno calendars foundr   N%Unexpected value None for self.clientz Unexpected value None for cal_idhttps://http://"Unexpected value None for self.urlr:   )r.   r`   r,   r_   )rr   get_display_namer$   NotFoundErrorr,   r^   
ValueErrorr4   r'   	objectify	canonical
startswithjoinrL   r   r]   )rd   r.   r-   r   display_namecalsr,   r7   r7   r8   r      sF   

$


zCalendarSet.calendarr9   rh   NNNNNN)r0   r1   r2   r3   r6   rg   rr   rm   rS   r4   r   r   r|   r   r7   r7   r7   r8   r\      sJ    



%
$r\   c                       s  e Zd ZdZ			d@ded deeB eB eB dB dedB de	ddf
 fd	d
Z
e		dAdddeeB eB eB dB dedB dd fddZ				dBdedB dedB de	dB ddfddZ				dBdedB dedB de	dB ddfddZdCddZ			d@dedB dedB dedB ddfddZdDddZdEd d!Zed"d# ZejdFd$d#ZdGd&d'ZdGd(d)Z		*dHd+d,Zdefd-d.Z		/dId0d1ZdeedB  fd2d3ZdJd5d6ZdKd8d9ZdLd;d<Z dMd>d?Z!  Z"S )N	Principala!  
    This class represents a DAV Principal. It doesn't do much, except
    keep track of the URLs for the calendar-home-set, etc.

    A principal MUST have a non-empty DAV:displayname property
    (defined in Section 13.2 of [RFC2518]),
    and a DAV:resourcetype property (defined in Section 13.9 of [RFC2518]).
    Additionally, a principal MUST report the DAV:principal XML element
    in the value of the DAV:resourcetype property.

    (TODO: the resourcetype is actually never checked, and the DisplayName
    is not stored anywhere)
    Nr^   r   r,   calendar_home_setkwargsr9   c                    s   || _ t jd||d| |du rL| jdu rtd| jj| _| t }|du r?t	
d t	
d t	
d| jj  | jjt|| _dS dS )a  
        Returns a Principal.

        End-users usually shouldn't need to construct Principal-objects directly.  Use davclient.principal() to get the principal object of the logged-in user  and davclient.principals() to get other principals.

        Args:
          client: a DAVClient() object
          url: The URL, if known.
          calendar_home_set: the calendar home set, if known

        If url is not given, deduct principal path as well as calendar home set
        path from doing propfinds.
        r^   r,   Nr   "calendar server lacking a feature:)current-user-principal property not foundz assuming %s is the principal URLr7   )_calendar_home_setsuper__init__r^   r   r,   get_propertyr#   CurrentUserPrincipalr?   warningr   r'   r   )rd   r^   r,   r   r   cup	__class__r7   r8   r   4  s   



zPrincipal.__init__c                    s~   | ||p|j |d}|du r=|t I dH }|du r3td td td|j  d |S |j t||_ |S )ap  
        Create a Principal, discovering URL if not provided.

        This is the recommended way to create a Principal with async clients
        as it handles async URL discovery.

        For sync clients, you can use the regular constructor: Principal(client)

        Args:
            client: A DAVClient or AsyncDAVClient instance
            url: The principal URL (if known)
            calendar_home_set: The calendar home set URL (if known)

        Returns:
            Principal with URL discovered if not provided

        Example (async):
            principal = await Principal.create(async_client)
        )r^   r,   r   Nr   r   z	assuming z is the principal URL)	r,   r   r#   r   r?   r   r   r'   r   )clsr^   r,   r   	principalr   r7   r7   r8   createY  s   

zPrincipal.creater.   r-   rw   ry   c                 C   s*   | j r| ||||S | jj||||dS )z
        Convenience method, bypasses the self.calendar_home_set object.
        See CalendarSet.make_calendar for details.

        For async clients, returns a coroutine that must be awaited.
        rw   rx   )rl   r|   r   r   r~   r7   r7   r8   r     s   zPrincipal.make_calendarr]   c                    s(   |   I dH }|j||||dI dH S )r   Nr   )_async_get_calendar_home_setr   )rd   r.   r-   rw   rx   r   r7   r7   r8   r|     s   zPrincipal._async_make_calendarr\   c                    sN   | j r| j S | t I dH }|dur!d|v r!d|vr!t|}|| _| j S )z*Async helper to get the calendar home set.NrV   rW   r   r   r"   CalendarHomeSetr   r   rd   calendar_home_set_urlr7   r7   r8   r     s   z&Principal._async_get_calendar_home_setcal_urlc                 C   s   |s2|r+t |tst |tr+|ds|dr+| jdu r!tdt| jt|dS | j	||S | jdu r;tdt| j| jj
|dS )z
        The calendar method will return a calendar object.
        It will not initiate any communication with the server.
        r   r   Nr   rX   )rL   r'   r4   r   r^   r   r]   r   r   r   r,   r   )rd   r.   r-   r   r7   r7   r8   r     s"   


zPrincipal.calendar.vCalAddress | Coroutine[Any, Any, vCalAddress]c                 C   sh   | j r|  S ddlm}m} |  }|  }| t	 }||d }|||j
d< |||j
d< |S )z
        Returns the principal, as an icalendar.vCalAddress object.
        For async clients, returns a coroutine that must be awaited.
        r   r   vTextcncutype)rl   _async_get_vcal_address	icalendarr   r   r   calendar_user_address_setr   r"   CalendarUserTypeparams)rd   r   r   r   idsr   retr7   r7   r8   get_vcal_address  s   zPrincipal.get_vcal_addressr   c                    s   ddl m}m} |  }t|ts|I dH }| jt ddI dH }|du r,t	
ddd |D r5J tt|d	d
 d}| t I dH }||d j}|||jd< |||jd< |S )zDAsync counterpart of get_vcal_address() for use with AsyncDAVClient.r   r   NFparse_props,No calendar user addresses given from serverc                 S       g | ]}|j t j kr|qS r7   tagr#   Hrefra   xr7   r7   r8   re          z5Principal._async_get_vcal_address.<locals>.<listcomp>c                 S      t | dd S N	preferredr   intrK   r   r7   r7   r8   <lambda>      z3Principal._async_get_vcal_address.<locals>.<lambda>keyr   r   )r   r   r   r   rL   r4   r   r"   CalendarUserAddressSetr$   r   sortedr6   r   textr   )rd   r   r   r   addresses_el	addressesr   r   r7   r7   r8   r     s   


z!Principal._async_get_vcal_addressc                 C   s@   | j s| t }|d urd|v rd|vrt|}|| _| j S )NrV   rW   r   r   r7   r7   r8   r     s   zPrincipal.calendar_home_setc                 C   s`   t |tr
|| _d S t|}|d ur"|jr"|j| jjjkr"|| j_t| j| jj|| _d S N)	rL   r\   r   r'   r   hostnamer^   r,   r   )rd   r,   sanitized_urlr7   r7   r8   r     s   

	rh   c                 C   s   | j | S )a]  
        Return the principal's calendars.

        For sync clients, returns a list of Calendar objects directly.
        For async clients, returns a coroutine that must be awaited.

        Example (sync):
            calendars = principal.get_calendars()

        Example (async):
            calendars = await principal.get_calendars()
        )r^   rr   rc   r7   r7   r8   rr   '  s   zPrincipal.get_calendarsc                 C   rs   rt   ru   rc   r7   r7   r8   rS   7  rv   zPrincipal.calendars/dict[str, FreeBusy] | Coroutine[Any, Any, dict]c                 C   s   t  }|dd |dd |dd t }t  }|d| |dt  |d	| |d
| || | 	 }t|| d}|D ]	}	|j
|	dd qI| jr\| ||S |  | jj|j|jtd}
|
j| dS )zSends a freebusy-request for some attendee to the server
        as per RFC6638.

        For async clients, returns a coroutine that must be awaited.
        prodidz-//tobixen/python-caldav//ENversionz2.0rx   REQUESTuiddtstampdtstartdtenddatar`   T)no_default_parameters)headersr`   )r   r]   adduuiduuid4r   r   nowadd_componentschedule_outboxadd_attendeerl   _async_freebusy_requestadd_organizerr^   postr,   r   r   "_parse_scheduling_response_objects)rd   r   r   	attendeesfreebusy_icalr   freebusy_compoutbox	caldavobjattendeerq   r7   r7   r8   freebusy_requestD  s(   
zPrincipal.freebusy_requestc                    sD   t }|I dH }| I dH  | j|j|j|I dH }|j| dS )z=Async implementation of freebusy_request() for async clients.Nr   )r   r   r^   r   r,   r   r   )rd   r   fb_objr   rq   r7   r7   r8   r   d  s   
z!Principal._async_freebusy_request8list[str | None] | Coroutine[Any, Any, list[str | None]]c                 C   sj   | j r|  S | jt dd}|du rtddd |D r"J t|}|jdd d	 d
d |D S )z$
        defined in RFC6638
        Fr   Nr   c                 S   r   r7   r   r   r7   r7   r8   re     r   z7Principal.calendar_user_address_set.<locals>.<listcomp>c                 S   r   r   r   r   r7   r7   r8   r     r   z5Principal.calendar_user_address_set.<locals>.<lambda>r   c                 S      g | ]}|j qS r7   r   r   r7   r7   r8   re     r   )	rl    _async_calendar_user_address_setr   r"   r   r$   r   r6   sortrd   
_addressesr   r7   r7   r8   r   q  s   
z#Principal.calendar_user_address_setc                    sd   | j t ddI d H }|d u rtddd |D rJ t|}|jdd d d	d |D S )
NFr   r   c                 S   r   r7   r   r   r7   r7   r8   re     r   z>Principal._async_calendar_user_address_set.<locals>.<listcomp>c                 S   r   r   r   r   r7   r7   r8   r     r   z<Principal._async_calendar_user_address_set.<locals>.<lambda>r   c                 S   r   r7   r   r   r7   r7   r8   re     r   )r   r"   r   r$   r   r6   r   r   r7   r7   r8   r     s   
z*Principal._async_calendar_user_address_set2ScheduleInbox | Coroutine[Any, Any, ScheduleInbox]c                 C      | j r|  S t| dS )z
        Returns the schedule inbox, as defined in RFC6638.
        For async clients, returns a coroutine that must be awaited.
        r   )rl   _async_schedule_inboxScheduleInboxrc   r7   r7   r8   schedule_inbox     
zPrincipal.schedule_inbox4ScheduleOutbox | Coroutine[Any, Any, ScheduleOutbox]c                 C   r   )z
        Returns the schedule outbox, as defined in RFC6638.
        For async clients, returns a coroutine that must be awaited.
        r   )rl   _async_schedule_outboxScheduleOutboxrc   r7   r7   r8   r     r  zPrincipal.schedule_outboxr   c                    $   |  t I d H }t| j|dS Nr   )r   r"   ScheduleInboxURLr   r^   rd   r,   r7   r7   r8   r        zPrincipal._async_schedule_inboxr  c                    r  r  )r   r"   ScheduleOutboxURLr  r^   r  r7   r7   r8   r    r	  z Principal._async_schedule_outboxNNNr   r   )r9   r\   )r9   r   )r9   r   r9   Nr   )r9   r   )r9   r   )r9   r   )r9   r  )r9   r   )r9   r  )#r0   r1   r2   r3   r	   r4   r   r   r'   r   r   classmethodr   r   r|   r   r   r   r   propertyr   setterrr   rS   r   dictr   r   r6   r   r   r   r   r  __classcell__r7   r7   r   r8   r   %  s    %.









 

	
	
	r   c                       s  e Zd ZdZ						dded deeB eB eB dB ded dedB d	edB d
df fddZ		d	dddZ
dddZd fdd	ZdddZdeded
ee fddZ	d	dddZdd
ee fddZd ed
d!fd"d#Zd efd$d%Zd&d' Z		(	(dd)ee d edB d*ed+ed
d!f
d,d-Zdd.d/Zdd1d2Zdd4d5Zdd7d8Z	
	!dd9d:Zdd;d<Zdd=d>Z dd?d@Z!dddBdCZ"ddDdEZ#ddFe$e dGed
e$e fdHdIZ%dJe$e&eef  d
ee' fdKdLZ(ddFe$e dGed
e$e' fdMdNZ)	(ddFe$e dGed
ee&eef  fdOdPZ*	(ddFe$e dGed
ee' fdQdRZ+dSdT Z,		U	V	(ddWe-dXe-dB dYddZee.dV B d[ed
e/d\ fd]d^Z0d_d` Z1	(d	addbdcZ2ddde Z3dfe4dged
dfdhdiZ5ddkdlZ6		(		(				ddmednedoedgedpee7j8 dB d
dqfdrdsZ9dWe-dXe-d
dtfdudvZ:ddxdyZ;	z	(	dd{e/e d|ed}edB d
d~fddZ<dddZ=dd Z>ddedB d
dfddZ?		ddede7j@dB ded\ d
d!fddZA		ddede7j@dB ded\ d
dfddZBded
d!fddZCded
d!fddZDded
d!fddZE	
	!dddZFded
d!fddZGded
d!fddZHded
d!fddZIeGZJdddZKdddZLded\ d
efddZM		(	(ddedB deded
dfddZN	
	dddZOeOZPeNZQ		(	(ddedB deded
dfddZRdddZSdddZT  ZUS )r]   z
    The `Calendar` object is used to represent a calendar collection.
    Refer to the RFC for details:
    :rfc:`4791#section-5.3.1`.
    Nr^   r   r,   r`   r!   r.   r_   r9   c              	      s$   t  jd||||||d| dS )a  
        Initialize a Calendar object.

        Args:
            client: A DAVClient instance
            url: The url for this calendar. May be a full URL or a relative URL.
            parent: The parent object (typically a CalendarSet or Principal)
            name: The display name for the calendar (stored in props cache)
            id: The calendar id (used when creating new calendars)
            props: A dict with known properties for this calendar
        )r^   r,   r`   r_   rj   r.   Nr7   )r   r   )rd   r^   r,   r`   r.   r_   rj   extrar   r7   r8   r     s
   
zCalendar.__init__ None | Coroutine[Any, Any, None]c                 C   s  |du r
t t }|| _|du r<| jr:| jjjdtd}|d dvr(t	d|d dkr7|d d	kr7d
}nd}nd}| j
j|d }|| _t }d}| j pX| jjd}	|rg|	rgt|}||g7 }|r}t }
|D ]	}|
t|7 }
qo||
7 }|d
kr|t t t g 7 }t | }|d
krt nt | }| jr| |||||S | j|||dd |rz	| |g W dS  ty   z|  }t||k W Y dS  ty   t j!ddd Y Y dS w w dS )z
        Create a new calendar with display name `name` in `parent`.

        For async clients, returns a coroutine that must be awaited.
        Nzcreate-calendarreturn_typesupport)fullfragilequirkz>Creation of calendars (allegedly) not supported on this serverr  	behaviourzmkcol-requiredmkcol
mkcalendarr:   zcreate-calendar.set-displayname   rootquery_methodr,   expected_return_valueDcalendar server does not support display name on calendar?  IgnoringTexc_info)"r4   r   r   r_   r^   featuresis_supportedr  r$   MkcalendarErrorr`   r,   r   r#   PropDisplayNamer"   SupportedCalendarComponentSetCompResourceType
Collectionr]   SetMkcol
Mkcalendarrl   _async_create_queryset_propertiesr>   r   assert_r?   r   )rd   r.   r_   rw   rx   	supportedrD   propr   supports_displaynamesccssccsetr  current_display_namer7   r7   r8   _create  sf   

zCalendar._createc                    s   | j |||ddI dH  |rKz| |gI dH  W dS  tyJ   z| t I dH }t||k W Y dS  tyI   tj	ddd Y Y dS w w dS )zAAsync implementation of _create (call via _create, not directly).r  r  Nr"  Tr#  )
r2  r3  r>   r   r#   r)  r$   r4  r?   r   )rd   rD   r  rx   r.   r   r;  r7   r7   r8   r1    s"   zCalendar._async_createc              	      s$  | j r	| j|dS |du r8zt|  }W n tjy    Y dS w |D ]}z|  W q# tjy5   Y q#w dS | jj	dt
}|du rL| jj	d }|d dkrtddD ]+}zt   W n
 tjyj   Y nw z
|   td	 W qW tjy   d
}Y  nw |r| jddS t   dS )uO  Delete the calendar.

        For async clients, returns a coroutine that must be awaited.

        wipe: tristate controlling cleanup behaviour
          None (default) – wipe all objects instead of deleting if the server
                           doesn't support calendar deletion
          True           – wipe all objects and return without deleting the
                           calendar itself (useful for servers where deletion
                           moves calendars to a trashbin)
          False          – always attempt to delete the calendar via HTTP DELETE
        wipeTNdelete-calendarr  r  r      333333?F)rl   _async_deleter6   searchr$   r   deleter^   r%  r&  r  ranger   DeleteError
get_eventsr   )rd   r>  objectsobj
quirk_info_r   r7   r8   rD  -  sF   zCalendar.deletec              	      sL  ddl }|du r8z	|  I dH }W n tjy   Y dS w |D ]}z	| I dH  W q  tjy5   Y q w dS | jjdt}|du rL| jjd }|d dkrt	ddD ]7}z
t
| I dH  W n
 tjym   Y nw z| jddI dH  |d	I dH  W qW tjy   d
}Y  nw |r| jddI dH  dS t
| I dH  dS )z*Async implementation of Calendar.delete().r   NTr?  r  r  r@  )eventrA  Fr=  )asynciorC  r$   r   rD  r^   r%  r&  r  rE  r!   rB  rF  r   )rd   r>  rM  rH  rI  rJ  rK  r7   r7   r8   rB  a  sF   zCalendar._async_deleterq   with_fallbackc                 C   s   |j pg D ]}|jt j}|r|  S q|stddg}| jr0| jj	
dr0|d | jr?| jj	
dr?|d |S )zExtract supported component types from a propfind DAVResponse.

        Both the sync and async paths produce a DAVResponse via propfind,
        which always populates response.results via the protocol layer.
        z.supported-calendar-component-set not supportedVEVENTzsave-load.todoVTODOzsave-load.journalVJOURNAL)rO   rI   rK   r"   r*  r   r$   PropfindErrorr^   r%  r&  rR   )rd   rq   rN  rT   
componentsrfc_defaultr7   r7   r8   #_supported_components_from_response  s   


z,Calendar._supported_components_from_responseT*list[Any] | Coroutine[Any, Any, list[Any]]c                 C   sF   | j du r	td| jr| |S t g}| j|dd}| ||S )a  
        returns a list of component types supported by the calendar, in
        string format (typically ['VJOURNAL', 'VTODO', 'VEVENT'])

        RFC 4791 section 5.2.3: supported-calendar-component-set is optional.
        When absent, the server MUST accept all component types, so we return
        the RFC default list (trimmed by known server limitations from
        compatibility hints) rather than raising or returning empty.
        See https://github.com/python-caldav/caldav/issues/653
        Nr   Fparse_response_xml)r,   r   rl   _async_get_supported_componentsr"   r*  get_propertiesrU  rd   rN  rj   rq   r7   r7   r8   get_supported_components  s   


z!Calendar.get_supported_componentsc                    s,   t  g}| j|ddI d H }| ||S )NFrW  )r"   r*  rZ  rU  r[  r7   r7   r8   rY    s   
z(Calendar._async_get_supported_componentsicalDCalendarObjectResource | Coroutine[Any, Any, CalendarObjectResource]c                 K   sz   | j r| j||fi |S | ||| jd}| |_|  |D ]}|j|fi | q |jdd d |_	|
  |S )a  
        sends a schedule request to the server.  Equivalent with add_event, add_todo, etc,
        but the attendees will be added to the ical object before sending it to the server.

        For async clients, returns a coroutine that must be awaited.
        r   r^   veventr   r   )rl   _async_save_with_invites_calendar_comp_class_by_datar^   r`   r   r   icalendar_instancewalkr_   r}   rd   r]  r   attendeeoptionsrI  r   r7   r7   r8   save_with_invites  s   	zCalendar.save_with_invitesc                    s   |  ||| jd}| |_| I dH  |D ]}t|tr%| I dH }|j|fi | q|j	dd d |_
| I dH  |S )z>Async implementation of save_with_invites() for async clients.r_  Nr`  r   r   )rb  r^   r`   r   rL   r   r   r   rc  rd  r_   r}   re  r7   r7   r8   ra    s   
z!Calendar._async_save_with_invitesc                 K   sP   |st |tst |tr&dt|vr&|rd|vr||d< tjdd|i|S |S )Ns   BEGIN:VCALENDARical_fragmentobjtyper7   )rL   r4   bytesr&   r%   create_ical)rd   r]  ri  	ical_datar7   r7   r8   _use_or_create_ics  s   zCalendar._use_or_create_icsFobjclassno_overwrite	no_createc                 K   sn   || j | j|fdd|j  i|| d}| jr"| j|||dS |j||dd}|jdur5|jdd |S )	aG  Add a new calendar object (event, todo, journal) to the calendar.

        This method is for adding new content to the calendar.  To update
        an existing object, fetch it first and use ``object.save()``.

        Args:
          objclass: Event, Journal or Todo
          ical: ical object (text, icalendar or vobject instance)
          no_overwrite: existing calendar objects should not be overwritten
          no_create: don't create a new object, existing calendar objects should be updated
          dtstart: properties to be inserted into the icalendar object
          dtend: properties to be inserted into the icalendar object
          summary: properties to be inserted into the icalendar object
          alarm_trigger: when given, one alarm will be added
          alarm_action: when given, one alarm will be added
          alarm_attach: when given, one alarm will be added

        Note that the list of parameters going into the icalendar
        object and alarms is not complete.  Refer to the RFC or the
        icalendar library for a full list of properties.
        ri  Vr   )ro  rp  Nro  rp  only_this_recurrenceTfix)	r^   rm  r0   upperrl   _async_add_object_finishr}   r,   _handle_reverse_relations)rd   rn  r]  ro  rp  rl  or7   r7   r8   
add_object  s"    
zCalendar.add_objectc                    s8   |j ||ddI dH }|jdur|jddI dH  |S )zLAsync helper for add_object(): awaits save() then handles reverse relations.Nrr  Trt  )r}   r,   rx  )rd   ry  ro  rp  r7   r7   r8   rw    s
   
z!Calendar._async_add_object_finish"Event | Coroutine[Any, Any, Event]c                 O      | j tg|R i |S )zy
        Add an event to the calendar.

        Returns ``self.add_object(Event, ...)`` - see :meth:`add_object`
        )rz  r   rd   largsr   r7   r7   r8   	add_event     zCalendar.add_event Todo | Coroutine[Any, Any, Todo]c                 O   r|  )z{
        Add a todo/task to the calendar.

        Returns ``self.add_object(Todo, ...)`` - see :meth:`add_object`
        )rz  r    r}  r7   r7   r8   add_todo#  r  zCalendar.add_todo&Journal | Coroutine[Any, Any, Journal]c                 O   r|  )z
        Add a journal entry to the calendar.

        Returns ``self.add_object(Journal, ...)`` - see :meth:`add_object`
        )rz  r   r}  r7   r7   r8   add_journal+  r  zCalendar.add_journalc                 O      | j |i |S )z
        Deprecated: Use :meth:`add_object` instead.

        This method is an alias kept for backwards compatibility.
        See https://github.com/python-caldav/caldav/issues/71
        )rz  r}  r7   r7   r8   save_object6  s   	zCalendar.save_objectc                 O   r  )z
        Deprecated: Use :meth:`add_event` instead.

        This method is an alias kept for backwards compatibility.
        See https://github.com/python-caldav/caldav/issues/71
        )r  r}  r7   r7   r8   
save_eventA     zCalendar.save_eventc                 O   r  )z
        Deprecated: Use :meth:`add_todo` instead.

        This method is an alias kept for backwards compatibility.
        See https://github.com/python-caldav/caldav/issues/71
        )r  r}  r7   r7   r8   	save_todoJ  r  zCalendar.save_todoc                 O   r  )z
        Deprecated: Use :meth:`add_journal` instead.

        This method is an alias kept for backwards compatibility.
        See https://github.com/python-caldav/caldav/issues/71
        )r  r}  r7   r7   r8   save_journalS  r  zCalendar.save_journalry   c                 C   sH   | j du r"| jd}| jr| ||S | jd| j||d| j | S )z
        The save method for a calendar is only used to create it, for now.
        We know we have to create it when we don't have a url.

        For async clients, returns a coroutine that must be awaited.

        Returns:
         * self
        NrP   )r_   r.   rx   r7   )r,   rj   rK   rl   _async_saver<  r_   extra_init_options)rd   rx   r   r7   r7   r8   r}   \  s   

zCalendar.savec                    s(   | j d|| j|d| jI dH  | S )zAsync implementation of save.)r.   r_   rx   Nr7   )r<  r_   r  )rd   r   rx   r7   r7   r8   r  o  s   "zCalendar._async_save
event_urlsraise_notfoundc           
      c   s    | j du r
tdt t  }t | dd |D  }| |dd}|t g}|rL|j	D ]}|j	| }|rKd|v rKt
d| d| q3|D ]}	|	||	 tjj fV  qNdS )	u   
        get multiple events' data.
        TODO: Does it overlap the _request_report_build_resultlist method
        ## WARNING: async logic is duplicated in _async_multiget — mirror any changes there
        Nr   c                 S      g | ]	}t j|jd qS )valuer#   r   rD   ra   ur7   r7   r8   re         z&Calendar._multiget.<locals>.<listcomp>report404Status  in )r,   r   r#   r(  r"   CalendarDataCalendarMultiGetr2  expand_simple_propsstatusesr$   r   r   )
rd   r  r  r6  r  rq   rO   rQ   statusrr7   r7   r8   	_multigetv  s    


zCalendar._multigetrO   c                    s    fdd|D S )z?Post-processing shared by multiget and _async_multiget_objects.c              
      s@   g | ]\}}  | j jttt|d d| dqS )z/:@rB   r,   r   r`   )rb  r^   r,   r   r   r   r4   )ra   r,   r   rc   r7   r8   re     s    z+Calendar._post_multiget.<locals>.<listcomp>r7   )rd   rO   r7   rc   r8   _post_multiget  s   
zCalendar._post_multigetc                 C   s(   | j r
| j||dS | | j||dS )z
        get multiple events' data
        TODO: Does it overlap the _request_report_build_resultlist method?
        @author mtorange@gmail.com (refactored by Tobias)
        r  )rl   _async_multiget_objectsr  r  rd   r  r  r7   r7   r8   multiget  s   zCalendar.multigetc                    s   | j d u r
tdt t  }t | dd |D  }| |d dI d H }|t g |rO|j	D ]}|j	| }|rNd|v rNt
d| d| q6 fdd D S )	Nr   c                 S   r  r  r  r  r7   r7   r8   re     r  z,Calendar._async_multiget.<locals>.<listcomp>r  r  r  r  c                    s    g | ]}| | t jj fqS r7   )r"   r  r   )ra   r  rO   r7   r8   re     r   )r,   r   r#   r(  r"   r  r  r2  r  r  r$   r   )rd   r  r  r6  r  rq   rQ   r  r7   r  r8   _async_multiget  s   


zCalendar._async_multigetc                    s   |  | j||dI dH S )zAsync version of multiget.r  N)r  r  r  r7   r7   r8   r    s   z Calendar._async_multiget_objectsc                 O   s   t | j|i |S )z
        get multiple events' data
        @author mtorange@gmail.com
        (refactored by Tobias)
        This is for backward compatibility.  It may be removed in a later release.
        )r6   r  r}  r7   r7   r8   calendar_multiget  s   zCalendar.calendar_multigetrO  maybestartend
compfilterexpandverify_expandr   c                 C   sn   t jdtdd |rtd |dkr|duo|du}|dkr"t}n	|dkr)t}nd}| j||||d	d
}|S )a  
        .. deprecated:: 3.0
            Use :meth:`search` instead. This method will be removed in 4.0.

        Search events by date in the calendar.

        Args:
            start: Start of the date range to search.
            end: End of the date range (optional for open-ended search).
            compfilter: Component type to search for. Defaults to "VEVENT".
                Set to None to fetch all calendar components.
            expand: Should recurrent events be expanded? Default "maybe"
                becomes True unless the search is open-ended.
            verify_expand: Not in use anymore, kept for backward compatibility.

        Returns:
            List of CalendarObjectResource objects matching the search.

        Example (migrate to search)::

            # Legacy (deprecated):
            events = calendar.date_search(start, end, expand=True)

            # Recommended:
            events = calendar.search(start=start, end=end, event=True, expand=True)
        z7use `calendar.search rather than `calendar.date_search`   )
stacklevelz`verify_expand in date_search does not work anymore, as we're doing client side expansion insteadr  NrO  rP  F)r  r  
comp_classr  split_expanded)warningswarnDeprecationWarningloggingr   r   r    rC  )rd   r  r  r  r  r  r  rH  r7   r7   r8   date_search  s0   $zCalendar.date_searchc              
   C   s   g }| |}|D ]O}|| }tjj|v r(|tjj}|du r%| |n|}	nd}|	du r0t}	t|}
|
jdu r=t	|}
| j
|
| j
krGq	||	| j| j
|
|| |d q	||fS )z<Shared post-processing for _request_report_build_resultlist.N)r,   r   r`   rj   )r  r"   r  r   poprb  r   r'   r   r   r,   r   rR   r^   )rd   rq   r  props_matchesrO   r  pdatacdatacomp_class_r,   r7   r7   r8   %_post_request_report_build_resultlist  s4   


	z.Calendar._post_request_report_build_resultlisthtuple[Any, list[CalendarObjectResource]] | Coroutine[Any, Any, tuple[Any, list[CalendarObjectResource]]]c                 C   sP   |du r	t  gnt  g| }| jr| |||S | |dd}| |||S )z
        Takes some input XML, does a report query on a calendar object
        and returns the resource objects found.

        For async clients, returns a coroutine that must be awaited.
        Nr   r  )r"   r  rl   &_async_request_report_build_resultlistr2  r  )rd   xmlr  rj   no_calendardatar  rq   r7   r7   r8    _request_report_build_resultlist1  s
    	z)Calendar._request_report_build_resultlistc                    s$   |  |ddI dH }| |||S )z9Async implementation of _request_report_build_resultlist.r   r  N)r2  r  )rd   r  r  r  rq   r7   r7   r8   r  @  s   z/Calendar._async_request_report_build_resultlist
searchargssort_reversec                 C   s$  |D ]}|d dksJ |}|dkrd}|dkrd}|dkr d}|d	kr@t |d	 tr2|d	 g|d	< |d	 D ]}||| q6q|d
krEq|dksN||jv rs|| }|dv rlt |trlt |tslt|j|j|jt	j
d}t||| q|dr|j|dd || dd q||||  qdS )zPopulate a CalDAVSearcher from a dict of search keyword arguments.

        Shared by :meth:`searcher` and :meth:`search`.
        r   rK  class_classno_categoryno_categories	no_class_no_class	sort_keysr  r  )r  r  alarm_start	alarm_end)tzinfono_   Nundef)operator)rL   r4   add_sort_key__dataclass_fields___dater   yearmonthdayr   utcsetattrr   add_property_filter)rd   my_searcherr  r  r   aliassortkeyr  r7   r7   r8   _populate_searcherE  s<   
zCalendar._populate_searcherr   c                 K   s2   ddl m} | }| |_| |||dd |S )a  Create a searcher object for building complex search queries.

        This is the recommended way to perform advanced searches. The
        returned searcher can have filters added, and then be executed:

        .. code-block:: python

            searcher = calendar.searcher(event=True, start=..., end=...)
            searcher.add_property_filter("SUMMARY", "meeting")
            results = searcher.search()

        For simple searches, use :meth:`search` directly instead.

        :param searchargs: Search parameters (same as for :meth:`search`)
        :return: A CalDAVSearcher bound to this calendar

        See :class:`caldav.search.CalDAVSearcher` for available filter methods.
        r   r   r  F)rC  r   	_calendarr  rK   )rd   r  r   r  r7   r7   r8   searcherh  s
   zCalendar.searcherr  server_expandr  rj   z*list[_CC] | Coroutine[Any, Any, list[_CC]]c	              	   K   st   ddl m}
 t|	ddtsJ |
 }| ||	| |s!|r!|}| jr/|| ||||||S | | ||||||S )aB  Sends a search request towards the server, processes the
        results if needed and returns the objects found.

        Refactoring 2025-11: a new class
        class:`caldav.search.CalDAVSearcher` has been made, and
        this method is sort of a wrapper for
        CalDAVSearcher.search, ensuring backward
        compatibility.  The documentation may be slightly overlapping.

        I believe that for simple tasks, this method will be easier to
        use than the new interface, hence there are no plans for the
        foreseeable future to deprecate it.  This search method will
        continue working as it has been doing before for all
        foreseeable future.  I believe that for simple tasks, this
        method will be easier to use than to construct a
        CalDAVSearcher object and do searches from there.  The
        refactoring was made necessary because the parameter list to
        `search` was becoming unmanagable.  Advanced searches should
        be done via the new interface.

        Caveat: The searching is done on the server side, the RFC is
        not very crystal clear on many of the corner cases, and
        servers often behave differently when presented with a search
        request.  There is planned work to work around server
        incompatibilities on the client side, but as for now
        complicated searches will give different results on different
        servers.

        ``todo`` - searches explicitly for todo.  Unless
        ``include_completed`` is specified, there is some special
        logic ensuring only pending tasks is returned.

        There is corresponding ``event`` and ``journal`` bools to
        specify that the search should be only for events or journals.
        When neither are set, one should expect to get all objects
        returned - but quite some calendar servers will return
        nothing.  This will be solved client-side in the future, as
        for 2.0 it's recommended to search separately for tasks,
        events and journals to ensure consistent behaviour across
        different calendar servers and providers.

        ``sort_keys`` refers to (case-insensitive) properties in the
        icalendar object, ``sort_reverse`` can also be given.  The
        sorting will be done client-side.

        Use ``start`` and ``end`` for time-range searches.  Open-ended
        searches are supported (i.e. "everything in the future"), but
        it's recommended to use closed ranges (i.e. have an "event
        horizon" of a year and ask for "everything from now and one
        year ahead") and get the data expanded.

        With the boolean ``expand`` set, you don't have to think too
        much about recurrences - they will be expanded, and with the
        (default) ``split_expanded`` set, each recurrence will be
        returned as a separate list object (otherwise all recurrences
        will be put into one ``VCALENDAR`` and returned as one
        ``Event``).  This makes it safe to use the ``event.component``
        property.  The non-expanded resultset may include events where
        the timespan doesn't match the date interval you searched for,
        as well as items with multiple components ("special"
        recurrences), meaning you may need logic on the client side to
        handle the recurrences.  *Only time range searches over closed
        time intervals may be expanded*.

        As for 2.0, the expand-logic is by default done on the
        client-side, for consistent results across various server
        incompabilities.  However, you may force server-side expansion
        by setting ``server_expand=True``

        Text attribute search parameters can be given to query the
        "properties" in the calendar data: category, uid, summary,
        comment, description, location, status.  According to the RFC,
        a substring search should be done.

        You may use no_category, no_summary, etc to search for objects
        that are missing those attributes.

        Negated text matches are not supported yet.

        For power-users, those parameters are also supported:

         * ``xml`` - use this search query, and ignore other filter parameters
         * ``comp_class`` - alternative to the ``event``, ``todo`` or ``journal`` booleans described above.
         * ``filters`` - other kind of filters (in lxml tree format)

        r   r   r  T)rC  r   rL   rK   boolr  rl   async_search)rd   r  r  r  r  rj   filterspost_filter_hacksr  r   r  r7   r7   r8   rC    s   czCalendar.searchz(FreeBusy | Coroutine[Any, Any, FreeBusy]c                 C   s@   t  t ||g }| jr| |S | |dd}t| |jS )z
        Search the calendar, but return only the free/busy information.

        Args:
          start : defaults to datetime.today().
          end : same as above.

        Returns:
          FreeBusy object (or a coroutine for async clients)
        r   r  )r"   FreeBusyQuery	TimeRangerl   r   r2  r   raw)rd   r  r  r  rq   r7   r7   r8   r     s
   
zCalendar.freebusy_requestr   c                    s"   |  |ddI d H }t| |jS )Nr   r  )r2  r   r  )rd   r  rq   r7   r7   r8   r     s   z Calendar._async_freebusy_requestduepriorityr  include_completedsort_key,list[Todo] | Coroutine[Any, Any, list[Todo]]c                 C   s   |r|f}| j d||dS )a  
        Fetches a list of todo items (this is a wrapper around search).

        For sync clients, returns a list of Todo objects directly.
        For async clients, returns a coroutine that must be awaited.

        Args:
          sort_keys: use this field in the VTODO for sorting (iterable of lower case string, i.e. ('priority','due')).
          include_completed: boolean - by default, only pending tasks are listed
          sort_key: DEPRECATED, for backwards compatibility with version 0.4.

        Example (sync):
            todos = calendar.get_todos()

        Example (async):
            todos = await calendar.get_todos()
        T)todor  r  )rC  )rd   r  r  r  r7   r7   r8   	get_todos  s   zCalendar.get_todosc                 O   r  )z
        Deprecated: Use :meth:`get_todos` instead.

        This method is an alias kept for backwards compatibility.
        )r  r}  r7   r7   r8   todos8  s   zCalendar.todosc                 C   s   |du rt S t|dr9|dD ]&}| }|dkrt  S |dkr&t  S |dkr.t  S |dkr6t  S qt S t|dret|j	sEt S t
jtt
jtt
jtt
jti}|j	D ]}|j|v rd||j   S qVt S )	z
        takes some data, either as icalendar text or icalender object (TODO:
        consider vobject) and returns the appropriate
        CalendarResourceObject child class.
        Nr=   
zBEGIN:VEVENTzBEGIN:VTODOzBEGIN:VJOURNALzBEGIN:VFREEBUSYsubcomponents)r   hasattrr=   stripr   r    r   r   lenr  r   r   )rd   r   lineical2caldavscr7   r7   r8   rb  @  s8   




z%Calendar._calendar_comp_class_by_datar   r   c                 C   s   t ||| d S )z7
        Returns the event with the given URL.
        r  )r   load)rd   rQ   r   r7   r7   r8   event_by_urld  s   zCalendar.event_by_urlr   comp_filterr  c                    sh   | j r
|  ||S | j ||dddd} fdd|D }|s'td  tt|dk |d S )	a>  
        Get one calendar object from the calendar by UID.

        Args:
         uid: the object uid
         comp_class: filter by component type (Event, Todo, Journal)
         comp_filter: for backward compatibility.  Don't use!

        Returns:
         CalendarObjectResource (Event, Todo, or Journal)
        Tinsistr   r  r  r  r  r  c                       g | ]	}|j  kr|qS r7   r_   ra   ry  r   r7   r8   re     r  z.Calendar.get_object_by_uid.<locals>.<listcomp>%s not found on serverr   r   )rl   _async_get_object_by_uidrC  r$   r   r4  r  rd   r   r   r  items_foundr7   r  r8   get_object_by_uidj  s   	zCalendar.get_object_by_uidc                    s\   | j  ||ddddI dH } fdd|D }|s!td  tt|dk |d	 S )
z%Async helper for get_object_by_uid().Tr  r  Nc                    r  r7   r  r  r  r7   r8   re     r  z5Calendar._async_get_object_by_uid.<locals>.<listcomp>r  r   r   )rC  r$   r   r4  r  r	  r7   r  r8   r    s   z!Calendar._async_get_object_by_uidc                 C      | j |tdS )z
        Get a task/todo from the calendar by UID.

        Returns the task with the given uid.
        See :meth:`get_object_by_uid` for more details.
        r  )r  r    rd   r   r7   r7   r8   get_todo_by_uid     	zCalendar.get_todo_by_uidc                 C   r  )z
        Get an event from the calendar by UID.

        Returns the event with the given uid.
        See :meth:`get_object_by_uid` for more details.
        r  )r  r   r  r7   r7   r8   get_event_by_uid  r  zCalendar.get_event_by_uidc                 C   r  )z
        Get a journal entry from the calendar by UID.

        Returns the journal with the given uid.
        See :meth:`get_object_by_uid` for more details.
        r  )r  r   r  r7   r7   r8   get_journal_by_uid  r  zCalendar.get_journal_by_uidc                 O   r  )z
        Deprecated: Use :meth:`get_object_by_uid` instead.

        This method is an alias kept for backwards compatibility.
        )r  r}  r7   r7   r8   object_by_uid     zCalendar.object_by_uidc                 C   
   |  |S )z
        Deprecated: Use :meth:`get_event_by_uid` instead.

        This method is an alias kept for backwards compatibility.
        )r  r  r7   r7   r8   event_by_uid     
zCalendar.event_by_uidc                 C   r  )z
        Deprecated: Use :meth:`get_todo_by_uid` instead.

        This method is an alias kept for backwards compatibility.
        )r  r  r7   r7   r8   todo_by_uid  r  zCalendar.todo_by_uidc                 C   r  )z
        Deprecated: Use :meth:`get_journal_by_uid` instead.

        This method is an alias kept for backwards compatibility.
        )r  r  r7   r7   r8   journal_by_uid  r  zCalendar.journal_by_uid.list[Event] | Coroutine[Any, Any, list[Event]]c                 C      | j tdS )ay  
        List all events from the calendar.

        For sync clients, returns a list of Event objects directly.
        For async clients, returns a coroutine that must be awaited.

        Returns:
         * [Event(), ...]

        Example (sync):
            events = calendar.get_events()

        Example (async):
            events = await calendar.get_events()
        r  )rC  r   rc   r7   r7   r8   rG    s   zCalendar.get_eventsc                 C   rs   )z
        Deprecated: Use :meth:`get_events` instead.

        This method is an alias kept for backwards compatibility.
        )rG  rc   r7   r7   r8   events  rv   zCalendar.eventsrH  c                 C   s   ddl }g }|D ]*}t|dr#tjj|jv r#|t|jtjj  qt|dr2|t|j	  q|
  d|}|j| dd }d| S )	a  
        Generate a fake sync token for servers without sync support.
        Uses a hash of all ETags to detect changes.

        Args:
            objects: List of calendar objects to generate token from

        Returns:
            A fake sync token string
        r   Nrj   r,   |F)usedforsecurityfake-)hashlibr  r#   GetEtagr   rj   rR   r4   r,   r   r   r   md5encode	hexdigest)rd   rH  r   etagsrI  combined
hash_valuer7   r7   r8   _generate_fake_sync_token  s   


z"Calendar._generate_fake_sync_token
sync_tokenload_objectsdisable_fallbackdSynchronizableCalendarObjectCollection | Coroutine[Any, Any, SynchronizableCalendarObjectCollection]c              
   C   s  | j r
| |||S d}| jjjdtd}|ddkr%|r#tdd}|r3t	|t
r3|dr3d}|rz6| jj|d	gd
}| j|t gdd\}}|rc|D ]}	z|	  W qP tjyb   Y qPw t| ||jdW S  tjtjfy }
 z|rz td|
 d W Y d}
~
nd}
~
ww td t|  }|r|D ]}	t|	dr|	jdu rz|	  W q tjy   Y qw q|rFt|d drtjj|d jvrFz[| jt gdd}|t g}dd |D }tdt | d |! D ]0\}}t
| j"#|$ }||v r(t|| dsi || _|| j%| td|  qW n t&yE }
 ztd|
  W Y d}
~
nd}
~
ww | '|}|rft	|t
rf|drf||krft| g |dS t| ||dS )aE  get_objects_by_sync_token aka get_objects

        For async clients, returns a coroutine that must be awaited.

        Do a sync-collection report, ref RFC 6578 and
        https://github.com/python-caldav/caldav/issues/87

        This method will return all objects in the calendar if no
        sync_token is passed (the method should then be referred to as
        "objects"), or if the sync_token is unknown to the server.  If
        a sync-token known by the server is passed, it will return
        objects that are added, deleted or modified since last time
        the sync-token was set.

        If load_objects is set to True, the objects will be loaded -
        otherwise empty CalendarObjectResource objects will be returned.

        This method will return a SynchronizableCalendarObjectCollection object, which is
        an iterable.

        This method transparently falls back to retrieving all objects if the server
        doesn't support sync tokens. The fallback behavior is identical from the user's
        perspective, but less efficient as it transfers the entire calendar on each sync.

        If disable_fallback is set to True, the method will raise an exception instead
        of falling back to retrieving all objects. This is useful for testing whether
        the server truly supports sync tokens.
        T
sync-tokenr  r  unsupported+Sync tokens are not supported by the serverFr  getetagr)  rj   rj   r  r   rH  r)  Sync-collection REPORT failed (!), falling back to full retrievalN6Using fallback sync mechanism (retrieving all objects)_datar   rj   r   rk   c                 S      i | ]
}t |j |qS r7   r4   r,   r   ra   rI  r7   r7   r8   
<dictcomp>      z6Calendar.get_objects_by_sync_token.<locals>.<dictcomp>Fallback: Fetching ETags for  objectsFallback: Added ETag to )Failed to fetch ETags for fallback sync: )(rl    _async_get_objects_by_sync_tokenr^   r%  r&  r  rK   r$   ReportErrorrL   r4   r   _build_sync_collection_bodyr  r#   r!  r  r   &SynchronizableCalendarObjectCollectionr)  DAVErrorr?   rb   debugr6   rC  r  r7  r   rj   _query_propertiesr  r  itemsr,   r   r   updater>   r(  rd   r)  r*  r+  use_sync_tokensync_supportr  rq   rH  rI  eall_objects
etag_props
url_to_objurl_strrj   canonical_url_strfake_sync_tokenr7   r7   r8   get_objects_by_sync_token-  s   "


	



z"Calendar.get_objects_by_sync_tokenc                 O   r  )z
        Deprecated: Use :meth:`get_objects_by_sync_token` instead.

        This method is an alias kept for backwards compatibility.
        )rU  r}  r7   r7   r8   objects_by_sync_token  r  zCalendar.objects_by_sync_tokenrE  c              
      s  d}| j jjdtd}|ddkr|rtdd}|r*t|tr*|	dr*d}|rz<| j j
|d	gd
}| j|t gddI dH \}}|r`|D ]}	z	|	 I dH  W qJ tjy_   Y qJw t| ||jdW S  tjtjfy }
 z|rw td|
 d W Y d}
~
nd}
~
ww td t|  I dH }|r|D ] }	t|	dr|	jdu rz	|	 I dH  W q tjy   Y qw q|rLt|d drtjj|d jvrLz^| jt gddI dH }|t g}dd |D }tdt| d | D ]0\}}t| j !|" }||v r.t|| dsi || _|| j#| td|  qW n t$yK }
 ztd|
  W Y d}
~
nd}
~
ww | %|}|rlt|trl|	drl||krlt| g |dS t| ||dS )z2Async implementation of get_objects_by_sync_token.Tr-  r  r  r.  r/  Fr  r0  r1  r2  Nr3  r4  r5  r6  r7  r   rj   r   r8  c                 S   r9  r7   r:  r;  r7   r7   r8   r<    r=  z=Calendar._async_get_objects_by_sync_token.<locals>.<dictcomp>r>  r?  r@  rA  )&r^   r%  r&  r  rK   r$   rC  rL   r4   r   rD  r  r#   r!  r  r   rE  r)  rF  r?   rb   rG  r6   rC  r  r7  r   rj   rH  r  r  rI  r,   r   r   rJ  r>   r(  rK  r7   r7   r8   rB    s   





z)Calendar._async_get_objects_by_sync_token2list[Journal] | Coroutine[Any, Any, list[Journal]]c                 C   r  )zd
        List all journals from the calendar.

        Returns:
         * [Journal(), ...]
        r  )rC  r   rc   r7   r7   r8   get_journals  s   zCalendar.get_journalsc                 C   rs   )z
        Deprecated: Use :meth:`get_journals` instead.

        This method is an alias kept for backwards compatibility.
        )rX  rc   r7   r7   r8   journals%  rv   zCalendar.journals)NNNNNNr   )r9   r  r  r   )T)r9   rV  )NFF)FF)r9   r{  )r9   r  )r9   r  )r9   r^  )r9   ry   )F)NrO  r  F)NNF)r9   r  )r9   r   )NFTFNNNN)r9   r   )r  FN)r9   r  r   )r9   r  )r9   r,  )r9   rW  )Vr0   r1   r2   r3   r	   r4   r   r   r'   r   r<  r1  rD  rB  r   r  r6   rU  r\  rY  rg  ra  rm  typer!   rz  rw  r  r  r  r  r  r  r  r}   r  r   r  tupler(   r  r  r  r  r  r   r   r   r  r  r  r  r  r  r  r"   r  rC  r   r   r  r  rb  r  
CompFilterr  r  r  r  r  r  r  r  r  rL  rG  r  r(  rU  rV  rH  get_objectsrB  rX  rY  r  r7   r7   r   r8   r]     s   	

P
4'




1





	
		
 " 



H#

#
 



$	
-













 



T	r]   c                	       sd   e Zd ZdZ			dded dedB deeB eB e	B dB ddf fdd	Z
dddZdd Z  ZS )ScheduleMailboxaw  
    RFC6638 defines an inbox and an outbox for handling event scheduling.

    TODO: As ScheduleMailboxes works a bit like calendars, I've chosen
    to inheritate the Calendar class, but this is a bit incorrect, a
    ScheduleMailbox is a collection, but not really a calendar.  We
    should create a common base class for ScheduleMailbox and Calendar
    eventually.
    Nr^   r   r   r,   r9   c              	      s  t  j||d d| _|s|r|j| _|s$|r$| jdu r td| jj}|dur<|du r0td|jt	|| _dS |du rDtd| jdu rMtd|j| _z| jjt| 
|  | _W dS  ty   tjddd t| j  d| _td	t|  tjf dw )
z9
        Will locate the mbox if no url is given
        r   Nr   z Unexpected value None for clientz#Unexpected value None for principalzsomething bad happenedTr#  zprincipal has no %s.  %s)r   r   _itemsr^   r   r   r,   r   r'   r   r   findpropr>   r  r$   r4  check_scheduling_supportr   r4   ERR_FRAGMENT)rd   r^   r   r,   r   r7   r8   r   9  s:   	

$zScheduleMailbox.__init__ list | Coroutine[Any, Any, list]c                    s    j r  S  fdd} js2z jdd _W  jS  ty1   td j |  _Y  jS w z	 j  W  jS  tyJ   |  _Y  jS w )u3  Return all items currently in this scheduling mailbox (inbox or outbox).

        For async clients, returns a coroutine that must be awaited.

        Unlike regular calendars, schedule mailboxes contain raw iTIP messages
        (METHOD:REQUEST, METHOD:REPLY, METHOD:CANCEL, …) rather than permanent
        calendar objects.  Items should be processed and then deleted; they are
        not meant to be kept indefinitely.

        Servers often do not support the sync-collection REPORT (RFC 6578) on
        schedule-inbox/outbox — the inbox is not a full calendar collection and
        may not be indexed the same way.  We therefore attempt the sync-token
        path first (efficient for repeat polling) but fall back transparently to
        a plain PROPFIND depth-1 followed by individual GETs.  Both paths return
        loaded CalendarObjectResource objects.

        Claude says that this method does NOT belong on the Calendar
        super-class.  Calendar exposes type-specific accessors
        (get_events, get_todos, …) and uses search() internally.  The
        mailbox is a different beast — it holds transient, mixed-type
        scheduling messages and must use children() as its fallback
        because search() / REPORT queries against a mailbox URL are
        unreliable across servers.
        c                     s,    fdd   D } | D ]}|  q| S )Nc                       g | ]}t |d   jdqS r   )r,   r^   r   r^   r   rc   r7   r8   re     s    zJScheduleMailbox.get_items.<locals>._load_from_children.<locals>.<listcomp>childrenr  rI  r   rc   r7   r8   _load_from_children  s   
z6ScheduleMailbox.get_items.<locals>._load_from_childrenTr*  _sync-collection REPORT not supported on scheduling mailbox %s; falling back to PROPFIND depth-1)	rl   _async_get_itemsr_  rH  r>   r  rG  r,   syncrd   rj  r7   rc   r8   	get_itemsf  s,   

zScheduleMailbox.get_itemsc                    s    fdd} j s2z jddI dH  _ W  j S  ty1   td j | I dH  _ Y  j S w z j  I dH  W  j S  tyP   | I dH  _ Y  j S w )z"Async implementation of get_items.c                     s:    fdd   I d H D } | D ]	}| I d H  q| S )Nc                    rd  re  rf  r   rc   r7   r8   re     s    zQScheduleMailbox._async_get_items.<locals>._load_from_children.<locals>.<listcomp>rg  ri  rc   r7   r8   rj    s   
z=ScheduleMailbox._async_get_items.<locals>._load_from_childrenTrk  Nrl  )r_  rH  r>   r  rG  r,   _async_syncro  r7   rc   r8   rm    s*   z ScheduleMailbox._async_get_itemsr  )r9   rc  )r0   r1   r2   r3   r	   r   r4   r   r   r'   r   rp  rm  r  r7   r7   r   r8   r^  .  s     
-3r^  c                   @      e Zd ZejZdS )r   N)r0   r1   r2   r"   r  r`  r7   r7   r7   r8   r         
r   c                   @   rr  )r  N)r0   r1   r2   r"   r
  r`  r7   r7   r7   r8   r    rs  r  c                	   @   s   e Zd ZdZdddZdee fddZdefdd	Z	d
d Z
dededeee ee f fddZ		dddZdeeef fddZdS )rE  z
    This class may hold a cached snapshot of a calendar, and changes
    in the calendar can easily be copied over through the sync method.

    To create a SynchronizableCalendarObjectCollection object, use
    calendar.objects(load_objects=True)
    r9   Nc                 C   s   || _ || _|| _d | _d S r   )r   r)  rH  _objects_by_url)rd   r   rH  r)  r7   r7   r8   r     s   
z/SynchronizableCalendarObjectCollection.__init__c                 C   s
   | j  S r   )rH  __iter__rc   r7   r7   r8   ru       
z/SynchronizableCalendarObjectCollection.__iter__c                 C   s
   t | jS r   )r  rH  rc   r7   r7   r8   __len__  rv  z.SynchronizableCalendarObjectCollection.__len__c                 C   s0   | j du ri | _ | D ]
}|| j |j < q
| j S )zp
        returns a dict of the contents of the SynchronizableCalendarObjectCollection, URLs -> objects.
        N)rt  r,   r   )rd   rI  r7   r7   r8   objects_by_url  s
   
z5SynchronizableCalendarObjectCollection.objects_by_urlcurrent_by_url
old_by_urlc           	      C   s   g }g }|  D ]3\}}||v r6t|| dr|| jnd}t|dr&|jnd}||kr5|dur5|| q|| q|D ]}||vrK|||  q>t| | _d| _| j	| j| _
||fS )zPure post-processing for the fallback sync path (no I/O).

        Compares current server state against cached state to determine what
        changed, then updates internal state.
        r   N)rI  r  r   rR   r6   valuesrH  rt  r   r(  r)  )	rd   ry  rz  updated_objsdeleted_objsr,   rI  old_datanew_datar7   r7   r8   _post_sync_fallback  s$   
z:SynchronizableCalendarObjectCollection._post_sync_fallback6tuple[Any, Any] | Coroutine[Any, Any, tuple[Any, Any]]c           	   	   C   s  | j jr|  S g }g }t| jto| jd}|sz| j j| jdd}t|jtr3|jdr3d}no|  }|D ]U}|j	
 |_	|j	|v ritjj||j	 jv ritjj|jv ri||j	 jtjj |jtjj kriq9|||j	< z|  || W q9 tjy   || ||j	 Y q9w t| | _d| _|j| _||fW S W n tjtjfy   d}Y nw td t| j  }|D ]}z|  W q tjy   Y qw dd |D }| ||  S )	a  Contact the server, fetch changes, and update the local collection.

        Falls back to comparing the full calendar state when the server does
        not support sync tokens.

        Returns a coroutine for async clients; call with ``await`` in that case.
        r  Frk  TN5Using fallback sync mechanism (comparing all objects)c                 S      i | ]}|j  |qS r7   r,   r   r;  r7   r7   r8   r<  ?	      z?SynchronizableCalendarObjectCollection.sync.<locals>.<dictcomp>)r   rl   rq  rL   r)  r4   r   rU  rx  r,   r   r#   r!  r   rj   r  rR   r$   r   r  r6   r{  rH  rt  rC  rF  r?   rG  rC  r  	rd   r|  r}  is_fake_tokenupdatesoburI  current_objectsry  r7   r7   r8   rn    s\   

"



z+SynchronizableCalendarObjectCollection.syncc           	   	      s  g }g }t | jto| jd}|sz| jj| jddI dH }t |jtr/|jdr/d}nr|  }|D ]X}|j |_|j|v ret	j
j||j jv ret	j
j|jv re||j jt	j
j |jt	j
j kreq5|||j< z| I dH  || W q5 tjy   || ||j Y q5w t| | _d| _|j| _||fW S W n tjtjfy   d}Y nw td t| j I dH }|D ]}z	| I dH  W q tjy   Y qw dd |D }| ||  S )	zAsync implementation of sync().

        NOTE: the real-token loop mixes I/O (await obj.load()) with data
        manipulation; any changes here must be mirrored in sync().
        r  Frk  NTr  c                 S   r  r7   r  r;  r7   r7   r8   r<  w	  r  zFSynchronizableCalendarObjectCollection._async_sync.<locals>.<dictcomp>)rL   r)  r4   r   r   rU  rx  r,   r   r#   r!  r   rj   r  rR   r$   r   r  r6   r{  rH  rt  rC  rF  r?   rG  rC  r  r  r7   r7   r8   rq  B	  sZ   
"



z2SynchronizableCalendarObjectCollection._async_syncr  )r9   r  )r0   r1   r2   r3   r   r   r   ru  r   rw  rx  r  r[  r6   r  rn  rq  r7   r7   r7   r8   rE    s"    



CrE  )Mr3   r  r   r  dataclassesr   r   r   r  r   timer   typingr   r   r	   r
   urllib.parser   r   r   r   r   r   r   r   	davclientr   rC  r   collections.abcr   r   r   r   r   base_clientr   calendarobjectresourcer   r   r   r   r    	davobjectr!   elementsr"   r#   libr$   r%   lib.python_utilitiesr&   lib.urlr'   r(   	getLoggerr?   r+   r4   rA   rH   r  r  rN   r6   rU   rY   r[   r\   r   r]   r^  r   r  rE  r7   r7   r7   r8   <module>   sr     

			    	            