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