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 collections import namedtuple
11 from librarian import DirDocProvider, ParseError
12 from librarian.parser import WLDocument
13 from librarian.cover import DefaultEbookCover
17 """Option for optparse. Use it like `optparse.OptionParser.add_option`."""
18 def __init__(self, *names, **options):
20 self.options = options
22 def add(self, parser):
23 parser.add_option(*self.names, **self.options)
26 return self.options['dest']
28 def value(self, options):
29 return getattr(options, self.name())
32 class Book2Anything(object):
33 """A class for creating book2... scripts.
35 Subclass it for any format you want to convert to.
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.
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',
57 action='store_true', dest='verbose', default=False,
58 help='print status messages to stdout')
59 parser.add_option('-t', '--html-toc',
60 action='store_true', dest='html_toc', default=False,
61 help='with inline html toc')
62 parser.add_option('-d', '--make-dir',
63 action='store_true', dest='make_dir', default=False,
64 help='create a directory for author and put the output file in it')
65 parser.add_option('-o', '--output-file',
66 dest='output_file', metavar='FILE',
67 help='specifies the output file')
68 parser.add_option('-O', '--output-dir',
69 dest='output_dir', metavar='DIR',
70 help='specifies the directory for output')
72 if cls.cover_optional:
73 parser.add_option('-c', '--with-cover',
74 action='store_true', dest='with_cover', default=False,
75 help='create default cover')
76 parser.add_option('-C', '--image-cache',
77 dest='image_cache', metavar='URL',
78 help='prefix for image download cache' +
79 (' (implies --with-cover)' if cls.cover_optional else ''))
80 for option in cls.parser_options + cls.transform_options + cls.transform_flags:
83 options, input_filenames = parser.parse_args()
85 if len(input_filenames) < 1:
89 # Prepare additional args for parser.
91 for option in cls.parser_options:
92 parser_args[option.name()] = option.value(options)
93 # Prepare additional args for transform method.
95 for option in cls.transform_options:
96 transform_args[option.name()] = option.value(options)
97 # Add flags to transform_args, if any.
98 transform_flags = [flag.name() for flag in cls.transform_flags
99 if flag.value(options)]
101 transform_args['flags'] = transform_flags
102 # Add cover support, if any.
104 transform_args['html_toc'] = True
106 if options.image_cache:
107 def cover_class(*args, **kwargs):
108 return DefaultEbookCover(image_cache=options.image_cache, *args, **kwargs)
109 transform_args['cover'] = cover_class
110 elif not cls.cover_optional or options.with_cover:
111 transform_args['cover'] = DefaultEbookCover
116 for main_input in input_filenames:
120 # Where to find input?
121 if cls.uses_provider:
122 path, fname = os.path.realpath(main_input).rsplit('/', 1)
123 provider = DirDocProvider(path)
127 # Where to write output?
128 if not (options.output_file or options.output_dir):
129 output_file = os.path.splitext(main_input)[0] + '.' + cls.ext
133 # Do the transformation.
134 doc = WLDocument.from_file(main_input, provider=provider, **parser_args)
135 transform = cls.transform
136 if transform is None:
137 transform = getattr(WLDocument, 'as_%s' % cls.ext)
138 output = transform(doc, **transform_args)
140 doc.save_output_file(output,
141 output_file, options.output_dir, options.make_dir, cls.ext)
143 except ParseError, e:
144 print '%(file)s:%(name)s:%(message)s' % {
146 'name': e.__class__.__name__,