-# Create your views here.
+# -*- coding: utf-8 -*-
+# Copyright (C) 2008 Lincoln de Sousa <lincoln@minaslivre.org>
+#
+# This program is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of the
+# License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful,
+# but WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public
+# License along with this program; if not, write to the
+# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
+# Boston, MA 02111-1307, USA.
+from django.conf import settings
+from django.http import HttpResponseRedirect, HttpResponseForbidden
+from django.contrib.auth import authenticate, login as login_django, \
+ logout as logout_django
+from django.contrib.auth.models import User, Group
+from django.forms import HiddenInput, ModelForm
+from django import forms
+from django.shortcuts import render_to_response, get_object_or_404
+from django.template import RequestContext, Context, loader
+from eventos.models import Palestrante, Trabalho, TipoTrabalho, Trilha, Evento, Improve
+from eventos.forms import RegisterSpeaker
+from django.db.models import Q
+import smtplib
+
+forbidden = \
+ HttpResponseForbidden('<h2>You are not allowed to do this action.<h2>')
+
+class SpeakerForm(ModelForm):
+ class Meta:
+ model = Palestrante
+ exclude = ('usuario',)
+
+class TalkForm(ModelForm):
+ class Meta:
+ model = Trabalho
+
+class ImproveForm(ModelForm):
+ class Meta:
+ model = Improve
+
+class SubscribeForm(forms.Form):
+ full_name = forms.CharField(label=u'Nome completo', max_length=255)
+ email = forms.EmailField()
+ username = forms.CharField(max_length=255)
+ password = forms.CharField(label=u'Senha',
+ max_length=255,
+ widget=forms.PasswordInput)
+ confirm_password = forms.CharField(label=u'Confirmar senha',
+ max_length=255,
+ widget=forms.PasswordInput)
+
+ def clean_username(self):
+ data = self.cleaned_data['username']
+ if User.objects.filter(username=data):
+ raise forms.ValidationError(u'O usuário "%s" já existe' % data)
+ return data
+
+ def clean_confirm_password(self):
+ passwd = self.cleaned_data['password']
+ conf_passwd = self.cleaned_data['confirm_password']
+ if passwd != conf_passwd:
+ raise forms.ValidationError(u'A confirmação difere da senha')
+ return conf_passwd
+
+def login(request):
+ """This is a function that will be used as a front-end to the
+ django's login system. It receives username and password fields
+ from a POST request and tries to login the user.
+
+ If login is successful, user will be redirected to the referer
+ address, otherwise will be redirected to /?login_failed.
+ """
+ username = request.POST['username']
+ password = request.POST['password']
+
+ user = authenticate(username=username, password=password)
+
+ if user is not None:
+ if user.is_active:
+ login_django(request, user)
+ try:
+ request.session.delete_test_cookie()
+ except KeyError:
+ pass
+ return HttpResponseRedirect('/')
+ else:
+ return HttpResponseRedirect('/?login_failed')
+ else:
+ return HttpResponseRedirect('/?login_failed')
+
+ request.session.set_test_cookie()
+ return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
+
+def logout(request):
+ """Simple front-end to django's logout stuff. This function should
+ be mapped to an url and simply called without any parameter.
+ """
+ logout_django(request)
+ return HttpResponseRedirect('/')
+
+def speaker_add(request):
+ """Adds a new speaker to the system.
+ """
+ uform = RegisterSpeaker(request.POST or None)
+
+ form = SpeakerForm(request.POST or None)
+
+ if request.POST and form.is_valid() and uform.is_valid():
+ cd = uform.cleaned_data
+ group = Group.objects.get_or_create(name='palestrantes')[0]
+
+ # creating the user that will be set as the user of the
+ # speaker.
+ user = User(username=cd['username'])
+ user.set_password(cd['password1'])
+ user.is_active = True
+ user.save()
+ user.groups.add(group)
+
+ # this commit=False is to avoid IntegritErrors, because at
+ # this point, the speaker doesn't have an user associated
+ # with it.
+ instance = form.save(commit=False)
+ instance.usuario = user
+ instance.save()
+ return HttpResponseRedirect('/')
+
+ c = {'form': form, 'uform': uform}
+ return render_to_response('eventos/speaker-add.html', Context(c),
+ context_instance=RequestContext(request))
+
+def speaker_details(request, lid):
+ """Shows a simple form containing all editable fields of a
+ speaker and gives the speaker the possibility to save them =)
+ """
+ speaker = get_object_or_404(Palestrante, pk=lid)
+ d = {'speaker' : speaker}
+ if not hasattr(request.user, 'palestrante_set'):
+ return render_to_response('eventos/speaker-view.html', Context(d),
+ context_instance=RequestContext(request))
+
+ entity = request.user.palestrante_set.get()
+ if entity.id != int(lid):
+ return render_to_response('eventos/speaker-view.html', Context(d),
+ context_instance=RequestContext(request))
+
+ form = SpeakerForm(request.POST or None, instance=entity)
+
+ if request.POST and form.is_valid():
+ form.save()
+
+ c = {'form': form}
+ return render_to_response('eventos/speaker-details.html', Context(c),
+ context_instance=RequestContext(request))
+
+def speaker_talks(request, lid):
+ """Lists all talks of a speaker (based on speaker id -- lid
+ parameter).
+ """
+ if not hasattr(request.user, 'palestrante_set'):
+ return forbidden
+
+ entity = request.user.palestrante_set.get()
+ if entity.id != int(lid):
+ return forbidden
+
+ talks = Trabalho.objects.filter(
+ Q(palestrante=entity) | Q(outros_palestrantes=entity) )
+
+ c = {'speaker': entity, 'talks': talks}
+ return render_to_response('eventos/talk-list.html', Context(c),
+ context_instance=RequestContext(request))
+
+def talk_details(request, tid):
+ """Shows a form to edit a talk
+ """
+ # If the user is not a speaker we should not try to show anything.
+ if not hasattr(request.user, 'palestrante_set'):
+ return forbidden
+
+ # Selected in settings.py (SITE_ID) variable, because an event can
+ # be linked with only one site.
+ event = Evento.objects.get(site__id__exact=settings.SITE_ID)
+
+ # building the form
+ entity = get_object_or_404(Trabalho, pk=tid)
+ form = TalkForm(request.POST or None, instance=entity)
+
+ # These fields should not be shown to the user.
+ form.fields['palestrante'].widget = HiddenInput()
+ form.fields['evento'].widget = HiddenInput()
+
+ # These fields are event specific
+ trilhas = Trilha.objects.filter(evento=event)
+ form.fields['trilha']._set_queryset(trilhas)
+
+ tipos = TipoTrabalho.objects.filter(evento=event)
+ form.fields['tipo']._set_queryset(tipos)
+
+ # hidding the owner in the other speakers list
+ other = Palestrante.objects.exclude(pk=entity.id)
+ form.fields['outros_palestrantes']._set_queryset(other)
+ if other.count() == 0:
+ # I need set the value to '', otherwise the wise django
+ # newforms will fill the field with the invalid string '[]'
+ form.fields['outros_palestrantes'].initial = ''
+ form.fields['outros_palestrantes'].widget = HiddenInput()
+
+ # avoiding smart people trying to se talks of other speakers.
+ speaker = request.user.palestrante_set.get()
+ if speaker.id != entity.palestrante.id \
+ and speaker not in entity.outros_palestrantes.all():
+ return forbidden
+
+ if request.POST and form.is_valid():
+ form.save()
+
+ c = {'form': form}
+ return render_to_response('eventos/talk-details.html', Context(c),
+ context_instance=RequestContext(request))
+
+def talk_delete(request, tid):
+ """Drops a talk but only if the logged in user is its owner.
+ """
+ if not hasattr(request.user, 'palestrante_set'):
+ return forbidden
+
+ entity = request.user.palestrante_set.get()
+ talk = Trabalho.objects.filter(pk=tid, palestrante=entity)
+ if not talk:
+ return forbidden
+
+ talk.delete()
+ return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
+
+def talk_add(request):
+ """Shows a form to the speaker send a talk
+ """
+ if not hasattr(request.user, 'palestrante_set'):
+ return forbidden
+
+ # building the form
+ form = TalkForm(request.POST or None)
+
+ # These fields should not be shown to the user.
+
+ # Selected in settings.py (SITE_ID) variable, because an event can
+ # be linked with only one site.
+ entity = request.user.palestrante_set.get()
+ form.fields['palestrante'].widget = HiddenInput(attrs={'value' : entity.id})
+
+ event = Evento.objects.get(site__id__exact=settings.SITE_ID)
+ form.fields['evento'].widget = HiddenInput(attrs={'value' : event.id})
+
+ # These fields are event specific
+ trilhas = Trilha.objects.filter(evento=event)
+ form.fields['trilha']._set_queryset(trilhas)
+
+ tipos = TipoTrabalho.objects.filter(evento=event)
+ form.fields['tipo']._set_queryset(tipos)
+
+ # hidding the owner in the other speakers list
+ other = Palestrante.objects.exclude(pk=entity.id)
+ form.fields['outros_palestrantes']._set_queryset(other)
+ if other.count() == 0:
+ form.fields['outros_palestrantes'].widget = HiddenInput()
+
+ if request.POST and form.is_valid():
+ # validation
+ cleaned = form.cleaned_data
+ if cleaned['tipo'].evento.id != event.id:
+ return forbidden
+
+ if cleaned['trilha'].evento.id != event.id:
+ return forbidden
+
+ instance = form.save()
+ return HttpResponseRedirect('/speaker/%d/talks/' % entity.id)
+
+ c = {'form': form}
+ return render_to_response('eventos/talk-add.html', Context(c),
+ context_instance=RequestContext(request))
+
+def list_all_talks(request):
+ event = Evento.objects.get(site__id__exact=settings.SITE_ID)
+ trilhas = Trilha.objects.filter(evento=event)
+
+ improve = []
+ for t in trilhas:
+ talks = Trabalho.objects.filter(trilha=t)
+ aux = {'trilha':t.nome, 'talks':talks}
+ improve.append(aux)
+
+ c = {'improve': improve,}
+ return render_to_response('eventos/improve.html', Context(c),
+ context_instance=RequestContext(request))
+
+def talk_improve(request, tid):
+ if not hasattr(request.user, 'palestrante_set') and request.POST:
+ return forbidden
+
+ talk = get_object_or_404(Trabalho, pk=tid)
+ speakers = [i for i in talk.outros_palestrantes.all()]
+ speakers = [ talk.palestrante ] + speakers
+ improve = Improve.objects.filter(trabalho=talk)
+
+ # building the form
+ form = ImproveForm(request.POST or None)
+ form.fields['trabalho'].widget = HiddenInput(attrs={'value':talk.id})
+ form.fields['usuario'].widget = HiddenInput(attrs={'value':request.user.id})
+
+ if request.POST and form.is_valid():
+ event = Evento.objects.get(site__id__exact=settings.SITE_ID)
+ # validation
+ cleaned = form.cleaned_data
+ if cleaned['trabalho'].evento.id != event.id:
+ return forbidden
+
+ emails = [i.email for i in speakers]
+ user = cleaned['usuario'].get_full_name()
+ comments = cleaned['comentario']
+ msg = (u"From: emsl@minaslivre.org\r\nTo: %s\r\n"
+ u"Subject: Comentário em seu Trabalho EMSL 2008\r\n"
+ u"Content-Type: text/plain; charset=utf-8\r\n"
+ u"\r\n %s comentou seu trabalho.\r\n%s\r\r\n"
+ % (", ".join(emails), user, comments))
+ smtp = smtplib.SMTP("localhost")
+ smtp.sendmail("emsl@minaslivre.org", emails, str(msg.encode("utf8")))
+ smtp.quit()
+
+ instance = form.save()
+ return HttpResponseRedirect('/improve/%d/' % talk.id)
+
+ c = {'talk': talk, 'form': form, 'improve': improve,
+ 'len_comments': len(improve), 'speaker': speaker}
+ return render_to_response('eventos/talk-improve.html', Context(c),
+ context_instance=RequestContext(request))
+
+def subscribe(request):
+ """This view shows a form with name, login and password fields and
+ if it receives a post, it will get data from the above fields and
+ create an User (yes, the django User). I think this user will be
+ used as an attendee.
+
+ This function authenticates the new user.
+ """
+ form = SubscribeForm(request.POST or None)
+
+ if request.POST and form.is_valid():
+ new_user = User.objects.create_user(request.POST['username'],
+ request.POST['email'],
+ request.POST['password'])
+ login(request)
+ return HttpResponseRedirect('/')
+
+ context = {'form': form}
+ return render_to_response('eventos/subscribe.html', Context(context),
+ context_instance=RequestContext(request))