
    WwgiD                        d 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 dd
lmZ ddlmZmZ g dZ ed       G d d             Z G d dej.                        Z ed       G d d             Z ed       G d d             Zdej6                  defdZddddddddddedee   deee	j>                        d eej@                     d!ed"ee   d#ee   d$ejB                  fd%Z"y)&zO
Utility classes for handling embedded files in PDFs.

.. versionadded:: 0.7.0
    N)	dataclass)datetime)ListOptional)x509   )cryptgenericmiscwriter)RecipientEncryptionPolicy)get_courier)pdf_name
pdf_string)
embed_fileEmbeddedFileObjectEmbeddedFileParamsFileSpecRelatedFileSpecwrap_encrypted_payloadT)frozenc                   X    e Zd ZU dZeed<   	 dZeed<   	 dZee	   ed<   	 dZ
ee	   ed<   y)r   T
embed_sizeembed_checksumNcreation_datemodification_date)__name__
__module____qualname__r   bool__annotations__r   r   r   r   r        N/var/www/horilla/myenv/lib/python3.12/site-packages/pyhanko/pdf_utils/embed.pyr   r      sO    J  ND )-M8H%, -1x)0r#   r   c                        e Zd Ze	 	 	 d	dej
                  dedee   dee	   dd f
d       Z
	 	 	 	 	 d
dej
                  dee   dee	   f fdZd fd	Z xZS )r   
pdf_writerdataparams	mime_typereturnc                 H    t        ||||      }|r|j                          |S )a  
        Construct an embedded file object from file data.

        This is a very thin wrapper around the constructor, with a slightly
        less intimidating API.

        .. note::
            This method will not register the embedded file into the document's
            embedded file namespace, see :func:`.embed_file`.

        :param pdf_writer:
            PDF writer to use.
        :param data:
            File contents, as a :class:`bytes` object.
        :param compress:
            Whether to compress the embedded file's contents.
        :param params:
            Optional embedded file parameters.
        :param mime_type:
            Optional MIME type string.
        :return:
            An embedded file object.
        )r&   stream_datar(   r)   )r   compress)clsr&   r'   r-   r(   r)   results          r$   from_file_dataz!EmbeddedFileObject.from_file_data?   s/    B $!	
 OOr#   c                     t         |   ||||j                         t        j                  d      | d<   |t        j                  d|z         | d<   |j                  |       | _        || _        y )N)	dict_datar,   encoded_datahandlerz/EmbeddedFile/Type/z/Subtype)super__init__security_handlerr
   r   
add_objectef_stream_refr(   )selfr&   r2   r,   r3   r(   r)   	__class__s          r$   r8   zEmbeddedFileObject.__init__k   sx     	#%//	 	 	
  ((9W &//i@D'2248r#   c                    |H| j                   s<|j                  }|j                  }|j                  }|||k7  r| j	                  |       | j
                  }|t        j                         x| d<   }|j                  r+t        j                  t        | j                              |d<   |j                  rEt        j                  | j                        j                         }	t        j                   |	      |d<   |j"                  "t        j$                  |j"                        |d<   |j&                  "t        j$                  |j&                        |d<   t(        
| U  |||       y )Nz/Paramsz/Sizez	/CheckSumz/CreationDatez/ModDate)r4   container_ref)_has_crypt_filtercrypt_filter_configembedded_file_filter_namestream_filter_nameadd_crypt_filterr(   r
   DictionaryObjectr   NumberObjectlenr'   r   hashlibmd5digestByteStringObjectr   pdf_dater   r7   write_to_stream)r<   streamr4   r?   cfcef_filter_namerC   r(   
param_dictchecksumr=   s             r$   rM   z"EmbeddedFileObject.write_to_stream   sJ    t'='=--C ::N!$!7!7*"&88%%n5 +2+C+C+EEDOj  &-&:&:3tyy>&J
7#$$";;tyy188:*1*B*B8*L
;'##/.5.>.>((/
?+ ''3)0)9)9,,*
:& 	G= 	  	
r#   )TNN)NNNNN)NN)r   r   r   classmethodr   BasePdfFileWriterbytesr   r   strr0   r8   rM   __classcell__)r=   s   @r$   r   r   >   s    
 /3#'),,) )
 +,) C=) 
) )\ /3#',, +, C=*"
 "
r#   r   c                   F    e Zd ZU dZeed<   	 eed<   	 eded    fd       Z	y)r   z=
    Dataclass modelling a RelatedFile construct in PDF.
    nameembedded_datalstc                 B    fd}t        j                   |             S )Nc               3      K   D ];  } t        j                  | j                         | j                  j                   = y w)N)r
   r   rY   rZ   r;   )rfsr[   s    r$   _genz/RelatedFileSpec.fmt_related_files.<locals>._gen   s=      6((22''5556s   AA)r
   ArrayObject)r.   r[   r_   s    ` r$   fmt_related_filesz!RelatedFileSpec.fmt_related_files   s    	6
 ""46**r#   N)
r   r   r   __doc__rV   r!   r   rS   r   ra   r"   r#   r$   r   r      sA     I &%
 +D):$; + +r#   r   c                       e Zd ZU dZeed<   	 dZee   ed<   	 dZee	   ed<   	 dZ
ee   ed<   	 dZeej                     ed<   	 dZeee      ed<   	 dZeee      ed	<   	 d
ej$                  fdZy)r   zD
    Dataclass modelling an embedded file description in a PDF.
    file_spec_stringN	file_namerZ   descriptionaf_relationshipf_related_filesuf_related_filesr*   c                 ,   t        j                  t        d      t        d      t        d      t        | j                        i      }| j
                  t        | j
                        |d<   | j                  ^t        j                  t        d      | j                  j                  i      x|d<   }| j
                  | j                  j                  |d<   | j                  "t        j                  | j                        |d<   | j                  | j                  |d<   | j                  }| j                  }|s|rYt        j                         x|d<   }|rt        j                  |      |d<   |r$| j
                  t        j                  |      |d<   |S )	z>
        Represent the file spec as a PDF dictionary.
        r5   z	/Filespecz/Fz/UFz/EFz/Descz/AFRelationshipz/RF)r
   rE   r   r   rd   re   rZ   r;   rf   TextStringObjectrg   rh   ri   r   ra   )r<   r/   ef_dict	f_related
uf_relatedrfs         r$   as_pdf_objectzFileSpec.as_pdf_object   sm   
 ))!8K#8
4+@+@ A
 >>%&t~~6F5M)&-&>&>TND$6$6$D$D' F5MG
 ~~)!%!3!3!A!A'%66t7G7GHF7O+(,(<(<F$%((	**

!(!9!9!;;F5MB*<<YG4dnn8+==jI5	r#   )r   r   r   rb   rV   r!   re   r   rZ   r   rf   rg   r
   
NameObjectrh   r   r   ri   rE   rp   r"   r#   r$   r   r      s       $Ix}# 37M8./6
 "&K#% 59OXg0018 8<OXd?34; 9=htO45<&w77 &r#   r   r&   specc                 Z   |j                   }|t        j                  d      |j                         }| j                  }	 |d   }	 |d   }d|v rt        d      	 |d   }|j                  t        j                  |j                               | j                  |      }|j                  |       | j                  |       |j                   *| j#                  d       	 |d	   }	|	j                  |       y| j#                  d
       y# t
        $ r< t        j                         }| j                  |      |d<   | j                          Y 	w xY w# t
        $ r= t        j                         }| j                  |      |d<   | j                  |       Y Lw xY w# t
        $ r= t        j                         }| j                  |      |d<   | j                  |       Y w xY w# t
        $ r< t        j                         }	| j                  |	      |d	<   | j                          Y Cw xY w)z
    Embed a file in the document-wide embedded file registry of a PDF writer.

    :param pdf_writer:
        PDF writer to house the embedded file.
    :param spec:
        File spec describing the embedded file.
    :return:
    Nz/File spec does not have an embedded file streamz/Namesz/EmbeddedFilesz/Kidsz,Only flat name trees are supported right now)   r   )versionz/AF)r      )rZ   r   PdfWriteErrorrp   rootKeyErrorr
   rE   r:   update_rootupdate_containerNotImplementedErrorr`   appendr   rd   rg   ensure_output_version)
r&   rr   	ef_streamspec_objrx   
names_dictef_name_treeef_name_arrspec_obj_refroot_af_arrs
             r$   r   r   "  s%    ""I  =
 	
 !!#H??D!(^
0!"23 ,!:
 	
2"8, w))$*?*?@A((2L|$,'(((8	%u+K
 	<((((8W  !--/
#..z:X !  0//1'1'<'<\'J
#$##J/0  2))+!+!6!6{!CX##L12   	%!--/K$//<DK""$	%sL   D E F !G% AEEAFFAG"!G"%AH*)H*zattachment.pdfzWrapped document)passwordcertsr9   rd   r(   re   rf   include_explanation_pageplaintext_payloadr   r   r9   rd   r(   re   r*   c          
         t        j                         }	|V|du |du k(  rt        d      ||J t        j                  ddd      }
|
j                          t        j                  t        j                  j                  t        j                  j                  ddt        j                  t        j                  |
it        j                              }|
j                  |t                      n{t        j                  d	      }|j                          t        j                   j#                  |t        j                  t        j$                  |it        j$                        d
      }|	j'                  |       t)        j*                         x|	j,                  d<   }t/        d      |d<   t)        j0                  |      |d<   t/        d      |d<   t2        j5                  |	| d|xs
 t7                     }t9        ||||      }t;        |	|       |rt)        j*                  t/        d      t)        j*                  t/        d      t=        |	      i      i      }d}t)        j>                  |jA                  d            }t        jB                  |	jE                  |      d|      }|	jG                  |       |	S )a|
  
    Include a PDF document as an encrypted attachment in a wrapper document.

    This function sets certain flags in the wrapper document's collection
    dictionary to instruct compliant PDF viewers to display the attachment
    instead of the wrapping document. Viewers that do not fully support
    PDF collections will display a landing page instead, explaining
    how to open the attachment manually.

    Using this method mitigates some weaknesses in the PDF standard's encryption
    provisions, and makes it harder to manipulate the encrypted attachment
    without knowing the encryption key.

    .. danger::
        Until PDF supports authenticated encryption mechanisms, this is
        a mitigation strategy, not a foolproof defence mechanism.

    .. warning::
        While users of viewers that do not support PDF collections can still
        open the attached file manually, the viewer still has to support
        PDF files where only the attachments are encrypted.

    .. note::
        This is not quite the same as the "unencrypted wrapper document"
        pattern discussed in the PDF 2.0 specification. The latter is intended
        to support nonstandard security handlers. This function uses a standard
        security handler on the wrapping document to encrypt the attachment
        as a binary blob.
        Moreover, the functionality in this function is available in PDF 1.7
        viewers as well.

    :param plaintext_payload:
        The plaintext payload (a binary representation of a PDF document).
    :param security_handler:
        The security handler to use on the wrapper document.
        If ``None``, a security handler will be constructed based on the
        ``password`` or ``certs`` parameter.
    :param password:
        Password to encrypt the attachment with.
        Will be ignored if ``security_handler`` is provided.
    :param certs:
        Encrypt the file using PDF public-key encryption, targeting the
        keys in the provided certificates.
        Will be ignored if ``security_handler`` is provided.
    :param file_spec_string:
        PDFDocEncoded file spec string for the attachment.
    :param params:
        Embedded file parameters to use.
    :param file_name:
        Unicode file name for the attachment.
    :param description:
        Description for the attachment
    :param include_explanation_page:
        If ``False``, do not generate an explanation page in the wrapper
        document. This setting could be useful if you want to customise the
        wrapper document's behaviour yourself.
    :return:
        A :class:`~writer.PdfFileWriter` representing the wrapper document.
    NzSIf 'security_handler' is not provided, exactly one of 'password' or 'cert' must be.    F)keylenacts_as_defaultencrypt_metadata)default_file_filter)ru   pubkey_handler_subfilterlegacy_keylenr   rA   )policy)r   )rA   r   z/Collectionr5   z/Dz/Hz/Viewzapplication/pdf)r'   r)   r(   )rd   re   rZ   rf   z/Fontz/F1a  
        BT
            /F1 10 Tf 10 830 Td 12 TL
            (This document is a wrapper for an encrypted attachment.) '
            (Your viewer should prompt for a password and ) '
            (open the attached file automatically.) Tj
            (If not, navigate to the attached document manually.) ' T*
            (In addition, your viewer must support encryption ) '
            (scoped to embedded files.) Tj
        ET
        latin1)r,   )r   r   g
ףp=@gQO@)contents	media_box	resources)$r   PdfFileWriter
ValueErrorr	   PubKeyAESCryptFilterset_embedded_onlyPubKeySecurityHandlerSecurityHandlerVersionAES256PubKeyAdbeSubFilterS5CryptFilterConfigurationDEF_EMBEDDED_FILEadd_recipientsr   StandardAESCryptFilterStandardSecurityHandlerbuild_from_pwSTD_CF_assign_security_handlerr
   rE   rx   r   rk   r   r0   r   r   r   r   StreamObjectencode
PageObjectr:   insert_page)r   r   r   r9   rd   r(   re   rf   r   w	pubkey_cfstd_cfcollection_dictef_objrr   r   stream_contentrN   explanation_pages                      r$   r   r   g  s   N 	A%4-0?  $$$2255I '')$::44;;).)B)B)E)E"!&$)$B$B,,i8(-(?(?%	  $$U3L3N$O 11<F$$&$<<JJ$)$B$B\\6*% "'  K   /0.5.F.F.HHAFF=O'6OG#445EFOD'~OG..	#-+-	 / F )	D q$,,!7#;#;e_k!n5$
	
 %%&--h7
 ",,\\&),	
 	
&'Hr#   )#rb   rH   dataclassesr   r   typingr   r   
asn1cryptor    r	   r
   r   r   crypt.pubkeyr   
font.basicr   r   r   __all__r   r   r   r   r   rT   r   rU   rV   CertificateSecurityHandlerr   r   r"   r#   r$   <module>r      sg    !  !  * * 3 # ) $  @d
-- d
N $+ + +< $Z Z ZzB9633 B98 B9P #.28<,+/#"!ff smf D))*+	f
 u445f f '(f }f fr#   