U
    ™j7g…1  ã                   @   sÂ   d Z ddlmZ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mZ dd	l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mZmZmZmZ G dd„ dƒZ dS )zD
Main API client handler for fetching data from the IPinfo service.
é    )ÚIPv4AddressÚIPv6AddressNé   )ÚAPIError)ÚDefaultCache)ÚDetails)ÚRequestQuotaExceededErrorÚTimeoutExceededError)ÚAPI_URLÚBATCH_MAX_SIZEÚCACHE_MAXSIZEÚ	CACHE_TTLÚREQUEST_TIMEOUT_DEFAULTÚBATCH_REQ_TIMEOUT_DEFAULTÚ	cache_key)Úhandler_utils)Úis_bogon)Ú
continentsÚ	countriesÚcountries_currenciesÚeu_countriesÚcountries_flagsc                   @   sH   e Zd ZdZddd„Zddd„Zdeddfdd	„Zd
d„ Zddd„Z	dS )ÚHandlerzq
    Allows client to request data for specified IP address.
    Instantiates and maintains access to cache.
    Nc                 K   sÖ   || _ | d¡pt| _| d¡p"t| _| d¡p2t| _| d¡pBt| _| d¡pRt| _| di ¡| _d| jkrxt| jd< d|krŒ|d | _	n8| d	i ¡}d
|kr¨t
|d
< d|kr¸t|d< tf |Ž| _	| dd¡| _dS )zi
        Initialize the Handler object with country name list and the
        cache initialized.
        r   r   r   r   Z	continentÚrequest_optionsÚtimeoutÚcacheÚcache_optionsÚmaxsizeZttlÚheadersN)Úaccess_tokenÚgetr   r   r   r   r   r   r   r   r   r   r   r   )Úselfr   Úkwargsr   © r#   ú2/tmp/pip-unpacked-wheel-bv8pilsi/ipinfo/handler.pyÚ__init__(   s&    ÿ

zHandler.__init__c                 C   sT  t |tƒst |tƒr|j}|rBt|ƒrBi }||d< d|d< t|ƒS z| jt|ƒ }t|ƒW S  tk
rn   Y nX | j	–}|dk	rˆ||d< t
}|rœ|d| 7 }t | j| j¡}tj|fd|i|—Ž}|jdkrÒtƒ ‚|jd	kr|j}	|j d
¡}
|
dkr| ¡ }n
d|ji}t|	|ƒ‚| ¡ }t || j| j| j| j| j¡ || jt|ƒ< t|ƒS )z»
        Get details for specified IP address as a Details object.

        If `timeout` is not `None`, it will override the client-level timeout
        just for this operation.
        ÚipTÚbogonNr   ú/r   é­  i  zContent-Typeúapplication/jsonÚerror)Ú
isinstancer   r   Úexplodedr   r   r   r   ÚKeyErrorr   r
   r   Úget_headersr   r   Úrequestsr    Ústatus_coder   ÚjsonÚtextr   Úformat_detailsr   r   r   r   r   )r!   Ú
ip_addressr   ÚdetailsÚcached_ipaddrÚreq_optsÚurlr   ÚresponseZ
error_codeÚcontent_typeZerror_responser#   r#   r$   Ú
getDetailsS   sV    
 ÿ





úzHandler.getDetailsTc                 C   sj  |dkrt }i }g }|D ]†}t|tƒs0t|tƒr6|j}|rdt|ƒrdi }	||	d< d|	d< t|	ƒ||< qz| jt|ƒ }
|
||< W q t	k
rœ   | 
|¡ Y qX qt|ƒdkr°|S |dk	rÀt ¡ }| jd|i–}td }t | j| j¡}d|d	< tdt|ƒ|ƒD ]d}|dk	r4t ¡ | |kr4t |tƒ |¡  S |||| … }ztj|f||d
œ|—Ž}W n: tk
rš } zt |||¡ W Y ¢  S d}~X Y nX z|jdkr°tƒ ‚| ¡  W n: tk
rô } zt |||¡ W Y ¢  S d}~X Y nX | ¡ }| ¡ D ]\}}	|	| jt|ƒ< q| |¡ | ¡ D ]0}t|t ƒr2t !|| j"| j#| j$| j%| j&¡ q2qþ|S )a/  
        Get details for a batch of IP addresses at once.

        There is no specified limit to the number of IPs this function can
        accept; it can handle as much as the user can fit in RAM (along with
        all of the response data, which is at least a magnitude larger than the
        input list).

        The input list is broken up into batches to abide by API requirements.
        The batch size can be adjusted with `batch_size` but is clipped to
        `BATCH_MAX_SIZE`.
        Defaults to `BATCH_MAX_SIZE`.

        For each batch, `timeout_per_batch` indicates the maximum seconds to
        spend waiting for the HTTP request to complete. If any batch fails with
        this timeout, the whole operation fails.
        Defaults to `BATCH_REQ_TIMEOUT_DEFAULT` seconds.

        `timeout_total` is a seconds-denominated hard-timeout for the time
        spent in HTTP operations; regardless of whether all batches have
        succeeded so far, if `timeout_total` is reached, the whole operation
        will fail by raising `TimeoutExceededError`.
        Defaults to being turned off.

        `raise_on_fail`, if turned off, will return any result retrieved so far
        rather than raise an exception when errors occur, including timeout and
        quota errors.
        Defaults to on.
        Nr&   Tr'   r   r   ú/batchr*   úcontent-type©r2   r   r)   )'r   r,   r   r   r-   r   r   r   r   r.   ÚappendÚlenÚtimer   r
   r   r/   r   r   ÚrangeÚreturn_or_failr	   r0   ÚpostÚ	Exceptionr1   r   Úraise_for_statusr2   ÚitemsÚupdateÚvaluesÚdictr4   r   r   r   r   r   )r!   Úip_addressesÚ
batch_sizeZtimeout_per_batchZtimeout_totalÚraise_on_failÚresultÚlookup_addressesr5   r6   r7   Ú
start_timer8   r9   r   ÚiÚchunkr:   ÚeZjson_responseÚdetailr#   r#   r$   ÚgetBatchDetails”   sŽ    % ÿÿþ  ÿÿ ÿÿ
((
ú
	zHandler.getBatchDetailsc                 C   s†   g }|D ](}t |tƒs t |tƒr&|j}| |¡ q| j–}t› d}t d| j	¡}d|d< t
j|f||dœ|—Ž}| ¡  | ¡ d S )zi
        Gets a URL to a map on https://ipinfo.io/map given a list of IPs (max
        500,000).
        z
/map?cli=1Nr*   r>   r?   Z	reportUrl)r,   r   r   r-   r@   r   r
   r   r/   r   r0   rE   rG   r2   )r!   ÚipsZip_strsr&   r8   r9   r   r:   r#   r#   r$   ÚgetMap  s&    
ÿ ÿÿzHandler.getMapc                 c   sæ  |d krt }i }g }|D ]„}t|tƒs0t|tƒr6|j}|rbt|ƒrbi }||d< d|d< t|ƒV  qz| jt|ƒ }|||< W q t	k
rš   | 
|¡ Y qX qt|ƒdkr¶t| ¡ ƒ‚td }	t | j| j¡}
d|
d< tdt|ƒ|ƒD ]ú}|||| … }ztj|	||
d}W n( tk
r6 } z|‚W 5 d }~X Y nX z|jd	krLtƒ ‚| ¡  W n8 tk
rŽ } zt ||¡ W Y ¢  S d }~X Y nX | ¡ }t || j| j| j| j | j!¡ |D ]$}| "|¡}|| jt|ƒ< |V  qºqæd S )
Nr&   Tr'   r   r=   r*   r>   r?   r)   )#r   r,   r   r   r-   r   r   r   r   r.   r@   rA   ÚStopIterationrH   r
   r   r/   r   r   rC   r0   rE   rF   r1   r   rG   rD   r2   r4   r   r   r   r   r   r    )r!   rL   rM   rN   rO   rP   r5   r6   r7   r9   r   rR   Úbatchr:   rT   r&   rU   r#   r#   r$   ÚgetBatchDetailsIter0  sd     ÿ&ú
zHandler.getBatchDetailsIter)N)NN)NT)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r%   r<   r   rV   rX   r[   r#   r#   r#   r$   r   "   s   
+
Dú
   ür   )!r_   Ú	ipaddressr   r   rB   r0   r+   r   Zcache.defaultr   r6   r   Ú
exceptionsr   r	   r   r
   r   r   r   r   r   r   Ú r'   r   Údatar   r   r   r   r   r   r#   r#   r#   r$   Ú<module>   s   $		