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