summaryrefslogtreecommitdiff
path: root/scripts/urlgrabber
blob: 3c7cfbf8b53d24dc05146b9dd42f4ddc3c985c41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
#!/usr/bin/python -t

#   This library is free software; you can redistribute it and/or
#   modify it under the terms of the GNU Lesser General Public
#   License as published by the Free Software Foundation; either
#   version 2.1 of the License, or (at your option) any later version.
#
#   This library is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#   Lesser General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public
#   License along with this library; if not, write to the 
#      Free Software Foundation, Inc., 
#      59 Temple Place, Suite 330, 
#      Boston, MA  02111-1307  USA

# This file is part of urlgrabber, a high-level cross-protocol url-grabber
# Copyright 2002-2006 Michael D. Stenner, Ryan Tomayko

from __future__ import print_function

"""NAME
  urlgrabber - a simple client for the urlgrabber python package

DESCRIPTION
  This is a thin client for the urlgrabber python package.  It is
  provided mainly for helping debug the python package.  It provides
  low-level access to most urlgrabber features from the shell.

  There are two types of options available for this program.  They are
  'client options' and 'module options'.  Client options apply
  specifically to the behavior of this client, whereas module options
  are built-in options to the urlgrabber module.  Both of these are
  avaible from the client command line, but they're documented a
  little differently.  Client options are documented here, and module
  options are documented through the '--help <option>' syntax.

CLIENT OPTIONS
  -h, --help

     In its short form, (-h) this provides a short usage discription.
     In its long form, it processes the remaining command line as help
     topics.  Legal topics are:
       doc          this info
       options      a list of module options
       <option(s)>  documentation for a given module option
       all          documentation for all module options

     Examples:
       urlgrabber --help options
       urlgrabber --help copy_local

  -o FILE

     By default, downloaded data will be written to a file named using
     the basename of the url.  For example,
     'http://foo.com/index.html' will be written to 'index.html'.  You
     can override this for your convenience or when necessary for urls
     like 'http://foo.com/'
     
  -O

     Print the local name of each downloaded file to STDOUT.  This is
     helpful when not using the '-o' option, but is particularly
     useful when using --copy_local=0 (the default) on local files
     because local files will not be copied and the output filename
     will not be the same as that provided with '-o'.

  --repeat=N

     Grab each url N times.  This is mostly for debugging keepalive.

  -p, --progress

     Use the default text-based progress meter.

  -v, --verbose=N

     Increment the verbosity level with each use of '-v' or set it
     directly with --verbose=N.  Currently, distinct levels are 0-2.
     The default is 0.

  -d SPEC, --debug=SPEC

     Turn on internal urlgrabber debugging.  This is equivalent (but
     overrides) running with the environment variable:
       URLGRABBER_DEBUG=SPEC 
     SPEC can be of the form LEVEL,FILENAME, where
     LEVEL can be string (DEBUG, WARN, etc) or number.
     FILENAME can be the name of a file or "-" for STDOUT.  The
     default is STDERR.  Example: -d1,- logs everything to STDOUT.
     Note: this only works for python > 2.3 because it requires the
     logging package.

  -D

     A convenience alias for: --verbose=3 --progress --debug=INFO,- 

  --profile

     Profile the actual fetching and print the results.

"""

MAINHELP = """usage: urlgrabber [options] <url>
urlgrabber - a simple client for the urlgrabber python package

options:
  -h, --help        print this message
  --help doc        print basic intro and documentation
  --help options    list available options to the grabber module
  --help <option>   print documentation for a module option
  --help all        print documentation for all module options
  --<option>=VAL    specify a module option. VAL must be a python value,
                    including quotes in the case of strings.
                    e.g.  --user_agent='"foobar/2.0"'

  --output FILE
  -o FILE           write output to FILE, otherwise the basename of the
                    url will be used
  -O                print the names of saved files to STDOUT
  --repeat=N        grab each URL N times (mostly for debugging keepalive)
  -p, --progress    use the default text progress meter
  -v                increment the verbosity level (defaults to 0)
  --verbose=N       set the verbosity level to N
  -d SPEC, --debug=SPEC
                    turn on urlgrabber module debugging with
                    SPEC=LEVEL,FILENAME.  e.g. -d 1,debug.txt
  -D                a convenience option equivalent to:
                    --verbose=3 --progress --debug=INFO,- 
  --profile         profile the actual fetching and print the results
  """

import sys
import getopt
import re

import urlgrabber.grabber
from urlgrabber.grabber import URLGrabber, URLGrabberOptions, URLGrabError

class client_options:
    def __init__(self):
        self.ug_options, self.ug_defaults = self.get_ug_options()
        self.process_command_line()
    
    def get_ug_options(self):
        ugo = URLGrabberOptions()
        ug_options = ['copy_local', 'keepalive', 'prefix', 'reget',
                      'data', 'quote', 'throttle', 'bandwidth',
                      'proxies', 'retry', 'retrycodes',
                      'range', 'user_agent', 
                      'http_headers', 'ftp_headers', 
                      'ssl_ca_cert', 'ssl_context',
                      'text', 'close_connection',
                      'cache_openers','timeout']
        options_exclude = ['delegate', 'interrupt_callback',
                           'failure_callback', 'urlparser', 'opener',
                           'checkfunc', 'progress_obj']
        for k in ugo.__dict__.keys():
            if (k not in ug_options) and (k not in options_exclude):
                ug_options.append(k)
                #print k
        ug_defaults = {}
        for k in list(ug_options):
            try:
                ug_defaults[k] = repr(getattr(ugo, k))
            except AttributeError:
                ug_options.remove(k)
        return ug_options, ug_defaults

    def process_command_line(self):
        short_options = 'vd:ho:OpD'
        long_options = ['profile', 'repeat=', 'verbose=',
                        'debug=', 'help', 'progress', 'output=']
        ug_long = [ o + '=' for o in self.ug_options ]
        try:
            optlist, args = getopt.getopt(sys.argv[1:], short_options,
                                          long_options + ug_long)
        except getopt.GetoptError as e:
            print("Error:", e, file=sys.stderr)
            self.help([], ret=1)

        self.verbose = 0
        self.debug = None
        self.outputfile = None
        self.localfile = 0
        self.repeat = 1
        self.progress = 0
        self.profile = 0
        self.ugops = {}
        self.args = args
        
        ug_dash = [ '--' + o for o in self.ug_options ]
        if not args: self.help(args)
        for (o, v) in optlist:
            if o == '--help' or o == '-h': self.help(args)
            if o == '--verbose': self.verbose = v
            if o == '-v':        self.verbose += 1
            if o == '-o':        self.outputfile = v
            if o == '--output':  self.outputfile = v
            if o == '-p' or o == '--progress': self.progress = 1
            if o == '-d' or o == '--debug': self.debug = v
            if o == '--profile': self.profile = 1
            if o == '-O': self.localfile = 1
            if o == '--repeat':
                try:
                    self.repeat = int(v)
                    if self.repeat < 1: raise ValueError()
                except ValueError:
                    print('ERROR: repeat value must be an int >= 1')
                    sys.exit(1)
            if o == '-D':
                self.verbose = 3
                self.debug = "INFO,-"
                self.progress = 1
            if o in ug_dash:
                try:
                    val = eval(v)
                except Exception as e:
                    print("error processing option value: %s" % v)
                    print(e)
                    sys.exit(1)
                else:
                    self.ugops[o[2:]] = val

        if len(self.args) > 1 and self.outputfile is not None:
            print("ERROR: cannot use -o when grabbing multiple files")
            sys.exit(1)

    def help(self, args, ret=0):
        if not args:
            print(MAINHELP)
        else:
            for a in args:
                m = getattr(self, 'help_'+a, None)
                if m is not None:
                    m()
                elif a in self.ug_options:
                    self.help_ug_option(a)
                else:
                    print('ERROR: no help on command "%s"' % a)
        sys.exit(ret)

    def help_doc(self):
        print(__doc__)

    def help_options(self):
        width = max(map(len, self.ug_options))
        format  = '  %-' + str(width) + 's = %s'
        hformat = '  %-' + str(width) + 's   %s'
        print(hformat % ('OPTION', 'DEFAULT'))
        print('-'*(width + 20))
        for k in self.ug_options:
            print(format % (k, self.ug_defaults[k]))

    def help_all(self):
        for k in self.ug_options:
            self.help_ug_option(k)

    def help_ug_option(self, option):
        help = ''
        m = re.search(r'^(  '+option+'.*?)\s*^ {,2}\S',
                     urlgrabber.grabber.__doc__, re.M|re.S)
        if m:
            print(m.group(1))
        else:
            print('  %s:  no help found for this option' % option)
        print('')
            
class ugclient:
    def __init__(self):
        op = client_options()
        self.op = op
        if op.verbose >= 2 and op.ugops:
            print("Module Options:")
            width = max(map(len, op.ugops.keys()))
            format = "  %-" + str(width) + "s = %s"
            for k, v in op.ugops.items():
                print(format % (k, repr(v)))

        if op.debug:
            self.set_debug_logger(op.debug)
            if hasattr(urlgrabber.grabber, '_log_package_state'):
                urlgrabber.grabber._log_package_state()

        kwargs = dict(op.ugops)
        if op.progress:
            from urlgrabber.progress import text_progress_meter
            kwargs['progress_obj'] = text_progress_meter()

        self.g = URLGrabber(**kwargs)

    def run(self):
        for url in self.op.args:
            if self.op.verbose: print('grabbing: %s' % url)
            try:
                for i in range(0, self.op.repeat):
                    f = self.g.urlgrab(url, self.op.outputfile)
                if self.op.localfile: print(f)
            except URLGrabError as e:
                print(e)
                sys.exit(1)
        
    def set_debug_logger(self, dbspec):
        try:
            dbinfo = dbspec.split(',')
            import logging
            level = logging._levelNames.get(dbinfo[0], None)
            if level is None: level = int(dbinfo[0])
            if level < 1: raise ValueError()
            
            formatter = logging.Formatter('%(asctime)s %(message)s')
            if len(dbinfo) > 1: filename = dbinfo[1]
            else: filename = ''
            if filename == '': handler = logging.StreamHandler(sys.stderr)
            elif filename == '-': handler = logging.StreamHandler(sys.stdout)
            else:  handler = logging.FileHandler(filename)
            handler.setFormatter(formatter)
            DBOBJ = logging.getLogger('urlgrabber')
            DBOBJ.addHandler(handler)
            DBOBJ.setLevel(level)
        except (KeyError, ImportError, ValueError):
            DBOBJ = None
        urlgrabber.grabber.set_logger(DBOBJ)

if __name__ == '__main__':
    ugc = ugclient()
    if ugc.op.profile:
        import profile
        import pstats
        prof = profile.Profile()
        prof.run('ugc.run()')
        pstats.Stats(prof).strip_dirs().sort_stats('cumulative').print_stats()
    else:
        ugc.run()