+ new_fragment.tags = set(book_tags + themes + [book_tag] + ancestor_tags)
+
+ if not book.parent:
+ book.build_epub(remove_descendants=False)
+
+ book_descendants = list(book.children.all())
+ # add l-tag to descendants and their fragments
+ # delete unnecessary EPUB files
+ while len(book_descendants) > 0:
+ child_book = book_descendants.pop(0)
+ child_book.tags = list(child_book.tags) + [book_tag]
+ if child_book.has_epub_file():
+ child_book.epub_file.delete()
+ child_book.save()
+ for fragment in child_book.fragments.all():
+ fragment.tags = set(list(fragment.tags) + [book_tag])
+ book_descendants += list(child_book.children.all())
+
+ # refresh cache
+ book.reset_tag_counter()
+ book.reset_theme_counter()
+
+ book.save()
+ return book
+
+
+ def refresh_tag_counter(self):
+ tags = {}
+ for child in self.children.all().order_by():
+ for tag_pk, value in child.tag_counter.iteritems():
+ tags[tag_pk] = tags.get(tag_pk, 0) + value
+ for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
+ tags[tag.pk] = 1
+ self.set__tag_counter_value(tags)
+ self.save(reset_short_html=False, refresh_mp3=False)
+ return tags
+
+ def reset_tag_counter(self):
+ self._tag_counter = None
+ self.save(reset_short_html=False, refresh_mp3=False)
+ if self.parent:
+ self.parent.reset_tag_counter()
+
+ @property
+ def tag_counter(self):
+ if self._tag_counter is None:
+ return self.refresh_tag_counter()
+ return dict((int(k), v) for k, v in self.get__tag_counter_value().iteritems())
+
+ def refresh_theme_counter(self):
+ tags = {}
+ for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
+ for tag in fragment.tags.filter(category='theme').order_by():
+ tags[tag.pk] = tags.get(tag.pk, 0) + 1
+ self.set__theme_counter_value(tags)
+ self.save(reset_short_html=False, refresh_mp3=False)
+ return tags
+
+ def reset_theme_counter(self):
+ self._theme_counter = None
+ self.save(reset_short_html=False, refresh_mp3=False)
+ if self.parent:
+ self.parent.reset_theme_counter()
+
+ @property
+ def theme_counter(self):
+ if self._theme_counter is None:
+ return self.refresh_theme_counter()
+ return dict((int(k), v) for k, v in self.get__theme_counter_value().iteritems())