U
    	ڲg%                    @   s  d Z ddlmZ dZddddg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 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mZ ddlmZ ddl m!Z! dd	l"Z"dd	l#Z#zdd	l$Z$W n e%k
r   d	Z$Y nX zddl&m'Z' dZ(W n e%k
r>   dZ(Y nX ddl)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z= ddl>m?Z?m@Z@mAZA ddlBmCZC de"_DeEeFZGeHdZIeHdZJdZKeKZLdZMdZNeOdd d!gZPd"d#d$d%d&ZQd'd(d)ZRd*d+dd,ZSd-d+dd,ZTd.ZUd/ZVd0ZWd1ZXd2ZYeOd3d4d5d6gZZd+d7d8Z[G d9d: d:e\Z]eOd;gZ^G d<d= d=e
Z_d>d Z`d?d Zae.d@d	d	d	d	e:d	dd	d	d	d	dd	dfdAdZbdBdC ZcdgdDdEZddFdG Zee.dd	d	d	d	d	e:d	d	d	d	dfdHdZfdIdJ ZgdKdL ZhdMdN ZidOdP ZjdQdR ZkdSdT ZldUdV ZmdWdX ZnG dYdZ dZeoZpd[d\ Zqdhd_d`ZrG dadb dbeoZsdcdd Ztdedf Zud	S )izVClient for discovery based APIs.

A client library for Google's discovery based APIs.
    )absolute_importz$jcgregorio@google.com (Joe Gregorio)buildbuild_from_documentfix_method_name	key2param)OrderedDictN)BytesGenerator)MIMEMultipart)MIMENonMultipart)MutualTLSChannelError)mtls)service_account)universeTF)_auth	mimeparse)_add_query_parameter
positional)	HttpErrorInvalidJsonErrorMediaUploadSizeErrorUnacceptableMimeTypeErrorUnknownApiNameOrVersionUnknownFileType)BatchHttpRequestHttpMockHttpMockSequenceHttpRequestMediaFileUploadMediaUpload
build_http)	JsonModel
MediaModelRawModel)Schemas   z{[^}]*}z[a-zA-Z0-9_-]+zDhttps://www.googleapis.com/discovery/v1/apis/{api}/{apiVersion}/restzAhttps://{api}.googleapis.com/$discovery/rest?version={apiVersion}z)A description of how to use this functionPUTPOSTPATCH
         (   )ZKBZMBZGBZTBzThe request body.object)descriptiontypezOThe filename of the media request body, or an instance of a MediaUpload object.string)r-   r.   requiredzPThe MIME type of the media request body, or an instance of a MediaUpload object.)	pageTokennextPageToken!GOOGLE_API_USE_CLIENT_CERTIFICATEGOOGLE_API_USE_MTLS_ENDPOINTGOOGLE_CLOUD_UNIVERSE_DOMAINzgoogleapis.comtraceppZuseripstrictquery)r.   locationc                       s   e Zd Z fddZ  ZS )APICoreVersionErrorc                    s   d}t  | d S )NzIgoogle-api-core >= 2.18.0 is required to use the universe domain feature.)super__init__)selfmessage	__class__ =/tmp/pip-unpacked-wheel-rfrvjkbl/googleapiclient/discovery.pyr=      s    zAPICoreVersionError.__init__)__name__
__module____qualname__r=   __classcell__rB   rB   r@   rC   r;      s   r;   bodyc                   @   s   e Zd ZejZdS )_BytesGeneratorN)rD   rE   rF   r   writeZ_write_linesrB   rB   rB   rC   rI      s   rI   c                 C   s6   |  dd dd} t| s&| tkr.| d S | S dS )zFix method names to avoid '$' characters and reserved word conflicts.

    Args:
      name: string, method name.

    Returns:
      The name with '_' appended if the name is a reserved word and '$' and '-'
      replaced with '_'.
    $_-N)replacekeyword	iskeywordRESERVED_WORDS)namerB   rB   rC   r      s    
c                 C   sT   g }t | } | d  s"|d | D ]"}| r>|| q&|d q&d|S )zConverts key names into parameter names.

    For example, converting "max-results" -> "max_results"

    Args:
      key: string, the method key name.

    Returns:
      A safe method name based on the key name.
    r   xrL    )listisalphaappendisalnumjoin)keyresultcrB   rB   rC   r      s    
   c                 C   s  | |d}|dkr$|dkr d}nd}|dkr4t  }n|}d}t||D ]}t||}zBt|||| ||	|||d	}t||||||||
|||d}W  qW qF tk
r } z |jjt	j
krW Y qFn|W 5 d}~X Y qFX qF|dkr|  |dkrtd| |f n|S dS )a)  Construct a Resource for interacting with an API.

    Construct a Resource object for interacting with an API. The serviceName and
    version are the names from the Discovery service.

    Args:
      serviceName: string, name of the service.
      version: string, the version of the service.
      http: httplib2.Http, An instance of httplib2.Http or something that acts
        like it that HTTP requests will be made through.
      discoveryServiceUrl: string, a URI Template that points to the location of
        the discovery service. It should have two parameters {api} and
        {apiVersion} that when filled in produce an absolute URI to the discovery
        document for that service.
      developerKey: string, key obtained from
        https://code.google.com/apis/console.
      model: googleapiclient.Model, converts to and from the wire format.
      requestBuilder: googleapiclient.http.HttpRequest, encapsulator for an HTTP
        request.
      credentials: oauth2client.Credentials or
        google.auth.credentials.Credentials, credentials to be used for
        authentication.
      cache_discovery: Boolean, whether or not to cache the discovery doc.
      cache: googleapiclient.discovery_cache.base.CacheBase, an optional
        cache object for the discovery documents.
      client_options: Mapping object or google.api_core.client_options, client
        options to set user options on the client.
        (1) The API endpoint should be set through client_options. If API endpoint
        is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
        to control which endpoint to use.
        (2) client_cert_source is not supported, client cert should be provided using
        client_encrypted_cert_source instead. In order to use the provided client
        cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
        set to `true`.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      adc_cert_path: str, client certificate file path to save the application
        default client certificate for mTLS. This field is required if you want to
        use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
        environment variable must be set to `true` in order to use this field,
        otherwise this field doesn't nothing.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      adc_key_path: str, client encrypted private key file path to save the
        application default client encrypted private key for mTLS. This field is
        required if you want to use the default client certificate.
        `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
        `true` in order to use this field, otherwise this field doesn't nothing.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      num_retries: Integer, number of times to retry discovery with
        randomized exponential backoff in case of intermittent/connection issues.
      static_discovery: Boolean, whether or not to use the static discovery docs
        included in the library. The default value for `static_discovery` depends
        on the value of `discoveryServiceUrl`. `static_discovery` will default to
        `True` when `discoveryServiceUrl` is also not provided, otherwise it will
        default to `False`.
      always_use_jwt_access: Boolean, whether always use self signed JWT for service
        account credentials. This only applies to
        google.oauth2.service_account.Credentials.

    Returns:
      A Resource object with methods for interacting with the service.

    Raises:
      google.auth.exceptions.MutualTLSChannelError: if there are any problems
        setting up mutual TLS channel.
    )api
apiVersionNTF)num_retriesstatic_discovery)
basehttpdeveloperKeymodelrequestBuildercredentialsclient_optionsadc_cert_pathadc_key_pathalways_use_jwt_accessname: %s  version: %s)r   _discovery_service_uri_optionsuritemplateexpand_retrieve_discovery_docr   r   respstatushttp_client	NOT_FOUNDcloser   )serviceNameversionrc   discoveryServiceUrlrd   re   rf   rg   cache_discoverycacherh   ri   rj   r`   ra   rk   paramsZdiscovery_httpserviceZdiscovery_urlZrequested_urlcontenterB   rB   rC   r      s\    W



c                 C   s2   | dk	r| gS |dkr&t d tgS ttgS dS )aZ  
      Returns Discovery URIs to be used for attempting to build the API Resource.

    Args:
      discoveryServiceUrl:
          string, the Original Discovery Service URL preferred by the customer.
      version:
          string, API Version requested

    Returns:
        A list of URIs to be tried for the Service Discovery, in order.
    NzADiscovery V1 does not support empty versions. Defaulting to V2...)loggerwarningV2_DISCOVERY_URIDISCOVERY_URI)rx   rw   rB   rB   rC   rm   Z  s    rm   c	              
   C   s@  ddl m}	 |r6|dkr |	 }|r6|| }
|
r6|
S |r^|	||}
|
rN|
S td||f | }dtjkr~t| dtjd }|rt| d|}t	
d| t|tj|}|j|d	\}}
z|
d
}
W n tk
r   Y nX zt|
}W n8 tk
r" } zt	d|
  t W 5 d}~X Y nX |r<|r<|| |
 |
S )a  Retrieves the discovery_doc from cache or the internet.

    Args:
      url: string, the URL of the discovery document.
      http: httplib2.Http, An instance of httplib2.Http or something that acts
        like it through which HTTP requests will be made.
      cache_discovery: Boolean, whether or not to cache the discovery doc.
      serviceName: string, name of the service.
      version: string, the version of the service.
      cache: googleapiclient.discovery_cache.base.Cache, an optional cache
        object for the discovery documents.
      developerKey: string, Key for controlling API usage, generated
        from the API Console.
      num_retries: Integer, number of times to retry discovery with
        randomized exponential backoff in case of intermittent/connection issues.
      static_discovery: Boolean, whether or not to use the static discovery docs
        included in the library.

    Returns:
      A unicode string representation of the discovery document.
    r$   )discovery_cacheNrl   ZREMOTE_ADDRZuserIprZ   zURL being requested: GET %s)r`   utf-8zFailed to parse as JSON: )rT   r   Z
autodetectgetZget_static_docr   osenvironr   r   debugr   Znull_postprocexecutedecodeAttributeErrorjsonloads
ValueErrorerrorr   set)urlrc   ry   rv   rw   rz   rd   r`   ra   r   r}   Z
actual_urlreqrq   r|   r~   rB   rB   rC   rp   t  sF     


rp   c                 C   s$   t s t| dd }|r |tkr td S )Nuniverse_domain)HAS_UNIVERSEgetattrDEFAULT_UNIVERSEr;   )rg   Zcredentials_universerB   rB   rC   4_check_api_core_compatible_with_credentials_universe  s    r   c                 C   s  |dkrt jj }t|tjjr0t jj|}|dk	rn|df|j	dfg}|D ]\}}|dk	rNt
d|qNt| trt| } nt| trt| d} d| krt|ttfrtd t tj| d | d }d}trttd}t|j|}| tj!|}nt"|d	d}|r$t#|}|j$r6|j$}t%| }|dkrt&| 'd
i 'di 'di ( }|r|s|j	r|rt jj)*d|j	rt+j,|j	|j-|j.d}|dkrt+j/|j-|j.d}t0| |j-st+1||}|r&t|t2j3r&|r&t4t2j3dr&|5|}|6| |r8t+7|}nt8 }d}tt9d}|dkr`t:d|rv|j;rvt:d|dkr|rt4|dr|j<r|j<}n"|	r|
rt=> rt=?|	|
}|r| \}}}t@rt|t@jAr|jBn|}|C||d| d| kr|r|j$stj| d | d }ttDd}|dkrPt:d|dksj|dkr|rtr|tj!krt:dtj! d|}nt"|dd}t0| |dkr| 'dg }tEd|k}tF|||||| | ||d 	S )!a  Create a Resource for interacting with an API.

    Same as `build()`, but constructs the Resource object from a discovery
    document that is it given, as opposed to retrieving one over HTTP.

    Args:
      service: string or object, the JSON discovery document describing the API.
        The value passed in may either be the JSON string or the deserialized
        JSON.
      base: string, base URI for all HTTP requests, usually the discovery URI.
        This parameter is no longer used as rootUrl and servicePath are included
        within the discovery document. (deprecated)
      future: string, discovery document with future capabilities (deprecated).
      http: httplib2.Http, An instance of httplib2.Http or something that acts
        like it that HTTP requests will be made through.
      developerKey: string, Key for controlling API usage, generated
        from the API Console.
      model: Model class instance that serializes and de-serializes requests and
        responses.
      requestBuilder: Takes an http request and packages it up to be executed.
      credentials: oauth2client.Credentials or
        google.auth.credentials.Credentials, credentials to be used for
        authentication.
      client_options: Mapping object or google.api_core.client_options, client
        options to set user options on the client.
        (1) The API endpoint should be set through client_options. If API endpoint
        is not set, `GOOGLE_API_USE_MTLS_ENDPOINT` environment variable can be used
        to control which endpoint to use.
        (2) client_cert_source is not supported, client cert should be provided using
        client_encrypted_cert_source instead. In order to use the provided client
        cert, `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be
        set to `true`.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      adc_cert_path: str, client certificate file path to save the application
        default client certificate for mTLS. This field is required if you want to
        use the default client certificate. `GOOGLE_API_USE_CLIENT_CERTIFICATE`
        environment variable must be set to `true` in order to use this field,
        otherwise this field doesn't nothing.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      adc_key_path: str, client encrypted private key file path to save the
        application default client encrypted private key for mTLS. This field is
        required if you want to use the default client certificate.
        `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable must be set to
        `true` in order to use this field, otherwise this field doesn't nothing.
        More details on the environment variables are here:
        https://google.aip.dev/auth/4114
      always_use_jwt_access: Boolean, whether always use self signed JWT for service
        account credentials. This only applies to
        google.oauth2.service_account.Credentials.

    Returns:
      A Resource object with methods for interacting with the service.

    Raises:
      google.auth.exceptions.MutualTLSChannelError: if there are any problems
        setting up mutual TLS channel.
    Nrg   zclient_options.credentials_filez,Arguments http and {} are mutually exclusiver   rootUrlzYou are using HttpMock or HttpMockSequence withouthaving the service discovery doc in cache. Try calling build() without mocking once first to populate the cache.servicePathr   authZoauth2scopeszGclient_options.credentials_file and credentials are mutually exclusive.)r   quota_project_idwith_always_use_jwt_accessfalse)truer   zQUnsupported GOOGLE_API_USE_CLIENT_CERTIFICATE value. Accepted values: true, falseziClientOptions.client_cert_source is not supported, please use ClientOptions.client_encrypted_cert_source.r   client_encrypted_cert_sourcerT   ZmtlsRootUrlauto)neverr   alwayszTUnsupported GOOGLE_API_USE_MTLS_ENDPOINT value. Accepted values: never, auto, alwaysr   z1mTLS is not supported in any universe other than .featuresZdataWrapper	rc   baseUrlre   rd   rf   resourceDescrootDescschemar   )GgoogleZapi_corerh   ZClientOptions
isinstancecollectionsabcMapping	from_dictZcredentials_filer   formatstrr   r   bytesr   r   r   r   r   r   urllibparseurljoinr   r   getenvr5   r   Zdetermine_domainr   rN   r   r   r;   Zapi_endpointr#   rU   r   keys
exceptionsZDuplicateCredentialArgsr   Zcredentials_from_filer   r   Zdefault_credentialsr   Zwith_scopesr   ZCredentialshasattrr   Z_create_self_signed_jwtZauthorized_httpr   r3   r   Zclient_cert_sourcer   r   Zhas_default_client_cert_sourceZ$default_client_encrypted_cert_sourcegoogle_auth_httplib2ZAuthorizedHttprc   Zadd_certificater4   r    Resource)r|   rb   futurerc   rd   re   rf   rg   rh   ri   rj   rk   Zbanned_optionsoptionrR   r   Zuniverse_domain_envZclient_universeZaudience_for_self_signed_jwtr   r   Zclient_cert_to_useZuse_client_certZ	cert_pathZkey_pathZ
passphraseZhttp_channelZmtls_endpointZuse_mtls_endpointZhttp_credentialsr   rB   rB   rC   r     s.   K

 







 


 


c                 C   s   |dkr6t | t dks(t | t dkr,| S t| S nl|dkrJtt| S |dkr^tt| S |dkrvtt|  S t | t dkst | t dkr| S t| S dS )af  Convert value to a string based on JSON Schema type.

    See http://tools.ietf.org/html/draft-zyp-json-schema-03 for more details on
    JSON Schema.

    Args:
      value: any, the value to convert
      schema_type: string, the type that value should be interpreted as

    Returns:
      A string representation of 'value' based on the schema_type.
    r/   rT   integernumberbooleanN)r.   r   intfloatboollower)valueZschema_typerB   rB   rC   _cast  s     
 r   c                 C   sR   t | dk rdS | dd  }t|}|dk	rFt| dd |> S t| S dS )zConvert a string media size, such as 10GB or 3TB into an integer.

    Args:
      maxSize: string, size as a string, such as 2MB or 7GB.

    Returns:
      The size as an integer value.
    r]   r   N)lenupper_MEDIA_SIZE_BIT_SHIFTSr   r   )maxSizeZunitsZ	bit_shiftrB   rB   rC   _media_size_to_long  s    	
r   c                 C   s   d| d | d |d S )a  Creates an absolute media path URL.

    Constructed using the API root URI and service path from the discovery
    document and the relative path for the API method.

    Args:
      root_desc: Dictionary; the entire original deserialized discovery document.
      path_url: String; the relative URL for the API method. Relative to the API
          root, which is specified in the discovery document.

    Returns:
      String; the absolute URI for media upload for the API method.
    z'%(root)supload/%(service_path)s%(path)sr   r   )rootZservice_pathpathrB   )	root_descpath_urlrB   rB   rC   _media_path_url_from_info  s
    r   c                 C   sv   |  di }|di  D ]\}}|||< qtD ]}t ||< q2|tkrrd| krrt }|| d  ||d< |S )a#  Updates parameters of an API method with values specific to this library.

    Specifically, adds whatever global parameters are specified by the API to the
    parameters for the individual method. Also adds parameters which don't
    appear in the discovery document, but are available to all discovery based
    APIs (these are listed in STACK_QUERY_PARAMETERS).

    SIDE EFFECTS: This updates the parameters dictionary object in the method
    description.

    Args:
      method_desc: Dictionary with metadata describing an API method. Value comes
          from the dictionary of methods stored in the 'methods' key in the
          deserialized discovery document.
      root_desc: Dictionary; the entire original deserialized discovery document.
      http_method: String; the HTTP method used to call the API method described
          in method_desc.
      schema: Object, mapping of schema names to schema descriptions.

    Returns:
      The updated Dictionary stored in the 'parameters' key of the method
          description dictionary.
    
parametersrequestrH   )	
setdefaultr   itemsSTACK_QUERY_PARAMETERS#STACK_QUERY_PARAMETER_DEFAULT_VALUEcopyHTTP_PAYLOAD_METHODSBODY_PARAMETER_DEFAULT_VALUEupdate)method_descr   http_methodr   r   rR   r-   rH   rB   rB   rC   _fix_up_parameters&  s    
r   c                 C   s\   |  di }| dg }t| dd}d}|rRt||}t |d< t |d< |||fS )a  Adds 'media_body' and 'media_mime_type' parameters if supported by method.

    SIDE EFFECTS: If there is a 'mediaUpload' in the method description, adds
    'media_upload' key to parameters.

    Args:
      method_desc: Dictionary with metadata describing an API method. Value comes
          from the dictionary of methods stored in the 'methods' key in the
          deserialized discovery document.
      root_desc: Dictionary; the entire original deserialized discovery document.
      path_url: String; the relative URL for the API method. Relative to the API
          root, which is specified in the discovery document.
      parameters: A dictionary describing method parameters for method described
          in method_desc.

    Returns:
      Triple (accept, max_size, media_path_url) where:
        - accept is a list of strings representing what content types are
          accepted for media upload. Defaults to empty list if not in the
          discovery document.
        - max_size is a long representing the max size in bytes allowed for a
          media upload. Defaults to 0L if not in the discovery document.
        - media_path_url is a String; the absolute URI for media upload for the
          API method. Constructed using the API root URI and service path from
          the discovery document and the relative path for the API method. If
          media upload is not supported, this is None.
    ZmediaUploadacceptr   rT   N
media_bodymedia_mime_type)r   r   r   "MEDIA_BODY_PARAMETER_DEFAULT_VALUEr   'MEDIA_MIME_TYPE_PARAMETER_DEFAULT_VALUE)r   r   r   r   media_uploadr   max_sizemedia_path_urlrB   rB   rC   _fix_up_media_uploadR  s    
r   c           
      C   sJ   | d }| d }| d }t | |||}t| |||\}}}	||||||	fS )a  Updates a method description in a discovery document.

    SIDE EFFECTS: Changes the parameters dictionary in the method description with
    extra parameters which are used locally.

    Args:
      method_desc: Dictionary with metadata describing an API method. Value comes
          from the dictionary of methods stored in the 'methods' key in the
          deserialized discovery document.
      root_desc: Dictionary; the entire original deserialized discovery document.
      schema: Object, mapping of schema names to schema descriptions.

    Returns:
      Tuple (path_url, http_method, method_id, accept, max_size, media_path_url)
      where:
        - path_url is a String; the relative URL for the API method. Relative to
          the API root, which is specified in the discovery document.
        - http_method is a String; the HTTP method used to call the API method
          described in the method description.
        - method_id is a String; the name of the RPC method associated with the
          API method, and is in the method description in the 'id' key.
        - accept is a list of strings representing what content types are
          accepted for media upload. Defaults to empty list if not in the
          discovery document.
        - max_size is a long representing the max size in bytes allowed for a
          media upload. Defaults to 0L if not in the discovery document.
        - media_path_url is a String; the absolute URI for media upload for the
          API method. Constructed using the API root URI and service path from
          the discovery document and the relative path for the API method. If
          media upload is not supported, this is None.
    r   
httpMethodid)r   r   )
r   r   r   r   r   Z	method_idr   r   r   r   rB   rB   rC   _fix_up_method_description{  s        
r   c                 C   s>   t j| }t j|}|j|jkr(| S t j|j|jdS )a  
    Update the media upload base url if its netloc doesn't match base url netloc.

    This can happen in case the base url was overridden by
    client_options.api_endpoint.

    Args:
      media_path_url: String; the absolute URI for media upload.
      base_url: string, base URL for the API. All requests are relative to this URI.

    Returns:
      String; the absolute URI for media upload.
    )netloc)r   r   urlparser   
urlunparse_replace)r   base_urlZparsed_media_urlZparsed_base_urlrB   rB   rC   _fix_up_media_path_base_url  s    r   c                 C   sZ   | ds| dr"tj| |S | dr0| n| d }| drN|dd n|}|| S )z8Custom urljoin replacement supporting : before / in url.zhttp://zhttps:///r$   N)
startswithr   r   r   endswith)rb   r   new_basenew_urlrB   rB   rC   _urljoin  s
    
r   c                   @   s    e Zd ZdZdd Zdd ZdS )ResourceMethodParametersa-  Represents the parameters associated with a method.

    Attributes:
      argmap: Map from method parameter name (string) to query parameter name
          (string).
      required_params: List of required parameters (represented by parameter
          name as string).
      repeated_params: List of repeated parameters (represented by parameter
          name as string).
      pattern_params: Map from method parameter name (string) to regular
          expression (as a string). If the pattern is set for a parameter, the
          value for that parameter must match the regular expression.
      query_params: List of parameters (represented by parameter name as string)
          that will be used in the query string.
      path_params: Set of parameters (represented by parameter name as string)
          that will be used in the base URL path.
      param_types: Map from method parameter name (string) to parameter type. Type
          can be any valid JSON schema type; valid values are 'any', 'array',
          'boolean', 'integer', 'number', 'object', or 'string'. Reference:
          http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5.1
      enum_params: Map from method parameter name (string) to list of strings,
         where each list of strings is the list of acceptable enum values.
    c                 C   s@   i | _ g | _g | _i | _g | _t | _i | _i | _| 	| dS )a]  Constructor for ResourceMethodParameters.

        Sets default values and defers to set_parameters to populate.

        Args:
          method_desc: Dictionary with metadata describing an API method. Value
              comes from the dictionary of methods stored in the 'methods' key in
              the deserialized discovery document.
        N)
argmaprequired_paramsrepeated_paramspattern_paramsquery_paramsr   path_paramsparam_typesenum_paramsset_parameters)r>   r   rB   rB   rC   r=     s    
z!ResourceMethodParameters.__init__c           
      C   sD  | di }tt| }| D ]\}}t|}|| j|< | drV|d | j|< | drn|d | j|< | dr| j	| | dr| j
	| | ddkr| j	| | ddkr| j| | d	d
| j|< q$t|d D ]N}t|dD ]8}t|d}	| j|	 |	| jkr| j|	 qqdS )a  Populates maps and lists based on method description.

        Iterates through each parameter for the method and parses the values from
        the parameter dictionary.

        Args:
          method_desc: Dictionary with metadata describing an API method. Value
              comes from the dictionary of methods stored in the 'methods' key in
              the deserialized discovery document.
        r   patternenumr0   repeatedr:   r9   r   r.   r/   r   N)r   r   sortedr   r   r   r   r   r   rW   r   r   r   addr   URITEMPLATEfinditerVARNAMEgroupremove)
r>   r   r   Zsorted_parametersargdescparammatch	namematchrR   rB   rB   rC   r    s0    




z'ResourceMethodParameters.set_parametersN)rD   rE   rF   __doc__r=   r  rB   rB   rB   rC   r     s   r   c                    s:  t t|	\ t 	f
dd}dtdg}tjdkrn|d t|di 	 }|
t tj	 }dd	 d
g D }d|kr|d t|D ]}	|	|kr||	 q|D ]}
|
|krqd}|
jkrd}d}|
jkrd}d j|
  }|dd}d|krh|d|
|||	|d f  n$|dd}|d|
||||f  |dg }|dg }|r|r|d t||D ]\}	}|d|	|f  qqdkr dr|d n|d |	d  t|dd| |fS )ae  Creates a method for attaching to a Resource.

    Args:
      methodName: string, name of the method to use.
      methodDesc: object, fragment of deserialized discovery document that
        describes the method.
      rootDesc: object, the entire deserialized discovery document.
      schema: object, mapping of schema names to schema descriptions.
    c           "   
      s  |    |D ]}|jkrtd|qt| }|D ]}|| d kr:||= q:jD ]0}||krX|tks|tt	
drXtd| qXj
 D ]^\}}||krt|| tr|| g}n|| }|D ]&}t||d krtd|||f qqj D ]l\}}||kr|jkr4t|| ts4|| }n
|| g}|D ]&}	|	|krBtd||	t|f qBqi }
i }| D ]\}}	j|d |jkrt|	tg krć fdd|	D }n
t|	 }|jkr||
j| < |jkr|||j| < q||d	d }|d
d }|dd }| jr<| j|
d< | j}drVt }ndkrft }dd }i }||||
||\}}}}t	|}t | j!|| }d }d}|rt|tr(|d krt"#d| t$%|\}}|d krt&|t'(|gd)st*|t+||d}nt|t,r:|}ntd|- d k	r||-   krldkr|n nt.d t|}t | j!|| }t/|| j!}|0 rt1|dd}|0 r|}n|d kr|2 |d< |3d|- }t1|dd}nt4d}t5|ddd  t6|d 7d }|8| |9| t6|2 7d }d|d < |3d|- }|8| |9| t:; } t<| d!d"}!|!j=|d!d# | > }|? }d$| |d< t1|dd%}t"@d&|f  | jA| jB|jC||||d'S )(Nz%Got an unexpected keyword argument {}responsezMissing required parameter "%s"z9Parameter "%s" value "%s" does not match the pattern "%s"z9Parameter "%s" value "%s" is not an allowed value in "%s"r/   c                    s   g | ]}t | qS rB   )r   ).0rS   Zto_typerB   rC   
<listcomp>  s     z0createMethod.<locals>.method.<locals>.<listcomp>rH   r   r   rZ   _mediar_   rT   zDmedia_mime_type argument not specified: trying to auto-detect for %s,)mimetypez*media_filename must be str or MediaUpload.r   zMedia larger than: %sZ
uploadType	resumablezcontent-typeZmediarelatedZ_write_headersc                 S   s   d S NrB   r>   rB   rB   rC   <lambda>      z.createMethod.<locals>.method.<locals>.<lambda>r   binaryzContent-Transfer-EncodingF)mangle_from_)unixfromz multipart/related; boundary="%s"	multipartzURL being requested: %s %s)methodrH   headersmethodIdr  )D_validate_credentialsr   	TypeErrorr   rU   r   r   _PAGE_TOKEN_NAMES_findPageTokenName_methodPropertiesr   r   r   r   rer  r   r   r   r   r.   r   r   r   _developerKey_modelr   r!   r"   r   rn   ro   r   _baseUrlr   r   	mimetypes
guess_typer   r   
best_matchrY   r   r   r   sizer   r   r  r   r  Zgetbytesr	   setattrr
   splitset_payloadattachioBytesIOrI   flattengetvalueget_boundaryr   _requestBuilder_httpr  )"r>   kwargsrR   r   regexZpvaluesZpvalueenumsvaluesr   Zactual_query_paramsZactual_path_paramsrZ   Z
cast_valueZ
body_valueZmedia_filenamer   re   api_versionr$  r{   r9   rH   Zexpanded_urlr   r  multipart_boundaryrL   r   ZmsgRootmsgpayloadfpg
r   r   r   ZmediaPathUrl
methodDescr%  
methodNamer   ZpathUrlr   r  rC   r#  C  s   



 






    

.






zcreateMethod.<locals>.methodr-   z

r   zArgs:
r   c                 S   s   g | ]}t |qS rB   )r   )r  srB   rB   rC   r    s     z createMethod.<locals>.<listcomp>ZparameterOrderrH   rT   z (repeated)z (required)zA parameter$refz<  %s: object, %s%s%s
    The object takes the form of:

%s

r.   r/   z  %s: %s, %s%s%s
r  ZenumDescriptionsz    Allowed values
z      %s - %s
r  r  z/
Returns:
  The media object as a string.

    z(
Returns:
  An object of the form:

    r  )r   r   r   r   DEFAULT_METHOD_DOCr   r   rW   rU   r   extendr   r  r   r   ZprettyPrintByNamezipr   ZprettyPrintSchemar3  rY   )rJ  rI  r   r   r#  ZdocsZskip_parametersZall_argsZargs_orderedrR   r  r  r0   Z	paramdescZparamdocZ	paramtyper  ZenumDescr  rB   rH  rC   createMethod-  s~    

 4






rP  r1   r2   c                    s"   t  fdd}|fS )a  Creates any _next methods for attaching to a Resource.

    The _next methods allow for easy iteration through list() responses.

    Args:
      methodName: string, name of the method to use.
      pageTokenName: string, name of request page token field.
      nextPageTokenName: string, name of response page token field.
      isPageTokenParameter: Boolean, True if request page token is a query
          parameter, False if request page token is a field of the request body.
    c                    s   | d}|sdS t|} rHt|j||_td|jf  nV| j}||j}||< |	||_t
|j|_d|jkr|jd= td|f  |S )a  Retrieves the next page of results.

        Args:
          previous_request: The request for the previous page. (required)
          previous_response: The response from the request for the previous page. (required)

        Returns:
          A request object that you can call 'execute()' on to request the next
          page. Returns None if there are no more items in the collection.
        NzNext page request URL: %s %szcontent-lengthzNext page request body: %s %s)r   r   r   urir   r   r-  ZdeserializerH   	serializer   Z	body_sizer$  )r>   Zprevious_requestZprevious_responser2   r   re   rH   isPageTokenParameterrJ  nextPageTokenNamepageTokenNamerB   rC   
methodNextI  s(    
  
z$createNextMethod.<locals>.methodNext)r   )rJ  rV  rU  rT  rW  rB   rS  rC   createNextMethod6  s    'rX  c                   @   s~   e Zd ZdZerejndfddZdd Zdd Z	d	d
 Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zdd ZdS )r   z(A class for interacting with a resource.rT   c
           
      C   sN   g | _ || _|| _|| _|| _|| _|| _|| _|| _|	| _	d| _
|   dS )a  Build a Resource from the API description.

        Args:
          http: httplib2.Http, Object to make http requests with.
          baseUrl: string, base URL for the API. All requests are relative to this
              URI.
          model: googleapiclient.Model, converts to and from the wire format.
          requestBuilder: class or callable that instantiates an
              googleapiclient.HttpRequest object.
          developerKey: string, key obtained from
              https://code.google.com/apis/console
          resourceDesc: object, section of deserialized discovery document that
              describes a resource. Note that the top level discovery document
              is considered a resource.
          rootDesc: object, the entire deserialized discovery document.
          schema: object, mapping of schema names to schema descriptions.
          universe_domain: string, the universe for the API. The default universe
          is "googleapis.com".
        FN)_dynamic_attrsr=  r.  r-  r,  r<  _resourceDesc	_rootDesc_schema_universe_domain_credentials_validated_set_service_methods)
r>   rc   r   re   rf   rd   r   r   r   r   rB   rB   rC   r=   v  s    zResource.__init__c                 C   s   | j | || j|< dS )zSets an instance attribute and tracks it in a list of dynamic attributes.

        Args:
          attr_name: string; The name of the attribute to be set
          value: The value being set on the object and tracked in the dynamic cache.
        N)rY  rW   __dict__)r>   	attr_namer   rB   rB   rC   _set_dynamic_attr  s    zResource._set_dynamic_attrc                 C   s(   t  | j}| jD ]
}||= q|d= |S )zTrim the state down to something that can be pickled.

        Uses the fact that the instance variable _dynamic_attrs holds attrs that
        will be wiped and restored on pickle serialization.
        rY  )r   r`  rY  )r>   Z
state_dictZdynamic_attrrB   rB   rC   __getstate__  s
    
zResource.__getstate__c                 C   s   | j | g | _|   dS )zReconstitute the state of the object from being pickled.

        Uses the fact that the instance variable _dynamic_attrs holds attrs that
        will be wiped and restored on pickle serialization.
        N)r`  r   rY  r_  )r>   staterB   rB   rC   __setstate__  s    zResource.__setstate__c                 C   s   | S r  rB   r  rB   rB   rC   	__enter__  s    zResource.__enter__c                 C   s   |    d S r  )ru   )r>   exc_typeexcexc_tbrB   rB   rC   __exit__  s    zResource.__exit__c                 C   s   | j   dS )zClose httplib2 connections.N)r=  ru   r  rB   rB   rC   ru     s    zResource.closec                 C   s<   |  | j| j| j | | j| j| j | | j| j d S r  )_add_basic_methodsrZ  r[  r\  _add_nested_resources_add_next_methodsr  rB   rB   rC   r_    s    zResource._set_service_methodsc           	         s   ||kr:d|d | ddf  d fdd	}| d| d|kr|d  D ]h\}}t||||\}}| ||| | j | d	d
rNt|d |||\}}| ||| | j qNd S )Nz%s%sr   Z	batchPathbatchc                    s   t |  dS )a  Create a BatchHttpRequest object based on the discovery document.

                Args:
                  callback: callable, A callback to be called for each response, of the
                    form callback(id, response, exception). The first parameter is the
                    request id, and the second is the deserialized response object. The
                    third is an apiclient.errors.HttpError exception object if an HTTP
                    error occurred while processing the request, or None if no error
                    occurred.

                Returns:
                  A BatchHttpRequest object based on the discovery document.
                )callback	batch_uri)r   )ro  rp  rB   rC   new_batch_http_request  s    z;Resource._add_basic_methods.<locals>.new_batch_http_requestrr  methodsZsupportsMediaDownloadFr  )N)r   rb  r   rP  __get__rA   )	r>   r   r   r   rr  rJ  rI  fixedMethodNamer#  rB   rq  rC   rk    s<    
        zResource._add_basic_methodsc           	         sT   d|krP fdd}|d   D ],\}}|||\}}| ||| | j q"d S )N	resourcesc                    s8   t | }  fdd}t|dd t|dd | |fS )a&  Create a method on the Resource to access a nested Resource.

                Args:
                  methodName: string, name of the method to use.
                  methodDesc: object, fragment of deserialized discovery document that
                    describes the method.
                c                    s&   t | j| j| j| j| j | jd	S )Nr   )r   r=  r.  r-  r,  r<  r]  r  )rI  r   r   rB   rC   methodResource  s    zTResource._add_nested_resources.<locals>.createResourceMethod.<locals>.methodResourcer  zA collection resource.Z__is_resource__T)r   r3  )rJ  rI  rw  r   r   )rI  rC   createResourceMethod  s
    z<Resource._add_nested_resources.<locals>.createResourceMethod)r   rb  rt  rA   )	r>   r   r   r   ry  rJ  rI  ru  r#  rB   rx  rC   rl    s     zResource._add_nested_resourcesc           
      C   s   d|krd S |d   D ]|\}}tt||d}|s6qd}t|di }|sbd}tt||d}|shqt|d |||\}}	| ||	| | j qd S )Nrs  r  Tr   Fr   _next)r   r)  r*  r   rX  rb  rt  rA   )
r>   r   r   rJ  rI  rU  rT  rV  ru  r#  rB   rB   rC   rm  )  s6    

 zResource._add_next_methodsc                 C   s2   t | jdd}tr&| jp(t| j|nd| _| jS )a  Validates client's and credentials' universe domains are consistent.

        Returns:
            bool: True iff the configured universe domain is valid.

        Raises:
            UniverseMismatchError: If the configured universe domain is not valid.
        rg   NT)r   r=  r   r^  r   Zcompare_domainsr]  )r>   rg   rB   rB   rC   r&  H  s    	zResource._validate_credentialsN)rD   rE   rF   r  r   r   r   r=   rb  rc  re  rf  rj  ru   r_  rk  rl  rm  r&  rB   rB   rB   rC   r   s  s   
.

-&r   c                    s   t  fddtD dS )zSearch field names for one like a page token.

    Args:
      fields: container of string, names of fields.

    Returns:
      First name that is either 'pageToken' or 'nextPageToken' if one exists,
      otherwise None.
    c                 3   s   | ]}| kr|V  qd S r  rB   )r  Z	tokenNamefieldsrB   rC   	<genexpr>i  s      z%_findPageTokenName.<locals>.<genexpr>N)nextr(  r{  rB   r{  rC   r)  ^  s    
 r)  c                 C   s0   |  |i }d|kr$| |d i }| di S )a  Get properties of a field in a method description.

    Args:
      methodDesc: object, fragment of deserialized discovery document that
        describes the method.
      schema: object, mapping of schema names to schema descriptions.
      name: string, name of top-level field in method description.

    Returns:
      Object representing fragment of deserialized discovery document
      corresponding to 'properties' field of object corresponding to named field
      in method description, if it exists, otherwise empty dict.
    rL  Z
properties)r   )rI  r   rR   r  rB   rB   rC   r*  m  s    r*  )NNr$   T)r1   r2   T)vr  
__future__r   
__author____all__r   r   collections.abcr   email.generatorr   Zemail.mime.multipartr	   Zemail.mime.nonmultipartr
   http.clientclientrs   r7  r   rO   loggingr/  r   r+  r   Zgoogle.api_core.client_optionsr   Zgoogle.auth.exceptionsr   Zgoogle.auth.transportr   Zgoogle.oauth2r   Zhttplib2rn   r   ImportErrorZgoogle.api_corer   r   Zgoogleapiclientr   r   Zgoogleapiclient._helpersr   r   Zgoogleapiclient.errorsr   r   r   r   r   r   Zgoogleapiclient.httpr   r   r   r   r   r   r   Zgoogleapiclient.modelr    r!   r"   Zgoogleapiclient.schemar#   ZRETRIES	getLoggerrD   r   compiler  r	  r   ZV1_DISCOVERY_URIr   rM  	frozensetr   r   r   r   r   r(  r3   r4   r5   r   r   r   r   r;   rQ   rI   r   r   r   rm   rp   r   r   r   r   r   r   r   r   r   r   r,   r   rP  rX  r   r)  r*  rB   rB   rB   rC   <module>   s  

 $	





	
      
T  ,)/Z     
= l