Response images.
[librarian.git] / src / librarian / mobi.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from __future__ import unicode_literals
7
8 from copy import deepcopy
9 import os
10 import subprocess
11 from tempfile import NamedTemporaryFile
12
13 from librarian import OutputFile
14
15
16 def transform(wldoc, verbose=False, sample=None, cover=None,
17               use_kindlegen=False, flags=None, hyphenate=True, ilustr_path='',
18               converter_path=None):
19     """ produces a MOBI file
20
21     wldoc: a WLDocument
22     sample=n: generate sample e-book (with at least n paragraphs)
23     cover: a cover.Cover factory overriding default
24     flags: less-advertising,
25     converter_path: override path to MOBI converter,
26       either ebook-convert or kindlegen
27     """
28
29     document = deepcopy(wldoc)
30     del wldoc
31
32     epub = document.as_epub(verbose=verbose, sample=sample,
33                             cover=cover or True, flags=flags,
34                             hyphenate=hyphenate, ilustr_path=ilustr_path,
35                             output_type='mobi')
36     if verbose:
37         kwargs = {}
38     else:
39         devnull = open("/dev/null", 'w')
40         kwargs = {"stdout": devnull, "stderr": devnull}
41
42     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
43                                      delete=False)
44     output_file.close()
45
46     if use_kindlegen:
47         output_file_basename = os.path.basename(output_file.name)
48         subprocess.check_call([converter_path or 'kindlegen',
49                                '-c2', epub.get_filename(),
50                                '-o', output_file_basename], **kwargs)
51     else:
52         subprocess.check_call([converter_path or 'ebook-convert',
53                                epub.get_filename(),
54                                output_file.name, '--no-inline-toc',
55                                '--mobi-file-type=both',
56                                '--mobi-ignore-margins'], **kwargs)
57     return OutputFile.from_filename(output_file.name)