
    Dj-/                    `   d Z ddlmZ ddlZddlZddlZddlmZmZm	Z	m
Z
mZmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZmZmZ dd	l m!Z!  ej"        e#          Z$d
Z% G d de&          Z' G d de'          Z( G d de'          Z) G d de'          Z* G d d          Z+dS )a   
Low-level CloudKit client for the Notes container.

This "escape hatch" is also used internally by NotesService to implement
developer-friendly methods. It returns typed Pydantic models from
pyicloud.services.notes_models.cloudkit and hides HTTP details.
    )annotationsN)DictIterableIteratorListNoReturnOptional)ValidationError)

CKFVStringCKLookupResponseCKQueryFilterByCKQueryObjectCKQueryResponseCKZoneChangesZoneCKZoneChangesZoneReqCKZoneIDCKZoneIDReqCloudKitExtraMode)CloudKitApiErrorCloudKitAuthErrorCloudKitContainerClientCloudKitRateLimitedredact_cloudkit_url   )NOTES_ZONE_REQ)g      $@g      N@c                      e Zd ZdZdS )
NotesErrorzBase Notes transport error.N__name__
__module____qualname____doc__     Y/home/thesage/.hermes/venv/lib/python3.11/site-packages/pyicloud/services/notes/client.pyr   r   /   s        %%%%r$   r   c                      e Zd ZdZdS )NotesAuthErrorz!Auth/PCS/cookie issues (401/403).Nr   r#   r$   r%   r'   r'   3   s        ++++r$   r'   c                  &     e Zd ZdZdd	 fdZ xZS )
NotesRateLimitedz429 Too Many Requests.Nmessagestrretry_afterOptional[float]c                X    t                                          |           || _        d S N)super__init__r,   )selfr*   r,   	__class__s      r%   r1   zNotesRateLimited.__init__:   s)    !!!&r$   r/   )r*   r+   r,   r-   r   r    r!   r"   r1   __classcell__r3   s   @r%   r)   r)   7   sH          ' ' ' ' ' ' ' ' ' ' 'r$   r)   c                  &     e Zd ZdZdd	 fdZ xZS )
NotesApiErrorzCatch-all API error.Nr*   r+   payloadOptional[object]c                X    t                                          |           || _        d S r/   )r0   r1   r9   )r2   r*   r9   r3   s      r%   r1   zNotesApiError.__init__B   s&    !!!r$   r/   )r*   r+   r9   r:   r4   r6   s   @r%   r8   r8   ?   sH                  r$   r8   c                      e Zd ZdZdedd>dZed?d            Zd@dZdddddAd!Z	dd"dBd&Z
dCd*Zd+d,dDd1ZdEd3ZdFd5ZedGd9            ZedHd=            ZdS )ICloudKitNotesClientz
    Raw CloudKit service for the Notes container.

    Methods map 1:1 to CloudKit endpoints:
      - /records/query
      - /records/lookup
      - /changes/zone
    N)validation_extratimeoutbase_urlr+   base_paramsDict[str, object]r>   CloudKitExtraMode | Noner?   tuple[float, float]c          
         t          |||||dd| j                  | _        || _        t                              d           d S )NlowerT)r>   r?   bool_param_styleredact_urls
debug_hookz CloudKitNotesClient initialized.)r   _dump_http_debug_client_validation_extraLOGGERinfo)r2   r@   sessionrA   r>   r?   s         r%   r1   zCloudKitNotesClient.__init__T   sX     /-$,	
 	
 	
 "2677777r$   exc	Exceptionreturnr   c                ^   | j         p| }t          | t                    rt          t	          |                     |t          | t
                    r$t          t	          |           | j                  |t          | t                    r$t          t	          |           | j
                  | )N)r,   )r9   )	__cause__
isinstancer   r'   r+   r   r)   r,   r   r8   r9   )rP   causes     r%   _raise_notes_errorz&CloudKitNotesClient._raise_notes_errorj   s    $c,-- 	6 S**5c.// 	U"3s88IIIuTc+,, 	JC#+>>>EIr$   opboolc                    t          |t                    r?t          |j        t                    r%|                     ||j        pi |j                   dS dS )NTF)rU   r   rT   r
   _log_validationr9   )r2   rX   rP   s      r%   _log_cloudkit_validationz,CloudKitNotesClient._log_cloudkit_validationu   sZ    c+,, 	M?2
 2
 	   S[%6BFFF4ur$   )desired_keysresults_limitcontinuationqueryr   zone_idr   r]   Optional[List[str]]r^   Optional[int]r_   Optional[str]r   c                  t                               d|j                   	 | j                            |||||          }t                               dt          |j                             |S # t          t          t          f$ rP}| 
                    d|          rt                               d           |                     |           Y d }~d S d }~ww xY w)Nz"Executing query for recordType: %s)r`   ra   r]   r^   r_   zQuery returned %d records.zrecords.queryz!Query response validation failed.)rM   rN   
recordTyperK   r`   lenrecordsr   r   r   r\   errorrW   )r2   r`   ra   r]   r^   r_   resprP   s           r%   r`   zCloudKitNotesClient.query   s     	8%:JKKK	)<%%)+) &  D KK4c$,6G6GHHHK "35HI 	) 	) 	),,_cBB B@AAA##C(((((((((	)s   AA0 0CACC)r]   record_namesIterable[str]r   c                  t          |          }t                              dt          |                     	 | j                            |t          |          }t                              dt          |j                             |S # t          t          t          f$ rP}|                     d|          rt                              d           |                     |           Y d }~d S d }~ww xY w)Nz Executing lookup for %d records.)ra   r]   zLookup returned %d records.zrecords.lookupz"Lookup response validation failed.)listrM   rN   rg   rK   lookupr   rh   r   r   r   r\   ri   rW   )r2   rk   r]   record_names_listrj   rP   s         r%   ro   zCloudKitNotesClient.lookup   s     !..6<M8N8NOOO	)<&&!&) '  D
 KK5s4<7H7HIIIK "35HI 	) 	) 	),,-=sCC CABBB##C(((((((((	)s   AB
 
C1!AC,,C1zone_reqr   Iterator[CKZoneChangesZone]c             #  P  K   t                               d|j        j                   d}	 | j                            |          D ]u}t                               d|t          |j                             |V  |j        rt           	                    d           nt                               d           |dz  }vd S # t          t          t          f$ rP}|                     d|          rt                               d           |                     |           Y d }~d S d }~ww xY w)	Nz#Start fetching changes for zone: %sr   rq   z$Changes page %d returned %d records.z+More changes to come, advancing sync token.zAll changes fetched.zchanges.zonez#Changes response validation failed.)rM   rN   zoneIDzoneNamerK   iter_changesrg   rh   
moreComingdebugr   r   r   r\   ri   rW   )r2   rq   page_numzonerP   s        r%   changeszCloudKitNotesClient.changes   sF     
 	98?;STTT	)1181DD  :%%  
 


? 8LL!NOOOOKK 6777A  !"35HI 	) 	) 	),,^SAA DBCCC##C(((((((((	)s   BB> >D%AD  D%i   
chunk_sizeurlr~   intIterator[bytes]c             #     K   	 | j                             ||          E d {V  d S # t          t          t          f$ r }|                     |           Y d }~d S d }~ww xY w)Nr}   )rK   download_asset_streamr   r   r   rW   )r2   r   r~   rP   s       r%   r   z)CloudKitNotesClient.download_asset_stream   s      	)|99% :            !"35HI 	) 	) 	)##C(((((((((	)s   "( AAA	directoryc                   dd l }dd l}t                              dt	          |          |            |j        |d           d|                                j         }|j        	                    ||          }t          |d          5 }|                     |          D ]}|                    |           	 d d d            n# 1 swxY w Y   t                              d|           |S )Nr   z)Downloading asset from %s to directory %sTexist_okzicloud-asset-wbz Finished downloading asset to %s)osuuidrM   rN   r   makedirsuuid4hexpathjoinopenr   write)	r2   r   r   r   r   fnamer   fchunks	            r%   download_asset_toz%CloudKitNotesClient.download_asset_to   s2   			7$$	
 	
 	

 	I----2

 022w||Iu--$ 	33C88  	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	6===s   .CC
C
	zone_namec                  t                               d|           t                               d           t          dt	          ddt          dd          	          g
          }	 | j                            |t          |                    }|rt                               d           |S n2# t          $ r%}t           
                    d|           Y d}~nd}~ww xY wt                               d           t          t          |d          g g d          }	 | j                            |          }n9# t          t          t           f$ r}|                     |           Y d}~nd}~ww xY w|j        r|j        d         nd}|r?t'          |dd          r.t                               d           t)          |j                  S t                               d|           t/          d          )aZ  
        Fetch a current sync token cheaply by issuing a zero-limit query that
        requests getCurrentSyncToken=true (already in params) and reading the top-level token.

        Some deployments place the token in CKQueryResponse.syncToken; if absent,
        we fall back to a one-shot changes call (no records) to harvest a token.
        z(Fetching current sync token for zone: %sz-Attempting to get sync token via cheap query.SearchIndexesEQUALS	indexNameSTRINGrecents)typevalue)
comparator	fieldName
fieldValue)rf   filterBy)rv   )r`   ra   z+Successfully obtained sync token via query.z;Failed to get sync token via query, falling back. Error: %sNz0Falling back to get sync token via changes call.REGULAR_CUSTOM_ZONE)rv   zoneTypeF)ru   desiredRecordTypesdesiredKeysreversert   r   	syncTokenz2Successfully obtained sync token via changes call.z(Failed to obtain sync token for zone: %szUnable to obtain sync token)rM   rN   ry   r   r   r   rK   query_sync_tokenr   rQ   warningr   r   r|   r   r   r   rW   zonesgetattrr+   r   ri   r8   )	r2   r   qtokenerq   envrP   zs	            r%   current_sync_tokenz&CloudKitNotesClient.current_sync_token   s7    	>	JJJDEEE&'))xyIII  	
 	
 	
	L11#Y777 2  E  IJJJ  	 	 	NNMq   DDDD	 	GHHH'Y9NOOO!	
 
 
	),&&&99CC "35HI 	) 	) 	)##C((((((((	)I/CIaLL4 	$K.. 	$KKLMMMq{###?KKK9:::s1   (AB1 1
C ;CC  D< <E2E--E2r9   r   Nonec                   t          j        d          sd S t          d                              d          }|                     dd          }t           j                            dd          }	 t          j        |d	           n# t          $ r Y d S w xY wt           j                            || d
| d          }	 t          |dd          5 }t          j        ||d|dd           d d d            n# 1 swxY w Y   n# t          $ r Y nw xY wt           j                            || d
| d          }		 t          |dd           }
t          |di           }d }	 |j        }n# t          $ r d }Y nw xY wt          |	dd          5 }|                    d|
 d| dt          |           d           |rkt!          t          j        dd                    }t#          |          |k    r!|                    |d |         dz              n|                    |           d d d            d S # 1 swxY w Y   d S # t          $ r Y d S w xY w)NPYICLOUD_NOTES_DEBUGtime%Y%m%d-%H%M%S/.	workspacenotes_debugTr   _z_http_request.jsonwutf-8encoding)r   r9   F   ensure_asciiindentz_http_response.txtstatus_codeheaderszstatus=z
url=z	
headers=z

PYICLOUD_DEBUG_MAX_BYTES524288z
[truncated]
)r   getenv
__import__strftimereplacer   r   r   rQ   r   jsondumpr   textr   dictr   rg   )rX   r   r9   rj   tssafe_opout_dirreq_pathr   res_pathstatusr   	body_text	max_bytess                 r%   rJ   z$CloudKitNotesClient._dump_http_debug(  s7   y/00 	F((99**S#&&',,{M::	K$///// 	 	 	FF	7<<B)L)L)L)L)LMM	hg666 !	G44aeTU                   	 	 	D	7<<B)L)L)L)L)LMM	T=$77FdIr22GI! I		 ! ! ! 			!hg666 +!R&RRRRtG}}RRRSSS + #BI.H($S$S T TI9~~	11	*9* 58I IJJJJ	***+ + + + + + + + + + + + + + + + + +  	 	 	DD	s   0B 
BB?D C9-D 9C==D  C=D 
DD<$I !E) (I )E85I 7E88I BH4'I 4H88I ;H8<I 
IIdataerrr
   c                *   t          j        d          sd S t          d                              d          }t           j                            dd          }	 t          j        |d           n# t          $ r Y d S w xY wt           j                            || d|  d	          }	 t          |d
d          5 }t          j
        | |                                |d|dd           d d d            d S # 1 swxY w Y   d S # t          $ r Y d S w xY w)Nr   r   r   r   r   Tr   r   z_validation.jsonr   r   r   )rX   errorsr   Fr   r   )r   r   r   r   r   r   r   rQ   r   r   r   r   )rX   r   r   r   r   r   r   s          r%   r[   z#CloudKitNotesClient._log_validationO  s   y/00 	F((99',,{M::	K$///// 	 	 	FF	w||G%A%AR%A%A%ABB		dC'222 a	tDD!&	                      	 	 	DD	sH   A1 1
A?>A?)D ;/C7*D 7C;;D >C;?D 
DD)r@   r+   rA   rB   r>   rC   r?   rD   )rP   rQ   rR   r   )rX   r+   rP   rQ   rR   rY   )r`   r   ra   r   r]   rb   r^   rc   r_   rd   rR   r   )rk   rl   r]   rb   rR   r   )rq   r   rR   rr   )r   r+   r~   r   rR   r   )r   r+   r   r+   rR   r+   )r   r+   rR   r+   )rX   r+   r   r+   r9   r   rR   r   )rX   r+   r   r   r   r
   rR   r   )r   r    r!   r"   DEFAULT_TIMEOUTr1   staticmethodrW   r\   r`   ro   r|   r   r   r   rJ   r[   r#   r$   r%   r=   r=   J   se         6:'68 8 8 8 8 8,    \    -1'+&*) ) ) ) ) )> -1	) ) ) ) ) ).) ) ) )>  	) ) ) ) ) )   (6; 6; 6; 6;t $ $ $ \$L    \  r$   r=   ),r"   
__future__r   r   loggingr   typingr   r   r   r   r   r	   pydanticr
   pyicloud.common.cloudkitr   r   r   r   r   r   r   r   r   r   pyicloud.common.cloudkit.clientr   r   r   r   r   
_constantsr   	getLoggerr   rM   r   rQ   r   r'   r)   r8   r=   r#   r$   r%   <module>r      sM    # " " " " "   				 E E E E E E E E E E E E E E E E $ $ $ $ $ $                                     ' & & & & &		8	$	$& & & & & & & &, , , , ,Z , , ,' ' ' ' 'z ' ' '    J   Y Y Y Y Y Y Y Y Y Yr$   