6f1f5d6bfb62796a15f92e1d8acbcaa2054800a3
[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                             html_toc=True, cover=cover or True, flags=flags,
34                             hyphenate=hyphenate, ilustr_path=ilustr_path, output_type='mobi')
35     if verbose:
36         kwargs = {}
37     else:
38         devnull = open("/dev/null", 'w')
39         kwargs = {"stdout": devnull, "stderr": devnull}
40
41     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
42                                      delete=False)
43     output_file.close()
44
45     if use_kindlegen:
46         output_file_basename = os.path.basename(output_file.name)
47         subprocess.check_call([converter_path or 'kindlegen',
48                                '-c2', epub.get_filename(),
49                                '-o', output_file_basename], **kwargs)
50     else:
51         subprocess.check_call([converter_path or 'ebook-convert',
52                                epub.get_filename(),
53                                output_file.name, '--no-inline-toc',
54                                '--mobi-file-type=both',
55                                '--mobi-ignore-margins'], **kwargs)
56     return OutputFile.from_filename(output_file.name)