o
    9Biv@                     @  s  d Z ddlmZ ddlZddl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 ddlmZ dd	lmZmZmZ dd
lmZ ddlmZmZmZmZmZ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( ddl)m*Z*m+Z+m,Z,m-Z-m.Z. ddl/m0Z1 ddl2m3Z3 ddl4m5Z5 ddl6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZC ddlDmEZEm Z  G dd dejFZGeG dd deHZIG dd dejFZJedd eJd!ZKe	eeef e.gdf ZLe3 ZMG d"d# d#ejFeK ZNG d$d% d%ejFeK ZOed d&G d'd( d(ZPedXd/d0ZQee+eG d1d2 d2e
eK ZReReJ ZSeQjTdYd4d5ZUeQjTdZd7d8ZVeQjTd[d:d;ZWeQjTd\d=d>ZXeQjTd]d@dAZYeQjTd^dCdDZZeQjTd_dFdGZ[eQjTd`dIdJZ\dadNdOZ]G dPdQ dQeCZ^dbdVdWZ_dS )czD
Private implementation module for public L{twisted.web.websocket}.
    )annotationsN)	dataclassfield)singledispatch)CallableGenericTypeVarUnion)implementer)URL)
ConnectionConnectionTypeWSConnection)ConnectionState)
AcceptConnectionBytesMessageCloseConnectionEventPingPongRejectConnection
RejectDataRequestTextMessage)H11Handshake)RemoteProtocolError)Deferred)	IConsumer	IProtocolIPushProducerIReactorTCP
ITransport)Factory)Logger)Failure)BAD_REQUEST)URIBrowserLikePolicyForHTTPSResponse_StandardEndpointFactory)Headers)IAgentEndpointFactoryIPolicyForHTTPS)Resource)NOT_DONE_YETr   c                   @  sP   e Zd ZdZdddZdd
dZddddZd d!ddZd"ddZd#ddZ	dS )$WebSocketTransportz9
    The transport that can send websocket messages.
    textstrreturnNonec                 C     dS )z&
        Send a text message.
        N )selfr0   r5   r5   [/var/www/html/Trade-python/venv/lib/python3.10/site-packages/twisted/web/_websocket_impl.pysendTextMessageA       z"WebSocketTransport.sendTextMessagedatabytesc                 C  r4   )z'
        Send a bytes message.
        Nr5   r6   r:   r5   r5   r7   sendBytesMessageF   r9   z#WebSocketTransport.sendBytesMessage  codeintc                 C  r4   )z0
        Drop the websocket connection.
        Nr5   )r6   r?   r5   r5   r7   loseConnectionK   r9   z!WebSocketTransport.loseConnection    payloadc                 C  r4   )a  
        Send a websocket Ping request to measure latency.

        @note: Per U{Mozilla's documentation
            <https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#pings_and_pongs_the_heartbeat_of_websockets>},
            multiple 'ping' requests may be coalesced into a single 'pong', and
            unsolicited 'pong' requests must be ignored, so we do not return a
            L{deferred <twisted.internet.defer.Deferred>} here; pongs are
            delivered separately.
        Nr5   r6   rC   r5   r5   r7   pingP   r9   zWebSocketTransport.pingproducerr   c                 C  r4   )zF
        Attach the given L{IPushProducer} to this transport.
        Nr5   r6   rF   r5   r5   r7   attachProducer\   r9   z!WebSocketTransport.attachProducerc                 C  r4   )zT
        Detach a previously attached L{IPushProducer} from this transport.
        Nr5   r6   r5   r5   r7   detachProducera   r9   z!WebSocketTransport.detachProducerNr0   r1   r2   r3   r:   r;   r2   r3   )r>   )r?   r@   r2   r3   rB   rC   r;   r2   r3   rF   r   r2   r3   r2   r3   )
__name__
__module____qualname____doc__r8   r=   rA   rE   rH   rJ   r5   r5   r5   r7   r/   <   s    


r/   c                   @  s   e Zd ZU dZded< dS )ConnectionRejectedz
    A websocket connection was rejected by an HTTP response.

    @ivar response: The HTTP response that describes the rejection.
    r(   responseN)rQ   rR   rS   rT   __annotations__r5   r5   r5   r7   rU   g   s   
 rU   c                   @  sL   e Zd ZdZ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 ) WebSocketProtocolac  
    An object that conforms to L{WebSocketProtocol} can receive all the events
    from a websocket connection.

    @note: While this is I{sort of} like a L{byte-stream protocol
        <twisted.internet.interfaces.IProtocol>}, the interface is distinct in
        a few ways; in particular, we have discrete C{negotiationStarted} and
        C{negotiationFinished} methods, representing those events in the
        websocket handshaking process, and no C{connectionMade}; similarly,
        since websockets can natively support both text and bytes messages,
        rather than fragmentable segments of a byte stream, we have
        C{textMessageReceived} and C{bytesMessageReceived} but no
        C{dataReceived}.  Finally, this is a L{typing.Protocol} and not a
        L{zope.interface.Interface}, since it does not predate the L{typing}
        module.
    	transportr/   r2   r3   c                 C  r4   )z
        An underlying transport (e.g.: a TCP connection) has been established;
        negotiation of the websocket transport has begun.
        Nr5   r6   rY   r5   r5   r7   negotiationStarted   r9   z$WebSocketProtocol.negotiationStartedc                 C  r4   )zn
        Negotiation is complete: a bidirectional websocket channel is now fully
        established.
        Nr5   rI   r5   r5   r7   negotiationFinished   r9   z%WebSocketProtocol.negotiationFinishedrC   r;   c                 C  r4   )a  
        A Pong message was received.

        @note: Per U{the standard
            <https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2>}::

                A Pong frame sent in response to a Ping frame must have identical
                "Application data" as found in the message body of the Ping frame
                being replied to.

                If an endpoint receives a Ping frame and has not yet sent Pong
                frame(s) in response to previous Ping frame(s), the endpoint MAY
                elect to send a Pong frame for only the most recently processed
                Ping frame.

            Given that some Pong frames may be dropped, this event should only
            be used in concert with the transport's L{.ping
            <WebSocketTransport.ping>} method for its intended purpose, to
            measure latency and connection durability, not to transport
            application data.
        Nr5   rD   r5   r5   r7   pongReceived   r9   zWebSocketProtocol.pongReceivedmessager1   c                 C  r4   )z<
        A text message was received from the peer.
        Nr5   )r6   r^   r5   r5   r7   textMessageReceived   r9   z%WebSocketProtocol.textMessageReceivedr:   c                 C  r4   )z=
        A bytes message was received from the peer.
        Nr5   r<   r5   r5   r7   bytesMessageReceived   r9   z&WebSocketProtocol.bytesMessageReceivedreasonr$   c                 C  r4   )z4
        The websocket connection was lost.
        Nr5   r6   ra   r5   r5   r7   connectionLost   r9   z WebSocketProtocol.connectionLostN)rY   r/   r2   r3   rP   rN   )r^   r1   r2   r3   rL   ra   r$   r2   r3   )
rQ   rR   rS   rT   r[   r\   r]   r_   r`   rc   r5   r5   r5   r7   rX   r   s    




rX   _WSPT)	covariantboundc                   @     e Zd ZdZd	ddZdS )
WebSocketServerFactoryz
    A L{WebSocketServerFactory} is a factory for a particular kind of
    L{WebSocketProtocol} that implements server-side websocket listeners via
    L{WebSocketResource}.
    requestr   r2   re   c                 C  r4   )a/  
        To conform to L{WebSocketServerFactory}, you must implement a
        C{buildProtocol} method which takes a L{Request
        <twisted.web.server.Request>} and returns a L{WebSocketProtocol}.

        @return: a L{WebSocketProtocol} that will handle the inbound
            connection.
        Nr5   )r6   rj   r5   r5   r7   buildProtocol   r9   z$WebSocketServerFactory.buildProtocolN)rj   r   r2   re   rQ   rR   rS   rT   rk   r5   r5   r5   r7   ri          ri   c                   @  rh   )
WebSocketClientFactoryz
    A L{WebSocketClientFactory} is a factory for a particular kind of
    L{WebSocketProtocol} that implements client-side websocket listeners via
    L{WebSocketClientEndpoint}.
    urlr1   r2   re   c                 C  r4   )a#  
        To conform to L{WebSocketServerFactory}, you must implement a
        C{buildProtocol} method which takes a string representing an URL and
        returns a L{WebSocketProtocol}.

        @return: a L{WebSocketProtocol} that will handle the outgoing
            connection.
        Nr5   )r6   ro   r5   r5   r7   rk      r9   z$WebSocketClientFactory.buildProtocolN)ro   r1   r2   re   rl   r5   r5   r5   r7   rn      rm   rn   )frozenc                   @  sH   e Zd ZU dZded< 	 ded< 	 ee ddfdddZdddZdS )WebSocketClientEndpointz
    A L{WebSocketClientEndpoint} describes an URL to connect to and a way of
    connecting to that URL, that can connect a L{WebSocketClientFactory} to
    that URL.
    r+   endpointFactoryr1   ro   Nreactorr    	tlsPolicyr,   connectTimeout
int | NonebindAddressbytes | Noner2   c                 C  s   t ||||}t||S )a)  
        Construct a L{WebSocketClientEndpoint} from a reactor and a URL.

        @param reactor: The reactor to use for the TCP connection.

        @param url: a string describing an URL where a websocket server lives.

        @param tlsPolicy: The TLS policy to use for HTTPS connections.

        @param connectTimeout: The number of seconds for the TCP-level
            connection timeout.

        @param bindAddress: The bind address to use for the TCP client
            connections.

        @return: the newly constructed endpoint.
        )r)   rq   )clsrs   ro   rt   ru   rw   rr   r5   r5   r7   new   s   
zWebSocketClientEndpoint.newprotocolFactoryWebSocketClientFactory[_WSP]re   c                   sX   j tjd}dfdd	 |t fd
dI dH }|j	I dH S )ae  
        Make an outgoing connection to this L{WebSocketClientEndpoint}'s HTTPS
        connection.

        @param protocolFactory: The constructor for the protocol.

        @return: A coroutine (that yields L{Deferred}s) that completes with the
            connected L{WebSocketProtocol} once the websocket connection is
            established.
        zutf-8wscWSConnection | Connectiontr!   r2   r3   c                   s<   t  j}t|jddd d}|| t|j| d S )N )schemehostport)	r   fromTextro   r1   replacewritesend	WSRequestr   )r}   r   htargetrI   r5   r7   clientBootstrap   s   z8WebSocketClientEndpoint.connect.<locals>.clientBootstrapc                     s   t ttj jS N)_WebSocketWireProtocolr   r   CLIENTrk   ro   r5   r   r{   r6   r5   r7   <lambda>'  s
    
z1WebSocketClientEndpoint.connect.<locals>.<lambda>Nr}   r~   r   r!   r2   r3   )
rr   endpointForURIr&   	fromBytesro   encodeconnectProtocolFactoryforProtocol_done)r6   r{   endpoint	connectedr5   r   r7   r     s   
	zWebSocketClientEndpoint.connect)rs   r    ro   r1   rt   r,   ru   rv   rw   rx   r2   rq   )r{   r|   r2   re   )	rQ   rR   rS   rT   rW   classmethodr'   rz   r   r5   r5   r5   r7   rq      s   
 rq   eventr   protoAnyWSWPr2   r3   c                 C  r4   )z,
    Handle a websocket protocol event.
    Nr5   r   r   r5   r5   r7   _handleEvent1  r9   r   c                   @  s   e Zd ZU ded< ded< ded< eddZd	ed
< eddZded< dZded< d8ddZd9ddZ	d:ddZ
d;ddZd<d d!Zd:d"d#Zd=d>d&d'Zd?d@d,d-ZdAd0d1Zd9d2d3Zd9d4d5Zd9d6d7ZdS )Br   r~   _wsconn
_Bootstrap
_bootstrapre   _wspF)initr!   rY   zDeferred[_WSP]r   NzResponse | None_rejectResponser2   r3   c                 C  s   || _ t | _|   d S r   )rY   r   r   connectionMaderZ   r5   r5   r7   makeConnectionG  s   z%_WebSocketWireProtocol.makeConnectionc                 C  s    | j |  | | j| j d S r   )r   r[   r   r   rY   rI   r5   r5   r7   r   L  s   z%_WebSocketWireProtocol.connectionMader:   r;   c                 C  s*   | j | | j  D ]}t||  qd S r   )r   receive_dataeventsr   )r6   r:   r   r5   r5   r7   dataReceivedQ  s   z#_WebSocketWireProtocol.dataReceivedra   r$   c                 C  s0   | j | | jd ur| j| d | _d S d S r   )r   rc   r   _bodyDataFinishedrb   r5   r5   r7   rc   V  s
   

z%_WebSocketWireProtocol.connectionLostr0   r1   c                 C  ,   | j }|d us	J || jt| d S r   )rY   r   r   r   r   )r6   r0   r   r5   r5   r7   r8   ]     z&_WebSocketWireProtocol.sendTextMessagec                 C  r   r   )rY   r   r   r   r   )r6   r:   r   r5   r5   r7   r=   b  r   z'_WebSocketWireProtocol.sendBytesMessagerB   rC   c                 C  r   r   )rY   r   r   r   r   )r6   rC   r   r5   r5   r7   rE   g  r   z_WebSocketWireProtocol.pingr>   r   r?   r@   c                 C  s6   | j }|d us	J || jt|| |  d S r   )rY   r   r   r   r   rA   )r6   r?   ra   r   r5   r5   r7   rA   l  s   z%_WebSocketWireProtocol.loseConnectionrF   r   c                 C  s   t | j|d d S )NT)r   rY   registerProducerrG   r5   r5   r7   rH   r  s   z%_WebSocketWireProtocol.attachProducerc                 C  s   t | j  d S r   )r   rY   unregisterProducerrI   r5   r5   r7   rJ   u  s   z%_WebSocketWireProtocol.detachProducerc                 C  s$   | j }| ` || j | j  d S r   )r   callbackr   r\   r6   doner5   r5   r7   _completeConnectionx  s   z*_WebSocketWireProtocol._completeConnectionc                 C  s,   | j d usJ | j}| `|t| j  d S r   )r   r   errbackrU   r   r5   r5   r7   _rejectConnection~  s   z(_WebSocketWireProtocol._rejectConnection)rY   r!   r2   r3   rP   rL   rd   rK   rM   rN   )r>   r   )r?   r@   ra   r1   r2   r3   rO   )rQ   rR   rS   rW   r   rY   r   r   r   r   r   rc   r8   r=   rE   rA   rH   rJ   r   r   r5   r5   r5   r7   r   8  s&   
 








r   r   c                 C  s   |   d S r   )r   r   r5   r5   r7   _handle_acceptConnection  s   r   r   c                 C  sD   t  }| jD ]
\}}||| qtd| jd||j|_|  d S )Nz1.1r   )r*   headersaddRawHeaderr(   status_coderY   r   r   )r   r   hdrkvr5   r5   r7   _handle_rejectConnection  s
   r   r   c                 C  s8   |j d us	J d|j | j | jr|j  d S d S )Nz7response should never be None when receiving RejectData)r   _bodyDataReceivedr:   body_finishedrY   rA   r   r5   r5   r7   _handle_rejectData  s   r   r   c                 C     |j | j d S r   )r   r_   r:   r   r5   r5   r7   _handle_textMessage     r   r   c                 C  r   r   )r   r`   r:   r   r5   r5   r7   _handle_bytesMessage  r   r   r   c                 C  s   |j |j|   d S r   )rY   r   r   r   rV   r   r5   r5   r7   _handle_ping  s   r   r   c                 C  r   r   )r   r]   rC   r   r5   r5   r7   _handle_pong  r   r   r   c                 C  sB   |j d usJ |jjtjkr|j |j|   |j   d S r   )	rY   r   stater   CLOSEDr   r   rV   rA   r   r5   r5   r7   _handle_closeConnection  s   r   rj   r   r;   c                 C  s   |  t | dd dS )Nzcontent-typez
text/plains$   websocket protocol negotiation error)setResponseCoder%   	setHeader)rj   r5   r5   r7   _negotiationError  s   
r   c                      s,   e Zd ZdZd fddZdddZ  ZS )WebSocketResourcez
    A L{WebSocketResource} is a L{Resource} that presents a websocket listener.
    You can install it into any twisted web server resource hierarchy.
    factory)WebSocketServerFactory[WebSocketProtocol]r2   r3   c                   s   t    || _dS )a#  
        Create a L{WebSocketResource} that will respond to incoming connections
        with the given L{WebSocketServerFactory}.

        @param factory: The factory that will be used to respond to inbound
            websocket connections on appropriately formatted GET requests.
        N)super__init__r   )r6   r   	__class__r5   r7   r     s   

zWebSocketResource.__init__rj   r   bytes | intc              
   C  s   t tj}|j }dd |D }z	|||j W n ty8 } ztj	d||d t
|W  Y d}~S d}~ww | j|}|dusGJ d|t }|j}|jj}	|	dus\J d|dusdJ dt|t|}
|j|
 |	| |  tS )	zv
        This implementation of the C{GET} HTTP method will respond to inbound
        websocket connections.
        c                 S  s"   g | ]\}}|D ]}||fqqS r5   r5   ).0hkeyhvalsvalr5   r5   r7   
<listcomp>  s   " z0WebSocketResource.render_GET.<locals>.<listcomp>z{request} failed with {rpe})rj   rpeNz"connection not accepted by twistedzchannel transport not connectedz"connection not accepted by wsproto)r   r   SERVERrequestHeadersgetAllRawHeadersinitiate_upgrade_connectionpathr   _logerrorr   r   rk   r   r   
connectionchannelrY   r   serverBootstrap_protocolUpgradeForWebsocketsr   r\   r.   )r6   rj   	handshakerawsimpleHeadersr   wsprottoSendwsconr   	wireProtor5   r5   r7   
render_GET  s,   


zWebSocketResource.render_GET)r   r   r2   r3   )rj   r   r2   r   )rQ   rR   rS   rT   r   r   __classcell__r5   r5   r   r7   r     s    r   r}   r~   r   r!   c                 C  r4   )zC
    The server requires no bootstrapping, so this is a no-op.
    Nr5   )r}   r   r5   r5   r7   r     r9   r   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )r   r   r   r   r2   r3   )rj   r   r2   r;   r   )`rT   
__future__r   typingdataclassesr   r   	functoolsr   r   r   r   r	   zope.interfacer
   	hyperlinkr   wsprotor   r   r   wsproto.connectionr   wsproto.eventsr   r   r   r   r   r   r   r   r   r   r   wsproto.handshaker   wsproto.utilitiesr   twisted.internet.deferr   twisted.internet.interfacesr   r   r   r    r!   twisted.internet.protocolr"   r   twisted.loggerr#   twisted.python.failurer$   twisted.web._responsesr%   twisted.web.clientr&   r'   r(   r)   twisted.web.http_headersr*   twisted.web.iwebr+   r,   twisted.web.resourcer-   twisted.web.serverr.   Protocolr/   	ExceptionrU   rX   re   r   r   ri   rn   rq   r   r   r   registerr   r   r   r   r   r   r   r   r   r   r   r5   r5   r5   r7   <module>   sx   0+
EPK	
,