fix expected html output to contain secX anchors
[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 WLCover
13 from librarian import get_resource
14
15
16 def transform(wldoc, verbose=False,
17               sample=None, cover=None, 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 object
23     flags: less-advertising,
24     """
25
26     document = deepcopy(wldoc)
27     del wldoc
28     book_info = document.book_info
29
30     # provide a cover by default
31     if not cover:
32         cover = WLCover
33     cover_file = NamedTemporaryFile(suffix='.png', delete=False)
34     c = cover(book_info)
35     c.save(cover_file)
36
37     if cover.uses_dc_cover:
38         if document.book_info.cover_by:
39             document.edoc.getroot().set('data-cover-by', document.book_info.cover_by)
40         if document.book_info.cover_source:
41             document.edoc.getroot().set('data-cover-source', document.book_info.cover_source)
42
43     if not flags:
44         flags = []
45     flags = list(flags) + ['without-fonts']
46     epub = document.as_epub(verbose=verbose, sample=sample, html_toc=True,
47             flags=flags, style=get_resource('mobi/style.css'))
48
49     if verbose:
50         kwargs = {}
51     else:
52         devnull = open("/dev/null", 'w')
53         kwargs = {"stdout": devnull, "stderr": devnull}
54
55     output_file = NamedTemporaryFile(prefix='librarian', suffix='.mobi', delete=False)
56     output_file.close()
57     subprocess.check_call(['ebook-convert', epub.get_filename(), output_file.name,
58             '--no-inline-toc', '--cover=%s' % cover_file.name], **kwargs)
59     os.unlink(cover_file.name)
60     return OutputFile.from_filename(output_file.name)