Allow using remote cache for image downloading. Also, DRY in book2* scripts
[librarian.git] / librarian / book2anything.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 #
7 from collections import namedtuple
8 import os.path
9 import optparse
10
11 from librarian import DirDocProvider, ParseError
12 from librarian.parser import WLDocument
13 from librarian.cover import WLCover
14
15
16 class Option(object):
17     """Option for optparse. Use it like `optparse.OptionParser.add_option`."""
18     def __init__(self, *names, **options):
19         self.names = names
20         self.options = options
21
22     def add(self, parser):
23         parser.add_option(*self.names, **self.options)
24
25     def name(self):
26         return self.options['dest']
27
28     def value(self, options):
29         return getattr(options, self.name())
30
31
32 class Book2Anything(object):
33     """A class for creating book2... scripts.
34     
35     Subclass it for any format you want to convert to.
36     """
37     format_name = None # Set format name, like "PDF".
38     ext = None # Set file extension, like "pdf".
39     uses_cover = False # Can it add a cover?
40     cover_optional = True # Only relevant if uses_cover
41     uses_provider = False # Does it need a DocProvider?
42     transform = None # Transform method. Uses WLDocument.as_{ext} by default.
43     parser_options = [] # List of Option objects for additional parser args.
44     transform_options = [] # List of Option objects for additional transform args.
45     transform_flags = [] # List of Option objects for supported transform flags.
46
47
48     @classmethod
49     def run(cls):
50         # Parse commandline arguments
51         usage = """Usage: %%prog [options] SOURCE [SOURCE...]
52         Convert SOURCE files to %s format.""" % cls.format_name
53
54         parser = optparse.OptionParser(usage=usage)
55
56         parser.add_option('-v', '--verbose', 
57                 action='store_true', dest='verbose', default=False,
58                 help='print status messages to stdout')
59         parser.add_option('-d', '--make-dir',
60                 action='store_true', dest='make_dir', default=False,
61                 help='create a directory for author and put the output file in it')
62         parser.add_option('-o', '--output-file',
63                 dest='output_file', metavar='FILE',
64                 help='specifies the output file')
65         parser.add_option('-O', '--output-dir',
66                 dest='output_dir', metavar='DIR',
67                 help='specifies the directory for output')
68         if cls.uses_cover:
69             if cls.cover_optional:
70                 parser.add_option('-c', '--with-cover', 
71                         action='store_true', dest='with_cover', default=False,
72                         help='create default cover')
73             parser.add_option('-C', '--image-cache',
74                     dest='image_cache', metavar='URL',
75                     help='prefix for image download cache' +
76                         (' (implies --with-cover)' if cls.cover_optional else ''))
77         for option in cls.parser_options + cls.transform_options + cls.transform_flags:
78             option.add(parser)
79
80         options, input_filenames = parser.parse_args()
81
82         if len(input_filenames) < 1:
83             parser.print_help()
84             return(1)
85
86         # Prepare additional args for parser.
87         parser_args = {}
88         for option in cls.parser_options:
89             parser_args[option.name()] = option.value(options)
90         # Prepare additional args for transform method.
91         transform_args = {}
92         for option in cls.transform_options:
93             transform_args[option.name()] = option.value(options)
94         # Add flags to transform_args, if any.
95         transform_flags = [flag.name() for flag in cls.transform_flags
96                     if flag.value(options)]
97         if transform_flags:
98             transform_args['flags'] = transform_flags
99         # Add cover support, if any.
100         if cls.uses_cover:
101             if options.image_cache:
102                 transform_args['cover'] = lambda x: WLCover(x, image_cache = options.image_cache)
103             elif not cls.cover_optional or options.with_cover:
104                 transform_args['cover'] = WLCover
105
106
107         # Do some real work
108         try:
109             for main_input in input_filenames:
110                 if options.verbose:
111                     print main_input
112
113             # Where to find input?
114             if cls.uses_provider:
115                 path, fname = os.path.realpath(main_input).rsplit('/', 1)
116                 provider = DirDocProvider(path)
117             else:
118                 provider = None
119
120             # Where to write output?
121             if not (options.output_file or options.output_dir):
122                 output_file = os.path.splitext(main_input)[0] + '.' + cls.ext
123             else:
124                 output_file = None
125
126             # Do the transformation.
127             doc = WLDocument.from_file(main_input, provider=provider, **parser_args)
128             transform = cls.transform
129             if transform is None:
130                 transform = getattr(WLDocument, 'as_%s' % cls.ext)
131             output = transform(doc, **transform_args)
132
133             doc.save_output_file(output,
134                 output_file, options.output_dir, options.make_dir, cls.ext)
135
136         except ParseError, e:
137             print '%(file)s:%(name)s:%(message)s' % {
138                 'file': main_input,
139                 'name': e.__class__.__name__,
140                 'message': e
141             }