add signals

This commit is contained in:
bakatrouble 2019-01-30 23:52:05 +03:00
parent 56f516e25b
commit fbfe97fe5b
3 changed files with 33 additions and 2 deletions

View File

@ -1,4 +1,5 @@
from django.apps import AppConfig from django.apps import AppConfig
from django.db.models.signals import post_delete
class AggregatorConfig(AppConfig): class AggregatorConfig(AppConfig):
@ -6,9 +7,17 @@ class AggregatorConfig(AppConfig):
def ready(self): def ready(self):
self.register_config() self.register_config()
self.register_signals()
def register_config(self): def register_config(self):
import djconfig import djconfig
from .forms import AggregatorAppConfigForm from .forms import AggregatorAppConfigForm
djconfig.register(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)

View File

@ -48,8 +48,6 @@ class Chat(models.Model):
obj.photo.save(os.path.basename(path), f, save=True) obj.photo.save(os.path.basename(path), f, save=True)
obj.photo_id = chat.photo.small_file_id obj.photo_id = chat.photo.small_file_id
obj.save() obj.save()
if created:
transaction.on_commit(lambda: collect_new_messages.delay(obj.pk))
return obj return obj
def __str__(self): def __str__(self):

24
aggregator/signals.py Normal file
View File

@ -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