U
    ҭcT                     @   s  d Z ddlZddlZddlZddlm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ZddlZddlZddlZddlZzddlmZ W n  ek
r   ddlmZ Y nX eeZdZdej ZdZd	d
dhZG dd d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* ddl+m,Z, ddl+m-Z- ddl+m.Z. ddl+m/Z/ ddl0m1Z1 ddl0m2Z2 ddl0m3Z3 ddl0m4Z4 ddl0m5Z5 ddl0m6Z6 dd l0m7Z7 dd!l8m9Z9 dd"l:m;Z; d#d$ Z<e<ee_e<e e_ e<e"e_"e<e#e_#e<e%e_%e<e&e_&e<e(e_(e<e*e_*e<e,e_,e<e-e_-e<e.e_.e<e/e_/e<e1e_1e<e2e_2e<e3e_3e<e4e_4e<e5e_5e<e6e_6e<e7e_7e<e9e_9e<e;e_;d%d& Z=d'd( Z>ze? d)d* Z@W n eAk
r   d+d* Z@Y nX dS ),za
Core client functionality, common across all API requests (including performing
HTTP requests).
    N)datetime)	timedelta)	urlencodezX-Goog-Maps-Experience-IDzGoogleGeoApiClientPython/%szhttps://maps.googleapis.comi  i  i  c                   @   sr   e Zd ZdZddddddddddddddefddZdd	 Zd
d Zdd ZdddZ	dd Z
dd Zdd ZdS )Clientz6Performs requests to the Google Maps API web services.N<   ip  Tc                 C   s&  |s|r|st d|r*|ds*t d|rBtd|sBt d|pLt | _|| _|rj|sb|rjt d|r|rtj	d}t
|d d	k st
|d d	krt
|d
 dk rtd||f| _n|| _|| _|| _|| _t|d| _|pi | _| jdi }|dti | j|| jdd |	| _|
| _zt| jt
krlt| jt
krltt| j| jd | _n^| jrt| jt
krt| j| _n6| jrt| jt
krt| jd | _n
td t d| j W n  t!k
r   td Y nX || _"t#$d| j| _%| &| || _'dS )a  
        :param key: Maps API key. Required, unless "client_id" and
            "client_secret" are set. Most users should use an API key.
        :type key: string

        :param client_id: (for Maps API for Work customers) Your client ID.
            Most users should use an API key instead.
        :type client_id: string

        :param client_secret: (for Maps API for Work customers) Your client
            secret (base64 encoded). Most users should use an API key instead.
        :type client_secret: string

        :param channel: (for Maps API for Work customers) When set, a channel
            parameter with this value will be added to the requests.
            This can be used for tracking purpose.
            Can only be used with a Maps API client ID.
        :type channel: str

        :param timeout: Combined connect and read timeout for HTTP requests, in
            seconds. Specify "None" for no timeout.
        :type timeout: int

        :param connect_timeout: Connection timeout for HTTP requests, in
            seconds. You should specify read_timeout in addition to this option.
            Note that this requires requests >= 2.4.0.
        :type connect_timeout: int

        :param read_timeout: Read timeout for HTTP requests, in
            seconds. You should specify connect_timeout in addition to this
            option. Note that this requires requests >= 2.4.0.
        :type read_timeout: int

        :param retry_timeout: Timeout across multiple retriable requests, in
            seconds.
        :type retry_timeout: int

        :param queries_per_second: Number of queries per second permitted. Unset queries_per_minute to None. If set smaller number will be used.
            If the rate limit is reached, the client will sleep for the
            appropriate amount of time before it runs the current query.
        :type queries_per_second: int

        :param queries_per_minute: Number of queries per minute permitted. Unset queries_per_second to None. If set smaller number will be used.
            If the rate limit is reached, the client will sleep for the
            appropriate amount of time before it runs the current query.
        :type queries_per_minute: int

        :param retry_over_query_limit: If True, requests that result in a
            response indicating the query rate limit was exceeded will be
            retried. Defaults to True.
        :type retry_over_query_limit: bool

        :param experience_id: The value for the HTTP header field name
            'X-Goog-Maps-Experience-ID'.
        :type experience_id: str

        :raises ValueError: when either credentials are missing, incomplete
            or invalid.
        :raises NotImplementedError: if connect_timeout and read_timeout are
            used with a version of requests prior to 2.4.0.

        :param requests_kwargs: Extra keyword arguments for the requests
            library, which among other things allow for proxy auth to be
            implemented. See the official requests docs for more info:
            http://docs.python-requests.org/en/latest/api/#main-interface
        :type requests_kwargs: dict

        :param requests_session: Reused persistent session for flexibility.
        :type requests_session: requests.Session
        
        :param base_url: The base URL for all requests. Defaults to the Maps API
            server. Should not have a trailing slash.
        :type base_url: string

        zDMust provide API key or enterprise credentials when creating client.ZAIzazInvalid API key provided.z^[a-zA-Z0-9._-]*$zThe channel argument must be an ASCII alphanumeric string. The period (.), underscore (_)and hyphen (-) characters are allowed. If used without client_id, it must be 0-999.z;Specify either timeout, or connect_timeout and read_timeout.r            z7Connect/Read timeouts require requests v2.4.0 or higher)secondsheadersz
User-AgentT)r   timeoutZverifyr   zAMISSING VALID NUMBER for queries_per_second or queries_per_minutezAPI queries_quota: %sz:MISSING VALUE for queries_per_second or queries_per_minute N)(
ValueError
startswithrematchrequestsZSessionsessionkey__version__splitintNotImplementedErrorr   	client_idclient_secretchannelr   retry_timeoutrequests_kwargspopupdate_USER_AGENTqueries_per_secondqueries_per_minutetypemathfloorminqueries_quotasysexitloggerinfo	NameErrorretry_over_query_limitcollectionsdeque
sent_timesset_experience_idbase_url)selfr   r   r   r   Zconnect_timeoutZread_timeoutr   r   r"   r#   r   r.   Zexperience_idZrequests_sessionr3   chunksr    r6   N/home/ubuntu/graampay/app_env/lib/python3.8/site-packages/googlemaps/client.py__init__9   s\    R0
 

zClient.__init__c                 G   sN   t |dks|d dkr$|   dS | jdi }d||t< || jd< dS )zSets the value for the HTTP header field name
        'X-Goog-Maps-Experience-ID' to be used on subsequent API calls.

        :param experience_id_args: the experience ID
        :type experience_id_args: string varargs
        r   Nr   ,)lenclear_experience_idr   r   join_X_GOOG_MAPS_EXPERIENCE_ID)r4   Zexperience_id_argsr   r6   r6   r7   r2      s    zClient.set_experience_idc                 C   s   | j di }|tdS )zGets the experience ID for the HTTP header field name
        'X-Goog-Maps-Experience-ID'

        :return: The experience ID if set
        :rtype: str
        r   N)r   getr=   r4   r   r6   r6   r7   get_experience_id   s    zClient.get_experience_idc                 C   s2   | j d}|dkrdS |ti  || j d< dS )zlClears the experience ID for the HTTP header field name
        'X-Goog-Maps-Experience-ID' if set.
        r   N)r   r>   r   r=   r?   r6   r6   r7   r;      s
    zClient.clear_experience_idr   c
                 C   s  |dkr| j }|st }t | }
|
| jkr:tj |dkrhdd|d   }t|t		 d   | 
|||}|p|i }t| jf|}| jj}|	dk	r| jj}|	|d< z||| f|}W nP tjjk
r   tj Y n0 tk
r } ztj|W 5 d}~X Y nX |jtkr<| ||||d |||||		S | jrt| j| jkrt | jd  }|dk rtd|  z0|r||}n
| |}| jt  |W S  tjjk
r } z@t|tjjr| js | ||||d |||||		 W Y S d}~X Y nX dS )aN  Performs HTTP GET/POST with credentials, returning the body as
        JSON.

        :param url: URL path for the request. Should begin with a slash.
        :type url: string

        :param params: HTTP GET parameters.
        :type params: dict or list of key/value tuples

        :param first_request_time: The time of the first request (None if no
            retries have occurred).
        :type first_request_time: datetime.datetime

        :param retry_counter: The number of this retry, or zero for first attempt.
        :type retry_counter: int

        :param base_url: The base URL for the request. Defaults to the Maps API
            server. Should not have a trailing slash.
        :type base_url: string

        :param accepts_clientid: Whether this call supports the client/signature
            params. Some APIs require API keys (e.g. Roads).
        :type accepts_clientid: bool

        :param extract_body: A function that extracts the body from the request.
            If the request was not successful, the function should raise a
            googlemaps.HTTPError or googlemaps.ApiError as appropriate.
        :type extract_body: function

        :param requests_kwargs: Same extra keywords arg for requests as per
            __init__, but provided here to allow overriding internally on a
            per-request basis.
        :type requests_kwargs: dict

        :raises ApiError: when the API returns an error.
        :raises Timeout: if the request timed out.
        :raises TransportError: when something went wrong while trying to
            exceute a request.
        Nr   g      ?g      ?r	   json)r3   r   nowr   
googlemaps
exceptionsZTimeouttimesleeprandom_generate_auth_urldictr   r   r>   postr   	ExceptionZTransportErrorstatus_code_RETRIABLE_STATUSES_requestr1   r:   r(   	_get_bodyappendZ_RetriableRequest
isinstance_OverQueryLimitr.   )r4   urlparamsZfirst_request_timeZretry_counterr3   accepts_clientidZextract_bodyr   Z	post_jsonelapsedZdelay_secondsZ
authed_urlZfinal_requests_kwargsZrequests_methodresponseeZelapsed_since_earliestresultr6   r6   r7   rN      sn    +



    



    zClient._requestc                 O   s   | j ||S )N)rN   )r4   argskwargsr6   r6   r7   _get`  s    zClient._getc                 C   sp   |j dkrtj|j | }|d }|dks8|dkr<|S |dkrXtj||dtj||dd S )N   statusZOKZZERO_RESULTSZOVER_QUERY_LIMITZerror_message)rL   rC   rD   	HTTPErrorrA   rR   r>   ZApiError)r4   rW   bodyZ
api_statusr6   r6   r7   rO   c  s    
 zClient._get_bodyc                 C   s   t | ddpi }t|tkr2tt|f| }nt| |dd  }|r| jr| jr| jrp|d| jf |d| jf d	|t
|g}t| j|}|d | S | jr|d| jf |d t
| S tddS )	a;  Returns the path and query string portion of the request URL, first
        adding any necessary parameters.

        :param path: The path portion of the URL.
        :type path: string

        :param params: URL parameters.
        :type params: dict or list of key/value tuples

        :rtype: string

        _extra_paramsNr   Zclient?z&signature=r   zMMust provide API key for this API. It does not accept enterprise credentials.)getattrr$   rI   sorteditemsr   r   r   rP   r<   urlencode_params	sign_hmacr   r   )r4   pathrT   rU   extra_paramssigr6   r6   r7   rH   t  s    zClient._generate_auth_url)Nr   NTNNN)__name__
__module____qualname____doc___DEFAULT_BASE_URLr8   r2   r@   r;   rN   r\   rO   rH   r6   r6   r6   r7   r   6   s:         
 

         
qr   )
directions)distance_matrix)	elevation)elevation_along_path)geocode)reverse_geocode)	geolocate)timezone)snap_to_roads)nearest_roads)speed_limits)snapped_speed_limits)
find_place)places)places_nearby)place)places_photo)places_autocomplete)places_autocomplete_query)
static_map)addressvalidationc                    s   t   fdd}|S )a  
    Provides a single entry point for modifying all API methods.
    For now this is limited to allowing the client object to be modified
    with an `extra_params` keyword arg to each method, that is then used
    as the params for each web service request.

    Please note that this is an unsupported feature for advanced use only.
    It's also currently incompatibile with multiple threads, see GH #160.
    c                     sB   | dd | d _ | |}z| d `W n tk
r<   Y nX |S )Nri   r   )r   ra   AttributeError)rZ   r[   rY   funcr6   r7   wrapper  s    
z make_api_method.<locals>.wrapper)	functoolswraps)r   r   r6   r   r7   make_api_method  s    
r   c                 C   sF   | dd}|  dd} tt| |tj}t| }|	dS )zReturns a base64-encoded HMAC-SHA1 signature of a given string.

    :param secret: The key used for the signature, base64 encoded.
    :type secret: string

    :param payload: The payload to sign.
    :type payload: string

    :rtype: string
    asciistrictzutf-8)
encodehmacnewbase64urlsafe_b64decodehashlibZsha1urlsafe_b64encodedigestdecode)Zsecretpayloadrj   outr6   r6   r7   rg     s
    rg   c                 C   s`   g }| D ]F\}}t |ttfr<|D ]}||t|f q"q||t|f qtjt|S )zURL encodes the parameters.

    :param params: The parameters
    :type params: list of key/value tuples.

    :rtype: string
    )	rQ   listtuplerP   normalize_for_urlencoder   utilsZunquote_unreservedr   )rT   extendedr   valvr6   r6   r7   rf     s    
rf   c                 C   s.   t | tr| dS t | tr"| S tt| S )z5(Python 2) Converts the value to a `str` (raw bytes).utf8)rQ   unicoder   strr   valuer6   r6   r7   r     s
    


r   c                 C   s   t | tr| S tt| S )z(Python 3) No-op.)rQ   r   r   r   r6   r6   r7   r     s    
)Brn   r   r/   loggingr   r   r   r   r   r   r   rG   rE   r%   r)   rC   urllib.parser   ImportErrorurllib	getLoggerrk   r+   r=   r   r!   ro   rM   r   Zgooglemaps.directionsrp   Zgooglemaps.distance_matrixrq   Zgooglemaps.elevationrr   rs   Zgooglemaps.geocodingrt   ru   Zgooglemaps.geolocationrv   Zgooglemaps.timezonerw   Zgooglemaps.roadsrx   ry   rz   r{   Zgooglemaps.placesr|   r}   r~   r   r   r   r   Zgooglemaps.mapsr   Zgooglemaps.addressvalidationr   r   rg   rf   r   r   r-   r6   r6   r6   r7   <module>   s   


  f





















