
    2BfW                         d dl Z d dlZd dl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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  G d d      Z G d de      Z G d de      Zy)    N)time)urlsplit)ConnectionTypeWSConnection)	AcceptConnectionRejectConnectionCloseConnectionMessageRequestPingPongTextMessageBytesMessage)PerMessageDeflate)CloseReason)LocalProtocolError   )ConnectionErrorConnectionClosedc                   H    e Zd Z	 	 	 d
dZd Zd ZddZddZd Zd Z	d	 Z
y)BaseNc	                    d | _         || _        || _        || _        || _        d| _        g | _        d | _        d| _        d| _	        |t        j                  k(  | _        t        j                  | _        d | _        |dd l}	|	j$                  }|dd l}	|	j&                  }|t(        j*                  }|| _         |       | _        t1        |      | _        | j5                          | j                  s
t7                || j8                        | _        | j:                  j<                  j?                  dd      | j:                  _        | j:                  jA                          y )NTr   F)targetz	(_thread)z(simple_websocket.Base._thread))!subprotocolsockreceive_bytesping_intervalmax_message_sizepong_receivedinput_bufferincoming_messageincoming_message_len	connectedr   SERVER	is_serverr   NO_STATUS_RCVDclose_reasonclose_message	threadingThreadEvent	selectorsDefaultSelectorselector_classeventr   ws	handshaker   _threadthreadnamereplacestart)
selfr   connection_typer   r   r   thread_classevent_classr.   r)   s
             S/var/www/highfloat_scraper/venv/lib/python3.12/site-packages/simple_websocket/ws.py__init__zBase.__init__   s/     	** 0! $$%!)^-B-BB'66!$++L#//K!&66N, ]
/~~!##"$,,7;;++33:<    c                      y N )r7   s    r;   r1   zBase.handshakeB   s    r=   c                 Z   | j                   s t        | j                  | j                        t	        |t
              r&| j                  j                  t        |            }n.| j                  j                  t        t        |                  }| j                  j                  |       y)zSend data over the WebSocket connection.

        :param data: The data to send. If ``data`` is of type ``bytes``, then
                     a binary message is sent. Else, the message is sent in
                     text format.
        )dataN)r#   r   r'   r(   
isinstancebytesr0   sendr
   r   strr   )r7   rB   out_datas      r;   rE   z	Base.sendF   sp     ~~"4#4#4d6H6HIIdE"ww||G$67Hww||KSY$?@H		x r=   c                    | j                   r\| j                  sP| j                  j                  |      sy| j                  j	                          | j                   r| j                  sP	 | j                  j                  d      S # t        $ r Y nw xY w| j                   s t        | j                  | j                        y)a}  Receive data over the WebSocket connection.

        :param timeout: Amount of time to wait for the data, in seconds. Set
                        to ``None`` (the default) to wait indefinitely. Set
                        to 0 to read without blocking.

        The data received is returned, as ``bytes`` or ``str``, depending on
        the type of the incoming message.
        )timeoutNr   )
r#   r    r/   waitclearpop
IndexErrorr   r'   r(   )r7   rI   s     r;   receivezBase.receiveU   s     nnT%6%6::??7?3JJ nnT%6%6	$$((++ 		~~"4#4#4d6H6HII s   *B 	BBc                 <   | j                   s t        | j                  | j                        | j                  j                  t        |xs t        j                  |            }	 | j                  j                  |       d| _         y# t        $ r
 Y d| _         yw xY w)a@  Close the WebSocket connection.

        :param reason: A numeric status code indicating the reason of the
                       closure, as defined by the WebSocket specification. The
                       default is 1000 (normal closure).
        :param message: A text message to be sent to the other side.
        FN)r#   r   r'   r(   r0   rE   r	   r   NORMAL_CLOSUREr   BrokenPipeError)r7   reasonmessagerG   s       r;   closez
Base.closej   s     ~~"4#4#4d6H6HII77<<0k00'!; <	IINN8$   		s   %B 	BBc                      y r?   r@   )r7   requests     r;   choose_subprotocolzBase.choose_subprotocol|   s     r=   c                    d }| j                   rRt               | j                   z   }| j                         }|j                  | j                  t
        j                  d       | j                  r,	 |rt               }|k  s|j                  ||z
        s| j                  s"| j                  t        j                  d       nd| _	        | j                  j                  | j                  j                  t                            t!        ||      | j                   z   }| j                  j#                  | j$                        }t'        |      dk(  r
t)               | j                  j+                  |       | j-                         | _        | j                  r,|r|j                         nd  | j                  j                          y # t(        t.        f$ r$ d| _        | j0                  j3                          Y aw xY w)NTzPing/Pong timeoutrR   rS   Fr   )r   r   r.   registerr   r,   
EVENT_READr#   selectr   rT   r   POLICY_VIOLATIONrE   r0   r   maxrecvr   lenOSErrorreceive_data_handle_eventsConnectionResetErrorr/   set)r7   sel	next_pingnowin_datas        r;   r2   zBase._thread   s   !3!33I%%'CLLI$8$8$?nn&C C'szz)c//J#11 JJk.J.J/B ' D!-2*		tww||DF';<$'Y$7$:L:L$L	 ))..););<w<1$!)O$$W-!%!4!4!6% nn. 				 12 !&

 s!   /AG	 AG	 A-G	 	0G<;G<c           	         d}d}| j                   j                         D ]  }	 t        |t              rT| j	                  |      | _        || j                   j                  t        | j
                  t               g            z  }nt        |t              r| j                  r,|| j                   j                  |j                               z  }|j                  | _        |j                  | _        d| _        | j"                  j%                          d}nt        |t&              r.|| j                   j                  |j                               z  }nt        |t(              r	d| _        nt        |t,        t.        f      r| xj0                  t3        |j4                        z  c_        | j6                  rn| j0                  | j6                  kD  rU|| j                   j                  t        t8        j:                  d            z  }| j"                  j%                          d} n | j<                  |j4                  | _        nt        |t,              r~t        | j<                  t>              s6t?        | j<                  |j4                  z   jA                               | _        n| xj<                  |j4                  jA                         z  c_        nat        | j<                  t>              s(t?        | j<                  |j4                  z         | _        n| xj<                  |j4                  z  c_        |jB                  s#t        | j<                  tD        tF        f      r&| jH                  jK                  | j<                         nrt        |t,              r4| jH                  jK                  | j<                  jM                                n.| jH                  jK                  tG        | j<                               d | _        d| _        | j"                  j%                          n	  |r| jP                  j                  |       |S # tN        $ r" d}| j"                  j%                          d}Y Qw xY w)NTr=   )r   
extensionsFzMessage is too bigr   ))r0   eventsrC   r   rW   r   rE   r   r   r	   r%   responsecoder'   rR   r(   r#   r/   re   r   r   r   r   r   r"   r`   rB   r   r   MESSAGE_TOO_BIGr!   	bytearrayencodemessage_finishedrF   rD   r    appenddecoder   r   )r7   
keep_goingrG   r/   s       r;   rc   zBase._handle_events   s\   
WW^^% G	#EF#eW-'+'>'>u'ED$-=$($4$4$5$7#8.: !; ;H  7~~ DGGLL1A$BB(-

D%).D&%*DNJJNN$!&Jt,U^^-= >>Ht,)-D&\'BC--UZZ@-,, 558M8MM DGGLL'779M2O %P P

(%*
,,4 16

-#E;7)$*?*?K4=!%!6!6!C K K M5OD1 !11UZZ5F5F5HH1)$*?*?K4= $ 5 5

 B5DD1 !11UZZ?1 11 !$"7"7#uF))001F1FG#E;7))00 1188:< ))00t7L7L1MN,0D)01D-JJNN$GG	#P IINN8$ & #

 "
#s    H Q'DQC"Q'Q10Q1NN   NNNNNr?   NN)__name__
__module____qualname__r<   r1   rE   rN   rT   rW   r2   rc   r@   r=   r;   r   r      s7    FJ6:EI&P!J*$BMr=   r   c                   N     e Zd ZdZ	 	 	 d fd	Ze	 	 	 dd       Zd Zd Z xZ	S )ServerzThis class implements a WebSocket server.

    Instead of creating an instance of this class directly, use the
    ``accept()`` class method to create individual instances of the server,
    each bound to a client request.
    c	           
         || _         |xs g | _        t        | j                  t              r| j                  g| _        d| _        d }	d|v r|j                  d      }	d| _        nd|v r|j                  d      }	d| _        nd|v r'|j                  d      j                         }	d| _        n|j                  dd	      j                  d
      rc|d   }
t        |
d      st        |
d      r|
j                  }
t        |
d      r.|
j                  j                  }		 |	j                         }	d
| _        |	t        d      t        | A  |	t"        j$                  ||||||       y # t        $ r Y Ew xY w)Nunknownzwerkzeug.socketwerkzeugzgunicorn.socketgunicornzeventlet.inputeventletSERVER_SOFTWARE geventz
wsgi.inputrawrfilez+Cannot obtain socket from WSGI environment.)r8   r   r   r   r9   r:   r.   )environsubprotocolsrC   rF   modeget
get_socket
startswithhasattrr   r   _sockdupNotImplementedErrorRuntimeErrorsuperr<   r   r$   )r7   r   r   r   r   r   r9   r:   r.   r   
wsgi_input	__class__s              r;   r<   zServer.__init__   st    (.Bd''-!%!2!2 3D	';;01D"DI');;01D"DI(;;/0;;=D"DI[[*B/:: !.J:u-'*g2N'--
z5)!~~++88:D %	<LMM~/D/D'4'4*:&2(6 	 	8 + s   E% %	E10E1c	           
      "     | ||||||||      S )aS	  Accept a WebSocket connection from a client.

        :param environ: A WSGI ``environ`` dictionary with the request details.
                        Among other things, this class expects to find the
                        low-level network socket for the connection somewhere
                        in this dictionary. Since the WSGI specification does
                        not cover where or how to store this socket, each web
                        server does this in its own different way. Werkzeug,
                        Gunicorn, Eventlet and Gevent are the only web servers
                        that are currently supported.
        :param subprotocols: A list of supported subprotocols, or ``None`` (the
                             default) to disable subprotocol negotiation.
        :param receive_bytes: The size of the receive buffer, in bytes. The
                              default is 4096.
        :param ping_interval: Send ping packets to clients at the requested
                              interval in seconds. Set to ``None`` (the
                              default) to disable ping/pong logic. Enable to
                              prevent disconnections when the line is idle for
                              a certain amount of time, or to detect
                              unresponsive clients and disconnect them. A
                              recommended interval is 25 seconds.
        :param max_message_size: The maximum size allowed for a message, in
                                 bytes, or ``None`` for no limit. The default
                                 is ``None``.
        :param thread_class: The ``Thread`` class to use when creating
                             background threads. The default is the
                             ``threading.Thread`` class from the Python
                             standard library.
        :param event_class: The ``Event`` class to use when creating event
                            objects. The default is the `threading.Event``
                            class from the Python standard library.
        :param selector_class: The ``Selector`` class to use when creating
                               selectors. The default is the
                               ``selectors.DefaultSelector`` class from the
                               Python standard library.
        )r   r   r   r   r9   r:   r.   r@   )	clsr   r   r   r   r   r9   r:   r.   s	            r;   acceptzServer.accept%  s&    P 7!.m$4 ,+"0	2 	2r=   c                    d}| j                   j                         D ]o  \  }}|j                  d      sdj                  |dd  j	                  d      D cg c]  }|j                          c}      }|| d| dj                         z  }q |dz  }| j                  j                  |       | j                         | _
        y c c}w )	Ns   GET / HTTP/1.1
HTTP_-   _z: z
s   
)r   itemsr   joinsplit
capitalizerq   r0   rb   rc   r#   )r7   ri   keyvaluepheaders         r;   r1   zServer.handshakeS  s    ',,,,. 	=JC~~g&3qr7==;M"Na1<<>"NOfXRwd3::<<	= 	7W%,,.	 #Os   C
c                 J    |j                   D ]  }|| j                   v s|c S  y)a  Choose a subprotocol to use for the WebSocket connection.

        The default implementation selects the first protocol requested by the
        client that is accepted by the server. Subclasses can override this
        method to implement a different subprotocol negotiation algorithm.

        :param request: A ``Request`` object.

        The method should return the subprotocol to use, or ``None`` if no
        subprotocol is chosen.
        N)r   )r7   rV   r   s      r;   rW   zServer.choose_subprotocol]  s2     #// 	#Kd///""	# r=   )Nrw   NNNNN)
ry   rz   r{   __doc__r<   classmethodr   r1   rW   __classcell__r   s   @r;   r}   r}      sC     BFIM26)8V >BGK04+2 +2Z/r=   r}   c                   T     e Zd ZdZ	 	 	 d fd	Ze	 	 	 dd       Zd Zd fd	Z xZ	S )ClientzThis class implements a WebSocket client.

    Instead of creating an instance of this class directly, use the
    ``connect()`` class method to create an instance that is connected to a
    server.
    c
           	         t        |      }
|
j                  dv }|
j                  | _        |
j                  xs |rdnd| _        |
j
                  | _        |
j                  r"| xj
                  d|
j                  z   z  c_        |xs g | _        t        | j                  t              r| j                  g| _        g | _
        t        |t              r6|j                         D ]"  \  }}| j                  j                  ||f       $ nt        |t              r|| _
        t        j                  t        j                   t        j"                        }|rM|.t%        j&                  t$        j(                  j*                        }|j-                  || j                        }|j/                  | j                  | j                  f       t0        | e  |t4        j6                  |||||	       y )N)httpswssi  P   ?)purpose)server_hostname)r8   r   r   r   r9   r:   )r   schemehostnamehostportpathqueryr   rC   rF   extra_headeersdictr   rs   listsocketAF_INETSOCK_STREAMsslcreate_default_contextPurposeSERVER_AUTHwrap_socketconnectr   r<   r   CLIENT)r7   urlr   headersr   r   r   ssl_contextr9   r:   
parsed_url	is_securer   r   r   r   s                  r;   r<   zClient.__init__v  s    c]
%%)99	''	OOAyb	OO	IIz////I(.Bd''-!%!2!2 3D gt$%mmo 9
U##**C<89&")D}}V^^V-?-?@"!88KK335**4*KDdii+,~/D/D'4'4*:&2	 	 	Mr=   c
                 $     | |||||||||		      S )a_	  Returns a WebSocket client connection.

        :param url: The connection URL. Both ``ws://`` and ``wss://`` URLs are
                    accepted.
        :param subprotocols: The name of the subprotocol to use, or a list of
                             subprotocol names in order of preference. Set to
                             ``None`` (the default) to not use a subprotocol.
        :param headers: A dictionary or list of tuples with additional HTTP
                        headers to send with the connection request. Note that
                        custom headers are not supported by the WebSocket
                        protocol, so the use of this parameter is not
                        recommended.
        :param receive_bytes: The size of the receive buffer, in bytes. The
                              default is 4096.
        :param ping_interval: Send ping packets to the server at the requested
                              interval in seconds. Set to ``None`` (the
                              default) to disable ping/pong logic. Enable to
                              prevent disconnections when the line is idle for
                              a certain amount of time, or to detect an
                              unresponsive server and disconnect. A recommended
                              interval is 25 seconds. In general it is
                              preferred to enable ping/pong on the server, and
                              let the client respond with pong (which it does
                              regardless of this setting).
        :param max_message_size: The maximum size allowed for a message, in
                                 bytes, or ``None`` for no limit. The default
                                 is ``None``.
        :param ssl_context: An ``SSLContext`` instance, if a default SSL
                            context isn't sufficient.
        :param thread_class: The ``Thread`` class to use when creating
                             background threads. The default is the
                             ``threading.Thread`` class from the Python
                             standard library.
        :param event_class: The ``Event`` class to use when creating event
                            objects. The default is the `threading.Event``
                            class from the Python standard library.
        )r   r   r   r   r   r   r9   r:   r@   )
r   r   r   r   r   r   r   r   r9   r:   s
             r;   r   zClient.connect  s)    R 3\7!.m$4+ ,+G 	Gr=   c                 v   | j                   j                  t        | j                  | j                  | j
                  | j                              }| j                  j                  |       	 | j                  j                  | j                        }| j                   j                  |       	 t        | j                   j                               }	 t        |t              rt!        |j"                        t        |t$              st!        d      |j&                  | _        d| _        y # t        $ r Y nw xY w)N)r   r   r   extra_headersTi  )r0   rE   r   r   r   r   r   r   r_   r   rb   nextrl   StopIterationrC   r   r   status_coder   r   r#   )r7   rG   ri   r/   s       r;   r1   zClient.handshake  s    77<<TYYtyy595F5F6:6I6I!K L 			x iinnT%7%78GGG  )TWW^^-. e-.!%"3"344E#34!#&& ,, !  s   .#D+ +	D76D7c                 \    t         |   ||       | j                  j                          y )NrY   )r   rT   r   )r7   rR   rS   r   s      r;   rT   zClient.close  s!    VW5		r=   rv   rx   )
ry   rz   r{   r   r<   r   r   r1   rT   r   r   s   @r;   r   r   o  sI     8<JNBF MD 59IMAE+G +GZ, r=   r   )r,   r   r   r   urllib.parser   wsprotor   r   wsproto.eventsr   r   r	   r
   r   r   r   r   r   wsproto.extensionsr   wsproto.frame_protocolr   wsproto.utilitiesr   errorsr   r   r   r}   r   r@   r=   r;   <module>r      s^      
  ! 0
 
 
 1 . 0 5W WtyT yxoT or=   