2015-05-04 19:52:53 +00:00
|
|
|
from django.db import models
|
2015-06-17 10:34:14 +00:00
|
|
|
from django.utils import timezone
|
2015-05-04 19:52:53 +00:00
|
|
|
from django.utils.translation import ugettext_lazy as _
|
|
|
|
|
|
|
|
from . import settings
|
|
|
|
|
|
|
|
|
|
|
|
class Message(models.Model):
|
|
|
|
QUEUED = 'QUEUED'
|
|
|
|
SENT = 'SENT'
|
|
|
|
DEFERRED = 'DEFERRED'
|
|
|
|
FAILED = 'FAILED'
|
|
|
|
STATES = (
|
|
|
|
(QUEUED, _("Queued")),
|
|
|
|
(SENT, _("Sent")),
|
|
|
|
(DEFERRED, _("Deferred")),
|
|
|
|
(FAILED, _("Failes")),
|
|
|
|
)
|
|
|
|
|
2015-05-05 19:42:55 +00:00
|
|
|
CRITICAL = 0
|
|
|
|
HIGH = 1
|
|
|
|
NORMAL = 2
|
|
|
|
LOW = 3
|
2015-05-04 19:52:53 +00:00
|
|
|
PRIORITIES = (
|
|
|
|
(CRITICAL, _("Critical (not queued)")),
|
|
|
|
(HIGH, _("High")),
|
|
|
|
(NORMAL, _("Normal")),
|
|
|
|
(LOW, _("Low")),
|
|
|
|
)
|
|
|
|
|
|
|
|
state = models.CharField(_("State"), max_length=16, choices=STATES, default=QUEUED)
|
|
|
|
priority = models.PositiveIntegerField(_("Priority"), choices=PRIORITIES, default=NORMAL)
|
|
|
|
to_address = models.CharField(max_length=256)
|
|
|
|
from_address = models.CharField(max_length=256)
|
2015-06-17 10:34:14 +00:00
|
|
|
subject = models.TextField(_("subject"))
|
2015-05-05 19:42:55 +00:00
|
|
|
content = models.TextField(_("content"))
|
|
|
|
created_at = models.DateTimeField(_("created at"), auto_now_add=True)
|
|
|
|
retries = models.PositiveIntegerField(_("retries"), default=0)
|
|
|
|
# TODO rename to last_try
|
2015-06-17 10:34:14 +00:00
|
|
|
last_retry = models.DateTimeField(_("last try"), null=True)
|
2015-05-04 19:52:53 +00:00
|
|
|
|
2015-05-07 19:00:02 +00:00
|
|
|
def __str__(self):
|
|
|
|
return '%s to %s' % (self.subject, self.to_address)
|
|
|
|
|
2015-05-04 19:52:53 +00:00
|
|
|
def defer(self):
|
|
|
|
self.state = self.DEFERRED
|
|
|
|
# Max tries
|
|
|
|
if self.retries >= len(settings.MAILER_DEFERE_SECONDS):
|
|
|
|
self.state = self.FAILED
|
2015-06-17 10:34:14 +00:00
|
|
|
self.retries += 1
|
|
|
|
self.last_retry = timezone.now()
|
2015-05-07 14:09:37 +00:00
|
|
|
self.save(update_fields=('state', 'retries', 'last_retry'))
|
2015-05-04 19:52:53 +00:00
|
|
|
|
|
|
|
def sent(self):
|
|
|
|
self.state = self.SENT
|
2015-06-03 12:49:30 +00:00
|
|
|
self.save(update_fields=('state',))
|
2015-05-04 19:52:53 +00:00
|
|
|
|
|
|
|
def log(self, error):
|
|
|
|
result = SMTPLog.SUCCESS
|
|
|
|
if error:
|
|
|
|
result= SMTPLog.FAILURE
|
|
|
|
self.logs.create(log_message=str(error), result=result)
|
|
|
|
|
|
|
|
|
|
|
|
class SMTPLog(models.Model):
|
|
|
|
SUCCESS = 'SUCCESS'
|
|
|
|
FAILURE = 'FAILURE'
|
|
|
|
RESULTS = (
|
|
|
|
(SUCCESS, _("Success")),
|
|
|
|
(FAILURE, _("Failure")),
|
|
|
|
)
|
|
|
|
message = models.ForeignKey(Message, editable=False, related_name='logs')
|
|
|
|
result = models.CharField(max_length=16, choices=RESULTS, default=SUCCESS)
|
|
|
|
date = models.DateTimeField(auto_now_add=True)
|
|
|
|
log_message = models.TextField()
|