
    Oj?                       d dl mZ d dlZd dlZd dlZd dlmZmZ d dlm	Z	 ddl
mZmZ ddl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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(m)Z)m*Z*m+Z+m,Z, ddlm-Z-m.Z.m/Z/m0Z0m1Z1m2Z2 ddl3m4Z4 ddl5m6Z6m7Z7 dgZ8 G d de+      Z9 G d de9      Z:d!dZ; e<ejz                  j}                  dd            Z? e<ejz                  j}                  dd            Z@ e<ejz                  j}                  dd            ZA e<ejz                  j}                  dd            ZBe?e@eAeBf	 	 	 	 	 	 	 	 	 d"dZC e& eD       dddd        y)#    )annotationsN)	GeneratorSequence)Any   )HeadersMultipleValuesError)InvalidHandshakeInvalidHeaderInvalidHeaderValueInvalidMessageInvalidStatusInvalidUpgradeNegotiationErrorStatusLineTooLong)ClientExtensionFactory	Extension)build_authorization_basicbuild_extension
build_hostbuild_subprotocolparse_connectionparse_extensionparse_subprotocolparse_upgrade)RequestResponse)lazy_import)CLIENT
CONNECTINGOPENProtocolState)ConnectionOptionExtensionHeader
LoggerLikeOriginSubprotocolUpgradeProtocol)WebSocketURI)
accept_keygenerate_keyClientProtocolc                       e Zd ZdZdddeddd	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 d fdZddZddZddZdd	Z	dd
Z
d fdZ xZS )r-   as  
    Sans-I/O implementation of a WebSocket client connection.

    Args:
        uri: URI of the WebSocket server, parsed
            with :func:`~websockets.uri.parse_uri`.
        origin: Value of the ``Origin`` header. This is useful when connecting
            to a server that validates the ``Origin`` header to defend against
            Cross-Site WebSocket Hijacking attacks.
        extensions: List of supported extensions, in order in which they
            should be tried.
        subprotocols: List of supported subprotocols, in order of decreasing
            preference.
        state: Initial state of the WebSocket connection.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit. You may pass a ``(max_message_size,
            max_fragment_size)`` tuple to set different limits for messages and
            fragments when you expect long messages sent in short fragments.
        logger: Logger for this connection;
            defaults to ``logging.getLogger("websockets.client")``;
            see the :doc:`logging guide <../../topics/logging>` for details.

    Ni   )origin
extensionssubprotocolsstatemax_sizeloggerc                   t         |   t        |||       || _        || _        || _        || _        t               | _        y )N)sider2   r3   r4   )	super__init__r   urir/   available_extensionsavailable_subprotocolsr,   key)	selfr9   r/   r0   r1   r2   r3   r4   	__class__s	           h/var/www/origus_pro_usr/data/www/origus.pro/core/.venv/lib/python3.12/site-packages/websockets/client.pyr8   zClientProtocol.__init__J   sL     		 	 	
 $.!&2#>    c                   t               }t        | j                  j                  | j                  j                  | j                  j
                        |d<   | j                  j                  rt        | j                  j                   |d<   | j                  | j                  |d<   d|d<   d|d<   | j                  |d<   d|d	<   | j                  @t        | j                  D cg c]  }|j                  |j                         f  c}      |d
<   | j                  t        | j                        |d<   t!        | j                  j"                  |      S c c}w )a1  
        Create a handshake request to open a connection.

        You must send the handshake request with :meth:`send_request`.

        You can modify it before sending it, for example to add HTTP headers.

        Returns:
            WebSocket handshake request event to send to the server.

        HostAuthorizationr'   	websocketUpgrade
ConnectionzSec-WebSocket-Key13zSec-WebSocket-VersionSec-WebSocket-ExtensionsSec-WebSocket-Protocol)r   r   r9   hostportsecure	user_infor   r/   r<   r:   r   nameget_request_paramsr;   r   r   resource_name)r=   headersextension_factorys      r?   connectzClientProtocol.connecta   s5    )$TXX]]DHHMM488??S88'@$((BTBT'UGO$;;" $GH(	 )'+xx#$+/'($$02A .2-F-F) '++->-Q-Q-ST3G./ &&20A++1G,- txx--w77s   $#Ec                ,   |j                   dk7  rt        |      |j                  }t        |j	                  d      D cg c]  }t        |       c}g       }t        d |D              s#t        d|rdj                  |            d      t        |j	                  d      D cg c]  }t        |       c}g       }t        |      dk(  r|d   j                         d	k(  s#t        d|rdj                  |            d      	 |d
   }|t        | j                         k7  rt#        d
|      | j%                  |      | _        | j)                  |      | _        yc c}w c c}w # t        $ r t        d
      dt        $ r t        d
d      dw xY w)z
        Check a handshake response.

        Args:
            request: WebSocket handshake response received from the server.

        Raises:
            InvalidHandshake: If the handshake response is invalid.

        e   rF   c              3  B   K   | ]  }|j                         d k(    yw)upgradeN)lower).0values     r?   	<genexpr>z2ClientProtocol.process_response.<locals>.<genexpr>   s     F%5;;=I-Fs   , NrE   r   r   rD   zSec-WebSocket-Acceptzmultiple values)status_coder   rQ   sumget_allr   anyr   joinr   lenrX   KeyErrorr   r	   r+   r<   r   process_extensionsr0   process_subprotocolsubprotocol)r=   responserQ   rZ   
connectionrW   
s_w_accepts          r?   process_responsezClientProtocol.process_response   s    3&))""-029//,2OPe$PRT.

 F:FF zdii
3 GK  *-/6y/IJe]5!JB*

 G!gaj&6&6&8K&G 'DIIg,>TTtTT	U !78J
 DHH--$%;ZHH11':33G<3 Q K  	B 67TA" 	U 68IJPTT	Us   E&E#E( (+Fc                   g }|j                  d      }|r| j                  t        d      t        |D cg c]  }t	        |       c}g       }|D ][  \  }}| j                  D ]7  }|j
                  |k7  r	 |j                  ||      }	|j                  |	        K t        d| d|        |S c c}w # t        $ r Y ^w xY w)aj  
        Handle the Sec-WebSocket-Extensions HTTP response header.

        Check that each extension is supported, as well as its parameters.

        :rfc:`6455` leaves the rules up to the specification of each
        extension.

        To provide this level of flexibility, for each extension accepted by
        the server, we check for a match with each extension available in the
        client configuration. If no match is found, an exception is raised.

        If several variants of the same extension are accepted by the server,
        it may be configured several times, which won't make sense in general.
        Extensions must implement their own requirements. For this purpose,
        the list of previously accepted extensions is provided.

        Other requirements, for example related to mandatory extensions or the
        order of extensions, may be implemented by overriding this method.

        Args:
            headers: WebSocket handshake response headers.

        Returns:
            List of accepted extensions.

        Raises:
            InvalidHandshake: To abort the handshake.

        rH   zno extensions supportedzUnsupported extension: name = z, params = )r_   r:   r   r^   r   rN   process_response_paramsappend)
r=   rQ   accepted_extensionsr0   header_valueparsed_extensionsrN   response_paramsrR   	extensions
             r?   rd   z!ClientProtocol.process_extensions   s
   > 02__%?@
((0&'@AA7:CMN<.NPR8 *; %o)-)B)B %(--5 !$5$M$M+-@%	 (..y9 #, +""&{?2CE /8 #"? O , ! !s   B28B77	CCc                H   d}|j                  d      }|r| j                  t        d      t        |D cg c]  }t	        |       c}g       }t        |      dkD  rt        dddj                  |             |d   }|| j                  vrt        d|       |S c c}w )	a#  
        Handle the Sec-WebSocket-Protocol HTTP response header.

        If provided, check that it contains exactly one supported subprotocol.

        Args:
            headers: WebSocket handshake response headers.

        Returns:
           Subprotocol, if one was selected.

        NrI   zno subprotocols supportedr   zmultiple values: r\   r   zunsupported subprotocol: )r_   r;   r   r^   r   rb   r   ra   )r=   rQ   rf   r1   ro   parsed_subprotocolss         r?   re   z"ClientProtocol.process_subprotocol   s     +/'?@**2&'BCC9<EQR\"<0RTV: &'!+#,'		2E(F'GH 
 .a0K$"="==&)B;-'PQQ Ss   Bc                8   | j                   re| j                  j                  d|j                         |j                  j	                         D ]"  \  }}| j                  j                  d||       $ | j
                  j                  |j                                y)z
        Send a handshake request to the server.

        Args:
            request: WebSocket handshake request event.

        z> GET %s HTTP/1.1z> %s: %sN)debugr4   pathrQ   	raw_itemswritesrm   	serialize)r=   requestr<   rZ   s       r?   send_requestzClientProtocol.send_request  sw     ::KK17<<@%oo779 :
U!!*c59: 	7,,./r@   c              #    K   | j                   t        u rc	 t        j                  | j                  j
                  | j                  j                  | j                  j                        E d {   }| j"                  rj$                  |j&                  }}| j(                  j#                  d||       |j*                  j-                         D ]"  \  }}| j(                  j#                  d||       $ |j.                  r/| j(                  j#                  dt1        |j.                               	 | j3                         | j                   t        u sJ t<        | _         | j8                  j;                  |       t>        |          E d {    y 7 ## t        $ rP}|| _	        | j                          | j                         | _        t        | j                         d  Y d }~ud }~wt        $ rj}t        d      | _	        || j                  _        | j                          | j                         | _        t        | j                         d  Y d }~d }~ww xY w# t4        $ rr}|_        | j8                  j;                  |       || _	        | j                          | j                         | _        t        | j                         d  Y d }~d }~ww xY w7 Tw)Nz%did not receive a valid HTTP responsez< HTTP/1.1 %d %sz< %s: %sz< [body] (%d bytes)) r2   r    r   parsereader	read_line
read_exactread_to_eofr   handshake_excsend_eofdiscardparsernext	Exceptionr   	__cause__rv   r]   reason_phraser4   rQ   rx   bodyrb   rj   r
   
_exceptioneventsrm   r!   r7   )r=   rg   exccodephraser<   rZ   r>   s          r?   r~   zClientProtocol.parse-  s)    ::#&.nnKK))KK**KK++' * zz'33X5K5Kf!!"4dFC"*"2"2"<"<"> >JCKK%%j#u=>==KK%%&;S=OP	%%h/ ::+++DJKKx(7=?""Y
 % %(""llnT[[! %3;&" 03"","llnT[[!( $ &)#""8,%(""llnT[[! 	#s   K"AF .F/F 3B;K"/I!  AK"KK"F 	IAG("K"(I4AIK"IK"!	K*A'KK"KK")r9   r*   r/   zOrigin | Noner0   z'Sequence[ClientExtensionFactory] | Noner1   zSequence[Subprotocol] | Noner2   r#   r3   z*int | None | tuple[int | None, int | None]r4   zLoggerLike | NonereturnNone)r   r   )rg   r   r   r   )rQ   r   r   zlist[Extension])rQ   r   r   zSubprotocol | None)r{   r   r   r   )r   zGenerator[None])__name__
__module____qualname____doc__r    r8   rS   rj   rd   re   r|   r~   __classcell__r>   s   @r?   r-   r-   1   s    8 !%>B59!?D$("" 	"
 <" 3" " =" "" 
".!8F+=ZG#R"H0/# /#r@   c                        e Zd Zd fdZ xZS )ClientConnectionc                X    t        j                  dt               t        |   |i | y )Nz.ClientConnection was renamed to ClientProtocol)warningswarnDeprecationWarningr7   r8   )r=   argskwargsr>   s      r?   r8   zClientConnection.__init__`  s)    <	
 	$)&)r@   )r   r   r   r   r   r   )r   r   r   r8   r   r   s   @r?   r   r   _  s    * *r@   r   c                    t        | t        t        f      ryt        | t              rt        | j                  t
              ryt        | t              r| j                  j                  dv ry| S )a  
    Determine whether a connection error is retryable or fatal.

    When reconnecting automatically with ``async for ... in connect(...)``
    (:mod:`asyncio`, :mod:`trio`) or ``for ... in reconnect(...)``
    (:mod:`threading`), whenever a connection attempt fails,
    :func:`process_exception` determines whether to retry connecting or to raise
    the exception.

    This function defines the default behavior, which is to retry on:

    * :exc:`OSError` and :exc:`asyncio.TimeoutError`: network errors;
    * :exc:`~websockets.exceptions.InvalidMessage` when it stems from an
      :exc:`EOFError`: also network errors;
    * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500,
      502, 503, or 504: server or proxy errors.

    All other exceptions are considered fatal.

    You can change this behavior with the ``process_exception`` argument of
    :func:`~websockets.asyncio.client.connect` (:mod:`asyncio`),
    :func:`~websockets.trio.client.connect` (:mod:`trio`), or
    :func:`~websockets.sync.client.reconnect` (:mod:`threading`).

    Return :obj:`None` if the exception is retryable i.e. when the error could
    be transient and trying to reconnect with the same parameters could succeed.
    The exception will be logged at the ``INFO`` level.

    Return an exception, either ``exc`` or a new exception, if the exception is
    fatal i.e. when trying to reconnect will most likely produce the same error.
    That exception will be raised, breaking out of the retry loop.

    N)i  i  i  i  )	
isinstanceOSErrorTimeoutErrorr   r   EOFErrorr   rg   r]   )r   s    r?   process_exceptionr   h  s\    F #./#~&:cmmX+N#}%#,,*B*B G + Jr@    WEBSOCKETS_BACKOFF_INITIAL_DELAY5WEBSOCKETS_BACKOFF_MIN_DELAYz3.1WEBSOCKETS_BACKOFF_MAX_DELAYz90.0WEBSOCKETS_BACKOFF_FACTORz1.618c              #  t   K   t        j                          | z   |}||k  r| ||z  }||k  r	 | w)z
    Generate a series of backoff delays between reconnection attempts.

    Yields:
        How many seconds to wait before retrying to connect.

    )random)initial_delay	min_delay	max_delayfactordelays        r?   backoffr     sM      --/M
))E
)
 )
  s   /88z.legacy.client)WebSocketClientProtocolrS   unix_connect)deprecated_aliases)r   r   r   zException | None)
r   floatr   r   r   r   r   r   r   zGenerator[float])E
__future__r   osr   r   collections.abcr   r   typingr   datastructuresr   r	   
exceptionsr
   r   r   r   r   r   r   r   r0   r   r   rQ   r   r   r   r   r   r   r   r   http11r   r   importsr   protocolr   r    r!   r"   r#   r$   r%   r&   r'   r(   r)   r9   r*   utilsr+   r,   __all__r-   r   r   r   environgetBACKOFF_INITIAL_DELAYBACKOFF_MIN_DELAYBACKOFF_MAX_DELAYBACKOFF_FACTORr   globals r@   r?   <module>r      sV   " 	   /  8	 	 	 :	 	 	 &   ? ?   + 
k#X k#\	*~ *.b bjjnn-OQTUV "**..)GOP "**..)GPQ rzz~~&A7KL 1(("	  	
 0 I $4#(	r@   