import base64 import email from django import forms from django.contrib import admin from django.core.urlresolvers import reverse from django.db.models import Count from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from orchestra.admin.utils import admin_link, admin_colored, admin_date, wrap_admin_view from orchestra.contrib.tasks import task from .engine import send_pending from .models import Message, SMTPLog COLORS = { Message.QUEUED: 'purple', Message.SENT: 'green', Message.DEFERRED: 'darkorange', Message.FAILED: 'red', SMTPLog.SUCCESS: 'green', SMTPLog.FAILURE: 'red', } class MessageAdmin(admin.ModelAdmin): list_display = ( 'display_subject', 'colored_state', 'priority', 'to_address', 'from_address', 'created_at_delta', 'display_retries', 'last_try_delta', ) list_filter = ('state', 'priority', 'retries') list_prefetch_related = ('logs__id') search_fields = ('to_address', 'from_address', 'subject',) fieldsets = ( (None, { 'fields': ('state', 'priority', ('retries', 'last_try_delta', 'created_at_delta'), 'display_full_subject', 'display_from', 'display_to', 'display_content'), }), (_("Edit"), { 'classes': ('collapse',), 'fields': ('subject', 'from_address', 'to_address', 'content'), }), ) readonly_fields = ( 'retries', 'last_try_delta', 'created_at_delta', 'display_full_subject', 'display_to', 'display_from', 'display_content', ) date_hierarchy = 'created_at' colored_state = admin_colored('state', colors=COLORS) created_at_delta = admin_date('created_at') last_try_delta = admin_date('last_try') def display_subject(self, instance): subject = instance.subject if len(subject) > 64: return subject[:64] + '…' return subject display_subject.short_description = _("Subject") display_subject.admin_order_field = 'subject' display_subject.allow_tags = True def display_retries(self, instance): num_logs = instance.logs__count if num_logs == 1: pk = instance.logs.all()[0].id url = reverse('admin:mailer_smtplog_change', args=(pk,)) else: url = reverse('admin:mailer_smtplog_changelist') url += '?&message=%i' % instance.pk return '%d' % (url, instance.retries) display_retries.short_description = _("Retries") display_retries.admin_order_field = 'retries' display_retries.allow_tags = True def display_content(self, instance): part = email.message_from_string(instance.content) payload = part.get_payload() if isinstance(payload, list): for cpart in payload: cpayload = cpart.get_payload() if cpart.get_content_type().startswith('text/'): part = cpart payload = cpayload if cpart.get_content_type() == 'text/html': payload = '