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
13 from wolnelektury.utils import makedirs
16 class UnicodeException(Exception):
18 """ Dirty workaround for Python Unicode handling problems. """
19 return unicode(self).encode('utf-8')
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
25 message = unicode(args)
26 except UnicodeDecodeError:
27 message = unicode(args, encoding='utf-8', errors='ignore')
30 class ParseError(UnicodeException):
33 class ValidationError(UnicodeException):
36 class NoDublinCore(ValidationError):
37 """There's no DublinCore section, and it's required."""
40 class NoProvider(UnicodeException):
41 """There's no DocProvider specified, and it's needed."""
44 class XMLNamespace(object):
45 '''A handy structure to repsent names in an XML namespace.'''
47 def __init__(self, uri):
50 def __call__(self, tag):
51 return '{%s}%s' % (self.uri, tag)
53 def __contains__(self, tag):
54 return tag.startswith('{' + str(self) + '}')
57 return 'XMLNamespace(%r)' % self.uri
60 return '%s' % self.uri
62 class EmptyNamespace(XMLNamespace):
64 super(EmptyNamespace, self).__init__('')
66 def __call__(self, tag):
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/")
79 WLNS = EmptyNamespace()
83 """Represents a WL URI. Extracts slug from it."""
86 example = 'http://wolnelektury.pl/katalog/lektura/template/'
87 _re_wl_uri = re.compile(r'http://(www\.)?wolnelektury.pl/katalog/lektura/'
88 '(?P<slug>[-a-z0-9]+)/?$')
90 def __init__(self, uri):
93 self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
97 match = cls._re_wl_uri.match(uri)
99 raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
100 uri, cls._re_wl_uri.pattern))
104 def from_slug(cls, slug):
105 """Contructs an URI from slug.
107 >>> WLURI.from_slug('a-slug').uri
108 u'http://wolnelektury.pl/katalog/lektura/a-slug/'
111 uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
114 def __unicode__(self):
120 def __eq__(self, other):
121 return self.slug == other.slug
124 class DocProvider(object):
125 """Base class for a repository of XML files.
127 Used for generating joined files, like EPUBs.
130 def by_slug(self, slug):
131 """Should return a file-like object with a WL document XML."""
132 raise NotImplementedError
134 def by_uri(self, uri, wluri=WLURI):
135 """Should return a file-like object with a WL document XML."""
137 return self.by_slug(wluri.slug)
140 class DirDocProvider(DocProvider):
141 """ Serve docs from a directory of files in form <slug>.xml """
143 def __init__(self, dir_):
147 def by_slug(self, slug):
148 fname = slug + '.xml'
149 return open(os.path.join(self.dir, fname))
152 import lxml.etree as etree
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"],
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],
173 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
175 def xinclude_forURI(uri):
176 e = etree.Element(XINS("include"))
178 return etree.tostring(e, encoding=unicode)
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
184 dcstring = etree.tostring(bookinfo.to_etree(), \
185 method='xml', encoding=unicode, pretty_print=True)
187 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
188 u'\n</plain-text>\n</utwor>'
191 def serialize_raw(element):
192 b = u'' + (element.text or '')
194 for child in element.iterchildren():
195 e = etree.tostring(child, method='xml', encoding=unicode,
202 'raw': serialize_raw,
205 def serialize_children(element, format='raw'):
206 return SERIALIZERS[format](element)
208 def get_resource(path):
209 return os.path.join(os.path.dirname(__file__), path)
212 class OutputFile(object):
213 """Represents a file returned by one of the converters."""
220 os.unlink(self._filename)
222 def __nonzero__(self):
223 return self._string is not None or self._filename is not None
226 def from_string(cls, string):
227 """Converter returns contents of a file as a string."""
230 instance._string = string
234 def from_filename(cls, filename):
235 """Converter returns contents of a file as a named file."""
238 instance._filename = filename
241 def get_string(self):
242 """Get file's contents as a string."""
244 if self._filename is not None:
245 with open(self._filename) as f:
251 """Get file as a file-like object."""
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)
259 def get_filename(self):
260 """Get file as a fs path."""
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)
269 self._filename = temp.name
270 return self._filename
274 def save_as(self, path):
275 """Save file to a path. Create directories, if necessary."""
277 dirname = os.path.dirname(os.path.abspath(path))
279 shutil.copy(self.get_filename(), path)
282 class URLOpener(urllib.FancyURLopener):
283 version = 'FNP Librarian (http://github.com/fnp/librarian)'
284 urllib._urlopener = URLOpener()