KGRKJGETMRETU895U-589TY5MIGM5JGB5SDFESFREWTGR54TY
Server : Apache/2.2.17 (Unix) mod_ssl/2.2.17 OpenSSL/0.9.8e-fips-rhel5 DAV/2 PHP/5.2.17
System : Linux localhost 2.6.18-419.el5 #1 SMP Fri Feb 24 22:47:42 UTC 2017 x86_64
User : nobody ( 99)
PHP Version : 5.2.17
Disable Function : NONE
Directory :  /proc/21573/root/usr/lib/python2.4/site-packages/urlgrabber/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : //proc/21573/root/usr/lib/python2.4/site-packages/urlgrabber/grabber.pyc
m
ArMc
@sdZdkZdkZdkZdkZdkZdkZdkZdkZdk	Z	dk
Z
dkTy!dei
ddddUWn
dZnXdkZe
ie
iZydklZWnej
oZd	ZnXyd
klZWnej
oZeZnXydklZWnej
oZeZnXy/dkZdklZlZeZeZ Wnej
oZe!Z nXy>dk"Z"d
k"l#Z#l$Z$l%Z%l&Z&l'Z'l(Z(l)Z)Wn'ej
oZfZ*eZ)dZ+n&Xe#e$e%e&fZ*dZ+dk,Z,ye,i-Z.eZ/Wne0j
oeZ.e!Z/nXea1dZ2dZ3e3de4fdYZ5dfdYZ6edZ7dZ8edZ9dfdYZ:dfdYZ;dfdYZ<e<Z=dfdYZ>gZ?ed Z@gZAd!ZBd"ZCd#ZDd$ZEd%ZFeddeeed&d'd(d)d*d+d,ged-	ZGd.ZHd/ZIed0ZJd1ZKd2ZLd3ZMd4ZNed5joeHeIeJd6ndS(7s6A high-level cross-protocol url-grabber.

GENERAL ARGUMENTS (kwargs)

  Where possible, the module-level default is indicated, and legal
  values are provided.

  copy_local = 0   [0|1]

    ignored except for file:// urls, in which case it specifies
    whether urlgrab should still make a copy of the file, or simply
    point to the existing copy. The module level default for this
    option is 0.

  close_connection = 0   [0|1]

    tells URLGrabber to close the connection after a file has been
    transfered. This is ignored unless the download happens with the
    http keepalive handler (keepalive=1).  Otherwise, the connection
    is left open for further use. The module level default for this
    option is 0 (keepalive connections will not be closed).

  keepalive = 1   [0|1]

    specifies whether keepalive should be used for HTTP/1.1 servers
    that support it. The module level default for this option is 1
    (keepalive is enabled).

  progress_obj = None

    a class instance that supports the following methods:
      po.start(filename, url, basename, length, text)
      # length will be None if unknown
      po.update(read) # read == bytes read so far
      po.end()

  text = None
  
    specifies an alternativ text item in the beginning of the progress
    bar line. If not given, the basename of the file is used.

  throttle = 1.0

    a number - if it's an int, it's the bytes/second throttle limit.
    If it's a float, it is first multiplied by bandwidth.  If throttle
    == 0, throttling is disabled.  If None, the module-level default
    (which can be set on default_grabber.throttle) is used. See
    BANDWIDTH THROTTLING for more information.

  timeout = None

    a positive float expressing the number of seconds to wait for socket
    operations. If the value is None or 0.0, socket operations will block
    forever. Setting this option causes urlgrabber to call the settimeout
    method on the Socket object used for the request. See the Python
    documentation on settimeout for more information.
    http://www.python.org/doc/current/lib/socket-objects.html

  bandwidth = 0

    the nominal max bandwidth in bytes/second.  If throttle is a float
    and bandwidth == 0, throttling is disabled.  If None, the
    module-level default (which can be set on
    default_grabber.bandwidth) is used. See BANDWIDTH THROTTLING for
    more information.

  range = None

    a tuple of the form (first_byte, last_byte) describing a byte
    range to retrieve. Either or both of the values may set to
    None. If first_byte is None, byte offset 0 is assumed. If
    last_byte is None, the last byte available is assumed. Note that
    the range specification is python-like in that (0,10) will yeild
    the first 10 bytes of the file.

    If set to None, no range will be used.
    
  reget = None   [None|'simple'|'check_timestamp']

    whether to attempt to reget a partially-downloaded file.  Reget
    only applies to .urlgrab and (obviously) only if there is a
    partially downloaded file.  Reget has two modes:

      'simple' -- the local file will always be trusted.  If there
        are 100 bytes in the local file, then the download will always
        begin 100 bytes into the requested file.

      'check_timestamp' -- the timestamp of the server file will be
        compared to the timestamp of the local file.  ONLY if the
        local file is newer than or the same age as the server file
        will reget be used.  If the server file is newer, or the
        timestamp is not returned, the entire file will be fetched.

    NOTE: urlgrabber can do very little to verify that the partial
    file on disk is identical to the beginning of the remote file.
    You may want to either employ a custom "checkfunc" or simply avoid
    using reget in situations where corruption is a concern.

  user_agent = 'urlgrabber/VERSION'

    a string, usually of the form 'AGENT/VERSION' that is provided to
    HTTP servers in the User-agent header. The module level default
    for this option is "urlgrabber/VERSION".

  http_headers = None

    a tuple of 2-tuples, each containing a header and value.  These
    will be used for http and https requests only.  For example, you
    can do
      http_headers = (('Pragma', 'no-cache'),)

  ftp_headers = None

    this is just like http_headers, but will be used for ftp requests.

  proxies = None

    a dictionary that maps protocol schemes to proxy hosts. For
    example, to use a proxy server on host "foo" port 3128 for http
    and https URLs:
      proxies={ 'http' : 'http://foo:3128', 'https' : 'http://foo:3128' }
    note that proxy authentication information may be provided using
    normal URL constructs:
      proxies={ 'http' : 'http://user:host@foo:3128' }
    Lastly, if proxies is None, the default environment settings will
    be used.

  prefix = None

    a url prefix that will be prepended to all requested urls.  For
    example:
      g = URLGrabber(prefix='http://foo.com/mirror/')
      g.urlgrab('some/file.txt')
      ## this will fetch 'http://foo.com/mirror/some/file.txt'
    This option exists primarily to allow identical behavior to
    MirrorGroup (and derived) instances.  Note: a '/' will be inserted
    if necessary, so you cannot specify a prefix that ends with a
    partial file or directory name.

  opener = None
  
    Overrides the default urllib2.OpenerDirector provided to urllib2
    when making requests.  This option exists so that the urllib2
    handler chain may be customized.  Note that the range, reget,
    proxy, and keepalive features require that custom handlers be
    provided to urllib2 in order to function properly.  If an opener
    option is provided, no attempt is made by urlgrabber to ensure
    chain integrity.  You are responsible for ensuring that any
    extension handlers are present if said features are required.
    
  data = None

    Only relevant for the HTTP family (and ignored for other
    protocols), this allows HTTP POSTs.  When the data kwarg is
    present (and not None), an HTTP request will automatically become
    a POST rather than GET.  This is done by direct passthrough to
    urllib2.  If you use this, you may also want to set the
    'Content-length' and 'Content-type' headers with the http_headers
    option.  Note that python 2.2 handles the case of these
    badly and if you do not use the proper case (shown here), your
    values will be overridden with the defaults.
    

RETRY RELATED ARGUMENTS

  retry = None

    the number of times to retry the grab before bailing.  If this is
    zero, it will retry forever. This was intentional... really, it
    was :). If this value is not supplied or is supplied but is None
    retrying does not occur.

  retrycodes = [-1,2,4,5,6,7]

    a sequence of errorcodes (values of e.errno) for which it should
    retry. See the doc on URLGrabError for more details on this.  You
    might consider modifying a copy of the default codes rather than
    building yours from scratch so that if the list is extended in the
    future (or one code is split into two) you can still enjoy the
    benefits of the default list.  You can do that with something like
    this:

      retrycodes = urlgrabber.grabber.URLGrabberOptions().retrycodes
      if 12 not in retrycodes:
          retrycodes.append(12)
      
  checkfunc = None

    a function to do additional checks. This defaults to None, which
    means no additional checking.  The function should simply return
    on a successful check.  It should raise URLGrabError on an
    unsuccessful check.  Raising of any other exception will be
    considered immediate failure and no retries will occur.

    If it raises URLGrabError, the error code will determine the retry
    behavior.  Negative error numbers are reserved for use by these
    passed in functions, so you can use many negative numbers for
    different types of failure.  By default, -1 results in a retry,
    but this can be customized with retrycodes.

    If you simply pass in a function, it will be given exactly one
    argument: a CallbackObject instance with the .url attribute
    defined and either .filename (for urlgrab) or .data (for urlread).
    For urlgrab, .filename is the name of the local file.  For
    urlread, .data is the actual string data.  If you need other
    arguments passed to the callback (program state of some sort), you
    can do so like this:

      checkfunc=(function, ('arg1', 2), {'kwarg': 3})

    if the downloaded file has filename /tmp/stuff, then this will
    result in this call (for urlgrab):

      function(obj, 'arg1', 2, kwarg=3)
      # obj.filename = '/tmp/stuff'
      # obj.url = 'http://foo.com/stuff'
      
    NOTE: both the "args" tuple and "kwargs" dict must be present if
    you use this syntax, but either (or both) can be empty.

  failure_callback = None

    The callback that gets called during retries when an attempt to
    fetch a file fails.  The syntax for specifying the callback is
    identical to checkfunc, except for the attributes defined in the
    CallbackObject instance.  The attributes for failure_callback are:

      exception = the raised exception
      url       = the url we're trying to fetch
      tries     = the number of tries so far (including this one)
      retry     = the value of the retry option

    The callback is present primarily to inform the calling program of
    the failure, but if it raises an exception (including the one it's
    passed) that exception will NOT be caught and will therefore cause
    future retries to be aborted.

    The callback is called for EVERY failure, including the last one.
    On the last try, the callback can raise an alternate exception,
    but it cannot (without severe trickiness) prevent the exception
    from being raised.

  interrupt_callback = None

    This callback is called if KeyboardInterrupt is received at any
    point in the transfer.  Basically, this callback can have three
    impacts on the fetch process based on the way it exits:

      1) raise no exception: the current fetch will be aborted, but
         any further retries will still take place

      2) raise a URLGrabError: if you're using a MirrorGroup, then
         this will prompt a failover to the next mirror according to
         the behavior of the MirrorGroup subclass.  It is recommended
         that you raise URLGrabError with code 15, 'user abort'.  If
         you are NOT using a MirrorGroup subclass, then this is the
         same as (3).

      3) raise some other exception (such as KeyboardInterrupt), which
         will not be caught at either the grabber or mirror levels.
         That is, it will be raised up all the way to the caller.

    This callback is very similar to failure_callback.  They are
    passed the same arguments, so you could use the same function for
    both.
      
  urlparser = URLParser()

    The URLParser class handles pre-processing of URLs, including
    auth-handling for user/pass encoded in http urls, file handing
    (that is, filenames not sent as a URL), and URL quoting.  If you
    want to override any of this behavior, you can pass in a
    replacement instance.  See also the 'quote' option.

  quote = None

    Whether or not to quote the path portion of a url.
      quote = 1    ->  quote the URLs (they're not quoted yet)
      quote = 0    ->  do not quote them (they're already quoted)
      quote = None ->  guess what to do

    This option only affects proper urls like 'file:///etc/passwd'; it
    does not affect 'raw' filenames like '/etc/passwd'.  The latter
    will always be quoted as they are converted to URLs.  Also, only
    the path part of a url is quoted.  If you need more fine-grained
    control, you should probably subclass URLParser and pass it in via
    the 'urlparser' option.

BANDWIDTH THROTTLING

  urlgrabber supports throttling via two values: throttle and
  bandwidth Between the two, you can either specify and absolute
  throttle threshold or specify a theshold as a fraction of maximum
  available bandwidth.

  throttle is a number - if it's an int, it's the bytes/second
  throttle limit.  If it's a float, it is first multiplied by
  bandwidth.  If throttle == 0, throttling is disabled.  If None, the
  module-level default (which can be set with set_throttle) is used.

  bandwidth is the nominal max bandwidth in bytes/second.  If throttle
  is a float and bandwidth == 0, throttling is disabled.  If None, the
  module-level default (which can be set with set_bandwidth) is used.

  THROTTLING EXAMPLES:

  Lets say you have a 100 Mbps connection.  This is (about) 10^8 bits
  per second, or 12,500,000 Bytes per second.  You have a number of
  throttling options:

  *) set_bandwidth(12500000); set_throttle(0.5) # throttle is a float

     This will limit urlgrab to use half of your available bandwidth.

  *) set_throttle(6250000) # throttle is an int

     This will also limit urlgrab to use half of your available
     bandwidth, regardless of what bandwidth is set to.

  *) set_throttle(6250000); set_throttle(1.0) # float

     Use half your bandwidth

  *) set_throttle(6250000); set_throttle(2.0) # float

    Use up to 12,500,000 Bytes per second (your nominal max bandwidth)

  *) set_throttle(6250000); set_throttle(0) # throttle = 0

     Disable throttling - this is more efficient than a very large
     throttle setting.

  *) set_throttle(0); set_throttle(1.0) # throttle is float, bandwidth = 0

     Disable throttling - this is the default when the module is loaded.

  SUGGESTED AUTHOR IMPLEMENTATION (THROTTLING)

  While this is flexible, it's not extremely obvious to the user.  I
  suggest you implement a float throttle as a percent to make the
  distinction between absolute and relative throttling very explicit.

  Also, you may want to convert the units to something more convenient
  than bytes/second, such as kbps or kB/s, etc.

N(t*sfrom t.is import __version__s???(t_cCs|S(N(tst(R((t6/usr/lib/python2.4/site-packages/urlgrabber/grabber.pyRs(s
HTTPException(sHTTPResponse(sHTTPHandlersHTTPSHandler(sHTTPRangeHandlersHTTPSRangeHandlersFileRangeHandlersFTPRangeHandlersrange_tuple_normalizesrange_tuple_to_headers
RangeErroricCso|atotidjo
|t_ntotidjo
|t_ntidjo
|t_ndS(sSet the DEBUG object.  This is called by _init_default_logger when
    the environment variable URLGRABBER_DEBUG is set, but can also be
    called by a calling program.  Basically, if the calling program uses
    the logging module and would like to incorporate urlgrabber logging,
    then it can do so this way.  It's probably not necessary as most
    internal logging is only for debugging purposes.

    The passed-in object should be a logging.Logger instance.  It will
    be pushed into the keepalive and byterange modules if they're
    being used.  The mirror module pulls this object in on import, so
    you will need to manually push into it.  In fact, you may find it
    tidier to simply push your logging object (or objects) into each
    of these modules independently.
    N(tDBOBJtDEBUGthave_keepalivet	keepalivetNonet
have_ranget	byteranget
sslfactory(R((Rt
set_loggers

cCsTy!tidid}dk}|ii|dt|d}|djo
t	n|i
d}t|djo|d}nd}|djo|iti}n3|djo|iti}n|i|}|i||id	}|i||i|Wn"ttt	fj
o
d}nXt|dS(
stExamines the environment variable URLGRABBER_DEBUG and creates
    a logging object (logging.logger) based on the contents.  It takes
    the form

      URLGRABBER_DEBUG=level,filename
      
    where "level" can be either an integer or a log level from the
    logging module (DEBUG, INFO, etc).  If the integer is zero or
    less, logging will be disabled.  Filename is the filename where
    logs will be sent.  If it is "-", then stdout will be used.  If
    the filename is empty or missing, stderr will be used.  If the
    variable cannot be processed or the logging module cannot be
    imported (python < 2.3) then logging will be disabled.  Here are
    some examples:

      URLGRABBER_DEBUG=1,debug.txt   # log everything to debug.txt
      URLGRABBER_DEBUG=WARNING,-     # log warning and higher to stdout
      URLGRABBER_DEBUG=INFO          # log info and higher to stderr
      
    This funtion is called during module initialization.  It is not
    intended to be called from outside.  The only reason it is a
    function at all is to keep the module-level namespace tidy and to
    collect the code into a nice block.tURLGRABBER_DEBUGt,Niis%(asctime)s %(message)stt-t
urlgrabber(tostenvirontsplittdbinfotloggingt_levelNamestgettinttlevelt
ValueErrort	Formattert	formattertlentfilenamet
StreamHandlertsyststderrthandlertstdouttFileHandlertsetFormattert	getLoggerRt
addHandlertsetLeveltKeyErrortImportErrorR	R
(RRR RRR$R((Rt_init_default_loggers.	#





tURLGrabErrorcBstZdZRS(s
    URLGrabError error codes:

      URLGrabber error codes (0 -- 255)
        0    - everything looks good (you should never see this)
        1    - malformed url
        2    - local file doesn't exist
        3    - request for non-file local file (dir, etc)
        4    - IOError on fetch
        5    - OSError on fetch
        6    - no content length header when we expected one
        7    - HTTPException
        8    - Exceeded read limit (for urlread)
        9    - Requested byte range not satisfiable.
        10   - Byte range requested, but range support unavailable
        11   - Illegal reget mode
        12   - Socket timeout
        13   - malformed proxy url
        14   - HTTPError (includes .code and .exception attributes)
        15   - user abort
        
      MirrorGroup error codes (256 -- 511)
        256  - No more mirrors left to try

      Custom (non-builtin) classes derived from MirrorGroup (512 -- 767)
        [ this range reserved for application-specific error codes ]

      Retry codes (< 0)
        -1   - retry the download, unknown reason

    Note: to test which group a code is in, you can simply do integer
    division by 256: e.errno / 256

    Negative codes are reserved for use by functions passed in to
    retrygrab with checkfunc.  The value -1 is built in as a generic
    retry code and is already included in the retrycodes list.
    Therefore, you can create a custom check function that simply
    returns -1 and the fetch will be re-tried.  For more customized
    retries, you can use other negative number and include them in
    retry-codes.  This is nice for outputting useful messages about
    what failed.

    You can use these error codes like so:
      try: urlgrab(url)
      except URLGrabError, e:
         if e.errno == 3: ...
           # or
         print e.strerror
           # or simply
         print e  #### print '[Errno %i] %s' % (e.errno, e.strerror)
    (t__name__t
__module__t__doc__(((RR.
s3tCallbackObjectcBstZdZdZRS(sContainer for returned callback data.

    This is currently a dummy class into which urlgrabber can stuff
    information for passing to callbacks.  This way, the prototype for
    all callbacks is the same, regardless of the data that will be
    passed back.  Any function that accepts a callback function as an
    argument SHOULD document what it will define in this object.

    It is possible that this class will have some greater
    functionality in the future.
    cKs|ii|dS(N(tselft__dict__tupdatetkwargs(R3R6((Rt__init__Os(R/R0R1R7(((RR2CscKsti|||S(sJgrab the file at <url> and make a local copy at <filename>
    If filename is none, the basename of the url is used.
    urlgrab returns the filename of the local file, which may be different
    from the passed-in filename if the copy_local kwarg == 0.
    
    See module documentation for a description of possible kwargs.
    N(tdefault_grabberturlgrabturlR R6(R:R R6((RR9RscKsti||S(s0open the url and return a file object
    If a progress object or throttle specifications exist, then
    a special file object will be returned that supports them.
    The file object can be treated like any other file object.
    
    See module documentation for a description of possible kwargs.
    N(R8turlopenR:R6(R:R6((RR;\scKsti|||S(s`read the url into a string, up to 'limit' bytes
    If the limit is exceeded, an exception will be thrown.  Note that urlread
    is NOT intended to be used as a way of saying "I want the first N bytes"
    but rather 'read the whole file into memory, but don't use too much'
    
    See module documentation for a description of possible kwargs.
    N(R8turlreadR:tlimitR6(R:R=R6((RR<fst	URLParsercBsAtZdZdZdZdZdZdZdZRS(sGProcess the URLs before passing them to urllib2.

    This class does several things:

      * add any prefix
      * translate a "raw" file to a proper file: url
      * handle any http or https auth that's encoded within the url
      * quote the url

    Only the "parse" method is called directly, and it calls sub-methods.

    An instance of this class is held in the options object, which
    means that it's easy to change the behavior by sub-classing and
    passing the replacement in.  It need only have a method like:

        url, parts = urlparser.parse(url, opts)
    cCsJ|i}|io|i||i}nti|}|\}	}}}
}}|	p#t|	djoc|	tijoS|ddjoti
i|}ndti|}ti|}d}n|	ddgjo|i|}n|djo|i|}n|o|i|}nti|}||fS(sparse the url and return the (modified) url and its parts

        Note: a raw file WILL be quoted when it's converted to a URL.
        However, other urls (ones which come with a proper scheme) may
        or may not be quoted according to opts.quote

          opts.quote = 1     --> quote it
          opts.quote = 0     --> do not quote it
          opts.quote = None  --> guess
        iis/\sfile:thttpthttpsN(toptstquotetprefixR3t
add_prefixR:turlparsetpartstschemethosttpathtparmtquerytfragRtstringtlettersRtabspathturllibtpathname2urltprocess_httpR	tguess_should_quotet
urlunparse(R3R:RARLRBRHRFRKRIRGRJ((Rtparses(
	
+

cCsB|ddjp|ddjo||}n|d|}|S(Nit/i(RCR:(R3R:RC((RRDs"cCs|\}
}}	}}}d|jotoyc|idd\}}d|jo:|idd\}}ti
|}ti
|}nWn.tj
o"}tdtdtnXtotid||ntid|||n|
||	|||fS(Nt@it:sBad URL: %ssadding HTTP auth: %s, %s(RFRGRHRIRJRKRLtauth_handlerRt	user_passtusertpasswordRPtunquoteRteR.RR:Rtinfotadd_passwordR	(R3RFRLR\R^RHR[RZRKRIRGRJ((RRRs
cCs=|\}}}}}}ti|}||||||fS(s	quote the URL

        This method quotes ONLY the path part.  If you need to quote
        other parts, you should override this and pass in your derived
        class.  The other alternative is to quote other parts before
        passing into urlgrabber.
        N(	RFRGRHRIRJRKRLRPRB(R3RFRLRHRKRIRGRJ((RRBst0123456789ABCDEFc
Cs|\}}}}	}}d|jodSnti|d}|djox|djot
||djodSn||d|d!i}|d|ijp|d|ijodSnti|d|d}qOWdSndS(s
        Guess whether we should quote a path.  This amounts to
        guessing whether it's already quoted.

        find ' '   ->  1
        find '%'   ->  1
        find '%XX' ->  0
        else       ->  1
        t it%iiiN(RFRGRHRIRJRKRLRMtfindtindRtuppertcodeR3thexvals(
R3RFRLRgRHRKReRIRGRJ((RRSs 	


((	R/R0R1RURDRRRBRhRS(((RR>qs	%			tURLGrabberOptionscBsGtZdZedZdZdZdZdZdZ	RS(sClass to ease kwargs handling.cKs5||_|djo|in|i|dS(sInitialize URLGrabberOptions object.
        Set default values for all options and then update options specified
        in kwargs.
        N(tdelegateR3R	t
_set_defaultst_set_attributesR6(R3RjR6((RR7s
	
cCs>|io't|i|ot|i|Snt|dS(N(R3RjthasattrtnametgetattrtAttributeError(R3Rn((Rt__getattr__scCsW|idjodSn<t|itdjot|iSn|i|iSdS(sRCalculate raw throttle value from throttle and bandwidth 
        values.
        iN(R3tthrottlettypetfloatt	bandwidth(R3((Rtraw_throttlescKstd||S(sCreate a derived URLGrabberOptions instance.
        This method creates a new instance and overrides the
        options specified in kwargs.
        RjN(RiR3R6(R3R6((RtderivescKs}|ii|to&|idot|i|_n|idddgjo#t
dtd|ifndS(s7Update object attributes with those provided in kwargs.trangetsimpletcheck_timestampisIllegal reget mode: %sN(R3R4R5R6R
thas_keytrange_tuple_normalizeRxtregetR	R.R(R3R6((RRlscCsd|_d|_d|_d|_ddddddg|_d|_d|_d|_	d|_
d	t|_d
|_
d|_d|_d|_d|_d|_d|_t|_d|_d|_d|_d|_d|_t|_d|_d|_d|_dS(sSet all options to their default values. 
        When adding new options, make sure a default is
        provided here.
        f1.0iiiiiiis
urlgrabber/%siN( R	R3tprogress_objRrRutretryt
retrycodest	checkfunct
copy_localtclose_connectionRxt__version__t
user_agentRtproxiesR}tfailure_callbacktinterrupt_callbackRCtopenertTruet
cache_openersttimeoutttextthttp_headerstftp_headerstdataR>t	urlparserRBtssl_ca_certtssl_context(R3((RRks8								
															(
R/R0R1R	R7RqRvRwRlRk(((RRis
				
t
URLGrabbercBsJtZdZdZdZdZedZedZdZ	RS(sProvides easy opening of URLs with a variety of options.
    
    All options are specified as kwargs. Options may be specified when
    the class is created and may be overridden on a per request basis.
    
    New objects inherit default values from default_grabber.
    cKst||_dS(N(RiR6R3RA(R3R6((RR7@sc	Gsd}
x|
d}
d}d}
d}	to!tid|
|i|dny9t
||f|h}totidn|SWnPt
j
o!}|}|i}	|i}
n%tj
o}|}|i}	nXtotid|n|	oototid|	n|i|	\}}}td|d|dd	|
d
|i}||||n|idjp|
|ijototidnn|
dj	o8|
|ijo(totid|
|inq	q	WdS(
Niisattempt %i/%s: %stsuccesss
exception: %sscalling callback: %st	exceptionR:ttriesRsretries exceeded, re-raisings)retrycode (%i) not in list %s, re-raising(RR	Rt	retrycodetcallbackRR_RARtargstapplytfunctrR.R^RterrnotKeyboardInterruptRR3t_make_callbacktcb_functcb_argst	cb_kwargsR2tobjR(R3RARRRRR^RRRRRRR((Rt_retryCsP

		
 	cKsI|ii|}|ii||\}}d}|i	|||S(sopen the url and return a file object
        If a progress object or throttle value specified when this 
        object was created, then  a special file object will be 
        returned that supports them. The file object can be treated 
        like any other file object.
        cCst|ddd|S(NR RA(tURLGrabberFileObjectR:R	RA(RAR:((Rt	retryfunc{sN(
R3RARwR6RRUR:RFRR(R3R:R6RFRRA((RR;rs
	c
s[ii|}|ii||\}}|\}	}}}
}}|djoti
iti|}n|	djo|ioti|}|oti
id||}nti
i|p tdtd|fq9ti
i|p tdtd|fq9|ip|Sq9nd}i||||S(	s	grab the file at <url> and make a local copy at <filename>
        If filename is none, the basename of the url is used.
        urlgrab returns the filename of the local file, which may be 
        different from the passed-in filename if copy_local == 0.
        tfiles//isLocal file does not exist: %sisNot a normal file: %scst|||}zo|i|idj	oQi	|i\}}}t
}||_||_t||f||nWd|iX|S(N(RR:R RAtfot_do_grabRR	R3RRRRR2RRtclose(RAR:R RRRRR(R3(RRs
			N(R3RARwR6RRUR:RFRGRHRIRJRKRLR R	RtbasenameRPR]Rturl2pathnametnormpathtexistsR.RtisfileRxRR(
R3R:R R6RLRHRFRKRIRGRJRAR((R3RR9s(

csii|}|ii||\}}|dj	o|d}nd}i||||}|o6t
||jo#tdtd||fn|S(s2read the url into a string, up to 'limit' bytes
        If the limit is exceeded, an exception will be thrown.  Note
        that urlread is NOT intended to be used as a way of saying 
        "I want the first N bytes" but rather 'read the whole file 
        into memory, but don't use too much'
        ic	st|ddd|}d}z|djo|i}n|i|}|idj	oQi
|i\}}}t}||_||_t||f||nWd|iX|S(NR RAR(RR:R	RARtsR=treadRR3RRRRR2RRRR(	RAR:R=RRRRRR(R3(RRs
			isExceeded limit (%i): %sN(R3RARwR6RRUR:RFR=R	RRRRR.R(R3R:R=R6RRFRRA((R3RR<s
cCs&t|o|fhfSn|SdS(N(tcallabletcallback_obj(R3R((RRs
(
R/R0R1R7RR;R	R9R<R(((RR7s		/	
+(RcBstZdZdZdZdZdZdZdZdZ	dZ
ed	Zed
Z
ddZd
ZRS(sThis is a file-object wrapper that supports progress objects 
    and throttling.

    This exists to solve the following problem: lets say you want to
    drop-in replace a normal open with urlopen.  You want to use a
    progress meter and/or throttling, but how do you do that without
    rewriting your code?  Answer: urlopen will return a wrapped file
    object that does the progress meter and-or throttling internally.
    cCsr||_||_||_d|_d|_dd|_ti|_	d|_
d|_d|_|i
dS(NRiii(R:R3R RAR	Rt_rbuft	_rbufsizettimet_ttimet_tsizet_amount_readt_openert_do_open(R3R:R RA((RR7s					
			cCs4t|i|ot|i|Snt|dS(sThis effectively allows us to wrap at the instance level.
        Any attribute not found in _this_ object will be searched for
        in self.fo.  This includes methods.N(RmR3RRnRoRp(R3Rn((RRqscCs|iio|iiSnc|idjoRg}to
|ii}t	o|ii
p
|ii}|ii
oY|it|ii
|p|itin|p|itiqnti|ii|ii}|o$|it|it|n|o|it	n|it|iiot|||_n|i||_g|i_n|iS(s8Build a urllib2 OpenerDirector based on request options.N( R3RARRR	thandlersRRtneed_keepalive_handlertrange_handlersRxR}tneed_range_handlerRtappendtCachedProxyHandlerturllib2tHTTPHandlert
FTPHandlerRtget_factoryRRtssl_factorytkeepalive_http_handlertHTTPSHandlertextendRYRtCachedOpenerDirectort
create_openert
addheaders(R3RRRR((Rt_get_openers4
 



c	si}tiiiii	i
d}i|\}
}d}ioxiidjoed}y<|id}ti|}|ijo
d}nWqtfj
o
d}qXn||
o(d}di_d_d_ntog|o\|
i|
idi_id=i
d_i|\}
}qntii\}}}	}}}t&i'|	}	ii(pii)p
ii*p0|
i+_+t,|
do|
i-_-qnii(oy!t.|d}
|
i}
Wn"t0t1tfj
o
d}
nXii(i2t3i4t&i'it5i"i6|	|
d	ii7ii(i8dn|
|_
_dS(
NcsXiidjotSndijotSnt|t	ptSn|i
djS(NtRangei(R3RAR}R	tFalsetreqtheaderst
isinstanceRtHTTPResponseRg(R(R3R(Rt
_checkNoReget9siRzs
last-modifiediRtreadlinesContent-LengthR(9R3RRRtRequestR:RARRt_add_headerst_build_rangeRt
_make_requestRthdrtfetch_againt
reget_timeR}t
getdate_tztmodified_tupletrfc822t	mktime_tztmodified_stampt	TypeErrorR	RRRRRRRERGRHRIRJRKRLRPR]R~RvRRRmRRtlengthR+RtstarttstrR RRRR5(R3RRKRRRGRLRJRHRIRRRRRR((R3RRR2s`


	




	 $*
cCs|iio|id|iiny|i}Wntj
o
d}nX|ii	o>|djo1x.|ii	D]\}}|i||qzWn|iio>|djo1x.|iiD]\}}|i||qWndS(Ns
User-agentR?R@tftp(shttpshttps(
R3RARRt
add_headertget_typetreq_typeRR	RthtvR(R3RRRR((RRs


cCsJd|_d|_d}d}to|iio~t	|i
tijoeyt
i|i
}Wntj
oqX|t|_|t}||_|df}d|_n|iioWtptdtdn|ii}|do|d||df}qn|o+t|}|o|id|qFndS(NiRii
s2Byte range requested but range support unavailableR(R	R3RRtreget_lengthtrtR
RAR}RsR ttypestStringTypesRtstatRtOSErrortST_MTIMEtST_SIZERRxR.Rtrange_tuple_to_headertheaderRR(R3RRRRR((RRs0		-

	

 cCsyztoT|iioGti}ti|iiz|i	|}Wdti|Xn|i	|}|i}Wntj
o%}tdtd|fn_tj
o}tdt|n6tij
o9}tdt|}|i|_||_|ntj
oo}t|do:to3t|ito tdtd|fqtdtd	|fnutj
o%}td
td|fnEtj
o.}tdtd
|i i!|fnX||fSdS(NisBad URL: %si	itreasonisTimeout: %sisIOError: %sisOSError: %sisHTTP Exception (%s): %s("thave_socket_timeoutR3RARtsockettgetdefaulttimeouttold_totsetdefaulttimeoutRtopenRRR_RRR^R.Rt
RangeErrorRRt	HTTPErrortnew_eRgRtIOErrorRmRRtTimeoutErrorRt
HTTPExceptiont	__class__R/(R3RRRRRR^R((RRs8 	
*   *cCs|iot|id}nt|id}y |ii\}}||}Wnt
j
o}	d}nXdd}d}|dj	ot|||}n|i|}
|t|
}x\|
oT|i|
|dj	ot|||}n|i|}
|t|
}qW|iy>|iid}ti|}ti|i||fWnt
fj
o	}nX|S(sdump the file to self.filename.tabtwbiiis
last-modifiedN(R3RRR tnew_foRARxtlowthightamountRRR	tbstsizetminRtblockRtwriteRRRRRRRRtutimeR^(R3R^RR	R
RRRRRRR((RRs<





c
Cs^|io?|dj	o2t|i}||jo||}qIdSn|ig}	t|i}x|djp|o|ii	oX|i
|ii	ti|i}|djoti|nti|_n|djo
|i}nt||i}y|ii|}Wntij
o%}tdtd|fnbtj
o%}tdtd|fn2tj
o%}tdtd|fnXt|}|pPn|o||}n|	i|||}||_
|i||_|iio|iii |iqgqgWt!i"|	d|_dS(	sfill the buffer to contain at least 'amt' bytes by reading
        from the underlying file object.  If amt is None, then it will
        read until it gets nothing more.  It updates the progress meter
        and throttles after every self._rbufsize bytes.NiisSocket Error: %sisTimeout: %ssIOError: %sR(#R3RtamtR	RtLtbuftbufsizeRARvRRRtdifftsleepRt
readamountR
RRtnewRterrorR^R.RRRtnewsizeRRR~R5RMtjoin(
R3RRR^RRRRRR((Rt_fill_buffersN
'


  !

	
cCsS|i||djo|id}|_n|i| |i|}|_|S(NR(R3RRR	RR(R3RR((RR"s


icCs%ti|id}x|djod|jot|ijnoZt|i}|i||i	t|i|jpPnti|id|}qW|djot|i}n|d}d|jot|ijno
|}n|i| |i|}|_|S(Ns
ii(RMRdR3RtiR=RRRRR(R3R=RRR((RR*s5

'
cCsd|iio|iii|in|ii|iioy|iiWq`q`XndS(N(R3RAR~tendRRRR(R3((RR9s


(R/R0R1R7RqRRRRRRR	RRRR(((RRs		
		6	N		 	#	4cGsxJtD]B\}}||jo)x|iD]}|i|q*W|SqqW|pti}n|i	|}ti
||f|S(N(t_handler_cachetcached_handlersRRR$t
add_parentRRRRR(RRR$RR ((RRBs

c	CsxtD]9\}}||jo totid|nPqqWx{|iD]m\}}t	i
|\}}t	i
|\}}|djp
|djotdtd|qQqQWtotid|nti|}ti||f|S(Nsre-using proxy settings: %si
sBad proxy URL: %sscreating new proxy handler: %s(t_proxy_cachetpdictR$RRtdebugtitemstkRRPt	splittypetutypeR:t	splithostRHtotherR	R.RR_RtProxyHandlerR(	RR#R(R&R:RHR$RR*((RROs"
	
!cCs
|t_dS(s8Deprecated. Use: default_grabber.throttle = new_throttleN(tnew_throttleR8Rr(R,((Rtset_throttlebscCs
|t_dS(s:Deprecated. Use: default_grabber.bandwidth = new_bandwidthN(t
new_bandwidthR8Ru(R.((Rt
set_bandwidthfscCs
|t_dS(s@Deprecated. Use: default_grabber.progress_obj = new_progress_objN(tnew_progress_objR8R~(R0((Rtset_progress_objjscCs
|t_dS(s<Deprecated. Use: default_grabber.user_agent = new_user_agentN(tnew_user_agentR8R(R2((Rtset_user_agentnsiiiiiiic
Cs^hd|<d|<d|<d|<d|<d|<d|<d|	<}
t	|||
S(
s5Deprecated. Use: urlgrab() with the retry arg insteadRRR~RrRuRRRN(RRR~RrRutnumtriesRRR6R9R:R (R:R RRR~RrRuR4RRR6((Rt	retrygrabrsN	c
CsIdk}y|idd!\}}Wn1tj
o%dG|idGdGH|inXh}x@|idD]1}ti	|dd\}}t|||<qkWt
dtdd	d
titifGHydkl}Wntj
o	}nX||d<ytt||f|}	Wntj
o}|GHnXd
G|	GHdS(Niisusage:is8<url> <filename> [copy_local=0|1] [close_connection=0|1]t=f1.0i is)throttle: %s,  throttle bandwidth: %s B/s(stext_progress_meterR~sLOCAL FILE:(R"targvR:R RtexitR6taRMRR&RRR-R/R8RrRutprogressttext_progress_meterR,R^RR9RnR.(
R9R^R:R&RR R"R;R6Rn((Rt
_main_tests0	


cCsDdk}y|idd!\}}Wn1tj
o%dG|idGdGH|inXh}x@|idD]1}ti	|dd\}}t|||<qkWydk
l}Wntj
o	}nX||d<d	d
}	|	dhdd<f|d
<ytt||f|}
Wntj
o}|GHnXdG|
GHdS(Niisusage:is8<url> <filename> [copy_local=0|1] [close_connection=0|1]R6(stext_progress_meterR~tfoocCsq|G|GHdk}|i}|djodGHtddn|djodGHtddndGHdS(	Nf0.5s
forcing retryif0.75sforcing failureisforcing immediate failureR(thellottheretrandomtrnumR.(R R>R?R@RA((Rtcfuncs		

R>R?RsLOCAL FILE:(shello(R"R7R:R RR8R6R9RMRR&RRR:R;R,R^RBRR5RnR.(R9R^R:R&RR R"R;R6RBRn((Rt_retry_tests.	


cCsdk}dk}dk}|djo
t}nd|GHt|}
|
i}|
i
xttt
tgD]r}	|i|}|i}t|dd}d|	iG|	|||i}||jo	dGHqpdGHqpWdS(Nsusing file "%s" for comparisonsistesting %-30s tpassedtFAILED(R@t	cStringIOR"R R	t__file__RRRts_inputRt_test_file_object_smallreadt_test_file_object_readallt_test_file_object_readlinet_test_file_object_readlinesttestfunctStringIOtfo_inputt	fo_outputRtwrapperR/tgetvaluets_output(R RFRHROR@RQR"RPRSRMR((Rt_file_object_tests$

	


	cCs7x0|id}|i||pdSqqWdS(Nii(RQRRRPR(RQRPR((RRIs
cCs|i}|i|dS(N(RQRRRPR(RQRPR((RRJscCs4x-|i}|i||pdSqqWdS(Ni(RQRRRPR(RQRPR((RRKs
cCs)|i}|iti|ddS(NR(RQt	readlinestliRPRRMR(RQRPRV((RRLst__main__ttest(OR1Rtos.pathR"RERRRRMRPRRR/RRRtHTTPBasicAuthHandlertHTTPPasswordMgrWithDefaultRealmRYti18nRR,tmsgthttplibRR	RRRRRRRRRtHTTPRangeHandlertHTTPSRangeHandlertFileRangeHandlertFTPRangeHandlerR|RRRR
RRRRRpRR
R-RR.R2R9R;R<R>RiRR8RRRR"RR-R/R1R3R5R<RCRTRIRJRKRL(>RR<RR3R
RTRRLRR/R<RR8RR9R-RRIRPRRRRJRRRaR]RRR.R|RMRRR;RRR"RRR
RYRRRKRR`RR"RRiR-RER_R1R>RCRRbR5RR2((Rt?ms										!
			
	5		
		-6
	
wO	f					6		#				


Anon7 - 2021