if DC is under <powiesc> and not <utwor>, still get it.
[wolnelektury.git] / apps / oai / handlers.py
1 from oaipmh import server, common, metadata, error
2 from catalogue.models import Book, Tag
3 from api.models import Deleted
4 from api.handlers import WL_BASE
5 from librarian.dcparser import BookInfo
6 from django.contrib.contenttypes.models import ContentType
7 from django.contrib.auth.models import User
8 from datetime import datetime
9 from lxml import etree
10 from lxml.etree import ElementTree
11 from django.db.models import Q
12 from django.conf import settings
13 from django.contrib.sites.models import Site
14
15
16 WL_DC_READER_XPATH = '(.|*)/rdf:RDF/rdf:Description/%s/text()' 
17 wl_dc_reader = metadata.MetadataReader(
18     fields={
19     'title':       ('textList', WL_DC_READER_XPATH % 'dc:title'),
20     'creator':     ('textList', WL_DC_READER_XPATH % 'dc:creator'),
21     'subject':     ('textList', (WL_DC_READER_XPATH + ' | ' + WL_DC_READER_XPATH + ' | ' + WL_DC_READER_XPATH) %
22                     ('dc:subject.period', 'dc:subject.type', 'dc:subject.genre')),
23     'description': ('textList', WL_DC_READER_XPATH % 'dc:description'),
24     'publisher':   ('textList', WL_DC_READER_XPATH % 'dc:publisher'),
25     'contributor': ('textList', (WL_DC_READER_XPATH + ' | ' + WL_DC_READER_XPATH + ' | ' + WL_DC_READER_XPATH) %
26                     ('dc:contributor.editor', 'dc:contributor.translator', 'dc:contributor.technical_editor')),
27     'date':        ('textList', WL_DC_READER_XPATH % 'dc:date'),
28     'type':        ('textList', WL_DC_READER_XPATH % 'dc:type'),
29     'format':      ('textList', WL_DC_READER_XPATH % 'dc:format'),
30     'identifier':  ('textList', WL_DC_READER_XPATH % 'dc:identifier.url'),
31     'source':      ('textList', WL_DC_READER_XPATH % 'dc:source'),
32     'language':    ('textList', WL_DC_READER_XPATH % 'dc:language'),
33     #'isPartOf':     ('textList', 'rdf:RDF/rdf:Description/dc:relation.isPartOf/text()'),
34     'hasPart':     ('textList', WL_DC_READER_XPATH % 'dc:relation.hasPart'),
35     #    'relation':    ('textList', 'rdf:RDF/rdf:Description/dc:relation/text()'),
36     #    'coverage':    ('textList', 'rdf:RDF/rdf:Description/dc:coverage/text()'),
37     'rights':      ('textList', WL_DC_READER_XPATH % 'dc:rights')
38     },
39     namespaces={
40     'dc': 'http://purl.org/dc/elements/1.1/',
41     'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'}
42     )
43
44
45 NS_DCTERMS = "http://purl.org/dc/terms/"
46
47
48 def nsdcterms(name):
49     return '{%s}%s' % (NS_DCTERMS, name)
50
51
52 class Catalogue(common.ResumptionOAIPMH):
53     TAG_CATEGORIES = ['author', 'epoch', 'kind', 'genre']
54
55     def __init__(self, metadata_registry):
56         super(Catalogue, self).__init__()
57         self.metadata_registry = metadata_registry
58
59         self.oai_id = "oai:" + Site.objects.get_current().domain + ":%s"
60
61         # earliest change
62         year_zero = datetime(1990, 1, 1, 0, 0, 0)
63
64         try:
65             earliest_change = \
66                 Book.objects.order_by('changed_at')[0].changed_at
67         except: earliest_change = year_zero
68
69         try:
70             earliest_delete = \
71                 Deleted.objects.exclude(slug__exact=u'').ordery_by('deleted_at')[0].deleted_at
72         except: earliest_delete = year_zero
73
74         self.earliest_datestamp = earliest_change <= earliest_delete and \
75             earliest_change or earliest_delete
76
77     def metadata(self, book):
78         try:
79             xml = etree.parse(book.xml_file)
80         finally:
81             book.xml_file.close()
82         md = wl_dc_reader(xml)
83         return md.getMap()
84
85     def record_for_book(self, book, headers_only=False):
86         meta = None
87         identifier = self.slug_to_identifier(book.slug)
88         if isinstance(book, Book):
89             #            setSpec = map(self.tag_to_setspec, book.tags.filter(category__in=self.TAG_CATEGORIES))
90             header = common.Header(identifier, book.changed_at, [], False)
91             if not headers_only:
92                 meta = common.Metadata(self.metadata(book))
93             about = None
94         elif isinstance(book, Deleted):
95             header = common.Header(identifier, book.deleted_at, [], True)
96             if not headers_only:
97                 meta = common.Metadata({})
98             about = None
99         if headers_only:
100             return header
101         return header, meta, about
102
103     def identify(self, **kw):
104         ident = common.Identify(
105             'Wolne Lektury',  # generate
106             '%s/oaipmh' % WL_BASE,  # generate
107             '2.0',  # version
108             [m[1] for m in settings.MANAGERS],  # adminEmails
109             self.earliest_datestamp,  # earliest datestamp of any change
110             'persistent',  # deletedRecord
111             'YYYY-MM-DDThh:mm:ssZ',  # granularity
112             ['identity'],  # compression
113             []  # descriptions
114             )
115         return ident
116
117     def books(self, tag, from_, until):
118         if tag:
119             # we do not support sets, since they are problematic for deleted books.
120             raise error.NoSetHierarchyError("Wolne Lektury does not support sets.")
121             # books = Book.tagged.with_all([tag])
122         else:
123             books = Book.objects.all()
124         deleted = Deleted.objects.exclude(slug__exact=u'')
125
126         books = books.order_by('changed_at')
127         deleted = deleted.order_by('deleted_at')
128         if from_:
129             books = books.filter(changed_at__gte=from_)
130             deleted = deleted.filter(deleted_at__gte=from_)
131         if until:
132             books = books.filter(changed_at__lte=until)
133             deleted = deleted.filter(deleted_at__lte=until)
134         return list(books) + list(deleted)
135
136     @staticmethod
137     def tag_to_setspec(tag):
138         return "%s:%s" % (tag.category, tag.slug)
139
140     @staticmethod
141     def setspec_to_tag(s):
142         if not s: return None
143         cs = s.split(':')
144         if len(cs) == 2:
145             if not cs[0] in Catalogue.TAG_CATEGORIES:
146                 raise error.NoSetHierarchyError("No category part in set")
147             tag = Tag.objects.get(slug=cs[1], category=cs[0])
148             return tag
149         raise error.NoSetHierarchyError("Setspec should have two components: category:slug")
150
151     def getRecord(self, **kw):
152         """
153 Returns (header, metadata, about) for given record.
154         """
155         slug = self.identifier_to_slug(kw['identifier'])
156         try:
157             book = Book.objects.get(slug=slug)
158             return self.record_for_book(book)
159         except Book.DoesNotExist:
160             book_type = ContentType.objects.get_for_model(Book)
161             try:
162                 deleted_book = Deleted.objects.get(content_type=book_type,
163                                                   slug=slug)
164             except:
165                 raise error.IdDoesNotExistError("No item for this identifier")
166             return self.record_for_book(deleted_book)
167
168     def validate_kw(self, kw):
169         if 'resumptionToken' in kw:
170             raise error.BadResumptionTokenError("No resumption token support at this point")
171         if 'metadataPrefix' in kw and not self.metadata_registry.hasWriter(kw['metadataPrefix']):
172             raise error.CannotDisseminateFormatError("This format is not supported")
173
174     def identifier_to_slug(self, ident):
175         return ident.split(':')[-1]
176
177     def slug_to_identifier(self, slug):
178         return self.oai_id % slug
179
180     def listIdentifiers(self, **kw):
181         self.validate_kw(kw)
182         records = [self.record_for_book(book, headers_only=True) for
183                    book in self.books(None,
184                            kw.get('from_', None),
185                            kw.get('until', None))]
186         return records, None
187
188     def listRecords(self, **kw):
189         """
190 can get a resumptionToken kw.
191 returns result, token
192         """
193         self.validate_kw(kw)
194         records = [self.record_for_book(book) for
195                    book in self.books(None,
196                            kw.get('from_', None),
197                            kw.get('until', None))]
198
199         return records, None
200
201     def listMetadataFormats(self, **kw):
202         formats = [
203             ('oai_dc',
204              'http://www.openarchives.org/OAI/2.0/oai_dc.xsd',
205              server.NS_OAIDC),
206             ('qdc',
207              'http://dublincore.org/schemas/xmls/qdc/2006/01/06/dcterms.xsd',
208              NS_DCTERMS)]
209         if 'identifier' in kw:
210             slug = self.identifier_to_slug(kw['identifier'])
211             try:
212                 b = Book.objects.get(slug=slug)
213                 return formats
214             except:
215                 try:
216                     d = Deleted.objects.get(slug=slug)
217                     return []
218                 except:
219                     raise error.IdDoesNotExistError("This id does not exist")
220         else:
221             return formats
222
223     def listSets(self, **kw):
224         raise error.NoSetHierarchyError("Wolne Lektury does not support sets.")
225         # tags = []
226         # for category in Catalogue.TAG_CATEGORIES:
227         #     for tag in Tag.objects.filter(category=category):
228         #         tags.append(("%s:%s" % (tag.category, tag.slug),
229         #                      tag.name,
230         #                      tag.description))
231         # return tags, None