Find unused tags.
[wolnelektury.git] / src / catalogue / signals.py
1 # This file is part of Wolne Lektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Wolne Lektury. See NOTICE for more information.
3 #
4 from django.conf import settings
5 from django.core.cache import caches
6 from django.core.exceptions import ImproperlyConfigured
7 from django.db.models.signals import post_save, post_delete
8 from django.dispatch import receiver
9 from newtagging.models import tags_updated
10 from .models import BookMedia, Book, Collection, Fragment, Tag
11
12
13 ####
14 # BookMedia
15 ####
16
17
18 @receiver([post_save, post_delete], sender=BookMedia)
19 def bookmedia_save(sender, instance, **kwargs):
20     instance.book.set_audio_length()
21     instance.book.save()
22
23
24 ####
25 # Collection
26 ####
27
28
29 @receiver(post_save, sender=Collection)
30 def collection_save(sender, instance, **kwargs):
31     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
32
33
34 ####
35 # Book
36 ####
37
38
39 @receiver(post_save, sender=Book)
40 def book_save(sender, instance, **kwargs):
41     # Books come out anywhere.
42     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
43     # deleting selectively is too much work
44     try:
45         caches['template_fragments'].clear()
46     except ImproperlyConfigured:
47         pass
48     instance.clear_cache()
49
50
51 @receiver(post_delete, sender=Book)
52 def book_delete(sender, instance, **kwargs):
53     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
54
55
56 ####
57 # Tag
58 ####
59
60
61 @receiver(Tag.after_change)
62 def tag_after_change(sender, instance, **kwargs):
63     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
64
65     for book in Book.tagged.with_all([instance]).only('pk'):
66         book.clear_cache()
67
68
69 @receiver(tags_updated)
70 def receive_tags_updated(sender, instance, affected_tags, **kwargs):
71     categories = set(tag.category for tag in affected_tags if tag.category not in ('set', 'book'))
72     if not categories:
73         return
74
75     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
76     if sender in (Book,):
77         instance.clear_cache()