52234fe2f315dacc0413aacbb8e0849ab9b939b9
[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 and language from it."""
70     DEFAULT_LANGUAGE = u'pol'
71
72     slug = None
73     language = None
74
75     example = 'http://wolnelektury.pl/katalog/lektura/template/'
76     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
77             '(?P<slug>[-a-z]+)(/(?P<lang>[a-z]{3})/?)?')
78
79     def __init__(self, uri=None):
80         if uri is not None:
81             self.uri = uri
82             match = self._re_wl_uri.match(uri)
83             assert match
84             self.slug = match.group('slug')
85             self.language = match.group('lang') or self.DEFAULT_LANGUAGE
86
87     @classmethod
88     def from_slug_and_lang(cls, slug, lang):
89         """Contructs an URI from slug and language code.
90
91         >>> WLURI.from_slug_and_lang('a-slug', WLURI.DEFAULT_LANGUAGE).uri
92         'http://wolnelektury.pl/katalog/lektura/a-slug/'
93         >>> WLURI.from_slug_and_lang('a-slug', 'deu').uri
94         'http://wolnelektury.pl/katalog/lektura/a-slug/deu/'
95
96         """
97         if lang is None:
98             lang = self.DEFAULT_LANGUAGE
99         uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
100         if lang is not None and lang != cls.DEFAULT_LANGUAGE:
101             uri += lang + '/'
102         instance = cls()
103         instance.slug = slug
104         instance.language = lang
105         instance.uri = uri
106         return instance
107
108     def __unicode__(self):
109         return self.uri
110
111     def __eq__(self, other):
112         return self.slug, self.language == other.slug, other.language
113
114     def filename_stem(self):
115         stem = self.slug
116         if self.language != self.DEFAULT_LANGUAGE:
117             stem += '_' + self.language
118         return stem
119
120     def validate_language(self, language):
121         if language != self.language:
122             raise ValidationError("Incorrect language definition in URI")
123
124
125 class DocProvider(object):
126     """Base class for a repository of XML files.
127
128     Used for generating joined files, like EPUBs.
129     """
130
131     def by_slug_and_lang(self, slug, lang=None):
132         """Should return a file-like object with a WL document XML."""
133         raise NotImplementedError
134
135     def by_slug(self, slug):
136         """Should return a file-like object with a WL document XML."""
137         return self.by_slug_and_lang(slug)
138
139     def by_uri(self, uri):
140         """Should return a file-like object with a WL document XML."""
141         wluri = WLURI(uri)
142         return self.by_slug_and_lang(wluri.slug, wluri.language)
143
144
145 class DirDocProvider(DocProvider):
146     """ Serve docs from a directory of files in form <slug>.xml """
147
148     def __init__(self, dir_):
149         self.dir = dir_
150         self.files = {}
151         return super(DirDocProvider, self).__init__()
152
153     def by_slug_and_lang(self, slug, lang=None):
154         fname = WLURI.from_slug_and_lang(slug, lang).filename_stem() + '.xml'
155         return open(os.path.join(self.dir, fname))
156
157
158 import lxml.etree as etree
159 import dcparser
160
161 DEFAULT_BOOKINFO = dcparser.BookInfo(
162         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
163         { DCNS('creator'): [u'Some, Author'],
164           DCNS('title'): [u'Some Title'],
165           DCNS('subject.period'): [u'Unknown'],
166           DCNS('subject.type'): [u'Unknown'],
167           DCNS('subject.genre'): [u'Unknown'],
168           DCNS('date'): ['1970-01-01'],
169           DCNS('language'): [WLURI.DEFAULT_LANGUAGE],
170           # DCNS('date'): [creation_date],
171           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
172           DCNS('description'):
173           [u"""Publikacja zrealizowana w ramach projektu
174              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
175              wykonana przez Bibliotekę Narodową z egzemplarza
176              pochodzącego ze zbiorów BN."""],
177           DCNS('identifier.url'): [WLURI.example],
178           DCNS('rights'):
179             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
180
181 def xinclude_forURI(uri):
182     e = etree.Element(XINS("include"))
183     e.set("href", uri)
184     return etree.tostring(e, encoding=unicode)
185
186 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
187     """Wrap the text within the minimal XML structure with a DC template."""
188     bookinfo.created_at = creation_date
189
190     dcstring = etree.tostring(bookinfo.to_etree(), \
191         method='xml', encoding=unicode, pretty_print=True)
192
193     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
194         u'\n</plain-text>\n</utwor>'
195
196
197 def serialize_raw(element):
198     b = u'' + (element.text or '')
199
200     for child in element.iterchildren():
201         e = etree.tostring(child, method='xml', encoding=unicode,
202                 pretty_print=True)
203         b += e
204
205     return b
206
207 SERIALIZERS = {
208     'raw': serialize_raw,
209 }
210
211 def serialize_children(element, format='raw'):
212     return SERIALIZERS[format](element)
213
214 def get_resource(path):
215     return os.path.join(os.path.dirname(__file__), path)
216
217
218 class OutputFile(object):
219     """Represents a file returned by one of the converters."""
220
221     _string = None
222     _filename = None
223
224     def __del__(self):
225         if self._filename:
226             os.unlink(self._filename)
227
228     def __nonzero__(self):
229         return self._string is not None or self._filename is not None
230
231     @classmethod
232     def from_string(cls, string):
233         """Converter returns contents of a file as a string."""
234
235         instance = cls()
236         instance._string = string
237         return instance
238
239     @classmethod
240     def from_filename(cls, filename):
241         """Converter returns contents of a file as a named file."""
242
243         instance = cls()
244         instance._filename = filename
245         return instance
246
247     def get_string(self):
248         """Get file's contents as a string."""
249
250         if self._filename is not None:
251             with open(self._filename) as f:
252                 return f.read()
253         else:
254             return self._string
255
256     def get_file(self):
257         """Get file as a file-like object."""
258
259         if self._string is not None:
260             from StringIO import StringIO
261             return StringIO(self._string)
262         elif self._filename is not None:
263             return open(self._filename)
264
265     def get_filename(self):
266         """Get file as a fs path."""
267
268         if self._filename is not None:
269             return self._filename
270         elif self._string is not None:
271             from tempfile import NamedTemporaryFile
272             temp = NamedTemporaryFile(prefix='librarian-', delete=False)
273             temp.write(self._string)
274             temp.close()
275             self._filename = temp.name
276             return self._filename
277         else:
278             return None
279
280     def save_as(self, path):
281         """Save file to a path. Create directories, if necessary."""
282
283         dirname = os.path.dirname(os.path.abspath(path))
284         if not os.path.isdir(dirname):
285             os.makedirs(dirname)
286         shutil.copy(self.get_filename(), path)