Updated API tests.
[redakcja.git] / apps / api / handlers / library_handlers.py
1 # -*- encoding: utf-8 -*-
2
3 __author__= "Ɓukasz Rekucki"
4 __date__ = "$2009-09-25 15:49:50$"
5 __doc__ = "Module documentation."
6
7 from piston.handler import BaseHandler, AnonymousBaseHandler
8 from piston.utils import rc
9
10 import settings
11 import librarian
12 import api.forms as forms
13 from datetime import date
14
15 from django.core.urlresolvers import reverse
16 from wlrepo import MercurialLibrary, RevisionNotFound
17
18 from librarian import dcparser
19
20 #
21 # Document List Handlers
22 #
23 class BasicLibraryHandler(AnonymousBaseHandler):
24     allowed_methods = ('GET',)
25
26     def read(self, request):
27         """Return the list of documents."""
28         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
29
30         document_list = [{
31             'url': reverse('document_view', args=[docid]),
32             'name': docid } for docid in lib.documents() ]
33
34         return {'documents' : document_list}
35
36 class LibraryHandler(BaseHandler):
37     allowed_methods = ('GET', 'POST')
38     anonymous = BasicLibraryHandler
39
40     def read(self, request):
41         """Return the list of documents."""
42         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
43
44         document_list = [{
45             'url': reverse('document_view', args=[docid]),
46             'name': docid } for docid in lib.documents() ]
47
48         return {'documents' : document_list }
49
50     def create(self, request):
51         """Create a new document."""
52         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
53
54         form = forms.DocumentUploadForm(request.POST, request.FILES)
55         if not form.is_valid():
56             return rc.BAD_REQUEST
57
58         f = request.FILES['ocr']
59         data = f.read().decode('utf-8')
60
61         if form.cleaned_data['generate_dc']:
62             data = librarian.wrap_text(data, unicode(date.today()))
63
64         # TODO: what if the file exists ?
65         doc = lib.document_create(form.cleaned_data['bookname'])
66         doc.quickwrite('xml', data, '$AUTO$ XML data uploaded.',
67             user=request.user.username)
68
69         return {
70             'url': reverse('document_view', args=[doc.id]),
71             'name': doc.id,
72             'revision': doc.revision }
73
74 #
75 # Document Handlers
76 #
77 class BasicDocumentHandler(AnonymousBaseHandler):
78     allowed_methods = ('GET',)
79
80     def read(self, request, docid):
81         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
82
83         opts = forms.DocumentGetForm(request.GET)
84         if not opts.is_valid():
85             return rc.BAD_REQUEST
86
87         doc = lib.document(docid)
88
89         result = {
90             'name': doc.id,
91             'text_url': reverse('doctext_view', args=[doc.id]),
92             'dc_url': reverse('docdc_view', docid=doc.id),
93             'latest_rev': doc.revision,
94         }
95
96         return result
97
98 #
99 # Document Meta Data
100 #
101 class DocumentHandler(BaseHandler):
102     allowed_methods = ('GET', 'PUT')
103     anonymous = BasicDocumentHandler
104
105     def read(self, request, docid):
106         """Read document's meta data"""
107         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
108
109         opts = forms.DocumentGetForm(request.GET)
110         if not opts.is_valid():
111             return rc.BAD_REQUEST
112
113         try:
114             doc = lib.document(docid)
115             udoc = doc.take(request.user.username)
116         except RevisionNotFound:
117             return rc.NOT_HERE
118
119         # is_shared = udoc.ancestorof(doc)
120         # is_uptodate = is_shared or shared.ancestorof(document)
121
122         result = {
123             'name': udoc.id,
124             'text_url': reverse('doctext_view', args=[udoc.id]),
125             'dc_url': reverse('docdc_view', args=[udoc.id]),
126             'parts_url': reverse('docparts_view', args=[udoc.id]),
127             'latest_rev': udoc.revision,
128             'latest_shared_rev': doc.revision,
129             # 'shared': is_shared,
130             # 'up_to_date': is_uptodate,
131         }
132
133         #if request.GET.get('with_part', 'no') == 'yes':
134         #    result['parts'] = document.parts()
135
136         return result
137
138 #
139 # Document Text View
140 #
141 class DocumentTextHandler(BaseHandler):
142     allowed_methods = ('GET', 'PUT')
143
144     def read(self, request, docid):
145         """Read document as raw text"""
146         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
147         try:
148             return lib.document(docid, request.user.username).data('xml')
149         except RevisionNotFound:
150             return rc.NOT_HERE
151
152     def update(self, request, docid):
153         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
154         try:
155             data = request.PUT['contents']
156             prev = request.PUT['revision']
157
158             if request.PUT.has_key('message'):
159                 msg = u"$USER$ " + request.PUT['message']
160             else:
161                 msg = u"$AUTO$ XML content update."
162
163             current = lib.document(docid, request.user.username)
164             orig = lib.document_for_rev(prev)
165
166             if current != orig:
167                 return rc.DUPLICATE_ENTRY
168
169             doc.quickwrite('xml', data, msg)
170
171             return rc.ALL_OK
172         except (RevisionNotFound, KeyError):
173             return rc.NOT_HERE
174
175 #
176 # Dublin Core handlers
177 #
178 # @requires librarian
179 #
180 class DocumentDublinCoreHandler(BaseHandler):
181     allowed_methods = ('GET', 'PUT')
182
183     def read(self, request, docid):
184         """Read document as raw text"""
185         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
186         try:
187             doc = lib.document(docid, request.user.username).data('xml')
188             bookinfo = dcparser.BookInfo.from_string(doc.read())
189
190             return bookinfo.serialize()
191         except RevisionNotFound:
192             return rc.NOT_HERE
193
194     def update(self, request, docid):
195         lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
196         try:
197             bi_json = request.PUT['contents']
198             prev = request.PUT['revision']
199             if request.PUT.has_key('message'):
200                 msg = u"$USER$ " + request.PUT['message']
201             else:
202                 msg = u"$AUTO$ Dublin core update."
203
204             current = lib.document(docid, request.user.username)
205             orig = lib.document_for_rev(prev)
206
207             if current != orig:
208                 return rc.DUPLICATE_ENTRY
209
210             xmldoc = parser.WLDocument.from_string(current.data('xml'))
211             document.book_info = dcparser.BookInfo.from_json(bi_json)
212
213             # zapisz
214             current.quickwrite('xml', document.serialize().encode('utf-8'),\
215                 message=msg, user=request.user.username)
216
217             return rc.ALL_OK
218         except (RevisionNotFound, KeyError):
219             return rc.NOT_HERE