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 fnpdjango.storage import BofhFileSystemStorage
15 from catalogue import constants
16 from catalogue.fields import EbookField
17 from catalogue.models import Tag, Fragment, BookMedia
18 from catalogue.utils import create_zip, split_tags, related_tag_name
19 from catalogue import app_settings
20 from catalogue import tasks
21 from newtagging import managers
23 bofh_storage = BofhFileSystemStorage()
25 permanent_cache = get_cache('permanent')
28 class Book(models.Model):
29 """Represents a book imported from WL-XML."""
30 title = models.CharField(_('title'), max_length=120)
31 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
32 sort_key_author = models.CharField(_('sort key by author'), max_length=120, db_index=True, editable=False, default=u'')
33 slug = models.SlugField(_('slug'), max_length=120, db_index=True,
35 common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
36 language = models.CharField(_('language code'), max_length=3, db_index=True,
37 default=app_settings.DEFAULT_LANGUAGE)
38 description = models.TextField(_('description'), blank=True)
39 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
40 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
41 parent_number = models.IntegerField(_('parent number'), default=0)
42 extra_info = jsonfield.JSONField(_('extra information'), default={})
43 gazeta_link = models.CharField(blank=True, max_length=240)
44 wiki_link = models.CharField(blank=True, max_length=240)
45 # files generated during publication
47 cover = EbookField('cover', _('cover'),
48 null=True, blank=True,
49 upload_to=lambda i, n: 'book/cover/%s.jpg' % i.slug,
50 storage=bofh_storage, max_length=255)
51 # Cleaner version of cover for thumbs
52 cover_thumb = EbookField('cover_thumb', _('cover thumbnail'),
53 null=True, blank=True,
54 upload_to=lambda i, n: 'book/cover_thumb/%s.jpg' % i.slug,
56 ebook_formats = constants.EBOOK_FORMATS
57 formats = ebook_formats + ['html', 'xml']
59 parent = models.ForeignKey('self', blank=True, null=True,
60 related_name='children')
62 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
64 objects = models.Manager()
65 tagged = managers.ModelTaggedItemManager(Tag)
66 tags = managers.TagDescriptor(Tag)
68 html_built = django.dispatch.Signal()
69 published = django.dispatch.Signal()
71 class AlreadyExists(Exception):
75 ordering = ('sort_key',)
76 verbose_name = _('book')
77 verbose_name_plural = _('books')
78 app_label = 'catalogue'
80 def __unicode__(self):
83 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
84 from sortify import sortify
86 self.sort_key = sortify(self.title)
87 self.title = unicode(self.title) # ???
89 ret = super(Book, self).save(force_insert, force_update, **kwargs)
92 self.reset_short_html()
97 def get_absolute_url(self):
98 return ('catalogue.views.book_detail', [self.slug])
102 def create_url(slug):
103 return ('catalogue.views.book_detail', [slug])
109 def language_code(self):
110 return constants.LANGUAGES_3TO2.get(self.language, self.language)
112 def language_name(self):
113 return dict(settings.LANGUAGES).get(self.language_code(), "")
115 def book_tag_slug(self):
116 return ('l-' + self.slug)[:120]
119 slug = self.book_tag_slug()
120 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
122 book_tag.name = self.title[:50]
123 book_tag.sort_key = self.title.lower()
127 def has_media(self, type_):
128 if type_ in Book.formats:
129 return bool(getattr(self, "%s_file" % type_))
131 return self.media.filter(type=type_).exists()
133 def get_media(self, type_):
134 if self.has_media(type_):
135 if type_ in Book.formats:
136 return getattr(self, "%s_file" % type_)
138 return self.media.filter(type=type_)
143 return self.get_media("mp3")
145 return self.get_media("odt")
147 return self.get_media("ogg")
149 return self.get_media("daisy")
151 def reset_short_html(self):
155 type(self).objects.filter(pk=self.pk).update(_related_info=None)
156 # Fragment.short_html relies on book's tags, so reset it here too
157 for fragm in self.fragments.all().iterator():
158 fragm.reset_short_html()
161 author = self.tags.filter(category='author')[0].sort_key
164 type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
168 def has_description(self):
169 return len(self.description) > 0
170 has_description.short_description = _('description')
171 has_description.boolean = True
174 def has_mp3_file(self):
175 return bool(self.has_media("mp3"))
176 has_mp3_file.short_description = 'MP3'
177 has_mp3_file.boolean = True
179 def has_ogg_file(self):
180 return bool(self.has_media("ogg"))
181 has_ogg_file.short_description = 'OGG'
182 has_ogg_file.boolean = True
184 def has_daisy_file(self):
185 return bool(self.has_media("daisy"))
186 has_daisy_file.short_description = 'DAISY'
187 has_daisy_file.boolean = True
189 def wldocument(self, parse_dublincore=True, inherit=True):
190 from catalogue.import_utils import ORMDocProvider
191 from librarian.parser import WLDocument
193 if inherit and self.parent:
194 meta_fallbacks = self.parent.cover_info()
196 meta_fallbacks = None
198 return WLDocument.from_file(self.xml_file.path,
199 provider=ORMDocProvider(self),
200 parse_dublincore=parse_dublincore,
201 meta_fallbacks=meta_fallbacks)
204 def zip_format(format_):
205 def pretty_file_name(book):
206 return "%s/%s.%s" % (
207 book.extra_info['author'],
211 field_name = "%s_file" % format_
212 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
213 paths = [(pretty_file_name(b), getattr(b, field_name).path)
214 for b in books.iterator()]
215 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
217 def zip_audiobooks(self, format_):
218 bm = BookMedia.objects.filter(book=self, type=format_)
219 paths = map(lambda bm: (None, bm.file.path), bm)
220 return create_zip(paths, "%s_%s" % (self.slug, format_))
222 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
225 index = search.Index()
227 index.index_book(self, book_info)
233 index.index.rollback()
238 def from_xml_file(cls, xml_file, **kwargs):
239 from django.core.files import File
240 from librarian import dcparser
242 # use librarian to parse meta-data
243 book_info = dcparser.parse(xml_file)
245 if not isinstance(xml_file, File):
246 xml_file = File(open(xml_file))
249 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
254 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
255 dont_build=None, search_index=True,
256 search_index_tags=True):
257 if dont_build is None:
259 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
261 # check for parts before we do anything
263 if hasattr(book_info, 'parts'):
264 for part_url in book_info.parts:
266 children.append(Book.objects.get(slug=part_url.slug))
267 except Book.DoesNotExist:
268 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
272 book_slug = book_info.url.slug
273 if re.search(r'[^a-z0-9-]', book_slug):
274 raise ValueError('Invalid characters in slug')
275 book, created = Book.objects.get_or_create(slug=book_slug)
282 raise Book.AlreadyExists(_('Book %s already exists') % (
284 # Save shelves for this book
285 book_shelves = list(book.tags.filter(category='set'))
286 old_cover = book.cover_info()
289 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
291 book.language = book_info.language
292 book.title = book_info.title
293 if book_info.variant_of:
294 book.common_slug = book_info.variant_of.slug
296 book.common_slug = book.slug
297 book.extra_info = book_info.to_dict()
300 meta_tags = Tag.tags_from_info(book_info)
302 book.tags = set(meta_tags + book_shelves)
304 cover_changed = old_cover != book.cover_info()
305 obsolete_children = set(b for b in book.children.all()
306 if b not in children)
307 notify_cover_changed = []
308 for n, child_book in enumerate(children):
309 new_child = child_book.parent != book
310 child_book.parent = book
311 child_book.parent_number = n
313 if new_child or cover_changed:
314 notify_cover_changed.append(child_book)
315 # Disown unfaithful children and let them cope on their own.
316 for child in obsolete_children:
318 child.parent_number = 0
320 tasks.fix_tree_tags.delay(child)
322 notify_cover_changed.append(child)
324 # delete old fragments when overwriting
325 book.fragments.all().delete()
326 # Build HTML, fix the tree tags, build cover.
327 has_own_text = bool(book.html_file.build())
328 tasks.fix_tree_tags.delay(book)
329 if 'cover' not in dont_build:
330 book.cover.build_delay()
331 book.cover_thumb.build_delay()
333 # No saves behind this point.
336 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
337 if format_ not in dont_build:
338 getattr(book, '%s_file' % format_).build_delay()
339 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
340 if format_ not in dont_build:
341 getattr(book, '%s_file' % format_).build_delay()
343 if not settings.NO_SEARCH_INDEX and search_index:
344 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
346 for child in notify_cover_changed:
347 child.parent_cover_changed()
349 cls.published.send(sender=book)
352 def fix_tree_tags(self):
353 """Fixes the l-tags on the book's subtree.
356 * the book has its parents book-tags,
357 * its fragments have the book's and its parents book-tags,
358 * runs those for every child book too,
359 * touches all relevant tags,
360 * resets tag and theme counter on the book and its ancestry.
362 def fix_subtree(book, parent_tags):
363 affected_tags = set(book.tags)
364 book.tags = list(book.tags.exclude(category='book')) + parent_tags
365 sub_parent_tags = parent_tags + [book.book_tag()]
366 for frag in book.fragments.all():
367 affected_tags.update(frag.tags)
368 frag.tags = list(frag.tags.exclude(category='book')
370 for child in book.children.all():
371 affected_tags.update(fix_subtree(child, sub_parent_tags))
376 while parent is not None:
377 parent_tags.append(parent.book_tag())
378 parent = parent.parent
380 affected_tags = fix_subtree(self, parent_tags)
381 for tag in affected_tags:
385 while book is not None:
386 book.reset_tag_counter()
387 book.reset_theme_counter()
390 def cover_info(self, inherit=True):
391 """Returns a dictionary to serve as fallback for BookInfo.
393 For now, the only thing inherited is the cover image.
397 for field in ('cover_url', 'cover_by', 'cover_source'):
398 val = self.extra_info.get(field)
403 if inherit and need and self.parent is not None:
404 parent_info = self.parent.cover_info()
405 parent_info.update(info)
409 def parent_cover_changed(self):
410 """Called when parent book's cover image is changed."""
411 if not self.cover_info(inherit=False):
412 if 'cover' not in app_settings.DONT_BUILD:
413 self.cover.build_delay()
414 self.cover_thumb.build_delay()
415 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
416 if format_ not in app_settings.DONT_BUILD:
417 getattr(self, '%s_file' % format_).build_delay()
418 for child in self.children.all():
419 child.parent_cover_changed()
421 def other_versions(self):
422 """Find other versions (i.e. in other languages) of the book."""
423 return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
425 def related_info(self):
426 """Keeps info about related objects (tags, media) in cache field."""
427 if self._related_info is not None:
428 return self._related_info
430 rel = {'tags': {}, 'media': {}}
432 tags = self.tags.filter(category__in=(
433 'author', 'kind', 'genre', 'epoch'))
434 tags = split_tags(tags)
435 for category in tags:
437 for tag in tags[category]:
438 tag_info = {'slug': tag.slug, 'name': tag.name}
439 for lc, ln in settings.LANGUAGES:
440 tag_name = getattr(tag, "name_%s" % lc)
442 tag_info["name_%s" % lc] = tag_name
444 rel['tags'][category] = cat
446 for media_format in BookMedia.formats:
447 rel['media'][media_format] = self.has_media(media_format)
452 parents.append((book.parent.title, book.parent.slug))
454 parents = parents[::-1]
456 rel['parents'] = parents
459 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
462 def related_themes(self):
463 theme_counter = self.theme_counter
464 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
465 for tag in book_themes:
466 tag.count = theme_counter[tag.pk]
469 def reset_tag_counter(self):
473 cache_key = "Book.tag_counter/%d" % self.id
474 permanent_cache.delete(cache_key)
476 self.parent.reset_tag_counter()
479 def tag_counter(self):
481 cache_key = "Book.tag_counter/%d" % self.id
482 tags = permanent_cache.get(cache_key)
488 for child in self.children.all().order_by().iterator():
489 for tag_pk, value in child.tag_counter.iteritems():
490 tags[tag_pk] = tags.get(tag_pk, 0) + value
491 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
495 permanent_cache.set(cache_key, tags)
498 def reset_theme_counter(self):
502 cache_key = "Book.theme_counter/%d" % self.id
503 permanent_cache.delete(cache_key)
505 self.parent.reset_theme_counter()
508 def theme_counter(self):
510 cache_key = "Book.theme_counter/%d" % self.id
511 tags = permanent_cache.get(cache_key)
517 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
518 for tag in fragment.tags.filter(category='theme').order_by().iterator():
519 tags[tag.pk] = tags.get(tag.pk, 0) + 1
522 permanent_cache.set(cache_key, tags)
525 def pretty_title(self, html_links=False):
527 rel_info = book.related_info()
528 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
529 for tag in rel_info['tags'].get('author', ())]
530 if 'parents' in rel_info:
531 books = [(name, Book.create_url(slug))
532 for name, slug in rel_info['parents']]
533 names.extend(reversed(books))
534 names.append((self.title, self.get_absolute_url()))
537 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
539 names = [tag[0] for tag in names]
540 return ', '.join(names)
543 def tagged_top_level(cls, tags):
544 """ Returns top-level books tagged with `tags`.
546 It only returns those books which don't have ancestors which are
547 also tagged with those tags.
550 # get relevant books and their tags
551 objects = cls.tagged.with_all(tags)
552 parents = objects.exclude(children=None).only('slug')
553 # eliminate descendants
554 l_tags = Tag.objects.filter(category='book',
555 slug__in=[book.book_tag_slug() for book in parents.iterator()])
556 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
558 objects = objects.exclude(pk__in=descendants_keys)
563 def book_list(cls, filter=None):
564 """Generates a hierarchical listing of all books.
566 Books are optionally filtered with a test function.
571 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
572 'title', 'parent', 'slug')
574 books = books.filter(filter).distinct()
576 book_ids = set(b['pk'] for b in books.values("pk").iterator())
577 for book in books.iterator():
578 parent = book.parent_id
579 if parent not in book_ids:
581 books_by_parent.setdefault(parent, []).append(book)
583 for book in books.iterator():
584 books_by_parent.setdefault(book.parent_id, []).append(book)
587 books_by_author = SortedDict()
588 for tag in Tag.objects.filter(category='author').iterator():
589 books_by_author[tag] = []
591 for book in books_by_parent.get(None, ()):
592 authors = list(book.tags.filter(category='author'))
594 for author in authors:
595 books_by_author[author].append(book)
599 return books_by_author, orphans, books_by_parent
602 "SP": (1, u"szkoła podstawowa"),
603 "SP1": (1, u"szkoła podstawowa"),
604 "SP2": (1, u"szkoła podstawowa"),
605 "P": (1, u"szkoła podstawowa"),
606 "G": (2, u"gimnazjum"),
608 "LP": (3, u"liceum"),
610 def audiences_pl(self):
611 audiences = self.extra_info.get('audiences', [])
612 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
613 return [a[1] for a in audiences]
615 def choose_fragment(self):
616 tag = self.book_tag()
617 fragments = Fragment.tagged.with_any([tag])
618 if fragments.exists():
619 return fragments.order_by('?')[0]
621 return self.parent.choose_fragment()
626 # add the file fields
627 for format_ in Book.formats:
628 field_name = "%s_file" % format_
629 upload_to = (lambda upload_path:
630 lambda i, n: upload_path % i.slug
631 )('book/%s/%%s.%s' % (format_, format_))
632 EbookField(format_, _("%s file" % format_.upper()),
634 storage=bofh_storage,
638 ).contribute_to_class(Book, field_name)