b30c1fefa79a4ff3ac634db6db3cf1e68d2d7990
[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 from librarian.cover import DefaultEbookCover
14 from librarian import get_resource
15
16
17 def transform(wldoc, verbose=False, sample=None, cover=None,
18               use_kindlegen=False, flags=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     """
26
27     document = deepcopy(wldoc)
28     del wldoc
29     book_info = document.book_info
30
31     if not flags:
32         flags = []
33     flags = list(flags)
34
35     epub = document.as_epub(verbose=verbose, sample=sample,
36                             html_toc=True, cover=True, flags=flags)
37     if verbose:
38         kwargs = {}
39     else:
40         devnull = open("/dev/null", 'w')
41         kwargs = {"stdout": devnull, "stderr": devnull}
42
43     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
44                                      delete=False)
45     output_file.close()
46
47     if use_kindlegen:
48         output_file_basename = os.path.basename(output_file.name)
49         subprocess.check_call(['kindlegen', '-c2', epub.get_filename(),
50                               '-o', output_file_basename], **kwargs)
51     else:
52         subprocess.check_call(['ebook-convert', 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)