release
[librarian.git] / src / librarian / builders / mobi.py
1 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 import os
5 import subprocess
6 from tempfile import NamedTemporaryFile
7 from librarian import functions, get_resource, OutputFile
8 from librarian.hyphenator import Hyphenator
9 from .epub import EpubBuilder
10
11
12 class MobiBuilder(EpubBuilder):
13     file_extension = 'mobi'
14     isbn_field = 'isbn_mobi'
15
16     def build(self, document, use_kindlegen=False, converter_path=None, **kwargs):
17         bibl_lng = document.meta.language
18         short_lng = functions.lang_code_3to2(bibl_lng)
19         try:
20             self.hyphenator = Hyphenator(get_resource('res/hyph-dictionaries/hyph_' +
21                                        short_lng + '.dic'))
22         except:
23             pass
24
25         epub = super().build(document, **kwargs)
26
27         devnull = open("/dev/null", 'w')
28         gen_kwargs = {"stdout": devnull, "stderr": devnull}
29
30         output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi',
31                                      delete=False)
32         output_file.close()
33
34         if use_kindlegen:
35             output_file_basename = os.path.basename(output_file.name)
36             subprocess.check_call([converter_path or 'kindlegen',
37                                '-c2', epub.get_filename(),
38                                '-o', output_file_basename], **gen_kwargs)
39         else:
40             subprocess.check_call([converter_path or 'ebook-convert',
41                                epub.get_filename(),
42                                output_file.name, '--no-inline-toc',
43                                '--mobi-file-type=both',
44                                '--mobi-ignore-margins',
45                                ], **gen_kwargs)
46         devnull.close()
47         return OutputFile.from_filename(output_file.name)
48