add message send tasks and respect dynamic send setting
This commit is contained in:
parent
899367e6a3
commit
c6abe5911e
|
@ -0,0 +1,18 @@
|
|||
# Generated by Django 4.0.4 on 2022-04-27 16:47
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
("app", "0001_initial"),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AddField(
|
||||
model_name="message",
|
||||
name="sent_at",
|
||||
field=models.DateTimeField(null=True),
|
||||
),
|
||||
]
|
|
@ -103,6 +103,7 @@ class Message(models.Model):
|
|||
text = models.CharField(max_length=160)
|
||||
to = models.ForeignKey(Helper, on_delete=models.CASCADE)
|
||||
created_at = models.DateTimeField(auto_now_add=True)
|
||||
sent_at = models.DateTimeField(null=True)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.to.name}({self.created_at}): {self.text}"
|
||||
|
@ -127,6 +128,10 @@ class LoginToken(models.Model):
|
|||
msg.save()
|
||||
self.sent_at = timezone.now()
|
||||
self.save()
|
||||
# import here to break import cycle
|
||||
from .tasks import send_message
|
||||
|
||||
send_message.apply_async((msg.pk,))
|
||||
|
||||
def get_absolute_url(self):
|
||||
return reverse("token_login", kwargs={"token": self.id})
|
||||
|
|
|
@ -1,6 +1,38 @@
|
|||
from celery import shared_task
|
||||
from .models import Message
|
||||
from django.db import transaction
|
||||
from django.utils import timezone
|
||||
from dynamic_preferences.registries import global_preferences_registry
|
||||
|
||||
global_preferences = global_preferences_registry.manager()
|
||||
|
||||
# cron task to send normal messages(reminders,changes) in batches
|
||||
@shared_task
|
||||
def test():
|
||||
return "Hello, Celery!"
|
||||
def send_messages():
|
||||
if not global_preferences["helper__send_sms"]:
|
||||
print("sms disabled, not sending")
|
||||
return
|
||||
with transaction.atomic():
|
||||
for msg in Message.objects.select_for_update().filter(sent_at__isnull=True):
|
||||
if msg.sent_at:
|
||||
continue
|
||||
print(f"TODO: send message @{msg.to.phone} {msg.text}")
|
||||
msg.sent_at = timezone.now()
|
||||
msg.save()
|
||||
|
||||
|
||||
# singlemessage so registration links arrive faster.
|
||||
# will silently fail when messages are disabled.
|
||||
# those messages will be picked up by the cron send later
|
||||
# once we have decided to continue sending messages
|
||||
@shared_task
|
||||
def send_message(msgid):
|
||||
if not global_preferences["helper__send_sms"]:
|
||||
return
|
||||
with transaction.atomic():
|
||||
msg = Message.objects.select_for_update().get(pk=msgid)
|
||||
if msg.sent_at:
|
||||
return
|
||||
print(f"TODO: send message @{msg.to.phone} {msg.text}")
|
||||
msg.sent_at = timezone.now()
|
||||
msg.save()
|
||||
|
|
Loading…
Reference in New Issue