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.edu.pl/lekcje/template'
83 _re_wl_uri = re.compile(r'http://(www\.)?edukacjamedialna.edu.pl/lekcje/'
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://edukacjamedialna.edu.pl/lekcje/a-slug/'
107 uri = 'http://edukacjamedialna.edu.pl/lekcje/%s/' % slug
110 def __unicode__(self):
117 return type(self).from_slug(self.slug)
119 def __eq__(self, other):
120 return self.slug == other.slug
123 class DocProvider(object):
124 """Base class for a repository of XML files.
126 Used for generating joined files, like EPUBs.
129 def by_slug(self, slug):
130 """Should return an IOFile object with a WL document XML."""
131 raise NotImplementedError
133 def by_uri(self, uri, wluri=WLURI):
134 """Should return an IOFile object with a WL document XML."""
136 return self.by_slug(wluri.slug)
139 class DirDocProvider(DocProvider):
140 """ Serve docs from a directory of files in form <slug>.xml """
142 def __init__(self, dir_):
146 def by_slug(self, slug):
147 fname = slug + '.xml'
148 return IOFile.from_filename(os.path.join(self.dir, fname))
151 import lxml.etree as etree
154 DEFAULT_BOOKINFO = dcparser.BookInfo(
155 { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
157 DCNS('creator.expert'): [u'Some, Author'],
158 DCNS('creator.scenario'): [u'Some, Author'],
159 DCNS('creator.textbook'): [u'Some, Author'],
160 DCNS('title'): [u'Some Title'],
161 DCNS('subject.period'): [u'Unknown'],
162 DCNS('subject.type'): [u'Unknown'],
163 DCNS('subject.genre'): [u'Unknown'],
164 DCNS('date'): ['1970-01-01'],
165 DCNS('language'): [u'pol'],
166 # DCNS('date'): [creation_date],
167 DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
169 [u"""Publikacja zrealizowana w ramach projektu
170 Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
171 wykonana przez Bibliotekę Narodową z egzemplarza
172 pochodzącego ze zbiorów BN."""],
173 DCNS('identifier.url'): [WLURI.example],
175 [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
177 def xinclude_forURI(uri):
178 e = etree.Element(XINS("include"))
180 return etree.tostring(e, encoding=unicode)
182 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
183 """Wrap the text within the minimal XML structure with a DC template."""
184 bookinfo.created_at = creation_date
186 dcstring = etree.tostring(bookinfo.to_etree(), \
187 method='xml', encoding=unicode, pretty_print=True)
189 return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
190 u'\n</plain-text>\n</utwor>'
193 def serialize_raw(element):
194 b = u'' + (element.text or '')
196 for child in element.iterchildren():
197 e = etree.tostring(child, method='xml', encoding=unicode,
204 'raw': serialize_raw,
207 def serialize_children(element, format='raw'):
208 return SERIALIZERS[format](element)
210 def get_resource(path):
211 return os.path.join(os.path.dirname(__file__), path)
214 class IOFile(object):
215 """ Represents a file fed as input or returned as a result. """
218 _filename_tmp = False
220 def __init__(self, attachments=None):
221 self.attachments = attachments or {}
224 if self._filename_tmp:
225 os.unlink(self._filename)
227 def __nonzero__(self):
228 return self._string is not None or self._filename is not None
231 def from_string(cls, string, *args, **kwargs):
232 """Converter returns contents of a file as a string."""
234 instance = cls(*args, **kwargs)
235 instance._string = string
239 def from_filename(cls, filename, *args, **kwargs):
240 """Converter returns contents of a file as a named file."""
242 instance = cls(*args, **kwargs)
243 instance._filename = filename
246 def get_string(self):
247 """Get file's contents as a string."""
249 if self._filename is not None:
250 with open(self._filename) as f:
256 """Get file as a file-like object."""
258 if self._string is not None:
259 from StringIO import StringIO
260 return StringIO(self._string)
261 elif self._filename is not None:
262 return open(self._filename)
264 def get_filename(self):
265 """Get file as a fs path."""
267 if self._filename is not None:
268 return self._filename
269 elif self._string is not None:
270 from tempfile import NamedTemporaryFile
271 temp = NamedTemporaryFile(prefix='librarian-', delete=False)
272 temp.write(self._string)
274 self._filename = temp.name
275 self._filename_tmp = True
276 return self._filename
280 def save_as(self, path):
281 """Save file to a path. Create directories, if necessary."""
283 dirname = os.path.dirname(os.path.abspath(path))
284 if not os.path.isdir(dirname):
286 shutil.copy(self.get_filename(), path)
288 def dump_to(self, path, directory=None):
289 """ Path should be name for main file. """
291 dirname = os.path.dirname(os.path.abspath(path))
292 for filename, attachment in self.attachments.items():
293 attachment.save_as(os.path.join(dirname, filename))
296 class Format(object):
297 """ Generic format class. """
298 def __init__(self, wldoc, **kwargs):
300 self.customization = kwargs
303 raise NotImplementedError
306 class URLOpener(urllib.FancyURLopener):
307 version = 'FNP Librarian (http://github.com/fnp/librarian)'
308 urllib._urlopener = URLOpener()