From 23a95499b8065f49b9fe9d2ad8fe88d987a2ecd8 Mon Sep 17 00:00:00 2001 From: Luca Date: Sun, 7 May 2023 01:55:15 +0200 Subject: [PATCH] Receive incoming messages every 300 seconds --- shiftregister/app/sipgate/history.py | 55 +++++++++++++++++++ shiftregister/settings.py | 8 +++ shiftregister/team/admin.py | 6 ++ shiftregister/team/migrations/0001_initial.py | 30 ++++++++++ shiftregister/team/models.py | 11 ++++ shiftregister/team/tasks.py | 27 +++++++++ 6 files changed, 137 insertions(+) create mode 100644 shiftregister/app/sipgate/history.py create mode 100644 shiftregister/team/migrations/0001_initial.py create mode 100644 shiftregister/team/tasks.py diff --git a/shiftregister/app/sipgate/history.py b/shiftregister/app/sipgate/history.py new file mode 100644 index 0000000..46d6274 --- /dev/null +++ b/shiftregister/app/sipgate/history.py @@ -0,0 +1,55 @@ +from datetime import timezone +from django.conf import settings +import requests + + +BASE_URL = "https://api.sipgate.com/v2" + + +class SMS: + def __init__(self, item): + self.content = item["smsContent"] + self.created_at = item["created"] + self.id = item["id"] + self.sender = item["source"] + + +def list_incoming_sms(from_date=None): + if not settings.SIPGATE_INCOMING_TOKEN_ID: + raise RuntimeError("required setting SIPGATE_INCOMING_TOKEN_ID is not set") + + if not settings.SIPGATE_INCOMING_TOKEN: + raise RuntimeError("required setting SIPGATE_INCOMING_TOKEN is not set") + + limit = 10 + params = { + "directions": "INCOMING", + "limit": limit, + "types": "SMS", + } + + if from_date is not None: + params["from"] = ( + from_dt.astimezone(timezone.utc).isoformat(timespec="seconds") + "Z" + ) + + items = [] + offset = 0 + total = 10 + while offset < total: + r = requests.get( + f"{BASE_URL}/history", + auth=requests.auth.HTTPBasicAuth( + settings.SIPGATE_INCOMING_TOKEN_ID, settings.SIPGATE_INCOMING_TOKEN + ), + params=params | {"offset": offset}, + ) + r.raise_for_status() + + data = r.json() + + items += data["items"] + offset += limit + total = data["totalCount"] + + return list(map(lambda item: SMS(item), items)) diff --git a/shiftregister/settings.py b/shiftregister/settings.py index 4dfa297..b86b60b 100644 --- a/shiftregister/settings.py +++ b/shiftregister/settings.py @@ -170,6 +170,10 @@ CELERY_BEAT_SCHEDULE = { "task": "shiftregister.app.tasks.send_reminders", "schedule": float(getenv("REMINDER_SEND_INTERVAL", 300.0)), # seconds }, + "receive-messages-every-300-seconds": { + "task": "shiftregister.team.tasks.receive_messages", + "schedule": float(getenv("MESSAGE_RECEIVE_INTERVAL", 300.0)), # seconds + }, } CELERY_BEAT_SCHEDULE_FILENAME = str(BASE_DIR / "storage" / "celerybeat-schedule") @@ -193,3 +197,7 @@ SIPGATE_SMS_EXTENSION = getenv("SIPGATE_SMS_EXTENSION") SIPGATE_TOKEN_ID = getenv("SIPGATE_TOKEN_ID") SIPGATE_TOKEN = getenv("SIPGATE_TOKEN") + +SIPGATE_INCOMING_TOKEN_ID = getenv("SIPGATE_INCOMING_TOKEN_ID") + +SIPGATE_INCOMING_TOKEN = getenv("SIPGATE_INCOMING_TOKEN") diff --git a/shiftregister/team/admin.py b/shiftregister/team/admin.py index 8c38f3f..83e7dd6 100644 --- a/shiftregister/team/admin.py +++ b/shiftregister/team/admin.py @@ -1,3 +1,9 @@ from django.contrib import admin +from .models import IncomingMessage # Register your models here. + + +@admin.register(IncomingMessage) +class IncomingMessageAdmin(admin.ModelAdmin): + list_display = ("sender", "created_at") diff --git a/shiftregister/team/migrations/0001_initial.py b/shiftregister/team/migrations/0001_initial.py new file mode 100644 index 0000000..8a57e79 --- /dev/null +++ b/shiftregister/team/migrations/0001_initial.py @@ -0,0 +1,30 @@ +# Generated by Django 4.0.4 on 2023-05-06 23:27 + +from django.db import migrations, models +import phonenumber_field.modelfields + + +class Migration(migrations.Migration): + initial = True + + dependencies = [] + + operations = [ + migrations.CreateModel( + name="IncomingMessage", + fields=[ + ("id", models.IntegerField(primary_key=True, serialize=False)), + ( + "sender", + phonenumber_field.modelfields.PhoneNumberField( + max_length=128, region=None + ), + ), + ("content", models.TextField()), + ("created_at", models.DateTimeField()), + ], + options={ + "get_latest_by": "created_at", + }, + ), + ] diff --git a/shiftregister/team/models.py b/shiftregister/team/models.py index f83e695..eff69d9 100644 --- a/shiftregister/team/models.py +++ b/shiftregister/team/models.py @@ -1,4 +1,15 @@ from django.db import models +from phonenumber_field.modelfields import PhoneNumberField from shiftregister.app.models import * # Create your models here. + + +class IncomingMessage(models.Model): + class Meta: + get_latest_by = "created_at" + + id = models.IntegerField(primary_key=True) + sender = PhoneNumberField() + content = models.TextField() + created_at = models.DateTimeField() diff --git a/shiftregister/team/tasks.py b/shiftregister/team/tasks.py new file mode 100644 index 0000000..7e30a93 --- /dev/null +++ b/shiftregister/team/tasks.py @@ -0,0 +1,27 @@ +from celery import shared_task +from django.conf import settings +from shiftregister.app.sipgate.history import list_incoming_sms +from .models import IncomingMessage +import sentry_sdk + + +@shared_task +def receive_messages(): + if not settings.SIPGATE_INCOMING_TOKEN or not settings.SIPGATE_INCOMING_TOKEN_ID: + return + + try: + from_dt = IncomingMessage.objects.latest() + except IncomingMessage.DoesNotExist: + from_dt = None + + try: + for sms in list_incoming_sms(from_dt): + IncomingMessage( + id=sms.id, + sender=sms.sender, + content=sms.content, + created_at=sms.created_at, + ).save() + except Exception as e: + sentry_sdk.capture_exception(e)