Annotations
[oweals/karmaworld.git] / karmaworld / utils / ajax_utils.py
1 import json
2 from django.core.exceptions import ObjectDoesNotExist
3 from django.http import HttpResponseBadRequest, HttpResponseNotFound, HttpResponse
4
5
6 def format_session_increment_field(cls, id, field):
7     return cls.__name__ + '-' + field + '-' + str(id)
8
9
10 def ajax_base(request, event_processor, allowed_methods):
11     """Handle an AJAX request"""
12     if not request.method in allowed_methods or not request.is_ajax():
13         # return that the api call failed
14         return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be an ajax request with method ' + str(allowed_methods)}),
15                                       mimetype="application/json")
16
17     resp = event_processor(request)
18     if resp:
19         return resp
20     else:
21         return HttpResponse(status=204)
22
23
24 def ajax_pk_base(cls, request, pk, event_processor):
25     """Handle an AJAX request"""
26     if not request.is_ajax():
27         # return that the api call failed
28         return HttpResponseBadRequest(json.dumps({'status': 'fail', 'message': 'must be a POST ajax request'}),
29                                       mimetype="application/json")
30
31     try:
32         obj = cls.objects.get(pk=pk)
33         event_processor(request.user, obj)
34
35     except ObjectDoesNotExist:
36         return HttpResponseNotFound(json.dumps({'status': 'fail', 'message': 'id does not match a ' + cls.__name__}),
37                                     mimetype="application/json")
38
39     return HttpResponse(status=204)
40
41
42 def ajax_increment(cls, request, pk, field, user_profile_field=None, event_processor=None):
43     def ajax_increment_work(request_user, obj):
44         count = getattr(obj, field)
45         setattr(obj, field,  count+1)
46         obj.save()
47
48         if event_processor:
49             event_processor(request.user, obj)
50
51         # Record that user has performed this, to prevent
52         # them from doing it again
53         if user_profile_field:
54             getattr(request_user.get_profile(), user_profile_field).add(obj)
55             obj.save()
56
57     return ajax_pk_base(cls, request, pk, ajax_increment_work)