a
    î½jçX  ã                   @   st   d Z ddlZdd„ ZdZdd„ ZG dd	„ d	eƒZG d
d„ dƒZG dd„ deƒZ	dZ
G dd„ dƒZdd„ Zdd„ ZdS )zÌSimplexml module provides xmpppy library with all needed tools to handle XML nodes and XML streams.
I'm personally using it in many other separate projects. It is designed to be as standalone as possible.é    Nc                 C   s4   |   dd¡  dd¡  dd¡  dd¡  d	d
¡  dd
¡S )zWReturns provided string with symbols & < > " replaced by their respective XML entities.ú&z&amp;ú<z&lt;ú>z&gt;ú"z&quot;úÚ ú)Úreplace)Útxt© r   úT/Users/admin/.hermes/hermes-agent/venv/lib/python3.9/site-packages/xmpp/simplexml.pyÚ	XMLescape   s    r   zutf-8c                 C   sN   t | tƒr| S z|  ¡ }W n ty4   t| ƒ}Y n0 t |tƒsJt|tƒS |S )zqConverts object "what" to unicode string using it's own __str__ method if accessible or unicode method otherwise.)Ú
isinstanceÚstrÚ__str__ÚAttributeErrorÚENCODING)ÚwhatÚrr   r   r   Úustr   s
    r   c                   @   sx  e Zd ZdZdZdi g ddddfdd„ZdNdd	„ZdOd
d„Zdd„ Zdi g ddfdd„Z	dd„ Z
dd„ Zdd„ Zi fdd„Zdd„ Zdd„ Zdd„ Zdd„ Zd d!„ Zd"d#„ Zd$d%„ Zd&d'„ Zi dfd(d)„Zd*d+„ Zd,d-„ Zi ddfd.d/„Zi dfd0d1„Zd2d3„ Zd4d5„ Zd6d7„ Zd8d9„ Zd:d;„ ZdPd<d=„Z i dfd>d?„Z!d@dA„ Z"i fdBdC„Z#dDdE„ Z$dFdG„ Z%dHdI„ Z&dJdK„ Z'dLdM„ Z(dS )QÚNodea’   Node class describes syntax of separate XML Node. It have a constructor that permits node creation
        from set of "namespace name", attributes and payload of text strings and other nodes.
        It does not natively support building node from text string and uses NodeBuilder class for that purpose.
        After creation node can be mangled in many ways so it can be completely changed.
        Also node can be serialised into string in one of two modes: default (where the textual representation
        of node describes it exactly) and "fancy" - with whitespace added to make indentation and thus make
        result more readable by human.

        Node class have attribute FORCE_NODE_RECREATION that is defaults to False thus enabling fast node
        replication from the some other node. The drawback of the fast way is that new node shares some
        info with the "original" node that is changing the one node may influence the other. Though it is
        rarely needed (in xmpppy it is never needed at all since I'm usually never using original node after
        replication (and using replication only to move upwards on the classes tree).
    r   NFc                 C   sJ  |râ| j rt|tƒrt|ƒ}t|tƒs6t|| ƒ}d}nª|j|ji g g |ji f\| _| _| _| _	| _
| _| _t|j ¡ ƒD ]}|j| | j|< qx|j	D ]}	| j	 |	¡ q”|j
D ]}
| j
 |
¡ q¬t|j ¡ ƒD ]\}}|| j|< qÌn.ddi g g di f\| _| _| _| _	| _
| _| _|r|| _i | _|rJt| ¡ ƒD ]\}}|| j|< q4t| ¡ ƒD ]L\}}|dkrt|| jd< n| d¡r’|| j|dd… < || | j|< qV|rþ|rÜdg| d¡ d	d… \}| _|  |¡| _n"d
|v rø| ¡ \| _| _n|| _t|tƒr|g}|D ]0}t|tƒr2| j|d n| j	 t|ƒ¡ qdS )aÍ   Takes "tag" argument as the name of node (prepended by namespace, if needed and separated from it
            by a space), attrs dictionary as the set of arguments, payload list as the set of textual strings
            and child nodes that this node carries within itself and "parent" argument that is another node
            that this one will be the child of. Also the __init__ can be provided with "node" argument that is
            either a text string containing exactly one node or another Node instance to begin with. If both
            "node" and other arguments is provided then the node initially created as replica of "node"
            provided and then modified to be compliant with other arguments.TÚtagr   NÚxmlnsúxmlns:é   ú:éþÿÿÿú ©Únode)ÚFORCE_NODE_RECREATIONr   r   r   ÚNodeBuilderÚnameÚ	namespaceÚparentÚattrsÚdataÚkidsÚnsdÚlistÚkeysÚappendÚitemsÚ	nsp_cacheÚ
startswithÚsplitÚ
lookup_nspÚaddChildr   )Úselfr   r%   Úpayloadr$   ÚnspÚ
node_builtr   Úkeyr&   ÚkidÚkÚvÚattrÚvalÚpfxÚir   r   r   Ú__init__4   sD    

4$$."

zNode.__init__r   c                 C   sR   | j  |d ¡}|d u r$| j |d ¡}|d u rN| jrJ| j |¡}|| j|< ndS |S )Nz%http://www.gajim.org/xmlns/undeclared)r(   Úgetr-   r$   r0   )r2   r<   Únsr   r   r   r0   b   s    zNode.lookup_nspc                 C   s  |d d d d | j  }| jrL| jr4| jj| jkrLd| jvrL|d| j  }t| j ¡ ƒD ]&}t| j| ƒ}|d|t|ƒf  }qZ|d }d	}| jr@|r¢|d
 }| jD ]–}|sÖt	| j
ƒd |krÖ|t| j
| ƒ }n(t	| j
ƒd |krþ|t| j
|  ¡ ƒ }t|tƒr$|| |o|d ¡ }n|r6|| ¡  }|d }q¨|snt	| j
ƒd |krn|t| j
| ƒ }n*t	| j
ƒd |kr˜|t| j
|  ¡ ƒ }| jsÌ| d¡rÌ|dd… d }|r|d
 }nB|rî| j
sî||d d d  }|d | j  d }|r|d
 }|S )z Method used to dump node into textual representation.
            if "fancy" argument is set to True produces indented output for readability.é   é   r   r   r   z xmlns="%s"z %s="%s"r   r   Ú
Néÿÿÿÿz />z</)r"   r#   r$   r%   r)   r*   r   r   r'   Úlenr&   Ústripr   r   r   Úendswith)r2   ÚfancyÚsr6   r;   ÚcntÚar   r   r   r   n   s:    

*(
.*"zNode.__str__c                 C   sd   d}d}| j r@| j D ]*}|| j|  }|r6|| ¡  }|d }qt| jƒd |kr`|| j|  }|S )z¤ Serialise node, dropping all tags and leaving CDATA intact.
            That is effectively kills all formatiing, leaving only text were contained in XML.
        r   r   rA   )r'   r&   ÚgetCDATArE   )r2   rI   rJ   rK   r   r   r   rL      s    

 zNode.getCDATAc                 C   sZ   d|v rt dƒ‚|r |}| |_nt|| ||d}|r>| |¡ | j |¡ | j d¡ |S )z If "node" argument is provided, adds it as child node. Else creates new node from
            the other arguments' values and adds it as well.r   z,Use namespace=x instead of attrs={'xmlns':x})r   r$   r%   r3   r   )r   r$   r   ÚsetNamespacer'   r+   r&   )r2   r"   r%   r3   r#   r   Znewnoder   r   r   r1   œ   s    
zNode.addChildc                 C   s    | j  t|ƒ¡ | j d¡ dS )z Adds some CDATA to node. N)r&   r+   r   r'   ©r2   r&   r   r   r   ÚaddDataª   s    zNode.addDatac                 C   s
   g | _ dS )z" Removes all CDATA from the node. N)r&   ©r2   r   r   r   Ú	clearData®   s    zNode.clearDatac                 C   s   | j |= dS )z Deletes an attribute "key" N©r%   ©r2   r6   r   r   r   ÚdelAttr±   s    zNode.delAttrc                 C   s,   t |tƒs|  ||¡}d| j| j |¡< |S )z© Deletes the "node" from the node's childs list, if "node" is an instance.
            Else deletes the first node that have specified name and (optionally) attributes. N)r   r   ÚgetTagr'   Úindex)r2   r   r%   r   r   r   ÚdelChild´   s    zNode.delChildc                 C   s   | j S )z. Returns all node's attributes as dictionary. rR   rP   r   r   r   ÚgetAttrsº   s    zNode.getAttrsc                 C   s    z| j | W S    Y dS 0 dS )z' Returns value of specified attribute. NrR   rS   r   r   r   ÚgetAttr½   s    zNode.getAttrc                 C   s   | j S )z) Returns all node's child nodes as list. )r'   rP   r   r   r   ÚgetChildrenÁ   s    zNode.getChildrenc                 C   s   d  | j¡S )z2 Returns all node CDATA as string (concatenated). r   )Újoinr&   rP   r   r   r   ÚgetDataÄ   s    zNode.getDatac                 C   s   | j S )z Returns the name of node ©r"   rP   r   r   r   ÚgetNameÇ   s    zNode.getNamec                 C   s   | j S )z Returns the namespace of node ©r#   rP   r   r   r   ÚgetNamespaceÊ   s    zNode.getNamespacec                 C   s   | j S )z* Returns the parent of node (if present). ©r$   rP   r   r   r   Ú	getParentÍ   s    zNode.getParentc                 C   sx   g }t tt| jƒt| jƒƒƒD ]T}|t| jƒk rJ| j| rJ| | j| ¡ |t| jƒk r| j| r| | j| ¡ q|S )zä Return the payload of node i.e. list of child nodes and CDATA entries.
            F.e. for "<node>text1<nodea/><nodeb/> text2</node>" will be returned list:
            ['text1', <nodea instance>, <nodeb instance>, ' text2']. )ÚrangeÚmaxrE   r&   r'   r+   )r2   Úretr=   r   r   r   Ú
getPayloadÐ   s
    (*zNode.getPayloadc                 C   s   | j |||ddS )zx Filters all child nodes using specified arguments as filter.
            Returns the first found or None if not found. rA   )Úone)ÚgetTags)r2   r"   r%   r#   r   r   r   rU   Ù   s    zNode.getTagc                 C   s&   z|   |¡j| W S    Y dS 0 dS )zY Returns attribute value of the child with specified name (or None if no such attribute).N)rU   r%   )r2   r   r:   r   r   r   Ú
getTagAttrÝ   s    zNode.getTagAttrc                 C   s$   z|   |¡ ¡ W S    Y dS 0 dS )z< Returns cocatenated CDATA of the child with specified name.N)rU   r\   ©r2   r   r   r   r   Ú
getTagDataá   s    zNode.getTagDatac                 C   s   g }| j D ]x}|sq
|r&|| ¡ kr&q
| ¡ |krnt| ¡ ƒD ]$}||jvs^|j| || kr> qnq>| |¡ |r
|r
|d   S q
|sŒ|S dS )zk Filters all child nodes using specified arguments as filter.
            Returns the list of nodes found. r   N)r'   r`   r^   r)   r*   r%   r+   )r2   r"   r%   r#   rg   Únodesr   r6   r   r   r   rh   å   s    
"
zNode.getTagsc                 c   sp   | j D ]d}|sq|dur&|| ¡ kr&q| ¡ |krt| ¡ ƒD ]$}||jvs^|j| || kr> qq>|V  qdS )z@ Iterate over all children using specified arguments as filter. N)r'   r`   r^   r)   r*   r%   )r2   r"   r%   r#   r   r6   r   r   r   ÚiterTagsó   s    

ÿzNode.iterTagsc                 C   s   || j |< dS )z, Sets attribute "key" with the value "val". NrR   )r2   r6   r;   r   r   r   ÚsetAttrÿ   s    zNode.setAttrc                 C   s   t |ƒg| _dS )zA Sets node's CDATA to provided string. Resets all previous CDATA!N)r   r&   rN   r   r   r   ÚsetData  s    zNode.setDatac                 C   s
   || _ dS )z Changes the node name. Nr]   )r2   r;   r   r   r   ÚsetName  s    zNode.setNamec                 C   s
   || _ dS )z Changes the node namespace. Nr_   )r2   r#   r   r   r   rM     s    zNode.setNamespacec                 C   s
   || _ dS )z¥ Sets node's parent to "node". WARNING: do not checks if the parent already present
            and not removes the node from the list of childs of previous parent. Nra   ©r2   r   r   r   r   Ú	setParent  s    zNode.setParentc                 C   s.   t |tƒr|g}|r$|  j|7  _n|| _dS )zÄ Sets node payload according to the list specified. WARNING: completely replaces all node's
            previous content. If you wish just to add child or CDATA - use addData or addChild methods. N)r   r   r'   )r2   r3   Úaddr   r   r   Ú
setPayload  s    zNode.setPayloadc                 C   s.   | j |||dd}|r|S | j|||dS dS )z} Same as getTag but if the node with specified namespace/attributes not found, creates such
            node and returns it. rA   )r#   rg   r_   N)rh   r1   )r2   r"   r%   r#   r   r   r   r   ÚsetTag  s    zNode.setTagc                 C   s8   z||   |¡j|< W n   | j|||id Y n0 dS )zv Creates new node (if not already present) with name "tag"
            and sets it's attribute "attr" to value "val". rR   N)rU   r%   r1   )r2   r   r:   r;   r   r   r   Ú
setTagAttr  s    zNode.setTagAttrc                 C   sB   z|   ||¡ t|ƒ¡ W n"   | j||t|ƒgd Y n0 dS )z Creates new node (if not already present) with name "tag" and (optionally) attributes "attrs"
            and sets it's CDATA to string "val". ©r3   N)rU   ro   r   r1   )r2   r   r;   r%   r   r   r   Ú
setTagData   s    zNode.setTagDatac                 C   s
   || j v S )z% Checks if node have attribute "key".rR   rS   r   r   r   Úhas_attr%  s    zNode.has_attrc                 C   s
   |   |¡S )z( Returns node's attribute "item" value. )rY   ©r2   Úitemr   r   r   Ú__getitem__(  s    zNode.__getitem__c                 C   s   |   ||¡S )z% Sets node's attribute "item" value. )rn   )r2   r{   r;   r   r   r   Ú__setitem__+  s    zNode.__setitem__c                 C   s
   |   |¡S )z" Deletes node's attribute "item". )rT   rz   r   r   r   Ú__delitem__.  s    zNode.__delitem__c                 C   s8   |dkrt | ƒ| _ | j S |dkr0t| ƒ| _| jS t‚dS )zK Reduce memory usage caused by T/NT classes - use memory only when needed. ÚTÚNTN)r   r€   r   ©r2   r:   r   r   r   Ú__getattr__1  s    

zNode.__getattr__)r   )r   )r   ))Ú__name__Ú
__module__Ú__qualname__Ú__doc__r    r>   r0   r   rL   r1   rO   rQ   rT   rW   rX   rY   rZ   r\   r^   r`   rb   rf   rU   ri   rk   rh   rm   rn   ro   rp   rM   rr   rt   ru   rv   rx   ry   r|   r}   r~   r‚   r   r   r   r   r   $   sL   .

!	
r   c                   @   s0   e Zd ZdZdd„ Zdd„ Zdd„ Zdd	„ Zd
S )r   z= Auxiliary class used to quick access to node's child nodes. c                 C   s   || j d< d S )Nr   )Ú__dict__rq   r   r   r   r>   =  ó    z
T.__init__c                 C   s   | j  |¡S ©N)r   rU   r   r   r   r   r‚   >  rˆ   zT.__getattr__c                 C   s4   t |tƒr"tj| j |¡|d n| j ||¡S d S )Nr   )r   r   r>   r   ru   rx   ©r2   r:   r;   r   r   r   Ú__setattr__?  s    "zT.__setattr__c                 C   s   | j  |¡S r‰   )r   rW   r   r   r   r   Ú__delattr__B  rˆ   zT.__delattr__N)rƒ   r„   r…   r†   r>   r‚   r‹   rŒ   r   r   r   r   r   ;  s
   r   c                   @   s    e Zd ZdZdd„ Zdd„ ZdS )r€   z: Auxiliary class used to quick create node's child nodes. c                 C   s   | j  |¡S r‰   )r   r1   r   r   r   r   r‚   F  rˆ   zNT.__getattr__c                 C   s2   t |tƒr| jj||d n| jj||gdS d S )Nr   rw   )r   r   r   r1   rŠ   r   r   r   r‹   G  s    zNT.__setattr__N)rƒ   r„   r…   r†   r‚   r‹   r   r   r   r   r€   D  s   r€   Znodebuilderc                   @   sŽ   e Zd ZdZd"dd„Zdd„ Zdd„ Zd	d
„ Zdd„ Zdd„ Z	dd„ Z
d#dd„Zdd„ Zdd„ Zdd„ Zdd„ Zd$dd„Zdd„ Zd d!„ ZdS )%r!   a½   Builds a Node class minidom from data parsed to it. This class used for two purposes:
        1. Creation an XML Node from a textual representation. F.e. reading a config file. See an XML2Node method.
        2. Handling an incoming XML stream. This is done by mangling
           the __dispatch_depth parameter and redefining the dispatch method.
        You do not need to use this class directly if you do not designing your own XML handler.Nc                 C   s®   |   tdd¡ tjj ¡ | _| j| j_| j	| j_
| j| j_| j| j_d| j_| jj| _d| _d| _d| _d| _d| _d| _|| _d| _d| _d| _d| _|rª| j |d¡ dS )al   Takes two optional parameters: "data" and "initial_node".
            By default class initialised with empty Node class instance.
            Though, if "initial_node" is provided it used as "starting point".
            You can think about it as of "node upgrade".
            "data" (if provided) feeded to parser immidiatedly after instance init.
            z(Preparing to handle incoming XML stream.ÚstartTr   rA   Nr   )ÚDEBUGÚDBG_NODEBUILDERÚxmlÚparsersÚexpatÚParserCreateÚ_parserÚstarttagÚStartElementHandlerÚendtagÚEndElementHandlerÚhandle_cdataÚCharacterDataHandlerÚhandle_namespace_startÚStartNamespaceDeclHandlerÚbuffer_textÚParseÚ_NodeBuilder__depthÚ_NodeBuilder__last_depthÚ_NodeBuilder__max_depthÚ_dispatch_depthÚ_document_attrsÚ_document_nspÚ	_mini_domÚlast_is_dataÚ_ptrÚdata_bufferÚstreamError)r2   r&   Zinitial_noder   r   r   r>   R  s*    




zNodeBuilder.__init__c                 C   s2   | j r.| jj d | j ¡¡ | j d d …= d | _ d S )Nr   )r¨   r§   r&   r+   r[   rP   r   r   r   Úcheck_data_bufferp  s    zNodeBuilder.check_data_bufferc                 C   s,   |   ¡  d| j_d| j_d| j_d| j_dS )z> Method used to allow class instance to be garbage-collected. N)rª   r”   r–   r˜   rš   rœ   rP   r   r   r   Údestroyv  s
    zNodeBuilder.destroyc           	   
   C   s¾  |   ¡  |  ¡  |  td| j|t|ƒf d¡ | j| jkrx| jsVt||| j	dd| _ntj
| j||| j	dd | j| _n6| j| jkr®| jj t|| j|dd¡ | jjd | _| jdkr’i | _i | _	dg| d	¡ d
d… \}}t| ¡ ƒD ]H\}}|dkr|| j	d< qî| d¡r,|| j	|dd… < qî|| j|< qî| j	 |d¡}z|  |||¡ W n8 ty } zd| _tt|ƒƒ‚W Y d}~n
d}~0 0 | js´| jjr´| jjj d¡ d| _dS )ú$XML Parser callback. Used internallyz$DEPTH -> %i , tag -> %s, attrs -> %sZdownT)r   r%   r4   r5   )r   r$   r%   r5   rD   rA   r   r   r   Nr   r   r   z*http://www.gajim.org/xmlns/undeclared-rootr   )rª   Ú
_inc_depthrŽ   r   rŸ   Úreprr¢   r¥   r   r¤   r>   r§   r'   r+   r£   r/   r)   r,   r.   r?   Ústream_header_receivedÚ
ValueErrorr   r¦   r$   r&   )	r2   r   r%   r4   r"   r:   r;   r@   Úer   r   r   r•   ~  s<    

"zNodeBuilder.starttagc                 C   s¦   |   td| j|f d¡ |  ¡  | j| jkr\| j ¡ dkrN| j ¡ d  ¡ | _|  	| j¡ n&| j| jkrt| j
j| _
n|   tdd¡ |  ¡  d| _| jdkr¢|  ¡  dS )r¬   zDEPTH -> %i , tag -> %sÚupÚerrorr   z2Got higher than dispatch level. Stream terminated?ÚstopN)rŽ   r   rŸ   rª   r¢   r¥   r^   rZ   r©   Údispatchr§   r$   Ú
_dec_depthr¦   Ústream_footer_receivedrj   r   r   r   r—   ¡  s    zNodeBuilder.endtagc                 C   s@   |   t|d¡ | jr(| jr<| j |¡ n| jr<|g| _d| _dS )r¬   r&   rA   N)rŽ   r   r¦   r¨   r+   r§   rN   r   r   r   r™   ±  s    zNodeBuilder.handle_cdatac                 C   s   |   ¡  dS )r¬   N©rª   )r2   ÚprefixÚurir   r   r   r›   »  s    z"NodeBuilder.handle_namespace_startc                 C   s   dS )zM Gets all NodeBuilder walking events. Can be used for debugging if redefined.Nr   )r2   ÚlevelÚtextÚcommentr   r   r   rŽ   ¿  s    zNodeBuilder.DEBUGc                 C   s   |   ¡  | jS )z Returns just built Node. )rª   r¥   rP   r   r   r   ÚgetDomÁ  s    zNodeBuilder.getDomc                 C   s   dS )z¾ Gets called when the NodeBuilder reaches some level of depth on it's way up with the built
            node as argument. Can be redefined to convert incoming XML stanzas to program events. Nr   )r2   Zstanzar   r   r   rµ   Å  s    zNodeBuilder.dispatchc                 C   s   |   ¡  dS )z( Method called when stream just opened. Nr¸   )r2   r@   r   r%   r   r   r   r¯   È  s    z"NodeBuilder.stream_header_receivedc                 C   s   |   ¡  dS )z( Method called when stream just closed. Nr¸   rP   r   r   r   r·   Ë  s    z"NodeBuilder.stream_footer_receivedr   c                 C   s   | j |ko| j|kS )z9 Return True if at least one end tag was seen (at level) )rŸ   r¡   )r2   r»   r   r   r   Úhas_received_endtagÏ  s    zNodeBuilder.has_received_endtagc                 C   s*   | j | _|  j d7  _ t| j | jƒ| _d S ©NrA   )rŸ   r    rd   r¡   rP   r   r   r   r­   Ó  s    zNodeBuilder._inc_depthc                 C   s   | j | _|  j d8  _ d S rÀ   )rŸ   r    rP   r   r   r   r¶   Ø  s    zNodeBuilder._dec_depth)NN)N)r   )rƒ   r„   r…   r†   r>   rª   r«   r•   r—   r™   r›   rŽ   r¾   rµ   r¯   r·   r¿   r­   r¶   r   r   r   r   r!   L  s    
#


r!   c                 C   s   t | ƒ ¡ S )z³ Converts supplied textual string into XML node. Handy f.e. for reading configuration file.
        Raises xml.parser.expat.parsererror if provided string is not well-formed XML. ©r!   r¾   ©r   r   r   r   ÚXML2NodeÜ  s    rÃ   c                 C   s   t | ƒ ¡ S )a   Converts supplied textual string into XML node. Survives if xml data is cutted half way round.
        I.e. "<html>some text <br>some more text". Will raise xml.parser.expat.parsererror on misplaced
        tags though. F.e. "<b>some text <br>some more text</b>" will not work.rÁ   rÂ   r   r   r   ÚBadXML2Nodeá  s    rÄ   )r†   Zxml.parsers.expatr   r   r   r   Úobjectr   r   r€   r   r!   rÃ   rÄ   r   r   r   r   Ú<module>   s     	 