#1868: check uri pattern in strict mode
[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 UnicodeException(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 ParseError(UnicodeException):
22     pass
23
24 class ValidationError(UnicodeException):
25     pass
26
27 class NoDublinCore(ValidationError):
28     """There's no DublinCore section, and it's required."""
29     pass
30
31 class NoProvider(UnicodeException):
32     """There's no DocProvider specified, and it's needed."""
33     pass
34
35 class XMLNamespace(object):
36     '''A handy structure to repsent names in an XML namespace.'''
37
38     def __init__(self, uri):
39         self.uri = uri
40
41     def __call__(self, tag):
42         return '{%s}%s' % (self.uri, tag)
43
44     def __contains__(self, tag):
45         return tag.startswith('{' + str(self) + '}')
46
47     def __repr__(self):
48         return 'XMLNamespace(%r)' % self.uri
49
50     def __str__(self):
51         return '%s' % self.uri
52
53 class EmptyNamespace(XMLNamespace):
54     def __init__(self):
55         super(EmptyNamespace, self).__init__('')
56
57     def __call__(self, tag):
58         return tag
59
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")
67
68 WLNS = EmptyNamespace()
69
70
71 class WLURI(object):
72     """Represents a WL URI. Extracts slug from it."""
73     slug = None
74
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]+)/?$')
78
79     def __init__(self, uri):
80         uri = unicode(uri)
81         self.uri = uri
82         self.slug = uri.rstrip('/').rsplit('/', 1)[-1]
83
84     @classmethod
85     def strict(cls, uri):
86         match = cls._re_wl_uri.match(uri)
87         if not match:
88             raise ValidationError(u'Invalid URI (%s). Should match: %s' % (
89                         uri, cls._re_wl_uri.pattern))
90         return cls(uri)
91
92     @classmethod
93     def from_slug(cls, slug):
94         """Contructs an URI from slug.
95
96         >>> WLURI.from_slug('a-slug').uri
97         u'http://wolnelektury.pl/katalog/lektura/a-slug/'
98
99         """
100         uri = 'http://wolnelektury.pl/katalog/lektura/%s/' % slug
101         return cls(uri)
102
103     def __unicode__(self):
104         return self.uri
105
106     def __str__(self):
107         return self.uri
108
109     def __eq__(self, other):
110         return self.slug == other.slug
111
112
113 class DocProvider(object):
114     """Base class for a repository of XML files.
115
116     Used for generating joined files, like EPUBs.
117     """
118
119     def by_slug(self, slug):
120         """Should return a file-like object with a WL document XML."""
121         raise NotImplementedError
122
123     def by_uri(self, uri, wluri=WLURI):
124         """Should return a file-like object with a WL document XML."""
125         wluri = wluri(uri)
126         return self.by_slug(wluri.slug)
127
128
129 class DirDocProvider(DocProvider):
130     """ Serve docs from a directory of files in form <slug>.xml """
131
132     def __init__(self, dir_):
133         self.dir = dir_
134         self.files = {}
135
136     def by_slug(self, slug):
137         fname = slug + '.xml'
138         return open(os.path.join(self.dir, fname))
139
140
141 import lxml.etree as etree
142 import dcparser
143
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"],
155           DCNS('description'):
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],
161           DCNS('rights'):
162             [u"Domena publiczna - zm. [OPIS STANU PRAWNEGO TEKSTU]"] })
163
164 def xinclude_forURI(uri):
165     e = etree.Element(XINS("include"))
166     e.set("href", uri)
167     return etree.tostring(e, encoding=unicode)
168
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
172
173     dcstring = etree.tostring(bookinfo.to_etree(), \
174         method='xml', encoding=unicode, pretty_print=True)
175
176     return u'<utwor>\n' + dcstring + u'\n<plain-text>\n' + ocrtext + \
177         u'\n</plain-text>\n</utwor>'
178
179
180 def serialize_raw(element):
181     b = u'' + (element.text or '')
182
183     for child in element.iterchildren():
184         e = etree.tostring(child, method='xml', encoding=unicode,
185                 pretty_print=True)
186         b += e
187
188     return b
189
190 SERIALIZERS = {
191     'raw': serialize_raw,
192 }
193
194 def serialize_children(element, format='raw'):
195     return SERIALIZERS[format](element)
196
197 def get_resource(path):
198     return os.path.join(os.path.dirname(__file__), path)
199
200
201 class OutputFile(object):
202     """Represents a file returned by one of the converters."""
203
204     _string = None
205     _filename = None
206
207     def __del__(self):
208         if self._filename:
209             os.unlink(self._filename)
210
211     def __nonzero__(self):
212         return self._string is not None or self._filename is not None
213
214     @classmethod
215     def from_string(cls, string):
216         """Converter returns contents of a file as a string."""
217
218         instance = cls()
219         instance._string = string
220         return instance
221
222     @classmethod
223     def from_filename(cls, filename):
224         """Converter returns contents of a file as a named file."""
225
226         instance = cls()
227         instance._filename = filename
228         return instance
229
230     def get_string(self):
231         """Get file's contents as a string."""
232
233         if self._filename is not None:
234             with open(self._filename) as f:
235                 return f.read()
236         else:
237             return self._string
238
239     def get_file(self):
240         """Get file as a file-like object."""
241
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)
247
248     def get_filename(self):
249         """Get file as a fs path."""
250
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)
257             temp.close()
258             self._filename = temp.name
259             return self._filename
260         else:
261             return None
262
263     def save_as(self, path):
264         """Save file to a path. Create directories, if necessary."""
265
266         dirname = os.path.dirname(os.path.abspath(path))
267         if not os.path.isdir(dirname):
268             os.makedirs(dirname)
269         shutil.copy(self.get_filename(), path)