fix for error msg
[librarian.git] / src / librarian / packagers.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 print_function, unicode_literals
7
8 import os
9 from librarian import pdf, epub, mobi, DirDocProvider, ParseError
10 from librarian.parser import WLDocument
11
12 from .util import makedirs
13
14
15 class Packager(object):
16     cover = None
17     flags = None
18
19     @classmethod
20     def transform(cls, *args, **kwargs):
21         return cls.converter.transform(*args, **kwargs)
22
23     @classmethod
24     def prepare_file(cls, main_input, output_dir, verbose=False,
25                      overwrite=False):
26         path, fname = os.path.realpath(main_input).rsplit('/', 1)
27         provider = DirDocProvider(path)
28         slug, ext = os.path.splitext(fname)
29
30         if output_dir != '':
31             makedirs(output_dir)
32         outfile = os.path.join(output_dir, slug + '.' + cls.ext)
33         if os.path.exists(outfile) and not overwrite:
34             return
35
36         doc = WLDocument.from_file(main_input, provider=provider)
37         output_file = cls.transform(doc, cover=cls.cover, flags=cls.flags)
38         doc.save_output_file(output_file, output_path=outfile)
39
40     @classmethod
41     def prepare(cls, input_filenames, output_dir='', verbose=False,
42                 overwrite=False):
43         try:
44             for main_input in input_filenames:
45                 if verbose:
46                     print(main_input)
47                 cls.prepare_file(main_input, output_dir, verbose, overwrite)
48         except ParseError as e:
49             print('%(file)s:%(name)s:%(message)s' % {
50                 'file': main_input,
51                 'name': e.__class__.__name__,
52                 'message': e.message
53             })
54
55
56 class EpubPackager(Packager):
57     converter = epub
58     ext = 'epub'
59
60
61 class MobiPackager(Packager):
62     converter = mobi
63     ext = 'mobi'
64
65
66 class PdfPackager(Packager):
67     converter = pdf
68     ext = 'pdf'
69
70     @classmethod
71     def transform(cls, *args, **kwargs):
72         return cls.converter.transform(*args, morefloats='new', **kwargs)