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 ebook_formats = constants.EBOOK_FORMATS
48 formats = ebook_formats + ['html', 'xml']
50 parent = models.ForeignKey('self', blank=True, null=True,
51 related_name='children')
53 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
55 objects = models.Manager()
56 tagged = managers.ModelTaggedItemManager(Tag)
57 tags = managers.TagDescriptor(Tag)
59 html_built = django.dispatch.Signal()
60 published = django.dispatch.Signal()
62 class AlreadyExists(Exception):
66 ordering = ('sort_key',)
67 verbose_name = _('book')
68 verbose_name_plural = _('books')
69 app_label = 'catalogue'
71 def __unicode__(self):
74 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
75 from sortify import sortify
77 self.sort_key = sortify(self.title)
78 self.title = unicode(self.title) # ???
80 ret = super(Book, self).save(force_insert, force_update, **kwargs)
83 self.reset_short_html()
88 def get_absolute_url(self):
89 return ('catalogue.views.book_detail', [self.slug])
94 return ('catalogue.views.book_detail', [slug])
100 def language_code(self):
101 return constants.LANGUAGES_3TO2.get(self.language, self.language)
103 def language_name(self):
104 return dict(settings.LANGUAGES).get(self.language_code(), "")
106 def book_tag_slug(self):
107 return ('l-' + self.slug)[:120]
110 slug = self.book_tag_slug()
111 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
113 book_tag.name = self.title[:50]
114 book_tag.sort_key = self.title.lower()
118 def has_media(self, type_):
119 if type_ in Book.formats:
120 return bool(getattr(self, "%s_file" % type_))
122 return self.media.filter(type=type_).exists()
124 def get_media(self, type_):
125 if self.has_media(type_):
126 if type_ in Book.formats:
127 return getattr(self, "%s_file" % type_)
129 return self.media.filter(type=type_)
134 return self.get_media("mp3")
136 return self.get_media("odt")
138 return self.get_media("ogg")
140 return self.get_media("daisy")
142 def reset_short_html(self):
146 type(self).objects.filter(pk=self.pk).update(_related_info=None)
147 # Fragment.short_html relies on book's tags, so reset it here too
148 for fragm in self.fragments.all().iterator():
149 fragm.reset_short_html()
152 author = self.tags.filter(category='author')[0].sort_key
155 type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
159 def has_description(self):
160 return len(self.description) > 0
161 has_description.short_description = _('description')
162 has_description.boolean = True
165 def has_mp3_file(self):
166 return bool(self.has_media("mp3"))
167 has_mp3_file.short_description = 'MP3'
168 has_mp3_file.boolean = True
170 def has_ogg_file(self):
171 return bool(self.has_media("ogg"))
172 has_ogg_file.short_description = 'OGG'
173 has_ogg_file.boolean = True
175 def has_daisy_file(self):
176 return bool(self.has_media("daisy"))
177 has_daisy_file.short_description = 'DAISY'
178 has_daisy_file.boolean = True
180 def wldocument(self, parse_dublincore=True, inherit=True):
181 from catalogue.import_utils import ORMDocProvider
182 from librarian.parser import WLDocument
184 if inherit and self.parent:
185 meta_fallbacks = self.parent.cover_info()
187 meta_fallbacks = None
189 return WLDocument.from_file(self.xml_file.path,
190 provider=ORMDocProvider(self),
191 parse_dublincore=parse_dublincore,
192 meta_fallbacks=meta_fallbacks)
195 def zip_format(format_):
196 def pretty_file_name(book):
197 return "%s/%s.%s" % (
198 book.extra_info['author'],
202 field_name = "%s_file" % format_
203 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
204 paths = [(pretty_file_name(b), getattr(b, field_name).path)
205 for b in books.iterator()]
206 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
208 def zip_audiobooks(self, format_):
209 bm = BookMedia.objects.filter(book=self, type=format_)
210 paths = map(lambda bm: (None, bm.file.path), bm)
211 return create_zip(paths, "%s_%s" % (self.slug, format_))
213 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
216 index = search.Index()
218 index.index_book(self, book_info)
224 index.index.rollback()
229 def from_xml_file(cls, xml_file, **kwargs):
230 from django.core.files import File
231 from librarian import dcparser
233 # use librarian to parse meta-data
234 book_info = dcparser.parse(xml_file)
236 if not isinstance(xml_file, File):
237 xml_file = File(open(xml_file))
240 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
245 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
246 dont_build=None, search_index=True,
247 search_index_tags=True):
248 if dont_build is None:
250 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
252 # check for parts before we do anything
254 if hasattr(book_info, 'parts'):
255 for part_url in book_info.parts:
257 children.append(Book.objects.get(slug=part_url.slug))
258 except Book.DoesNotExist:
259 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
263 book_slug = book_info.url.slug
264 if re.search(r'[^a-z0-9-]', book_slug):
265 raise ValueError('Invalid characters in slug')
266 book, created = Book.objects.get_or_create(slug=book_slug)
273 raise Book.AlreadyExists(_('Book %s already exists') % (
275 # Save shelves for this book
276 book_shelves = list(book.tags.filter(category='set'))
277 old_cover = book.cover_info()
280 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
282 book.language = book_info.language
283 book.title = book_info.title
284 if book_info.variant_of:
285 book.common_slug = book_info.variant_of.slug
287 book.common_slug = book.slug
288 book.extra_info = book_info.to_dict()
291 meta_tags = Tag.tags_from_info(book_info)
293 book.tags = set(meta_tags + book_shelves)
295 cover_changed = old_cover != book.cover_info()
296 obsolete_children = set(b for b in book.children.all()
297 if b not in children)
298 notify_cover_changed = []
299 for n, child_book in enumerate(children):
300 new_child = child_book.parent != book
301 child_book.parent = book
302 child_book.parent_number = n
304 if new_child or cover_changed:
305 notify_cover_changed.append(child_book)
306 # Disown unfaithful children and let them cope on their own.
307 for child in obsolete_children:
309 child.parent_number = 0
311 tasks.fix_tree_tags.delay(child)
313 notify_cover_changed.append(child)
315 # delete old fragments when overwriting
316 book.fragments.all().delete()
317 # Build HTML, fix the tree tags, build cover.
318 has_own_text = bool(book.html_file.build())
319 tasks.fix_tree_tags.delay(book)
320 if 'cover' not in dont_build:
321 book.cover.build_delay()
323 # No saves behind this point.
326 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
327 if format_ not in dont_build:
328 getattr(book, '%s_file' % format_).build_delay()
329 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
330 if format_ not in dont_build:
331 getattr(book, '%s_file' % format_).build_delay()
333 if not settings.NO_SEARCH_INDEX and search_index:
334 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
336 for child in notify_cover_changed:
337 child.parent_cover_changed()
339 cls.published.send(sender=book)
342 def fix_tree_tags(self):
343 """Fixes the l-tags on the book's subtree.
346 * the book has its parents book-tags,
347 * its fragments have the book's and its parents book-tags,
348 * runs those for every child book too,
349 * touches all relevant tags,
350 * resets tag and theme counter on the book and its ancestry.
352 def fix_subtree(book, parent_tags):
353 affected_tags = set(book.tags)
354 book.tags = list(book.tags.exclude(category='book')) + parent_tags
355 sub_parent_tags = parent_tags + [book.book_tag()]
356 for frag in book.fragments.all():
357 affected_tags.update(frag.tags)
358 frag.tags = list(frag.tags.exclude(category='book')
360 for child in book.children.all():
361 affected_tags.update(fix_subtree(child, sub_parent_tags))
366 while parent is not None:
367 parent_tags.append(parent.book_tag())
368 parent = parent.parent
370 affected_tags = fix_subtree(self, parent_tags)
371 for tag in affected_tags:
375 while book is not None:
376 book.reset_tag_counter()
377 book.reset_theme_counter()
380 def cover_info(self, inherit=True):
381 """Returns a dictionary to serve as fallback for BookInfo.
383 For now, the only thing inherited is the cover image.
387 for field in ('cover_url', 'cover_by', 'cover_source'):
388 val = self.extra_info.get(field)
393 if inherit and need and self.parent is not None:
394 parent_info = self.parent.cover_info()
395 parent_info.update(info)
399 def parent_cover_changed(self):
400 """Called when parent book's cover image is changed."""
401 if not self.cover_info(inherit=False):
402 if 'cover' not in app_settings.DONT_BUILD:
403 self.cover.build_delay()
404 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
405 if format_ not in app_settings.DONT_BUILD:
406 getattr(self, '%s_file' % format_).build_delay()
407 for child in self.children.all():
408 child.parent_cover_changed()
410 def other_versions(self):
411 """Find other versions (i.e. in other languages) of the book."""
412 return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
414 def related_info(self):
415 """Keeps info about related objects (tags, media) in cache field."""
416 if self._related_info is not None:
417 return self._related_info
419 rel = {'tags': {}, 'media': {}}
421 tags = self.tags.filter(category__in=(
422 'author', 'kind', 'genre', 'epoch'))
423 tags = split_tags(tags)
424 for category in tags:
426 for tag in tags[category]:
427 tag_info = {'slug': tag.slug, 'name': tag.name}
428 for lc, ln in settings.LANGUAGES:
429 tag_name = getattr(tag, "name_%s" % lc)
431 tag_info["name_%s" % lc] = tag_name
433 rel['tags'][category] = cat
435 for media_format in BookMedia.formats:
436 rel['media'][media_format] = self.has_media(media_format)
441 parents.append((book.parent.title, book.parent.slug))
443 parents = parents[::-1]
445 rel['parents'] = parents
448 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
451 def related_themes(self):
452 theme_counter = self.theme_counter
453 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
454 for tag in book_themes:
455 tag.count = theme_counter[tag.pk]
458 def reset_tag_counter(self):
462 cache_key = "Book.tag_counter/%d" % self.id
463 permanent_cache.delete(cache_key)
465 self.parent.reset_tag_counter()
468 def tag_counter(self):
470 cache_key = "Book.tag_counter/%d" % self.id
471 tags = permanent_cache.get(cache_key)
477 for child in self.children.all().order_by().iterator():
478 for tag_pk, value in child.tag_counter.iteritems():
479 tags[tag_pk] = tags.get(tag_pk, 0) + value
480 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
484 permanent_cache.set(cache_key, tags)
487 def reset_theme_counter(self):
491 cache_key = "Book.theme_counter/%d" % self.id
492 permanent_cache.delete(cache_key)
494 self.parent.reset_theme_counter()
497 def theme_counter(self):
499 cache_key = "Book.theme_counter/%d" % self.id
500 tags = permanent_cache.get(cache_key)
506 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
507 for tag in fragment.tags.filter(category='theme').order_by().iterator():
508 tags[tag.pk] = tags.get(tag.pk, 0) + 1
511 permanent_cache.set(cache_key, tags)
514 def pretty_title(self, html_links=False):
516 rel_info = book.related_info()
517 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
518 for tag in rel_info['tags'].get('author', ())]
520 logging.info("%s, %s" % (book.slug, unicode(rel_info['tags'].get('author', ()))))
521 if 'parents' in rel_info:
522 books = [(name, Book.create_url(slug))
523 for name, slug in rel_info['parents']]
524 names.extend(reversed(books))
525 names.append((self.title, self.get_absolute_url()))
528 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
530 names = [tag[0] for tag in names]
531 return ', '.join(names)
534 def tagged_top_level(cls, tags):
535 """ Returns top-level books tagged with `tags`.
537 It only returns those books which don't have ancestors which are
538 also tagged with those tags.
541 # get relevant books and their tags
542 objects = cls.tagged.with_all(tags)
543 parents = objects.filter(html_file='').only('slug')
544 # eliminate descendants
545 l_tags = Tag.objects.filter(category='book',
546 slug__in=[book.book_tag_slug() for book in parents.iterator()])
547 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
549 objects = objects.exclude(pk__in=descendants_keys)
554 def book_list(cls, filter=None):
555 """Generates a hierarchical listing of all books.
557 Books are optionally filtered with a test function.
562 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
563 'title', 'parent', 'slug')
565 books = books.filter(filter).distinct()
567 book_ids = set(b['pk'] for b in books.values("pk").iterator())
568 for book in books.iterator():
569 parent = book.parent_id
570 if parent not in book_ids:
572 books_by_parent.setdefault(parent, []).append(book)
574 for book in books.iterator():
575 books_by_parent.setdefault(book.parent_id, []).append(book)
578 books_by_author = SortedDict()
579 for tag in Tag.objects.filter(category='author').iterator():
580 books_by_author[tag] = []
582 for book in books_by_parent.get(None,()):
583 authors = list(book.tags.filter(category='author'))
585 for author in authors:
586 books_by_author[author].append(book)
590 return books_by_author, orphans, books_by_parent
593 "SP": (1, u"szkoła podstawowa"),
594 "SP1": (1, u"szkoła podstawowa"),
595 "SP2": (1, u"szkoła podstawowa"),
596 "P": (1, u"szkoła podstawowa"),
597 "G": (2, u"gimnazjum"),
599 "LP": (3, u"liceum"),
601 def audiences_pl(self):
602 audiences = self.extra_info.get('audiences', [])
603 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
604 return [a[1] for a in audiences]
606 def choose_fragment(self):
607 tag = self.book_tag()
608 fragments = Fragment.tagged.with_any([tag])
609 if fragments.exists():
610 return fragments.order_by('?')[0]
612 return self.parent.choose_fragment()
617 # add the file fields
618 for format_ in Book.formats:
619 field_name = "%s_file" % format_
620 EbookField(format_, _("%s file" % format_.upper()),
621 upload_to=book_upload_path(format_),
622 blank=True, default='').contribute_to_class(Book, field_name)