Project

General

Profile

Download (10.2 KB) Statistics
| Branch: | Tag: | Revision:

root / corbo / views.py @ 8e8b10ae

1
import urllib
2
import json
3

    
4
from django.conf import settings
5
from django.core import signing
6
from django.utils import timezone
7
from django.core.urlresolvers import reverse
8
from django.views.generic import CreateView, UpdateView, DeleteView, \
9
    ListView, TemplateView, RedirectView, DetailView, FormView, RedirectView
10
from django.contrib.syndication.views import Feed
11
from django.shortcuts import resolve_url
12
from django.utils.encoding import force_text
13
from django.utils.feedgenerator import Atom1Feed as DjangoAtom1Feed
14
from django.http import HttpResponseRedirect, HttpResponse, Http404
15
from django.contrib.auth import logout as auth_logout
16
from django.contrib.auth import views as auth_views
17
from django.contrib import messages
18
from django.utils.translation import ugettext_lazy as _
19
from django.utils.translation import ngettext
20

    
21
import models
22
from .forms import AnnounceForm, CategoryForm, SubscriptionsImportForm, \
23
    SendTestEmailForm, SendTestSMSForm
24
from . import utils
25

    
26
try:
27
    from mellon.utils import get_idps
28
except ImportError:
29
    get_idps = lambda: []
30

    
31

    
32
def login(request, *args, **kwargs):
33
    if any(get_idps()):
34
        if 'next' not in request.GET:
35
            return HttpResponseRedirect(resolve_url('mellon_login'))
36
        return HttpResponseRedirect(resolve_url('mellon_login') + '?next=' +
37
                                    urllib.quote(request.GET.get('next')))
38
    return auth_views.login(request, *args, **kwargs)
39

    
40

    
41
def logout(request, next_page=None):
42
    if any(get_idps()):
43
        return HttpResponseRedirect(resolve_url('mellon_logout'))
44
    auth_logout(request)
45
    if next_page is not None:
46
        next_page = resolve_url(next_page)
47
    else:
48
        next_page = '/'
49
    return HttpResponseRedirect(next_page)
50

    
51

    
52
class HomepageView(RedirectView):
53
    pattern_name = 'manage'
54

    
55

    
56
homepage = HomepageView.as_view()
57

    
58

    
59
class AnnounceCreateView(CreateView):
60

    
61
    form_class = AnnounceForm
62
    template_name = 'corbo/announce_form.html'
63

    
64
    def get_success_url(self):
65
        return reverse('view_category', kwargs={'slug': self.object.category.slug})
66

    
67
    def get_initial(self):
68
        initial = super(AnnounceCreateView, self).get_initial()
69
        initial['category'] = models.Category.objects.get(slug=self.kwargs['slug'])
70
        return initial
71

    
72
    def get_context_data(self, **kwargs):
73
        context = super(AnnounceCreateView, self).get_context_data(**kwargs)
74
        context['category'] = kwargs['form'].initial['category']
75
        return context
76

    
77

    
78
add_announce = AnnounceCreateView.as_view()
79

    
80

    
81
class AnnounceEditView(UpdateView):
82
    model = models.Announce
83
    form_class = AnnounceForm
84

    
85
    def get_context_data(self, **kwargs):
86
        context = super(AnnounceEditView, self).get_context_data(**kwargs)
87
        category_id = kwargs['form'].initial['category']
88
        context['category'] = models.Category.objects.get(pk=category_id)
89
        return context
90

    
91
    def get_success_url(self):
92
        return reverse('view_announce', kwargs={'pk': self.object.pk})
93

    
94

    
95
edit_announce = AnnounceEditView.as_view()
96

    
97

    
98
class AnnounceDeleteView(DeleteView):
99
    model = models.Announce
100

    
101
    def get_success_url(self):
102
        return reverse('view_category', kwargs={'slug': self.object.category.slug})
103

    
104

    
105
delete_announce = AnnounceDeleteView.as_view()
106

    
107

    
108
class CategoryCreateView(CreateView):
109
    form_class = CategoryForm
110
    template_name = 'corbo/category_form.html'
111

    
112
    def get_success_url(self):
113
        return reverse('manage')
114

    
115
    def form_valid(self, form):
116
        form.save()
117
        return super(CategoryCreateView, self).form_valid(form)
118

    
119

    
120
add_category = CategoryCreateView.as_view()
121

    
122

    
123
class CategoryEditView(UpdateView):
124
    form_class = CategoryForm
125
    model = models.Category
126

    
127
    def get_success_url(self):
128
        return reverse('view_category', kwargs={'slug': self.object.slug})
129

    
130

    
131
edit_category = CategoryEditView.as_view()
132

    
133

    
134
class CategoryView(ListView):
135
    model = models.Announce
136
    paginate_by = settings.ANNOUNCES_PER_PAGE
137

    
138
    def get_queryset(self):
139
        qs = super(CategoryView, self).get_queryset()
140
        return qs.filter(category__slug=self.kwargs['slug'])
141

    
142
    def get_context_data(self, **kwargs):
143
        context = super(CategoryView, self).get_context_data(**kwargs)
144
        context['category'] = models.Category.objects.get(slug=self.kwargs['slug'])
145
        return context
146

    
147

    
148
view_category = CategoryView.as_view()
149

    
150

    
151
class CategoryDeleteView(DeleteView):
152
    model = models.Category
153

    
154
    def get_success_url(self):
155
        return reverse('manage')
156

    
157

    
158
delete_category = CategoryDeleteView.as_view()
159

    
160

    
161
class UnsubscribeView(DeleteView):
162
    model = models.Subscription
163

    
164
    def get_object(self, queryset=None):
165
        data = signing.loads(self.kwargs['unsubscription_token'])
166
        try:
167
            return models.Subscription.objects.get(category__pk=data['category'],
168
                                                   identifier=data['identifier'])
169
        except models.Subscription.DoesNotExist:
170
            raise Http404
171

    
172
    def get_success_url(self):
173
        return reverse('unsubscription_done')
174

    
175

    
176
unsubscribe = UnsubscribeView.as_view()
177

    
178

    
179
class UnsubscriptionDoneView(TemplateView):
180
    template_name = 'corbo/unsubscription_done.html'
181

    
182

    
183
unsubscription_done = UnsubscriptionDoneView.as_view()
184

    
185

    
186
class ManageView(ListView):
187
    template_name = 'corbo/manage.html'
188
    model = models.Category
189
    paginate_by = settings.CATEGORIES_PER_PAGE
190

    
191
manage = ManageView.as_view()
192

    
193

    
194
class Atom1Feed(DjangoAtom1Feed):
195

    
196
    def root_attributes(self):
197
        attrs = super(Atom1Feed, self).root_attributes()
198
        attrs.update({'xml:base': self.feed['link']})
199
        return attrs
200

    
201

    
202
class AtomView(Feed):
203
    title = settings.RSS_TITLE
204
    description = settings.RSS_DESCRIPTION
205
    link = settings.RSS_LINK
206
    feed_item_link_template = settings.RSS_LINK_TEMPLATE
207
    feed_type = Atom1Feed
208

    
209
    def __init__(self, **kwargs):
210
        self.__dict__.update(kwargs)
211

    
212
    def items(self):
213
        limit = settings.RSS_ITEMS_LIMIT
214
        return models.Announce.objects.filter(publication_time__lte=timezone.now()).exclude(
215
            expiration_time__lt=timezone.now()).order_by('-publication_time')[:limit]
216

    
217
    def item_title(self, item):
218
        return item.title
219

    
220
    def item_description(self, item):
221
        return item.text
222

    
223
    def item_link(self, item):
224
        return self.feed_item_link_template.format(item.pk)
225

    
226
    def item_pubdate(self, item):
227
        return item.publication_time or item.mtime
228

    
229

    
230
atom = AtomView()
231

    
232

    
233
class SubscriptionsImportView(FormView):
234
    form_class = SubscriptionsImportForm
235
    template_name = 'corbo/subscriptions_import_form.html'
236

    
237
    def get_context_data(self, **kwargs):
238
        context = super(SubscriptionsImportView, self).get_context_data(**kwargs)
239
        context['category'] = models.Category.objects.get(slug=self.kwargs['slug'])
240
        return context
241

    
242
    def get_success_url(self):
243
        category = models.Category.objects.get(slug=self.kwargs['slug'])
244
        return reverse('view_category', kwargs={'slug': category.slug})
245

    
246
    def form_valid(self, form):
247
        new = 0
248
        c = models.Category.objects.get(slug=self.kwargs['slug'])
249
        for email in form.cleaned_data['subscribers']:
250
            obj, created = models.Subscription.objects.get_or_create(category=c, identifier='mailto:%s' % email)
251
            if created:
252
               new += 1
253
        messages.info(self.request, ngettext('%(new)d subscriber added', '%(new)d subscribers added', new) % {'new': new})
254
        return super(SubscriptionsImportView, self).form_valid(form)
255

    
256
subscriptions_import = SubscriptionsImportView.as_view()
257

    
258

    
259
class AnnounceView(DetailView):
260
    model = models.Announce
261
    template_name = 'corbo/announce_view.html'
262

    
263
    def get_context_data(self, **kwargs):
264
        context = super(AnnounceView, self).get_context_data(**kwargs)
265
        context['category'] = self.object.category
266
        context['broadcasts'] = self.object.broadcast_set.filter(deliver_time__isnull=False)
267
        context['sms_enabled'] = settings.SMS_GATEWAY_URL
268
        return context
269

    
270
view_announce = AnnounceView.as_view()
271

    
272

    
273
class SendAnnounceView(FormView):
274
    def get_initial(self):
275
        return {'email': self.request.user.email,
276
                'mobile': self.request.session.get('mellon_session', {}).get('mobile', '')}
277

    
278
    def get_success_url(self, *args, **kwargs):
279
        return reverse('view_announce', kwargs={'pk': self.kwargs['pk']})
280

    
281
    def get_context_data(self, **kwargs):
282
        context = super(SendAnnounceView, self).get_context_data(**kwargs)
283
        context['object'] = models.Announce.objects.get(pk=self.kwargs['pk'])
284
        return context
285

    
286

    
287
class EmailAnnounceView(SendAnnounceView):
288
    form_class = SendTestEmailForm
289
    template_name = 'corbo/email_test_announce_form.html'
290

    
291
    def form_valid(self, form):
292
        email = form.cleaned_data['email']
293
        announce = models.Announce.objects.get(pk=self.kwargs['pk'])
294
        utils.send_email(announce.title, announce.text, [email], announce.category.pk)
295
        messages.info(self.request, _('Email successfully sent'))
296
        return super(EmailAnnounceView, self).form_valid(form)
297

    
298
email_announce = EmailAnnounceView.as_view()
299

    
300

    
301
class SMSAnnounceView(SendAnnounceView):
302
    form_class = SendTestSMSForm
303
    template_name = 'corbo/sms_test_announce_form.html'
304

    
305
    def form_valid(self, form):
306
        mobile = form.cleaned_data['mobile']
307
        announce = models.Announce.objects.get(pk=self.kwargs['pk'])
308
        sms_sent = utils.send_sms(announce.text, [mobile])
309
        if sms_sent == 1:
310
            messages.info(self.request, _('SMS successfully sent'))
311
        else:
312
            messages.error(self.request, _('Error occured while sending SMS'))
313
        return super(SMSAnnounceView, self).form_valid(form)
314

    
315
sms_announce = SMSAnnounceView.as_view()
316

    
317

    
318
def menu_json(request):
319
    label = _('Announces')
320
    json_str = json.dumps([{'label': force_text(label),
321
                          'slug': 'announces',
322
                           'url': request.build_absolute_uri(reverse('manage'))}])
323

    
324
    for variable in ('jsonpCallback', 'callback'):
325
        if variable in request.GET:
326
            response = HttpResponse(content_type='application/javascript')
327
            json_str = '%s(%s);' % (request.GET[variable], json_str)
328
            break
329
    else:
330
        response = HttpResponse(content_type='application/json')
331
    response.write(json_str)
332
    return response
(11-11/13)