ee024e0e6bcb80eec7d8033546ee92b6f1e3a351
[wolnelektury.git] / src / catalogue / models / source.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.db import models
5 from django.utils.translation import gettext_lazy as _
6
7
8 class Source(models.Model):
9     """A collection of books, which might be defined before publishing them."""
10     netloc = models.CharField(_('network location'), max_length=120, primary_key=True)
11     name = models.CharField(_('name'), max_length=120, blank=True)
12
13     class Meta:
14         ordering = ('netloc',)
15         verbose_name = _('source')
16         verbose_name_plural = _('sources')
17         app_label = 'catalogue'
18
19     def __str__(self):
20         return self.netloc
21
22     def save(self, *args, **kwargs):
23         from catalogue.models import Book
24         try:
25             str(self.pk)
26             old_self = type(self).objects.get(pk=self)
27         except type(self).DoesNotExist:
28             old_name = ''
29             old_netloc = self.netloc
30         else:
31             old_name = old_self.name
32             old_netloc = old_self.netloc
33
34         ret = super(Source, self).save(*args, **kwargs)
35
36         # If something really changed here, find relevant books
37         # and invalidate their cached includes.
38         if old_name != self.name or old_netloc != self.netloc:
39             for book in Book.objects.all():
40                 source = book.get_extra_info_json().get('source_url', '')
41                 if self.netloc in source or (old_netloc != self.netloc and old_netloc in source):
42                     book.clear_cache()
43         return ret