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