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 print_function, unicode_literals
11 from tempfile import NamedTemporaryFile
13 from lxml import etree
15 from six.moves.urllib.request import FancyURLopener
16 from .util import makedirs
19 @six.python_2_unicode_compatible
20 class UnicodeException(Exception):
22 """ Dirty workaround for Python Unicode handling problems. """
23 args = self.args[0] if len(self.args) == 1 else self.args
25 message = six.text_type(args)
26 except UnicodeDecodeError:
27 message = six.text_type(args, encoding='utf-8', errors='ignore')
31 class ParseError(UnicodeException):
35 class ValidationError(UnicodeException):
39 class NoDublinCore(ValidationError):
40 """There's no DublinCore section, and it's required."""
44 class NoProvider(UnicodeException):
45 """There's no DocProvider specified, and it's needed."""
49 class XMLNamespace(object):
50 '''A handy structure to repsent names in an XML namespace.'''
52 def __init__(self, uri):
55 def __call__(self, tag):
56 return '{%s}%s' % (self.uri, tag)
58 def __contains__(self, tag):
59 return tag.startswith('{' + str(self) + '}')
62 return 'XMLNamespace(%r)' % self.uri
65 return '%s' % self.uri
68 class EmptyNamespace(XMLNamespace):
70 super(EmptyNamespace, self).__init__('')
72 def __call__(self, tag):
76 # some common namespaces we use
77 XMLNS = XMLNamespace('http://www.w3.org/XML/1998/namespace')
78 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
79 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
80 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
81 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
82 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
83 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
84 PLMETNS = XMLNamespace("http://dl.psnc.pl/schemas/plmet/")
86 WLNS = EmptyNamespace()
89 @six.python_2_unicode_compatible
91 """Represents a WL URI. Extracts slug from it."""
94 example = 'http://wolnelektury.pl/katalog/lektura/template/'
95 _re_wl_uri = re.compile(
96 r'http://(www\.)?wolnelektury.pl/katalog/lektur[ay]/'
97 '(?P<slug>[-a-z0-9]+)/?$'
100 def __init__(self, uri):
101 uri = six.text_type(uri)
103 self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
106 def strict(cls, uri):
107 match = cls._re_wl_uri.match(uri)
109 raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
110 uri, cls._re_wl_uri.pattern))
114 def from_slug(cls, slug):
115 """Contructs an URI from slug.
117 >>> print(WLURI.from_slug('a-slug').uri)
118 http://wolnelektury.pl/katalog/lektura/a-slug/
121 uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
127 def __eq__(self, other):
128 return self.slug == other.slug
131 class DocProvider(object):
132 """Base class for a repository of XML files.
134 Used for generating joined files, like EPUBs.
137 def by_slug(self, slug):
138 """Should return a file-like object with a WL document XML."""
139 raise NotImplementedError
141 def by_uri(self, uri, wluri=WLURI):
142 """Should return a file-like object with a WL document XML."""
144 return self.by_slug(wluri.slug)
147 class DirDocProvider(DocProvider):
148 """ Serve docs from a directory of files in form <slug>.xml """
150 def __init__(self, dir_):
154 def by_slug(self, slug):
155 fname = slug + '.xml'
156 return open(os.path.join(self.dir, fname), 'rb')
159 from . import dcparser
162 DEFAULT_BOOKINFO = dcparser.BookInfo(
164 RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'
167 DCNS('creator'): [u'Some, Author'],
168 DCNS('title'): [u'Some Title'],
169 DCNS('subject.period'): [u'Unknown'],
170 DCNS('subject.type'): [u'Unknown'],
171 DCNS('subject.genre'): [u'Unknown'],
172 DCNS('date'): ['1970-01-01'],
173 DCNS('language'): [u'pol'],
174 # DCNS('date'): [creation_date],
175 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
177 [u"""Publikacja zrealizowana w ramach projektu
178 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
179 wykonana przez Bibliotekę Narodową z egzemplarza
180 pochodzącego ze zbiorów BN."""],
181 DCNS('identifier.url'): [WLURI.example],
183 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"]
188 def xinclude_forURI(uri):
189 e = etree.Element(XINS("include"))
191 return etree.tostring(e, encoding='unicode')
194 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
195 """Wrap the text within the minimal XML structure with a DC template."""
196 bookinfo.created_at = creation_date
198 dcstring = etree.tostring(
199 bookinfo.to_etree(), method='xml', encoding='unicode',
203 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
204 u'\n</plain-text>\n</utwor>'
207 def serialize_raw(element):
208 b = u'' + (element.text or '')
210 for child in element.iterchildren():
211 e = etree.tostring(child, method='xml', encoding='unicode',
219 'raw': serialize_raw,
223 def serialize_children(element, format='raw'):
224 return SERIALIZERS[format](element)
227 def get_resource(path):
228 return os.path.join(os.path.dirname(__file__), path)
231 class OutputFile(object):
232 """Represents a file returned by one of the converters."""
239 os.unlink(self._filename)
241 def __nonzero__(self):
242 return self._bytes is not None or self._filename is not None
245 def from_bytes(cls, bytestring):
246 """Converter returns contents of a file as a string."""
249 instance._bytes = bytestring
253 def from_filename(cls, filename):
254 """Converter returns contents of a file as a named file."""
257 instance._filename = filename
261 """Get file's contents as a bytestring."""
263 if self._filename is not None:
264 with open(self._filename, 'rb') as f:
270 """Get file as a file-like object."""
272 if self._bytes is not None:
273 return six.BytesIO(self._bytes)
274 elif self._filename is not None:
275 return open(self._filename, 'rb')
277 def get_filename(self):
278 """Get file as a fs path."""
280 if self._filename is not None:
281 return self._filename
282 elif self._bytes is not None:
283 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
284 temp.write(self._bytes)
286 self._filename = temp.name
287 return self._filename
291 def save_as(self, path):
292 """Save file to a path. Create directories, if necessary."""
294 dirname = os.path.dirname(os.path.abspath(path))
296 shutil.copy(self.get_filename(), path)
299 class URLOpener(FancyURLopener):
300 version = 'FNP Librarian (http://github.com/fnp/librarian)'
303 urllib._urlopener = URLOpener()