import with for py2.5
[librarian.git] / librarian / __init__.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of Librarian, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from __future__ import with_statement
7
8 import os
9 import re
10 import shutil
11
12 class ParseError(Exception):
13     def __str__(self):
14         """ Dirty workaround for Python Unicode handling problems. """
15         return self.message
16
17     def __unicode__(self):
18         """ Dirty workaround for Python Unicode handling problems. """
19         return self.message
20
21 class ValidationError(Exception):
22     pass
23
24 class NoDublinCore(ValidationError):
25     """There's no DublinCore section, and it's required."""
26     pass
27
28 class NoProvider(Exception):
29     """There's no DocProvider specified, and it's needed."""
30     pass
31
32 class XMLNamespace(object):
33     '''A handy structure to repsent names in an XML namespace.'''
34
35     def __init__(self, uri):
36         self.uri = uri
37
38     def __call__(self, tag):
39         return '{%s}%s' % (self.uri, tag)
40
41     def __contains__(self, tag):
42         return tag.startswith('{' + str(self) + '}')
43
44     def __repr__(self):
45         return 'XMLNamespace(%r)' % self.uri
46
47     def __str__(self):
48         return '%s' % self.uri
49
50 class EmptyNamespace(XMLNamespace):
51     def __init__(self):
52         super(EmptyNamespace, self).__init__('')
53
54     def __call__(self, tag):
55         return tag
56
57 # some common namespaces we use
58 RDFNS = XMLNamespace('http://www.w3.org/1999/02/22-rdf-syntax-ns#')
59 DCNS = XMLNamespace('http://purl.org/dc/elements/1.1/')
60 XINS = XMLNamespace("http://www.w3.org/2001/XInclude")
61 XHTMLNS = XMLNamespace("http://www.w3.org/1999/xhtml")
62 NCXNS = XMLNamespace("http://www.daisy.org/z3986/2005/ncx/")
63 OPFNS = XMLNamespace("http://www.idpf.org/2007/opf")
64
65 WLNS = EmptyNamespace()
66
67
68 class WLURI(object):
69     """Represents a WL URI. Extracts slug and language from it."""
70
71     slug = None
72     language = None
73
74     _re_wl_uri = re.compile('http://wolnelektury.pl/katalog/lektura/'
75             '(?P<slug>[-a-z]+)(/(?P<lang>[a-z]{3})/?)?')
76
77     def __init__(self, uri):
78         self.uri = uri
79         match = self._re_wl_uri.match(uri)
80         assert match
81         self.slug = match.group('slug')
82         self.language = match.group('lang')
83
84
85 class DocProvider(object):
86     """Base class for a repository of XML files.
87
88     Used for generating joined files, like EPUBs.
89     """
90
91     def by_slug_and_lang(self, slug, lang=None):
92         """Should return a file-like object with a WL document XML."""
93         raise NotImplementedError
94
95     def by_slug(self, slug):
96         """Should return a file-like object with a WL document XML."""
97         return self.by_slug_and_lang(slug)
98
99     def by_uri(self, uri):
100         """Should return a file-like object with a WL document XML."""
101         wluri = WLURI(uri)
102         return self.by_slug_and_lang(wluri.slug, wluri.language)
103
104
105 class DirDocProvider(DocProvider):
106     """ Serve docs from a directory of files in form <slug>.xml """
107
108     def __init__(self, dir_):
109         self.dir = dir_
110         self.files = {}
111         return super(DirDocProvider, self).__init__()
112
113     def by_slug_and_lang(self, slug, lang=None):
114         fname = "%s%s.xml" % (slug, ".%s" % lang if lang else "")
115         return open(os.path.join(self.dir, fname))
116
117
118 import lxml.etree as etree
119 import dcparser
120
121 DEFAULT_BOOKINFO = dcparser.BookInfo(
122         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
123         { DCNS('creator'): [u'Some, Author'],
124           DCNS('title'): [u'Some Title'],
125           DCNS('subject.period'): [u'Unknown'],
126           DCNS('subject.type'): [u'Unknown'],
127           DCNS('subject.genre'): [u'Unknown'],
128           DCNS('date'): ['1970-01-01'],
129           DCNS('language'): [u'pol'],
130           # DCNS('date'): [creation_date],
131           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
132           DCNS('description'):
133           [u"""Publikacja zrealizowana w ramach projektu
134              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
135              wykonana przez Bibliotekę Narodową z egzemplarza
136              pochodzącego ze zbiorów BN."""],
137           DCNS('identifier.url'):
138             [u"http://wolnelektury.pl/katalog/lektura/template"],
139           DCNS('rights'):
140             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
141
142 def xinclude_forURI(uri):
143     e = etree.Element(XINS("include"))
144     e.set("href", uri)
145     return etree.tostring(e, encoding=unicode)
146
147 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
148     """Wrap the text within the minimal XML structure with a DC template."""
149     bookinfo.created_at = creation_date
150
151     dcstring = etree.tostring(bookinfo.to_etree(), \
152         method='xml', encoding=unicode, pretty_print=True)
153
154     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
155         u'\n</plain-text>\n</utwor>'
156
157
158 def serialize_raw(element):
159     b = u'' + (element.text or '')
160
161     for child in element.iterchildren():
162         e = etree.tostring(child, method='xml', encoding=unicode,
163                 pretty_print=True)
164         b += e
165
166     return b
167
168 SERIALIZERS = {
169     'raw': serialize_raw,
170 }
171
172 def serialize_children(element, format='raw'):
173     return SERIALIZERS[format](element)
174
175 def get_resource(path):
176     return os.path.join(os.path.dirname(__file__), path)
177
178
179 class OutputFile(object):
180     """Represents a file returned by one of the converters."""
181
182     _string = None
183     _filename = None
184
185     def __del__(self):
186         if self._filename:
187             os.unlink(self._filename)
188
189     def __nonzero__(self):
190         return self._string is not None or self._filename is not None
191
192     @classmethod
193     def from_string(cls, string):
194         """Converter returns contents of a file as a string."""
195
196         instance = cls()
197         instance._string = string
198         return instance
199
200     @classmethod
201     def from_filename(cls, filename):
202         """Converter returns contents of a file as a named file."""
203
204         instance = cls()
205         instance._filename = filename
206         return instance
207
208     def get_string(self):
209         """Get file's contents as a string."""
210
211         if self._filename is not None:
212             with open(self._filename) as f:
213                 return f.read()
214         else:
215             return self._string
216
217     def get_file(self):
218         """Get file as a file-like object."""
219
220         if self._string is not None:
221             from StringIO import StringIO
222             return StringIO(self._string)
223         elif self._filename is not None:
224             return open(self._filename)
225
226     def get_filename(self):
227         """Get file as a fs path."""
228
229         if self._filename is not None:
230             return self._filename
231         elif self._string is not None:
232             from tempfile import NamedTemporaryFile
233             temp = NamedTemporaryFile(prefix='librarian-', delete=False)
234             temp.write(self._string)
235             temp.close()
236             self._filename = temp.name
237             return self._filename
238         else:
239             return None
240
241     def save_as(self, path):
242         """Save file to a path. Create directories, if necessary."""
243
244         dirname = os.path.dirname(os.path.abspath(path))
245         if not os.path.isdir(dirname):
246             os.makedirs(dirname)
247         shutil.copy(self.get_filename(), path)