o
    NK&h66                  
   @  s  d dl mZ d dl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 d dl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mZmZ d dlmZ d dlmZmZ d dlm Z  d dl!m"Z"m#Z# ddl$m%Z%m&Z&m'Z' 	dSdTddZ(				dUdVd%d&Z)			'dWdXd(d)Z*ddefdYd+d,Z+		dZd[d.d/Z,d\d5d6Z-ddd7dddedddf
d]dGdHZ.		I	Jd^d_dLdMZ/		N				d`dadQdRZ0dS )b    )annotations)datetimetimezone)
formatdateparsedate_to_datetime)
guess_type)path)PurePath)time)AnyAnyStrCallableOptionalUnion)
quote_plus)Header
open_async
stat_async)DEFAULT_HTTP_CONTENT_TYPE)Default_default)logger)HTMLProtocolRange   )HTTPResponseJSONResponseResponseStream   NstatusintheadersOptional[dict[str, str]]returnr   c                 C  s   t d| |dS )a  Returns an empty response to the client.

    Args:
        status (int, optional): HTTP response code. Defaults to `204`.
        headers ([type], optional): Custom HTTP headers. Defaults to `None`.

    Returns:
        HTTPResponse: An empty response to the client.
        bodyr   r!   r   )r   r!    r(   M/var/www/html/venv/lib/python3.10/site-packages/sanic/response/convenience.pyempty   s   r*      application/jsonr&   r   content_typestrdumpsOptional[Callable[..., AnyStr]]kwargsr   c                 K  s   t | f||||d|S )a  Returns response object with body in json format.

    Args:
        body (Any): Response data to be serialized.
        status (int, optional): HTTP response code. Defaults to `200`.
        headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.
        content_type (str, optional): The content type (string) of the response. Defaults to `"application/json"`.
        dumps (Callable[..., AnyStr], optional): A custom json dumps function. Defaults to `None`.
        **kwargs (Any): Remaining arguments that are passed to the json encoder.

    Returns:
        JSONResponse: A response object with body in json format.
    )r   r!   r-   r/   )r   )r&   r   r!   r-   r/   r1   r(   r(   r)   json$   s   r2   text/plain; charset=utf-8c                 C  s0   t | tstdt| j dt| |||dS )a	  Returns response object with body in text format.

    Args:
        body (str): Response data.
        status (int, optional): HTTP response code. Defaults to `200`.
        headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.
        content_type (str, optional): The content type (string) of the response. Defaults to `"text/plain; charset=utf-8"`.

    Returns:
        HTTPResponse: A response object with body in text format.

    Raises:
        TypeError: If the body is not a string.
    z!Bad body type. Expected str, got )r   r!   r-   )
isinstancer.   	TypeErrortype__name__r   r&   r   r!   r-   r(   r(   r)   textC   s   
r;   Optional[AnyStr]c                 C  s   t | |||dS )a  Returns response object without encoding the body.

    Args:
        body (Optional[AnyStr]): Response data.
        status (int, optional): HTTP response code. Defaults to `200`.
        headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.
        content_type (str, optional): The content type (string) of the response. Defaults to `"application/octet-stream"`.

    Returns:
        HTTPResponse: A response object without encoding the body.
    r:   r'   r:   r(   r(   r)   rawa   s   r=   Union[str, bytes, HTMLProtocol]c                 C  sD   t | ttfst| dr|  } n	t| dr|  } t| ||ddS )a  Returns response object with body in html format.

    Body should be a `str` or `bytes` like object, or an object with `__html__` or `_repr_html_`.

    Args:
        body (Union[str, bytes, HTMLProtocol]): Response data.
        status (int, optional): HTTP response code. Defaults to `200`.
        headers (Dict[str, str], optional): Custom HTTP headers. Defaults to `None`.

    Returns:
        HTTPResponse: A response object with body in html format.
    __html___repr_html_text/html; charset=utf-8r5   )r6   r.   byteshasattrr?   r@   r   r%   r(   r(   r)   htmlz   s   


rD   request_headersr   last_modifiedUnion[datetime, float, int]Optional[HTTPResponse]c              	     s   z|  d}W n
 ty   Y dS w zt|}W n ttfy+   td| Y dS w t|ts?tj	t
|tjdjdd}| du rX| durXtd |jtjd n| durp| du rptd	 |jtjd | | kr}td
dS dS )a=  Validate file based on request headers.

    Args:
        request_headers (Header): The request headers.
        last_modified (Union[datetime, float, int]): The last modified date and time of the file.

    Returns:
        Optional[HTTPResponse]: A response object with status 304 if the file is not modified.
    zIf-Modified-SinceNz9Ignorning invalid If-Modified-Since header received: '%s')tzr   microsecondzpCannot compare tz-aware and tz-naive datetimes. To avoid this conflict Sanic is converting last_modified to UTC.)tzinfoztCannot compare tz-aware and tz-naive datetimes. To avoid this conflict Sanic is converting if_modified_since to UTC.i0  )r   )getoneKeyErrorr   r7   
ValueErrorr   warningr6   r   fromtimestampfloatr   utcreplace	utcoffset	timestampr   )rE   rF   if_modified_sincer(   r(   r)   validate_file   sH   


rX   TlocationUnion[str, PurePath]Optional[Header]validate_when_requestedbool	mime_typeOptional[str]filename.Optional[Union[datetime, float, int, Default]]max_ageOptional[Union[float, int]]no_storeOptional[bool]_rangeOptional[Range]c              	     s  t |tr|jdd }nt |trt| I dH }|j}|r2|dur2|r2t||I dH }|r2|S |p5i }|rB|dt	|dd |rN|dd| d	 |	rSd
}n|rhd| }|dt	t
 | dd nd}|d| |pxt| d }t| ddI dH 4 I dH 9}|
r||
jI dH  ||
jI dH }d|
j d|
j d|
j |d< d}n| I dH }W d  I dH  n1 I dH sw   Y  |pt|d pd}t||||dS )as  Return a response object with file data.

    Args:
        location (Union[str, PurePath]): Location of file on system.
        status (int, optional): HTTP response code. Won't enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to 200.
        request_headers (Optional[Header], optional): The request headers.
        validate_when_requested (bool, optional): If `True`, will validate the file when requested. Defaults to True.
        mime_type (Optional[str], optional): Specific mime_type.
        headers (Optional[Dict[str, str]], optional): Custom Headers.
        filename (Optional[str], optional): Override filename.
        last_modified (Optional[Union[datetime, float, int, Default]], optional): The last modified date and time of the file.
        max_age (Optional[Union[float, int]], optional): Max age for cache control.
        no_store (Optional[bool], optional): Any cache should not store this response. Defaults to None.
        _range (Optional[Range], optional):

    Returns:
        HTTPResponse: The response object with the file data.
    r   rJ   NzLast-ModifiedT)usegmtContent-Dispositionattachment; filename=""zno-storezpublic, max-age=expireszno-cachezcache-controlrbmodebytes -/Content-Range   
text/plainr:   )r6   r   rT   rV   r   r   st_mtimerX   
setdefaultr   r
   r   splitr   seekstartreadsizeendtotalr   r   )rY   r   rE   r\   r^   r!   r`   rF   rb   rd   rf   statresponsecache_controlf
out_streamr(   r(   r)   file   sj   
 

(r   .  rA   toc                 C  s*   |pi }t | dd}||d< t|||dS )a;  Cause a HTTP redirect (302 by default) by setting a Location header.

    Args:
        to (str): path or fully qualified URL to redirect to
        headers (Optional[Dict[str, str]], optional): optional dict of headers to include in the new request. Defaults to None.
        status (int, optional): status code (int) of the new request, defaults to 302. Defaults to 302.
        content_type (str, optional): the content type (string) of the response. Defaults to "text/html; charset=utf-8".

    Returns:
        HTTPResponse: A response object with the redirect.
    z:/%#?&=@[]!$&'()*+,;)safeLocationr5   )r   r   )r   r!   r   r-   safe_tor(   r(   r)   redirect.  s   r      
chunk_sizer   c                   s   |pi }|r| dd| d |ptd }|p#t|d p#d} r> j} j} j}	d| d| d	|	 |d
< d} fdd}
t|
|||dS )a  Return a streaming response object with file data.

    :param location: Location of file on system.
    :param chunk_size: The size of each chunk in the stream (in bytes)
    :param mime_type: Specific mime_type.
    :param headers: Custom Headers.
    :param filename: Override filename.
    :param _range:

    Args:
        location (Union[str, PurePath]): Location of file on system.
        status (int, optional): HTTP response code. Won't enforce the passed in status if only a part of the content will be sent (206) or file is being validated (304). Defaults to `200`.
        chunk_size (int, optional): The size of each chunk in the stream (in bytes). Defaults to `4096`.
        mime_type (Optional[str], optional): Specific mime_type.
        headers (Optional[Dict[str, str]], optional): Custom HTTP headers.
        filename (Optional[str], optional): Override filename.
        _range (Optional[Range], optional): The range of bytes to send.
    ri   rj   rk   rm   r   rv   rq   rr   rs   rt   ru   c              	     s   t ddI d H 4 I d H ^} rH| jI d H   j}|dkrG|t jfI d H }t|dk r5n|t|8 }| |I d H  |dks!n	 |I d H }t|dk rXn	| |I d H  qIW d   I d H  d S 1 I d H srw   Y  d S )Nrn   ro   r   r   )r   rz   r{   r}   r|   minlenwrite)r   r   to_sendcontentrf   r   rY   r(   r)   _streaming_fnv  s(   .z"file_stream.<locals>._streaming_fn)streaming_fnr   r!   r-   )rx   r   ry   r   r{   r~   r   r   )rY   r   r   r^   r!   r`   rf   r{   r~   r   r   r(   r   r)   file_streamL  s*   r   )r   N)r   r    r!   r"   r#   r   )r+   Nr,   N)r&   r   r   r    r!   r"   r-   r.   r/   r0   r1   r   r#   r   )r+   Nr3   )
r&   r.   r   r    r!   r"   r-   r.   r#   r   )
r&   r<   r   r    r!   r"   r-   r.   r#   r   )r+   N)r&   r>   r   r    r!   r"   r#   r   )rE   r   rF   rG   r#   rH   )rY   rZ   r   r    rE   r[   r\   r]   r^   r_   r!   r"   r`   r_   rF   ra   rb   rc   rd   re   rf   rg   r#   r   )Nr   rA   )
r   r.   r!   r"   r   r    r-   r.   r#   r   )r+   r   NNNN)rY   rZ   r   r    r   r    r^   r_   r!   r"   r`   r_   rf   rg   r#   r   )1
__future__r   r   r   email.utilsr   r   	mimetypesr   osr   pathlibr	   r
   typingr   r   r   r   r   urllib.parser   sanic.compatr   r   r   sanic.constantsr   sanic.helpersr   r   	sanic.logr   sanic.models.protocol_typesr   r   typesr   r   r   r*   r2   r;   r=   rD   rX   r   r   r   r(   r(   r(   r)   <module>   sp    ! 
7b 