18bc5e6f097c639e6f04cfd9e50bd96c65c7465f
[cascardo/ema.git] / eventos / views.py
1 # -*- coding: utf-8 -*-
2 # Copyright (C) 2008 Lincoln de Sousa <lincoln@minaslivre.org>
3 #
4 # This program is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU General Public License as
6 # published by the Free Software Foundation; either version 2 of the
7 # License, or (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public
15 # License along with this program; if not, write to the
16 # Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17 # Boston, MA 02111-1307, USA.
18 from django.conf import settings
19 from django.http import HttpResponseRedirect, HttpResponseForbidden
20 from django.contrib.auth import authenticate, login as login_django, \
21     logout as logout_django
22 from django.contrib.auth.models import User, Group
23 from django.forms import HiddenInput, ModelForm
24 from django.shortcuts import render_to_response, get_object_or_404
25 from django.template import RequestContext, Context, loader
26 from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento
27 from eventos.forms import RegisterSpeaker
28 from django.db.models import Q
29
30 forbidden = \
31     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
32
33 class SpeakerForm(ModelForm):
34     class Meta:
35         model = Palestrante
36         exclude = ('usuario',)
37
38 class TalkForm(ModelForm):
39     class Meta:
40         model = Trabalho
41
42 def login(request):
43     """This is a function that will be used as a front-end to the
44     django's login system. It receives username and password fields
45     from a POST request and tries to login the user.
46
47     If login is successful, user will be redirected to the referer
48     address, otherwise will be redirected to /?login_failed.
49     """
50     username = request.POST['username']
51     password = request.POST['password']
52     user = authenticate(username=username, password=password)
53
54     if user is not None:
55         if user.is_active:
56             login_django(request, user)
57             try:
58                 request.session.delete_test_cookie()
59             except KeyError:
60                 pass
61             return HttpResponseRedirect('/')
62         else:
63             return HttpResponseRedirect('/?login_failed')
64     else:
65         return HttpResponseRedirect('/?login_failed')
66
67     request.session.set_test_cookie()
68     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
69
70 def logout(request):
71     """Simple front-end to django's logout stuff. This function should
72     be mapped to an url and simply called without any parameter.
73     """
74     logout_django(request)
75     return HttpResponseRedirect('/')
76
77 def speaker_add(request):
78     """Adds a new speaker to the system.
79     """
80     uform = RegisterSpeaker(request.POST or None)
81
82     form = SpeakerForm(request.POST or None)
83
84     if request.POST and form.is_valid() and uform.is_valid():
85         cd = uform.cleaned_data
86         group = Group.objects.get_or_create(name='palestrantes')[0]
87
88         # creating the user that will be set as the user of the
89         # speaker.
90         user = User(username=cd['username'])
91         user.set_password(cd['password1'])
92         user.is_active = True
93         user.save()
94         user.groups.add(group)
95
96         # this commit=False is to avoid IntegritErrors, because at
97         # this point, the speaker doesn't have an user associated
98         # with it.
99         instance = form.save(commit=False)
100         instance.usuario = user
101         instance.save()
102         return HttpResponseRedirect('/')
103
104     c = {'form': form, 'uform': uform}
105     return render_to_response('eventos/speaker-add.html', Context(c),
106                               context_instance=RequestContext(request))
107
108 def speaker_details(request, lid):
109     """Shows a simple form containing all editable fields of a
110     speaker and gives the speaker the possibility to save them =)
111     """
112     if not hasattr(request.user, 'palestrante_set'):
113         return forbidden
114
115     entity = request.user.palestrante_set.get()
116     if entity.id != int(lid):
117         return forbidden
118
119     form = SpeakerForm(request.POST or None, instance=entity)
120
121     if request.POST and form.is_valid():
122         form.save()
123
124     c = {'form': form}
125     return render_to_response('eventos/speaker-details.html', Context(c),
126                               context_instance=RequestContext(request))
127
128 def speaker_talks(request, lid):
129     """Lists all talks of a speaker (based on speaker id -- lid
130     parameter).
131     """
132     if not hasattr(request.user, 'palestrante_set'):
133         return forbidden
134
135     entity = request.user.palestrante_set.get()
136     if entity.id != int(lid):
137         return forbidden
138
139     talks = Trabalho.objects.filter(
140         Q(palestrante=entity) | Q(outros_palestrantes=entity) )
141
142     c = {'speaker': entity, 'talks': talks}
143     return render_to_response('eventos/talk-list.html', Context(c),
144                               context_instance=RequestContext(request))
145
146 def talk_details(request, tid):
147     """Shows a form to edit a talk
148     """
149     # If the user is not a speaker we should not try to show anything.
150     if not hasattr(request.user, 'palestrante_set'):
151         return forbidden
152
153     # Selected in settings.py (SITE_ID) variable, because an event can
154     # be linked with only one site.
155     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
156
157     # building the form
158     entity = get_object_or_404(Trabalho, pk=tid)
159     form = TalkForm(request.POST or None, instance=entity)
160
161     # These fields should not be shown to the user.
162     form.fields['palestrante'].widget = HiddenInput()
163     form.fields['evento'].widget = HiddenInput()
164
165     # These fields are event specific
166     trilhas = Trilha.objects.filter(evento=event)
167     form.fields['trilha']._set_queryset(trilhas)
168
169     tipos = TipoTrabalho.objects.filter(evento=event)
170     form.fields['tipo']._set_queryset(tipos)
171
172     # hidding the owner in the other speakers list
173     other = Palestrante.objects.exclude(pk=entity.id)
174     form.fields['outros_palestrantes']._set_queryset(other)
175     if other.count() == 0:
176         # I need set the value to '', otherwise the wise django
177         # newforms will fill the field with the invalid string '[]'
178         form.fields['outros_palestrantes'].initial = ''
179         form.fields['outros_palestrantes'].widget = HiddenInput()
180
181     # avoiding smart people trying to se talks of other speakers.
182     speaker = request.user.palestrante_set.get()
183     if speaker.id != entity.palestrante.id \
184             and speaker not in entity.outros_palestrantes.all():
185         return forbidden
186
187     if request.POST and form.is_valid():
188         form.save()
189
190     c = {'form': form}
191     return render_to_response('eventos/talk-details.html', Context(c),
192                               context_instance=RequestContext(request))
193
194 def talk_delete(request, tid):
195     """Drops a talk but only if the logged in user is its owner.
196     """
197     if not hasattr(request.user, 'palestrante_set'):
198         return forbidden
199
200     entity = request.user.palestrante_set.get()
201     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
202     if not talk:
203         return forbidden
204
205     talk.delete()
206     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
207
208 def talk_add(request):
209     """Shows a form to the speaker send a talk
210     """
211     if not hasattr(request.user, 'palestrante_set'):
212         return forbidden
213
214     # building the form
215     form = TalkForm(request.POST or None)
216
217     # These fields should not be shown to the user.
218
219     # Selected in settings.py (SITE_ID) variable, because an event can
220     # be linked with only one site.
221     entity = request.user.palestrante_set.get()
222     form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
223
224     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
225     form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
226
227     # These fields are event specific
228     trilhas = Trilha.objects.filter(evento=event)
229     form.fields['trilha']._set_queryset(trilhas)
230
231     tipos = TipoTrabalho.objects.filter(evento=event)
232     form.fields['tipo']._set_queryset(tipos)
233
234     # hidding the owner in the other speakers list
235     other = Palestrante.objects.exclude(pk=entity.id)
236     form.fields['outros_palestrantes']._set_queryset(other)
237     if other.count() == 0:
238         form.fields['outros_palestrantes'].widget = HiddenInput()
239
240     if request.POST and form.is_valid():
241         # validation
242         cleaned = form.cleaned_data
243         if cleaned['tipo'].evento.id != event.id:
244             return forbidden
245
246         if cleaned['trilha'].evento.id != event.id:
247             return forbidden
248
249         instance = form.save()
250         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
251
252     c = {'form': form}
253     return render_to_response('eventos/talk-add.html', Context(c),
254                               context_instance=RequestContext(request))
255
256 def list_all_talks(request):
257     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
258     trilhas = Trilha.objects.filter(evento=event)
259
260     improve = []
261     for t in trilhas:
262         talks = Trabalho.objects.filter(trilha=t)
263         aux = {'trilha':t.nome, 'talks':talks}
264         improve.append(aux)
265
266     c = {'improve': improve,}
267     return render_to_response('eventos/improve.html', Context(c),
268                               context_instance=RequestContext(request))