U
    ڲgUJ                     @  s   d Z ddlmZ ddlZddl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 ddlmZ ddlmZmZ ddlmZ erdd	l
mZ dd
lmZ ddlmZ ddlmZ eeZedZdZ dddddZ!G dd dZ"dS )z7
The httplib2 algorithms ported for use with requests.
    )annotationsN)parsedate_tz)TYPE_CHECKING
CollectionMapping)CaseInsensitiveDict)	DictCacheSeparateBodyBaseCache)
Serializer)Literal)PreparedRequest)HTTPResponse)	BaseCachez9^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)-  4  strztuple[str, str, str, str, str]urireturnc                 C  s@   t | }|dk	st| }|d |d |d |d |d fS )zParses a URI using the regex given in Appendix B of RFC 3986.

    (scheme, authority, path, query, fragment) = parse_uri(uri)
    N               )URImatchAssertionErrorgroups)r   r   r    r   ;/tmp/pip-unpacked-wheel-rew7nuve/cachecontrol/controller.py	parse_uri'   s    
r    c                   @  s   e Zd ZdZd/dddddd	d
ZedddddZedddddZdddddZdddddZ	dddddZ
ddddd Zd0ddd!d"d#d$d%d&d'Zd1dd(d"dd$d)d*d+Zdd!d!d,d-d.ZdS )2CacheControllerz4An interface to see if request should cached or not.NTzBaseCache | NoneboolzSerializer | NonezCollection[int] | None)cachecache_etags
serializerstatus_codesc                 C  s4   |d krt  n|| _|| _|p"t | _|p,d| _d S )N)      i,  r   r   )r   r#   r$   r
   r%   cacheable_status_codes)selfr#   r$   r%   r&   r   r   r   __init__5   s    zCacheController.__init__r   r   c           	      C  sh   t |\}}}}}|r|s&td| | }| }|s>d}|rPd||gpR|}|d | | }|S )z4Normalize the URL to create a safe key for the cachez(Only absolute URIs are allowed. uri = %s/?z://)r    	Exceptionlowerjoin)	clsr   scheme	authoritypathqueryfragmentrequest_uri
defrag_urir   r   r   _urlnormA   s    zCacheController._urlnormc                 C  s
   |  |S )N)r9   )r1   r   r   r   r   	cache_urlU   s    zCacheController.cache_urlzMapping[str, str]zdict[str, int | None])headersr   c           
      C  s(  t dft dft dfddddddddt dfd}|d|dd}i }|dD ]}| s^qP|d	d
}|d  }z|| \}}	W n$ tk
r   td| Y qPY nX |r|	sd ||< |rPz||d
  ||< W qP tk
r   |	rtd| Y qP tk
r    td||j	 Y qPX qP|S )NTF)NF)max-agez	max-stale	min-freshno-cacheno-storezno-transformzonly-if-cachedzmust-revalidatepublicprivatezproxy-revalidatezs-maxagezcache-controlzCache-Control ,=r   r   z,Ignoring unknown cache-control directive: %sz-Missing value for cache-control directive: %sz8Invalid value for cache-control directive %s, must be %s)
intgetsplitstripKeyErrorloggerdebug
IndexError
ValueError__name__)
r*   r;   known_directives
cc_headersretvalcc_directiveparts	directivetyprequiredr   r   r   parse_cache_controlY   sV    
z#CacheController.parse_cache_controlr   zHTTPResponse | None)requestr   c                 C  s   d|j krdS |j}|dk	s t| j|}|dkrBtd dS t| jtr\| j	|}nd}| j
|||}|dkrtd |S )zO
        Load a cached response, or return None if it's not available.
        ZRangeNzNo cache entry availablez1Cache entry deserialization failed, entry ignored)r;   urlr   r#   rF   rJ   rK   
isinstancer	   get_bodyr%   loadswarning)r*   rX   r:   
cache_dataZ	body_fileresultr   r   r   _load_from_cache   s    


z CacheController._load_from_cachezHTTPResponse | Literal[False]c                 C  s@  |j dk	st| |j }td| | |j}d|krHtd dS d|krj|d dkrjtd dS | |}|s|dS t|j	t
krd	}t| |S t|j}|rd
|krd|krtd | j| td dS t }t|d
 }|dk	stt|dd }	td||	 }
td|
 | |}d}|d}|dk	r^|}td| nLd|krt|d }|dk	rt|dd |	 }td|}td| |d}|dk	r|}td| |d}|dk	r|
|7 }
td|
 ||
krtd td||
 |S d|kr<td | j| dS )ze
        Return a cached response if it exists in the cache, otherwise
        return False.
        NzLooking up "%s" in the cacher>   z-Request header has "no-cache", cache bypassedFr<   r   z1Request header has "max_age" as 0, cache bypassedzQReturning cached permanent redirect response (ignoring date and etag information)dateetagz(Purging cached response: no date or etagz!Ignoring cached response: no dater   zCurrent age based on date: %iz#Freshness lifetime from max-age: %iexpiresz#Freshness lifetime from expires: %iz+Freshness lifetime from request max-age: %ir=   z'Adjusted current age from min-fresh: %iz2The response is "fresh", returning cached responsez%i > %iz4The cached response is "stale" with no etag, purging)rY   r   r:   rJ   rK   rW   r;   r`   rE   statusPERMANENT_REDIRECT_STATUSESr   r#   deletetimer   calendartimegmmaxrF   )r*   rX   r:   ccrespmsgr;   now
time_tuplera   current_ageresp_ccfreshness_lifetimemax_agerc   expire_time	min_freshr   r   r   cached_request   s|    














 





zCacheController.cached_requestzdict[str, str]c                 C  sH   |  |}i }|rDt|j}d|kr0|d |d< d|krD|d |d< |S )Nrb   ETagzIf-None-Matchzlast-modifiedzLast-ModifiedzIf-Modified-Since)r`   r   r;   )r*   rX   rl   new_headersr;   r   r   r   conditional_headers  s    

z#CacheController.conditional_headersr   zbytes | Nonez
int | NoneNone)r:   rX   responsebodyexpires_timer   c                 C  sd   t | jtrB| jj|| j||d|d |dk	r`| j|| n| jj|| j||||d dS )z.
        Store the data in the cache.
            )rc   N)rZ   r#   r	   setr%   dumpsZset_body)r*   r:   rX   r{   r|   r}   r   r   r   
_cache_set&  s    zCacheController._cache_setz2HTTPResponse | weakref.ReferenceType[HTTPResponse])rX   response_or_refr|   r&   r   c                 C  s  t |tjr | }|dkr$dS n|}|p,| j}|j|krLtd|j| dS t|j}d|krt	|d }|dk	svt
t|dd }	nd}	|dk	rd|kr|d  rt|d t|krdS | |j}
| |}|jdk	st
| |j}td| d}d	|krd
}td d	|
kr2d
}td |r\| j|r\td | j| |rfdS d|ddkrtd dS | jrd|krd}|drt	|d }|dk	rt|dd |	 }t|d}td| d td | ||||| n
t|jtkr<td | |||d nd|krt	|d }|dk	s`t
t|dd }	|d}|dk	r|dkrtd |}| ||||| nhd|kr|d rt	|d }|dk	rt|dd |	 }nd}td| | ||||| dS )zc
        Algorithm for caching requests.

        This assumes a requests Response object.
        NzStatus code %s not in %sra   r   r   content-lengthz&Updating cache with response from "%s"Fr?   TzResponse header has "no-store"zRequest header has "no-store"z0Purging existing cache entry to honor "no-store"*varyrB   zResponse header has "Vary: *"rb   rc   i u zetag object cached for z secondszCaching due to etagzCaching permanent redirectr~   r<   z'Caching b/c date exists and max-age > 0z4Caching b/c of expires header. expires in {} seconds)rZ   weakrefReferenceTyper)   rd   rJ   rK   r   r;   r   r   rh   ri   isdigitrE   lenrW   rY   r:   r#   rF   rf   r$   rj   r   re   format)r*   rX   r   r|   r&   r{   r)   response_headersro   ra   cc_reqrk   r:   no_storer}   rc   rs   r   r   r   cache_responseD  s    

  


















zCacheController.cache_response)rX   r{   r   c                   sj   |j dk	st| |j }| |}|s,|S dg |j fdd|j D  d|_| ||| |S )zOn a 304 we will get a new set of headers that we want to
        update our cached value with, assuming we have one.

        This should only ever be called when we've sent an ETag and
        gotten a 304 as the response.
        Nr   c                   s"   i | ]\}}|   kr||qS r   )r/   ).0kvexcluded_headersr   r   
<dictcomp>  s    z:CacheController.update_cached_response.<locals>.<dictcomp>r'   )	rY   r   r:   r`   r;   updateitemsrd   r   )r*   rX   r{   r:   cached_responser   r   r   update_cached_response  s    	
	
	z&CacheController.update_cached_response)NTNN)NN)NN)rN   
__module____qualname____doc__r+   classmethodr9   r:   rW   r`   rv   ry   r   r   r   r   r   r   r   r!   2   s,       6n  "   r!   )#r   
__future__r   rh   loggingrerg   r   email.utilsr   typingr   r   r   Zrequests.structuresr   Zcachecontrol.cacher   r	   Zcachecontrol.serializer
   r   requestsr   urllib3r   r   	getLoggerrN   rJ   compiler   re   r    r!   r   r   r   r   <module>   s*   

