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