2 # -*- coding: utf-8 -*-
4 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
5 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
7 from __future__ import print_function, unicode_literals
12 from librarian import DirDocProvider, ParseError
13 from librarian.parser import WLDocument
14 from librarian.cover import make_cover
18 """Option for optparse. Use it like `optparse.OptionParser.add_option`."""
19 def __init__(self, *names, **options):
21 self.options = options
23 def add(self, parser):
24 parser.add_option(*self.names, **self.options)
27 return self.options['dest']
29 def value(self, options):
30 return getattr(options, self.name())
33 class Book2Anything(object):
34 """A class for creating book2... scripts.
36 Subclass it for any format you want to convert to.
38 format_name = None # Set format name, like "PDF".
39 ext = None # Set file extension, like "pdf".
40 uses_cover = False # Can it add a cover?
41 cover_optional = True # Only relevant if uses_cover
42 uses_provider = False # Does it need a DocProvider?
43 transform = None # Transform method. Uses WLDocument.as_{ext} by default.
44 parser_options = [] # List of Option objects for additional parser args.
45 transform_options = [] # List of Option objects for additional transform args.
46 transform_flags = [] # List of Option objects for supported transform flags.
50 # Parse commandline arguments
51 usage = """Usage: %%prog [options] SOURCE [SOURCE...]
52 Convert SOURCE files to %s format.""" % cls.format_name
54 parser = optparse.OptionParser(usage=usage)
56 parser.add_option('-v', '--verbose', action='store_true', dest='verbose', default=False,
57 help='print status messages to stdout')
58 parser.add_option('-d', '--make-dir', action='store_true', dest='make_dir', default=False,
59 help='create a directory for author and put the output file in it')
60 parser.add_option('-o', '--output-file', dest='output_file', metavar='FILE',
61 help='specifies the output file')
62 parser.add_option('-O', '--output-dir', dest='output_dir', metavar='DIR',
63 help='specifies the directory for output')
65 if cls.cover_optional:
66 parser.add_option('-c', '--with-cover', action='store_true', dest='with_cover', default=False,
67 help='create default cover')
68 parser.add_option('-C', '--image-cache', dest='image_cache', metavar='URL',
69 help='prefix for image download cache' +
70 (' (implies --with-cover)' if cls.cover_optional else ''))
71 for option in cls.parser_options + cls.transform_options + cls.transform_flags:
74 options, input_filenames = parser.parse_args()
76 if len(input_filenames) < 1:
80 # Prepare additional args for parser.
82 for option in cls.parser_options:
83 parser_args[option.name()] = option.value(options)
84 # Prepare additional args for transform method.
86 for option in cls.transform_options:
87 transform_args[option.name()] = option.value(options)
88 # Add flags to transform_args, if any.
89 transform_flags = [flag.name() for flag in cls.transform_flags if flag.value(options)]
91 transform_args['flags'] = transform_flags
93 transform_args['verbose'] = True
94 # Add cover support, if any.
96 if options.image_cache:
97 def cover_class(book_info, *args, **kwargs):
98 return make_cover(book_info, image_cache=options.image_cache, *args, **kwargs)
99 transform_args['cover'] = cover_class
100 elif not cls.cover_optional or options.with_cover:
101 transform_args['cover'] = make_cover
105 for main_input in input_filenames:
109 if isinstance(main_input, six.binary_type):
110 main_input = main_input.decode('utf-8')
112 # Where to find input?
113 if cls.uses_provider:
114 path, fname = os.path.realpath(main_input).rsplit('/', 1)
115 provider = DirDocProvider(path)
119 # Where to write output?
120 if not (options.output_file or options.output_dir):
121 output_file = os.path.splitext(main_input)[0] + '.' + cls.ext
123 output_file = options.output_file
125 # Do the transformation.
126 doc = WLDocument.from_file(main_input, provider=provider, **parser_args)
127 transform = cls.transform
128 if transform is None:
129 transform = getattr(WLDocument, 'as_%s' % cls.ext)
130 output = transform(doc, **transform_args)
132 doc.save_output_file(output, output_file, options.output_dir, options.make_dir, cls.ext)
134 except ParseError as e:
135 print('%(file)s:%(name)s:%(message)s' % {
137 'name': e.__class__.__name__,