o
    Ð­j\V  ã                   @  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 ddlmZmZ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!m"Z" ddl#m$Z$m%Z%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/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œdbdDdE„Z7		dcdddGdH„Z8zd dIl9m:Z: d dJl;m$Z< W n e=yß   dedQdR„Z>Y nw e:j?e:j?e:j@e:j@dSœZAddTddTdSœZBdedUdR„Z>dfdWdX„ZCddddYœdgdZd[„ZDed\ƒZEed]ed^eEf d_�ZFG d`da„ daƒZGdS )hé    )ÚannotationsN)ÚSequence)ÚAnyÚCallableÚLiteralÚTypeVarÚcasté   )ÚClientProtocol)ÚHeadersLike)ÚInvalidProxyMessageÚInvalidProxyStatusÚ
ProxyError)ÚClientExtensionFactory)Ú enable_client_permessage_deflate)Úvalidate_subprotocols)Ú
USER_AGENTÚResponse)Ú
CONNECTINGÚEvent)ÚProxyÚ	get_proxyÚparse_proxyÚprepare_connect_request)ÚStreamReader)Ú	BytesLikeÚ
LoggerLikeÚOriginÚSubprotocol)ÚWebSocketURIÚ	parse_urié   )Ú
Connection)ÚDeadline)ÚconnectÚunix_connectÚClientConnectionc                      s\   e Zd ZdZdddddœd"‡ fdd„Zdedfd#dd„Zd$‡ fdd„Zd%‡ fd d!„Z‡  Z	S )&r&   a+  
    :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 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úsocket.socketÚprotocolr
   r+   úfloat | Noner,   r-   r.   ú*int | None | tuple[int | None, int | None]ÚreturnÚNonec                  s*   |  t  ¡ | _tƒ j||||||d� d S )Nr*   )Ú	threadingr   Úresponse_rcvdÚsuperÚ__init__)Úselfr/   r1   r+   r,   r-   r.   ©Ú	__class__© úS/var/www/html/CropPilot/venv/lib/python3.10/site-packages/websockets/sync/client.pyr9   7   s   


úzClientConnection.__init__NÚadditional_headersúHeadersLike | NoneÚuser_agent_headerú
str | NoneÚtimeoutc                 C  s    | j td��, | j ¡ | _|dur| jj |¡ |dur$| jj d|¡ | j | j¡ W d  ƒ n1 s5w   Y  | j	 
|¡sDtdƒ‚| jjdurN| jj‚dS )z1
        Perform the opening handshake.

        )Úexpected_stateNz
User-Agentz.timed out while waiting for handshake response)Úsend_contextr   r1   r$   ÚrequestÚheadersÚupdateÚ
setdefaultÚsend_requestr7   ÚwaitÚTimeoutErrorÚhandshake_exc)r:   r?   rA   rC   r=   r=   r>   Ú	handshakeL   s   
úÿzClientConnection.handshakeÚeventr   c                   s<   | j du rt|tƒsJ ‚|| _ | j ¡  dS tƒ  |¡ dS )z.
        Process one incoming event.

        N)ÚresponseÚ
isinstancer   r7   Úsetr8   Úprocess_event)r:   rO   r;   r=   r>   rS   h   s
   
zClientConnection.process_eventc                   s(   zt ƒ  ¡  W | j ¡  dS | j ¡  w )zI
        Read incoming data from the socket and process events.

        N)r8   Úrecv_eventsr7   rR   )r:   r;   r=   r>   rT   v   s   zClientConnection.recv_events)r/   r0   r1   r
   r+   r2   r,   r2   r-   r2   r.   r3   r4   r5   )r?   r@   rA   rB   rC   r2   r4   r5   )rO   r   r4   r5   )r4   r5   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r9   r   rN   rS   rT   Ú__classcell__r=   r=   r;   r>   r&      s    øür&   ÚdeflateTr(   r'   i   r)   )ÚsockÚsslÚserver_hostnameÚoriginÚ
extensionsÚsubprotocolsÚcompressionr?   rA   ÚproxyÚ	proxy_sslÚproxy_server_hostnameÚopen_timeoutr+   r,   r-   Úmax_sizer.   ÚloggerÚcreate_connectionÚuriÚstrr[   úsocket.socket | Noner\   ússl_module.SSLContext | Noner]   rB   r^   úOrigin | Noner_   ú'Sequence[ClientExtensionFactory] | Noner`   úSequence[Subprotocol] | Nonera   r?   r@   rA   rb   ústr | Literal[True] | Nonerc   rd   re   r2   r+   r,   r-   rf   r3   r.   rg   úLoggerLike | Nonerh   útype[ClientConnection] | NoneÚkwargsr   r4   c                K  s.  |du rd|v r|  d¡}t dt¡ t| ƒ}|js"|dur"tdƒ‚|  dd¡}|  dd¡}|rH|du r<|du r<tdƒ‚|durH|durHtd	ƒ‚|durPt|ƒ |d
krYt|ƒ}n|durdtd|› �ƒ‚|rhd}
|durnd}
|
du rvt	|ƒ}
t
|ƒ}|du r€t}zà|du �r|r£t tjtj¡}| | ¡ ¡ |dus�J ‚| |¡ n\|
durêt|
ƒ}|jdd… dkrÁt||||  dd¡d�}n>|jdd… dkræ|jdkr×|dur×tdƒ‚t|||f|	||dœ|¤Ž}ntdƒ‚| d| ¡ ¡ tj|j|jffi |¤Ž}| d¡ |�s| tjtjd¡ |j�rK|du �rt ¡ }|du �r%|j}| | ¡ ¡ |du �r9|j ||d�}nt!|||d�}t"tj|ƒ}| d¡ t#||||||d�}|||||||d�}W n t$�yr   |du�rq| %¡  ‚ w z| &||	| ¡ ¡ W n t$�y�   | '¡  |j( )¡  ‚ w | *¡  |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. 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.
        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 incompatiblerZ   zunsupported compression: Té   ÚsocksÚsource_address)Ú
local_addré   ÚhttpÚhttpsz8proxy_ssl argument is incompatible with an http:// proxy©rA   r\   r]   zunsupported proxyrC   ©r]   )r^   r_   r`   rf   rg   r*   )+ÚpopÚwarningsÚwarnÚDeprecationWarningr    ÚsecureÚ
ValueErrorr   r   r   r#   r&   r/   ÚAF_UNIXÚSOCK_STREAMÚ
settimeoutrC   r$   r   ÚschemeÚconnect_socks_proxyÚconnect_http_proxyÚAssertionErrorrI   rh   ÚhostÚportÚ
setsockoptÚIPPROTO_TCPÚTCP_NODELAYÚ
ssl_moduleÚcreate_default_contextÚwrap_socketÚSSLSSLSocketr   r
   Ú	ExceptionÚcloserN   Úclose_socketÚrecv_events_threadÚjoinÚstart_keepalive)ri   r[   r\   r]   r^   r_   r`   ra   r?   rA   rb   rc   rd   re   r+   r,   r-   rf   r.   rg   rh   rs   Úws_uriru   rv   ÚdeadlineÚproxy_parsedÚsock_2r1   Ú
connectionr=   r=   r>   r$   ‚   sì   p
þ


úÿýúù

ÿþ




ú
ú
ýý
ýr$   rv   c                 K  sD   |du r|  d¡du r|  d¡du rd}nd}td|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\   rt   zws://localhost/zwss://localhost/T)ri   ru   rv   r=   )Úgetr$   )rv   ri   rs   r=   r=   r>   r%   ‹  s
   r%   )Ú	ProxyType)r   r   rœ   r   r�   r#   r0   c                 K  s   t dƒ‚)Nz6connecting through a SOCKS proxy requires python-socks)ÚImportError)rb   rœ   r�   rs   r=   r=   r>   rŠ   ¯  s   rŠ   )Úsocks5hÚsocks5Úsocks4aÚsocks4Fc              
   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y4   ‚  tyD } ztdƒ|‚d}~ww )z0Connect via a SOCKS proxy and return the socket.rC   z failed to connect to SOCKS proxyN)Ú
SocksProxyÚSOCKS_PROXY_TYPESr‰   r�   rŽ   ÚusernameÚpasswordÚSOCKS_PROXY_RDNSrI   rC   r$   ÚOSErrorrL   r/   r–   r   )rb   rœ   r�   rs   Úsocks_proxyÚexcr=   r=   r>   rŠ   Æ  s"   ú
€ÿr   c              
   C  s  t ƒ }tj|j|j|jdd�}zsz	 |  | ¡ ¡ |  d¡}|r&| 	|¡ n| 
¡  t|ƒ q tyg } z-t|jtƒs>J ‚|j}d|j  krLdk r_n t|ƒ‚|W  Y d }~W |  d ¡ S t|ƒ‚d }~w tjyr   tdƒ‚ ty‚ } ztdƒ|‚d }~ww |  d ¡ w )NT)rb   i   éÈ   i,  z(timed out while connecting to HTTP proxyz0did not receive a valid HTTP response from proxy)r   r   ÚparseÚ	read_lineÚ
read_exactÚread_to_eofrˆ   rC   ÚrecvÚ	feed_dataÚfeed_eofÚnextÚStopIterationrQ   ÚvalueÚstatus_coder   r/   rL   r–   r   )r[   r�   ÚreaderÚparserÚdatar¯   rP   r=   r=   r>   Úread_connect_responseà  sH   ü
ùþ
ø€ÿþ€ÿr¿   r~   c                K  s´   |  d| ¡ ¡ tj| j| jffi |¤Ž}| jdkr<|d u r"t ¡ }|d u r)| j}| 	| ¡ ¡ |j
||d�}| 	d ¡ | t| ||ƒ¡ zt||ƒ W |S  tyY   | ¡  ‚ w )NrC   r}   r   )rI   rC   r/   rh   r�   rŽ   r‰   r’   r“   rˆ   r”   Úsendallr   r¿   r–   r—   )rb   rœ   r�   rA   r\   r]   rs   r[   r=   r=   r>   r‹     s$   

üþr‹   ÚTÚF.)Úboundc                   @  sT   e Zd ZdZdZ	d$d%dd„Zd&dd„Zd'dd„Zd(dd„Zd)dd„Z	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   Nr[   r0   rt   ússl_module.SSLContextr]   rB   r4   r5   c                 C  sB   t  ¡ | _t  ¡ | _|| _|j| j| j|d�| _|  | jj¡ d S )Nr   )	r’   Ú	MemoryBIOÚincomingÚoutgoingÚ
ssl_socketÚwrap_bioÚ
ssl_objectÚrun_ioÚdo_handshake)r:   r[   rt   r]   r=   r=   r>   r9   6  s   

ýzSSLSSLSocket.__init__ÚfuncúCallable[..., T]Úargsr   rÁ   c                 G  sš   	 d}d}z||Ž }W n t jy   d}Y n t jy"   d}Y nw | j ¡ }|r0| j |¡ |rH| j | j¡}|rB| j	 
|¡ n| j	 ¡  q |rKq |S )NTF)r’   ÚSSLWantReadErrorÚSSLWantWriteErrorrÇ   ÚreadrÈ   rÀ   rµ   Úrecv_bufsizerÆ   ÚwriteÚ	write_eof)r:   rÍ   rÏ   Ú	want_readÚ
want_writeÚresultr¾   r=   r=   r>   rË   F  s,   ÿ

zSSLSSLSocket.run_ioÚbuflenÚintÚbytesc                 C  s*   z	|   | jj|¡W S  tjy   Y dS w )Nó    )rË   rÊ   rÒ   r’   ÚSSLEOFError)r:   rÙ   r=   r=   r>   rµ   d  s
   ÿzSSLSSLSocket.recvr¾   r   c                 C  s   |   | jj|¡S ©N)rË   rÊ   rÔ   )r:   r¾   r=   r=   r>   Úsendj  s   zSSLSSLSocket.sendc              	   C  sš   d}t |ƒ�=}| d¡�}t|ƒ}||k r$||  ||d … ¡7 }||k sW d   ƒ n1 s.w   Y  W d   ƒ d S W d   ƒ d S 1 sFw   Y  d S )Nr   ÚB)Ú
memoryviewr   Úlenrß   )r:   r¾   ÚcountÚviewÚ	byte_viewÚamountr=   r=   r>   rÀ   m  s   ÿ€PþzSSLSSLSocket.sendallÚnamerj   c                 C  s   t | j|ƒS rÞ   )ÚgetattrrÈ   )r:   rç   r=   r=   r>   Ú__getattr__x  s   zSSLSSLSocket.__getattr__rÞ   )r[   r0   rt   rÄ   r]   rB   r4   r5   )rÍ   rÎ   rÏ   r   r4   rÁ   )rÙ   rÚ   r4   rÛ   )r¾   r   r4   rÚ   )r¾   r   r4   r5   )rç   rj   r4   r   )rU   rV   rW   rX   rÓ   r9   rË   rµ   rß   rÀ   ré   r=   r=   r=   r>   r•   ,  s    ü



r•   ).ri   rj   r[   rk   r\   rl   r]   rB   r^   rm   r_   rn   r`   ro   ra   rB   r?   r@   rA   rB   rb   rp   rc   rl   rd   rB   re   r2   r+   r2   r,   r2   r-   r2   rf   r3   r.   r3   rg   rq   rh   rr   rs   r   r4   r&   )NN)rv   rB   ri   rB   rs   r   r4   r&   )
rb   r   rœ   r   r�   r#   rs   r   r4   r0   )r[   r0   r�   r#   r4   r   )rb   r   rœ   r   r�   r#   rA   rB   r\   rl   r]   rB   rs   r   r4   r0   )HÚ
__future__r   r/   r\   r’   r6   r�   Úcollections.abcr   Útypingr   r   r   r   r   Úclientr
   Údatastructuresr   Ú
exceptionsr   r   r   Úextensions.baser   Úextensions.permessage_deflater   rG   r   Úhttp11r   r   r1   r   r   rb   r   r   r   r   Ústreamsr   r   r   r   r   ri   r   r    r    r"   Úutilsr#   Ú__all__r&   r$   r%   Úpython_socksr¢   Úpython_socks.syncr¨   r£   rŠ   ÚSOCKS5ÚSOCKS4r©   r¬   r¿   r‹   rÁ   rÂ   r•   r=   r=   r=   r>   Ú<module>   s”    iã  þþüü

'ù&