1 # -*- coding: utf-8 -*-
 
   2 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
 
   3 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
 
   5 from collections import namedtuple
 
   7 from django.db import models
 
   8 from django.db.models import permalink, Q
 
  10 from django.core.cache import cache
 
  11 from django.core.files.storage import DefaultStorage
 
  12 from django.utils.translation import ugettext_lazy as _
 
  13 from django.contrib.auth.models import User
 
  14 from django.template.loader import render_to_string
 
  15 from django.utils.datastructures import SortedDict
 
  16 from django.utils.safestring import mark_safe
 
  17 from django.utils.translation import get_language
 
  18 from django.core.urlresolvers import reverse
 
  19 from django.db.models.signals import post_save, m2m_changed, pre_delete
 
  21 from django.conf import settings
 
  23 from newtagging.models import TagBase, tags_updated
 
  24 from newtagging import managers
 
  25 from catalogue.fields import JSONField, OverwritingFileField
 
  26 from catalogue.utils import create_zip, split_tags
 
  27 from catalogue.tasks import touch_tag, index_book
 
  28 from shutil import copy
 
  36 # Those are hard-coded here so that makemessages sees them.
 
  38     ('author', _('author')),
 
  39     ('epoch', _('epoch')),
 
  41     ('genre', _('genre')),
 
  42     ('theme', _('theme')),
 
  47 # not quite, but Django wants you to set a timeout
 
  48 CACHE_FOREVER = 2419200  # 28 days
 
  51 class TagSubcategoryManager(models.Manager):
 
  52     def __init__(self, subcategory):
 
  53         super(TagSubcategoryManager, self).__init__()
 
  54         self.subcategory = subcategory
 
  56     def get_query_set(self):
 
  57         return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
 
  61     name = models.CharField(_('name'), max_length=50, db_index=True)
 
  62     slug = models.SlugField(_('slug'), max_length=120, db_index=True)
 
  63     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True)
 
  64     category = models.CharField(_('category'), max_length=50, blank=False, null=False,
 
  65         db_index=True, choices=TAG_CATEGORIES)
 
  66     description = models.TextField(_('description'), blank=True)
 
  68     user = models.ForeignKey(User, blank=True, null=True)
 
  69     book_count = models.IntegerField(_('book count'), blank=True, null=True)
 
  70     gazeta_link = models.CharField(blank=True, max_length=240)
 
  71     wiki_link = models.CharField(blank=True, max_length=240)
 
  73     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
 
  74     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
 
  76     class UrlDeprecationWarning(DeprecationWarning):
 
  87     categories_dict = dict((item[::-1] for item in categories_rev.iteritems()))
 
  90         ordering = ('sort_key',)
 
  91         verbose_name = _('tag')
 
  92         verbose_name_plural = _('tags')
 
  93         unique_together = (("slug", "category"),)
 
  95     def __unicode__(self):
 
  99         return "Tag(slug=%r)" % self.slug
 
 102     def get_absolute_url(self):
 
 103         return ('catalogue.views.tagged_object_list', [self.url_chunk])
 
 105     def has_description(self):
 
 106         return len(self.description) > 0
 
 107     has_description.short_description = _('description')
 
 108     has_description.boolean = True
 
 111         """Returns global book count for book tags, fragment count for themes."""
 
 113         if self.category == 'book':
 
 115             objects = Book.objects.none()
 
 116         elif self.category == 'theme':
 
 117             objects = Fragment.tagged.with_all((self,))
 
 119             objects = Book.tagged.with_all((self,)).order_by()
 
 120             if self.category != 'set':
 
 121                 # eliminate descendants
 
 122                 l_tags = Tag.objects.filter(slug__in=[book.book_tag_slug() for book in objects])
 
 123                 descendants_keys = [book.pk for book in Book.tagged.with_any(l_tags)]
 
 125                     objects = objects.exclude(pk__in=descendants_keys)
 
 126         return objects.count()
 
 129     def get_tag_list(tags):
 
 130         if isinstance(tags, basestring):
 
 135             tags_splitted = tags.split('/')
 
 136             for name in tags_splitted:
 
 138                     real_tags.append(Tag.objects.get(slug=name, category=category))
 
 140                 elif name in Tag.categories_rev:
 
 141                     category = Tag.categories_rev[name]
 
 144                         real_tags.append(Tag.objects.exclude(category='book').get(slug=name))
 
 146                     except Tag.MultipleObjectsReturned, e:
 
 147                         ambiguous_slugs.append(name)
 
 150                 # something strange left off
 
 151                 raise Tag.DoesNotExist()
 
 153                 # some tags should be qualified
 
 154                 e = Tag.MultipleObjectsReturned()
 
 156                 e.ambiguous_slugs = ambiguous_slugs
 
 159                 e = Tag.UrlDeprecationWarning()
 
 164             return TagBase.get_tag_list(tags)
 
 168         return '/'.join((Tag.categories_dict[self.category], self.slug))
 
 171     def tags_from_info(info):
 
 172         from slughifi import slughifi
 
 173         from sortify import sortify
 
 175         categories = (('kinds', 'kind'), ('genres', 'genre'), ('authors', 'author'), ('epochs', 'epoch'))
 
 176         for field_name, category in categories:
 
 178                 tag_names = getattr(info, field_name)
 
 181                     tag_names = [getattr(info, category)]
 
 183                     # For instance, Pictures do not have 'genre' field.
 
 185             for tag_name in tag_names:
 
 186                 tag_sort_key = tag_name
 
 187                 if category == 'author':
 
 188                     tag_sort_key = tag_name.last_name
 
 189                     tag_name = tag_name.readable()
 
 190                 tag, created = Tag.objects.get_or_create(slug=slughifi(tag_name), category=category)
 
 193                     tag.sort_key = sortify(tag_sort_key.lower())
 
 195                 meta_tags.append(tag)
 
 200 def get_dynamic_path(media, filename, ext=None, maxlen=100):
 
 201     from slughifi import slughifi
 
 203     # how to put related book's slug here?
 
 206         ext = media.formats[media.type].ext
 
 207     if media is None or not media.name:
 
 208         name = slughifi(filename.split(".")[0])
 
 210         name = slughifi(media.name)
 
 211     return 'book/%s/%s.%s' % (ext, name[:maxlen-len('book/%s/.%s' % (ext, ext))-4], ext)
 
 214 # TODO: why is this hard-coded ?
 
 215 def book_upload_path(ext=None, maxlen=100):
 
 216     return lambda *args: get_dynamic_path(*args, ext=ext, maxlen=maxlen)
 
 219 def get_customized_pdf_path(book, customizations):
 
 221     Returns a MEDIA_ROOT relative path for a customized pdf. The name will contain a hash of customization options.
 
 223     customizations.sort()
 
 224     h = hash(tuple(customizations))
 
 226     pdf_name = '%s-custom-%s' % (book.slug, h)
 
 227     pdf_file = get_dynamic_path(None, pdf_name, ext='pdf')
 
 232 def get_existing_customized_pdf(book):
 
 234     Returns a list of paths to generated customized pdf of a book
 
 236     pdf_glob = '%s-custom-' % (book.slug,)
 
 237     pdf_glob = get_dynamic_path(None, pdf_glob, ext='pdf')
 
 238     pdf_glob = re.sub(r"[.]([a-z0-9]+)$", "*.\\1", pdf_glob)
 
 239     return glob(path.join(settings.MEDIA_ROOT, pdf_glob))
 
 242 class BookMedia(models.Model):
 
 243     FileFormat = namedtuple("FileFormat", "name ext")
 
 244     formats = SortedDict([
 
 245         ('mp3', FileFormat(name='MP3', ext='mp3')),
 
 246         ('ogg', FileFormat(name='Ogg Vorbis', ext='ogg')),
 
 247         ('daisy', FileFormat(name='DAISY', ext='daisy.zip')),
 
 249     format_choices = [(k, _('%s file') % t.name)
 
 250             for k, t in formats.items()]
 
 252     type        = models.CharField(_('type'), choices=format_choices, max_length="100")
 
 253     name        = models.CharField(_('name'), max_length="100")
 
 254     file        = OverwritingFileField(_('file'), upload_to=book_upload_path())
 
 255     uploaded_at = models.DateTimeField(_('creation date'), auto_now_add=True, editable=False)
 
 256     extra_info  = JSONField(_('extra information'), default='{}', editable=False)
 
 257     book = models.ForeignKey('Book', related_name='media')
 
 258     source_sha1 = models.CharField(null=True, blank=True, max_length=40, editable=False)
 
 260     def __unicode__(self):
 
 261         return "%s (%s)" % (self.name, self.file.name.split("/")[-1])
 
 264         ordering            = ('type', 'name')
 
 265         verbose_name        = _('book media')
 
 266         verbose_name_plural = _('book media')
 
 268     def save(self, *args, **kwargs):
 
 269         from slughifi import slughifi
 
 270         from catalogue.utils import ExistingFile, remove_zip
 
 273             old = BookMedia.objects.get(pk=self.pk)
 
 274         except BookMedia.DoesNotExist, e:
 
 277             # if name changed, change the file name, too
 
 278             if slughifi(self.name) != slughifi(old.name):
 
 279                 self.file.save(None, ExistingFile(self.file.path), save=False, leave=True)
 
 281         super(BookMedia, self).save(*args, **kwargs)
 
 283         # remove the zip package for book with modified media
 
 285             remove_zip("%s_%s" % (old.book.slug, old.type))
 
 286         remove_zip("%s_%s" % (self.book.slug, self.type))
 
 288         extra_info = self.get_extra_info_value()
 
 289         extra_info.update(self.read_meta())
 
 290         self.set_extra_info_value(extra_info)
 
 291         self.source_sha1 = self.read_source_sha1(self.file.path, self.type)
 
 292         return super(BookMedia, self).save(*args, **kwargs)
 
 296             Reads some metadata from the audiobook.
 
 299         from mutagen import id3
 
 301         artist_name = director_name = project = funded_by = ''
 
 302         if self.type == 'mp3':
 
 304                 audio = id3.ID3(self.file.path)
 
 305                 artist_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE1'))
 
 306                 director_name = ', '.join(', '.join(tag.text) for tag in audio.getall('TPE3'))
 
 307                 project = ", ".join([t.data for t in audio.getall('PRIV') 
 
 308                         if t.owner=='wolnelektury.pl?project'])
 
 309                 funded_by = ", ".join([t.data for t in audio.getall('PRIV') 
 
 310                         if t.owner=='wolnelektury.pl?funded_by'])
 
 313         elif self.type == 'ogg':
 
 315                 audio = mutagen.File(self.file.path)
 
 316                 artist_name = ', '.join(audio.get('artist', []))
 
 317                 director_name = ', '.join(audio.get('conductor', []))
 
 318                 project = ", ".join(audio.get('project', []))
 
 319                 funded_by = ", ".join(audio.get('funded_by', []))
 
 324         return {'artist_name': artist_name, 'director_name': director_name,
 
 325                 'project': project, 'funded_by': funded_by}
 
 328     def read_source_sha1(filepath, filetype):
 
 330             Reads source file SHA1 from audiobok metadata.
 
 333         from mutagen import id3
 
 335         if filetype == 'mp3':
 
 337                 audio = id3.ID3(filepath)
 
 338                 return [t.data for t in audio.getall('PRIV') 
 
 339                         if t.owner=='wolnelektury.pl?flac_sha1'][0]
 
 342         elif filetype == 'ogg':
 
 344                 audio = mutagen.File(filepath)
 
 345                 return audio.get('flac_sha1', [None])[0] 
 
 352 class Book(models.Model):
 
 353     title         = models.CharField(_('title'), max_length=120)
 
 354     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
 
 355     slug = models.SlugField(_('slug'), max_length=120, db_index=True,
 
 357     common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
 
 358     language = models.CharField(_('language code'), max_length=3, db_index=True,
 
 359                     default=settings.CATALOGUE_DEFAULT_LANGUAGE)
 
 360     description   = models.TextField(_('description'), blank=True)
 
 361     created_at    = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
 
 362     changed_at    = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
 
 363     parent_number = models.IntegerField(_('parent number'), default=0)
 
 364     extra_info    = JSONField(_('extra information'), default='{}')
 
 365     gazeta_link   = models.CharField(blank=True, max_length=240)
 
 366     wiki_link     = models.CharField(blank=True, max_length=240)
 
 367     # files generated during publication
 
 369     cover = models.FileField(_('cover'), upload_to=book_upload_path('png'),
 
 370                 null=True, blank=True)
 
 371     ebook_formats = ['pdf', 'epub', 'mobi', 'txt']
 
 372     formats = ebook_formats + ['html', 'xml']
 
 374     parent        = models.ForeignKey('self', blank=True, null=True, related_name='children')
 
 375     objects  = models.Manager()
 
 376     tagged   = managers.ModelTaggedItemManager(Tag)
 
 377     tags     = managers.TagDescriptor(Tag)
 
 379     html_built = django.dispatch.Signal()
 
 380     published = django.dispatch.Signal()
 
 382     class AlreadyExists(Exception):
 
 386         ordering = ('sort_key',)
 
 387         verbose_name = _('book')
 
 388         verbose_name_plural = _('books')
 
 390     def __unicode__(self):
 
 393     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
 
 394         from sortify import sortify
 
 396         self.sort_key = sortify(self.title)
 
 398         ret = super(Book, self).save(force_insert, force_update)
 
 401             self.reset_short_html()
 
 406     def get_absolute_url(self):
 
 407         return ('catalogue.views.book_detail', [self.slug])
 
 413     def book_tag_slug(self):
 
 414         return ('l-' + self.slug)[:120]
 
 417         slug = self.book_tag_slug()
 
 418         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
 
 420             book_tag.name = self.title[:50]
 
 421             book_tag.sort_key = self.title.lower()
 
 425     def has_media(self, type):
 
 426         if type in Book.formats:
 
 427             return bool(getattr(self, "%s_file" % type))
 
 429             return self.media.filter(type=type).exists()
 
 431     def get_media(self, type):
 
 432         if self.has_media(type):
 
 433             if type in Book.formats:
 
 434                 return getattr(self, "%s_file" % type)
 
 436                 return self.media.filter(type=type)
 
 441         return self.get_media("mp3")
 
 443         return self.get_media("odt")
 
 445         return self.get_media("ogg")
 
 447         return self.get_media("daisy")                       
 
 449     def reset_short_html(self):
 
 453         cache_key = "Book.short_html/%d/%s"
 
 454         for lang, langname in settings.LANGUAGES:
 
 455             cache.delete(cache_key % (self.id, lang))
 
 456         cache.delete("Book.mini_box/%d" % (self.id, ))
 
 457         # Fragment.short_html relies on book's tags, so reset it here too
 
 458         for fragm in self.fragments.all():
 
 459             fragm.reset_short_html()
 
 461     def short_html(self):
 
 463             cache_key = "Book.short_html/%d/%s" % (self.id, get_language())
 
 464             short_html = cache.get(cache_key)
 
 468         if short_html is not None:
 
 469             return mark_safe(short_html)
 
 471             tags = self.tags.filter(category__in=('author', 'kind', 'genre', 'epoch'))
 
 472             tags = split_tags(tags)
 
 475             # files generated during publication
 
 476             for ebook_format in self.ebook_formats:
 
 477                 if self.has_media(ebook_format):
 
 478                     formats[ebook_format] = self.get_media(ebook_format)
 
 481             short_html = unicode(render_to_string('catalogue/book_short.html',
 
 482                 {'book': self, 'tags': tags, 'formats': formats}))
 
 485                 cache.set(cache_key, short_html, CACHE_FOREVER)
 
 486             return mark_safe(short_html)
 
 490             cache_key = "Book.mini_box/%d" % (self.id, )
 
 491             short_html = cache.get(cache_key)
 
 495         if short_html is None:
 
 496             authors = self.tags.filter(category='author')
 
 498             short_html = unicode(render_to_string('catalogue/book_mini_box.html',
 
 499                 {'book': self, 'authors': authors, 'STATIC_URL': settings.STATIC_URL}))
 
 502                 cache.set(cache_key, short_html, CACHE_FOREVER)
 
 503         return mark_safe(short_html)
 
 505     def has_description(self):
 
 506         return len(self.description) > 0
 
 507     has_description.short_description = _('description')
 
 508     has_description.boolean = True
 
 511     def has_mp3_file(self):
 
 512         return bool(self.has_media("mp3"))
 
 513     has_mp3_file.short_description = 'MP3'
 
 514     has_mp3_file.boolean = True
 
 516     def has_ogg_file(self):
 
 517         return bool(self.has_media("ogg"))
 
 518     has_ogg_file.short_description = 'OGG'
 
 519     has_ogg_file.boolean = True
 
 521     def has_daisy_file(self):
 
 522         return bool(self.has_media("daisy"))
 
 523     has_daisy_file.short_description = 'DAISY'
 
 524     has_daisy_file.boolean = True
 
 526     def wldocument(self, parse_dublincore=True):
 
 527         from catalogue.import_utils import ORMDocProvider
 
 528         from librarian.parser import WLDocument
 
 530         return WLDocument.from_file(self.xml_file.path,
 
 531                 provider=ORMDocProvider(self),
 
 532                 parse_dublincore=parse_dublincore)
 
 534     def build_cover(self, book_info=None):
 
 535         """(Re)builds the cover image."""
 
 536         from StringIO import StringIO
 
 537         from django.core.files.base import ContentFile
 
 538         from librarian.cover import WLCover
 
 540         if book_info is None:
 
 541             book_info = self.wldocument().book_info
 
 543         cover = WLCover(book_info).image()
 
 545         cover.save(imgstr, 'png')
 
 546         self.cover.save(None, ContentFile(imgstr.getvalue()))
 
 548     def build_pdf(self, customizations=None, file_name=None):
 
 549         """ (Re)builds the pdf file.
 
 550         customizations - customizations which are passed to LaTeX class file.
 
 551         file_name - save the pdf file under a different name and DO NOT save it in db.
 
 553         from os import unlink
 
 554         from django.core.files import File
 
 555         from catalogue.utils import remove_zip
 
 557         pdf = self.wldocument().as_pdf(customizations=customizations)
 
 559         if file_name is None:
 
 560             # we'd like to be sure not to overwrite changes happening while
 
 561             # (timely) pdf generation is taking place (async celery scenario)
 
 562             current_self = Book.objects.get(id=self.id)
 
 563             current_self.pdf_file.save('%s.pdf' % self.slug,
 
 564                     File(open(pdf.get_filename())))
 
 565             self.pdf_file = current_self.pdf_file
 
 567             # remove cached downloadables
 
 568             remove_zip(settings.ALL_PDF_ZIP)
 
 570             for customized_pdf in get_existing_customized_pdf(self):
 
 571                 unlink(customized_pdf)
 
 573             print "saving %s" % file_name
 
 574             print "to: %s" % DefaultStorage().path(file_name)
 
 575             DefaultStorage().save(file_name, File(open(pdf.get_filename())))
 
 577     def build_mobi(self):
 
 578         """ (Re)builds the MOBI file.
 
 581         from django.core.files import File
 
 582         from catalogue.utils import remove_zip
 
 584         mobi = self.wldocument().as_mobi()
 
 586         self.mobi_file.save('%s.mobi' % self.slug, File(open(mobi.get_filename())))
 
 588         # remove zip with all mobi files
 
 589         remove_zip(settings.ALL_MOBI_ZIP)
 
 591     def build_epub(self):
 
 592         """(Re)builds the epub file."""
 
 593         from django.core.files import File
 
 594         from catalogue.utils import remove_zip
 
 596         epub = self.wldocument().as_epub()
 
 598         self.epub_file.save('%s.epub' % self.slug,
 
 599                 File(open(epub.get_filename())))
 
 601         # remove zip package with all epub files
 
 602         remove_zip(settings.ALL_EPUB_ZIP)
 
 605         from django.core.files.base import ContentFile
 
 607         text = self.wldocument().as_text()
 
 608         self.txt_file.save('%s.txt' % self.slug, ContentFile(text.get_string()))
 
 611     def build_html(self):
 
 612         from markupstring import MarkupString
 
 613         from django.core.files.base import ContentFile
 
 614         from slughifi import slughifi
 
 615         from librarian import html
 
 617         meta_tags = list(self.tags.filter(
 
 618             category__in=('author', 'epoch', 'genre', 'kind')))
 
 619         book_tag = self.book_tag()
 
 621         html_output = self.wldocument(parse_dublincore=False).as_html()
 
 623             self.html_file.save('%s.html' % self.slug,
 
 624                     ContentFile(html_output.get_string()))
 
 626             # get ancestor l-tags for adding to new fragments
 
 630                 ancestor_tags.append(p.book_tag())
 
 633             # Delete old fragments and create them from scratch
 
 634             self.fragments.all().delete()
 
 636             closed_fragments, open_fragments = html.extract_fragments(self.html_file.path)
 
 637             for fragment in closed_fragments.values():
 
 639                     theme_names = [s.strip() for s in fragment.themes.split(',')]
 
 640                 except AttributeError:
 
 643                 for theme_name in theme_names:
 
 646                     tag, created = Tag.objects.get_or_create(slug=slughifi(theme_name), category='theme')
 
 648                         tag.name = theme_name
 
 649                         tag.sort_key = theme_name.lower()
 
 655                 text = fragment.to_string()
 
 657                 if (len(MarkupString(text)) > 240):
 
 658                     short_text = unicode(MarkupString(text)[:160])
 
 659                 new_fragment = Fragment.objects.create(anchor=fragment.id, book=self,
 
 660                     text=text, short_text=short_text)
 
 663                 new_fragment.tags = set(meta_tags + themes + [book_tag] + ancestor_tags)
 
 665             self.html_built.send(sender=self)
 
 670     def zip_format(format_):
 
 671         def pretty_file_name(book):
 
 672             return "%s/%s.%s" % (
 
 673                 b.get_extra_info_value()['author'],
 
 677         field_name = "%s_file" % format_
 
 678         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
 
 679         paths = [(pretty_file_name(b), getattr(b, field_name).path)
 
 681         result = create_zip.delay(paths,
 
 682                     getattr(settings, "ALL_%s_ZIP" % format_.upper()))
 
 685     def zip_audiobooks(self, format_):
 
 686         bm = BookMedia.objects.filter(book=self, type=format_)
 
 687         paths = map(lambda bm: (None, bm.file.path), bm)
 
 688         result = create_zip.delay(paths, "%s_%s" % (self.slug, format_))
 
 691     def search_index(self, book_info=None, reuse_index=False):
 
 693             idx = search.ReusableIndex()
 
 699             idx.index_book(self, book_info)
 
 705     def from_xml_file(cls, xml_file, **kwargs):
 
 706         from django.core.files import File
 
 707         from librarian import dcparser
 
 709         # use librarian to parse meta-data
 
 710         book_info = dcparser.parse(xml_file)
 
 712         if not isinstance(xml_file, File):
 
 713             xml_file = File(open(xml_file))
 
 716             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
 
 721     def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
 
 722             build_epub=True, build_txt=True, build_pdf=True, build_mobi=True,
 
 725         from sortify import sortify
 
 727         # check for parts before we do anything
 
 729         if hasattr(book_info, 'parts'):
 
 730             for part_url in book_info.parts:
 
 732                     children.append(Book.objects.get(slug=part_url.slug))
 
 733                 except Book.DoesNotExist, e:
 
 734                     raise Book.DoesNotExist(_('Book "%s" does not exist.') %
 
 739         book_slug = book_info.url.slug
 
 740         if re.search(r'[^a-z0-9-]', book_slug):
 
 741             raise ValueError('Invalid characters in slug')
 
 742         book, created = Book.objects.get_or_create(slug=book_slug)
 
 748                 raise Book.AlreadyExists(_('Book %s already exists') % (
 
 750             # Save shelves for this book
 
 751             book_shelves = list(book.tags.filter(category='set'))
 
 753         book.language = book_info.language
 
 754         book.title = book_info.title
 
 755         if book_info.variant_of:
 
 756             book.common_slug = book_info.variant_of.slug
 
 758             book.common_slug = book.slug
 
 759         book.set_extra_info_value(book_info.to_dict())
 
 762         meta_tags = Tag.tags_from_info(book_info)
 
 764         book.tags = set(meta_tags + book_shelves)
 
 766         book_tag = book.book_tag()
 
 768         for n, child_book in enumerate(children):
 
 769             child_book.parent = book
 
 770             child_book.parent_number = n
 
 773         # Save XML and HTML files
 
 774         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
 
 776         # delete old fragments when overwriting
 
 777         book.fragments.all().delete()
 
 779         if book.build_html():
 
 780             if not settings.NO_BUILD_TXT and build_txt:
 
 783         book.build_cover(book_info)
 
 785         if not settings.NO_BUILD_EPUB and build_epub:
 
 788         if not settings.NO_BUILD_PDF and build_pdf:
 
 791         if not settings.NO_BUILD_MOBI and build_mobi:
 
 794         if not settings.NO_SEARCH_INDEX and search_index:
 
 795             index_book.delay(book.id, book_info)
 
 797         book_descendants = list(book.children.all())
 
 798         descendants_tags = set()
 
 799         # add l-tag to descendants and their fragments
 
 800         while len(book_descendants) > 0:
 
 801             child_book = book_descendants.pop(0)
 
 802             descendants_tags.update(child_book.tags)
 
 803             child_book.tags = list(child_book.tags) + [book_tag]
 
 805             for fragment in child_book.fragments.all():
 
 806                 fragment.tags = set(list(fragment.tags) + [book_tag])
 
 807             book_descendants += list(child_book.children.all())
 
 809         for tag in descendants_tags:
 
 815         book.reset_tag_counter()
 
 816         book.reset_theme_counter()
 
 818         cls.published.send(sender=book)
 
 821     def reset_tag_counter(self):
 
 825         cache_key = "Book.tag_counter/%d" % self.id
 
 826         cache.delete(cache_key)
 
 828             self.parent.reset_tag_counter()
 
 831     def tag_counter(self):
 
 833             cache_key = "Book.tag_counter/%d" % self.id
 
 834             tags = cache.get(cache_key)
 
 840             for child in self.children.all().order_by():
 
 841                 for tag_pk, value in child.tag_counter.iteritems():
 
 842                     tags[tag_pk] = tags.get(tag_pk, 0) + value
 
 843             for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by():
 
 847                 cache.set(cache_key, tags, CACHE_FOREVER)
 
 850     def reset_theme_counter(self):
 
 854         cache_key = "Book.theme_counter/%d" % self.id
 
 855         cache.delete(cache_key)
 
 857             self.parent.reset_theme_counter()
 
 860     def theme_counter(self):
 
 862             cache_key = "Book.theme_counter/%d" % self.id
 
 863             tags = cache.get(cache_key)
 
 869             for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by():
 
 870                 for tag in fragment.tags.filter(category='theme').order_by():
 
 871                     tags[tag.pk] = tags.get(tag.pk, 0) + 1
 
 874                 cache.set(cache_key, tags, CACHE_FOREVER)
 
 877     def pretty_title(self, html_links=False):
 
 879         names = list(book.tags.filter(category='author'))
 
 885         names.extend(reversed(books))
 
 888             names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
 
 890             names = [tag.name for tag in names]
 
 892         return ', '.join(names)
 
 895     def tagged_top_level(cls, tags):
 
 896         """ Returns top-level books tagged with `tags'.
 
 898         It only returns those books which don't have ancestors which are
 
 899         also tagged with those tags.
 
 902         # get relevant books and their tags
 
 903         objects = cls.tagged.with_all(tags)
 
 904         # eliminate descendants
 
 905         l_tags = Tag.objects.filter(category='book', slug__in=[book.book_tag_slug() for book in objects])
 
 906         descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags)]
 
 908             objects = objects.exclude(pk__in=descendants_keys)
 
 913     def book_list(cls, filter=None):
 
 914         """Generates a hierarchical listing of all books.
 
 916         Books are optionally filtered with a test function.
 
 921         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
 
 922                 'title', 'parent', 'slug')
 
 924             books = books.filter(filter).distinct()
 
 925             book_ids = set((book.pk for book in books))
 
 927                 parent = book.parent_id
 
 928                 if parent not in book_ids:
 
 930                 books_by_parent.setdefault(parent, []).append(book)
 
 933                 books_by_parent.setdefault(book.parent_id, []).append(book)
 
 936         books_by_author = SortedDict()
 
 937         for tag in Tag.objects.filter(category='author'):
 
 938             books_by_author[tag] = []
 
 940         for book in books_by_parent.get(None,()):
 
 941             authors = list(book.tags.filter(category='author'))
 
 943                 for author in authors:
 
 944                     books_by_author[author].append(book)
 
 948         return books_by_author, orphans, books_by_parent
 
 951         "SP1": (1, u"szkoła podstawowa"),
 
 952         "SP2": (1, u"szkoła podstawowa"),
 
 953         "P": (1, u"szkoła podstawowa"),
 
 954         "G": (2, u"gimnazjum"),
 
 956         "LP": (3, u"liceum"),
 
 958     def audiences_pl(self):
 
 959         audiences = self.get_extra_info_value().get('audiences', [])
 
 960         audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
 
 961         return [a[1] for a in audiences]
 
 964 def _has_factory(ftype):
 
 965     has = lambda self: bool(getattr(self, "%s_file" % ftype))
 
 966     has.short_description = t.upper()
 
 968     has.__name__ = "has_%s_file" % ftype
 
 972 # add the file fields
 
 973 for t in Book.formats:
 
 974     field_name = "%s_file" % t
 
 975     models.FileField(_("%s file" % t.upper()),
 
 976             upload_to=book_upload_path(t),
 
 977             blank=True).contribute_to_class(Book, field_name)
 
 979     setattr(Book, "has_%s_file" % t, _has_factory(t))
 
 982 class Fragment(models.Model):
 
 983     text = models.TextField()
 
 984     short_text = models.TextField(editable=False)
 
 985     anchor = models.CharField(max_length=120)
 
 986     book = models.ForeignKey(Book, related_name='fragments')
 
 988     objects = models.Manager()
 
 989     tagged = managers.ModelTaggedItemManager(Tag)
 
 990     tags = managers.TagDescriptor(Tag)
 
 993         ordering = ('book', 'anchor',)
 
 994         verbose_name = _('fragment')
 
 995         verbose_name_plural = _('fragments')
 
 997     def get_absolute_url(self):
 
 998         return '%s#m%s' % (reverse('book_text', args=[self.book.slug]), self.anchor)
 
1000     def reset_short_html(self):
 
1004         cache_key = "Fragment.short_html/%d/%s"
 
1005         for lang, langname in settings.LANGUAGES:
 
1006             cache.delete(cache_key % (self.id, lang))
 
1008     def short_html(self):
 
1010             cache_key = "Fragment.short_html/%d/%s" % (self.id, get_language())
 
1011             short_html = cache.get(cache_key)
 
1015         if short_html is not None:
 
1016             return mark_safe(short_html)
 
1018             short_html = unicode(render_to_string('catalogue/fragment_short.html',
 
1019                 {'fragment': self}))
 
1021                 cache.set(cache_key, short_html, CACHE_FOREVER)
 
1022             return mark_safe(short_html)
 
1025 class Collection(models.Model):
 
1026     """A collection of books, which might be defined before publishing them."""
 
1027     title = models.CharField(_('title'), max_length=120, db_index=True)
 
1028     slug = models.SlugField(_('slug'), max_length=120, primary_key=True)
 
1029     description = models.TextField(_('description'), null=True, blank=True)
 
1031     models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)
 
1032     book_slugs = models.TextField(_('book slugs'))
 
1035         ordering = ('title',)
 
1036         verbose_name = _('collection')
 
1037         verbose_name_plural = _('collections')
 
1039     def __unicode__(self):
 
1050 def _tags_updated_handler(sender, affected_tags, **kwargs):
 
1051     # reset tag global counter
 
1052     # we want Tag.changed_at updated for API to know the tag was touched
 
1053     for tag in affected_tags:
 
1054         touch_tag.delay(tag)
 
1056     # if book tags changed, reset book tag counter
 
1057     if isinstance(sender, Book) and \
 
1058                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
 
1059                     exclude(category__in=('book', 'theme', 'set')).count():
 
1060         sender.reset_tag_counter()
 
1061     # if fragment theme changed, reset book theme counter
 
1062     elif isinstance(sender, Fragment) and \
 
1063                 Tag.objects.filter(pk__in=(tag.pk for tag in affected_tags)).\
 
1064                     filter(category='theme').count():
 
1065         sender.book.reset_theme_counter()
 
1066 tags_updated.connect(_tags_updated_handler)
 
1069 def _pre_delete_handler(sender, instance, **kwargs):
 
1070     """ refresh Book on BookMedia delete """
 
1071     if sender == BookMedia:
 
1072         instance.book.save()
 
1073 pre_delete.connect(_pre_delete_handler)
 
1075 def _post_save_handler(sender, instance, **kwargs):
 
1076     """ refresh all the short_html stuff on BookMedia update """
 
1077     if sender == BookMedia:
 
1078         instance.book.save()
 
1079 post_save.connect(_post_save_handler)