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. """
17 def __unicode__(self):
18 """ Dirty workaround for Python Unicode handling problems. """
21 class ParseError(UnicodeException):
24 class ValidationError(UnicodeException):
27 class NoDublinCore(ValidationError):
28 """There's no DublinCore section, and it's required."""
31 class NoProvider(UnicodeException):
32 """There's no DocProvider specified, and it's needed."""
35 class XMLNamespace(object):
36 '''A handy structure to repsent names in an XML namespace.'''
38 def __init__(self, uri):
41 def __call__(self, tag):
42 return '{%s}%s' % (self.uri, tag)
44 def __contains__(self, tag):
45 return tag.startswith('{' + str(self) + '}')
48 return 'XMLNamespace(%r)' % self.uri
51 return '%s' % self.uri
53 class EmptyNamespace(XMLNamespace):
55 super(EmptyNamespace, self).__init__('')
57 def __call__(self, tag):
60 # some common namespaces we use
61 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
62 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
63 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
64 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
65 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
66 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
68 WLNS = EmptyNamespace()
72 """Represents a WL URI. Extracts slug from it."""
75 example = 'http://wolnelektury.pl/katalog/lektura/template/'
76 _re_wl_uri = re.compile(r'http://(www\.)?wolnelektury.pl/katalog/lektura/'
77 '(?P<slug>[-a-z0-9]+)/?$')
79 def __init__(self, uri):
82 self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
86 match = cls._re_wl_uri.match(uri)
88 raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
89 uri, cls._re_wl_uri.pattern))
93 def from_slug(cls, slug):
94 """Contructs an URI from slug.
96 >>> WLURI.from_slug('a-slug').uri
97 u'http://wolnelektury.pl/katalog/lektura/a-slug/'
100 uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
103 def __unicode__(self):
109 def __eq__(self, other):
110 return self.slug == other.slug
113 class DocProvider(object):
114 """Base class for a repository of XML files.
116 Used for generating joined files, like EPUBs.
119 def by_slug(self, slug):
120 """Should return a file-like object with a WL document XML."""
121 raise NotImplementedError
123 def by_uri(self, uri, wluri=WLURI):
124 """Should return a file-like object with a WL document XML."""
126 return self.by_slug(wluri.slug)
129 class DirDocProvider(DocProvider):
130 """ Serve docs from a directory of files in form <slug>.xml """
132 def __init__(self, dir_):
136 def by_slug(self, slug):
137 fname = slug + '.xml'
138 return open(os.path.join(self.dir, fname))
141 import lxml.etree as etree
144 DEFAULT_BOOKINFO = dcparser.BookInfo(
145 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
146 { DCNS('creator'): [u'Some, Author'],
147 DCNS('title'): [u'Some Title'],
148 DCNS('subject.period'): [u'Unknown'],
149 DCNS('subject.type'): [u'Unknown'],
150 DCNS('subject.genre'): [u'Unknown'],
151 DCNS('date'): ['1970-01-01'],
152 DCNS('language'): [u'pol'],
153 # DCNS('date'): [creation_date],
154 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
156 [u"""Publikacja zrealizowana w ramach projektu
157 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
158 wykonana przez Bibliotekę Narodową z egzemplarza
159 pochodzącego ze zbiorów BN."""],
160 DCNS('identifier.url'): [WLURI.example],
162 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
164 def xinclude_forURI(uri):
165 e = etree.Element(XINS("include"))
167 return etree.tostring(e, encoding=unicode)
169 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
170 """Wrap the text within the minimal XML structure with a DC template."""
171 bookinfo.created_at = creation_date
173 dcstring = etree.tostring(bookinfo.to_etree(), \
174 method='xml', encoding=unicode, pretty_print=True)
176 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
177 u'\n</plain-text>\n</utwor>'
180 def serialize_raw(element):
181 b = u'' + (element.text or '')
183 for child in element.iterchildren():
184 e = etree.tostring(child, method='xml', encoding=unicode,
191 'raw': serialize_raw,
194 def serialize_children(element, format='raw'):
195 return SERIALIZERS[format](element)
197 def get_resource(path):
198 return os.path.join(os.path.dirname(__file__), path)
201 class OutputFile(object):
202 """Represents a file returned by one of the converters."""
209 os.unlink(self._filename)
211 def __nonzero__(self):
212 return self._string is not None or self._filename is not None
215 def from_string(cls, string):
216 """Converter returns contents of a file as a string."""
219 instance._string = string
223 def from_filename(cls, filename):
224 """Converter returns contents of a file as a named file."""
227 instance._filename = filename
230 def get_string(self):
231 """Get file's contents as a string."""
233 if self._filename is not None:
234 with open(self._filename) as f:
240 """Get file as a file-like object."""
242 if self._string is not None:
243 from StringIO import StringIO
244 return StringIO(self._string)
245 elif self._filename is not None:
246 return open(self._filename)
248 def get_filename(self):
249 """Get file as a fs path."""
251 if self._filename is not None:
252 return self._filename
253 elif self._string is not None:
254 from tempfile import NamedTemporaryFile
255 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
256 temp.write(self._string)
258 self._filename = temp.name
259 return self._filename
263 def save_as(self, path):
264 """Save file to a path. Create directories, if necessary."""
266 dirname = os.path.dirname(os.path.abspath(path))
267 if not os.path.isdir(dirname):
269 shutil.copy(self.get_filename(), path)