Fixes
[wolnelektury.git] / src / catalogue / signals.py
1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. 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 picture.models import Picture, PictureArea
11 from .models import BookMedia, Book, Collection, Fragment, Tag
12
13
14 ####
15 # BookMedia
16 ####
17
18
19 @receiver([post_save, post_delete], sender=BookMedia)
20 def bookmedia_save(sender, instance, **kwargs):
21     instance.book.set_audio_length()
22     instance.book.save()
23
24
25 ####
26 # Collection
27 ####
28
29
30 @receiver(post_save, sender=Collection)
31 def collection_save(sender, instance, **kwargs):
32     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
33
34
35 ####
36 # Book
37 ####
38
39
40 @receiver(post_save, sender=Book)
41 def book_save(sender, instance, **kwargs):
42     # Books come out anywhere.
43     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
44     # deleting selectively is too much work
45     try:
46         caches['template_fragments'].clear()
47     except ImproperlyConfigured:
48         pass
49     instance.clear_cache()
50
51
52 @receiver(post_delete, sender=Book)
53 def book_delete(sender, instance, **kwargs):
54     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
55
56     if not settings.NO_SEARCH_INDEX:
57         # remove the book from search index, when it is deleted.
58         from search.index import Index
59         idx = Index()
60         idx.remove_book(instance)
61         idx.index_tags()
62
63
64 ####
65 # Tag
66 ####
67
68
69 @receiver(Tag.after_change)
70 def tag_after_change(sender, instance, **kwargs):
71     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
72
73     for model in Book, Picture:
74         for model_instance in model.tagged.with_all([instance]).only('pk'):
75             model_instance.clear_cache()
76
77     if instance.category == 'author':
78         for model in Fragment, PictureArea:
79             for model_instance in model.tagged.with_all([instance]).only('pk'):
80                 model_instance.clear_cache()
81
82
83 @receiver(tags_updated)
84 def receive_tags_updated(sender, instance, affected_tags, **kwargs):
85     categories = set(tag.category for tag in affected_tags if tag.category not in ('set', 'book'))
86     if not categories:
87         return
88
89     caches[settings.CACHE_MIDDLEWARE_ALIAS].clear()
90     instance.clear_cache()