db43657307afe03d6c581e61d9c325793f58db33
[wolnelektury.git] / apps / oai / handlers.py
1
2 from oaipmh import server, common
3 from catalogue.models import Book, Tag
4 from api.models import Deleted
5 from librarian.dcparser import BookInfo
6 from django.contrib.contenttypes.models import ContentType
7
8
9 class Catalogue(common.ResumptionOAIPMH):
10     def __init__(self):
11         super(Catalogue, self).__init__()
12
13     def metadata(self, book):
14         bi = BookInfo.from_file(book.xml_file)
15         meta = {}
16         for field in bi.FIELDS:
17             dc_field = field.uri.split('}')[1]
18             value = getattr(bi, dc_field.name)
19             if isinstance(value,list):
20                 value = ';'.join(map(unicode, value))
21             else:
22                 value = unicode(value)
23             meta["dc:"+dc_field] = value
24         return meta
25
26     def record_for_book(self, book):
27         header = common.Header(book.slug, book.changed_at, [], False)
28         meta = common.Metadata(self.metadata(book))
29         about = None
30         return header, meta, about
31
32     def getRecord(self, record, **kw):
33         """
34 Returns (header, metadata, about) for given record.
35         """
36         slug = kw['record']
37         try:
38             book = Book.objects.get(slug=slug)
39             return self.record_for_book(book)
40         except Book.DoesNotExist, e:
41             book_type = ContentType.objects.get_for_model(Book)
42             deleted_book = Deleted.objects.filter(content_type=book_type,
43                                                   slug=slug)
44             header = common.Header(deleted_book.slug,
45                                    deleted_book.deleted_at,
46                                    [], True)
47             meta = common.Metadata({})
48             return header, meta, None # None for about.
49                                    
50
51         
52     def listRecords(self, **kw):
53         """
54 can get a resumptionToken kw.
55 returns result, token
56         """
57         return [self.record_for_book(book) for book in Book.objects.all()]
58