
    hJ                        d dl mZmZ d dlmZ d dlmZ d dlZ ej                          d dl	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mZ d dl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+m,Z, d dl-m.Z.m/Z/m0Z0m1Z1 dZ2d Z3d Z4d Z5d Z6 G d de)      Z7 G d de
jp                  jN                  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                  jN                  j                               Z?e G d% d&e>e'j                  e
jp                  jN                  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/ d0eA      ZGed;d1       ZHed<d2       ZIe G d3 d4ej                  e;             ZJe G d5 d6ej                  e?             ZKe G d7 d8ej                  e<             ZLe G d9 d:ej                  eA             ZMy)=    )	b64encode	b64decode)Optional)implementerN)	endpoints)
ITransport)ConnectionDoneConnectionAbortedConnectionLost)Deferred)Failure)connectionDone)publichltypehlval)_is_tls_error_maybe_tls_reason)	websocket)TransportDetails)ConnectionRequestConnectionResponseConnectionDeny)protocol)IWebSocketClientAgent)create_transport_detailstransport_channel_id)PerMessageDeflateOfferPerMessageDeflateOfferAcceptPerMessageDeflateResponsePerMessageDeflateResponseAccept)create_client_agentWebSocketAdapterProtocolWebSocketServerProtocolWebSocketClientProtocolWebSocketAdapterFactoryWebSocketServerFactoryWebSocketClientFactoryWrappingWebSocketAdapterWrappingWebSocketServerProtocolWrappingWebSocketClientProtocolWrappingWebSocketServerFactoryWrappingWebSocketClientFactorylistenWS	connectWSWampWebSocketServerProtocolWampWebSocketServerFactoryWampWebSocketClientProtocolWampWebSocketClientFactoryc                     t        |       S )zB
    :returns: an instance implementing IWebSocketClientAgent
    )_TwistedWebSocketClientAgentreactors    V/var/www/Befach/backend/env/lib/python3.12/site-packages/autobahn/twisted/websocket.pyr!   r!   V   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   ]   sc    
 &,;BB4HXCYZ
 	
 &&w/&&x0D
 	
 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   q   sZ    
 gt$&
 	

J LLN:%077A  #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&!
0 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%( 
 MM
 

 7E6L2R` )AQSZ[
""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    
 #;4>>4>>"Z2B2\2\/ ++00		NN((9 	 	H"4#6#67!$)), 	 	.	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I $		  +I6<<(HHNN,V\\:;&78HHNNJ $		  + n5&,,'Gv||Y/ ,,..HHNNVYY   HHNNT $		d6<<6HPVP\P\  ^ 	V$ HHNNU &t':': ; %dii 0  2 HHNNa &t':': ; %dii 0"(  *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.dataReceivedU  sP    K"4#4#45!$)), %c$i 0 	 	2 	4 r8   c                     |r1t        | j                  d      r| j                  j                          y | j                  j                          y )NabortConnection)r   r   r   loseConnection)ra   aborts     r7   _closeConnectionz)WebSocketAdapterProtocol._closeConnection^  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._onOpene  sS    "",, 24>>4CZCZCdCdfrsJ 2<D##.r8   c                 &    | j                  |       y r_   )onMessageBegin)ra   isBinarys     r7   _onMessageBeginz(WebSocketAdapterProtocol._onMessageBeginp  s    H%r8   c                 &    | j                  |       y r_   )onMessageFrameBegin)ra   lengths     r7   _onMessageFrameBeginz-WebSocketAdapterProtocol._onMessageFrameBegins  s      (r8   c                 &    | j                  |       y r_   )onMessageFrameDatara   payloads     r7   _onMessageFrameDataz,WebSocketAdapterProtocol._onMessageFrameDatav  s    (r8   c                 $    | j                          y r_   )onMessageFrameEndr   s    r7   _onMessageFrameEndz+WebSocketAdapterProtocol._onMessageFrameEndy  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~$.4 0> ,*W ,*\! !,	&))!%*-	=,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  s2    46$//;R]ef~~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%         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.onConnect$  s7   '):;'G&&222()XD$H ' !!>!>@t@{@{  }A  }I  }I  }W  }W  AX  Y  Y)+=>(H  (B(BB%%h&@&@&a&a  dX  d_  d_  `d  `l  `l  `z  `z  d{  | ( 1 1X =D M**r8   c                 8    | j                   j                          y r_   )_protor   r   s    r7   r   zWrappingWebSocketAdapter.onOpen6  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.onMessage9  s    t'''!!("<"<"_"_  bb  c`'0G KK$$W- ! `))(*D*D*f*f  iU  i\  i\  ]^  i_  `  ``s   A% %	B1.9B,,B1c                 :    | j                   j                  d        y r_   )r   r   r   s       r7   r   z WrappingWebSocketAdapter.onCloseE  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.writeH  sL    DzU"#"TD1T?DTE2r8   c                 4    |D ]  }| j                  |        y r_   )r  )ra   r   ds      r7   writeSequencez&WrappingWebSocketAdapter.writeSequenceQ  s    AJJqM r8   c                 $    | j                          y r_   )	sendCloser   s    r7   r   z'WrappingWebSocketAdapter.loseConnectionV  s    r8   c                 6    | j                   j                         S r_   )r   getPeerr   s    r7   r
  z WrappingWebSocketAdapter.getPeerZ      ~~%%''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(     s4    &+$%	.)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)   c  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*   i  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"    #E!%)?@;EBB $r8   perMessageCompressionAcceptN)_factoryr   appendr&   rb   setProtocolOptions)ra   rY   rd   r6   enableCompressionr  subprotocolr  s           r7   rb   z'WrappingWebSocketServerFactory.__init__t  s      &1%%k2'',/07262D2D 	( 	F 	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+   o  s+     #'"#!(HT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'',/07262D2D 	( 	F 	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Z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   r.   r.     s    , w	"//,!, 557N}} !/!!'--"7v9NPWY`bmn K	 %%gllGLL'>[bdopD K %%gllGLL'7T_`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   r-   r-     sz    , w	"//,!abb$$W\\7NGU^_ 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/   8      r8   r/   c                       e Zd ZdZeZd Zy)r0   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   r0   rb   
_protocolsr&   ra   rY   r   r   rC  s        r7   rb   z#WampWebSocketServerFactory.__init__K  sT     jj5,,55dG[Q"oo{ 	''>t>v>r8   N)rx   ry   rz   r{   r/   r   rb   rs   r8   r7   r0   r0   C  s     +H?r8   r0   c                       e Zd ZdZy)r1   z
    Twisted-based WAMP-over-WebSocket client protocol.

    Implements:

    * :class:`autobahn.wamp.interfaces.ITransport`
    Nr   rs   r8   r7   r1   r1   b  r@  r8   r1   c                       e Zd ZdZeZd Zy)r2   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   r2   rb   rD  r'   noisyrE  s        r7   rb   z#WampWebSocketClientFactory.__init__u  s[     jj5,,55dG[Q"oo{''>t>v> 
r8   N)rx   ry   rz   r{   r1   r   rb   rs   r8   r7   r2   r2   m  s     +Hr8   r2   )N   N)N2    )Nr   r   r   typingr   zope.interfacer   r   use_twistedtwisted.internet.protocoltwistedrT   r   twisted.internet.interfacesr   twisted.internet.errorr	   r
   r   twisted.internet.deferr   twisted.python.failurer   r   autobahn.utilr   r   r   r   r   autobahn.wampr   autobahn.wamp.typesr   autobahn.websocket.typesr   r   r   autobahn.websocketr   autobahn.websocket.interfacesr   autobahn.twisted.utilr   r   autobahn.websocket.compressr   r   r   r    __all__r!   rA   rM   r\   r4   internetProtocolr"   r#   r$   objectr%   r&   ServerFactoryr'   ClientFactoryr(   r)   r*   r+   r,   r.   r-   r/   r0   r1   r2   rs   r8   r7   <module>rd     s  6 (  &        & 2  + * 4 / / : # 0 Z Z ' ? P$ $41(2&R4#8 4ns,w//88AA s,l 68X8X   =68X8X = =&f  H4h6U6UW^WgWgWpWpW~W~ H H6  E4h6U6UW^WgWgWpWpW~W~  E  ER ZP(v P( P(f&>@W &>@W <1%; <1~7%; 7t ( (V    F )"G"GI`   ?!E!EG] ? ?< )"G"GI`   !E!EG]  r8   