1 # -*- coding: utf-8 -*-
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
6 from __future__ import with_statement
12 class UnicodeException(Exception):
14 """ Dirty workaround for Python Unicode handling problems. """
15 return unicode(self).encode('utf-8')
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
21 message = unicode(args)
22 except UnicodeDecodeError:
23 message = unicode(args, encoding='utf-8', errors='ignore')
26 class ParseError(UnicodeException):
29 class ValidationError(UnicodeException):
32 class NoDublinCore(ValidationError):
33 """There's no DublinCore section, and it's required."""
36 class NoProvider(UnicodeException):
37 """There's no DocProvider specified, and it's needed."""
40 class XMLNamespace(object):
41 '''A handy structure to repsent names in an XML namespace.'''
43 def __init__(self, uri):
46 def __call__(self, tag):
47 return '{%s}%s' % (self.uri, tag)
49 def __contains__(self, tag):
50 return tag.startswith('{' + str(self) + '}')
53 return 'XMLNamespace(%r)' % self.uri
56 return '%s' % self.uri
58 class EmptyNamespace(XMLNamespace):
60 super(EmptyNamespace, self).__init__('')
62 def __call__(self, tag):
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")
73 WLNS = EmptyNamespace()
77 """Represents a WL URI. Extracts slug from it."""
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]+)/?$')
84 def __init__(self, uri):
87 self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
91 match = cls._re_wl_uri.match(uri)
93 raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
94 uri, cls._re_wl_uri.pattern))
98 def from_slug(cls, slug):
99 """Contructs an URI from slug.
101 >>> WLURI.from_slug('a-slug').uri
102 u'http://wolnelektury.pl/katalog/lektura/a-slug/'
105 uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
108 def __unicode__(self):
114 def __eq__(self, other):
115 return self.slug == other.slug
118 class DocProvider(object):
119 """Base class for a repository of XML files.
121 Used for generating joined files, like EPUBs.
124 def by_slug(self, slug):
125 """Should return a file-like object with a WL document XML."""
126 raise NotImplementedError
128 def by_uri(self, uri, wluri=WLURI):
129 """Should return a file-like object with a WL document XML."""
131 return self.by_slug(wluri.slug)
134 class DirDocProvider(DocProvider):
135 """ Serve docs from a directory of files in form <slug>.xml """
137 def __init__(self, dir_):
141 def by_slug(self, slug):
142 fname = slug + '.xml'
143 return open(os.path.join(self.dir, fname))
146 import lxml.etree as etree
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"],
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],
167 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
169 def xinclude_forURI(uri):
170 e = etree.Element(XINS("include"))
172 return etree.tostring(e, encoding=unicode)
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
178 dcstring = etree.tostring(bookinfo.to_etree(), \
179 method='xml', encoding=unicode, pretty_print=True)
181 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
182 u'\n</plain-text>\n</utwor>'
185 def serialize_raw(element):
186 b = u'' + (element.text or '')
188 for child in element.iterchildren():
189 e = etree.tostring(child, method='xml', encoding=unicode,
196 'raw': serialize_raw,
199 def serialize_children(element, format='raw'):
200 return SERIALIZERS[format](element)
202 def get_resource(path):
203 return os.path.join(os.path.dirname(__file__), path)
206 class OutputFile(object):
207 """Represents a file returned by one of the converters."""
214 os.unlink(self._filename)
216 def __nonzero__(self):
217 return self._string is not None or self._filename is not None
220 def from_string(cls, string):
221 """Converter returns contents of a file as a string."""
224 instance._string = string
228 def from_filename(cls, filename):
229 """Converter returns contents of a file as a named file."""
232 instance._filename = filename
235 def get_string(self):
236 """Get file's contents as a string."""
238 if self._filename is not None:
239 with open(self._filename) as f:
245 """Get file as a file-like object."""
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)
253 def get_filename(self):
254 """Get file as a fs path."""
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)
263 self._filename = temp.name
264 return self._filename
268 def save_as(self, path):
269 """Save file to a path. Create directories, if necessary."""
271 dirname = os.path.dirname(os.path.abspath(path))
272 if not os.path.isdir(dirname):
274 shutil.copy(self.get_filename(), path)