renaming another file (ugly name =)
[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 import forms
25 from django.shortcuts import render_to_response, get_object_or_404
26 from django.template import RequestContext, Context, loader
27 from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento, Improve
28 from eventos.forms import RegisterSpeaker
29 from django.db.models import Q
30
31 forbidden = \
32     HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
33
34 class SpeakerForm(ModelForm):
35     class Meta:
36         model = Palestrante
37         exclude = ('usuario',)
38
39 class TalkForm(ModelForm):
40     class Meta:
41         model = Trabalho
42
43 class ImproveForm(ModelForm):
44     class Meta:
45         model = Improve
46
47 class SubscribeForm(forms.Form):
48     full_name = forms.CharField(label=u'Nome completo', max_length=255)
49     email = forms.EmailField()
50     username = forms.CharField(max_length=255)
51     password = forms.CharField(label=u'Senha',
52                                max_length=255,
53                                widget=forms.PasswordInput)
54     confirm_password = forms.CharField(label=u'Confirmar senha',
55                                        max_length=255,
56                                        widget=forms.PasswordInput)
57
58     def clean_username(self):
59         data = self.cleaned_data['username']
60         if User.objects.filter(username=data):
61             raise forms.ValidationError(u'O usuário "%s" já existe' % data)
62         return data
63
64     def clean_confirm_password(self):
65         passwd = self.cleaned_data['password']
66         conf_passwd = self.cleaned_data['confirm_password']
67         if passwd != conf_passwd:
68             raise forms.ValidationError(u'A confirmação difere da senha')
69         return conf_passwd
70
71 def login(request):
72     """This is a function that will be used as a front-end to the
73     django's login system. It receives username and password fields
74     from a POST request and tries to login the user.
75
76     If login is successful, user will be redirected to the referer
77     address, otherwise will be redirected to /?login_failed.
78     """
79     username = request.POST['username']
80     password = request.POST['password']
81
82     user = authenticate(username=username, password=password)
83
84     if user is not None:
85         if user.is_active:
86             login_django(request, user)
87             try:
88                 request.session.delete_test_cookie()
89             except KeyError:
90                 pass
91             return HttpResponseRedirect('/')
92         else:
93             return HttpResponseRedirect('/?login_failed')
94     else:
95         return HttpResponseRedirect('/?login_failed')
96
97     request.session.set_test_cookie()
98     return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
99
100 def logout(request):
101     """Simple front-end to django's logout stuff. This function should
102     be mapped to an url and simply called without any parameter.
103     """
104     logout_django(request)
105     return HttpResponseRedirect('/')
106
107 def speaker_add(request):
108     """Adds a new speaker to the system.
109     """
110     uform = RegisterSpeaker(request.POST or None)
111
112     form = SpeakerForm(request.POST or None)
113
114     if request.POST and form.is_valid() and uform.is_valid():
115         cd = uform.cleaned_data
116         group = Group.objects.get_or_create(name='palestrantes')[0]
117
118         # creating the user that will be set as the user of the
119         # speaker.
120         user = User(username=cd['username'])
121         user.set_password(cd['password1'])
122         user.is_active = True
123         user.save()
124         user.groups.add(group)
125
126         # this commit=False is to avoid IntegritErrors, because at
127         # this point, the speaker doesn't have an user associated
128         # with it.
129         instance = form.save(commit=False)
130         instance.usuario = user
131         instance.save()
132         return HttpResponseRedirect('/')
133
134     c = {'form': form, 'uform': uform}
135     return render_to_response('eventos/speaker-add.html', Context(c),
136                               context_instance=RequestContext(request))
137
138 def speaker_details(request, lid):
139     """Shows a simple form containing all editable fields of a
140     speaker and gives the speaker the possibility to save them =)
141     """
142     speaker = get_object_or_404(Palestrante, pk=lid)
143     d = {'speaker' : speaker}
144     if not hasattr(request.user, 'palestrante_set'):
145         return render_to_response('eventos/speaker-view.html', Context(d),
146                                   context_instance=RequestContext(request))
147
148     entity = request.user.palestrante_set.get()
149     if entity.id != int(lid):
150         return render_to_response('eventos/speaker-view.html', Context(d),
151                                   context_instance=RequestContext(request))
152
153     form = SpeakerForm(request.POST or None, instance=entity)
154
155     if request.POST and form.is_valid():
156         form.save()
157
158     c = {'form': form}
159     return render_to_response('eventos/speaker-details.html', Context(c),
160                               context_instance=RequestContext(request))
161
162 def speaker_talks(request, lid):
163     """Lists all talks of a speaker (based on speaker id -- lid
164     parameter).
165     """
166     if not hasattr(request.user, 'palestrante_set'):
167         return forbidden
168
169     entity = request.user.palestrante_set.get()
170     if entity.id != int(lid):
171         return forbidden
172
173     talks = Trabalho.objects.filter(
174         Q(palestrante=entity) | Q(outros_palestrantes=entity) )
175
176     c = {'speaker': entity, 'talks': talks}
177     return render_to_response('eventos/talk-list.html', Context(c),
178                               context_instance=RequestContext(request))
179
180 def talk_details(request, tid):
181     """Shows a form to edit a talk
182     """
183     # If the user is not a speaker we should not try to show anything.
184     if not hasattr(request.user, 'palestrante_set'):
185         return forbidden
186
187     # Selected in settings.py (SITE_ID) variable, because an event can
188     # be linked with only one site.
189     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
190
191     # building the form
192     entity = get_object_or_404(Trabalho, pk=tid)
193     form = TalkForm(request.POST or None, instance=entity)
194
195     # These fields should not be shown to the user.
196     form.fields['palestrante'].widget = HiddenInput()
197     form.fields['evento'].widget = HiddenInput()
198
199     # These fields are event specific
200     trilhas = Trilha.objects.filter(evento=event)
201     form.fields['trilha']._set_queryset(trilhas)
202
203     tipos = TipoTrabalho.objects.filter(evento=event)
204     form.fields['tipo']._set_queryset(tipos)
205
206     # hidding the owner in the other speakers list
207     other = Palestrante.objects.exclude(pk=entity.id)
208     form.fields['outros_palestrantes']._set_queryset(other)
209     if other.count() == 0:
210         # I need set the value to '', otherwise the wise django
211         # newforms will fill the field with the invalid string '[]'
212         form.fields['outros_palestrantes'].initial = ''
213         form.fields['outros_palestrantes'].widget = HiddenInput()
214
215     # avoiding smart people trying to se talks of other speakers.
216     speaker = request.user.palestrante_set.get()
217     if speaker.id != entity.palestrante.id \
218             and speaker not in entity.outros_palestrantes.all():
219         return forbidden
220
221     if request.POST and form.is_valid():
222         form.save()
223
224     c = {'form': form}
225     return render_to_response('eventos/talk-details.html', Context(c),
226                               context_instance=RequestContext(request))
227
228 def talk_delete(request, tid):
229     """Drops a talk but only if the logged in user is its owner.
230     """
231     if not hasattr(request.user, 'palestrante_set'):
232         return forbidden
233
234     entity = request.user.palestrante_set.get()
235     talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
236     if not talk:
237         return forbidden
238
239     talk.delete()
240     return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
241
242 def talk_add(request):
243     """Shows a form to the speaker send a talk
244     """
245     if not hasattr(request.user, 'palestrante_set'):
246         return forbidden
247
248     # building the form
249     form = TalkForm(request.POST or None)
250
251     # These fields should not be shown to the user.
252
253     # Selected in settings.py (SITE_ID) variable, because an event can
254     # be linked with only one site.
255     entity = request.user.palestrante_set.get()
256     form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
257
258     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
259     form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
260
261     # These fields are event specific
262     trilhas = Trilha.objects.filter(evento=event)
263     form.fields['trilha']._set_queryset(trilhas)
264
265     tipos = TipoTrabalho.objects.filter(evento=event)
266     form.fields['tipo']._set_queryset(tipos)
267
268     # hidding the owner in the other speakers list
269     other = Palestrante.objects.exclude(pk=entity.id)
270     form.fields['outros_palestrantes']._set_queryset(other)
271     if other.count() == 0:
272         form.fields['outros_palestrantes'].widget = HiddenInput()
273
274     if request.POST and form.is_valid():
275         # validation
276         cleaned = form.cleaned_data
277         if cleaned['tipo'].evento.id != event.id:
278             return forbidden
279
280         if cleaned['trilha'].evento.id != event.id:
281             return forbidden
282
283         instance = form.save()
284         return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
285
286     c = {'form': form}
287     return render_to_response('eventos/talk-add.html', Context(c),
288                               context_instance=RequestContext(request))
289
290 def list_all_talks(request):
291     event = Evento.objects.get(site__id__exact=settings.SITE_ID)
292     trilhas = Trilha.objects.filter(evento=event)
293
294     improve = []
295     for t in trilhas:
296         talks = Trabalho.objects.filter(trilha=t)
297         aux = {'trilha':t.nome, 'talks':talks}
298         improve.append(aux)
299
300     c = {'improve': improve,}
301     return render_to_response('eventos/improve.html', Context(c),
302                               context_instance=RequestContext(request))
303
304 def talk_improve(request, tid):
305     if not hasattr(request.user, 'palestrante_set') and request.POST:
306         return forbidden
307
308     talk = get_object_or_404(Trabalho, pk=tid)
309     speaker = talk.palestrante
310     improve = Improve.objects.filter(trabalho=talk)
311
312     # building the form
313     form = ImproveForm(request.POST or None)
314     form.fields['trabalho'].widget = HiddenInput(attrs={'value':talk.id})
315     form.fields['usuario'].widget = HiddenInput(attrs={'value':request.user.id})
316
317     if request.POST and form.is_valid():
318         event = Evento.objects.get(site__id__exact=settings.SITE_ID)
319         # validation
320         cleaned = form.cleaned_data
321         if cleaned['trabalho'].evento.id != event.id:
322             return forbidden
323
324         instance = form.save()
325         return HttpResponseRedirect('/improve/%d/' % talk.id)
326
327     c = {'talk': talk, 'form': form, 'improve': improve,
328          'len_comments': len(improve), 'speaker': speaker}
329     return render_to_response('eventos/talk-improve.html', Context(c),
330                               context_instance=RequestContext(request))
331
332 def subscribe(request):
333     """This view shows a form with name, login and password fields and
334     if it receives a post, it will get data from the above fields and
335     create an User (yes, the django User). I think this user will be
336     used as an attendee.
337
338     This function authenticates the new user.
339     """
340     form = SubscribeForm(request.POST or None)
341
342     if request.POST and form.is_valid():
343         new_user = User.objects.create_user(request.POST['username'],
344                                             request.POST['email'],
345                                             request.POST['password'])
346         login(request)
347         return HttpResponseRedirect('/')
348
349     context = {'form': form}
350     return render_to_response('eventos/subscribe.html', Context(context),
351                               context_instance=RequestContext(request))