
    %i(                        d dl mZmZ d dlmZ d dlZd dlmZ  ej                          d dl	Z
d dlmZ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 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$ 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l0m1Z1 dZ2d Z3d Z4d Z5d Z6 G d de       Z7 G d de
jp                  j2                  jr                        Z:e G d de:ejv                               Z;e G d de:ejx                               Z< G d  d!e=      Z>e G d" d#e>ej~                  e
jp                  j2                  j                               Z?e G d$ d%e>ej                  e
jp                  j2                  j                               ZA ee.       G d& d'e=             ZC G d( d)eCe;      ZD G d* d+eCe<      ZE G d, d-e?      ZF G d. d/eA      ZGed:d0       ZHed;d1       ZIe G d2 d3ej                  e;             ZJe G d4 d5ej                  e?             ZKe G d6 d7ej                  e<             ZLe G d8 d9ej                  eA             ZMy)<    )	b64decode	b64encode)OptionalN)implementer)create_transport_detailstransport_channel_id)_is_tls_error_maybe_tls_reasonhltypehlvalpublic)	websocket)TransportDetails)protocol)PerMessageDeflateOfferPerMessageDeflateOfferAcceptPerMessageDeflateResponsePerMessageDeflateResponseAccept)IWebSocketClientAgent)ConnectionDenyConnectionRequestConnectionResponse)	endpoints)Deferred)ConnectionAbortedConnectionDoneConnectionLost)
ITransport)connectionDone)Failure)WampWebSocketClientFactoryWampWebSocketClientProtocolWampWebSocketServerFactoryWampWebSocketServerProtocolWebSocketAdapterFactoryWebSocketAdapterProtocolWebSocketClientFactoryWebSocketClientProtocolWebSocketServerFactoryWebSocketServerProtocolWrappingWebSocketAdapterWrappingWebSocketClientFactoryWrappingWebSocketClientProtocolWrappingWebSocketServerFactoryWrappingWebSocketServerProtocol	connectWScreate_client_agentlistenWSc                     t        |       S )zB
    :returns: an instance implementing IWebSocketClientAgent
    )_TwistedWebSocketClientAgentreactors    t/var/www/html/navyabakers_fullstack/navyabakers_prod/venv/lib/python3.12/site-packages/autobahn/twisted/websocket.pyr1   r1   R   s     (00    c                     t        | t              s#t        dj                  t	        |                   | j                  d      s| j                  d      st        d      y)z>
    raises a ValueError if `transport_config` is invalid
    z-'transport_config' must be a string, found {}zws://zwss://z6'transport_config' must start with 'ws://' or 'wss://'N)
isinstancestr
ValueErrorformattype
startswith)transport_configs    r7   check_transport_configrA   Y   se    
 &,;BB%&
 	
 &&w/8H8S8S9 QRRr8   c                     t        | t              st        d      g d}| j                         D ]   }||vst        dj	                  |             y)z5
    raises a ValueError if `options` is invalid
    z'options' must be a dict)origin	protocols	useragentheadersproxyz'options' may not contain '{}'N)r:   dictr<   keysr=   )options
valid_keysactual_ks      r7   check_client_optionsrM   n   sY    
 gt$344J LLN P:%=DDXNOOPr8   c                    |j                   r!ddlm} |j                  |j                        }|j
                  :|_        t        j                  | |j
                  d   |j
                  d         }|S |j                   r4ddlm} t        j                  | |j                  |j                        }|S t        j                  | |j                  |j                        }|S )Nr   sslhostport)isSecuretwisted.internetrP   optionsForClientTLSrQ   rG   contextFactoryr   HostnameEndpointSSL4ClientEndpointrR   )r6   factoryr@   rJ   rP   context_factoryendpoints          r7   _endpoint_from_configr\      s     (11',,?}} !0--MM&!MM&!
2 O% , 33	H O !11H Or8   c                       e Zd ZdZd ZddZy)r4   z6
    This agent creates connections using Twisted
    c                     || _         y N)_reactor)selfr6   s     r7   __init__z%_TwistedWebSocketClientAgent.__init__   s	    r8   Nc                 $  	 t        |       t        |       t        d|| j                  d|}|t        n||_        t        | j                  |||      }t               	|j                  |      }	fd	fd}|j                  |       	S )a-  
        Open a new connection.

        :param dict transport_config: valid transport configuration

        :param dict options: additional options for the factory

        :param protocol_class: a callable that returns an instance of
            the protocol (WebSocketClientProtocol if the default None
            is passed in)

        :returns: a Deferred that fires with an instance of
            `protocol_class` (or WebSocketClientProtocol by default)
            that has successfully shaken hands (completed the
            handshake).
        )urlr6   c                 (    j                  |        y r_   )errback)frtn_ds    r7   failedz1_TwistedWebSocketClientAgent.open.<locals>.failed   s    MM!r8   c                 N      fd} j                   j                  |        S )Nc                 *    j                         | S r_   )callback)argprotorh   s    r7   handshake_completedzQ_TwistedWebSocketClientAgent.open.<locals>.got_proto.<locals>.handshake_completed   s    u%
r8   )is_openaddCallbacks)rn   ro   ri   rh   s   ` r7   	got_protoz4_TwistedWebSocketClientAgent.open.<locals>.got_proto   s$     MM&&':FCLr8    )
rA   rM   r'   r`   r(   r   r\   r   connectrq   )
ra   r@   rJ   protocol_classrY   r[   proto_drr   ri   rh   s
           @@r7   openz!_TwistedWebSocketClientAgent.open   s    " 	/0W%( 
 $--
;B
 (6'=#> 	
 )MM7$4g
 
""7+		 	Y/r8   r_   )__name__
__module____qualname____doc__rb   rw   rs   r8   r7   r4   r4      s     /r8   r4   c                       e Zd ZU dZ ej
                         ZdZee	   e
d<   dZee   e
d<   d ZefdefdZdefd	Zdd
Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Z y)r&   a  
    Adapter class for Twisted WebSocket client and server protocols.

    Called from Twisted:

    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol.connectionMade`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol.connectionLost`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol.dataReceived`

    Called from Network-independent Code (WebSocket implementation):

    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onOpen`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onMessageBegin`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onMessageFrameData`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onMessageFrameEnd`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onMessageEnd`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onMessage`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onPing`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onPong`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._onClose`

    FIXME:

    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._closeConnection`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol._create_transport_details`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol.registerProducer`
    * :meth:`autobahn.twisted.websocket.WebSocketAdapterProtocol.unregisterProducer`
    Npeer	is_serverc                    t        | j                  | j                        | _        t        j
                  | j                  _        | j                  j                  | _        	 | j                  j                  | j                         | j                          | j                  j                  dt        | j                        t        | j                               y #  Y YxY w)Nz/{func} connection established for peer="{peer}"funcr}   )r   	transportr~   _transport_detailsr   CHANNEL_FRAMING_WEBSOCKETchannel_framingr}   setTcpNoDelay
tcpNoDelay_connectionMadelogdebugr   connectionMader   ra   s    r7   r   z'WebSocketAdapterProtocol.connectionMade  s    
 #;NNDNN#
 66 	/
 ++00		NN((9 	 	=++,tyy! 	 	
	s   !%C Creasonc                 n   d}t        |j                  t              r+| j                  j	                  d| j
                         d}nQt        |j                        r0| j                  j                  t        |j                               nt        |j                  t              r(| j                  j	                  d| j
                         nt        |j                  t              rjt        |j                        }t        |j                  d      r|j                  j                  }| j                  j	                  d| j
                  |       nF| j                  j	                  d	| j
                  t        |j                        |j                  
       | j                  |       |rE| j                  j	                  dt!        | j"                        t%        | j
                               y | j                  j	                  dt!        | j"                        t%        | j
                        |       y )NFz,Connection to/from {peer} was closed cleanly)r}   Tz-Connection to/from {peer} was aborted locallymessagezDConnection to/from {peer} was lost in a non-clean fashion: {message})r}   r   z7Connection to/from {peer} lost ({error_type}): {error}))r}   
error_typeerrorz8{func} connection lost for peer="{peer}", closed cleanlyr   zD{func} connection lost for peer="{peer}", closed with error {reason})r   r}   r   )r:   valuer   r   r   r}   r	   r   r
   r   r   r;   hasattrr   r>   _connectionLostr   connectionLostr   )ra   r   	was_cleanr   s       r7   r   z'WebSocketAdapterProtocol.connectionLost+  s    	fllN3HHNN>TYY   I6<<(HHNN,V\\:;&78HHNN?dii   n5&,,'Gv||Y/ ,,..HHNNVYY   HHNNIYY-ll	   	V$ HHNNJD//0499%   HHNNVD//0499%	  r8   datac           
          | j                   j                  dt        | j                        t	        | j
                        t	        t        |                   | j                  |       y )Nz2{func} received {data_len} bytes for peer="{peer}")r   r}   data_len)r   r   r   dataReceivedr   r}   len_dataReceivedra   r   s     r7   r   z%WebSocketAdapterProtocol.dataReceivedc  sP    @))*tyy!3t9%	 	 	
 	4 r8   c                     |r1t        | j                  d      r| j                  j                          y | j                  j                          y )NabortConnection)r   r   r   loseConnection)ra   aborts     r7   _closeConnectionz)WebSocketAdapterProtocol._closeConnectionn  s5    WT^^->?NN**, NN))+r8   c                     | j                   j                  r>dt        | j                  | j                   j                  d      i}|| j                   _        | j                          y )Nz
tls-unique)r   	is_securer   r   r~   
channel_idonOpen)ra   r   s     r7   _onOpenz WebSocketAdapterProtocol._onOpenu  sU    "",, 2NND$;$;$E$E|J
 2<D##.r8   c                 &    | j                  |       y r_   )onMessageBegin)ra   isBinarys     r7   _onMessageBeginz(WebSocketAdapterProtocol._onMessageBegin  s    H%r8   c                 &    | j                  |       y r_   )onMessageFrameBegin)ra   lengths     r7   _onMessageFrameBeginz-WebSocketAdapterProtocol._onMessageFrameBegin  s      (r8   c                 &    | j                  |       y r_   )onMessageFrameDatara   payloads     r7   _onMessageFrameDataz,WebSocketAdapterProtocol._onMessageFrameData  s    (r8   c                 $    | j                          y r_   )onMessageFrameEndr   s    r7   _onMessageFrameEndz+WebSocketAdapterProtocol._onMessageFrameEnd  s     r8   c                 &    | j                  |       y r_   )onMessageFramer   s     r7   _onMessageFramez(WebSocketAdapterProtocol._onMessageFrame  s    G$r8   c                 $    | j                          y r_   )onMessageEndr   s    r7   _onMessageEndz&WebSocketAdapterProtocol._onMessageEnd  s    r8   c                 (    | j                  ||       y r_   )	onMessage)ra   r   r   s      r7   
_onMessagez#WebSocketAdapterProtocol._onMessage  s    w)r8   c                 &    | j                  |       y r_   )onPingr   s     r7   _onPingz WebSocketAdapterProtocol._onPing      Gr8   c                 &    | j                  |       y r_   )onPongr   s     r7   _onPongz WebSocketAdapterProtocol._onPong  r   r8   c                 *    | j                  |||       y r_   )onClosera   wasCleancoder   s       r7   _onClosez!WebSocketAdapterProtocol._onClose  s    XtV,r8   c                 <    | j                   j                  ||       y)z
        Register a Twisted producer with this protocol.

        :param producer: A Twisted push or pull producer.
        :type producer: object
        :param streaming: Producer type.
        :type streaming: bool
        N)r   registerProducer)ra   producer	streamings      r7   r   z)WebSocketAdapterProtocol.registerProducer  s     	'')<r8   c                 8    | j                   j                          y)zA
        Unregister Twisted producer with this protocol.
        N)r   unregisterProducerr   s    r7   r   z+WebSocketAdapterProtocol.unregisterProducer  s     	))+r8   )F)!rx   ry   rz   r{   txaiomake_loggerr   r}   r   r;   __annotations__r~   boolr   r   r    r   bytesr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rs   r8   r7   r&   r&      s    : %


CD(3- $Ix~$
@ 0> 6W 6p	! 	!,&))!%*-	=,r8   r&   c                   6    e Zd ZdZ ej
                         ZdZy)r*   z
    Base class for Twisted-based WebSocket server protocols.

    Implements :class:`autobahn.websocket.interfaces.IWebSocketChannel`.
    TN)rx   ry   rz   r{   r   r   r   r~   rs   r8   r7   r*   r*     s     %


CIr8   r*   c                   H    e Zd ZdZ ej
                         ZdZdefdZ	d Z
y)r(   z
    Base class for Twisted-based WebSocket client protocols.

    Implements :class:`autobahn.websocket.interfaces.IWebSocketChannel`.
    Fresponsec                     | j                   j                  dt        | j                        |       | j	                  |      S )Nz{meth}(response={response}))methr   )r   r   r   
_onConnect	onConnect)ra   r   s     r7   r   z"WebSocketClientProtocol._onConnect  s:    )( 	 	

 ~~h''r8   c                     | j                   j                  d       | j                  j                  | j                  j
                         y )NzStarting TLS upgrade)r   r   r   startTLSrY   rV   r   s    r7   r   z WebSocketClientProtocol.startTLS  s/    -. ; ;<r8   N)rx   ry   rz   r{   r   r   r   r~   r   r   r   rs   r8   r7   r(   r(     s0     %


CI(#5 (=r8   r(   c                       e Zd ZdZy)r%   zP
    Adapter class for Twisted-based WebSocket client and server factories.
    Nrx   ry   rz   r{   rs   r8   r7   r%   r%     s    r8   r%   c                   8    e Zd ZdZ ej
                         Zd Zy)r)   z
    Base class for Twisted-based WebSocket server factories.

    Implements :class:`autobahn.websocket.interfaces.IWebSocketServerChannelFactory`
    c                     |j                  dd      }|ddlm} || _        t        j                  j
                  | g|i | y)a  

        .. note::
            In addition to all arguments to the constructor of
            :meth:`autobahn.websocket.interfaces.IWebSocketServerChannelFactory`,
            you can supply a ``reactor`` keyword argument to specify the
            Twisted reactor to be used.
        r6   Nr   r5   )poprT   r6   r   r)   rb   )ra   argskwargsr6   s       r7   rb   zWebSocketServerFactory.__init__  sA     **Y-?0''00GGGr8   Nrx   ry   rz   r{   r   r   r   rb   rs   r8   r7   r)   r)     s     %


CHr8   r)   c                   8    e Zd ZdZ ej
                         Zd Zy)r'   z
    Base class for Twisted-based WebSocket client factories.

    Implements :class:`autobahn.websocket.interfaces.IWebSocketClientChannelFactory`
    c                    |j                  dd      }|ddlm} || _        t        j                  j
                  | g|i | | j                  r4| j                  'ddlm} |j                  | j                        | _        yyy)a  

        .. note::
            In addition to all arguments to the constructor of
            :func:`autobahn.websocket.interfaces.IWebSocketClientChannelFactory`,
            you can supply a ``reactor`` keyword argument to specify the
            Twisted reactor to be used.
        r6   Nr   r5   rO   )r   rT   r6   r   r'   rb   rS   rG   rP   rU   rQ   rV   )ra   r   r   r6   rP   s        r7   rb   zWebSocketClientFactory.__init__  sv     **Y-?0''00GGG ==TZZ3 -"%"9"9$))"DD 4=r8   Nr   rs   r8   r7   r'   r'     s     %


CEr8   r'   c                   F    e Zd ZdZd Zd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zy)r+   a  
    An adapter for stream-based transport over WebSocket.

    This follows `websockify <https://github.com/kanaka/websockify>`_
    and should be compatible with that.

    It uses WebSocket subprotocol negotiation and supports the
    following WebSocket subprotocols:

      - ``binary`` (or a compatible subprotocol)
      - ``base64``

    Octets are either transmitted as the payload of WebSocket binary
    messages when using the ``binary`` subprotocol (or an alternative
    binary compatible subprotocol), or encoded with Base64 and then
    transmitted as the payload of WebSocket text messages when using
    the ``base64`` subprotocol.
    c                 P   t        |t              rv|}|j                  D ](  }|| j                  j                  v s|dk7  | _        |c S  t        t        j                  dj                  | j                  j                              t        |t              r|}|j                  | j                  j                  vrM| j                  t        j                  j                  dj                  | j                  j                               |j                  dk7  | _        y t        d      )Nbase64z2this server only speaks {0} WebSocket subprotocolsz2this client only speaks {0} WebSocket subprotocolszlogic error)r:   r   rD   rY   _subprotocols_binaryModer   NOT_ACCEPTABLEr=   r   r   _fail_connectionWebSocketProtocol CLOSE_STATUS_CODE_PROTOCOL_ERROR	Exception)ra   requestOrResponserequestpr   s        r7   r   z"WrappingWebSocketAdapter.onConnectG  s   '):;'G&& 222'(H}D$H !--DKKLL..  )+=>(H  (B(BB%%..OOHOO22  (00H<D M**r8   c                 8    | j                   j                          y r_   )_protor   r   s    r7   r   zWrappingWebSocketAdapter.onOpenc  s    ""$r8   c                 h   || j                   k7  r+| j                  t        j                  j                  d       y |s	 t        |      }| j                  j                  |       y # t        $ rC}| j                  t        j                  j                  dj                  |             Y d }~cd }~ww xY w)Nz>message payload type does not match the negotiated subprotocolz*message payload base64 decoding error: {0})r   r   r   r   "CLOSE_STATUS_CODE_UNSUPPORTED_DATAr   r   !CLOSE_STATUS_CODE_INVALID_PAYLOADr=   r   r   )ra   r   r   es       r7   r   z"WrappingWebSocketAdapter.onMessagef  s    t'''!!**MMP
 '0G KK$$W- ! )) 22TTDKKAN s   A% %	B1.9B,,B1c                 :    | j                   j                  d        y r_   )r   r   r   s       r7   r   z WrappingWebSocketAdapter.onClosex  s    ""4(r8   c                     t        |      t        k(  sJ | j                  r| j                  |d       y t	        |      }| j                  |d       y )NT)r   F)r>   r   r   sendMessager   r   s     r7   writezWrappingWebSocketAdapter.write{  sL    DzU"""TD1T?DTE2r8   c                 4    |D ]  }| j                  |        y r_   )r  )ra   r   ds      r7   writeSequencez&WrappingWebSocketAdapter.writeSequence  s     	AJJqM	r8   c                 $    | j                          y r_   )	sendCloser   s    r7   r   z'WrappingWebSocketAdapter.loseConnection  s    r8   c                 6    | j                   j                         S r_   )r   getPeerr   s    r7   r	  z WrappingWebSocketAdapter.getPeer      ~~%%''r8   c                 6    | j                   j                         S r_   )r   getHostr   s    r7   r  z WrappingWebSocketAdapter.getHost  r
  r8   N)rx   ry   rz   r{   r   r   r   r   r  r  r   r	  r  rs   r8   r7   r+   r+   2  s4    &+8%.$)3
((r8   r+   c                       e Zd ZdZy)r/   zD
    Server protocol for stream-based transport over WebSocket.
    Nr   rs   r8   r7   r/   r/         r8   r/   c                       e Zd ZdZy)r-   zD
    Client protocol for stream-based transport over WebSocket.
    Nr   rs   r8   r7   r-   r-     r  r8   r-   c                   2    e Zd ZdZ	 	 	 	 ddZd Zd Zd Zy)r.   zL
    Wrapping server factory for stream-based transport over WebSocket.
    Nc                    || _         ddg| _        |r| j                  j                  |       t        j	                  | ||| j                         | j                  |       | j                  d       |rd }| j                  |       y	y	)
z

        :param factory: Stream-based factory to be wrapped.
        :type factory: A subclass of ``twisted.internet.protocol.Factory``
        :param url: WebSocket URL of the server this server factory will work for.
        :type url: unicode
        binaryr   rd   r6   rD   autoFragmentSizeF
failByDropc                 L    | D ]  }t        |t              st        |      c S  y r_   )r:   r   r   )offersoffers     r7   acceptz7WrappingWebSocketServerFactory.__init__.<locals>.accept  s)    # CE!%)?@;EBBCr8   perMessageCompressionAcceptN)_factoryr   appendr)   rb   setProtocolOptions)ra   rY   rd   r6   enableCompressionr  subprotocolr  s           r7   rb   z'WrappingWebSocketServerFactory.__init__  s       &1%%k2''c7d6H6H 	( 	
 	1AB 	51C
 ###G r8   c                     t               }| |_        | j                  j                  |      |_        ||j                  _        |S r_   )r/   rY   r  buildProtocolr   r   ra   addrrn   s      r7   r$  z,WrappingWebSocketServerFactory.buildProtocol  8    /1}}2248!&r8   c                 b    | j                   j                          t        j                  |        y r_   )r  startFactoryr)   r   s    r7   r)  z+WrappingWebSocketServerFactory.startFactory  s     ""$++D1r8   c                 b    | j                   j                          t        j                  |        y r_   )r  stopFactoryr)   r   s    r7   r+  z*WrappingWebSocketServerFactory.stopFactory  s     !!#**40r8   NTr   N)rx   ry   rz   r{   rb   r$  r)  r+  rs   r8   r7   r.   r.     s+     )HV21r8   r.   c                   &    e Zd ZdZ	 	 	 	 ddZd Zy)r,   zL
    Wrapping client factory for stream-based transport over WebSocket.
    Nc                 V   || _         ddg| _        |r| j                  j                  |       t        j	                  | ||| j                         | j                  |       | j                  d       |r3t               g}| j                  |       d }| j                  |	       y
y
)a  

        :param factory: Stream-based factory to be wrapped.
        :type factory: A subclass of ``twisted.internet.protocol.Factory``
        :param url: WebSocket URL of the server this client factory will connect to.
        :type url: unicode
        r  r   r  r  Fr  )perMessageCompressionOffersc                 :    t        | t              rt        |       S y r_   )r:   r   r   )r   s    r7   r  z7WrappingWebSocketClientFactory.__init__.<locals>.accept  s    h(AB:8DD Cr8   r  N)r  r   r  r'   rb   r   r   )	ra   rY   rd   r6   r!  r  r"  r  r  s	            r7   rb   z'WrappingWebSocketClientFactory.__init__  s       &1%%k2''c7d6H6H 	( 	
 	1AB 	51 -./F###GE ###G r8   c                     t               }| |_        | j                  j                  |      |_        ||j                  _        |S r_   )r-   rY   r  r$  r   r   r%  s      r7   r$  z,WrappingWebSocketClientFactory.buildProtocol  r'  r8   r,  )rx   ry   rz   r{   rb   r$  rs   r8   r7   r,   r,     s!     ,H\r8   r,   c                    t        | d      r| j                  }nddlm} | j                  r|ddlm} |j                         }| j                  8|| _        |j                  | j                  d   | j                  d   | ||      }|S | j                  r,|j                  | j                  | j                  | |||      }|S |j                  | j                  | j                  | ||      }|S )a  
    Establish WebSocket connection to a server. The connection parameters like target
    host, port, resource and others are provided via the factory.

    :param factory: The WebSocket protocol factory to be used for creating client protocol instances.
    :type factory: An :class:`autobahn.websocket.WebSocketClientFactory` instance.

    :param contextFactory: SSL context factory, required for secure WebSocket connections ("wss").
    :type contextFactory: A `twisted.internet.ssl.ClientContextFactory <http://twistedmatrix.com/documents/current/api/twisted.internet.ssl.ClientContextFactory.html>`_ instance.

    :param timeout: Number of seconds to wait before assuming the connection has failed.
    :type timeout: int

    :param bindAddress: A (host, port) tuple of local address to bind to, or None.
    :type bindAddress: tuple

    :returns: The connector.
    :rtype: An object which implements `twisted.interface.IConnector <http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IConnector.html>`_.
    r6   r   r5   rO   rQ   rR   )r   r6   rT   rS   rP   ClientContextFactoryrG   rV   
connectTCP
connectSSLrQ   rR   )rY   rV   timeoutbindAddressr6   rP   conns          r7   r0   r0   !  s    , w	"//,!, 557N}} !/!!MM&!7==#8'7K
" K %%D K %%gllGWkD Kr8   c                     t        | d      r| j                  }nddlm} | j                  r.|t	        d      |j                  | j                  | |||      }|S |j                  | j                  | ||      }|S )a  
    Listen for incoming WebSocket connections from clients. The connection parameters like
    listening port and others are provided via the factory.

    :param factory: The WebSocket protocol factory to be used for creating server protocol instances.
    :type factory: An :class:`autobahn.websocket.WebSocketServerFactory` instance.

    :param contextFactory: SSL context factory, required for secure WebSocket connections ("wss").
    :type contextFactory: A twisted.internet.ssl.ContextFactory.

    :param backlog: Size of the listen queue.
    :type backlog: int

    :param interface: The interface (derived from hostname given) to bind to, defaults to '' (all).
    :type interface: str

    :returns: The listening port.
    :rtype: An object that implements `twisted.interface.IListeningPort <http://twistedmatrix.com/documents/current/api/twisted.internet.interfaces.IListeningPort.html>`_.
    r6   r   r5   zCSecure WebSocket listen requested, but no SSL context factory given)r   r6   rT   rS   r   	listenSSLrR   	listenTCP)rY   rV   backlog	interfacer6   listeners         r7   r2   r2   Y  s    , w	"//,!U  $$LL'>7I

 O $$W\\7GYOOr8   c                       e Zd ZdZy)r$   z
    Twisted-based WAMP-over-WebSocket server protocol.

    Implements:

    * :class:`autobahn.wamp.interfaces.ITransport`
    Nr   rs   r8   r7   r$   r$         r8   r$   c                       e Zd ZdZeZd Zy)r#   zD
    Twisted-based WAMP-over-WebSocket server protocol factory.
    c                     |j                  dd      }t        j                  j                  | ||       | j                  |d<   t        j                  | g|i | y)a  

        :param factory: A callable that produces instances that implement
            :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable

        :param serializers: A list of WAMP serializers to use (or ``None``
            for all available serializers).
        :type serializers: list of objects implementing
            :class:`autobahn.wamp.interfaces.ISerializer`
        serializersNrD   )r   r   r#   rb   
_protocolsr)   ra   rY   r   r   rC  s        r7   rb   z#WampWebSocketServerFactory.__init__  sT     jj5,,55dG[Q"oo{ 	''>t>v>r8   N)rx   ry   rz   r{   r$   r   rb   rs   r8   r7   r#   r#     s     +H?r8   r#   c                       e Zd ZdZy)r"   z
    Twisted-based WAMP-over-WebSocket client protocol.

    Implements:

    * :class:`autobahn.wamp.interfaces.ITransport`
    Nr   rs   r8   r7   r"   r"     r@  r8   r"   c                       e Zd ZdZeZd Zy)r!   zD
    Twisted-based WAMP-over-WebSocket client protocol factory.
    c                     |j                  dd      }t        j                  j                  | ||       | j                  |d<   t        j                  | g|i | d| _        y)a  

        :param factory: A callable that produces instances that implement
            :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable

        :param serializer: The WAMP serializer to use (or ``None`` for
           "best" serializer, chosen as the first serializer available from
           this list: CBOR, MessagePack, UBJSON, JSON).
        :type serializer: object implementing :class:`autobahn.wamp.interfaces.ISerializer`
        rC  NrD   F)r   r   r!   rb   rD  r'   noisyrE  s        r7   rb   z#WampWebSocketClientFactory.__init__  s[     jj5,,55dG[Q"oo{''>t>v> 
r8   N)rx   ry   rz   r{   r"   r   rb   rs   r8   r7   r!   r!     s     +Hr8   r!   )N   N)N2    )Nr   r   r   typingr   r   zope.interfacer   use_twistedtwisted.internet.protocoltwistedautobahn.twisted.utilr   r   autobahn.utilr	   r
   r   r   r   autobahn.wampr   autobahn.wamp.typesr   autobahn.websocketr   autobahn.websocket.compressr   r   r   r   autobahn.websocket.interfacesr   autobahn.websocket.typesr   r   r   rT   r   twisted.internet.deferr   twisted.internet.errorr   r   r   twisted.internet.interfacesr   r   twisted.python.failurer    __all__r1   rA   rM   r\   r4   internetProtocolr&   r*   r(   objectr%   r)   ServerFactoryr'   ClientFactoryr+   r/   r-   r.   r,   r0   r2   r$   r#   r"   r!   rs   r8   r7   <module>rd     s  6 (   &       P Q Q # 0 '  @ 
 ' + T T 2 4 *,1*P*(V7#8 7tG,w//88AA G,T 
h>>
 
  =h>>= =2f  H##++H H> %E##++%E %E\ Z`(v `( `(F55=1%; =1@8%; 8v 4 4n $ $N 	))+B	 	 ?((*@? ?@ 	))+B	 	 ((*@ r8   