
    DjxV                    l   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 ddlmZ ddlmZ ddlmZ dd	lmZ d
dlmZ d
dlmZ d
dlmZmZmZ  e            Z ej        e          Z d8dZ!d9dZ"	 d:d;dZ#ddd<d%Z$ddd<d&Z%ddd<d'Z&ddd<d(Z'	 d:d=d*Z(d>d-Z)d.dd/d?d5Z* G d6 d7          Z+dS )@u+  
Exporter helpers for Apple Notes → HTML.

These functions are thin, testable wrappers around the existing decoding,
datasource hydration, rendering, and file I/O utilities. They are intentionally
pure (no global state) and perform only the minimal work needed by CLI tools
and higher-level APIs.
    )annotationsN)DictIterableListOptionalTuple)Console)CKRecord   )BodyDecoder)	notes_pb2   )CloudKitNoteDataSource)ExportConfig)NoteRendererrender_note_fragmentrender_note_pagerecordr
   returnOptional[pb.Note]c                   t          | t                    sdS | j                            d          }|sdS 	 t	                                          |          }|rt          |dd          sdS t          j                    }|	                    |j
                   t          t          |dd          dd          S # t          $ r Y dS w xY w)zDecode a Note CKRecord's TextDataEncrypted and return a parsed pb.Note.

    Returns None if body is missing or cannot be parsed.
    NTextDataEncryptedbytesdocumentnote)
isinstancer
   fields	get_valuer   decodegetattrpbNoteStoreProtoParseFromStringr   	Exception)r   rawnbmsgs       e/home/thesage/.hermes/venv/lib/python3.11/site-packages/pyicloud/services/notes/rendering/exporter.pydecode_and_parse_noter)       s    
 fh'' t
-
!
!"5
6
6C t]]!!#&& 	Wd33 	4!!BH%%%wsJ55vtDDD   tts   4B: -AB: :
CCr   pb.Note	List[str]c                >   g }| j                             d          }|rNt          |d          r>t          |dg           pg D ]*}t          |dd           }|r|                    |           +g }t          |dg           pg D ]T}|                    d          r=|j                            d          r#|j        j        }|r|                    |           Ut                      }	g }
||z   D ]0}||	vr*|		                    |           |
                    |           1|
S )NAttachmentsvalue
recordNameattribute_runattachment_infoattachment_identifier)
r   	get_fieldhasattrr    appendHasFieldr1   r2   setadd)r   r   idsfldrefrnids_from_runsrattraidseenmergedas               r(   $_attachment_ids_from_record_and_runsrC   5   sQ   C
-
!
!-
0
0C
 wsG$$ 3,,2 	 	ClD11B 

2!M339r * *>>+,, 	*1F1O1O#2
 2
 	* '=C *$$S)))UUDF=   D==HHQKKKMM!M    note_recordconfigOptional[ExportConfig](Tuple[CloudKitNoteDataSource, List[str]]c                   t          |          }t          ||          }|r|                     |          }i }t          t	          |dd                    }t          |j                  D ]\  }	}
|r7t                              d|	            t          	                    |
           t          |
t                    rs|                    |
           	 |
j                            d          }|rt	          |dd          nd}t	          |dd          }|r
|
j        ||<   # t           $ r Y w xY w|r	 |                     t#          |                                                    }t          t	          |dd                    ra	 t                              d	           t          	                    |           t&                              d
|           n# t           $ r Y nw xY w|j        D ]}t          |t                    sd}	 t#          t	          |dd                                                    D ]Y}|j                            |          }t	          |dd          }t	          |dd          }t          |t*                    r|r|} nZn# t           $ r d}Y nw xY w|r|                    |j                  }|r	 |                    |          pd                                }n# t           $ r d}Y nw xY w|pt3                      }|                    |          }d|v pd|v pd|v pd|v }t	          |dd          o|p|}d}	 |                    |          }n# t           $ r Y nw xY w|r|rI	 |                    |          }n# t           $ r d}Y nw xY w|r|r||k    r|                    ||           n# t           $ r Y nw xY w||fS )zBuild a CloudKit-backed Note datasource for a single note.

    Returns (datasource, attachment_ids) where attachment_ids is the merged list
    of attachment record names to which the datasource has been hydrated.
    )_configdebugFzrec_idx Mediar.   Nr/   zmedia lookup responsezattachment media resp:
%sr    downloadURL audiovideomoviempegprefer_media_for_imagesT)r   rC   lookupboolr    	enumeraterecordsconsoleruleprintr   r
   add_attachment_recordr   r3   r/   r$   listkeysLOGGERinfostrgetget_attachment_utilowerr   is_image_utiget_primary_asset_urlget_thumbnail_urlset_primary_asset_url)	ck_clientrE   r   rF   dsatt_idsresp	media_maprK   rec_idxrecr:   r;   r<   mrespmrecurlkvaluparent
parent_uticonfis_imageis_avis_media_upgradecur_primary	cur_thumbs                               r(   build_datasourcer~   P   s    
 	/	/	/B2;EEG `(($&	WVWe4455%dl33 	 	LGS #111222c"""#x(( 
((---*..w77C9<F'#w555$C lD99B 7(+	"    D
  L	K!((inn.>.>)?)?@@7788 %<===e,,,$@%HHHH$   !M @J @JD%dH55 ! )-C	#!%gdHb&A&A&F&F&H&H!I!I & &A"&+"7"7":":C")#w"="=C ']D A AA)!S11 &a &&' %$ # # #"# 1J!*t!?!?! /J0$&$9$9&$A$A$GR"'%'' !+
 $- 0 0 0-/


0 $*#;\^^D'+'8'8'D'DH !(: 5 !8#*j#8!8#*j#8!8 $*Z#7	 " 07 $&?0 0 06#+#4u -
 +/K%.0.F.Fv.N.N#, % % % $% %0 
J4D 
J!5020D0DV0L0LII'0 !5 !5 !504III!5 )4 !J$4!J9D	9Q9Q$&$<$<VS$I$I$IA@JB    w;s   AD##
D0/D08AO
 AG O
 
G(%O
 'G((%O
 B
JO
 J(%O
 'J(("O
 )K54O
 5LO
 LAO
 M*)O
 *
M74O
 6M77O
 ?NO
 N$!O
 #N$$%O
 

OOrF   rj   r   rk   Iterable[str]
assets_dirra   out_dirDict[str, str]c                  t          j        |d           i }dd}t           j                            |          }|D ]}	|                    |	          pd                                }
 ||
          s8|                    |	          }|r*|                    d	          s|                    d
          sz	 |                     ||          }|}	 t          |d          5 }|
                    d          }ddd           n# 1 swxY w Y   |                    d          rW|                                                    d          s0|dz   }	 t          j        ||           |}n# t          $ r |}Y nw xY wn# t          $ r |}Y nw xY wt           j                            |t           j                            |                    }|                    |	|           |||	<   # t          $ r Y w xY w|S )u  Download PDFs for attachments and rewrite datasource URLs to local paths.

    Returns a mapping of attachment id → relative path used in HTML.
    Only applies to PDF UTIs. Files are renamed with `.pdf` extension when the
    magic header is present.
    Texist_oksOptional[str]r   rV   c                L    t          | o|                                 dv           S )N)zcom.adobe.pdfz
public.pdfzcom.apple.paper.doc.pdf)rV   rd   r   s    r(   _is_pdf_utiz(download_pdf_assets.<locals>._is_pdf_uti   s.     X		WW
 
 	
rD   rO   http://https://rb   Ns   %PDF-z.pdfstart)r   r   r   rV   osmakedirspathabspathrc   rd   rf   
startswithdownload_asset_toopenreadendswithreplacer$   relpathrh   )ri   rj   rk   r   r   rF   updatedr   note_subdirr?   utirr   
saved_pathresolvedfhheadnew_pathrels                     r(   download_pdf_assetsr      s    K
T**** G
 
 
 
 '//*--K  $$S))/R6688{3 	&&s++ 		22 	cnnZ6P6P 		"44S+FFJ!H&*d++ &r771::D& & & & & & & & & & & & & & &??8,, .Z5E5E5G5G5P5P6 6 .  *F2H.
:x888#+$ . . .#-. & & &%&'//("'//'2J2J/KKC$$S#...GCLL 	 	 	D	 Ns   9G)E<"D8E<D	E<D	AE<E)(E<)E85E<7E88E<;G)<FG)
FAG))
G76G7c               r   t          j        |d           i }|pt                      }dd}t           j                            |          }	|D ]}
|                    |
          pd                                }|                    |          sB|                    |
          }|s)	 |	                    |
          }n# t          $ r d	}Y nw xY w|r*|                    d
          s|                    d          s	 |                     ||	          }|}	 t          |d          5 }|                    d          }d	d	d	           n# 1 swxY w Y    ||          }|rW|                                                    |          s0||z   }	 t          j        ||           |}n# t          $ r |}Y nw xY wn# t          $ r |}Y nw xY wt           j                            |t           j                            |                    }|                    |
|           |||
<   # t          $ r Y w xY w|S )u   Download image attachments and rewrite datasource URLs to local paths.

    Returns a mapping of attachment id → relative path used in HTML.
    Applies to common image UTIs (jpeg/png/heic/webp/gif/bmp/tiff...).
    Tr   r   r   r   r   c                   	 |                      d          rdS |                      d          rdS |                      d          s|                      d          rdS |                      d          r| d	d
         dk    rdS t          |           d
k    r| dd	         dk    r| d	d
         }|dv rdS |                      d          rdS |                      d          s|                      d          rdS n# t          $ r Y nw xY wd S )Ns   z.jpgs   PNG

z.pngs   GIF87as   GIF89az.gif   RIFF      s   WEBPz.webp      ftyp)s   heics   heifs   mif1s   msf1s   hevcz.heics   BMz.bmps   II* s   MM *z.tiff)r   lenr$   r   brands     r(   _infer_image_extz/download_image_assets.<locals>._infer_image_ext  sA   	// v344 vy)) T__Y-G-G vw'' D2J',A,Aw 4yyB4!9#7#7QrT
III"7u%% vz** dooj.I.I w 	 	 	D	ts3   C6 C6 *C6 #C6 /C6 2C6 	*C6 6
DDrO   Nr   r   r      r   r   r   r   r   )r   r   r   r   r   rc   rd   re   rf   rg   r$   r   r   r   r   r   r   r   rh   )ri   rj   rk   r   r   rF   r   rx   r   r   r?   r   rr   r   r   r   r   extr   r   s                       r(   download_image_assetsr      s    K
T**** G#\^^D   2 '//*--K # #$$S))/R6688  %% 	&&s++ 	**3//    		22 	cnnZ6P6P 		"44S+FFJ!H&*d++ 'r772;;D' ' ' ' ' ' ' ' ' ' ' ' ' ' '&&t,, .z//11::3?? .)C/H.
:x888#+$ . . .#-. & & &%&'//("'//'2J2J/KKC$$S#...GCLL 	 	 	D	 Ns   (B>>CC>H&F9'E	=F9	E	F9E	<F9F&%F9&F52F94F55F98H&9GH&GAH&&
H43H4c                  t          j        |d           i }dd}t           j                            |          }|D ]}	|                    |	          pd                                }
d	|
v pd
|
v pd|
v pd|
v pd|
v }|sC|                    |	          }|r*|                    d          s|                    d          s	 |                     ||          }|}	 t          |d          5 }|
                    d          }ddd           n# 1 swxY w Y    ||          }|sd|
v rd}nd|
v rd}|rW|                                                    |          s0||z   }	 t          j        ||           |}n# t          $ r |}Y nw xY wn# t          $ r |}Y nw xY wt           j                            |t           j                            |                    }|                    |	|           |||	<   # t          $ r Y w xY w|S )u   Download audio/video attachments and rewrite datasource URLs to local paths.

    Returns a mapping of attachment id → relative path used in HTML.
    Tr   r   r   r   r   c                &   	 t          |           dk    r&| dd         dk    r| dd         }|dv rdS |dv rdS d	S t          |           dk    r| dd         d
k    rdS |                     d          rdS |                     d          s*|                     d          s|                     d          rdS |                     d          r| dd         dk    rdS |                     d          r| dd         dk    rdS n# t          $ r Y nw xY wd S )Nr   r   r   r   )s   M4A s   mp42s   isom.m4a)s   qt     moov.movz.mp4r   s   ID3z.mp3s   s   s   r   s   WAVEz.wavs   AVI z.avi)r   r   r$   r   s     r(   _infer_av_extz)download_av_assets.<locals>._infer_av_ext`  sb    	4yyB4!9#7#7QrT
777!6...!6v 4yyA~~$qs)w"6"6v v&& v ,,??;// ??;//
 vw'' D2J',A,Avw'' D2J',A,Av 	 	 	D	ts3   /D D !D D 5?D 6#D #D 
DDrO   rP   rQ   rS   rR   	quicktimer   r   r   r   Nzcom.apple.m4a-audior   r   r   r   r   )ri   rj   rk   r   r   rF   r   r   r   r?   r   rz   rr   r   r   r   r   r   r   r   s                       r(   download_av_assetsr   P  s    K
T**** G" " " "H '//*--K - -$$S))/R6688 sN "#~"}" #~" c! 	  	&&s++ 		22 	cnnZ6P6P 		"44S+FFJ!H&*d++ 'r772;;D' ' ' ' ' ' ' ' ' ' ' ' ' ' '#mD)) %,33$$++$ .z//11::3?? .)C/H.
:x888#+$ . . .#-. & & &%& '//("'//'2J2J/KKC$$S#...GCLL 	 	 	D	Ns   G;F-DFD	FD	AF#E;:F;F
F	F

FG;FG;FAG;;
H	H	c                  t          j        |d           i }t           j                            |          }|D ]M}|                    |          pd                                }	d|	vr1|                    |          }
|
r*|
                    d          s|
                    d          ss	 |                     |
|          }|}|                                	                    d          s0|dz   }	 t          j
        ||           |}n# t          $ r |}Y nw xY wt           j                            |t           j                            |                    }|                    ||           |||<   ># t          $ r Y Kw xY w|S )	u   Download VCard (contact) attachments and rewrite datasource URLs to local paths.

    Returns a mapping of attachment id → relative path used in HTML.
    Tr   rO   zpublic.vcardr   r   z.vcfr   )r   r   r   r   rc   rd   rf   r   r   r   r   r$   r   rh   )ri   rj   rk   r   r   rF   r   r   r?   r   rr   r   r   r   r   s                  r(   download_vcard_assetsr     s    K
T**** G'//*--K  $$S))/R6688$$&&s++ 		22 	cnnZ6P6P 		"44S+FFJ!H ##%%..v66 *%.*Jz8444'HH  * * *)HHH* '//("'//'2J2J/KKC$$S#...GCLL 	 	 	D	 Ns8   .AE83D
E8DE8DAE88
FF Optional[CloudKitNoteDataSource]c                &    t          | ||          S )Nr   )r   )r   rj   rF   s      r(   render_fragmentr     s    
  b8888rD   r   r   c                    | sdS t          j        dd|                                           } t          j        dd|           } | d d         pdS )Nuntitledz\s+ z	[^\w\- ]+-<   )resubstripr   s    r(   
_safe_namer     sT     z
vsA$$&&A
|S!$$ASbS6ZrD   F	full_pagefilenametitlehtml_fragmentr   rV   r   c                   t          j        |d           |rt          | |          n|}|pt          |            d}t           j                            |          }t           j                            t           j                            ||                    }t           j                            ||g          |k    rt          d          t          |dd          5 }	|	
                    |           d d d            n# 1 swxY w Y   |S )NTr   z.htmlz!filename must stay within out_dirwutf-8)encoding)r   r   r   r   r   r   join
commonpath
ValueErrorr   write)
r   r   r   r   r   pagefnamerootr   fs
             r(   
write_htmlr     s-    K$''''5>QE=111MD3:e,,333E7??7##D7??27<<e4455D	w4,''4//<===	dC'	*	*	* a	              Ks   !DD
Dc                  (    e Zd ZdZdddZ	 dddZdS )NoteExporterz5Orchestrator for exporting notes to HTML with assets.NrF   rG   c                p    || _         |pt                      | _        t          | j                  | _        d S N)clientr   rF   r   renderer)selfri   rF   s      r(   __init__zNoteExporter.__init__  s.    .$T[11rD   rE   r
   
output_dirra   r   r   r   c                F   t          |          }|sdS t          | j        ||| j                  \  }}t	          t          | j        dd          pd          }|                                                                }|dk    rt          | j        dd          pt          j	        
                    |d          }t          j	        
                    ||j                  }	t          | j        |||	|| j                   t          | j        |||	|| j                   t          | j        |||	|| j                   t          | j        |||	|| j                   | j                            ||          }
d}|j                            d          }|rT	 t)          |t*                    r|                    d	          }nt)          |t                    r|}n# t.          $ r Y nw xY wt          | j        d
d          }|d}t1          ||
|t3          |          |          S )z
        Export a single note record to HTML in the output directory.
        Returns the path to the written HTML file, or None if export failed (e.g. no body).
        Nexport_modearchivalr   assets)r   r   rF   UntitledTitleEncryptedr   r   Tr   )r)   r~   r   rF   ra   r    r   rd   r   r   r   r/   r   r   r   r   r   renderr   r   r   r   r   r$   r   rV   )r   rE   r   r   r   rj   rk   r   assets_rootr   r   r   	title_encr   s                 r(   exportzNoteExporter.export  sy    %[11 	4 't{Kt{SSG '$+}jIIWZXX!''))//11*$$!$+|TBB bgllHG GK k;3IJJJ%"{    "%"{    %"{    "%"{    ,,T266 &001ABB	 	i// &%,,W55EE	3// &%E    DKd;;	I9oo
 
 
 	
s   AG 
G%$G%r   )rF   rG   )rE   r
   r   ra   r   r   r   r   )__name__
__module____qualname____doc__r   r   rM   rD   r(   r   r   
  sX        ??2 2 2 2 2 #'	U
 U
 U
 U
 U
 U
 U
rD   r   )r   r
   r   r   )r   r
   r   r*   r   r+   r   )rE   r
   r   r*   rF   rG   r   rH   )rj   r   rk   r   r   ra   r   ra   rF   rG   r   r   )r   r*   rj   r   rF   rG   r   ra   )r   r   r   ra   )r   ra   r   ra   r   ra   r   rV   r   r   r   ra   ),r   
__future__r   loggingr   r   typingr   r   r   r   r   rich.consoler	   pyicloud.common.cloudkitr
   decodingr   protobufr   r!   ck_datasourcer   optionsr   r   r   r   r   rY   	getLoggerr   r_   r)   rC   r~   r   r   r   r   r   r   r   r   rM   rD   r(   <module>r      s    # " " " " "  				 				 8 8 8 8 8 8 8 8 8 8 8 8 8 8             - - - - - - " " " " " " & & & & & & 1 1 1 1 1 1 ! ! ! ! ! ! J J J J J J J J J J
'))		8	$	$   *   > &*	n n n n np &*8 8 8 8 8 8D &*Q Q Q Q Q Qv &*c c c c c cZ &*- - - - - -f &*9 9 9 9 9        "     (]
 ]
 ]
 ]
 ]
 ]
 ]
 ]
 ]
 ]
rD   