B
    ufGH                 @  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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^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?)i-  i4  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   Y/home/ankuromar296_gmail_com/myenv/lib/python3.7/site-packages/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d/ddd!d"d#d$d%d&d'Zd0dd!d"dd$d(d)d*Zdd!d!d+d,d-ZdS )1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,  i-  i4  )r   r    r!   r
   r"   cacheable_status_codes)selfr    r!   r"   r#   r   r   r   __init__3   s    zCacheController.__init__r   )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   _urlnorm?   s    zCacheController._urlnormc             C  s
   |  |S )N)r6   )r.   r   r   r   r   	cache_urlS   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 }x|dD ]}| s`qR|d	d
}|d  }y|| \}}	W n" tk
r   td| wRY nX |r|	sd ||< |rRy||d
  ||< W qR tk
r   |	rtd| Y qR tk
r    td||j	 Y qRX qRW |S )NTF)NF)zmax-agez	max-stalez	min-freshzno-cachez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'   r8   known_directives
cc_headersretvalcc_directiveparts	directivetyprequiredr   r   r   parse_cache_controlW   sP    
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.
        RangeNzNo cache entry availablez1Cache entry deserialization failed, entry ignored)r8   urlr   r    r?   rC   rD   
isinstancer	   get_bodyr"   loadswarning)r'   rQ   r7   
cache_data	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 cachezno-cachez-Request header has "no-cache", cache bypassedFzmax-ager   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: %iz	min-freshz'Adjusted current age from min-fresh: %iz2The response is "fresh", returning cached responsez%i > %iz4The cached response is "stale" with no etag, purging)rS   r   r7   rC   rD   rP   r8   r[   r>   statusPERMANENT_REDIRECT_STATUSESr   r    deletetimer   calendartimegmmaxr?   )r'   rQ   r7   ccrespmsgr8   now
time_tupler\   current_ageresp_ccfreshness_lifetimemax_ager^   expire_time	min_freshr   r   r   cached_request   sv    




















zCacheController.cached_requestzdict[str, str]c             C  sH   |  |}i }|rDt|j}d|kr0|d |d< d|krD|d |d< |S )Nr]   ETagzIf-None-Matchzlast-modifiedzLast-ModifiedzIf-Modified-Since)r[   r   r8   )r'   rQ   rg   new_headersr8   r   r   r   conditional_headers  s    

z#CacheController.conditional_headersr   zbytes | Nonez
int | NoneNone)r7   rQ   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.
            )r^   N)rT   r    r	   setr"   dumpsset_body)r'   r7   rQ   rv   rw   rx   r   r   r   
_cache_set$  s    zCacheController._cache_set)rQ   rv   rw   r#   r   c             C  s  |p| j }|j|kr(td|j| dS t|j}d|krft|d }|dk	sRt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rd
}td d	|	krd
}td |r6| j|r6td | j| |r@dS d|ddkr`td dS | jrd|krd}|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rt|d }|dk	s:tt	|dd }|
d}|dk	r|dkrtd |}| ||||| nhd|kr|d rt|d }|dk	rt	|dd | }nd}td| | ||||| dS )zc
        Algorithm for caching requests.

        This assumes a requests Response object.
        zStatus code %s not in %sNr\   r   r   zcontent-lengthz&Updating cache with response from "%s"Fzno-storeTzResponse header has "no-store"zRequest header has "no-store"z0Purging existing cache entry to honor "no-store"*varyr;   zResponse header has "Vary: *"r]   r^   i u zetag object cached for z secondszCaching due to etagzCaching permanent redirectry   zmax-agez'Caching b/c date exists and max-age > 0z4Caching b/c of expires header. expires in {} seconds)r&   r_   rC   rD   r   r8   r   r   rc   rd   isdigitr>   lenrP   rS   r7   r    r?   ra   r!   re   r}   r`   format)r'   rQ   rv   rw   r#   r&   response_headersrj   r\   cc_reqrf   r7   no_storerx   r^   rn   r   r   r   cache_responseB  s    

















zCacheController.cache_response)rQ   rv   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.
        Nzcontent-lengthc               s"   i | ]\}}|   kr||qS r   )r,   ).0kv)excluded_headersr   r   
<dictcomp>  s   z:CacheController.update_cached_response.<locals>.<dictcomp>r$   )	rS   r   r7   r[   r8   updateitemsr_   r}   )r'   rQ   rv   r7   cached_responser   )r   r   update_cached_response  s    	
	
z&CacheController.update_cached_response)NTNN)NN)NN)rG   
__module____qualname____doc__r(   classmethodr6   r7   rP   r[   rq   rt   r}   r   r   r   r   r   r   r   0   s"      6n   r   )"r   
__future__r   rc   loggingrerb   email.utilsr   typingr   r   r   Zrequests.structuresr   Zcachecontrol.cacher   r	   Zcachecontrol.serializer
   r   requestsr   urllib3r   r   	getLoggerrG   rC   compiler   r`   r   r   r   r   r   r   <module>   s(   

