update emails for stage2
[edumed.git] / wtem / views.py
1 # -*- coding: utf-8 -*-
2 import json
3 from copy import deepcopy
4 from functools import wraps
5
6 from django.conf import settings
7 from django.contrib import messages
8 from django.core.urlresolvers import reverse
9 from django.http import HttpResponseForbidden
10 from django.http.response import HttpResponseRedirect, Http404
11 from django.shortcuts import render, get_object_or_404
12 from django.utils import timezone
13 from django.utils.cache import patch_cache_control, add_never_cache_headers
14 from django.views.decorators.cache import never_cache
15 from django.views.decorators.csrf import csrf_exempt
16
17 from wtem.models import Confirmation
18 from .forms import WTEMForm, WTEMSingleForm
19 from .models import Submission, DEBUG_KEY, exercises, CompetitionState
20
21
22 def cache_until_start(view_func):
23     @wraps(view_func)
24     def _wrapped_view_func(request, *args, **kwargs):
25         response = view_func(request, *args, **kwargs)
26         max_age = max(int((CompetitionState.start - timezone.now()).total_seconds()) + 1, 0)
27         if max_age:
28             patch_cache_control(response, max_age=max_age)
29         else:
30             add_never_cache_headers(response)
31         return response
32
33     return _wrapped_view_func
34
35
36 def get_submission(submission_id):
37     try:
38         submission_id = int(submission_id)
39     except ValueError:
40         raise Http404
41     return get_object_or_404(Submission, id=submission_id)
42
43
44 @csrf_exempt
45 def form(request, submission_id, key):
46     state = CompetitionState.get_state()
47     if state == CompetitionState.DURING:
48         state = 'single'
49     return globals()['form_' + state](request, submission_id, key)
50
51
52 @cache_until_start
53 def form_before(request, submission_id, key):
54     submission = get_submission(submission_id)
55     if submission.key != key:
56         return render(request, 'wtem/key_not_found_before.html')
57     else:
58         submission.opened_link = True
59         submission.save()
60         return render(request, 'wtem/main_before.html')
61
62
63 def form_after(request, submission_id, key):
64     return render(request, 'wtem/main_after.html')
65
66
67 @never_cache
68 @csrf_exempt
69 def form_during(request, key):
70
71     if CompetitionState.get_state() != CompetitionState.DURING:
72         if request.META['REMOTE_ADDR'] not in getattr(settings, 'WTEM_CONTEST_IP_ALLOW', []):
73             return HttpResponseForbidden('Not allowed')
74
75     try:
76         submission = Submission.objects.get(key=key)
77     except Submission.DoesNotExist:
78         if settings.DEBUG and key == DEBUG_KEY:
79             submission = Submission.create(
80                 first_name='Debug', last_name='Debug', email='debug@debug.com', key=DEBUG_KEY)
81         else:
82             return render(request, 'wtem/key_not_found.html')
83     exercises_with_answers = deepcopy(exercises)
84     if submission.answers:
85         answers = json.loads(submission.answers)
86     else:
87         answers = {}
88     for exercise in exercises_with_answers:
89         exercise['saved_answer'] = answers.get(str(exercise['id']), '')
90         if exercise['type'] == 'open' and exercise.get('fields'):
91             field_answers = {field['id']: field['text'] for field in exercise['saved_answer']}
92             for field in exercise['fields']:
93                 field['saved_answer'] = field_answers.get(field['id'], '')
94     if request.method == 'GET':
95         return render(request, 'wtem/main.html', {'exercises': exercises_with_answers, 'end_time': submission.end_time})
96     elif request.method == 'POST':
97         form = WTEMForm(request.POST, request.FILES, instance=submission)
98         if form.is_valid():
99             form.save()
100             return render(request, 'wtem/thanks.html', dict(end_time=submission.end_time))
101         else:
102             raise Exception
103
104
105 @never_cache
106 @csrf_exempt
107 def form_single(request, submission_id, key):
108     if CompetitionState.get_state() != CompetitionState.DURING:
109         if request.META['REMOTE_ADDR'] not in getattr(settings, 'WTEM_CONTEST_IP_ALLOW', []):
110             return HttpResponseForbidden('Not allowed')
111
112     submission = get_submission(submission_id)
113     if submission.key != key:
114         return render(request, 'wtem/key_not_found.html')
115
116     i, exercise = submission.current_exercise()
117
118     exercise_count = len(exercises)
119
120     if not exercise:
121         return render(request, 'wtem/thanks_single.html')
122
123     if request.method == 'GET':
124         return render(request, 'wtem/single.html', {'exercise': exercise, 'no': i, 'exercise_count': exercise_count})
125     elif request.method == 'POST':
126         form = WTEMSingleForm(request.POST, request.FILES, instance=submission)
127         if form.is_valid():
128             try:
129                 form.save()
130             except ValueError as e:
131                 if e.message == 'wrong exercise id':
132                     messages.error(request, u'Próba wysłania odpowiedzi ponownie lub poza kolejnością')
133             return HttpResponseRedirect(reverse('wtem_form', kwargs={'submission_id': submission_id, 'key': key}))
134         else:
135             raise Exception
136
137
138 @cache_until_start
139 @csrf_exempt
140 def start(request, submission_id, key):
141     state = CompetitionState.get_state()
142     if state in (CompetitionState.BEFORE, CompetitionState.AFTER):
143         return globals()['form_' + state](request, submission_id, key)
144
145     submission = get_submission(submission_id)
146     if submission.key != key:
147         return render(request, 'wtem/key_not_found.html')
148
149     submission.opened_link = True
150     submission.save()
151
152     i, exercise = submission.current_exercise()
153     if not exercise:
154         return render(request, 'wtem/thanks_single.html')
155
156     return render(request, 'wtem/start.html', {'exercise_count': len(exercises), 'submission': submission})
157
158
159 def confirmation(request, id, key):
160     conf = get_object_or_404(Confirmation, id=id, key=key)
161     was_confirmed = conf.confirmed
162     if not was_confirmed:
163         conf.confirmed = True
164         conf.save()
165     return render(request, 'wtem/confirmed.html', {'confirmation': conf, 'was_confirmed': was_confirmed})