From fbfe97fe5b828e6eba0f1c80a1c99c81181a3922 Mon Sep 17 00:00:00 2001 From: bakatrouble Date: Wed, 30 Jan 2019 23:52:05 +0300 Subject: [PATCH] add signals --- aggregator/apps.py | 9 +++++++++ aggregator/models.py | 2 -- aggregator/signals.py | 24 ++++++++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) create mode 100644 aggregator/signals.py diff --git a/aggregator/apps.py b/aggregator/apps.py index d912167..4a30c66 100644 --- a/aggregator/apps.py +++ b/aggregator/apps.py @@ -1,4 +1,5 @@ from django.apps import AppConfig +from django.db.models.signals import post_delete class AggregatorConfig(AppConfig): @@ -6,9 +7,17 @@ class AggregatorConfig(AppConfig): def ready(self): self.register_config() + self.register_signals() def register_config(self): import djconfig from .forms import AggregatorAppConfigForm djconfig.register(AggregatorAppConfigForm) + + def register_signals(self): + from .models import AggregationSource, Chat + from .signals import aggregation_source_deleted, chat_deleted + + post_delete.connect(aggregation_source_deleted, sender=AggregationSource) + post_delete.connect(chat_deleted, sender=Chat) diff --git a/aggregator/models.py b/aggregator/models.py index 9558917..bd9ee43 100644 --- a/aggregator/models.py +++ b/aggregator/models.py @@ -48,8 +48,6 @@ class Chat(models.Model): obj.photo.save(os.path.basename(path), f, save=True) obj.photo_id = chat.photo.small_file_id obj.save() - if created: - transaction.on_commit(lambda: collect_new_messages.delay(obj.pk)) return obj def __str__(self): diff --git a/aggregator/signals.py b/aggregator/signals.py new file mode 100644 index 0000000..cb93ab0 --- /dev/null +++ b/aggregator/signals.py @@ -0,0 +1,24 @@ +from django.db import transaction +from pyrogram import Error + +from .client import get_client +from .models import Chat, AggregationSource +from .tasks import collect_new_messages + + +def aggregation_source_deleted(sender, instance: AggregationSource, **kwargs): + if not AggregationSource.objects.filter(chat_id=instance.chat_id): + Chat.objects.filter(chat_id=instance.chat_id).delete() + + +def chat_created(sender, instance: Chat, created, **kwargs): + if created: + transaction.on_commit(lambda: collect_new_messages.delay(instance.pk)) + + +def chat_deleted(sender, instance: Chat, **kwargs): + with get_client() as client: + try: + client.leave_chat(instance.chat_id) + except Error: + pass