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