a
    ñ»j [  ã                   @  s¶  d dl mZ d dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
mZmZ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 dd	lmZ dd
lmZ ddlmZmZmZ ddl 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* ddl+m,Z,m-Z-m.Z.m/Z/m0Z0 ddl1m2Z2 ddl3m4Z4 g d¢Z5G dd„ de2ƒZ6dddddddde!ddddddddddddœddd d!d"d#d$d!d%d!d&d d!d'd'd'd'd(d)d*d+d,dd-œd.d/„Z7dQd!d!d,dd0œd1d2„Z8zVd d3l9m:Z: d d4l;m,Z< e:j=e:j=e:j>e:j>d5œZ?dd6dd6d5œZ@d7d8d9d,d:d;œd<d=„ZAW n* eB�y8   d7d8d9d,d:d;œd>d=„ZAY n0 dRd7d8d!d?d@œdAdB„ZCd:d9dCdDœdEdF„ZDddddGœd7d8d9d!d d!d,d:dHœdIdJ„ZEedKƒZFedLedMeFf dN�ZGG dOdP„ dPƒZHdS )Sé    )ÚannotationsN)ÚSequence)ÚAnyÚCallableÚLiteralÚTypeVarÚcasté   )ÚClientProtocol)ÚHeadersÚHeadersLike)ÚInvalidProxyMessageÚInvalidProxyStatusÚ
ProxyError)ÚClientExtensionFactory)Ú enable_client_permessage_deflate)Úbuild_authorization_basicÚ
build_hostÚvalidate_subprotocols)Ú
USER_AGENTÚResponse)Ú
CONNECTINGÚEvent)ÚStreamReader)Ú
LoggerLikeÚOriginÚSubprotocol)ÚProxyÚWebSocketURIÚ	get_proxyÚparse_proxyÚ	parse_urié   )Ú
Connection)ÚDeadline)ÚconnectÚunix_connectÚClientConnectionc                	      s€   e Zd ZdZdddddœdddddd	d
dœ‡ fdd„Zdedfdddd
dœdd„Zdd
dœ‡ fdd„Zd
dœ‡ fdd„Z‡  Z	S )r'   a1  
    :mod:`threading` implementation of a WebSocket client connection.

    :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for
    receiving and sending messages.

    It supports iteration to receive messages::

        for message in websocket:
            process(message)

    The iterator exits normally when the connection is closed with close code
    1000 (OK) or 1001 (going away) or without a close code. It raises a
    :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is
    closed with any other code.

    The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and
    ``max_queue`` arguments have the same meaning as in :func:`connect`.

    Args:
        socket: Socket connected to a WebSocket server.
        protocol: Sans-I/O connection.

    é   é
   é   ©Úping_intervalÚping_timeoutÚclose_timeoutÚ	max_queueúsocket.socketr
   úfloat | Noneú*int | None | tuple[int | None, int | None]ÚNone)ÚsocketÚprotocolr,   r-   r.   r/   Úreturnc                  s*   |  t  ¡ | _tƒ j||||||d� d S )Nr+   )Ú	threadingr   Úresponse_rcvdÚsuperÚ__init__)Úselfr4   r5   r,   r-   r.   r/   ©Ú	__class__© ú<E:\soccer\ml_env\Lib\site-packages\websockets/sync/client.pyr:   6   s    

úzClientConnection.__init__NúHeadersLike | Noneú
str | None)Úadditional_headersÚuser_agent_headerÚtimeoutr6   c                 C  s    | j td��X | j ¡ | _|dur0| jj |¡ |durH| jj d|¡ | j | j¡ W d  ƒ n1 sj0    Y  | j	 
|¡sˆtdƒ‚| jjdurœ| jj‚dS )z1
        Perform the opening handshake.

        )Zexpected_stateNú
User-Agentz.timed out while waiting for handshake response)Zsend_contextr   r5   r%   ÚrequestÚheadersÚupdateÚ
setdefaultÚsend_requestr8   ÚwaitÚTimeoutErrorZhandshake_exc)r;   rB   rC   rD   r>   r>   r?   Ú	handshakeK   s    
,zClientConnection.handshaker   )Úeventr6   c                   s:   | j du r*t|tƒsJ ‚|| _ | j ¡  ntƒ  |¡ dS )z.
        Process one incoming event.

        N)ÚresponseÚ
isinstancer   r8   Úsetr9   Úprocess_event)r;   rN   r<   r>   r?   rR   g   s
    
zClientConnection.process_event)r6   c                   s*   zt ƒ  ¡  W | j ¡  n| j ¡  0 dS )zI
        Read incoming data from the socket and process events.

        N)r9   Úrecv_eventsr8   rQ   )r;   r<   r>   r?   rS   u   s    zClientConnection.recv_events)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r:   r   rM   rR   rS   Ú__classcell__r>   r>   r<   r?   r'      s   ø"ür'   ÚdeflateTr)   r(   i   r*   )ÚsockÚsslÚserver_hostnameÚoriginÚ
extensionsÚsubprotocolsÚcompressionrB   rC   ÚproxyÚ	proxy_sslÚproxy_server_hostnameÚopen_timeoutr,   r-   r.   Úmax_sizer/   ÚloggerÚcreate_connectionÚstrzsocket.socket | Nonezssl_module.SSLContext | NonerA   zOrigin | Nonez'Sequence[ClientExtensionFactory] | NonezSequence[Subprotocol] | Noner@   zstr | Literal[True] | Noner1   z
int | Noner2   zLoggerLike | Noneztype[ClientConnection] | Noner   )ÚurirZ   r[   r\   r]   r^   r_   r`   rB   rC   ra   rb   rc   rd   r,   r-   r.   re   r/   rf   rg   Úkwargsr6   c                K  sL  |du r&d|v r&|  d¡}t dt¡ t| ƒ}|jsD|durDtdƒ‚|  dd¡}|  dd¡}|r’|du rz|du rztdƒ‚n|dur’|dur’td	ƒ‚|dur¢t|ƒ |d
kr´t|ƒ}n|durÊtd|› �ƒ‚|rÒd}
|durÞd}
|
du rît	|ƒ}
t
|ƒ}|du �rt}�zÐ|du �r|�rPt tjtj¡}| | ¡ ¡ |du�sDJ ‚| |¡ nÄ|
du�rêt|
ƒ}|jdd… dk�r�t||||  dd¡d�}nX|jdd… dk�rà|jdk�rÂ|du�rÂtdƒ‚t|||f|	||dœ|¤Ž}ntdƒ‚n*| d| ¡ ¡ tj|j|jffi |¤Ž}| d¡ |�s6| tjtjd¡ |j�r¬|du �rPt ¡ }|du �r`|j}| | ¡ ¡ |du �rˆ|j ||d�}nt!|||d�}t"tj|ƒ}| d¡ t#||||||d�}|||||||d�}W n( t$�yþ   |du�rø| %¡  ‚ Y n0 z| &||	| ¡ ¡ W n( t$�y>   | '¡  |j( )¡  ‚ Y n0 | *¡  |S )aá  
    Connect to the WebSocket server at ``uri``.

    This function returns a :class:`ClientConnection` instance, which you can
    use to send and receive messages.

    :func:`connect` may be used as a context manager::

        from websockets.sync.client import connect

        with connect(...) as websocket:
            ...

    The connection is closed automatically when exiting the context.

    Args:
        uri: URI of the WebSocket server.
        sock: Preexisting TCP socket. ``sock`` overrides the host and port
            from ``uri``. You may call :func:`socket.create_connection` to
            create a suitable TCP socket.
        ssl: Configuration for enabling TLS on the connection.
        server_hostname: Host name for the TLS handshake. ``server_hostname``
            overrides the host name from ``uri``.
        origin: Value of the ``Origin`` header, for servers that require it.
        extensions: List of supported extensions, in order in which they
            should be negotiated and run.
        subprotocols: List of supported subprotocols, in order of decreasing
            preference.
        compression: The "permessage-deflate" extension is enabled by default.
            Set ``compression`` to :obj:`None` to disable it. See the
            :doc:`compression guide <../../topics/compression>` for details.
        additional_headers (HeadersLike | None): Arbitrary HTTP headers to add
            to the handshake request.
        user_agent_header: Value of  the ``User-Agent`` request header.
            It defaults to ``"Python/x.y.z websockets/X.Y"``.
            Setting it to :obj:`None` removes the header.
        proxy: If a proxy is configured, it is used by default. Set ``proxy``
            to :obj:`None` to disable the proxy or to the address of a proxy
            to override the system configuration. See the :doc:`proxy docs
            <../../topics/proxies>` for details.
        proxy_ssl: Configuration for enabling TLS on the proxy connection.
        proxy_server_hostname: Host name for the TLS handshake with the proxy.
            ``proxy_server_hostname`` overrides the host name from ``proxy``.
        open_timeout: Timeout for opening the connection in seconds.
            :obj:`None` disables the timeout.
        ping_interval: Interval between keepalive pings in seconds.
            :obj:`None` disables keepalive.
        ping_timeout: Timeout for keepalive pings in seconds.
            :obj:`None` disables timeouts.
        close_timeout: Timeout for closing the connection in seconds.
            :obj:`None` disables the timeout.
        max_size: Maximum size of incoming messages in bytes.
            :obj:`None` disables the limit.
        max_queue: High-water mark of the buffer where frames are received.
            It defaults to 16 frames. The low-water mark defaults to ``max_queue
            // 4``. You may pass a ``(high, low)`` tuple to set the high-water
            and low-water marks. If you want to disable flow control entirely,
            you may set it to ``None``, although that's a bad idea.
        logger: Logger for this client.
            It defaults to ``logging.getLogger("websockets.client")``.
            See the :doc:`logging guide <../../topics/logging>` for details.
        create_connection: Factory for the :class:`ClientConnection` managing
            the connection. Set it to a wrapper or a subclass to customize
            connection handling.

    Any other keyword arguments are passed to :func:`~socket.create_connection`.

    Raises:
        InvalidURI: If ``uri`` isn't a valid WebSocket URI.
        OSError: If the TCP connection fails.
        InvalidHandshake: If the opening handshake fails.
        TimeoutError: If the opening handshake times out.

    NÚssl_contextzssl_context was renamed to sslz-ssl argument is incompatible with a ws:// URIÚunixFÚpathzmissing path argumentz(path and sock arguments are incompatiblerY   zunsupported compression: Té   ÚsocksÚsource_address)Z
local_addré   ÚhttpÚhttpsz8proxy_ssl argument is incompatible with an http:// proxy©rC   r[   r\   zunsupported proxyrD   ©r\   )r]   r^   r_   re   rf   r+   )+ÚpopÚwarningsÚwarnÚDeprecationWarningr!   ÚsecureÚ
ValueErrorr   r   r   r$   r'   r4   ÚAF_UNIXÚSOCK_STREAMÚ
settimeoutrD   r%   r    ÚschemeÚconnect_socks_proxyÚconnect_http_proxyÚAssertionErrorrI   rg   ÚhostÚportÚ
setsockoptÚIPPROTO_TCPÚTCP_NODELAYÚ
ssl_moduleÚcreate_default_contextÚwrap_socketÚSSLSSLSocketr   r
   Ú	ExceptionÚcloserM   Zclose_socketZrecv_events_threadÚjoinZstart_keepalive)ri   rZ   r[   r\   r]   r^   r_   r`   rB   rC   ra   rb   rc   rd   r,   r-   r.   re   r/   rf   rg   rj   Úws_urirl   rm   ÚdeadlineZproxy_parsedZsock_2r5   Ú
connectionr>   r>   r?   r%   �   sè    n
þ





úÿýúù


ÿþ




úú

ý
r%   )rm   ri   rj   r6   c                 K  sD   |du r.|  d¡du r*|  d¡du r*d}nd}tf |d| dœ|¤ŽS )aÚ  
    Connect to a WebSocket server listening on a Unix socket.

    This function accepts the same keyword arguments as :func:`connect`.

    It's only available on Unix.

    It's mainly useful for debugging servers listening on Unix sockets.

    Args:
        path: File system path to the Unix socket.
        uri: URI of the WebSocket server. ``uri`` defaults to
            ``ws://localhost/`` or, when a ``ssl`` is provided, to
            ``wss://localhost/``.

    Nr[   rk   zws://localhost/zwss://localhost/T)ri   rl   rm   )Úgetr%   )rm   ri   rj   r>   r>   r?   r&   ˆ  s
    r&   )Ú	ProxyType)r   )Zsocks5hZsocks5Zsocks4aZsocks4Fr   r   r$   r0   )ra   r�   r�   rj   r6   c              
   K  sž   t t| j | j| j| j| jt| j ƒ}| d| 	¡ ¡ z|j
|j|jfi |¤ŽW S  tttj	fyl   ‚ Y n. ty˜ } ztdƒ|‚W Y d}~n
d}~0 0 dS )z0Connect via a SOCKS proxy and return the socket.rD   z failed to connect to SOCKS proxyN)Ú
SocksProxyÚSOCKS_PROXY_TYPESr   rƒ   r„   ÚusernameÚpasswordÚSOCKS_PROXY_RDNSrI   rD   r%   ÚOSErrorrL   r4   rŒ   r   )ra   r�   r�   rj   Zsocks_proxyÚexcr>   r>   r?   r€   ¸  s    úr€   c                 K  s   t dƒ‚d S )Nz-python-socks is required to use a SOCKS proxy)ÚImportError)ra   r�   r�   rj   r>   r>   r?   r€   Ó  s    Úbytes)ra   r�   rC   r6   c                 C  s„   t |j|j|jdd�}tƒ }t |j|j|jƒ|d< |d urB||d< | jd url| jd usZJ ‚t| j| jƒ|d< d|› d� ¡ | 	¡  S )NT)Zalways_include_portÚHostrE   zProxy-AuthorizationzCONNECT z HTTP/1.1
)
r   rƒ   r„   rz   r   r–   r—   r   ÚencodeÚ	serialize)ra   r�   rC   rƒ   rG   r>   r>   r?   Úprepare_connect_requestÜ  s    
ÿr    r   )rZ   r�   r6   c              
   C  s@  t ƒ }tj|j|j|jdd�}�zz>|  | ¡ ¡ |  d¡}|rL| 	|¡ n| 
¡  t|ƒ q$W nÀ tyØ } z`t|jtƒs€J ‚|j}d|j  krœdk r¼n n|W  Y d }~W |  d ¡ S t|ƒ‚W Y d }~nRd }~0  tjyò   tdƒ‚Y n0 t�y  } ztdƒ|‚W Y d }~n
d }~0 0 W |  d ¡ n|  d ¡ 0 d S )NF)Zinclude_bodyi   éÈ   i,  z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)r   r   ÚparseZ	read_lineZ
read_exactZread_to_eofr~   rD   ÚrecvZ	feed_dataZfeed_eofÚnextÚStopIterationrP   ÚvalueÚstatus_coder   r4   rL   rŒ   r   )rZ   r�   ÚreaderÚparserÚdatarš   rO   r>   r>   r?   Úread_connect_responseï  s>    ü


öÿþr«   rt   )ra   r�   r�   rC   r[   r\   rj   r6   c                K  sº   |  d| ¡ ¡ tj| j| jffi |¤Ž}| jdkrx|d u rDt ¡ }|d u rR| j}| 	| ¡ ¡ |j
||d�}| 	d ¡ | t| ||ƒ¡ zt||ƒ W n ty´   | ¡  ‚ Y n0 |S )NrD   rs   ru   )rI   rD   r4   rg   rƒ   r„   r   rˆ   r‰   r~   rŠ   Úsendallr    r«   rŒ   r�   )ra   r�   r�   rC   r[   r\   rj   rZ   r>   r>   r?   r�     s"    

r�   ÚTÚF.)Úboundc                   @  s|   e Zd ZdZdZddddddœd	d
„Zddddœdd„Zdddœdd„Zdddœdd„Zdddœdd„Z	dddœdd„Z
dS ) r‹   zr
    Socket-like object providing TLS-in-TLS.

    Only methods that are used by websockets are implemented.

    i   Nr0   zssl_module.SSLContextrA   r3   )rZ   rk   r\   r6   c                 C  sB   t  ¡ | _t  ¡ | _|| _|j| j| j|d�| _|  | jj¡ d S )Nru   )	rˆ   Ú	MemoryBIOÚincomingÚoutgoingÚ
ssl_socketÚwrap_bioÚ
ssl_objectÚrun_ioÚdo_handshake)r;   rZ   rk   r\   r>   r>   r?   r:   E  s    

ýzSSLSSLSocket.__init__zCallable[..., T]r   r­   )ÚfuncÚargsr6   c                 G  s˜   d}d}z||Ž }W n. t jy,   d}Y n t jyB   d}Y n0 | j ¡ }|r^| j |¡ |rŽ| j | j¡}|r‚| j	 
|¡ q | j	 ¡  q |r”q |S )NFT)rˆ   ÚSSLWantReadErrorÚSSLWantWriteErrorr²   Úreadr³   r¬   r£   Úrecv_bufsizer±   ÚwriteÚ	write_eof)r;   r¸   r¹   Z	want_readZ
want_writeÚresultrª   r>   r>   r?   r¶   U  s(    


zSSLSSLSocket.run_ioÚintrœ   )Úbuflenr6   c                 C  s.   z|   | jj|¡W S  tjy(   Y dS 0 d S )Nó    )r¶   rµ   r¼   rˆ   ÚSSLEOFError)r;   rÂ   r>   r>   r?   r£   s  s    zSSLSSLSocket.recv)rª   r6   c                 C  s   |   | jj|¡S ©N)r¶   rµ   r¾   )r;   rª   r>   r>   r?   Úsendy  s    zSSLSSLSocket.sendc              	   C  s‚   d}t |ƒ�b}| d¡�8}t|ƒ}||k rB||  ||d … ¡7 }q"W d   ƒ n1 sV0    Y  W d   ƒ n1 st0    Y  d S )Nr   ÚB)Ú
memoryviewr   ÚlenrÆ   )r;   rª   ÚcountÚviewÚ	byte_viewÚamountr>   r>   r?   r¬   |  s
    zSSLSSLSocket.sendallrh   )Únamer6   c                 C  s   t | j|ƒS rÅ   )Úgetattrr³   )r;   rÎ   r>   r>   r?   Ú__getattr__‡  s    zSSLSSLSocket.__getattr__)N)rT   rU   rV   rW   r½   r:   r¶   r£   rÆ   r¬   rÐ   r>   r>   r>   r?   r‹   ;  s    ür‹   )NN)N)IÚ
__future__r   r4   r[   rˆ   r7   rw   Úcollections.abcr   Útypingr   r   r   r   r   Úclientr
   Zdatastructuresr   r   Ú
exceptionsr   r   r   Zextensions.baser   Zextensions.permessage_deflater   rG   r   r   r   Zhttp11r   r   r5   r   r   Ústreamsr   r   r   r   ri   r   r   r   r    r!   r‘   r#   Úutilsr$   Ú__all__r'   r%   r&   Zpython_socksr“   Zpython_socks.syncr”   ZSOCKS5ZSOCKS4r•   r˜   r€   r›   r    r«   r�   r­   r®   r‹   r>   r>   r>   r?   Ú<module>   s’   iã>  
  þüü ý'ù &