
    
FZjCJ                     &   d Z ddlmZ ddlZddlZddl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 ddlmZmZ ddlmZmZ dZ G d de      Z G d de      Z G d de
      Z edddfdZ!d Z"eddfdZ#d Z$d Z%g dZ&y)zR
mygeotab.api
~~~~~~~~~~~~

Public objects and methods wrapping the MyGeotab API.
    )unicode_literalsN)urlparse)HTTPAdapter)Timeout)create_urllib3_context   )	__title____version__)AuthenticationExceptionMyGeotabExceptionTimeoutException)camelcaseify_parametersconvert_get_parameters)json_deserializejson_serializei,  c                       e Zd ZdZddddeddfdZed        Zed        Zd Z	d Z
d	 Zd
 Zd Zd Zd Zed        Zy)APIz3A simple and Pythonic wrapper for the MyGeotab API.Nmy.geotab.comc	                     |t        d      ||t        d      t        |||||      | _        || _        || _        d| _        || _        y)a  Initialize the MyGeotab API object with credentials.

        :param username: The username used for MyGeotab servers. Usually an email address.
        :type username: str
        :param password: The password associated with the username. Optional if `session_id` is provided.
        :type password: str
        :param database: The database or company name. Optional as this usually gets resolved upon authentication.
        :type database: str
        :param session_id: A session ID, assigned by the server.
        :type session_id: str
        :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication.
        :type server: str or None
        :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).
        :type timeout: float or None
        :param proxies: The proxies dictionary to apply to the request.
        :type proxies: dict or None
        :param cert: The path to client certificate. A single path to .pem file or a Tuple (.cer file, .key file).
        :type cert: str or Tuple or None
        :raise Exception: Raises an Exception if a username, or one of the session_id or password is not provided.
        Nz`username` cannot be Nonez1`password` and `session_id` must not both be Noneusername
session_iddatabaseserverpasswordr   )	ExceptionCredentialscredentialstimeout_proxies_API__reauthorize_count_cert)	selfr   r   r   r   r   r   proxiescerts	            NC:\Users\Rodrigo\frota-trucks-cliente\python\Lib\site-packages\mygeotab/api.py__init__zAPI.__init__!   sf    > 788
 2OPP&*xPVai
 #$ 
    c                 |    | j                   j                  sd| j                   _        | j                   j                  S )Nr   )r   r   r#   s    r&   _serverzAPI._serverL   s1    &&&5D#&&&r(   c                 .     t         fddD               S )zyWhether or not SSL be verified.

        :rtype: bool
        :return: True if the calls are being made locally.
        c              3   L   K   | ]  }|t        j                        v   y wN)get_api_urlr+   ).0sr#   s     r&   	<genexpr>z%API._is_verify_ssl.<locals>.<genexpr>Y   s"     Z?Y!qK55?Ys   !$)z	127.0.0.1	localhost)anyr*   s   `r&   _is_verify_sslzAPI._is_verify_sslR   s     Z?YZZZZr(   c           	      x   |t        d      t        |      }| j                  r&| j                  j                  s| j	                          d|vr3| j                  j                  r| j                  j                         |d<   	 t        | j                  ||| j                  | j                  | j                  | j                        }|d| _        |S # t        $ r}|j                  dk(  s|j                  dk(  rd|j                  v r| j                  dk(  rS| j                  j                   r=| xj                  d	z  c_        | j	                           | j"                  |fi |cY d}~S t%        | j                  j&                  | j                  j(                  | j                  j*                        | d}~ww xY w)
a  Makes a call to the API.

        :param method: The method name.
        :type method: str
        :param parameters: Additional parameters to send (for example, search=dict(id='b123') ).
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        :return: The results from the server.
        :rtype: dict or list
        NA method name must be specifiedr   
verify_sslr$   r%   r   InvalidUserExceptionDbUnavailableExceptionInitializingr   )r   r   r   r   authenticate	get_param_queryr+   r   r5   r    r"   r!   r   namemessager   callr   r   r   r   )r#   method
parametersparamsresult	exceptions         r&   rB   zAPI.call[   s    >=>>(4D$4$4$?$?&4+;+;+F+F$($4$4$>$>$@F=!	..ZZF !+,(M  	~~!77"::~QZQbQb?b++q0T5E5E5N5N,,1,%%'$499V:z::1((1143C3C3L3LdN^N^NeNe$% 	s'   AC 	F9BF4#F9)AF44F9c           	          |D cg c]%  }t        |d   t        |      dkD  r|d   ni       ' }}| j                  d|      S c c}w )a  Performs a multi-call to the API.

        :param calls: A list of call 2-tuples with method name and params
                      (for example, ('Get', dict(typeName='Trip')) ).
        :type calls: list((str, dict))
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        :return: The results from the server.
        :rtype: list
        r   r   )rC   rE   ExecuteMultiCall)calls)dictlenrB   )r#   rJ   rB   formatted_callss       r&   
multi_callzAPI.multi_call   sS     fkkej]a4tAw#d)a-tAwUWXejkyy+?yCC ls   *Ac                 <     | j                   dd|it        |      S )aX  Gets entities using the API. Shortcut for using call() with the 'Get' method.

        :param type_name: The type of entity.
        :type type_name: str
        :param parameters: Additional parameters to send. A parameter called `resultsLimit`
                           or `results_limit` will limit the number of entries returned. A
                           `search` parameter can further limit results, for example
                           search=dict(id='b123'). If a parameter called `search` is
                           omitted, any additional parameters are automatically added
                           to a `search` dictionary. This simplifies basic usage.
                           The following are equivalent calls:
                           api.get("Device", search={"id":"b2"})
                           api.get("Device", id="b2)
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        :return: The results from the server.
        :rtype: list
        	type_name)Get)rB   r   )r#   rP   rD   s      r&   getzAPI.get   s#    & tyyZ)Z7Mj7YZZr(   c                 *    | j                  d||      S )a  Adds an entity using the API. Shortcut for using call() with the 'Add' method.

        :param type_name: The type of entity.
        :type type_name: str
        :param entity: The entity to add.
        :type entity: dict
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        :return: The id of the object added.
        :rtype: str
        AddrP   entityrB   r#   rP   rV   s      r&   addzAPI.add   s     yy)FyCCr(   c                 *    | j                  d||      S )a  Sets an entity using the API. Shortcut for using call() with the 'Set' method.

        :param type_name: The type of entity.
        :type type_name: str
        :param entity: The entity to set.
        :type entity: dict
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        SetrU   rW   rX   s      r&   setzAPI.set   s     yy)FyCCr(   c                 *    | j                  d||      S )a  Removes an entity using the API. Shortcut for using call() with the 'Remove' method.

        :param type_name: The type of entity.
        :type type_name: str
        :param entity: The entity to remove.
        :type entity: dict
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        RemoverU   rW   rX   s      r&   removez
API.remove   s     yyYvyFFr(   c           	         	 | j                   j                  r| j                   j                  st        | j                   j                  | j                   j
                  | j                   j                        }t        | j                  d|| j                  | j                  | j                  | j                         | j                   S t        | j                   j                  | j                   j
                  | j                   j                        }t        | j                  d|| j                  | j                  | j                  | j                        }|rud|vr"| j                   j                  r| j                   S |d   }| j                   j                  }|dk7  r|}|d   }t        |d	   |d
   |d   |      | _         | j                   S y# t        $ r}|j                  dk(  s+|j                  dk(  rfd|j                   v sd|j                   v rJt#        | j                   j
                  | j                   j                  | j                   j                        | d}~ww xY w)a  Authenticates against the API server.

        :raise AuthenticationException: Raises if there was an issue with authenticating or logging in.
        :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
        :raise TimeoutException: Raises when the request does not respond after some time.
        :return: A Credentials object with a session ID created by the server.
        :rtype: Credentials
        )r   userName	sessionIdExtendSessionr8   )r   ra   r   Authenticatepath
ThisServerr   ra   rb   r   r:   r;   r<   UnknownDatabaseN)r   r   r   rK   r   r   r?   r+   r   r5   r    r"   r   r   r   r@   rA   r   )r#   extend_session_data	auth_datarF   
new_serverr   r   rG   s           r&   r=   zAPI.authenticate   s(   6	**43C3C3L3L&*!--66!--66"..99'#
 LL#'LL#22 MM '''))22))22))22I
 ..ZZF 'D,<,<,G,G+++#F^
))00-'F$]3#.
+[-E{S]G^`f$  '''  ! 	~~!77"::#y'8'88<MQZQbQb<b-$$--t/?/?/H/H$JZJZJaJa ! 	s'   CG B5G >AG 	I!BII!c                     t        | j                  | j                  | j                  | j                  | j
                        S )a  Returns a new API object from an existing Credentials object.

        :param credentials: The existing saved credentials.
        :type credentials: Credentials
        :return: A new API object populated with MyGeotab credentials.
        :rtype: API
        )r   r   r   r   r   )r   r   r   r   r   r   )r   s    r&   from_credentialszAPI.from_credentials  s>      )) )) ))"--%%
 	
r(   )__name__
__module____qualname____doc__DEFAULT_TIMEOUTr'   propertyr+   r5   rB   rN   rR   rY   r\   r_   r=   staticmethodrl    r(   r&   r   r      s    =
 )V ' '
 [ [,\D[*D
D
G?B 
 
r(   r   c                   *    e Zd ZdZddZd Zd Zd Zy)r   z The MyGeotab Credentials object.Nc                 J    || _         || _        || _        || _        || _        y)a  Initialize the Credentials object.

        :param username: The username used for MyGeotab servers. Usually an email address.
        :type username: str
        :param session_id: A session ID, assigned by the server.
        :type session_id: str
        :param database: The database or company name. Optional as this usually gets resolved upon authentication.
        :type database: str or None
        :param server: The server ie. my23.geotab.com. Optional as this usually gets resolved upon authentication.
        :type server: str or None
        :param password: The password associated with the username. Optional if `session_id` is provided.
        :type password: str or None
        Nr   )r#   r   r   r   r   r   s         r&   r'   zCredentials.__init__(  s'     !$  r(   c                 d    dj                  | j                  | j                  | j                        S )Nz{0} @ {1}/{2})formatr   r   r   r*   s    r&   __str__zCredentials.__str__<  s#    %%dmmT[[$--PPr(   c                 P    dj                  | j                  | j                        S )Nz5Credentials(username={username}, database={database}))r   r   )rx   r   r   r*   s    r&   __repr__zCredentials.__repr__?  s&    FMMW[WdWdoso|o|M}}r(   c                 Z    t        | j                  | j                  | j                        S )zA simple representation of the credentials object for passing into the API.authenticate() server call.

        :return: The simple credentials object for use by API.authenticate().
        :rtype: dict
        )ra   rb   r   )rK   r   r   r   r*   s    r&   r>   zCredentials.get_paramB  s"     T]]dooPTP]P]^^r(   r.   )rm   rn   ro   rp   r'   ry   r{   r>   rt   r(   r&   r   r   %  s    *!(Q~_r(   r   c                       e Zd ZdZddZy)GeotabHTTPAdapterz-HTTP adapter to enforce use of TLS for HTTPS.c                    t        t        j                        }|j                          t	        t        d      r#|xj
                  t        j                  z  c_        t        j                  j                  d||||d|| _        y )N)ssl_versionOP_ENABLE_MIDDLEBOX_COMPAT)	num_poolsmaxsizeblockssl_contextrt   )
r   sslPROTOCOL_TLS_CLIENTload_default_certshasattroptionsr   urllib3poolmanagerPoolManager)r#   connectionsr   r   pool_kwargsr   s         r&   init_poolmanagerz"GeotabHTTPAdapter.init_poolmanagerN  so    ,9P9PQ&&(3453#A#AA"..:: 
!7%[
\g
r(   N)F)rm   rn   ro   rp   r   rt   r(   r&   r~   r~   K  s
    7
r(   r~   Tc           
      :   t        |       }t        d||xs i       }t               }	t        j                         5 }
|
j                  dt                      |r||
_        	 |
j                  |t        |      |	d|||      }	 ddd       j                          |j                  j                  d      }|rd|j                         vr|j                   S t#        t%        |j                               S # t        $ r}t        |       |d}~ww xY w# 1 sw Y   xY w)	aB  Formats and performs the query against the API.

    :param server: The MyGeotab server.
    :type server: str
    :param method: The method name.
    :type method: str
    :param parameters: The parameters to send with the query.
    :type parameters: dict
    :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).
    :type timeout: float
    :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this.
    :type verify_ssl: bool
    :param proxies: The proxies dictionary to apply to the request.
    :type proxies: dict or None
    :param cert: The path to client certificate. A single path to .pem file or a Tuple (.cer file, .pem file)
    :type cert: str or Tuple or None
    :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
    :raise TimeoutException: Raises when the request does not respond after some time.
    :raise urllib2.HTTPError: Raises when there is an HTTP status code that indicates failure.
    :return: The JSON-decoded result from the server.
    )idrC   rE   https://T)dataheadersallow_redirectsr   verifyr$   NzContent-Typezapplication/json)r/   rK   get_headersrequestsSessionmountr~   r%   postr   r   r   raise_for_statusr   rR   lowertext_processr   )r   rC   rD   r   r9   r$   r%   api_endpointrE   r   sessionresponseexccontent_types                 r&   r?   r?   X  s   , v&LRz/?R@FmG				wj"3"56GL	4||#F+ $! $ H 
  ##''7L*,2D2D2FF}}$X]]344  	4"6*3	4 
	s)   $D!!C44	D=D		DDDc                 @    | rd| v rt        | d         d| v r| d   S | S )zProcesses the returned JSON from the server.

    :param data: The JSON data in dict form.
    :raise MyGeotabException: Raises when a server exception was encountered.
    :return: The result data.
    errorrF   )r   )r   s    r&   r   r     s4     d?#DM22t>!Kr(   c                 n    | t        d      |t        d      t        |      }t        || ||||      S )aN  Makes a call to an un-authenticated method on a server

    :param method: The method name.
    :type method: str
    :param server: The MyGeotab server.
    :type server: str
    :param timeout: The timeout to make the call, in seconds. By default, this is 300 seconds (or 5 minutes).
    :type timeout: float
    :param verify_ssl: If True, verify the SSL certificate. It's recommended not to modify this.
    :type verify_ssl: bool
    :param proxies: The proxies dictionary to apply to the request.
    :type proxies: dict or None
    :param parameters: Additional parameters to send (for example, search=dict(id='b123') ).
    :raise MyGeotabException: Raises when an exception occurs on the MyGeotab server.
    :raise TimeoutException: Raises when the request does not respond after some time.
    :return: The result from the server.
    r7   z/A server (eg. my3.geotab.com) must be specified)r   r9   r$   )r   r   r?   )rC   r   r   r9   r$   rD   s         r&   server_callr     sF    $ ~9::~IJJ(4J&&*g*^effr(   c                     t        |       }|j                  r|j                  n|j                  }|j                  dd       d|z   dz   S )zFormats the server URL properly in order to query the API.

    :return: A valid MyGeotab API request URL.
    :rtype: str
    / r   z/apiv1)r   netlocre   replace)r   parsedbase_urls      r&   r/   r/     sC     fF &v}}6;;HS" 8++r(   c                  \    ddj                  t        j                  t        t              dS )zLGets the request headers.

    :return: The user agent
    :rtype: dict
    zapplication/json; charset=UTF-8z8Python/{py_version[0]}.{py_version[1]} {title}/{version})
py_versiontitleversion)zContent-typez
User-Agent)rx   sysversion_infor	   r
   rt   r(   r&   r   r     s2     :PWW''y+ X 
 r(   )r   r   r   r   )'rp   
__future__r   r   r   urllib.parser   r   r   requests.adaptersr   requests.exceptionsr   urllib3.util.ssl_r   r   r	   r
   
exceptionsr   r   r   rD   r   r   serializersr   r   rq   objectr   r   r~   r?   r   r   r/   r   __all__rt   r(   r&   <module>r      s    ( 
 
 !   ) ' 4 $ T T G 9D
& D
N#_& #_L

 

 0?4Y]dh -5` )8DRV g4	, Qr(   