
    h<                    ^   d dl mZ d dlZd dlZd dlZd dlmZ d dlmZm	Z	m
Z
mZ d dlmZ d dlZd dlZd dlmZ d dlmZ d dlmZ d d	l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#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/m0Z0m1Z1m2Z2m3Z3m4Z4 d dl5m6Z6  G d d      Z7 G d de      Z8y)    )annotationsN)Sequence)AnyLiteralOptionalcast)unquote)Headers)ConnectionClosed)ServerExtensionFactory)ServerPerMessageDeflateFactory)HTTPResponse)WebSocketServerProtocol)Subprotocol)ASGI3ApplicationASGISendEventWebSocketAcceptEventWebSocketCloseEventWebSocketConnectEventWebSocketDisconnectEventWebSocketReceiveEventWebSocketResponseBodyEventWebSocketResponseStartEventWebSocketScopeWebSocketSendEvent)Config)TRACE_LOG_LEVEL)ClientDisconnectedget_client_addrget_local_addrget_path_with_query_stringget_remote_addris_ssl)ServerStatec                  (    e Zd ZdZddZddZddZy)ServerFc                     y N selfwss     QD:\jyotish\venv\Lib\site-packages\uvicorn/protocols/websockets/websockets_impl.pyregisterzServer.register1           c                     y r(   r)   r*   s     r-   
unregisterzServer.unregister4   r/   r0   c                    | j                    S r(   )closingr+   s    r-   
is_servingzServer.is_serving7   s    <<r0   N)r,   r   returnNone)r7   bool)__name__
__module____qualname__r4   r.   r2   r6   r)   r0   r-   r&   r&   .   s    G r0   r&   c                       e Zd ZU ded<   ded<   	 d	 	 	 	 	 	 	 d fdZ	 	 	 	 d fdZd fdZddZdd	Zdd
Z		 	 	 	 	 	 ddZ
ddZddZddZddZddZ xZS )WebSocketProtocolzlist[tuple[str, str]]extra_headersz+logging.Logger | logging.LoggerAdapter[Any]loggerc                   |j                   s|j                          || _        t        t        |j
                        | _        |xs t        j                         | _	        |j                  | _
        || _        |j                  | _        |j                  | _        d | _        d | _        d | _        d | _        |  t        j$                         | _        t        j$                         | _        t        j$                         | _        d | _        d| _        d| _        d | _        t5               | _        g }| j                  j8                  r|j;                  t=                      t>        |   | jB                  | j6                  | j                  jD                  | j                  jF                  | j                  jH                  | j                  jJ                  |tM        jN                  d             d | _(        |jR                  D cg c]'  \  }}|jU                  d      |jU                  d      f) c}}| _+        y c c}}w )NFzuvicorn.error)
ws_handler	ws_servermax_size	max_queueping_intervalping_timeout
extensionsr@   latin-1),loadedloadconfigr   r   
loaded_appappasyncioget_event_looploop	root_path	app_stateconnectionstasks	transportserverclientschemeEventhandshake_started_eventhandshake_completed_eventclosed_eventinitial_responseconnect_sent lost_connection_before_handshakeaccepted_subprotocolr&   rC   ws_per_message_deflateappendr   super__init__rB   ws_max_sizews_max_queuews_ping_intervalws_ping_timeoutlogging	getLoggerserver_headerdefault_headersdecoder?   )	r+   rL   server_staterS   _looprH   namevalue	__class__s	           r-   re   zWebSocketProtocol.__init__?   s    }}KKM(&*;*;<5W335	))" (33!''
 -1.2.2,0 	'.}}$)0&#MMO59!05-8<!!'35
;;--<>?nn[[,,kk..++6644!$$_5 	 		
 "Q]QmQm
Qm+$T[[#U\\)%<=Qm
 
s   ,H:c                   | j                   j                  |        || _        t        |      | _        t        |      | _        t        |      rdnd| _        | j                  j                  t              r>| j                  rd| j                  z  nd}| j                  j                  t        d|       t        | 9  |       y )Nwssr,   %s:%d -  z%sWebSocket connection made)rT   addrV   r    rW   r"   rX   r#   rY   r@   isEnabledForr   logrd   connection_made)r+   rV   prefixrs   s      r-   r{   z!WebSocketProtocol.connection_madex   s     	T""$Y/%i0%i0ed;;##O415Z$++-"FKKOOO-JFS	*r0   c                   | j                   j                  |        | j                  j                  t              r>| j
                  rd| j
                  z  nd}| j                  j                  t        d|       | j                  j                          | _	        | j                  j                          t        | 1  |       || j                  j                          y y )Nrv   rw   z%sWebSocket connection lost)rT   remover@   ry   r   rX   rz   r\   is_setr`   setrd   connection_lostrV   close)r+   excr|   rs   s      r-   r   z!WebSocketProtocol.connection_lost   s    %;;##O415Z$++-"FKKOOO-JFS484R4R4Y4Y4[0[-&&**,$;NN  " r0   c                    d| j                   _        | j                  j                         r| j	                  d       n| j                          | j                  j                          y )NT  )rC   r4   r\   r   fail_connectionsend_500_responserV   r   r5   s    r-   shutdownzWebSocketProtocol.shutdown   sJ    !%))002  &""$r0   c                :    | j                   j                  |       y r(   )rU   discard)r+   tasks     r-   on_task_completez"WebSocketProtocol.on_task_complete   s    

4 r0   c                t  K   |j                  d      \  }}}t        j                  j                  j	                  |       g }|j                  d      D ]>  }|j                  |j                  d      D cg c]  }|j                          c}       @ |j                         D 	
cg c])  \  }	}
|	j                  d      |
j                  dd      f+ }}	}
t        |      }| j                  |z   }| j                  j                  d      |j                  d      z   }d| j                  j                  dd	d
| j                  | j                   | j"                  | j                  |||j                  d      ||| j$                  j'                         di id| _        | j*                  j-                  | j/                               }|j1                  | j2                         | j4                  j7                  |       | j8                  j;                          d{    | j<                  S c c}w c c}
}	w 7 w)a(  
        This hook is called to determine if the websocket should return
        an HTTP response and close.

        Our behavior here is to start the ASGI application, and then wait
        for either `accept` or `close` in order to determine if we should
        close the connection.
        ?zSec-WebSocket-Protocol,asciisurrogateescape)errors	websocketz2.4)versionspec_versionz1.1zwebsocket.http.response)typeasgihttp_versionrY   rW   rX   rR   pathraw_pathquery_stringheaderssubprotocolsstaterH   N)	partition
websocketslegacy	handshakecheck_requestget_allextendsplitstrip	raw_itemsencoder	   rR   rL   asgi_versionrY   rW   rX   rS   copyscoperQ   create_taskrun_asgiadd_done_callbackr   rU   rx   r[   waitr^   )r+   r   request_headerspath_portion_r   r   headertokenrq   rr   asgi_headers	full_pathfull_raw_pathr   s                  r-   process_requestz!WebSocketProtocol.process_request   s     )-s(;%a##11/B"$%--.FGFFLL<M N<M5<M NO H
  /88:
:e [[!5<<@Q<#RS: 	 
 |$NNT)	--g69L9LW9UU   $ 8 8%P!kkkkkk%(//8#(^^((*4b9

  yy$$T]]_5t445

t**//111$$$= !O
6 	2s+   A3H85H+
H8(.H0EH8H6H8c                    | j                   S )z
        We override the standard 'process_subprotocol' behavior here so that
        we return whatever subprotocol is sent in the 'accept' message.
        )ra   )r+   r   available_subprotocolss      r-   process_subprotocolz%WebSocketProtocol.process_subprotocol   s     (((r0   c                    d}ddt        t        |            j                  d      z   dz   dd|g}| j                  j	                  dj                  |             | j                  j                          y )Ns   Internal Server ErrorsM   HTTP/1.1 500 Internal Server Error
content-type: text/plain; charset=utf-8
s   content-length: r   s   
s   connection: close
r0   )strlenr   rV   writejoinr[   r   )r+   msgcontents      r-   r   z#WebSocketProtocol.send_500_response   sk    &`#c#h-"6"6w"??'I$
 	SXXg./ 	$$((*r0   c                t   K   | j                   j                          | j                          d{    y7 w)z
        This is the main handler function for the 'websockets' implementation
        to call into. We just wait for close then return, and instead allow
        'send' and 'receive' events to drive the flow.
        N)r\   r   wait_closed)r+   protocolr   s      r-   rB   zWebSocketProtocol.ws_handler   s,      	&&**,   s   .868c                  K   	 | j                  | j                  | j                  | j                         d{   }| j                  j                          | j                  j                         sF| j                  j                  d       | j                          | j                  j                          y|Y| j                  j                  d|       | j                  j                          d{    | j                  j                          yy7 7 "# t        $ r7 | j                  j                          | j                  j                          Y yt         $ r | j                  j                          | j                  j#                  d       | j                  j                         s| j                          n#| j                  j                          d{  7   | j                  j                          Y yw xY ww)zr
        Wrapper around the ASGI callable, handling exceptions and unexpected
        termination states.
        Nz1ASGI callable returned without sending handshake.z4ASGI callable should return None, but returned '%s'.zException in ASGI application
)rN   r   asgi_receive	asgi_sendr]   r   r[   r   r@   errorr   rV   r   r\   r   r   BaseException	exception)r+   results     r-   r   zWebSocketProtocol.run_asgi   s}    
	'88DJJ0A0A4>>RRF !!#//668!!"UV&&($$&#!!"XZ`a4499;;;$$& $% S( <' " 	#!!#NN  " 	#!!#KK!!"CD//668&&(4499;;;NN  "	#sc   H4D DD B5H2D3 HD H=G>HBG>GG>;H=G>>Hc                  K   |d   }| j                   j                         s^|dk(  rt        d|      }| j                  j	                  dt        | j                        t        | j                               d | _        t        t        t           |j                  d            | _        d|v r%| j                  j                  d |d   D               | j                   j                          y |dk(  rt        d	|      }| j                  j	                  d
t        | j                        t        | j                               t         j"                  j$                  g df| _        | j                   j                          | j&                  j                          y |dk(  rt        d|      }| j                  j	                  dt        | j                        t        | j                        |d          t!        j"                  |d         }|j                  dg       D cg c]'  \  }}|j)                  d      |j)                  d      f) }}}||df| _        | j                   j                          y d}t+        ||z        | j&                  j                         s| j                  | j,                  j/                          d {    	 |dk(  rNt        d|      }|j                  d      }|j                  d      }	||	n|}
| j1                  |
       d {    n|dk(  rit        d	|      }|j                  dd      }|j                  dd      xs d}| j3                  ||       d {    | j&                  j                          nd}t+        ||z        y y | j                  ||dk(  rft        d|      }| j                  d   |d   z   }| j                  d d |fz   | _        |j                  dd       s+| j&                  j                          y d!}t+        ||z        y d"}t+        ||z        c c}}w 7 w7 '7 # t4        $ r}t6        |d }~ww xY ww)#Nr   zwebsocket.acceptr   z%s - "WebSocket %s" [accepted]subprotocolr   c              3  f   K   | ])  \  }}|j                  d       |j                  d       f + yw)rI   N)rn   ).0rq   rr   s      r-   	<genexpr>z.WebSocketProtocol.asgi_send.<locals>.<genexpr>  s5      . ,>KD% Y/i1HI+=s   /1zwebsocket.closer   z%s - "WebSocket %s" 403r0   zwebsocket.http.response.startr   z%s - "WebSocket %s" %dstatusrI   zmExpected ASGI message 'websocket.accept', 'websocket.close', or 'websocket.http.response.start' but got '%s'.zwebsocket.sendr   bytestextcodei  reasonrw   zJExpected ASGI message 'websocket.send' or 'websocket.close', but got '%s'.zwebsocket.http.response.bodyr      body	more_bodyFzBExpected ASGI message 'websocket.http.response.body' but got '%s'.z\Unexpected ASGI message '%s', after sending 'websocket.close' or response already completed.)r[   r   r   r@   infor   r   r!   r^   r   r   getra   r?   r   r   http
HTTPStatus	FORBIDDENr]   rn   RuntimeErrorr\   r   sendr   r   r   )r+   messagemessage_typer   rq   rr   r   r   
bytes_data	text_datadatar   r   r   r   s                  r-   r   zWebSocketProtocol.asgi_send  s!    v++224115w?  4#DJJ/.tzz:
 )-%,0+1FTaHb,c)'&&-- . ,39+=	.  ,,002!224g>  -#DJJ/.tzz:
 *.)B)BB(L%,,002!!%%'!@@<gF  ,#DJJ/.tzz:H%	 ):;Y`YdYdenprYsYs+$PUT[[+U\\)-DEYs   *0#(>%,,002G  #3#566""))+0E0E0M00557772#33"#7AG!(W!5J 'F 3I(2(:9
D))D/))!%66"#8'BG";;vt4D$[[26<"F**T6222%%))+ gC&s\'9::	 , * "".==;WE,,Q/'&/A(,(=(=bq(ATG(K%{{;6%%))+Z"3#566	 7 qCs\122e 8 * 3 $ 2(c12sj   HQ,P6	A<QP<QAQ P?AQ ,Q-/Q B!Q?Q Q 	QQQQc                  K   | j                   sd| _         ddiS | j                  j                          d {    | j                  rdddS | j                  j                         rdddS 	 | j                          d {   }t        |t              rd
|dS d
|dS 7 g7  # t        $ rX | j                  j                          | j                  j                  rdddcY S d| j                  xs d| j                  d	cY S w xY ww)NTr   zwebsocket.connectzwebsocket.disconnecti  )r   r   i  r   )r   r   r   zwebsocket.receive)r   r   )r   r   )r_   r\   r   r`   r]   r   recvr   r   rC   r4   
close_codeclose_reason
isinstancer   )r+   r   s     r-   r   zWebSocketProtocol.asgi_receivej  s       $D/00,,1133300 3DAA##%2DAA	r$D dC />>+d;;) 	4 % 	r!!#~~%% 6EE2DOO<St_c_p_pqq		rsQ   5DB4D-B#  B!B# D!B# #>D!D#DDDDr(   )rL   r   ro   r$   rS   zdict[str, Any]rp   z asyncio.AbstractEventLoop | None)rV   zasyncio.Transportr7   r8   )r   zException | Noner7   r8   )r7   r8   )r   zasyncio.Task[None]r7   r8   )r   r   r   r
   r7   zHTTPResponse | None)r   r
   r   zSequence[Subprotocol] | Noner7   zSubprotocol | None)r   r   r   r   r7   r   )r   r   r7   r8   )r7   zHWebSocketDisconnectEvent | WebSocketConnectEvent | WebSocketReceiveEvent)r:   r;   r<   __annotations__re   r{   r   r   r   r   r   r   rB   r   r   r   __classcell__)rs   s   @r-   r>   r>   ;   s    ((77 377
7
 "7
 "	7

 07
r+*+	+#!-%^))8T)	)+!':]3~<r0   r>   )9
__future__r   rO   r   rj   collections.abcr   typingr   r   r   r   urllib.parser	   r   websockets.legacy.handshakewebsockets.datastructuresr
   websockets.exceptionsr   websockets.extensions.baser   (websockets.extensions.permessage_deflater   websockets.legacy.serverr   websockets.serverr   websockets.typingr   uvicorn._typesr   r   r   r   r   r   r   r   r   r   r   uvicorn.configr   uvicorn.loggingr   uvicorn.protocols.utilsr   r   r    r!   r"   r#   uvicorn.serverr$   r&   r>   r)   r0   r-   <module>r      s|    "    $ / /    " - 2 = S 1 5 )    " +  '
  
 H</ H<r0   