views.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  1. import datetime
  2. import json
  3. from django.db import IntegrityError
  4. from django.http import HttpResponseForbidden, HttpResponseNotFound, HttpResponseRedirect, JsonResponse, HttpResponseNotAllowed
  5. from django.shortcuts import render
  6. from django.contrib.auth import authenticate, login as auth_login, logout as auth_logout
  7. from django.views.decorators.csrf import csrf_exempt
  8. from django.views.decorators.vary import vary_on_cookie
  9. from django.views.decorators.cache import cache_page
  10. from django.utils.translation import gettext as _
  11. from django.contrib.auth.models import User
  12. from .forms import CreateEventForm, LoginForm, UpdateSlotsForm
  13. from .models import Event, Participant, Date
  14. from .helpers import slots2string, string2slots, get_slot_count, slots2grid
  15. @cache_page(60 * 15)
  16. def index(request):
  17. return render(request, 'zitap/index.html')
  18. def my_events(request):
  19. if not request.session.get('user_id'):
  20. form = LoginForm({'username': request.session.get('username', '')})
  21. form.add_error('password', _('Please enter a password.'))
  22. return render(request, 'zitap/login.html', {'form': form, 'url': 'my-events', 'text': _('Login to My Events')})
  23. print(request.session.get('user_id'))
  24. events = Event.objects.filter(participant__user=request.user).prefetch_related('date_set', 'participant_set', 'participant_set__user')
  25. return render(request, 'zitap/my-events.html', {
  26. 'events': events,
  27. })
  28. def about(request):
  29. return render(request, 'zitap/about.html')
  30. @cache_page(60 * 15)
  31. def create_event(request):
  32. if request.method == 'POST':
  33. form = CreateEventForm(request.POST)
  34. if form.is_valid():
  35. data = form.cleaned_data
  36. # Try to create the event. If the url is already taken, try again.
  37. n = 0
  38. while n<10:
  39. try:
  40. event = Event.objects.create(
  41. name=data['event_name'],
  42. start_time=datetime.time(int(data['start_time']), 0),
  43. end_time=datetime.time(int(data['end_time']), 0),
  44. slot_interval=datetime.timedelta(minutes=int(data['slot_interval'])),
  45. )
  46. for date in data['event_date']:
  47. event.date_set.create(date=date)
  48. event.save()
  49. return HttpResponseRedirect(f'/{event.url}')
  50. except IntegrityError:
  51. n += 1
  52. form.add_error(None, _('Could not create event. Please try again.'))
  53. else:
  54. form = CreateEventForm()
  55. return render(request, 'zitap/create-event.html', {'form': form})
  56. @cache_page(60 * 15)
  57. @vary_on_cookie
  58. def event(request, url):
  59. event = Event.objects.filter(url=url).prefetch_related('date_set', 'participant_set', 'participant_set__user').first()
  60. participants = list(event.participant_set.all()) if event else []
  61. if not event:
  62. return render(request, 'zitap/event-not-found.html')
  63. # Check if the user is logged in
  64. participant = None
  65. if 'username' in request.session:
  66. for participant in participants:
  67. if participant.name == request.session['username']:
  68. break
  69. else:
  70. participant = None
  71. login_form = None
  72. n_slots = get_slot_count(event)
  73. update_form = UpdateSlotsForm(initial={'slots': slots2string(participant, n_slots)}, event=event, n_slots=n_slots, participant=participant)
  74. else:
  75. login_form = LoginForm()
  76. update_form = None
  77. return render(
  78. request,
  79. 'zitap/event.html',
  80. {'event': event, 'grid': slots2grid(event, participants, False), 'login_form': login_form, 'update_form': update_form}
  81. )
  82. def login(request, url):
  83. if url == 'my-events':
  84. text = _('Login to My Events')
  85. elif Event.objects.filter(url=url).exists():
  86. text = _('Login to Update Slots')
  87. else:
  88. return render(request, 'zitap/event-not-found.html')
  89. if request.method == 'POST':
  90. form = LoginForm(request.POST)
  91. elif 'username' in request.session:
  92. return HttpResponseRedirect(f'/{url}')
  93. else:
  94. form = LoginForm()
  95. if form.is_valid():
  96. data = form.cleaned_data
  97. user = authenticate(request, username=data['username'], password=data.get('password'))
  98. if user is None and data.get('password'):
  99. try:
  100. user = User.objects.create_user(data['username'], password=data.get('password'))
  101. except IntegrityError:
  102. form.add_error('password', _('Wrong password'))
  103. return render(request, 'zitap/login.html', {'form': form, 'url': url, 'text': text})
  104. elif user is None and User.objects.filter(username=data['username']).exists():
  105. form.add_error('username', _('Username already exists'))
  106. return render(request, 'zitap/login.html', {'form': form, 'url': url, 'text': text})
  107. if user:
  108. auth_login(request, user)
  109. request.session['user_id'] = user.id
  110. elif 'user_id' in request.session:
  111. del request.session['user_id']
  112. request.session['username'] = data['username']
  113. return HttpResponseRedirect(f'/{url}')
  114. return render(request, 'zitap/login.html', {'form': form, 'url': url, 'text': text})
  115. def logout(request, url):
  116. auth_logout(request)
  117. if url == 'my-events':
  118. return HttpResponseRedirect(f'/my-events/login')
  119. elif Event.objects.filter(url=url).exists():
  120. return HttpResponseRedirect(f'/{url}')
  121. else:
  122. return render(request, 'zitap/event-not-found.html')
  123. def update_slots(request, url):
  124. try:
  125. event = Event.objects.get(url=url)
  126. except Event.DoesNotExist:
  127. return render(request, 'zitap/event-not-found.html')
  128. if request.method != 'POST':
  129. return HttpResponseNotAllowed(['POST'])
  130. if 'username' not in request.session:
  131. return HttpResponseForbidden()
  132. slot_count = get_slot_count(event)
  133. participant = event.participant_set.filter(name=request.session['username'], event=event).first()
  134. form = UpdateSlotsForm(request.POST, event=event, n_slots=slot_count, participant=participant)
  135. if form.is_valid():
  136. data = form.cleaned_data
  137. if data['slots'] == '0' * slot_count and participant:
  138. participant.delete()
  139. elif not participant:
  140. participant = Participant.objects.create(name=request.session['username'], user_id=request.session['user_id'], event=event, slots=string2slots(data['slots'], slot_count))
  141. else:
  142. participant.slots = string2slots(data['slots'], slot_count)
  143. participant.save()
  144. return HttpResponseRedirect(f'/{event.url}')
  145. def event_api(request, url):
  146. """
  147. REST JSON API for an event
  148. """
  149. try:
  150. event = Event.objects.get(url=url)
  151. except Event.DoesNotExist:
  152. return JsonResponse({'error': 'Event not found'}, status=404)
  153. if request.method == 'GET':
  154. return JsonResponse({
  155. 'name': event.name,
  156. 'url': event.url,
  157. 'start_time': event.start_time.strftime('%H:%M'),
  158. 'end_time': event.end_time.strftime('%H:%M'),
  159. 'slot_interval': event.slot_interval.seconds // 60,
  160. 'dates': [date.date.strftime('%Y-%m-%d') for date in event.date_set.all()],
  161. })
  162. else:
  163. return HttpResponseNotAllowed(['GET'])
  164. @csrf_exempt
  165. def slots_api(request, url):
  166. """
  167. REST JSON API for slots of all participants of an event
  168. Slots are represented as a string of 0s and 1s where 0 means the slot is available and 1 means the slot is taken.
  169. The string begins with the first slot of the first day of the event and ends with the last slot of the last day of the event.
  170. """
  171. event = Event.objects.filter(url=url).prefetch_related('date_set', 'participant_set', 'participant_set__user').first()
  172. participants = list(event.participant_set.all()) if event else []
  173. if not event:
  174. return HttpResponseNotFound()
  175. slot_count = get_slot_count(event)
  176. # Check if the user is logged in and wants to update their slots
  177. if 'username' in request.session and request.method == 'POST':
  178. for participant in participants:
  179. if participant.name == request.session['username']:
  180. break
  181. else:
  182. participant = None
  183. slot_count = get_slot_count(event)
  184. form = UpdateSlotsForm(request.POST, event=event, n_slots=slot_count, participant=participant)
  185. if form.is_valid():
  186. data = form.cleaned_data
  187. if data['slots'] == '0' * slot_count and participant:
  188. participant.delete()
  189. elif not participant:
  190. participant = Participant.objects.create(name=request.session['username'], user_id=request.session.get('user_id'), event=event, slots=string2slots(data['slots'], slot_count))
  191. else:
  192. participant.slots = string2slots(data['slots'], slot_count)
  193. participant.save()
  194. # Get the slots of each participant
  195. data = {
  196. 'username': request.session.get('username'),
  197. 'n_slots': slot_count,
  198. 'participants': [participant.name for participant in participants],
  199. 'slots': [slots2string(participant, slot_count) for participant in participants],
  200. }
  201. return JsonResponse(data)