Merge remote-tracking branch 'upstream/master'
[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 from copy import deepcopy
7 import os
8 import subprocess
9 from tempfile import NamedTemporaryFile
10
11 from librarian import OutputFile
12 from librarian.cover import DefaultEbookCover
13 from librarian import get_resource
14
15
16 def transform(wldoc, verbose=False, sample=None, cover=None, 
17               use_kindlegen=False, flags=None):
18     """ produces a MOBI file
19
20     wldoc: a WLDocument
21     sample=n: generate sample e-book (with at least n paragraphs)
22     cover: a cover.Cover factory overriding default
23     flags: less-advertising,
24     """
25
26     document = deepcopy(wldoc)
27     del wldoc
28     book_info = document.book_info
29
30     if not flags:
31         flags = []
32     flags = list(flags)
33     
34     epub = document.as_epub(verbose=verbose, sample=sample,
35                             html_toc=True, cover=True, flags=flags)
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', 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(
48             ['kindlegen', '-c2', epub.get_filename(), '-o', output_file_basename],
49             **kwargs
50         )
51     else:
52         subprocess.check_call(
53             ['ebook-convert', epub.get_filename(), output_file.name,
54             '--no-inline-toc', 
55             '--mobi-file-type=both', 
56             '--mobi-ignore-margins'], **kwargs
57         )
58     return OutputFile.from_filename(output_file.name)