fix #3663: changed and updated sort keys
[librarian.git] / 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
7 from copy import deepcopy
8 import os
9 import subprocess
10 from tempfile import NamedTemporaryFile
11
12 from librarian import OutputFile
13
14
15 def transform(wldoc, verbose=False, sample=None, cover=None,
16               use_kindlegen=False, flags=None):
17     """ produces a MOBI file
18
19     wldoc: a WLDocument
20     sample=n: generate sample e-book (with at least n paragraphs)
21     cover: a cover.Cover factory overriding default
22     flags: less-advertising,
23     """
24
25     document = deepcopy(wldoc)
26     del wldoc
27
28     epub = document.as_epub(verbose=verbose, sample=sample,
29                             html_toc=True, cover=cover or True, flags=flags)
30     if verbose:
31         kwargs = {}
32     else:
33         devnull = open("/dev/null", 'w')
34         kwargs = {"stdout": devnull, "stderr": devnull}
35
36     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
37                                      delete=False)
38     output_file.close()
39
40     if use_kindlegen:
41         output_file_basename = os.path.basename(output_file.name)
42         subprocess.check_call(['kindlegen', '-c2', epub.get_filename(),
43                               '-o', output_file_basename], **kwargs)
44     else:
45         subprocess.check_call(['ebook-convert', epub.get_filename(),
46                                output_file.name, '--no-inline-toc',
47                                '--mobi-file-type=both',
48                                '--mobi-ignore-margins'], **kwargs)
49     return OutputFile.from_filename(output_file.name)