views.py 4.99 KB
Newer Older
1 2
# -*- coding: utf8 -*-

fred's avatar
fred committed
3
import email
4 5 6
import hashlib
import random
import socket
7
import urllib
jean-philippe's avatar
jean-philippe committed
8 9
import urllib2
import cookielib
10
import datetime
11

12
from django.conf import settings
13 14
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse_lazy
fred's avatar
fred committed
15
from django.db import models, IntegrityError
fred's avatar
fred committed
16
from django.http import JsonResponse
fred's avatar
fred committed
17
from django.shortcuts import get_object_or_404
18
from django.utils.translation import ugettext as _
19

fred's avatar
fred committed
20
from django.views.generic.base import TemplateView, RedirectView
21 22 23
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView, UpdateView
fred's avatar
fred committed
24 25
from django.views.decorators.csrf import csrf_exempt

26 27
from .forms import SubscribeForm, NewsletterForm
from .models import Subscriber, Newsletter
28 29


fred's avatar
fred committed
30 31 32 33 34
class SubscribeView(CreateView):
    form_class = SubscribeForm
    model = Subscriber

    success_url = 'thanks'
35
subscribe = csrf_exempt(SubscribeView.as_view())
36

37

fred's avatar
fred committed
38 39 40
class ThanksView(TemplateView):
    template_name = 'newsletter/thanks.html'
thanks = ThanksView.as_view()
41

42

fred's avatar
fred committed
43 44 45 46 47
class ConfirmationView(TemplateView):
    template_name = 'newsletter/done.html'

    def get_context_data(self, token, **kwargs):
        context = super(ConfirmationView, self).get_context_data(**kwargs)
48
        subscriber = get_object_or_404(Subscriber, password=token, is_validated=False)
fred's avatar
fred committed
49 50 51 52 53 54
        subscriber.is_validated = True
        subscriber.save()
        return context
confirmation = ConfirmationView.as_view()


jean-philippe's avatar
jean-philippe committed
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
def unsubscription(request) :
    UNSUBSCRIPTION_MESSAGE = _("Enter your email for unsunscribe to the newsletter.")
    UNSUBSCRIPTION_CONFIRMATION_MESSAGE = _("You're now unsubscribed")

    if request.method == 'GET' :
        form = SubscriptionForm()
        return render(request, 'unsubscription_form.html', {'form' : form, 'message' : UNSUBSCRIPTION_MESSAGE})
    elif request.method == 'POST' :
        form = SubscriptionForm(request.POST)
        if form.is_valid() :
            cd = form.cleaned_data
            try :
                subscriber = Subscriber.objects.get(email = cd['email'])
                
                cookie_jar = cookielib.CookieJar()
                url_opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))

                login_params = urllib.urlencode({'email' : subscriber.email, 'password' : subscriber.password})
                login_request = urllib2.Request(settings.NEWSLETTER_UNSUBSCRIPTION_URL, login_params)
                url = url_opener.open(login_request)
                
                unsubscribe_action_url = ("%s/%s" % (settings.NEWSLETTER_UNSUBSCRIPTION_URL, subscriber.email))
                unsubscribe_params = urllib.urlencode({'unsub' : 'Résilier', 'unsubconfirm' : '1'})
                unsubscribe_request = urllib2.Request(unsubscribe_action_url, unsubscribe_params)
                url = url_opener.open(unsubscribe_request)

                url.close()

                subscriber.delete()
                return render(request, 'unsubscription_form.html', {'message' : UNSUBSCRIPTION_CONFIRMATION_MESSAGE})
            except Subscriber.DoesNotExist :
                error_message = _("The entered email address does not exist. Please try another one.")
                return render(request, 'unsubscription_form.html', {'form' : form, 'message' : error_message})
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129


class NewsletterCreateView(CreateView):
    form_class = NewsletterForm
    model = Newsletter

    success_url = reverse_lazy('newsletter-list')

    def get_form(self, *args, **kwargs):
        if not self.request.user.has_perm('newsletter.add_newsletter'):
            raise PermissionDenied()
        return super(NewsletterCreateView, self).get_form(*args, **kwargs)

    def get_initial(self):
        initial = super(NewsletterCreateView, self).get_initial()
        initial['date'] = datetime.datetime.today()
        return initial

newsletter_create = NewsletterCreateView.as_view()


class NewsletterListView(ListView):
    model = Newsletter

newsletter_list = NewsletterListView.as_view()


class NewsletterDetailView(DetailView):
    model = Newsletter

newsletter_view = NewsletterDetailView.as_view()

class NewsletterUpdateView(UpdateView):
    form_class = NewsletterForm
    model = Newsletter

    def get_form(self, *args, **kwargs):
        if not self.request.user.has_perm('newsletter.add_newsletter'):
            raise PermissionDenied()
        return super(NewsletterUpdateView, self).get_form(*args, **kwargs)

newsletter_update = NewsletterUpdateView.as_view()
fred's avatar
fred committed
130 131


fred's avatar
fred committed
132
class NewsletterSendView(RedirectView):
fred's avatar
fred committed
133
    permanent = False
fred's avatar
fred committed
134 135 136 137 138 139 140 141 142 143
    def get_redirect_url(self, pk):
        if not self.request.user.has_perm('newsletter.add_newsletter'):
            raise PermissionDenied()

        newsletter = get_object_or_404(Newsletter, pk=pk)
        newsletter.send()
        return reverse_lazy('newsletter-list')

newsletter_send = NewsletterSendView.as_view()

fred's avatar
fred committed
144 145
@csrf_exempt
def stats(request) :
146
    return JsonResponse({'data': {'registered': Subscriber.objects.filter(is_registered=True).count()}})