__doc__ = "Module documentation."
from piston.handler import BaseHandler, AnonymousBaseHandler
-from piston.utils import rc
+
import settings
import librarian
from datetime import date
from django.core.urlresolvers import reverse
-from wlrepo import MercurialLibrary, RevisionNotFound
+from wlrepo import MercurialLibrary, RevisionNotFound, DocumentAlreadyExists
from librarian import dcparser
+import api.response as response
+from api.response import validate_form
+
#
# Document List Handlers
#
return {'documents' : document_list }
- def create(self, request):
+ @validate_form(forms.DocumentUploadForm, 'POST')
+ def create(self, request, form):
"""Create a new document."""
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
- form = forms.DocumentUploadForm(request.POST, request.FILES)
- if not form.is_valid():
- return rc.BAD_REQUEST
-
- f = request.FILES['ocr']
- data = f.read().decode('utf-8')
+ if form.cleaned_data['ocr_data']:
+ data = form.cleaned_data['ocr_data'].encode('utf-8')
+ else:
+ data = request.FILES['ocr'].read().decode('utf-8')
if form.cleaned_data['generate_dc']:
data = librarian.wrap_text(data, unicode(date.today()))
- # TODO: what if the file exists ?
- doc = lib.document_create(form.cleaned_data['bookname'])
- doc.quickwrite('xml', data, '$AUTO$ XML data uploaded.',
- user=request.user.username)
+ docid = form.cleaned_data['bookname']
+ try:
+ doc = lib.document_create(docid)
+ doc.quickwrite('xml', data, '$AUTO$ XML data uploaded.',
+ user=request.user.username)
+
+ url = reverse('document_view', args=[doc.id])
- return {
- 'url': reverse('document_view', args=[doc.id]),
- 'name': doc.id,
- 'revision': doc.revision }
+
+ return response.EntityCreated().django_response(\
+ body = {
+ 'url': url,
+ 'name': doc.id,
+ 'revision': doc.revision },
+ url = url )
+
+ except DocumentAlreadyExists:
+ # Document is already there
+ return response.EntityConflict().django_response(\
+ {"reason": "Document %s already exists." % docid})
#
# Document Handlers
allowed_methods = ('GET',)
def read(self, request, docid):
- lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
-
- opts = forms.DocumentGetForm(request.GET)
- if not opts.is_valid():
- return rc.BAD_REQUEST
-
- doc = lib.document(docid)
+ try:
+ lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
+ doc = lib.document(docid)
+ except RevisionNotFound:
+ return rc.NOT_FOUND
result = {
'name': doc.id,
'text_url': reverse('doctext_view', args=[doc.id]),
'dc_url': reverse('docdc_view', docid=doc.id),
- 'latest_rev': doc.revision,
+ 'public_revision': doc.revision,
}
return result
def read(self, request, docid):
"""Read document's meta data"""
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
-
- opts = forms.DocumentGetForm(request.GET)
- if not opts.is_valid():
- return rc.BAD_REQUEST
-
+
try:
doc = lib.document(docid)
udoc = doc.take(request.user.username)
except RevisionNotFound:
- return rc.NOT_HERE
+ return request.EnityNotFound().django_response()
# is_shared = udoc.ancestorof(doc)
# is_uptodate = is_shared or shared.ancestorof(document)
'text_url': reverse('doctext_view', args=[udoc.id]),
'dc_url': reverse('docdc_view', args=[udoc.id]),
'parts_url': reverse('docparts_view', args=[udoc.id]),
- 'latest_rev': udoc.revision,
- 'latest_shared_rev': doc.revision,
- # 'shared': is_shared,
- # 'up_to_date': is_uptodate,
- }
-
- #if request.GET.get('with_part', 'no') == 'yes':
- # result['parts'] = document.parts()
+ 'user_revision': udoc.revision,
+ 'public_revision': doc.revision,
+ }
return result
class DocumentTextHandler(BaseHandler):
allowed_methods = ('GET', 'PUT')
- def read(self, request, docid):
- """Read document as raw text"""
+ @validate_form(forms.DocumentEntryRequest)
+ def read(self, request, form, docid):
+ """Read document as raw text"""
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
+
try:
- return lib.document(docid, request.user.username).data('xml')
+ if request.GET['revision'] == 'latest':
+ document = lib.document(docid)
+ else:
+ document = lib.document_for_rev(request.GET['revision'])
+
+ # TODO: some finer-grained access control
+ return document.data('xml')
except RevisionNotFound:
- return rc.NOT_HERE
+ return response.EntityNotFound().django_response()
def update(self, request, docid):
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
orig = lib.document_for_rev(prev)
if current != orig:
- return rc.DUPLICATE_ENTRY
-
- doc.quickwrite('xml', data, msg)
-
- return rc.ALL_OK
+ return response.EntityConflict().django_response({
+ "reason": "out-of-date",
+ "provided_revision": orig.revision,
+ "latest_revision": current.revision })
+
+ ndoc = doc.quickwrite('xml', data, msg)
+
+ # return the new revision number
+ return {
+ "document": ndoc.id,
+ "subview": "xml",
+ "previous_revision": prev,
+ "updated_revision": ndoc.revision
+ }
+
except (RevisionNotFound, KeyError):
- return rc.NOT_HERE
+ return response.EntityNotFound().django_response()
#
# Dublin Core handlers
class DocumentDublinCoreHandler(BaseHandler):
allowed_methods = ('GET', 'PUT')
+ @validate_form(forms.DocumentEntryRequest)
def read(self, request, docid):
"""Read document as raw text"""
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
try:
- doc = lib.document(docid, request.user.username).data('xml')
- bookinfo = dcparser.BookInfo.from_string(doc.read())
-
+ if request.GET['revision'] == 'latest':
+ document = lib.document(docid)
+ else:
+ document = lib.document_for_rev(request.GET['revision'])
+
+ bookinfo = dcparser.BookInfo.from_string(doc.data('xml'))
return bookinfo.serialize()
except RevisionNotFound:
- return rc.NOT_HERE
+ return response.EntityNotFound().django_response()
def update(self, request, docid):
lib = MercurialLibrary(path=settings.REPOSITORY_PATH)
orig = lib.document_for_rev(prev)
if current != orig:
- return rc.DUPLICATE_ENTRY
+ return response.EntityConflict().django_response({
+ "reason": "out-of-date",
+ "provided": orig.revision,
+ "latest": current.revision })
xmldoc = parser.WLDocument.from_string(current.data('xml'))
document.book_info = dcparser.BookInfo.from_json(bi_json)
# zapisz
- current.quickwrite('xml', document.serialize().encode('utf-8'),\
+ ndoc = current.quickwrite('xml', \
+ document.serialize().encode('utf-8'),\
message=msg, user=request.user.username)
- return rc.ALL_OK
+ return {
+ "document": ndoc.id,
+ "subview": "xml",
+ "previous_revision": prev,
+ "updated_revision": ndoc.revision
+ }
except (RevisionNotFound, KeyError):
- return rc.NOT_HERE
+ return response.EntityNotFound().django_response()
--- /dev/null
+# -*- encoding: utf-8 -*-
+
+__author__= "Łukasz Rekucki"
+__date__ = "$2009-09-26 00:32:18$"
+__doc__ = "Extensible HTTP Responses."
+
+from django.http import HttpResponse
+from django.utils import simplejson as json
+
+MIME_PLAIN = 'text/plain'
+MIME_JSON = 'application/json'
+
+class ResponseObject(object):
+
+ def __init__(self, code, mimetype=MIME_JSON):
+ self._code = code
+ self._mime = mimetype
+
+ def django_response(self, body=None):
+ if body is None:
+ data = ''
+ elif self._mime == MIME_JSON:
+ data = json.dumps(body, default=lambda o: repr(o) )
+ else:
+ data = u"%s\n%s" % (self.MESSAGE, unicode(self._info))
+ data = data.encode('utf-8')
+
+ return HttpResponse(content=data, status=self._code, \
+ content_type=self._mime+'; charset=utf-8' )
+
+class SuccessAllOk(ResponseObject):
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 200, **kwargs)
+
+class EntityCreated(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 201, **kwargs)
+
+ def django_response(self, url, body):
+ response = ResponseObject.django_response(self, body)
+ response['Location'] = url
+ return response
+
+class RequestAccepted(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 202, **kwargs)
+
+ def django_response(self, ticket_status, ticket_uri):
+ return ResponseObject.django_response(self, {
+ 'status': ticket_status,
+ 'refer_to': ticket_uri })
+
+class SuccessNoContent(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 204, **kwargs)
+
+ def django_response(self):
+ return ResponseObject.django_response(self, body=None)
+
+
+#
+# Client errors
+#
+
+class BadRequest(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 400, **kwargs)
+
+class AccessDenied(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 403, **kwargs)
+
+ def django_response(self, reason):
+ return ResponseObject.django_response(self, \
+ body={'reason': reason})
+
+class EntityNotFound(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 404, **kwargs)
+
+class EntityGone(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 410, **kwargs)
+
+
+class EntityConflict(ResponseObject):
+
+ def __init__(self, **kwargs):
+ ResponseObject.__init__(self, 409, **kwargs)
+
+
+def validate_form(formclass, source='GET'):
+ from functools import wraps
+
+ def decorator(func):
+ @wraps(func)
+ def decorated(self, request, *args, **kwargs):
+ form = formclass(getattr(request, source), request.FILES)
+
+ if not form.is_valid():
+ errorlist = [{'field': k, 'errors': e} for k,e in form.errors]
+ return BadRequest().django_response(errorlist)
+
+ return func(self, request, form, *args, **kwargs)
+ return decorated
+ return decorator
+
+
+
+
+
+