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