book2mobi (using calibre)
[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 __future__ import with_statement
7
8 import os
9 import os.path
10 import subprocess
11 from StringIO import StringIO
12 from copy import deepcopy
13 from lxml import etree
14 import zipfile
15 from tempfile import NamedTemporaryFile
16 from shutil import rmtree
17
18 import sys
19
20 from librarian import epub
21
22 from librarian import functions, get_resource
23
24
25 def transform(provider, slug=None, file_path=None, output_file=None, output_dir=None, make_dir=False, verbose=False,
26               sample=None, cover=None, flags=None):
27     """ produces a MOBI file
28
29     provider: a DocProvider
30     slug: slug of file to process, available by provider
31     output_file: path to output file
32     output_dir: path to directory to save output file to; either this or output_file must be present
33     make_dir: writes output to <output_dir>/<author>/<slug>.epub instead of <output_dir>/<slug>.epub
34     sample=n: generate sample e-book (with at least n paragraphs)
35     cover: a cover.Cover object
36     flags: less-advertising,
37     """
38
39     # if output to dir, create the file
40     if output_dir is not None:
41         if make_dir:
42             author = unicode(book_info.author)
43             output_dir = os.path.join(output_dir, author)
44             try:
45                 os.makedirs(output_dir)
46             except OSError:
47                 pass
48         if slug:
49             output_file = os.path.join(output_dir, '%s.mobi' % slug)
50         else:
51             output_file = os.path.join(output_dir, os.path.splitext(os.path.basename(file_path))[0] + '.mobi')
52
53     epub_file = NamedTemporaryFile(suffix='.epub', delete=False)
54     if not flags:
55         flags = []
56     flags = list(flags) + ['without-fonts']
57     epub.transform(provider, file_path=file_path, output_file=epub_file, verbose=verbose,
58               sample=sample, cover=None, flags=flags, style=get_resource('mobi/style.css'))
59     subprocess.check_call(['ebook-convert', epub_file.name, output_file])
60     os.unlink(epub_file.name)