Source

django-swingcms / swingcms / mailserver / views.py

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 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
 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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import csv

from django.core.mail.message import EmailMessage, EmailMultiAlternatives
from django.db.transaction import commit_on_success
from django.views.decorators.csrf import csrf_protect
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.exceptions import ObjectDoesNotExist
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
from django.utils.safestring import mark_safe
from django.utils.html import clean_html

import settings
from custodian.code import get_user
from custodian.decorators import permission_required
from swingexceptions import SwingException, MSG_FORM_ERROR, MSG_PROHIBITED_ACTION
from custodian.models import User
from cms.code import search_content, html_to_text, strip_tags, get_template_path
from cms.models import ds, Logger, Category, LAYOUTS, Collage
from cms.views import message
from mailserver.code import request_email_subscribe_confirm, request_email_unsubscribe_confirm, get_link_to_privacy_policy
from mailserver.models import Email
from mailserver import forms, plugins



#############################################
##        EDIT SETTINGS AND BATCH          ##
#############################################


@csrf_protect
@permission_required('edit', 'mailserver')
@commit_on_success
def edit_settings(request):

    next_path = request.GET.get('next') or "/panel"
    current_path = request.get_full_path()
    user = get_user(request)

    if request.method == 'POST':

        form = forms.EditSettingsForm(data=request.POST)

        if form.is_valid():
            cd = form.cleaned_data
            for k,v in cd.items():
                ds.__setattr__(k.upper(), v)
            return HttpResponseRedirect(next_path)
    else:
        form = forms.EditSettingsForm(initial={'default_sender_email':ds.DEFAULT_SENDER_EMAIL,
                                               'default_from_email':ds.DEFAULT_FROM_EMAIL,
                                               'default_reply_to_email':ds.DEFAULT_REPLY_TO_EMAIL,
                                               'contact_email':ds.CONTACT_EMAIL,
                                               'test_emails':','.join(ds.TEST_EMAILS),

                                               'text_plain_top':ds.TEXT_PLAIN_TOP,
                                               'text_html_top':ds.TEXT_HTML_TOP,
                                               'text_plain_bottom':ds.TEXT_PLAIN_BOTTOM,
                                               'text_html_bottom':ds.TEXT_HTML_BOTTOM})
    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('mailserver settings'))
    obj_template_path = "cms/form.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


@csrf_protect
@permission_required('edit', 'mailserver')
@commit_on_success
def import_emails(request):

    next_path = request.GET.get('next') or "/panel"
    current_path = request.get_full_path()
    user = get_user(request)

    if request.method == 'POST':
        form = forms.ImportemailsForm(request.POST, request.FILES)
        if form.is_valid():
            cd = form.cleaned_data
            category_name = cd['category']
            category, created = Category.objects.get_or_create(name=category_name, scope='email')
            csv_file = cd['csv'].file
            is_subscriber = cd.get('as_subscribers', False)
            if cd['mode'] == 'replace':
                Email.objects.filter(categories=category).delete()
            reader = csv.reader(csv_file,
                                delimiter=',',
                                quotechar='"',
                                quoting=csv.QUOTE_ALL)

            # build email list, ignore errors, remove duplicates
            emails =[]
            for r in reader:
                try:
                    emails.append(r[0])
                except Exception, e:
                    if settings.VERBOSE:
                        print unicode(e)
            emails = list(set(emails))

            # insert in db
            for e in emails:
                email, created = Email.objects.get_or_create(email=e,
                                                             status='NOT CHECKED',
                                                             is_subscriber=is_subscriber)
                email.categories.add(category)

            return HttpResponseRedirect(next_path)
    else:
        form = forms.ImportemailsForm()

    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('import emails'))
    obj_template_path = "cms/form.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


@csrf_protect
@permission_required('edit', 'mailserver')
def export_emails(request):

    next_path = request.GET.get('next') or "/panel"
    current_path = request.get_full_path()
    user = get_user(request)

    if request.method == 'POST':

        form = forms.ExportemailsForm(request.POST)
        if form.is_valid():
            emails = Email.objects.all()
            category = form.cleaned_data['category']

            # only subscribers
            if category == 'subscriber':
                emails = emails.filter(is_subscriber=True)
            # only category
            elif not category == 'all':
                emails = emails.filter(categories__name=category)
            # alls
            else:
                pass

            # write csv file
            csv_file = open(form.cleaned_data['filename'], 'wb')
            writer = csv.writer(csv_file,
                                delimiter=',',
                                quotechar='"',
                                quoting=csv.QUOTE_ALL)
            for e in emails:
                writer.writerow((e,))
            csv_file.close()

            return HttpResponseRedirect(next_path)
    else:
        form = forms.ExportemailsForm()

    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('export emails'))
    obj_template_path = "cms/form.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


#############################################
##                  SEND                   ##
#############################################


@csrf_protect
@permission_required('send', 'email message')
def send_email(request, SendEmailForm=None, mode='simple'):

    next_path = request.GET.get('next') or "/panel"
    current_path = request.get_full_path()
    user = get_user(request)
    SendEmailForm = SendEmailForm or forms.FORM_FROM_MODE[mode]

    if request.method == 'POST':

        form = SendEmailForm(data=request.POST)

        if form.is_valid():

            cd = form.cleaned_data

            # build text
            text_html = cd['text']
            text_html = strip_tags(text_html, settings.PERMITTED_TAGS5)
            text_plain = html_to_text(text_html)
            text_html = clean_html(text_html)
            if cd.get('prepend_top'):
                text_plain = ds.TEXT_PLAIN_TOP + text_plain
                text_html = ds.TEXT_HTML_TOP + text_html
            if cd.get('append_bottom'):
                text_plain += ds.TEXT_PLAIN_BOTTOM
                text_html += ds.TEXT_HTML_BOTTOM

            # build to and bcc
            if cd.get('bcc') and len(cd['to']) > 1:
                to = []
                bcc = list(cd['to'])
            else:
                to = list(cd['to'])
                bcc = []
            to = list(set(to))
            bcc = list(set(bcc))
            if cd.get('add_test_emails'):
                bcc.extend(ds.TEST_EMAILS)

            # build email message
            recipient_numbers = len(to) + len(bcc)
            if not recipient_numbers:
                raise SwingException(_("Missing recipients."), level='WARNING', display=True)
            email_message = EmailMultiAlternatives(subject=cd['subject'],
                                                   body=text_plain,
                                                   from_email=cd['from_'] or ds.DEFAULT_FROM_EMAIL,
                                                   to=to,
                                                   bcc=bcc,
                                                   cc=None,
                                                   connection=None,
                                                   attachments=None,
                                                   headers={'sender':cd['sender'] or ds.DEFAULT_SENDER_EMAIL,
                                                            'reply_to':ds.DEFAULT_REPLY_TO_EMAIL})
            email_message.attach_alternative(text_html, 'text/html')
            file_ = cd.get('file')
            if file_:
                email_message.attach_file(file_)

            # send email message
            try:
                response = email_message.send()
                #delivering_time = (recipient_numbers/settings.SEND_BLOCK_SIZE + 1)*settings.SEND_PAUSE/60
                msg = _("Sended email message to %s recipients.") % recipient_numbers
                Logger.add(user, msg)
                return message(request, msg, 'INFO')
            except Exception, e:
                Logger.add(user, unicode(e))
                raise SwingException(_("Sending failed: maybe server not available."), level='WARNING', display=True)
    else:
        form = SendEmailForm()

    require_submit_confirm = True

    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('send email %s' % mode))
    obj_template_path = "cms/form.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


#############################################
##                CONTACTS                 ##
#############################################


#@csrf_protect # first generate csrf_token
def contacts(request):

    next_path = request.GET.get('next') or "/"
    current_path = request.get_full_path()
    user = get_user(request)
    language = request.LANGUAGE_CODE
    contact_email = ds.CONTACT_EMAIL

    if request.method == 'POST':

        form = forms.ContactForm(data=request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            email_message = EmailMessage(subject=u"message from %s user" % settings.DOMAIN,
                                         body=cd['text'],
                                         from_email=cd['email'],
                                         to=(contact_email,),
                                         connection=None,
                                         attachments=None,
                                         headers={},
                                         cc=None)
            # send email
            try:
                response = email_message.send()
                return message(request, _("Thank for your message."), 'INFO')
            except:
                return message(request, _("Server not available."), 'WARNING')
    else:
        form = forms.ContactForm()

    # build introduction and notes (with optional privacy policy link) messages
    privacy_policy = search_content(model_names=('article',),
                                    name='privacy policy',
                                    language=language,
                                    check_alternative=True)

    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('contacts'))
    obj_template_path = "mailserver/contacts.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


#############################################
##       SUBSCRIBE AND CONFIRM             ##
#############################################


#@csrf_protect # first generate csrf_token
@commit_on_success
def subscribe(request):

    current_path = request.get_full_path()
    user = get_user(request)

    if request.method == 'POST':

        form = forms.SubscribeAsObjForm(data=request.POST)
        if form.is_valid():

            # get data
            cd = form.cleaned_data
            raw_email = cd['email']
            categories_provided = Category.objects.filter(id__in=cd.get('categories') or (), scope='email')
            mode =  cd['mode']
            try:
                email = Email.objects.get(email=raw_email, is_subscriber=True)
            except ObjectDoesNotExist:
                email = None

            # SUBSCRIBE
            if  mode == 'subscribe':

                # insert new email and relate it to provided categories, if required confirm it
                if not email:
                    email = Email(email=raw_email, is_subscriber=True)
                    if settings.CONFIRM_SUBSCRIBE:
                        email.status = 'PENDING'
                        try:
                            request_email_subscribe_confirm(raw_email, email.token)
                            confirm_part_msg = _("Will receiv a confirmation email.")
                        except:
                            confirm_part_msg = _("Fail on sending a confirmation email: contact administrator for confirm your subscription.")
                    else:
                        confirm_part_msg = ''
                    email.save()
                    if categories_provided:
                        for c in categories_provided:
                            email.categories.add(c)
                        msg = _("Email added and inserted in %(cp)s category/ies.\n%(conf_msg)s") \
                                     % {'cp':', '.join((c.name for c in categories_provided)),
                                        'conf_msg':unicode(confirm_part_msg)}
                    else:
                        msg = _("Email added.\n%s" % unicode(confirm_part_msg))

                # insert present email in new category/ies
                elif categories_provided:

                    # defer after confirm add categories
                    if settings.CONFIRM_SUB_UNSUB_CATEGORIES:
                        try:
                            request_email_subscribe_confirm(raw_email,
                                                            email.token,
                                                            categories=categories_provided)
                            msg = _("Will receiv a confirmation email before insertion in %(cp)s category/ies.") \
                                       % {'cp':', '.join((c.name for c in categories_provided))}
                        except:
                            msg = _("Fail on sending a confirmation email before insertion in %(cp)s category/ies: contact administrator for confirm your subscription.") \
                                       % {'cp':', '.join((c.name for c in categories_provided))}

                    # insert now
                    else:
                        for c in categories_provided:
                            email.categories.add(c)
                        msg = _("Email inserted in %(cp)s category/ies.") % \
                                    {'cp':', '.join((c.name for c in categories_provided))}

                # try add new email but it is already present
                else:
                    msg = _("Email already present.")

            # UNSUBSCRIBE
            else:

                # try unsubscribe but email not exist
                if not email:
                    msg = _("Email not present.")

                # remove email from categories
                elif categories_provided:

                    # defer after confirm remove categories
                    if settings.CONFIRM_SUB_UNSUB_CATEGORIES:
                        try:
                            request_email_unsubscribe_confirm(raw_email,
                                                              email.token,
                                                              categories=categories_provided)
                            msg = _("Will receiv a confirmation email before remove from %(cp)s category/ies.") \
                                     % {'cp':', '.join((c.name for c in categories_provided))}
                        except:
                            msg = _("Fail on sending a confirmation email before remove from %(cp)s category/ies.") \
                                     % {'cp':', '.join((c.name for c in categories_provided))}

                    # remove now
                    else:
                        for c in categories_provided:
                            email.categories.remove(c)
                        msg = _("Email removed from %(cp)s category/ies.") \
                                    % {'cp':', '.join((c.name for c in categories_provided))}

                # remove email
                else:
                    if settings.CONFIRM_UNSUBSCRIBE:
                        confirmation_token = email.token
                        try:
                            request_email_unsubscribe_confirm(raw_email, confirmation_token)
                            msg = _("Will receiv a confirmation email.")
                        except Exception:
                            msg = _("Fail on sending a confirmation email: contact administrator for confirm your unsubscription.")
                    else:
                        email.delete()
                        msg = _("Email removed.")

            return message(request, msg, 'INFO')
    else:
        form = forms.SubscribeAsObjForm()

    link_to_privacy_policy = get_link_to_privacy_policy(request.LANGUAGE_CODE)

    # prepare layout
    layout = LAYOUTS['clean']
    layout.actualize(request=request,
                     user=user,
                     language=request.LANGUAGE_CODE,
                     caching=user.is_anonymous() and settings.CACHE_ACTIVE,
                     check_view_perms=True,
                     current_path=current_path,
                     here=_('subscribe'))
    obj_template_path = "mailserver/subscribe_as_obj.html"

    return render_to_response(layout.template_path, locals(), context_instance=RequestContext(request))


@commit_on_success
def confirm_email_subscribe(request, email, token, categories=None):
    """
    Test the email existence and ensure email owner
    before activating it or insert in category/ies.
    """
    categories = categories and categories.split('-')

    try:
        email = Email.objects.get(email=email, is_subscriber=True)
    except ObjectDoesNotExist:
        email = None

    if not email:
        level, msg = 'ERROR', _("This email not exist as subscriber.")

    elif categories and email.token == token:
        for c in categories:
            # maybe category deleted before inserting email
            try:
                email.categories.add(Category.objects.get(name=c, scope='email'))
            except ObjectDoesNotExist:
                pass
        # implicity confimr email
        email.status = 'CONFIRMED'
        email.save()
        level, msg = 'INFO', _("Email verified and inserted in category/ies.")

    elif email.token == token:
        email.status = 'CONFIRMED'
        email.save()
        level, msg = 'INFO', _("Your subscription is confirmed.")

    else:
        email.status = 'NOT CONFIRMED'
        email.save()
        level, msg = 'WARNNG', _("Key not matching. Email go in not confirmed status.")

    return message(request, msg, level)


@commit_on_success
def confirm_email_unsubscribe(request, email, token, categories=None):
    """
    Test the email existence and ensure email owner
    before deleting it or remove from category/ies.
    """
    categories = categories and categories.split('-')

    try:
        email = Email.objects.get(email=email, is_subscriber=True)
    except ObjectDoesNotExist:
        email = None

    if not email:
        level, msg = 'ERROR', _("This email not exist as subscriber.")

    elif categories and email.token == token:
        for c in categories:
            # maybe category deleted before removing email
            try:
                email.categories.remove(Category.objects.get(name=c, scope='email'))
            except ObjectDoesNotExist:
                pass
        level, msg = 'INFO', _("Email verified and removed from category/ies.")

    elif email.token == token:
        email.delete()
        level, msg = 'INFO', _("Email removed.")

    else:
        level, msg = 'WARNING', _("Key not matching.")

    return message(request, msg, level)


@commit_on_success
def confirm_email_user(request, username, token):
    """
    Test the email existence and ensure email owner
    before activate email and optionally user.
    """
    user = User.objects.get(username=username)

    try:
        email = Email.objects.get(user=user, is_subscriber=False)
    except ObjectDoesNotExist:
        email = None

    if not email:
        level, msg = 'ERROR', _("This email not exist.")

    elif email.status in ('PENDING','NOT CONFIRMED'):
        if email.token == token:
            email.status = 'ACTIVE'
            if settings.ACTIVE_ON_CONFIRM:
                user.is_active = True
                msg = _("Your email is confirmed and your account is now active.")
            else:
                msg = _("Your email is confirmed.")
            user.save()
        else:
            msg = _("Token not matching.")
            email.status = 'NOT CONFIRMED'
        email.save()
    else:
        msg = _("Status not supported in user's email confirmation.")

    return message(request, msg, 'INFO')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.