1'''
2Directory output OEBBook writer.
3'''
4
5
6__license__   = 'GPL v3'
7__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
8
9import os
10from calibre.ebooks.oeb.base import OPF_MIME, xml2str
11from calibre.ebooks.oeb.base import DirContainer, OEBError
12
13__all__ = ['OEBWriter']
14
15
16class OEBWriter:
17    DEFAULT_PROFILE = 'PRS505'
18    """Default renderer profile for content written with this Writer."""
19
20    TRANSFORMS = []
21    """List of transforms to apply to content written with this Writer."""
22
23    def __init__(self, version='2.0', page_map=False, pretty_print=False):
24        self.version = version
25        self.page_map = page_map
26        self.pretty_print = pretty_print
27
28    @classmethod
29    def config(cls, cfg):
30        """Add any book-writing options to the :class:`Config` object
31        :param:`cfg`.
32        """
33        oeb = cfg.add_group('oeb', _('OPF/NCX/etc. generation options.'))
34        versions = ['1.2', '2.0']
35        oeb('opf_version', ['--opf-version'], default='2.0', choices=versions,
36            help=_('OPF version to generate. Default is %default.'))
37        oeb('adobe_page_map', ['--adobe-page-map'], default=False,
38            help=_('Generate an Adobe "page-map" file if pagination '
39                   'information is available.'))
40        return cfg
41
42    @classmethod
43    def generate(cls, opts):
44        """Generate a Writer instance from command-line options."""
45        version = opts.opf_version
46        page_map = opts.adobe_page_map
47        pretty_print = opts.pretty_print
48        return cls(version=version, page_map=page_map,
49                   pretty_print=pretty_print)
50
51    def __call__(self, oeb, path):
52        """
53        Write the book in the :class:`OEBBook` object :param:`oeb` to a folder
54        at :param:`path`.
55        """
56        version = int(self.version[0])
57        opfname = None
58        if os.path.splitext(path)[1].lower() == '.opf':
59            opfname = os.path.basename(path)
60            path = os.path.dirname(path)
61        if not os.path.isdir(path):
62            os.mkdir(path)
63        output = DirContainer(path, oeb.log)
64        for item in oeb.manifest.values():
65            output.write(item.href, item.bytes_representation)
66
67        if version == 1:
68            metadata = oeb.to_opf1()
69        elif version == 2:
70            metadata = oeb.to_opf2(page_map=self.page_map)
71        else:
72            raise OEBError("Unrecognized OPF version %r" % self.version)
73        pretty_print = self.pretty_print
74        for mime, (href, data) in metadata.items():
75            if opfname and mime == OPF_MIME:
76                href = opfname
77            output.write(href, xml2str(data, pretty_print=pretty_print))
78        return
79