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
14 class UnicodeException(Exception):
16 """ Dirty workaround for Python Unicode handling problems. """
17 return unicode(self).encode('utf-8')
19 def __unicode__(self):
20 """ Dirty workaround for Python Unicode handling problems. """
21 args = self.args[0] if len(self.args) == 1 else self.args
23 message = unicode(args)
24 except UnicodeDecodeError:
25 message = unicode(args, encoding='utf-8', errors='ignore')
28 class ParseError(UnicodeException):
31 class ValidationError(UnicodeException):
34 class NoDublinCore(ValidationError):
35 """There's no DublinCore section, and it's required."""
38 class NoProvider(UnicodeException):
39 """There's no DocProvider specified, and it's needed."""
42 class XMLNamespace(object):
43 '''A handy structure to repsent names in an XML namespace.'''
45 def __init__(self, uri):
48 def __call__(self, tag):
49 return '{%s}%s' % (self.uri, tag)
51 def __contains__(self, tag):
52 return tag.startswith('{' + str(self) + '}')
55 return 'XMLNamespace(%r)' % self.uri
58 return '%s' % self.uri
60 class EmptyNamespace(XMLNamespace):
62 super(EmptyNamespace, self).__init__('')
64 def __call__(self, tag):
67 # some common namespaces we use
68 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
69 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
70 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
71 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
72 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
73 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
75 WLNS = EmptyNamespace()
79 """Represents a WL URI. Extracts slug from it."""
82 example = 'http://edukacjamedialna.pl/'
83 _re_wl_uri = re.compile(r'http://(www\.)?edukacjamedialna.pl/'
84 '(?P<slug>[-a-z0-9]+)/?$')
86 def __init__(self, uri):
89 self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
93 match = cls._re_wl_uri.match(uri)
95 raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
96 uri, cls._re_wl_uri.pattern))
100 def from_slug(cls, slug):
101 """Contructs an URI from slug.
103 >>> WLURI.from_slug('a-slug').uri
104 u'http://wolnelektury.pl/katalog/lektura/a-slug/'
107 uri = 'http://prawokultury.pl/publikacje/%s/' % slug
110 def __unicode__(self):
116 def __eq__(self, other):
117 return self.slug == other.slug
120 class DocProvider(object):
121 """Base class for a repository of XML files.
123 Used for generating joined files, like EPUBs.
126 def by_slug(self, slug):
127 """Should return a file-like object with a WL document XML."""
128 raise NotImplementedError
130 def by_uri(self, uri, wluri=WLURI):
131 """Should return a file-like object with a WL document XML."""
133 return self.by_slug(wluri.slug)
136 class DirDocProvider(DocProvider):
137 """ Serve docs from a directory of files in form <slug>.xml """
139 def __init__(self, dir_):
143 def by_slug(self, slug):
144 fname = slug + '.xml'
145 return open(os.path.join(self.dir, fname))
148 import lxml.etree as etree
151 DEFAULT_BOOKINFO = dcparser.BookInfo(
152 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
154 DCNS('creator.export'): [u'Some, Author'],
155 DCNS('creator.scenario'): [u'Some, Author'],
156 DCNS('creator.textbook'): [u'Some, Author'],
157 DCNS('title'): [u'Some Title'],
158 DCNS('subject.period'): [u'Unknown'],
159 DCNS('subject.type'): [u'Unknown'],
160 DCNS('subject.genre'): [u'Unknown'],
161 DCNS('date'): ['1970-01-01'],
162 DCNS('language'): [u'pol'],
163 # DCNS('date'): [creation_date],
164 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
166 [u"""Publikacja zrealizowana w ramach projektu
167 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
168 wykonana przez Bibliotekę Narodową z egzemplarza
169 pochodzącego ze zbiorów BN."""],
170 DCNS('identifier.url'): [WLURI.example],
172 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
174 def xinclude_forURI(uri):
175 e = etree.Element(XINS("include"))
177 return etree.tostring(e, encoding=unicode)
179 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
180 """Wrap the text within the minimal XML structure with a DC template."""
181 bookinfo.created_at = creation_date
183 dcstring = etree.tostring(bookinfo.to_etree(), \
184 method='xml', encoding=unicode, pretty_print=True)
186 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
187 u'\n</plain-text>\n</utwor>'
190 def serialize_raw(element):
191 b = u'' + (element.text or '')
193 for child in element.iterchildren():
194 e = etree.tostring(child, method='xml', encoding=unicode,
201 'raw': serialize_raw,
204 def serialize_children(element, format='raw'):
205 return SERIALIZERS[format](element)
207 def get_resource(path):
208 return os.path.join(os.path.dirname(__file__), path)
211 class OutputFile(object):
212 """Represents a file returned by one of the converters."""
219 os.unlink(self._filename)
221 def __nonzero__(self):
222 return self._string is not None or self._filename is not None
225 def from_string(cls, string):
226 """Converter returns contents of a file as a string."""
229 instance._string = string
233 def from_filename(cls, filename):
234 """Converter returns contents of a file as a named file."""
237 instance._filename = filename
240 def get_string(self):
241 """Get file's contents as a string."""
243 if self._filename is not None:
244 with open(self._filename) as f:
250 """Get file as a file-like object."""
252 if self._string is not None:
253 from StringIO import StringIO
254 return StringIO(self._string)
255 elif self._filename is not None:
256 return open(self._filename)
258 def get_filename(self):
259 """Get file as a fs path."""
261 if self._filename is not None:
262 return self._filename
263 elif self._string is not None:
264 from tempfile import NamedTemporaryFile
265 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
266 temp.write(self._string)
268 self._filename = temp.name
269 return self._filename
273 def save_as(self, path):
274 """Save file to a path. Create directories, if necessary."""
276 dirname = os.path.dirname(os.path.abspath(path))
277 if not os.path.isdir(dirname):
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()