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.
6 from django.conf import settings
7 from django.core.cache import get_cache
8 from django.db import models
9 from django.db.models import permalink
10 import django.dispatch
11 from django.utils.datastructures import SortedDict
12 from django.utils.translation import ugettext_lazy as _
14 from catalogue import constants
15 from catalogue.fields import EbookField
16 from catalogue.models import Tag, Fragment, BookMedia
17 from catalogue.utils import create_zip, split_tags, book_upload_path, related_tag_name
18 from catalogue import app_settings
19 from catalogue import tasks
20 from newtagging import managers
23 permanent_cache = get_cache('permanent')
26 class Book(models.Model):
27 """Represents a book imported from WL-XML."""
28 title = models.CharField(_('title'), max_length=120)
29 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
30 sort_key_author = models.CharField(_('sort key by author'), max_length=120, db_index=True, editable=False, default=u'')
31 slug = models.SlugField(_('slug'), max_length=120, db_index=True,
33 common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
34 language = models.CharField(_('language code'), max_length=3, db_index=True,
35 default=app_settings.DEFAULT_LANGUAGE)
36 description = models.TextField(_('description'), blank=True)
37 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
38 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
39 parent_number = models.IntegerField(_('parent number'), default=0)
40 extra_info = jsonfield.JSONField(_('extra information'), default={})
41 gazeta_link = models.CharField(blank=True, max_length=240)
42 wiki_link = models.CharField(blank=True, max_length=240)
43 # files generated during publication
45 cover = EbookField('cover', _('cover'),
46 upload_to=book_upload_path('jpg'), null=True, blank=True)
47 # Cleaner version of cover for thumbs
48 cover_thumb = EbookField('cover_thumb', _('cover thumbnail'),
49 upload_to=book_upload_path('th.jpg'), null=True, blank=True)
50 ebook_formats = constants.EBOOK_FORMATS
51 formats = ebook_formats + ['html', 'xml']
53 parent = models.ForeignKey('self', blank=True, null=True,
54 related_name='children')
56 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
58 objects = models.Manager()
59 tagged = managers.ModelTaggedItemManager(Tag)
60 tags = managers.TagDescriptor(Tag)
62 html_built = django.dispatch.Signal()
63 published = django.dispatch.Signal()
65 class AlreadyExists(Exception):
69 ordering = ('sort_key',)
70 verbose_name = _('book')
71 verbose_name_plural = _('books')
72 app_label = 'catalogue'
74 def __unicode__(self):
77 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
78 from sortify import sortify
80 self.sort_key = sortify(self.title)
81 self.title = unicode(self.title) # ???
83 ret = super(Book, self).save(force_insert, force_update, **kwargs)
86 self.reset_short_html()
91 def get_absolute_url(self):
92 return ('catalogue.views.book_detail', [self.slug])
97 return ('catalogue.views.book_detail', [slug])
103 def book_tag_slug(self):
104 return ('l-' + self.slug)[:120]
107 slug = self.book_tag_slug()
108 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
110 book_tag.name = self.title[:50]
111 book_tag.sort_key = self.title.lower()
115 def has_media(self, type_):
116 if type_ in Book.formats:
117 return bool(getattr(self, "%s_file" % type_))
119 return self.media.filter(type=type_).exists()
121 def get_media(self, type_):
122 if self.has_media(type_):
123 if type_ in Book.formats:
124 return getattr(self, "%s_file" % type_)
126 return self.media.filter(type=type_)
131 return self.get_media("mp3")
133 return self.get_media("odt")
135 return self.get_media("ogg")
137 return self.get_media("daisy")
139 def reset_short_html(self):
143 type(self).objects.filter(pk=self.pk).update(_related_info=None)
144 # Fragment.short_html relies on book's tags, so reset it here too
145 for fragm in self.fragments.all().iterator():
146 fragm.reset_short_html()
149 author = self.tags.filter(category='author')[0].sort_key
152 type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
156 def has_description(self):
157 return len(self.description) > 0
158 has_description.short_description = _('description')
159 has_description.boolean = True
162 def has_mp3_file(self):
163 return bool(self.has_media("mp3"))
164 has_mp3_file.short_description = 'MP3'
165 has_mp3_file.boolean = True
167 def has_ogg_file(self):
168 return bool(self.has_media("ogg"))
169 has_ogg_file.short_description = 'OGG'
170 has_ogg_file.boolean = True
172 def has_daisy_file(self):
173 return bool(self.has_media("daisy"))
174 has_daisy_file.short_description = 'DAISY'
175 has_daisy_file.boolean = True
177 def wldocument(self, parse_dublincore=True, inherit=True):
178 from catalogue.import_utils import ORMDocProvider
179 from librarian.parser import WLDocument
181 if inherit and self.parent:
182 meta_fallbacks = self.parent.cover_info()
184 meta_fallbacks = None
186 return WLDocument.from_file(self.xml_file.path,
187 provider=ORMDocProvider(self),
188 parse_dublincore=parse_dublincore,
189 meta_fallbacks=meta_fallbacks)
192 def zip_format(format_):
193 def pretty_file_name(book):
194 return "%s/%s.%s" % (
195 book.extra_info['author'],
199 field_name = "%s_file" % format_
200 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
201 paths = [(pretty_file_name(b), getattr(b, field_name).path)
202 for b in books.iterator()]
203 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
205 def zip_audiobooks(self, format_):
206 bm = BookMedia.objects.filter(book=self, type=format_)
207 paths = map(lambda bm: (None, bm.file.path), bm)
208 return create_zip(paths, "%s_%s" % (self.slug, format_))
210 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
213 index = search.Index()
215 index.index_book(self, book_info)
221 index.index.rollback()
226 def from_xml_file(cls, xml_file, **kwargs):
227 from django.core.files import File
228 from librarian import dcparser
230 # use librarian to parse meta-data
231 book_info = dcparser.parse(xml_file)
233 if not isinstance(xml_file, File):
234 xml_file = File(open(xml_file))
237 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
242 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
243 dont_build=None, search_index=True,
244 search_index_tags=True):
245 if dont_build is None:
247 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
249 # check for parts before we do anything
251 if hasattr(book_info, 'parts'):
252 for part_url in book_info.parts:
254 children.append(Book.objects.get(slug=part_url.slug))
255 except Book.DoesNotExist:
256 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
260 book_slug = book_info.url.slug
261 if re.search(r'[^a-z0-9-]', book_slug):
262 raise ValueError('Invalid characters in slug')
263 book, created = Book.objects.get_or_create(slug=book_slug)
270 raise Book.AlreadyExists(_('Book %s already exists') % (
272 # Save shelves for this book
273 book_shelves = list(book.tags.filter(category='set'))
274 old_cover = book.cover_info()
277 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
279 book.language = book_info.language
280 book.title = book_info.title
281 if book_info.variant_of:
282 book.common_slug = book_info.variant_of.slug
284 book.common_slug = book.slug
285 book.extra_info = book_info.to_dict()
288 meta_tags = Tag.tags_from_info(book_info)
290 book.tags = set(meta_tags + book_shelves)
292 cover_changed = old_cover != book.cover_info()
293 obsolete_children = set(b for b in book.children.all()
294 if b not in children)
295 notify_cover_changed = []
296 for n, child_book in enumerate(children):
297 new_child = child_book.parent != book
298 child_book.parent = book
299 child_book.parent_number = n
301 if new_child or cover_changed:
302 notify_cover_changed.append(child_book)
303 # Disown unfaithful children and let them cope on their own.
304 for child in obsolete_children:
306 child.parent_number = 0
308 tasks.fix_tree_tags.delay(child)
310 notify_cover_changed.append(child)
312 # delete old fragments when overwriting
313 book.fragments.all().delete()
314 # Build HTML, fix the tree tags, build cover.
315 has_own_text = bool(book.html_file.build())
316 tasks.fix_tree_tags.delay(book)
317 if 'cover' not in dont_build:
318 book.cover.build_delay()
319 book.cover_thumb.build_delay()
321 # No saves behind this point.
324 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
325 if format_ not in dont_build:
326 getattr(book, '%s_file' % format_).build_delay()
327 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
328 if format_ not in dont_build:
329 getattr(book, '%s_file' % format_).build_delay()
331 if not settings.NO_SEARCH_INDEX and search_index:
332 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
334 for child in notify_cover_changed:
335 child.parent_cover_changed()
337 cls.published.send(sender=book)
340 def fix_tree_tags(self):
341 """Fixes the l-tags on the book's subtree.
344 * the book has its parents book-tags,
345 * its fragments have the book's and its parents book-tags,
346 * runs those for every child book too,
347 * touches all relevant tags,
348 * resets tag and theme counter on the book and its ancestry.
350 def fix_subtree(book, parent_tags):
351 affected_tags = set(book.tags)
352 book.tags = list(book.tags.exclude(category='book')) + parent_tags
353 sub_parent_tags = parent_tags + [book.book_tag()]
354 for frag in book.fragments.all():
355 affected_tags.update(frag.tags)
356 frag.tags = list(frag.tags.exclude(category='book')
358 for child in book.children.all():
359 affected_tags.update(fix_subtree(child, sub_parent_tags))
364 while parent is not None:
365 parent_tags.append(parent.book_tag())
366 parent = parent.parent
368 affected_tags = fix_subtree(self, parent_tags)
369 for tag in affected_tags:
373 while book is not None:
374 book.reset_tag_counter()
375 book.reset_theme_counter()
378 def cover_info(self, inherit=True):
379 """Returns a dictionary to serve as fallback for BookInfo.
381 For now, the only thing inherited is the cover image.
385 for field in ('cover_url', 'cover_by', 'cover_source'):
386 val = self.extra_info.get(field)
391 if inherit and need and self.parent is not None:
392 parent_info = self.parent.cover_info()
393 parent_info.update(info)
397 def parent_cover_changed(self):
398 """Called when parent book's cover image is changed."""
399 if not self.cover_info(inherit=False):
400 if 'cover' not in app_settings.DONT_BUILD:
401 self.cover.build_delay()
402 self.cover_thumb.build_delay()
403 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
404 if format_ not in app_settings.DONT_BUILD:
405 getattr(self, '%s_file' % format_).build_delay()
406 for child in self.children.all():
407 child.parent_cover_changed()
409 def related_info(self):
410 """Keeps info about related objects (tags, media) in cache field."""
411 if self._related_info is not None:
412 return self._related_info
414 rel = {'tags': {}, 'media': {}}
416 tags = self.tags.filter(category__in=(
417 'author', 'kind', 'genre', 'epoch'))
418 tags = split_tags(tags)
419 for category in tags:
421 for tag in tags[category]:
422 tag_info = {'slug': tag.slug, 'name': tag.name}
423 for lc, ln in settings.LANGUAGES:
424 tag_name = getattr(tag, "name_%s" % lc)
426 tag_info["name_%s" % lc] = tag_name
428 rel['tags'][category] = cat
430 for media_format in BookMedia.formats:
431 rel['media'][media_format] = self.has_media(media_format)
436 parents.append((book.parent.title, book.parent.slug))
438 parents = parents[::-1]
440 rel['parents'] = parents
443 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
446 def related_themes(self):
447 theme_counter = self.theme_counter
448 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
449 for tag in book_themes:
450 tag.count = theme_counter[tag.pk]
453 def reset_tag_counter(self):
457 cache_key = "Book.tag_counter/%d" % self.id
458 permanent_cache.delete(cache_key)
460 self.parent.reset_tag_counter()
463 def tag_counter(self):
465 cache_key = "Book.tag_counter/%d" % self.id
466 tags = permanent_cache.get(cache_key)
472 for child in self.children.all().order_by().iterator():
473 for tag_pk, value in child.tag_counter.iteritems():
474 tags[tag_pk] = tags.get(tag_pk, 0) + value
475 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
479 permanent_cache.set(cache_key, tags)
482 def reset_theme_counter(self):
486 cache_key = "Book.theme_counter/%d" % self.id
487 permanent_cache.delete(cache_key)
489 self.parent.reset_theme_counter()
492 def theme_counter(self):
494 cache_key = "Book.theme_counter/%d" % self.id
495 tags = permanent_cache.get(cache_key)
501 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
502 for tag in fragment.tags.filter(category='theme').order_by().iterator():
503 tags[tag.pk] = tags.get(tag.pk, 0) + 1
506 permanent_cache.set(cache_key, tags)
509 def pretty_title(self, html_links=False):
511 rel_info = book.related_info()
512 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
513 for tag in rel_info['tags'].get('author', ())]
515 logging.info("%s, %s" % (book.slug, unicode(rel_info['tags'].get('author', ()))))
516 if 'parents' in rel_info:
517 books = [(name, Book.create_url(slug))
518 for name, slug in rel_info['parents']]
519 names.extend(reversed(books))
520 names.append((self.title, self.get_absolute_url()))
523 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
525 names = [tag[0] for tag in names]
526 return ', '.join(names)
529 def tagged_top_level(cls, tags):
530 """ Returns top-level books tagged with `tags`.
532 It only returns those books which don't have ancestors which are
533 also tagged with those tags.
536 # get relevant books and their tags
537 objects = cls.tagged.with_all(tags)
538 parents = objects.filter(html_file='').only('slug')
539 # eliminate descendants
540 l_tags = Tag.objects.filter(category='book',
541 slug__in=[book.book_tag_slug() for book in parents.iterator()])
542 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
544 objects = objects.exclude(pk__in=descendants_keys)
549 def book_list(cls, filter=None):
550 """Generates a hierarchical listing of all books.
552 Books are optionally filtered with a test function.
557 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
558 'title', 'parent', 'slug')
560 books = books.filter(filter).distinct()
562 book_ids = set(b['pk'] for b in books.values("pk").iterator())
563 for book in books.iterator():
564 parent = book.parent_id
565 if parent not in book_ids:
567 books_by_parent.setdefault(parent, []).append(book)
569 for book in books.iterator():
570 books_by_parent.setdefault(book.parent_id, []).append(book)
573 books_by_author = SortedDict()
574 for tag in Tag.objects.filter(category='author').iterator():
575 books_by_author[tag] = []
577 for book in books_by_parent.get(None,()):
578 authors = list(book.tags.filter(category='author'))
580 for author in authors:
581 books_by_author[author].append(book)
585 return books_by_author, orphans, books_by_parent
588 "SP": (1, u"szkoła podstawowa"),
589 "SP1": (1, u"szkoła podstawowa"),
590 "SP2": (1, u"szkoła podstawowa"),
591 "P": (1, u"szkoła podstawowa"),
592 "G": (2, u"gimnazjum"),
594 "LP": (3, u"liceum"),
596 def audiences_pl(self):
597 audiences = self.extra_info.get('audiences', [])
598 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
599 return [a[1] for a in audiences]
601 def choose_fragment(self):
602 tag = self.book_tag()
603 fragments = Fragment.tagged.with_any([tag])
604 if fragments.exists():
605 return fragments.order_by('?')[0]
607 return self.parent.choose_fragment()
612 # add the file fields
613 for format_ in Book.formats:
614 field_name = "%s_file" % format_
615 EbookField(format_, _("%s file" % format_.upper()),
616 upload_to=book_upload_path(format_),
617 blank=True, default='').contribute_to_class(Book, field_name)