
    =[j(                       d Z ddlmZ ddlZddlmZmZmZmZ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mZmZ ddlmZm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#m$Z$m%Z%m&Z&m'Z' d	dl(m)Z)m*Z* d	dl+m,Z,m-Z-m.Z. d	dl/m0Z0m1Z1 d	dl2m3Z3m4Z4  ej5        e6          Z7dZ8 G d de&          Z9 G d de&          Z: G d de          Z;dS )a  
High-level Apple Notes service built on top of a preconfigured CloudKit client.

Public API:
  - NotesService.recents(limit=50) -> Iterable[NoteSummary]
  - NotesService.recents_in_folder(folder_id, limit=20) -> Iterable[NoteSummary]
  - NotesService.iter_all(since=None) -> Iterable[NoteSummary]
  - NotesService.folders() -> Iterable[NoteFolder]
  - NotesService.in_folder(folder_id, limit=None) -> Iterable[NoteSummary]
  - NotesService.get(note_id, with_attachments=False) -> Note
  - NotesService.sync_cursor() -> str
  - NotesService.export_note(note_id, output_dir, **config_kwargs) -> str
  - NotesService.render_note(note_id, **config_kwargs) -> str
  - NotesService.iter_changes(since=None) -> Iterable[ChangeEvent]
  - NotesService.raw -> CloudKitNotesClient

Prefer the typed service methods for normal use. ``raw`` is an escape hatch for
advanced or unsupported CloudKit workflows.
    )annotationsN)DictIterableIteratorListOptional)CKErrorItem
CKFVStringCKLookupResponseCKQueryFilterByCKQueryObjectCKQueryResponseCKQuerySortByCKRecordCKReferenceCKTombstoneRecordCKZoneChangesZoneReqCloudKitExtraMode)CKReferenceFieldCKReferenceListField)BaseService)BodyDecoder   )
NOTES_ZONENOTES_ZONE_NAMENOTES_ZONE_REQ)CloudKitNotesClientNotesApiErrorNotesAuthError
NotesErrorNotesRateLimited)AttachmentIdNoteBody)
AttachmentNoteNoteSummary)NotesDesiredKeyNotesRecordType)ChangeEvent
NoteFolderHasSubfolderc                      e Zd ZdZdS )NoteNotFoundz#Raised when a note cannot be found.N__name__
__module____qualname____doc__     g/home/thesage/.hermes/hermes-agent/venv/lib/python3.11/site-packages/pyicloud/services/notes/service.pyr-   r-   =   s        --Dr4   r-   c                      e Zd ZdZdS )NoteLockedErrorz@Raised when a note is password protected and cannot be accessed.Nr.   r3   r4   r5   r7   r7   C   s        JJDr4   r7   c                      e Zd ZdZdZdZdZddd[ fdZddd\dZddd]dZ	ddd^dZ
d_dZddd`dZd d!dad&Zdbd'Zdcd)Zddd*Zddded,Zedfd.            Zdgd/Zdd0dhd4Zedid7            Zedjd:            Zdkd<Zdld=Zdmd?ZdndAZddBdodFZedpdI            ZedqdK            ZdrdMZ edsdN            Z!edpdO            Z"edtdQ            Z#dudUZ$dVdWdvdZZ% xZ&S )wNotesServicea#  
    Typed, developer-friendly Notes API.

    The service exposes lightweight listing helpers, full-note retrieval,
    attachment download helpers, and HTML render/export utilities while hiding
    most CloudKit details behind ``NoteSummary``, ``Note``, and ``Attachment``
    models.
    zcom.apple.notes
productionprivateN)cloudkit_validation_extraservice_rootstrparamsDict[str, str]r<   CloudKitExtraMode | Nonec                   t                                          |||           | j         d| j         d| j         d| j         }ddd|pi }t          ||||          | _        i | _        i | _	        d S )N)r=   sessionr?   z/database/1//T)
remapEnumsgetCurrentSyncToken)base_urlrC   base_paramsvalidation_extra)
super__init__r=   
_CONTAINER_ENV_SCOPEr   _raw_folder_name_cache_attachment_meta_cache)selfr=   rC   r?   r<   endpointrH   	__class__s          r5   rK   zNotesService.__init__Z   s     	lGFSSS'``T_``ty``SWS^`` #'
 
 |

 (#6	
 
 
	 =?=?###r4   2   limitrW   intreturnIterable[NoteSummary]c             #  j  K   |dk    rdS t           j        t           j        t           j        t           j        t           j        t           j        t           j        t           j        t           j	        g	}t          dt          ddt          dd          	          gt          d
d          g          }d}d}t                              d|           	 ||z
  }|dk    rdS | j                            |t$          |                     |          t)          d|          |          }|j        D ]Y}t-          |t.                    rB|                     |          }	|dz  }|	V  ||k    rt                              d|            dS Zt3          |dd          }|st                              d           dS )a   
        Yield the newest note summaries, ordered most-recent first.

        Args:
            limit: Maximum number of notes to yield.

        Yields:
            ``NoteSummary`` instances with lightweight metadata suitable for
            feeds, selectors, or navigation UIs.
        r   NSearchIndexesEQUALS	indexNameSTRINGrecentstypevalue
comparator	fieldName
fieldValuemodTimeF)rf   	ascending)
recordTypefilterBysortByzFetching recents: limit=%dT   queryzone_iddesired_keysresults_limitcontinuationr   z)Recents: yielded %d notes (limit reached)continuationMarkerz+Recents: no more continuation marker, done.)r'   TITLE_ENCRYPTEDSNIPPET_ENCRYPTEDMODIFICATION_DATEDELETEDFOLDERFIRST_ATTACHMENT_UTI_ENCRYPTEDFIRST_ATTACHMENT_THUMBNAIL&FIRST_ATTACHMENT_THUMBNAIL_ORIENTATIONATTACHMENTSr   r   r
   r   LOGGERdebugrO   ro   r   _coerce_keysminrecords
isinstancer   _summary_from_recordgetattr)
rR   rW   rq   ro   yieldedcont	remainingresprecsummarys
             r5   r`   zNotesService.recentsv   s      A::F +--#":6B'

 &'))xyIII   "IGGGH

 

 

 "15999	IA~~$(IOO&!..|<<!#y11! %4 % %D | 	 	c8,, "77<<GqLG!MMM%''G   4!5t<<D JKKK1	r4      	folder_idc             #  ,  K   |dk    rdS d}t          d|dz            }t                              d||           |                     |          D ]A}|j        |k    r4|j        s-|V  |dz  }||k    rt                              d|            dS BdS )	z
        Yield recent note summaries that belong to ``folder_id``.

        This is a convenience helper that filters the global recents feed rather
        than scanning the full Notes history.
        r   Nrm      z1Fetching recents in folder: folder_id=%s limit=%drV   r   z3Recents in folder: yielded %d notes (limit reached))maxr~   r   r`   r   
is_deleted)rR   r   rW   emittedwindowns         r5   recents_in_folderzNotesService.recents_in_folder   s       A::FS%!)$$?E	
 	
 	
 F++ 	 	A{i'''1e##LLMw   FF	 	r4   )sincer   Optional[str]c             #  F  K   |                      |          rt                              d           dS t                              d|rd| nd           | j                            t          t          t          j        g| 	                    t          j        t          j        t          j        t          j        t          j        t          j        g          |d                    D ]8}|j        D ].}t%          |t&                    r|                     |          V  /9dS )	ao  
        Yield note summaries from the Notes changes feed.

        Args:
            since: Optional sync token from ``sync_cursor()``. When provided, the
                iterator yields only note records changed since that cursor.

        Yields:
            ``NoteSummary`` instances for full exports, indexing jobs, or local
            cache refreshes.
        z6Skipping Notes full scan because sync token is currentNzIterating all notes%s since= FzoneIDdesiredRecordTypesdesiredKeys	syncTokenreversezone_req)_matches_current_sync_cursorr~   r   rO   changesr   r   r(   r%   r   r'   ru   rv   rw   rx   ry   r}   r   r   r   r   )rR   r   zoner   s       r5   iter_allzNotesService.iter_all   s5      ,,U33 	LLQRRRF,5.P.?.?.?.?bQQQI%%)!$3$8#9 --'7'9'9'/'.'3	 	     & 
 
 	9 	9D& | 9 9c8,, 933C888889'	9 	9r4   Iterable[NoteFolder]c              #  $  K   t           j        t          g}t          dt	          ddt          dd                    g          }d	}t                              d
           	 | j        	                    |t          |                     |          d|          }|j        D ]}t          |t                    r|j        }|                     |j                            d                    }t'          |j                            t                    pddd	          }|d	nt+          |          }	t-          |||	d	          V  | j                            ||           t'          |dd	          }|st                              d           d	S .)z
        Yield top-level Notes folders as ``NoteFolder`` models.

        Use this to build folder navigation or resolve folder IDs before calling
        ``in_folder()``.
        r\   r]   r^   r_   
parentlessra   rd   )rj   rk   NzFetching foldersTrm   rn   TitleEncryptedr3   rc   )idnamehas_subfolderscountrt   z+Folders: no more continuation marker, done.)r'   ru   _HAS_SUBFOLDER_FIELDr   r   r
   r~   r   rO   ro   r   r   r   r   r   
recordName_decode_encryptedfields	get_valuer   	get_fieldboolr*   rP   
setdefault)
rR   rq   ro   r   r   r   r   r   has_sub_valuehas_subs
             r5   folderszNotesService.folders   s      + 
 &'))x|LLL  	
 	
 	
 #'(((	$(IOO&!..|<<!! %4 % %D | H Hc8,, H #I11
,,-=>> D %,
,,-ABBHb% %M
 '4&;ddmATATG$$4t      +66y$GGG4!5t<<D JKKK9	r4   Optional[int]c             #    K   d}t                               d||           | j                            t	          t
          t          j        g|                     t          j
        t          j        t          j        t          j        t          j        t          j        t          j        t          j        t          j        g	          d                    D ]}|j        D ]}t)          |t*                    s|                     |          }t/          |j                            d          pd          }|s||k    r_|                     |          V  |dz  }|r%||k    rt                               d	|             d
S d
S )z
        Yield non-deleted notes in ``folder_id``, ordered newest first.

        Args:
            folder_id: Folder identifier from ``folders()`` or note metadata.
            limit: Optional maximum number of notes to yield.
        r   z/Fetching notes in folder: folder_id=%s limit=%sT)r   r   r   r   r   DeletedFr   z1Notes in folder: yielded %d notes (limit reached)N)r~   r   rO   r   r   r   r(   r%   r   r'   ru   rv   rw   rx   ry   rz   r{   r|   r}   r   r   r   _extract_folder_idr   r   r   r   )rR   r   rW   r   r   r   rec_folder_iddeleteds           r5   	in_folderzNotesService.in_folder/  s      =y%	
 	
 	
 I%%)!$3$8#9 --'7'9'9'/'.'F'B'N'3
  !   & 
 
 !	 !	D( |  !#x00  $ 7 7 < <sz33I>>G%HH my88//444441 W--LLKW   FFF)!	 !	r4   F)with_attachmentsnote_idr   r   r%   c                  t                               d||           |                     |t          j        t          j        t          j        t          j        t          j        t          j	        dg          }| 
                    |          }|j        r5t                               d|           t          d|j        p| d          |                     |          }	 |r;|j        r4t                               d|j        t'          |j                             n t                               d|j                   n6# t(          $ r) t                               d	|r	|j        rd
nd           Y nw xY wd}d}|r|j        nd}g }	|r|j        r|j        }	|r|                     ||	          }t/          |j        |j        |j        |j        |j        |j        |j        |j        |||          S )a  
        Return a single note with decoded text and optional attachment metadata.

        Args:
            note_id: The CloudKit note record identifier.
            with_attachments: When ``True``, resolve ``Attachment`` metadata and
                include it on the returned ``Note``.

        Raises:
            NoteNotFound: If the note does not exist.
            NoteLockedError: If the note is passphrase-locked and its content
                cannot be read.
        z-Fetching note: note_id=%s with_attachments=%sTextDataEncryptedrq   z%Note is locked and cannot be read: %szNote 'z' is locked and cannot be read.z"notes.body.decoded ok id=%s len=%dznotes.body.decoded empty id=%sznotes.body.decoded %sokemptyNattachment_ids)r   titlesnippetmodified_atr   folder_namer   	is_lockedtexthtmlattachments)r~   r   _lookup_note_recordr'   ru   rv   rw   rx   ry   r}   r   r   warningr7   r   _decode_note_bodyr   infor   len	Exceptionr   _resolve_attachments_for_recordr%   r   r   r   r   r   )
rR   r   r   targetr   	note_bodyr   r   r   r   s
             r5   getzNotesService.get`  sB    	;WFV	
 	
 	
 ))/11'&+# * 
 
 ++F33 	NNBGLLL!R1'RRR   **622		 JY^ J8J	''    <gjIII 	 	 	KK'!AinA'    	
 37"!*4y~~-/ 	61 	6&5N 	>>~ ?  K z-O+'+)'#
 
 
 	
s   AD< <0E/.E/c                v    t                               d           | j                            t                    S )z
        Return the current Notes sync token.

        Persist this token and pass it back to ``iter_all(since=...)`` or
        ``iter_changes(since=...)`` on a later run to perform incremental syncs.
        z#Fetching sync cursor for Notes zone	zone_name)r~   r   rO   current_sync_tokenr   rR   s    r5   sync_cursorzNotesService.sync_cursor  s0     	:;;;y++o+FFFr4   
output_dirc                    |                      |          }ddlm} ddlm}  |di |} || j        |          }|                    ||          }	|	st          d|           |	S )a  
        Export a note to HTML on disk and return the generated file path.

        Args:
            note_id: The UUID of the note to export.
            output_dir: Directory where the HTML file will be written.
            **config_kwargs: Keyword arguments forwarded to ``ExportConfig``,
                including ``export_mode``, ``assets_dir``, ``full_page``,
                ``preview_appearance``, ``pdf_object_height``, and link behavior
                settings.

        Returns:
            The path to the generated HTML file.

        Notes:
            By default, this produces archival output: a full HTML page with
            local asset downloads.
        r   )NoteExporterExportConfig)config)r   zFailed to export note: r3   )r   rendering.exporterr   rendering.optionsr   rO   exportr    )
rR   r   r   config_kwargsr   r   r   r   exporterpaths
             r5   export_notezNotesService.export_note  s    & ))'22 	544444333333....<	&999v*== 	B@w@@AAAr4   c                    |                      |          }ddlm}m} ddlm} ddlm}  |di |} ||          }	|	sdS  || j        ||	|          \  }
} ||          }|	                    |	|
          S )a  
        Render a note to an HTML fragment string.

        Args:
            note_id: The UUID of the note to render.
            **config_kwargs: Keyword arguments forwarded to ``ExportConfig`` to
                tune preview selection or link behavior for the rendered HTML.

        Returns:
            An HTML fragment string. This method does not download assets or
            write files to disk.
        r   )build_datasourcedecode_and_parse_noter   )NoteRendererr   r3   )
r   r   r   r   r   r   rendering.rendererr   rO   render)rR   r   r   r   r   r   r   r   r   noteds_renderers                r5   render_notezNotesService.render_note  s     ))'22OOOOOOOO333333444444....$$V,, 	2  FD&AAA<''tR(((r4   Iterable[ChangeEvent]c             #    K   |                      |          rt                              d           dS t                              d|rd| nd           | j                            t          t          t          j        g| 	                    t          j        t          j        t          j        t          j        t          j        t          j        g          |d                    D ]w}|j        D ]k}t%          |t&                    rVt)          |j                            d	          pd          }|rd
nd}t/          ||                     |                    V  nt%          |t2                    r<t5          |dd          }|r(t/          d
t7          |ddddddd                    V  t%          |t8                    r^|j        |j        |j        d}t                               d|j        pd|j        |j                   tC          d|j        pd |          t                               d|           tC          ddtE          |          i          ydS )z
        Yield ``ChangeEvent`` items from the Notes changes feed.

        Pass a sync token from ``sync_cursor()`` to process only new changes
        since a previous run.
        z8Skipping Notes change scan because sync token is currentNzIterating changes%sr   r   Fr   r   r   r   updated)rb   r   r   Tr   r   r   r   r   r   r   r   )serverErrorCodereasonr   z;CloudKit error during change enumeration: %s (%s) record=%sUNKNOWNz*CloudKit error during change enumeration: )payloadz*Unexpected record type in changes feed: %rz&Unexpected record type in changes feedrecord_repr)#r   r~   r   rO   r   r   r   r(   r%   r   r'   ru   rv   rw   rx   ry   r}   r   r   r   r   r   r   r)   r   r   r   r&   r	   r   r   r   errorr   repr)rR   r   r   r   deleted_flagevt_typerecord_namedetailss           r5   iter_changeszNotesService.iter_changes  s      ,,U33 	LLSTTTF*,N,=e,=,=,=BOOOI%%)!$3$8#9 --'7'9'9'/'.'3	 	     & 
 
 F	 F	D$ | 4 4c8,, #'
(<(<Y(G(G(P5#Q#QL,8GyyiH%%!66s;;      c#455 ")#|T"B"BK" )!*!,#.&*(,,0*.,0+/*/	" 	" 	"      c;// +.+>"%*&)n G
 LLU+8y
	   (B"2?iB B !(    I3OOO#<*DII6   c4%F	 F	r4   r   c                    | j         S )z
        Return the authenticated low-level Notes CloudKit client.

        This is an escape hatch for advanced or unsupported operations; prefer
        the typed service methods above for normal use.
        )rO   r   s    r5   rawzNotesService.rawJ  s     yr4   c                    |sdS 	 | j                             t                    |k    S # t          $ r&}t                              d|           Y d}~dS d}~ww xY w)z>Return whether an incremental Notes cursor is already current.Fr   z(Failed to preflight Notes sync token: %sN)rO   r   r   r   r~   r   )rR   r   excs      r5   r   z)NotesService._matches_current_sync_cursorV  ss     	5	9////JJeSS 	 	 	NNEsKKK55555	s   #* 
AAAr   rq   Optional[Iterable[object]]r   c                  | j                             |g|                     |                    }|j        D ]&}t	          |t
                    r|j        |k    r|c S 't                              d|           t          d|           )z2Return one Notes record or raise ``NoteNotFound``.)record_namesrq   zNote not found: %szNote not found: )
rO   lookupr   r   r   r   r   r~   r   r-   )rR   r   rq   r   r   s        r5   r   z NotesService._lookup_note_recorda  s     y!**<88   
 
 < 	 	C#x(( S^w-F-F


+W5557g77888r4   keysOptional[List[str]]c                    | d S g }| D ]T}t          |t                    r|                    |j                   2|                    t	          |                     U|S N)r   r'   appendrc   r>   )r  outks      r5   r   zNotesService._coerce_keyss  si    <4 	# 	#A!_-- #

17####

3q66""""
r4   bOptional[bytes | str]c                    | d S t          | t                    r| S 	 |                     dd          S # t          $ r Y d S w xY wNzutf-8replace)r   r>   decoder   )r  s    r5   r   zNotesService._decode_encrypted  s^    94a 	H	88GY/// 	 	 	44	s   3 
A Ar   c                   |j                             d          }t          |t                    r|j        r|j        j        S |j                             d          }t          |t                    r|j        r|j        d         j        S d S )NFolderFoldersr   )r   r   r   r   rc   r   r   )rR   r   ffls       r5   r   zNotesService._extract_folder_id  s    J  **a)** 	&qw 	&7%%Z!!),,b.// 	*BH 	*8A;))tr4   c                    |sd S || j         v r| j         |         S 	 | j                            |gdg          }d }|j        D ]Q}t	          |t
                    r:|j        |k    r/|                     |j        	                    d                    } nR|| j         |<   t                              d||           |S # t          t          t          f$ r) d | j         |<   t                              d|           Y d S w xY w)Nr   r   z*Folder name resolved: folder_id=%s name=%sz+Failed to resolve folder name: folder_id=%s)rP   rO   r  r   r   r   r   r   r   r   r~   r   r   r   r!   r   )rR   r   r   r   r   s        r5   _folder_namezNotesService._folder_name  s+    	4///*955	9##YK?O>P#QQD"&D|  c8,, 91L1L11
,,-=>> D E15D#I.LLEyRVWWWK~/?@ 	 	 	15D#I.NNH)TTT44	s   B B= =<C=<C=r&   c           
     h   |                      |j                            d                    }|                      |j                            d                    }|j                            d          }t          |j                            d          pd          }|                     |          }|                     |          }t          t          |dd                                                    t          j
                                        k    }t          |j        |||||||          S )	Nr   SnippetEncryptedModificationDater   Frj   r   r   )r   r   r   r   r   r%  r>   r   lowerr(   PasswordProtectedNoter&   r   )	rR   r   r   r   modifiedr   r   r   r   s	            r5   r   z!NotesService._summary_from_record  s    &&sz';';<L'M'MNN(()=)=>P)Q)QRR:''
 
 sz++I66?%@@++C00	''	22\2..//55774::<<= 	 ~ #	
 	
 	
 		
r4   Optional[NoteBody]c                   |j                             d          }|s"t                              d|j                   dS 	 t                                          |          }|rt          |t                    r|S t                              d|j        |r/t          |dd          rt          t          |dd                    nd           dS # t          $ r,}t                              d|j        |           Y d}~dS d}~ww xY w)	zADecode TextDataEncrypted into a NoteBody (text + attachment IDs).r   z*notes.body.missing TextDataEncrypted id=%sNz!notes.body.no_text id=%s bytes=%sbytesr4   0z%notes.body.decode_failed id=%s err=%s)r   r   r~   r   r   r   r  r   r#   r   r   r   r   )rR   r   r  nbes        r5   r   zNotesService._decode_note_body  s    j""#677 	LLEs~VVV4	%%c**B jX.. 	LL3 %b'488CGS11222   4 	 	 	NNBCNTUVVV44444	s    9C :AC 
D!C??Dr   r   Optional[List[AttachmentId]]List[Attachment]c          
     |    g }g }g }|r-|D ]*}t          |dd          }|r|                    |           +|j                            d          }|ret	          |d          rUt          |dg           pg }	|	D ]?}
t          |
dd          }|r*|                    |           |                    |           @t                      }g }|D ]0}||vr*|                    |           |                    |           1t                              d||           |s|s|S t                      }g }|r|n|}|D ]0}||vr*|                    |           |                    |           1 fd|D             }|rQg d}	  j	        
                    ||	          }nC# t          $ r6}t                              d
||           t          g           }Y d}~nd}~ww xY wt          |dg           D ]}t          |t                    s                     |          }|sct                              dt          |dd          t          |dd          r&t!          |j                                                  nd           |j        }                     ||          }|D ](}| j        |<   t                              d||           )|p|D ]7} j                            |          }|r||vr|                    |           8t                              dt-          |          t          |dd                     |S )zHydrate attachment metadata for a note.

        Combines attachment identifiers from CloudKit references and the decoded
        protobuf body. Missing records are skipped gracefully.
        
identifierNAttachmentsrc   r   z/notes.attachments.candidates alias=%s lookup=%sc                &    g | ]}|j         v|S r3   )rQ   ).0aidrR   s     r5   
<listcomp>z@NotesService._resolve_attachments_for_record.<locals>.<listcomp>  s&    WWW34;V0V0V30V0V0Vr4   )FilenameAttachmentUTIUTISize	ThumbnailFirstAttachmentThumbnailPrimaryAssetPreviewImagesPreviewAppearancesFallbackImageFallbackPDFPaperAssetsAttachmentIdentifierattachmentIdentifier
Identifierr   z-notes.attachments.lookup_failed ids=%s err=%s)r   r   z/notes.attachments.unhandled record=%s fields=%sr   z)notes.attachments.cached base=%s alias=%sz#Resolved %d attachments for note %s)r   r  r   r   hasattrsetaddr~   r   rO   r  r   r   r   r   _build_attachment_from_recordlistr  r   _attachment_aliasesrQ   r   r   )rR   r   r   r  	alias_idslookup_candidatesr9  identfldrefsrefrn
seen_aliasidscidseen_lookup
lookup_idslookup_source_idsmissingrq   r   errrec_a
attachmentbase_idaliasesaliasatts   `                           r5   r   z,NotesService._resolve_attachments_for_record  s    !#!	') 	,% , ,\488 ,$$U+++j""=11 	)73(( 	)&-c7B&?&?&E2D ) )S,55 )%,,R000$$R(((  #uu
 	  	 C*$$s###

3=	
 	
 	
  	, 	J !$ "
1BK--$ 	' 	'C+%%$$$!!#&&&WWWW*WWW 3	  L"4y''l'KK  4 4 4C  
 (3334 !y"55  !%22 !??FF
! LLI|T::"5(D99"U\..00111!   $-225'BB$  E9CD/6LLC    $* 	  	 C-11#66C  s#~~

31HHCt,,	
 	
 	

 
s   <F 
G#,GGnames	List[str]c                    |D ]v}| j                             |          }|t          |t                    r)	 |                    dd          c S # t
          $ r Y Yw xY wt          |t                    r|c S wd S r  )r   r   r   r.  r  r   r>   r   re  r   vs       r5   _coerce_stringzNotesService._coerce_stringV  s     
	 
	A
$$Q''Ay!U## 88GY77777    H!S!! ts   A
AAr  c                |    |g}t                               | g d          }|r||vr|                    |           |S )N)rG  rH  rI  )r9   rj  r  )r   r  rb  r5  s       r5   rO  z NotesService._attachment_aliasese  sU    -!00OOO
 

  	'*G33NN:&&&r4   Optional[Attachment]c           	     V   t          |dd           }|sd S |                     |g d          }|                     |ddg          }|                     |ddg          }d }d }d }|p|                     |dg          }|p|                     |dg          }|p|                     |d          }|p|                     |d	          }|p|                     |d
          }|p|                     |dg          }|p|                     |ddg          }|p|}t          |||||||          S )Nr   )r;  NameFileNamer<  r=  r>  FileSizerA  rE  rF  rB  rD  r?  r@  )r   filenameutisizedownload_urlpreview_urlthumbnail_url)r   rj  _coerce_int_coerce_asset_url_coerce_asset_url_from_listr$   )	rR   r   r9  rq  rr  rs  rt  ru  rv  s	            r5   rM  z*NotesService._build_attachment_from_recordo  s   c<.. 	4&&s,L,L,LMM!!#'?@@fj%9::#Tt'='=cNCS'T'T#St'='=cM?'S'S# 
t'G'G(
 (
 $ 
t'G'G(
 (
 " 
T%E%E&
 &
 "ST%;%;C/AR%S%S% 
)?)?+9:*
 *
 &4%#'
 
 
 	
r4   c                6   |D ]}| j                             |          }t          |t                    r|c S t          |t                    rt          |          c S t          |t
                    r%|                                rt          |          c S d S r  )r   r   r   rX   floatr>   isdigitrh  s       r5   rw  zNotesService._coerce_int  s     	 	A
$$Q''A!S!! !U## 1vv!S!! aiikk 1vvtr4   c                    |D ]Z}| j                             |          }|st          |dd           }t          |dd           }t          |t                    r|c S [d S Nrc   downloadURL)r   r   r   r   r>   )r   re  r   rS  valurls         r5   rx  zNotesService._coerce_asset_url  sx     	 	A*&&q))C #w--C#}d33C#s## 


tr4   r   c                X   | j                             |          }|sd S t          |dd           }t          |t          t
          f          r^|D ][}d }t          |t                    r|                    d          }nt          |dd           }t          |t                    r|r|c S \d S r~  )	r   r   r   r   rN  tupledictr   r>   )r   r   rS  r  tokenr  s         r5   ry  z(NotesService._coerce_asset_url_from_list  s    j""4(( 	4c7D))cD%=)) 	  eT** >))M22CC!%==Cc3'' C JJJtr4   rd  r$   	directoryc                    |j         p|j        p|j        }|st          d          t                              d|j        |           | j                            ||          S )N*Attachment does not expose a download URL.zDownloading attachment %s to %s)	rt  ru  rv  r   r~   r   r   rO   download_asset_to)rR   rd  r  r  s       r5   _download_attachment_toz$NotesService._download_attachment_to  sb    F#/FS5F 	N LMMM6	JJJy**3	:::r4   i   
chunk_sizer  Iterator[bytes]c             #     K   |j         p|j        p|j        }|st          d          t                              d|j        |           | j                            ||          E d {V  d S )Nr  z%Streaming attachment %s chunk_size=%dr  )	rt  ru  rv  r   r~   r   r   rO   download_asset_stream)rR   rd  r  r  s       r5   _stream_attachmentzNotesService._stream_attachment  s       F#/FS5F 	N LMMM<cfjQQQ9223:2NNNNNNNNNNNr4   )r=   r>   r?   r@   r<   rA   )rW   rX   rY   rZ   )r   r>   rW   rX   rY   rZ   )r   r   rY   rZ   )rY   r   )r   r>   rW   r   rY   rZ   )r   r>   r   r   rY   r%   )rY   r>   )r   r>   r   r>   rY   r>   )r   r>   rY   r>   )r   r   rY   r   )rY   r   )r   r   rY   r   )r   r>   rq   r  rY   r   )r  r  rY   r  )r  r  rY   r   )r   r   rY   r   )r   r   rY   r   )r   r   rY   r&   )r   r   rY   r,  )r   r   r   r2  rY   r3  )r   r   re  rf  rY   r   )r   r   r  r>   rY   rf  )r   r   rY   rl  )r   r   re  rf  rY   r   )r   r   r   r>   rY   r   )rd  r$   r  r>   rY   r>   )rd  r$   r  rX   rY   r  )'r/   r0   r1   r2   rL   rM   rN   rK   r`   r   r   r   r   r   r   r   r   r	  propertyr  r   r   staticmethodr   r   r   r%  r   r   r   rj  rO  rM  rw  rx  ry  r  r  __classcell__)rT   s   @r5   r9   r9   L   s         #JDF ?C@ @ @ @ @ @ @ @8 ') ? ? ? ? ? ?D /1     6 26 &9 &9 &9 &9 &9 &9P3 3 3 3l 9=/ / / / / /b =B N
 N
 N
 N
 N
 N
`G G G G   @) ) ) )8 6: R R R R R Rh    X	 	 	 	 48	9 9 9 9 9 9$ 	 	 	 \	    \      ,
 
 
 
0   : 8<	z z z z z zx    \    \(
 (
 (
 (
T 	 	 	 \	 
 
 
 \
    \ ; ; ; ; 5:O O O O O O O O O Or4   r9   )<r2   
__future__r   loggingtypingr   r   r   r   r   pyicloud.common.cloudkitr	   r
   r   r   r   r   r   r   r   r   r   r   pyicloud.common.cloudkit.modelsr   r   pyicloud.services.baser    pyicloud.services.notes.decodingr   
_constantsr   r   r   clientr   r   r   r    r!   domainr"   r#   modelsr$   r%   r&   models.constantsr'   r(   
models.dtor)   r*   	getLoggerr/   r~   r   r-   r7   r9   r3   r4   r5   <module>r     s   ( # " " " " "  ; ; ; ; ; ; ; ; ; ; ; ; ; ;                            S R R R R R R R . . . . . . 8 8 8 8 8 8 C C C C C C C C C C              + * * * * * * * 1 1 1 1 1 1 1 1 1 1 > > > > > > > > / / / / / / / /		8	$	$% 	 	 	 	 	: 	 	 		 	 	 	 	j 	 	 	EO EO EO EO EO; EO EO EO EO EOr4   