
    (ph
                       S r SSKJr  SrSSKrSSKJr  SSKrSSK	r	SSK
r
SSKrSSKrSSKrSSKrSSKrSSKrSSKrSSKr SSKr\R(                  rSSKJr  SSKJr  SSKJr  SSKJr  SS	K J!r!  SS
K J"r#  SSK$J%r%J&r&J'r'J(r(J)r)J*r*  SSK+J,r,  \
RZ                  " \.5      r/Sr0Sr1Sr2Sr3Sr4Sr5S r6S r7 " S S\5      r8 " S S\5      r9 " S S\5      r: " S S\:5      r; " S S\;5      r< " S S \;5      r= " S! S"\5      r> " S# S$\5      r? " S% S&\5      r@ " S' S(\5      rA " S) S*\5      rB " S+ S,\5      rC " S- S.\5      rD " S/ S0\5      rES1 rFS2 rGS3 rHg! \ a    \" 5       r GNf = f)4zClasses to encapsulate a single HTTP request.

The classes implement a command pattern, with every
object supporting an execute() method that does the
actual HTTP request.
    )absolute_importz$jcgregorio@google.com (Joe Gregorio)N)	Generator)MIMEMultipart)MIMENonMultipart)
FeedParser)_auth)_helpers)
BatchError	HttpErrorInvalidChunkSizeErrorResumableUploadErrorUnexpectedBodyErrorUnexpectedMethodError)	JsonModeli  @i   i  i  <   z https://www.googleapis.com/batchc                 J  ^ SnU S:  a  gU [         :X  a  gU [        R                  :X  a  U(       d  g [        R                  " UR                  S5      5      m[        T[        5      (       aZ  [        U4S jS 5       S5      nU(       a<  TS	   U   n[        U[        5      (       a  [        U5      S
:  a  US
   nSU;   a  US   nOTS
   S	   S   S   n [        R                  SU5        US;   a  gg! [        [        [        4 a    [        R                  SU5         gf = f)zDetermines whether a response should be retried.

Args:
  resp_status: The response status received.
  content: The response content body.

Returns:
  True if the response should be retried, otherwise False.
Ni  TFutf-8c              3   >   >#    U  H  nUTS    ;   d  M  Uv   M     g7f)errorN ).0kwdatas     G/var/www/html/venv/lib/python3.13/site-packages/googleapiclient/http.py	<genexpr>)_should_retry_response.<locals>.<genexpr>w   s&      "ABg. "As   	)errorsstatusmessage r   r   reasonr   z&Invalid JSON content from response: %sz*Encountered 403 Forbidden with reason "%s")userRateLimitExceededrateLimitExceeded)_TOO_MANY_REQUESTShttp_client	FORBIDDENjsonloadsdecode
isinstancedictnextlistlenUnicodeDecodeError
ValueErrorKeyErrorLOGGERwarning)resp_statuscontentr!   error_detail_keywordr   s       @r   _should_retry_responser7   P   s0    F c (( k+++	::gnnW56D$%% (,"A
 ($ (!']+?@F!&$//CK!O!'#v-%+H%5Fa)(3H=
 	CVL CC  #J9 	NNCWM	s   BC4 C4 4+D"!D"c                    Sn	Sn
Sn[        US-   5       H  nUS:  aD  U" 5       SU-  -  n[        R                  SUUUUUUU	(       a  U	R                  OU5        U" U5         SnU R                  " XV/UQ70 UD6u  pU(       a	  X:X  a  UeMx  [        U	R                  U
5      (       a  M    X4$    X4$ ! [
         a  nUn SnANGSnAf[        R                   a  nUn SnANeSnAf[         a  nUn SnANySnAf[         aD  n[        R                  R                  R                  UR                  5      S;  a  e Un SnANSnAf[        R                   a  nUn SnANSnAff = f)a{  Retries an HTTP request multiple times while handling errors.

If after all retries the request still fails, last error is either returned as
return value (for HTTP 5xx errors) or thrown (for ssl.SSLError).

Args:
  http: Http object to be used to execute request.
  num_retries: Maximum number of retries.
  req_type: Type of the request (used for logging retries).
  sleep, rand: Functions to sleep for random time between retries.
  uri: URI to be requested.
  method: HTTP method to be used.
  args, kwargs: Additional arguments passed to http.request.

Returns:
  resp, content - Response from the http request (may be HTTP 5xx).
N   r      zCSleeping %.2f seconds before retry %d of %d for %s: %s %s, after %s>   EPIPE	ETIMEDOUT
ECONNRESETECONNABORTEDECONNREFUSEDWSAETIMEDOUT)ranger2   r3   r   request_ssl_SSLErrorsockettimeoutConnectionErrorOSErrorerrno	errorcodegethttplib2ServerNotFoundErrorr7   )httpnum_retriesreq_typesleeprandurimethodargskwargsrespr5   	exception	retry_num
sleep_time	ssl_errorsocket_timeoutconnection_errorsocket_errorserver_not_found_errors                      r   _retry_requestr_      s^   ( DGI;?+	q=!Y,.JNNU#	 *	/I LLFtFvFMD: '%dkk7;;=q ,p =I  	"!I~~ 	' 'I 	)(I 	%
 ||%%)),*<*<= F  $I++ 	/.I	/sH   #B33
E%=CE%C""E%/C66E%:EE%E  E%c                   $    \ rS rSrSrS rS rSrg)MediaUploadProgress   zStatus of a resumable upload.c                     Xl         X l        g)zConstructor.

Args:
  resumable_progress: int, bytes sent so far.
  total_size: int, total bytes in complete upload, or None if the total
    upload size isn't known ahead of time.
Nresumable_progress
total_sizeselfre   rf   s      r   __init__MediaUploadProgress.__init__   s     #5$    c                     U R                   b;  U R                   S:w  a+  [        U R                  5      [        U R                   5      -  $ g)zPercent of upload completed, as a float.

Returns:
  the percentage complete as a float, returning 0.0 if the total size of
  the upload is unknown.
r           rf   floatre   rh   s    r   progressMediaUploadProgress.progress   ;     ??&4??a+?001E$//4JJJrk   rd   N__name__
__module____qualname____firstlineno____doc__ri   rq   __static_attributes__r   rk   r   ra   ra      s    '	%
rk   ra   c                   $    \ rS rSrSrS rS rSrg)MediaDownloadProgressi  zStatus of a resumable download.c                     Xl         X l        g)z{Constructor.

Args:
  resumable_progress: int, bytes received so far.
  total_size: int, total bytes in complete download.
Nrd   rg   s      r   ri   MediaDownloadProgress.__init__  s     #5$rk   c                     U R                   b;  U R                   S:w  a+  [        U R                  5      [        U R                   5      -  $ g)zPercent of download completed, as a float.

Returns:
  the percentage complete as a float, returning 0.0 if the total size of
  the download is unknown.
r   rm   rn   rp   s    r   rq   MediaDownloadProgress.progress  rs   rk   rd   Nrt   r   rk   r   r|   r|     s    )%
rk   r|   c                       \ rS rSrSrS rS rS rS rS r	S r
S	 r\R                  " S
5      SS j5       rS r\S 5       rSrg)MediaUploadi  aZ  Describes a media object to upload.

Base class that defines the interface of MediaUpload subclasses.

Note that subclasses of MediaUpload may allow you to control the chunksize
when uploading a media object. It is important to keep the size of the chunk
as large as possible to keep the upload efficient. Other factors may influence
the size of the chunk you use, particularly if you are working in an
environment where individual HTTP requests may have a hardcoded time limit,
such as under certain classes of requests under Google App Engine.

Streams are io.Base compatible objects that support seek(). Some MediaUpload
subclasses support using streams directly to upload data. Support for
streaming may be indicated by a MediaUpload sub-class and if appropriate for a
platform that stream will be used for uploading the media object. The support
for streaming is indicated by has_stream() returning True. The stream() method
should return an io.Base object that supports seek(). On platforms where the
underlying httplib module supports streaming, for example Python 2.6 and
later, the stream will be passed into the http library which will result in
less memory being used and possibly faster uploads.

If you need to upload media that can't be uploaded using any of the existing
MediaUpload sub-class then you can sub-class MediaUpload for your particular
needs.
c                     [        5       ezCChunk size for resumable uploads.

Returns:
  Chunk size in bytes.
NotImplementedErrorrp   s    r   	chunksizeMediaUpload.chunksize8  s     "##rk   c                     g).Mime type of the body.

Returns:
  Mime type.
application/octet-streamr   rp   s    r   mimetypeMediaUpload.mimetype@  s     *rk   c                     g)NSize of upload.

Returns:
  Size of the body, or None of the size is unknown.
Nr   rp   s    r   sizeMediaUpload.sizeH  s     rk   c                     g)QWhether this upload is resumable.

Returns:
  True if resumable upload or False.
Fr   rp   s    r   	resumableMediaUpload.resumableP  s     rk   c                     [        5       e)zGet bytes from the media.

Args:
  begin: int, offset from beginning of file.
  length: int, number of bytes to read, starting at begin.

Returns:
  A string of bytes read. May be shorter than length if EOF was reached
  first.
r   )rh   beginends      r   getbytesMediaUpload.getbytesX  s     "##rk   c                     g)Does the underlying upload support a streaming interface.

Streaming means it is an io.IOBase subclass that supports seek, i.e.
seekable() returns True.

Returns:
  True if the call to stream() will return an instance of a seekable io.Base
  subclass.
Fr   rp   s    r   
has_streamMediaUpload.has_streame  s     rk   c                     [        5       ezA stream interface to the data being uploaded.

Returns:
  The returned value is an io.IOBase subclass that supports seek, i.e.
  seekable() returns True.
r   rp   s    r   streamMediaUpload.streamq  s     "##rk   r9   Nc                     [        U 5      n[        R                  " U R                  5      nUb  U H  nX4	 M     UR                  US'   UR                  US'   [
        R                  " U5      $ )zUtility function for creating a JSON representation of a MediaUpload.

Args:
  strip: array, An array of names of members to not include in the JSON.

Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().
_class_module)typecopy__dict__ru   rv   r'   dumps)rh   striptdmembers        r   _to_jsonMediaUpload._to_jsonz  s\     JIIdmm$I  jj(||)zz!}rk   c                 "    U R                  5       $ )zCreate a JSON representation of an instance of MediaUpload.

Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().
r   rp   s    r   to_jsonMediaUpload.to_json  s     }}rk   c                     [         R                  " U5      nUS   n[        X3R                  S5      SS S9n[	        XBS   5      n[	        US5      nU" U5      $ )zUtility class method to instantiate a MediaUpload subclass from a JSON
representation produced by to_json().

Args:
  s: string, JSON from to_json().

Returns:
  An instance of the subclass of MediaUpload that was serialized with
  to_json().
r   .N)fromlistr   	from_json)r'   r(   
__import__splitgetattr)clssr   modulemklsr   s          r   new_from_jsonMediaUpload.new_from_json  sX     zz!}ivS(9#2(>?ah(C-	|rk   r   N)ru   rv   rw   rx   ry   r   r   r   r   r   r   r   util
positionalr   r   classmethodr   rz   r   rk   r   r   r     s`    4$*$
$ 
__Q &  rk   r   c                      ^  \ rS rSrSr\R                  " S5      \S4U 4S jj5       rS r	S r
S rS	 rS
 rS rS rS rSrU =r$ )MediaIoBaseUploadi  af  A MediaUpload for a io.Base objects.

Note that the Python file object is compatible with io.Base and can be used
with this class also.

  fh = BytesIO('...Some data to upload...')
  media = MediaIoBaseUpload(fh, mimetype='image/png',
    chunksize=1024*1024, resumable=True)
  farm.animals().insert(
      id='cow',
      name='cow.png',
      media_body=media).execute()

Depending on the platform you are working on, you may pass -1 as the
chunksize, which indicates that the entire file should be uploaded in a single
request. If the underlying platform supports streams, such as Python 2.6 or
later, then this can be very efficient as it avoids multiple connections, and
also avoids loading the entire file into memory before sending it. Note that
Google App Engine has a 5MB limit on request size, so you should never set
your chunksize larger than 5MB, or to -1.
   Fc                   > [         [        U ]  5         Xl        X l        US:X  d  US:  d
  [        5       eX0l        X@l        U R                  R                  S[        R                  5        U R                  R                  5       U l        g)a  Constructor.

Args:
  fd: io.Base or file object, The source of the bytes to upload. MUST be
    opened in blocking mode, do not use streams opened in non-blocking mode.
    The given stream must be seekable, that is, it must be able to call
    seek() on fd.
  mimetype: string, Mime-type of the file.
  chunksize: int, File will be uploaded in chunks of this many bytes. Only
    used if resumable=True. Pass in a value of -1 if the file is to be
    uploaded as a single chunk. Note that Google App Engine has a 5MB limit
    on request size, so you should never set your chunksize larger than 5MB,
    or to -1.
  resumable: bool, True if this is a resumable upload. False means upload
    in a single request.
r   r   N)superr   ri   _fd	_mimetyper   
_chunksize
_resumableseekosSEEK_ENDtell_size)rh   fdr   r   r   	__class__s        r   ri   MediaIoBaseUpload.__init__  sd    $ 	/1!R9q='))##a%XX]]_
rk   c                     U R                   $ r   )r   rp   s    r   r   MediaIoBaseUpload.chunksize       rk   c                     U R                   $ )r   )r   rp   s    r   r   MediaIoBaseUpload.mimetype  s     ~~rk   c                     U R                   $ )r   )r   rp   s    r   r   MediaIoBaseUpload.size  s     zzrk   c                     U R                   $ )r   )r   rp   s    r   r   MediaIoBaseUpload.resumable  r   rk   c                 n    U R                   R                  U5        U R                   R                  U5      $ )zGet bytes from the media.

Args:
  begin: int, offset from beginning of file.
  length: int, number of bytes to read, starting at begin.

Returns:
  A string of bytes read. May be shorted than length if EOF was reached
  first.
)r   r   read)rh   r   lengths      r   r   MediaIoBaseUpload.getbytes   s'     	exx}}V$$rk   c                     g)r   Tr   rp   s    r   r   MediaIoBaseUpload.has_stream  s     rk   c                     U R                   $ r   )r   rp   s    r   r   MediaIoBaseUpload.stream  s     xxrk   c                     [        S5      e)z%This upload type is not serializable.z&MediaIoBaseUpload is not serializable.r   rp   s    r   r   MediaIoBaseUpload.to_json#  s    !"JKKrk   )r   r   r   r   r   )ru   rv   rw   rx   ry   r   r   DEFAULT_CHUNK_SIZEri   r   r   r   r   r   r   r   r   rz   __classcell__r   s   @r   r   r     sY    , 
__Q/AU % %8%
L Lrk   r   c                   |   ^  \ rS rSrSr\R                  " S5      S\S4U 4S jj5       rS r	S r
\S	 5       rS
rU =r$ )MediaFileUploadi(  ab  A MediaUpload for a file.

Construct a MediaFileUpload and pass as the media_body parameter of the
method. For example, if we had a service that allowed uploading images:

  media = MediaFileUpload('cow.png', mimetype='image/png',
    chunksize=1024*1024, resumable=True)
  farm.animals().insert(
      id='cow',
      name='cow.png',
      media_body=media).execute()

Depending on the platform you are working on, you may pass -1 as the
chunksize, which indicates that the entire file should be uploaded in a single
request. If the underlying platform supports streams, such as Python 2.6 or
later, then this can be very efficient as it avoids multiple connections, and
also avoids loading the entire file into memory before sending it. Note that
Google App Engine has a 5MB limit on request size, so you should never set
your chunksize larger than 5MB, or to -1.
r:   NFc                    > SU l         Xl        [        U R                  S5      U l         Uc  [        R                  " U5      u  p%Uc  Sn[
        [        U ]  U R                   X#US9  g)aG  Constructor.

Args:
  filename: string, Name of the file.
  mimetype: string, Mime-type of the file. If None then a mime-type will be
    guessed from the file extension.
  chunksize: int, File will be uploaded in chunks of this many bytes. Only
    used if resumable=True. Pass in a value of -1 if the file is to be
    uploaded in a single chunk. Note that Google App Engine has a 5MB limit
    on request size, so you should never set your chunksize larger than 5MB,
    or to -1.
  resumable: bool, True if this is a resumable upload. False means upload
    in a single request.
Nrbr   r   r   )r   	_filenameopen	mimetypes
guess_typer   r   ri   )rh   filenamer   r   r   _r   s         r   ri   MediaFileUpload.__init__>  se    $ !-#..x8KH5ot-HHhy 	. 	
rk   c                 \    U R                   (       a  U R                   R                  5         g g r   )r   closerp   s    r   __del__MediaFileUpload.__del__]  s    88HHNN rk   c                 "    U R                  S/S9$ )zCreating a JSON representation of an instance of MediaFileUpload.

Returns:
   string, a JSON representation of this instance, suitable to pass to
   from_json().
r   )r   r   rp   s    r   r   MediaFileUpload.to_jsona  s     }}E7}++rk   c                 ^    [         R                  " U 5      n[        US   US   US   US   S9$ )Nr   r   r   r   )r   r   r   )r'   r(   r   )r   r   s     r   r   MediaFileUpload.from_jsonj  s8    JJqMkN{^oo	
 	
rk   )r   r   )ru   rv   rw   rx   ry   r   r   r   ri   r   r   staticmethodr   rz   r   r   s   @r   r   r   (  sK    * 
__Q!%1Cu
 
<, 
 
rk   r   c                   `   ^  \ rS rSrSr\R                  " S5      S\S4U 4S jj5       rSr	U =r
$ )MediaInMemoryUploadiu  z~MediaUpload for a chunk of bytes.

DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for
the stream.
r:   r   Fc                 V   > [         R                  " U5      n[        [        U ]  XRX4S9  g)a  Create a new MediaInMemoryUpload.

DEPRECATED: Use MediaIoBaseUpload with either io.TextIOBase or io.StringIO for
the stream.

Args:
  body: string, Bytes of body content.
  mimetype: string, Mime-type of the file or default of
    'application/octet-stream'.
  chunksize: int, File will be uploaded in chunks of this many bytes. Only
    used if resumable=True.
  resumable: bool, True if this is a resumable upload. False means upload
    in a single request.
r   N)ioBytesIOr   r  ri   )rh   bodyr   r   r   r   r   s         r   ri   MediaInMemoryUpload.__init__|  s-    , ZZ!41I 	2 	
rk   r   )ru   rv   rw   rx   ry   r   r   r   ri   rz   r   r   s   @r   r  r  u  s0     
__Q ,$
 
rk   r  c                       \ rS rSrSr\R                  " S5      \4S j5       r\R                  " S5      S	S j5       r	Sr
g)
MediaIoBaseDownloadi  a  "Download media resources.

Note that the Python file object is compatible with io.Base and can be used
with this class also.


Example:
  request = farms.animals().get_media(id='cow')
  fh = io.FileIO('cow.png', mode='wb')
  downloader = MediaIoBaseDownload(fh, request, chunksize=1024*1024)

  done = False
  while done is False:
    status, done = downloader.next_chunk()
    if status:
      print "Download %d%%." % int(status.progress() * 100)
  print "Download Complete!"
r   c                 d   Xl         X l        UR                  U l        X0l        SU l        SU l        SU l        [        R                  U l
        [        R                  U l        0 U l        UR                  R                  5        H)  u  pEUR!                  5       S;  d  M  XPR                  U'   M+     g)a
  Constructor.

Args:
  fd: io.Base or file object, The stream in which to write the downloaded
    bytes.
  request: googleapiclient.http.HttpRequest, the media request to perform in
    chunks.
  chunksize: int, File will be downloaded in chunks of this many bytes.
r   NF)acceptzaccept-encoding
user-agent)r   _requestrR   _urir   	_progress_total_size_donetimerP   _sleeprandom_rand_headersheadersitemslower)rh   r   rB   r   kvs         r   ri   MediaIoBaseDownload.__init__  s     KK	#
 jj]]
OO))+DA 779 KK#$a  ,rk   r9   c                 b   U R                   R                  5       nSU R                  U R                  U R                  -   S-
  4-  US'   U R                  R
                  n[        UUSU R                  U R                  U R                  SUS9u  pEUR                  S;   Ga   SU;   a  US   U R                  :w  a
  US   U l	        U =R                  [        U5      -  sl        U R                  R                  U5        S	U;   a+  US	   nUR                  S
S5      S   n[        U5      U l        OSU;   a  [        US   5      U l        U R                   b  U R                  U R                   :X  a  SU l        [%        U R                  U R                   5      U R"                  4$ UR                  S:X  am  US	   nUR                  S
S5      S   n[        U5      U l        U R                   S:X  a3  SU l        [%        U R                  U R                   5      U R"                  4$ ['        XEU R                  S9e)aX  Get the next chunk of the download.

Args:
  num_retries: Integer, number of times to retry with randomized
        exponential backoff. If all retries fail, the raised HttpError
        represents the last request. If zero (default), we attempt the
        request only once.

Returns:
  (status, done): (MediaDownloadProgress, boolean)
     The value of 'done' will be True when the media has been fully
     downloaded or the total size of the media is unknown.

Raises:
  googleapiclient.errors.HttpError if the response was not a 2xx.
  httplib2.HttpLib2Error if a transport error has occurred.
zbytes=%d-%dr9   rA   zmedia downloadGETr  )      zcontent-locationzcontent-range/content-lengthTi  r   rR   )r  r   r  r   r  rM   r_   r  r  r  r   r.   r   writersplitintr  r  r|   r   )rh   rN   r  rM   rV   r5   content_ranger   s           r   
next_chunkMediaIoBaseDownload.next_chunk  s   & --$$&(NNNNT__,q0,
 
 }}!!&KKJJII	
 ;;*$!T)d3E.F$)).S !34	NNc'l*NHHNN7#$& $_ 5&--c15a8#&v; !T)#&t,<'=#> '4>>T=M=M+M!
(9I9IJDJJVV[[C !1M"))#q1!4F"6{D1$!
)$..$:J:JKJJ  49955rk   )
r   r  r   r  r  r  r  r  r  r  N)r   )ru   rv   rw   rx   ry   r   r   r   ri   r+  rz   r   rk   r   r  r    sF    & 
__Q.@ % %< 
__Q@6 @6rk   r  c                   (    \ rS rSrSrS rSS jrSrg)_StreamSlicei  a  Truncated stream.

Takes a stream and presents a stream that is a slice of the original stream.
This is used when uploading media in chunks. In later versions of Python a
stream can be passed to httplib in place of the string of data to send. The
problem is that httplib just blindly reads to the end of the stream. This
wrapper presents a virtual stream that only reads to the end of the chunk.
c                 ^    Xl         X l        X0l        U R                   R                  U5        g)zConstructor.

Args:
  stream: (io.Base, file object), the stream to wrap.
  begin: int, the seek position the chunk begins at.
  chunksize: int, the size of the chunk.
N)_stream_beginr   r   )rh   r   r   r   s       r   ri   _StreamSlice.__init__  s%     #% rk   c                     U R                   R                  5       nU R                  U R                  -   nUS:X  d  X!-   U:  a  X2-
  nU R                   R	                  U5      $ )z{Read n bytes.

Args:
  n, int, the number of bytes to read.

Returns:
  A string of length 'n', or less if EOF is reached.
r   )r0  r   r1  r   r   )rh   ncurr   s       r   r   _StreamSlice.read&  sS     ll!kkDOO+7cgm	A||  ##rk   )r1  r   r0  N)r   )ru   rv   rw   rx   ry   ri   r   rz   r   rk   r   r.  r.    s    !$rk   r.  c                      \ rS rSrSr\R                  " S5           SS j5       r\R                  " S5      SS j5       r\R                  " S5      S	 5       r	\R                  " S5      SS
 j5       r
S rS r\S 5       r\S 5       rSrg)HttpRequesti7  z#Encapsulates a single HTTP request.   Nc	                 J   X0l         X@l        XPl        U=(       d    0 U l        Xpl        Xl        X l        Xl        / U l        SU l	        [        U R                  =(       d    S5      U l        SU l        SU l        [        R                  U l        [         R"                  U l        g)ah  Constructor for an HttpRequest.

Args:
  http: httplib2.Http, the transport object to use to make a request
  postproc: callable, called on the HTTP response and content to transform
            it into a data object before returning, or raising an exception
            on an error.
  uri: string, the absolute URI to send the request to
  method: string, the HTTP method to use
  body: string, the request body of the HTTP request,
  headers: dict, the HTTP request headers
  methodId: string, a unique identifier for the API method being called.
  resumable: MediaUpload, None if this is not a resumbale request.
Fr    Nr   )rR   rS   r  r  methodIdrM   postprocr   response_callbacks_in_error_stater.   	body_sizeresumable_urire   r  r  r  rP   r  )	rh   rM   r<  rR   rS   r  r  r;  r   s	            r   ri   HttpRequest.__init__:  s    4 	}" 	 ""$$ TYY_"- " #$ ]]
jjrk   r9   c                 T   Uc  U R                   nU R                  (       a  SnUc  U R                  XS9u  pCUc  M  U$ SU R                  ;  a"  [	        U R
                  5      U R                  S'   [        U R                  5      [        :  a  U R                  S:X  a  SU l	        SU R                  S'   SU R                  S'   [        R                  R                  U R                  5      n[        R                  R                  UR                  UR                  UR                   UR"                  SS45      U l        UR$                  U l        [	        [        U R&                  5      5      U R                  S'   [)        UUS	U R*                  U R,                  [	        U R                  5      [	        U R                  5      U R&                  U R                  S
9	u  pgU R.                   H  nU" U5        M     UR0                  S:  a  [3        XgU R                  S9eU R5                  Xg5      $ )am  Execute the request.

Args:
  http: httplib2.Http, an http object to be used in place of the
        one the HttpRequest request object was constructed with.
  num_retries: Integer, number of times to retry with randomized
        exponential backoff. If all retries fail, the raised HttpError
        represents the last request. If zero (default), we attempt the
        request only once.

Returns:
  A deserialized object model of the response body as determined
  by the postproc.

Raises:
  googleapiclient.errors.HttpError if the response was not a 2xx.
  httplib2.HttpLib2Error if a transport error has occurred.
N)rM   rN   r%  r   POSTx-http-method-overridez!application/x-www-form-urlencodedcontent-typerB   rS   r  r  ,  r&  )rM   r   r+  r  strr?  r.   rR   MAX_URI_LENGTHrS   urllibparseurlparse
urlunparseschemenetlocpathparamsqueryr  r_   r  r  r=  r   r   r<  )	rh   rM   rN   r  r   parsedrV   r5   callbacks	            r   executeHttpRequest.executel  s   ( <99D>>D,//t/M ,K 4<</-0-@DLL)* txx=>)dkkU.B DK5:DLL12+NDLL(\\**4884F||..v{{FMM4QUVDH DI-0TYY-@DLL)* 'KKJJMt{{#LL

 //HTN 0;;#Dtxx88}}T++rk   r:   c                 :    U R                   R                  U5        g)zadd_response_headers_callback

Args:
  cb: Callback to be called on receiving the response headers, of signature:

  def cb(resp):
    # Where resp is an instance of httplib2.Response
N)r=  append)rh   cbs     r   add_response_callback!HttpRequest.add_response_callback  s     	&&r*rk   c                    Uc  U R                   nU R                  R                  5       c  SnO#[        U R                  R                  5       5      nU R                  c  [
        R
                  " U R                  5      nU R                  R                  5       US'   US:w  a  X4S'   [        U R                  5      US'   [        UUSU R                  U R                  U R                  U R                  U R                  US9	u  pVUR                  S:X  a  SU;   a  US   U l        O^[!        XV5      eU R"                  (       aB  S	U-  S
S.nUR%                  U R                  SUS9u  pVU R'                  XV5      u  pU	(       a  X4$ U R                  R)                  5       (       a  U R                  R+                  5       n
U R                  R-                  5       S:X  aG  U
R/                  U R0                  5        U R                  R                  5       U R0                  -
  S-
  nGO[3        XR0                  U R                  R-                  5       5      n
[5        U R0                  U R                  R-                  5       -   S-
  U R                  R                  5       S-
  5      nOU R                  R7                  U R0                  U R                  R-                  5       5      n
[9        U
5      U R                  R-                  5       :  a!  [        U R0                  [9        U
5      -   5      nU R0                  [9        U
5      -   S-
  nS[        XR0                  -
  S-   5      0nUS:w  a  SU R0                  UU4-  US'   [;        US-   5       H  nUS:  a^  U R                  U R                  5       SU-  -  5        [<        R?                  SXR                  U R                  WR                  4-  5         UR%                  U R                  SXS9u  pV[A        UR                  U5      (       a  M    O   U R'                  WW5      $ !   SU l        e = f)a  Execute the next step of a resumable upload.

Can only be used if the method being executed supports media uploads and
the MediaUpload object passed in was flagged as using resumable upload.

Example:

  media = MediaFileUpload('cow.png', mimetype='image/png',
                          chunksize=1000, resumable=True)
  request = farm.animals().insert(
      id='cow',
      name='cow.png',
      media_body=media)

  response = None
  while response is None:
    status, response = request.next_chunk()
    if status:
      print "Upload %d%% complete." % int(status.progress() * 100)


Args:
  http: httplib2.Http, an http object to be used in place of the
        one the HttpRequest request object was constructed with.
  num_retries: Integer, number of times to retry with randomized
        exponential backoff. If all retries fail, the raised HttpError
        represents the last request. If zero (default), we attempt the
        request only once.

Returns:
  (status, body): (ResumableMediaStatus, object)
     The body will be None until the resumable media is fully uploaded.

Raises:
  googleapiclient.errors.HttpError if the response was not a 2xx.
  httplib2.HttpLib2Error if a transport error has occurred.
*zX-Upload-Content-TypezX-Upload-Content-Lengthr%  zresumable URI requestrF  r"  locationz
bytes */%s0)Content-Ranger%  PUTr!  r   r9   zContent-Lengthzbytes %d-%d/%sr`  r   r:   z7Retry #%d for media upload: %s %s, following status: %dT)!rM   r   r   rH  r@  r   r  r   r?  r_   r  r  rR   rS   r  r   r   r>  rB   _process_responser   r   r   r   re   r.  minr   r.   rA   r2   r3   r7   )rh   rM   rN   r   start_headersrV   r5   r  r   r  r   	chunk_endrX   s                r   r+  HttpRequest.next_chunk  s   N <99D>> (Dt~~**,-D% IIdll3M59^^5L5L5NM12s{;?78.1$...AM*+*'

{{YY%
MD {{c!jD&8%)*%5"*499!! )5t(;sSG LL););UGLTMD11$@LF~%>>$$&&>>((*D~~'')R/		$112 NN//1D4K4KKaO	 $114>>3K3K3M  ++dnn.F.F.HH1LNN'')A-	
 >>**'')A)A)CD
 4y4>>3355422SY>?//#d);a?I
 c).E.E"E"IJ
 ?'7''; (GO$ {Q/I1}DJJL1i<78M ++txxEF
 $&&u4 !- ! *$++w??! 0$ %%dG44'+$s   +P;;
Qc                    UR                   S;   a  SU l        SU R                  X5      4$ UR                   S:X  aA  SU l         [        US   R	                  S5      S   5      S-   U l        S	U;   a
  US	   U l        OS
U l        [        XU R                  S9e[        U R
                  U R                  R                  5       5      S4$ ! [         a
    SU l         Nof = f)ao  Process the response from a single chunk upload.

Args:
  resp: httplib2.Response, the response object.
  content: string, the content of the response.

Returns:
  (status, body): (ResumableMediaStatus, object)
     The body will be None until the resumable media is fully uploaded.

Raises:
  googleapiclient.errors.HttpError if the response was not a 2xx or a 308.
)r"     FN4  rA   -r9   r   r^  Tr&  )r   r>  r<  r)  r   re   r1   r@  r   rR   ra   r   r   )rh   rV   r5   s      r   rb  HttpRequest._process_responseG  s     ;;*$#(D t555[[C#(D ,*-d7m.A.A#.Fq.I*JQ*N' T!%)*%5"#'D Dtxx88   7 79L9L9NO
 	
  ,*+',s   (C CCc                     [         R                   " U R                  5      nUS   b  U R                  R                  5       US'   US	 US	 US	 US	 [        R
                  " U5      $ )z1Returns a JSON representation of the HttpRequest.r   rM   r<  r  r  )r   r   r   r   r'   r   )rh   r   s     r   r   HttpRequest.to_jsonk  s^    IIdmm$[>%!^^335AkNfIjMhKgJzz!}rk   c                     [         R                  " U 5      nUS   b  [        R                  US   5      US'   [	        UUUS   US   US   US   US   US   S9$ )z>Returns an HttpRequest populated with info from a JSON object.r   rR   rS   r  r  r;  )rR   rS   r  r  r;  r   )r'   r(   r   r   r8  )r   rM   r<  r   s       r   r   HttpRequest.from_jsonw  sp     JJqM[>%(66q~FAkN%X;6iLz]n	
 		
rk   c                     X4$ r   r   )rV   contentss     r   null_postprocHttpRequest.null_postproc  s
    ~rk   )r>  r  r  r  r?  r  rM   rS   r;  r<  r=  r   re   r@  rR   r   NNNN)Nr   )ru   rv   rw   rx   ry   r   r   ri   rU  rZ  r+  rb  r   r  r   rr  rz   r   rk   r   r8  r8  7  s    -	__Q /! /!b 
__Q>, >,@ 
__Q	+ 	+ 
__QK5 K5Z"
H
 
 
   rk   r8  c                       \ rS rSrSr\R                  " S5      SS j5       rS rS r	S r
S	 rS
 rS r\R                  " S5      SS j5       rS r\R                  " S5      SS j5       rSrg)BatchHttpRequesti  a:  Batches multiple HttpRequest objects into a single HTTP request.

Example:
  from googleapiclient.http import BatchHttpRequest

  def list_animals(request_id, response, exception):
    """Do something with the animals list response."""
    if exception is not None:
      # Do something with the exception.
      pass
    else:
      # Do something with the response.
      pass

  def list_farmers(request_id, response, exception):
    """Do something with the farmers list response."""
    if exception is not None:
      # Do something with the exception.
      pass
    else:
      # Do something with the response.
      pass

  service = build('farm', 'v2')

  batch = BatchHttpRequest()

  batch.add(service.animals().list(), list_animals)
  batch.add(service.farmers().list(), list_farmers)
  batch.execute(http=http)
r9   Nc                     Uc  [         nU[         :X  a  [        R                  S[         5        X l        Xl        0 U l        0 U l        / U l        SU l        SU l	        0 U l
        0 U l        g)a  Constructor for a BatchHttpRequest.

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 googleapiclient.errors.HttpError exception object if an HTTP error
    occurred while processing the request, or None if no error occurred.
  batch_uri: string, URI to send batch requests to.
Na  You have constructed a BatchHttpRequest using the legacy batch endpoint %s. This endpoint will be turned down on August 12, 2020. Please provide the API-specific endpoint or use service.new_batch_http_request(). For more details see https://developers.googleblog.com/2018/03/discontinuing-support-for-json-rpc-and.htmland https://developers.google.com/api-client-library/python/guide/batch.r   )_LEGACY_BATCH_URIr2   r3   
_batch_uri	_callback	_requests
_callbacks_order_last_auto_id_base_id
_responses_refreshed_credentials)rh   rT  	batch_uris      r   ri   BatchHttpRequest.__init__  s~     )I))NN[ " $ "       ')#rk   c                    SnSnUR                   b"  [        R                  " UR                   5      nSnUc  Ub  [        R                  " U5      nUbG  [        U5      U R                  ;  a.  [        R
                  " U5        SU R                  [        U5      '   UR                   b  U(       d!  [        R                  " X1R                  5        gg)zRefresh the credentials and apply to the request.

Args:
  request: HttpRequest, the request.
  http: httplib2.Http, the global http object for the batch.
NFTr9   )rM   r   get_credentials_from_httpidr  refresh_credentialsapply_credentialsr  )rh   rB   rM   credsrequest_credentialss        r   _refresh_and_apply_credentials/BatchHttpRequest._refresh_and_apply_credentials  s     #<<#33GLLAE"&=T-33D9E%y ; ;;))%09:++BuI6 <<':##E??; (;rk   c                     U R                   c  [        R                  " 5       U l         SU R                   < S[        R                  R                  U5      < S3$ )a	  Convert an id to a Content-ID header value.

Args:
  id_: string, identifier of individual request.

Returns:
  A Content-ID header with the id_ encoded into it. A UUID is prepended to
  the value because Content-ID headers are supposed to be universally
  unique.
< + >)r  uuiduuid4rJ  rK  quote)rh   id_s     r   _id_to_headerBatchHttpRequest._id_to_header  s<     ==  JJLDM
 #mmV\\-?-?-DEErk   c                     US   S:w  d	  US   S:w  a  [        SU-  5      eSU;  a  [        SU-  5      eUSS R                  SS5      u  p#[        R                  R	                  U5      $ )	a  Convert a Content-ID header value to an id.

Presumes the Content-ID header conforms to the format that _id_to_header()
returns.

Args:
  header: string, Content-ID header value.

Returns:
  The extracted id value.

Raises:
  BatchError if the header is not in the expected format.
r   r  r   r  z Invalid value for Content-ID: %s+r9   r  )r
   r   rJ  rK  unquote)rh   headerbaser  s       r   _header_to_idBatchHttpRequest._header_to_id  st     !9vbzS0?&HIIf?&HII1RL&&ua0	||##C((rk   c                    [         R                  R                  UR                  5      n[         R                  R	                  SSUR
                  UR                  UR                  S45      nUR                  S-   U-   S-   nUR                  R                  SS5      R                  S5      u  pV[        XV5      nUR                  R                  5       nUR                  b9  [        R                   " UR                  5      n	U	b  [        R"                  " X5        SU;   a  US	 UR%                  5        H	  u  pXU
'   M     UR&                  US'   UR)                  S5        UR*                  b<  UR-                  UR*                  5        [/        [1        UR*                  5      5      US	'   [2        R4                  " 5       n[7        US
S9nUR9                  USS9  UR;                  5       nXN-   $ )zConvert an HttpRequest object into a string.

Args:
  request: HttpRequest, the request to serialize.

Returns:
  The request as a string in application/http format.
r     z
 HTTP/1.1
rE  zapplication/jsonr$  NHostr%  r   )maxheaderlenFunixfrom)rJ  rK  rL  rR   rM  rP  rQ  rR  rS   r  rJ   r   r   r   rM   r   r  r  r  rO  set_unixfromr  set_payloadrH  r.   r  StringIOr   flattengetvalue)rh   rB   rS  request_linestatus_linemajorminormsgr  credentialskeyvaluefpgr  s                  r   _serialize_request#BatchHttpRequest._serialize_request)  s    &&w{{3||..V[[&--rB
 nns*\9MI**>;MNTT
 u,//&&(<<#99',,GK&''= W$'!--/JCH *mmF<<#OOGLL)$'GLL(9$:C ! [[]bq)			#	&{{}!!rk   c                    UR                  SS5      u  p!UR                  SS5      u  p4n[        5       nUR                  U5        UR                  5       nXGS'   [        R
                  " U5      nXXl        [        UR                  SS5      S   R                  SS5      5      Ul	        UR                  S	S5      S   n	X4$ )
zConvert string into httplib2 response and content.

Args:
  payload: string, headers and body as a string.

Returns:
  A pair (resp, content), such as would be returned from httplib2.request.

r9   r  r:   r   r$  r   r    z

)
r   r   feedr   rK   Responser!   r)  replaceversion)
rh   payloadr  protocolr   r!   parserr  rV   r5   s
             r   _deserialize_response&BatchHttpRequest._deserialize_responseY  s      '}}T15#.#4#4S!#< & GllnH   %8>>#q1!4<<S"EF--
A.q1}rk   c                    U =R                   S-  sl         [        U R                   5      U R                  ;   a:  U =R                   S-  sl         [        U R                   5      U R                  ;   a  M:  [        U R                   5      $ )z~Create a new id.

Auto incrementing number that avoids conflicts with ids already used.

Returns:
   string, a new unique id.
r9   )r~  rH  r{  rp   s    r   _new_idBatchHttpRequest._new_idu  sg     	a$$$%7!# $$$%74%%&&rk   r:   c                 `   [        U R                  5      [        :  a  [        S[        -  5      eUc  U R	                  5       nUR
                  b  [        S5      eX0R                  ;   a  [        SU-  5      eXR                  U'   X R                  U'   U R                  R                  U5        g)a  Add a new request.

Every callback added will be paired with a unique id, the request_id. That
unique id will be passed back to the callback when the response comes back
from the server. The default behavior is to have the library generate it's
own unique id. If the caller passes in a request_id then they must ensure
uniqueness for each request_id, and if they are not an exception is
raised. Callers should either supply all request_ids or never supply a
request id, to avoid such an error.

Args:
  request: HttpRequest, Request to add to the batch.
  callback: callable, A callback to be called for this 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 googleapiclient.errors.HttpError exception object if an HTTP error
    occurred while processing the request, or None if no errors occurred.
  request_id: string, A unique id for the request. The id will be passed
    to the callback with the response.

Returns:
  None

Raises:
  BatchError if a media request is added to a batch.
  KeyError is the request_id is not unique.
z9Exceeded the maximum calls(%d) in a single batch request.Nz1Media requests cannot be used in a batch request.z)A request with this ID already exists: %s)
r.   r}  MAX_BATCH_LIMITr
   r  r   r{  r1   r|  rX  )rh   rB   rT  
request_ids       r   addBatchHttpRequest.add  s    < t{{.K!"  J(PQQ'FSTT%,z"&.
#:&rk   c                    [        S5      n[        USS 5        U H_  nX5   n[        SS5      nSUS'   U R                  U5      US'   U R	                  U5      nUR                  U5        UR                  U5        Ma     [        R                  " 5       n	[        U	S	S
9n
U
R                  US	S9  U	R                  5       n0 nSUR                  5       -  US'   UR                  U R                  SXS9u  pUR                  S:  a  [!        XU R                  S9eSUS   -  nUR#                  S5      nX-   n[%        5       nUR'                  U5        UR)                  5       nUR+                  5       (       d
  [-        SXS9eUR/                  5        Hp  nU R1                  US   5      nU R3                  UR/                  5       5      u  nn[5        U[6        5      (       a  UR9                  S5      nUU4U R:                  U'   Mr     g)a  Serialize batch request, send to server, process response.

Args:
  http: httplib2.Http, an http object to be used to make the request with.
  order: list, list of request ids in the order they were added to the
    batch.
  requests: list, list of request objects to send.

Raises:
  httplib2.HttpLib2Error if a transport error has occurred.
  googleapiclient.errors.BatchError if the response is the wrong format.
mixed_write_headersc                     g r   r   rp   s    r   <lambda>+BatchHttpRequest._execute.<locals>.<lambda>  s    rk   applicationrM   binaryzContent-Transfer-Encodingz
Content-IDF)mangle_from_r  zmultipart/mixed; boundary="%s"rE  rC  rF  rG  r&  zcontent-type: %s

r   z'Response not in multipart/mixed format.)rV   r5   N)r   setattrr   r  r  r  attachr  r  r   r  r  get_boundaryrB   ry  r   r   r)   r   r  r   is_multipartr
   get_payloadr  r  r*   rH  encoder  )rh   rM   orderrequestsr   r  rB   r  r  r  r  r  rV   r5   r  
for_parserr  mime_responsepartresponses                       r   _executeBatchHttpRequest._execute  s     ()+<=  J*G"=&9C/7C+, $ 2 2: >C**73DOOD!NN3   [[]bu-			'E	*{{}/  "## OOF % 
 ;;#Dt?? ,d>.BB ..)%
J))++9  "--/D++D,>?J $ : :4;K;K;M NHg'3''!..1+3W*=DOOJ' 0rk   c                 P   [        U R                  5      S:X  a  gUc3  U R                   H#  nU R                  U   nUc  M  UR                  n  O   Uc  [	        S5      e[
        R                  " U5      nUbF  [
        R                  " U5      (       d+  [        R                  S5        [
        R                  " U5        U R                  XR                  U R                  5        0 n/ nU R                   HT  nU R                  U   u  pxUS   S:X  d  M  UR                  U5        U R                  U   nU R                  X15        X5U'   MV     U(       a  U R                  XU5        U R                   H  nU R                  U   u  pxU R                  U   nU R                  U   n	Sn
Sn UR                   S:  a  [#        XxUR$                  S9eUR'                  Xx5      n
U	b	  U	" X*U5        U R(                  c  M  U R)                  X*U5        M     g! ["         a  nUn SnANCSnAff = f)	a  Execute all the requests as a single batched HTTP request.

Args:
  http: httplib2.Http, an http object to be used in place of the one the
    HttpRequest request object was constructed with. If one isn't supplied
    then use a http object from the requests in this batch.

Returns:
  None

Raises:
  httplib2.HttpLib2Error if a transport error has occurred.
  googleapiclient.errors.BatchError if the response is the wrong format.
r   NzMissing a valid http object.z1Attempting refresh to obtain initial access_tokenr   401rG  r&  )r.   r}  r{  rM   r0   r   r  is_validr2   infor  r  r  rX  r  r|  r   r   rR   r<  rz  )rh   rM   r  rB   r  redo_requests
redo_orderrV   r5   rT  r  rW   es                r   rU  BatchHttpRequest.execute  s   " t{{q  <"kk
..4&"<<D	 * <;<< //5>>%((OP))%0dKK8 
++J OOJ7MDH~&!!*-..433GB,3j) & MM$M: ++J OOJ7MDnnZ0Gz2HHI;;#%#Dw{{CC"++D: #y9~~)zY?% &  	s   (5H
H%H  H%)	r  ry  rz  r|  r~  r}  r  r{  r  NNr   )ru   rv   rw   rx   ry   r   r   ri   r  r  r  r  r  r  r  r  rU  rz   r   rk   r   rv  rv    s    @ 
__Q0) 0)d<<F&).."`8' 
__Q*' *'XF>P 
__QN@ N@rk   rv  c                   (    \ rS rSrSrS rSS jrSrg)HttpRequestMockiI  zQMock of HttpRequest.

Do not construct directly, instead use RequestMockBuilder.
c                     Xl         X l        X0l        Uc  [        R                  " SSS.5      U l         SU R                   ;   a  U R                   S   U R                   l        gg)a)  Constructor for HttpRequestMock

Args:
  resp: httplib2.Response, the response to emulate coming from the request
  content: string, the response body
  postproc: callable, the post processing function usually supplied by
            the model class. See model.JsonModel.response() as an example.
Nr"  OK)r   r!   r!   )rV   r5   r<  rK   r  r!   )rh   rV   r5   r<  s       r   ri   HttpRequestMock.__init__O  sU     	 < ))SD*IJDItyy #yy2DII !rk   Nc                 N    U R                  U R                  U R                  5      $ )zExecute the request.

Same behavior as HttpRequest.execute(), but the response is
mocked and not really from an HTTP request/response.
)r<  rV   r5   )rh   rM   s     r   rU  HttpRequestMock.execute`  s     }}TYY55rk   )r5   r<  rV   r   )ru   rv   rw   rx   ry   ri   rU  rz   r   rk   r   r  r  I  s    
3"6rk   r  c                   6    \ rS rSrSrSS jr     SS jrSrg)	RequestMockBuilderii  a  A simple mock of HttpRequest

Pass in a dictionary to the constructor that maps request methodIds to
tuples of (httplib2.Response, content, opt_expected_body) that should be
returned when that method is called. None may also be passed in for the
httplib2.Response, in which case a 200 OK response will be generated.
If an opt_expected_body (str or dict) is provided, it will be compared to
the body and UnexpectedBodyError will be raised on inequality.

Example:
  response = '{"data": {"id": "tag:google.c...'
  requestBuilder = RequestMockBuilder(
    {
      'plus.activities.get': (None, response),
    }
  )
  googleapiclient.discovery.build("plus", "v1", requestBuilder=requestBuilder)

Methods that you do not supply a response for will return a
200 OK with an empty string as the response content or raise an excpetion
if check_unexpected is set to True. The methodId is taken from the rpcName
in the discovery document.

For more details see the project wiki.
c                     Xl         X l        g)a  Constructor for RequestMockBuilder

The constructed object should be a callable object
that can replace the class HttpResponse.

responses - A dictionary that maps methodIds into tuples
            of (httplib2.Response, content). The methodId
            comes from the 'rpcName' field in the discovery
            document.
check_unexpected - A boolean setting whether or not UnexpectedMethodError
                   should be raised on unsupplied method.
N)	responsescheck_unexpected)rh   r  r  s      r   ri   RequestMockBuilder.__init__  s     # 0rk   Nc	                    XpR                   ;   a  U R                   U   n	U	SS u  p[        U	5      S:  ay  U	S   n[        U5      [        U5      :w  a  [        X5      e[	        U[
        5      (       a  [        R                  " U5      n[        R                  " U5      nX\:w  a  [        X5      e[        XU5      $ U R                  (       a	  [        US9e[        S5      n[        SSUR                  5      $ )zImplements the callable interface that discovery.build() expects
of requestBuilder, which is to build an object compatible with
HttpRequest.execute(). See that method for the description of the
parameters and the expected response.
Nr:   )r;  Fz{})r  r.   boolr   r*   rH  r'   r(   r  r  r   r   r  )rh   rM   r<  rR   rS   r  r  r;  r   r  rV   r5   expected_bodymodels                 r   __call__RequestMockBuilder.__call__  s      ~~%~~h/H$RaLMD8}q  (&$t*4 .mBBmS11$(JJ}$=Mzz$'(-mBB"4(;;""'::e$E"4u~~>>rk   )r  r  )Frt  )ru   rv   rw   rx   ry   ri   r  rz   r   rk   r   r  r  i  s"    41* $?rk   r  c                   <    \ rS rSrSrSS jr     S	S jrS rSrg)
HttpMocki  zMock of httplib2.HttpNc                     Uc  SS0nU(       a+  [        US5       nUR                  5       U l        SSS5        OSU l        X l        SU l        SU l        SU l        SU l        SU l        g! , (       d  f       N8= f)zs
Args:
  filename: string, absolute filename to read response from
  headers: dict, header to return with response
Nr   200r   )r   r   r   response_headersr  rR   rS   r  )rh   r   r  fs       r   ri   HttpMock.__init__  sr     ?'Gh%FFH	 &% DI '	 &%s   A++
A9c                     Xl         X l        X0l        X@l        [        R
                  " U R                  5      U R                  4$ r   )rR   rS   r  r  rK   r  r  r   )rh   rR   rS   r  r  redirectionsconnection_types          r   rB   HttpMock.request  s8     	  !6!67BBrk   c                     g r   r   rp   s    r   r   HttpMock.close  s    rk   )r  r   r  rS   r  rR   r  r   NNr9   N)	ru   rv   rw   rx   ry   ri   rB   r   rz   r   rk   r   r  r    s&    . Crk   r  c                   2    \ rS rSrSrS r     SS jrSrg)HttpMockSequencei  al  Mock of httplib2.Http

Mocks a sequence of calls to request returning different responses for each
call. Create an instance initialized with the desired response headers
and content and then use as if an httplib2.Http instance.

  http = HttpMockSequence([
    ({'status': '401'}, ''),
    ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
    ({'status': '200'}, 'echo_request_headers'),
    ])
  resp, content = http.request("http://examples.com")

There are special values you can pass in for content to trigger
behavours that are helpful in testing.

'echo_request_headers' means return the request headers in the response body
'echo_request_headers_as_json' means return the request headers in
   the response body
'echo_request_body' means return the request body in the response body
'echo_request_uri' means return the request uri in the response body
c                 <    Xl         SU l        [        5       U l        g)zD
Args:
  iterable: iterable, a sequence of pairs of (headers, body)
TN)	_iterablefollow_redirectsr-   request_sequence)rh   iterables     r   ri   HttpMockSequence.__init__  s    
 " $ $rk   Nc                    U R                   R                  XX445        U R                  R                  S5      u  px[	        U[
        5      (       a  UR                  S5      nUS:X  a  UnOPUS:X  a  [        R                  " U5      nO3US:X  a%  [        US5      (       a  UR                  5       nOUnOUS:X  a  Un[	        U[
        5      (       a  UR                  S5      n[        R                  " U5      U4$ )Nr   r   s   echo_request_headerss   echo_request_headers_as_jsons   echo_request_bodyr   s   echo_request_uri)r  rX  r  popr*   rH  r  r'   r   hasattrr   rK   r  )	rh   rR   rS   r  r  r  r  rV   r5   s	            r   rB   HttpMockSequence.request  s     	$$c4%AB**1-gs##nnW-G--G77jj)G,,tV$$))+++Ggs##nnW-G  &//rk   )r  r  r  r  )ru   rv   rw   rx   ry   ri   rB   rz   r   rk   r   r
  r
    s"    .' 0rk   r
  c                 f   ^^ U R                   mSSS[        R                  S4UU4S jjnX l         U $ )a  Set the user-agent on every request.

Args:
   http - An instance of httplib2.Http
       or something that acts like it.
   user_agent: string, the value for the user-agent header.

Returns:
   A modified instance of http that was passed in.

Example:

  h = httplib2.Http()
  h = set_user_agent(h, "my-app-name/6.0")

Most of the time the user-agent will be set doing auth, this is for the rare
cases where you are accessing an unauthenticated endpoint.
r   Nc           	      b   > Uc  0 nSU;   a  T	S-   US   -   US'   OT	US'   T" U UUUUUS9u  pgXg4$ )1Modify the request headers to add the user-agent.r  r  rS   r  r  r  r  r   )
rR   rS   r  r  r  r  rV   r5   request_orig
user_agents
           r   new_request#set_user_agent.<locals>.new_request;  sb     ?G7"$.$4w|7L$LGL!$.GL!$%+
 }rk   rB   rK   DEFAULT_MAX_REDIRECTS)rM   r  r  r  s    ` @r   set_user_agentr  %  s;    & <<L
 33 2 LKrk   c                 b   ^ U R                   mSSS[        R                  S4U4S jjnXl         U $ )a  Tunnel PATCH requests over POST.
Args:
   http - An instance of httplib2.Http
       or something that acts like it.

Returns:
   A modified instance of http that was passed in.

Example:

  h = httplib2.Http()
  h = tunnel_patch(h, "my-app-name/6.0")

Useful if you are running on a platform that doesn't support PATCH.
Apply this last if you are using OAuth 1.0, as changing the method
will result in a different signature.
r   Nc           	         > Uc  0 nUS:X  a2  SUR                  SS5      ;   a  [        R                  S5        SUS'   SnT" U UUUUUS9u  pgXg4$ )	r  PATCHoauth_tokenauthorizationr    z;OAuth 1.0 request made with Credentials after tunnel_patch.rD  rC  r  )rJ   r2   r3   )	rR   rS   r  r  r  r  rV   r5   r  s	           r   r  !tunnel_patch.<locals>.new_requestm  ss     ?GWOR @@Q 18G,-F$%+
 }rk   r  )rM   r  r  s     @r   tunnel_patchr&  X  s6    $ <<L
 338 LKrk   c                      [         R                  " 5       b  [         R                  " 5       n O[        n [        R                  " U S9n UR
                  S1-
  Ul        U$ ! [         a     U$ f = f)zBuilds httplib2.Http object

Returns:
A httplib2.Http object, which is used to make http requests, and which has timeout set by default.
To override default timeout call

  socket.setdefaulttimeout(timeout_in_sec)

before interacting with this method.
)rE   ri  )rD   getdefaulttimeoutDEFAULT_HTTP_TIMEOUT_SECrK   Httpredirect_codesAttributeError)http_timeoutrM   s     r   
build_httpr.    sp     !-//1/==.D
"11SE9 K  
 	Ks   A 
A-,A-)Iry   
__future__r   
__author__r   http.clientclientr%   r  r'   loggingr   r   r  rD   r  rJ  r  rK   sslSSLErrorrC   ImportErrorobjectemail.generatorr   email.mime.multipartr   email.mime.nonmultipartr   email.parserr   googleapiclientr   r	   r   googleapiclient.errorsr
   r   r   r   r   r   googleapiclient.modelr   	getLoggerru   r2   r   rI  r  r$   r)  rx  r7   r_   ra   r|   r   r   r   r  r  r.  r8  rv  r  r  r  r
  r  r&  r.  r   rk   r   <module>r@     s   '3
  ! 	    	      ! LLM % . 4 # ! ,  ,			8	$&   6 CLOd& 6F 4L& L^yL yLxJ
' J
Z 
+  
Ft6& t6n%$6 %$PS& Sl
y@v y@x6f 6@O? O?d'v 'T=0v =0@0f2jE;  HMs   E E%$E%