not-wl support in pdf
[librarian.git] / librarian / __init__.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 re
10 import shutil
11
12 class ParseError(Exception):
13     def __str__(self):
14         """ Dirty workaround for Python Unicode handling problems. """
15         return self.message
16
17     def __unicode__(self):
18         """ Dirty workaround for Python Unicode handling problems. """
19         return self.message
20
21 class ValidationError(Exception):
22     pass
23
24 class NoDublinCore(ValidationError):
25     """There's no DublinCore section, and it's required."""
26     pass
27
28 class NoProvider(Exception):
29     """There's no DocProvider specified, and it's needed."""
30     pass
31
32 class XMLNamespace(object):
33     '''A handy structure to repsent names in an XML namespace.'''
34
35     def __init__(self, uri):
36         self.uri = uri
37
38     def __call__(self, tag):
39         return '{%s}%s' % (self.uri, tag)
40
41     def __contains__(self, tag):
42         return tag.startswith('{' + str(self) + '}')
43
44     def __repr__(self):
45         return 'XMLNamespace(%r)' % self.uri
46
47     def __str__(self):
48         return '%s' % self.uri
49
50 class EmptyNamespace(XMLNamespace):
51     def __init__(self):
52         super(EmptyNamespace, self).__init__('')
53
54     def __call__(self, tag):
55         return tag
56
57 # some common namespaces we use
58 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
59 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
60 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
61 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
62 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
63 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
64
65 WLNS = EmptyNamespace()
66
67
68 class WLURI(object):
69     """Represents a WL URI. Extracts slug from it."""
70     slug = None
71
72     example = 'http://wolnelektury.pl/katalog/lektura/template/'
73     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
74             '(?P<slug>[-a-z0-9]+)/?$')
75
76     def __init__(self, uri):
77         uri = unicode(uri)
78         self.uri = uri
79         self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
80
81     @classmethod
82     def strict(cls, uri):
83         match = cls._re_wl_uri.match(uri)
84         if not match:
85             raise ValueError('Supplied URI (%s) does not match '
86                 'the template: %s.' % (uri, cls._re_wl_uri))
87         return cls(uri)
88
89     @classmethod
90     def from_slug(cls, slug):
91         """Contructs an URI from slug.
92
93         >>> WLURI.from_slug('a-slug').uri
94         u'http://wolnelektury.pl/katalog/lektura/a-slug/'
95
96         """
97         uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
98         return cls(uri)
99
100     def __unicode__(self):
101         return self.uri
102
103     def __str__(self):
104         return self.uri
105
106     def __eq__(self, other):
107         return self.slug == other.slug
108
109
110 class DocProvider(object):
111     """Base class for a repository of XML files.
112
113     Used for generating joined files, like EPUBs.
114     """
115
116     def by_slug(self, slug):
117         """Should return a file-like object with a WL document XML."""
118         raise NotImplementedError
119
120     def by_uri(self, uri, wluri=WLURI):
121         """Should return a file-like object with a WL document XML."""
122         wluri = wluri(uri)
123         return self.by_slug(wluri.slug)
124
125
126 class DirDocProvider(DocProvider):
127     """ Serve docs from a directory of files in form <slug>.xml """
128
129     def __init__(self, dir_):
130         self.dir = dir_
131         self.files = {}
132
133     def by_slug(self, slug):
134         fname = slug + '.xml'
135         return open(os.path.join(self.dir, fname))
136
137
138 import lxml.etree as etree
139 import dcparser
140
141 DEFAULT_BOOKINFO = dcparser.BookInfo(
142         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
143         { DCNS('creator'): [u'Some, Author'],
144           DCNS('title'): [u'Some Title'],
145           DCNS('subject.period'): [u'Unknown'],
146           DCNS('subject.type'): [u'Unknown'],
147           DCNS('subject.genre'): [u'Unknown'],
148           DCNS('date'): ['1970-01-01'],
149           DCNS('language'): [u'pol'],
150           # DCNS('date'): [creation_date],
151           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
152           DCNS('description'):
153           [u"""Publikacja zrealizowana w ramach projektu
154              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
155              wykonana przez Bibliotekę Narodową z egzemplarza
156              pochodzącego ze zbiorów BN."""],
157           DCNS('identifier.url'): [WLURI.example],
158           DCNS('rights'):
159             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
160
161 def xinclude_forURI(uri):
162     e = etree.Element(XINS("include"))
163     e.set("href", uri)
164     return etree.tostring(e, encoding=unicode)
165
166 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
167     """Wrap the text within the minimal XML structure with a DC template."""
168     bookinfo.created_at = creation_date
169
170     dcstring = etree.tostring(bookinfo.to_etree(), \
171         method='xml', encoding=unicode, pretty_print=True)
172
173     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
174         u'\n</plain-text>\n</utwor>'
175
176
177 def serialize_raw(element):
178     b = u'' + (element.text or '')
179
180     for child in element.iterchildren():
181         e = etree.tostring(child, method='xml', encoding=unicode,
182                 pretty_print=True)
183         b += e
184
185     return b
186
187 SERIALIZERS = {
188     'raw': serialize_raw,
189 }
190
191 def serialize_children(element, format='raw'):
192     return SERIALIZERS[format](element)
193
194 def get_resource(path):
195     return os.path.join(os.path.dirname(__file__), path)
196
197
198 class OutputFile(object):
199     """Represents a file returned by one of the converters."""
200
201     _string = None
202     _filename = None
203
204     def __del__(self):
205         if self._filename:
206             os.unlink(self._filename)
207
208     def __nonzero__(self):
209         return self._string is not None or self._filename is not None
210
211     @classmethod
212     def from_string(cls, string):
213         """Converter returns contents of a file as a string."""
214
215         instance = cls()
216         instance._string = string
217         return instance
218
219     @classmethod
220     def from_filename(cls, filename):
221         """Converter returns contents of a file as a named file."""
222
223         instance = cls()
224         instance._filename = filename
225         return instance
226
227     def get_string(self):
228         """Get file's contents as a string."""
229
230         if self._filename is not None:
231             with open(self._filename) as f:
232                 return f.read()
233         else:
234             return self._string
235
236     def get_file(self):
237         """Get file as a file-like object."""
238
239         if self._string is not None:
240             from StringIO import StringIO
241             return StringIO(self._string)
242         elif self._filename is not None:
243             return open(self._filename)
244
245     def get_filename(self):
246         """Get file as a fs path."""
247
248         if self._filename is not None:
249             return self._filename
250         elif self._string is not None:
251             from tempfile import NamedTemporaryFile
252             temp = NamedTemporaryFile(prefix='librarian-', delete=False)
253             temp.write(self._string)
254             temp.close()
255             self._filename = temp.name
256             return self._filename
257         else:
258             return None
259
260     def save_as(self, path):
261         """Save file to a path. Create directories, if necessary."""
262
263         dirname = os.path.dirname(os.path.abspath(path))
264         if not os.path.isdir(dirname):
265             os.makedirs(dirname)
266         shutil.copy(self.get_filename(), path)