o
    iS'                     @   s   d Z ddlmZmZ ddlZeeZddl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 ddlmZ ddlmZ ddlmZmZ ddlmZ ej reddlm!Z" nddlm"Z" e#edZ$dddZ%dd Z&dd Z'dS )a(  The ``spyne.protocol.soap.mime`` module contains additional logic for using
optimized encodings for binary when encapsulating Soap 1.1 messages in Http.

The functionality in this code seems to work at first glance but is not well
tested.

Testcases and preferably improvements are most welcome.
    )print_functionunicode_literalsN)	b64encode)chain)etree)	generator)MIMEMultipart)MIMEApplication)encode_7or8bit)ValidationError)six)	ByteArrayFile)NS_XOP)message_from_string)message_from_bytes)xopTc                 C   s   t |}|d|  }|du rtddd}t|D ]}|jd|  kr(|} nqd}	|r/d}	d|	|f }d}
d	|}t|j|t	d
D ]\}
}|
 }|| ||_qEt ||
fS )a  Places the data from an attachment back into a SOAP message, replacing
    its xop:Include element or href.

    Returns a tuple of length 2 with the new message and the number of
    replacements made

    :param  id:       content-id or content-location of attachment
    :param  prefix:   Set this to true if id is content-id or false if it is
                      content-location.  It prefixes a "cid:" to the href value.
    :param  envelope: soap envelope string to be operated on
    :param  payload:  attachment data
    {%s}BodyNzSOAP Body tag not found	{%s}Fault zcid:z%s%sr   z.//xop:Include[@href="{}"])
namespaces)r   
fromstringfindr   listtagformat	enumeratexpathXPATH_NSDICT	getparentremovetexttostring)ns_soap_envhref_idenvelopepayloadprefixsoaptreesoapbodymessagechildidprefixnumr   nodeparent r0   X/var/www/html/LicenciasMIG/venv/lib/python3.10/site-packages/spyne/protocol/soap/mime.py_join_attachment<   s*   



r2   c                 C   s  | j }|\}}tjst|tjsJ d|vr|S |dd}|du r$d}|dd}|du r3tddt|}td|d}t	
d	d
| }	t|	|tjdfdd |D }	d|	}	t|	}
d}|
d}|
 D ]f}| dkrvqm|dr|d|ks|du r||
 d kr| }qm|d}|dkrt|jdd}n| }|dd}|d}d}|rt||||\}}|r|s|st||||d\}}qm|du rtdd|fS )a#  
    Translates an SwA multipart/related message into an application/soap+xml
    message.

    Returns the 'appication/soap+xml' version of the given HTTP body.

    References:
    SwA     http://www.w3.org/TR/SOAP-attachments
    XOP     http://www.w3.org/TR/xop10/
    MTOM    http://www.w3.org/TR/soap12-mtom/
            http://www.w3.org/Submission/soap11mtom10/

    :param  content_type: value of the Content-Type header field, parsed by
                          cgi.parse_header() function
    :param  ctx:          request context
    zmultipart/relatedcharsetNasciiboundaryz1Missing 'boundary' value from Content-Type headerrelatedr5   z\n\n.*r   c                 s   s    | ]}|V  qd S )Nr0   ).0er0   r0   r1   	<genexpr>   s    zcollapse_swa.<locals>.<genexpr>    start	multipart
Content-IDr   zContent-Transfer-Encodingbase64T)decodez<>zContent-LocationFzInvalid MtoM request)	in_stringr   PY2
isinstance	text_typegetr   r   r   resub	as_stringr   encoder   NLjoinr   	get_paramwalkget_content_maintypeget_payloadr   stripr2   )ctxcontent_typer#   r%   	mime_typecontent_datar3   r5   request
msg_stringmsgsoapmsgrootpartcter&   cidclocnumreplacesr0   r0   r1   collapse_swah   sd   





r_   c                 C   s  d |}t|}|dt }d}t|D ]}|jdt kr&| |f  S |} g }|  D ]\}	}
|	 dkr@|
	d} nq/|d 
 }i }|dd D ]}|
 	d	\}	}
|

d
||	< qOtddd}t|dt}|d= |d| |dd d| v r|d| d |d= |dd | D ]
\}	}
||	|
 q|d| || tt|D ]h}|| \}}t|ttfrdt| f }|| }d|_t|dt }d| |jd< || jr|| js||   tttr|| j}nd || }t|td}|d= |dd|f  || q| t!| d|" f }|# 	|}|}|| |dd 7 }|dt$t| i }| D ]	\}}|||< qOt| dkrf| |fS ||gfS )a  Apply MTOM to a SOAP envelope, separating attachments into a
    MIME multipart message.

    Returns a tuple of length 2 with dictionary of headers and string of body
    that can be sent with HTTPConnection

    References:
    XOP     http://www.w3.org/TR/xop10/
    MTOM    http://www.w3.org/TR/soap12-mtom/
            http://www.w3.org/Submission/soap11mtom10/

    :param headers   Headers dictionary of the SOAP message that would
                     originally be sent.
    :param envelope  Iterable containing SOAP envelope string that would have
                     originally been sent.
    :param params    params attribute from the Message object used for the SOAP
    :param paramvals values of the params, passed to Message.to_parent
    r   r   Nr   zcontent-type;r      =z"'r6   z?//<><>spyne_MIME_boundary<>r7   zxop+xmlzmime-versionz
start-infor<   z<spyneEnvelope>
SOAPActionr>   typezSpyneAttachment_%sz{%s}Includezcid:%shref)_encoderz<%s>z--%szContent-Length)%rK   r   r   r   _ns_soap_envr   r   itemslowersplitrP   r   r	   r
   	set_param
add_headerrE   attachrangelen
issubclassr   r   rO   r!   
SubElement_ns_xopattribfileNamedataload_from_filerd   set_payloadr"   get_boundaryrH   str)headersr%   params	paramvalsr(   r)   r*   r+   ctarraynvroottype
rootparamsctparammtompkgrootpkginametypidparaminclru   
attachmentboundmarraymtombodymtomheadersvaluer0   r0   r1   
apply_mtom   s~   






r   )T)(__doc__
__future__r   r   logging	getLogger__name__loggerrF   r?   r   	itertoolsr   lxmlr   emailr   email.mime.multipartr   email.mime.applicationr	   email.encodersr
   spyner   
spyne.utilr   spyne.model.binaryr   r   spyne.const.xmlr   rB   r   r   dictr   r2   r_   r   r0   r0   r0   r1   <module>   s.   	


,]