Separate the general from the WL-specific: PDF
[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 import urllib
12
13
14 class UnicodeException(Exception):
15     def __str__(self):
16         """ Dirty workaround for Python Unicode handling problems. """
17         return unicode(self).encode('utf-8')
18
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
22         try:
23             message = unicode(args)
24         except UnicodeDecodeError:
25             message = unicode(args, encoding='utf-8', errors='ignore')
26         return message
27
28 class ParseError(UnicodeException):
29     pass
30
31 class ValidationError(UnicodeException):
32     pass
33
34 class NoDublinCore(ValidationError):
35     """There's no DublinCore section, and it's required."""
36     pass
37
38 class NoProvider(UnicodeException):
39     """There's no DocProvider specified, and it's needed."""
40     pass
41
42 class XMLNamespace(object):
43     '''A handy structure to repsent names in an XML namespace.'''
44
45     def __init__(self, uri):
46         self.uri = uri
47
48     def __call__(self, tag):
49         return '{%s}%s' % (self.uri, tag)
50
51     def __contains__(self, tag):
52         return tag.startswith('{' + str(self) + '}')
53
54     def __repr__(self):
55         return 'XMLNamespace(%r)' % self.uri
56
57     def __str__(self):
58         return '%s' % self.uri
59
60 class EmptyNamespace(XMLNamespace):
61     def __init__(self):
62         super(EmptyNamespace, self).__init__('')
63
64     def __call__(self, tag):
65         return tag
66
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")
74
75 WLNS = EmptyNamespace()
76
77
78 class WLURI(object):
79     """Represents a WL URI. Extracts slug from it."""
80     slug = None
81
82     example = 'http://wolnelektury.pl/katalog/lektura/template/'
83     _re_wl_uri = re.compile(r'http://(www\.)?wolnelektury.pl/katalog/lektura/'
84             '(?P<slug>[-a-z0-9]+)/?$')
85
86     def __init__(self, uri):
87         uri = unicode(uri)
88         self.uri = uri
89         self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
90
91     @classmethod
92     def strict(cls, uri):
93         match = cls._re_wl_uri.match(uri)
94         if not match:
95             raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
96                         uri, cls._re_wl_uri.pattern))
97         return cls(uri)
98
99     @classmethod
100     def from_slug(cls, slug):
101         """Contructs an URI from slug.
102
103         >>> WLURI.from_slug('a-slug').uri
104         u'http://wolnelektury.pl/katalog/lektura/a-slug/'
105
106         """
107         uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
108         return cls(uri)
109
110     def __unicode__(self):
111         return self.uri
112
113     def __str__(self):
114         return self.uri
115
116     def __eq__(self, other):
117         return self.slug == other.slug
118
119
120 class DocProvider(object):
121     """Base class for a repository of XML files.
122
123     Used for generating joined files, like EPUBs.
124     """
125
126     def by_slug(self, slug):
127         """Should return a file-like object with a WL document XML."""
128         raise NotImplementedError
129
130     def by_uri(self, uri, wluri=WLURI):
131         """Should return a file-like object with a WL document XML."""
132         wluri = wluri(uri)
133         return self.by_slug(wluri.slug)
134
135
136 class DirDocProvider(DocProvider):
137     """ Serve docs from a directory of files in form <slug>.xml """
138
139     def __init__(self, dir_):
140         self.dir = dir_
141         self.files = {}
142
143     def by_slug(self, slug):
144         fname = slug + '.xml'
145         return open(os.path.join(self.dir, fname))
146
147
148 import lxml.etree as etree
149 import dcparser
150
151 DEFAULT_BOOKINFO = dcparser.BookInfo(
152         { RDFNS('about'): u'http://wiki.wolnepodreczniki.pl/Lektury:Template'},
153         { DCNS('creator'): [u'Some, Author'],
154           DCNS('title'): [u'Some Title'],
155           DCNS('subject.period'): [u'Unknown'],
156           DCNS('subject.type'): [u'Unknown'],
157           DCNS('subject.genre'): [u'Unknown'],
158           DCNS('date'): ['1970-01-01'],
159           DCNS('language'): [u'pol'],
160           # DCNS('date'): [creation_date],
161           DCNS('publisher'): [u"Fundacja Nowoczesna Polska"],
162           DCNS('description'):
163           [u"""Publikacja zrealizowana w ramach projektu
164              Wolne Lektury (http://wolnelektury.pl). Reprodukcja cyfrowa
165              wykonana przez Bibliotekę Narodową z egzemplarza
166              pochodzącego ze zbiorów BN."""],
167           DCNS('identifier.url'): [WLURI.example],
168           DCNS('rights'):
169             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
170
171 def xinclude_forURI(uri):
172     e = etree.Element(XINS("include"))
173     e.set("href", uri)
174     return etree.tostring(e, encoding=unicode)
175
176 def wrap_text(ocrtext, creation_date, bookinfo=DEFAULT_BOOKINFO):
177     """Wrap the text within the minimal XML structure with a DC template."""
178     bookinfo.created_at = creation_date
179
180     dcstring = etree.tostring(bookinfo.to_etree(), \
181         method='xml', encoding=unicode, pretty_print=True)
182
183     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
184         u'\n</plain-text>\n</utwor>'
185
186
187 def serialize_raw(element):
188     b = u'' + (element.text or '')
189
190     for child in element.iterchildren():
191         e = etree.tostring(child, method='xml', encoding=unicode,
192                 pretty_print=True)
193         b += e
194
195     return b
196
197 SERIALIZERS = {
198     'raw': serialize_raw,
199 }
200
201 def serialize_children(element, format='raw'):
202     return SERIALIZERS[format](element)
203
204 def get_resource(path):
205     return os.path.join(os.path.dirname(__file__), path)
206
207
208 class IOFile(object):
209     """ Represents a file fed as input or returned as a result. """
210     _string = None
211     _filename = None
212     _filename_tmp = False
213
214     def __init__(self, attachments=None):
215         self.attachments = attachments or {}
216
217     def __del__(self):
218         if self._filename_tmp:
219             os.unlink(self._filename)
220
221     def __nonzero__(self):
222         return self._string is not None or self._filename is not None
223
224     @classmethod
225     def from_string(cls, string, *args, **kwargs):
226         """Converter returns contents of a file as a string."""
227
228         instance = cls(*args, **kwargs)
229         instance._string = string
230         return instance
231
232     @classmethod
233     def from_filename(cls, filename, *args, **kwargs):
234         """Converter returns contents of a file as a named file."""
235
236         instance = cls(*args, **kwargs)
237         instance._filename = filename
238         return instance
239
240     def get_string(self):
241         """Get file's contents as a string."""
242
243         if self._filename is not None:
244             with open(self._filename) as f:
245                 return f.read()
246         else:
247             return self._string
248
249     def get_file(self):
250         """Get file as a file-like object."""
251
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)
257
258     def get_filename(self):
259         """Get file as a fs path."""
260
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)
267             temp.close()
268             self._filename = temp.name
269             self._filename_tmp = True
270             return self._filename
271         else:
272             return None
273
274     def save_as(self, path):
275         """Save file to a path. Create directories, if necessary."""
276
277         dirname = os.path.dirname(os.path.abspath(path))
278         if not os.path.isdir(dirname):
279             os.makedirs(dirname)
280         shutil.copy(self.get_filename(), path)
281
282     def dump_to(self, path, directory=None):
283         """ Path should be name for main file. """
284         self.save_as(path)
285         dirname = os.path.dirname(os.path.abspath(path))
286         for filename, attachment in self.attachments.items():
287             attachment.save_as(os.path.join(dirname, filename))
288
289
290 class Format(object):
291     """ Generic format class. """
292     def __init__(self, wldoc, **kwargs):
293         self.wldoc = wldoc
294         self.customization = kwargs
295
296     def build(self):
297         raise NotImplementedError
298
299
300 class URLOpener(urllib.FancyURLopener):
301     version = 'FNP Librarian (http://github.com/fnp/librarian)'
302 urllib._urlopener = URLOpener()