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 language_code(self):
104 return constants.LANGUAGES_3TO2.get(self.language, self.language)
106 def language_name(self):
107 return dict(settings.LANGUAGES).get(self.language_code(), "")
109 def book_tag_slug(self):
110 return ('l-' + self.slug)[:120]
113 slug = self.book_tag_slug()
114 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
116 book_tag.name = self.title[:50]
117 book_tag.sort_key = self.title.lower()
121 def has_media(self, type_):
122 if type_ in Book.formats:
123 return bool(getattr(self, "%s_file" % type_))
125 return self.media.filter(type=type_).exists()
127 def get_media(self, type_):
128 if self.has_media(type_):
129 if type_ in Book.formats:
130 return getattr(self, "%s_file" % type_)
132 return self.media.filter(type=type_)
137 return self.get_media("mp3")
139 return self.get_media("odt")
141 return self.get_media("ogg")
143 return self.get_media("daisy")
145 def reset_short_html(self):
149 type(self).objects.filter(pk=self.pk).update(_related_info=None)
150 # Fragment.short_html relies on book's tags, so reset it here too
151 for fragm in self.fragments.all().iterator():
152 fragm.reset_short_html()
155 author = self.tags.filter(category='author')[0].sort_key
158 type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
162 def has_description(self):
163 return len(self.description) > 0
164 has_description.short_description = _('description')
165 has_description.boolean = True
168 def has_mp3_file(self):
169 return bool(self.has_media("mp3"))
170 has_mp3_file.short_description = 'MP3'
171 has_mp3_file.boolean = True
173 def has_ogg_file(self):
174 return bool(self.has_media("ogg"))
175 has_ogg_file.short_description = 'OGG'
176 has_ogg_file.boolean = True
178 def has_daisy_file(self):
179 return bool(self.has_media("daisy"))
180 has_daisy_file.short_description = 'DAISY'
181 has_daisy_file.boolean = True
183 def wldocument(self, parse_dublincore=True, inherit=True):
184 from catalogue.import_utils import ORMDocProvider
185 from librarian.parser import WLDocument
187 if inherit and self.parent:
188 meta_fallbacks = self.parent.cover_info()
190 meta_fallbacks = None
192 return WLDocument.from_file(self.xml_file.path,
193 provider=ORMDocProvider(self),
194 parse_dublincore=parse_dublincore,
195 meta_fallbacks=meta_fallbacks)
198 def zip_format(format_):
199 def pretty_file_name(book):
200 return "%s/%s.%s" % (
201 book.extra_info['author'],
205 field_name = "%s_file" % format_
206 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
207 paths = [(pretty_file_name(b), getattr(b, field_name).path)
208 for b in books.iterator()]
209 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
211 def zip_audiobooks(self, format_):
212 bm = BookMedia.objects.filter(book=self, type=format_)
213 paths = map(lambda bm: (None, bm.file.path), bm)
214 return create_zip(paths, "%s_%s" % (self.slug, format_))
216 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
219 index = search.Index()
221 index.index_book(self, book_info)
227 index.index.rollback()
232 def from_xml_file(cls, xml_file, **kwargs):
233 from django.core.files import File
234 from librarian import dcparser
236 # use librarian to parse meta-data
237 book_info = dcparser.parse(xml_file)
239 if not isinstance(xml_file, File):
240 xml_file = File(open(xml_file))
243 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
248 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
249 dont_build=None, search_index=True,
250 search_index_tags=True):
251 if dont_build is None:
253 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
255 # check for parts before we do anything
257 if hasattr(book_info, 'parts'):
258 for part_url in book_info.parts:
260 children.append(Book.objects.get(slug=part_url.slug))
261 except Book.DoesNotExist:
262 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
266 book_slug = book_info.url.slug
267 if re.search(r'[^a-z0-9-]', book_slug):
268 raise ValueError('Invalid characters in slug')
269 book, created = Book.objects.get_or_create(slug=book_slug)
276 raise Book.AlreadyExists(_('Book %s already exists') % (
278 # Save shelves for this book
279 book_shelves = list(book.tags.filter(category='set'))
280 old_cover = book.cover_info()
283 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
285 book.language = book_info.language
286 book.title = book_info.title
287 if book_info.variant_of:
288 book.common_slug = book_info.variant_of.slug
290 book.common_slug = book.slug
291 book.extra_info = book_info.to_dict()
294 meta_tags = Tag.tags_from_info(book_info)
296 book.tags = set(meta_tags + book_shelves)
298 cover_changed = old_cover != book.cover_info()
299 obsolete_children = set(b for b in book.children.all()
300 if b not in children)
301 notify_cover_changed = []
302 for n, child_book in enumerate(children):
303 new_child = child_book.parent != book
304 child_book.parent = book
305 child_book.parent_number = n
307 if new_child or cover_changed:
308 notify_cover_changed.append(child_book)
309 # Disown unfaithful children and let them cope on their own.
310 for child in obsolete_children:
312 child.parent_number = 0
314 tasks.fix_tree_tags.delay(child)
316 notify_cover_changed.append(child)
318 # delete old fragments when overwriting
319 book.fragments.all().delete()
320 # Build HTML, fix the tree tags, build cover.
321 has_own_text = bool(book.html_file.build())
322 tasks.fix_tree_tags.delay(book)
323 if 'cover' not in dont_build:
324 book.cover.build_delay()
325 book.cover_thumb.build_delay()
327 # No saves behind this point.
330 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
331 if format_ not in dont_build:
332 getattr(book, '%s_file' % format_).build_delay()
333 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
334 if format_ not in dont_build:
335 getattr(book, '%s_file' % format_).build_delay()
337 if not settings.NO_SEARCH_INDEX and search_index:
338 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
340 for child in notify_cover_changed:
341 child.parent_cover_changed()
343 cls.published.send(sender=book)
346 def fix_tree_tags(self):
347 """Fixes the l-tags on the book's subtree.
350 * the book has its parents book-tags,
351 * its fragments have the book's and its parents book-tags,
352 * runs those for every child book too,
353 * touches all relevant tags,
354 * resets tag and theme counter on the book and its ancestry.
356 def fix_subtree(book, parent_tags):
357 affected_tags = set(book.tags)
358 book.tags = list(book.tags.exclude(category='book')) + parent_tags
359 sub_parent_tags = parent_tags + [book.book_tag()]
360 for frag in book.fragments.all():
361 affected_tags.update(frag.tags)
362 frag.tags = list(frag.tags.exclude(category='book')
364 for child in book.children.all():
365 affected_tags.update(fix_subtree(child, sub_parent_tags))
370 while parent is not None:
371 parent_tags.append(parent.book_tag())
372 parent = parent.parent
374 affected_tags = fix_subtree(self, parent_tags)
375 for tag in affected_tags:
379 while book is not None:
380 book.reset_tag_counter()
381 book.reset_theme_counter()
384 def cover_info(self, inherit=True):
385 """Returns a dictionary to serve as fallback for BookInfo.
387 For now, the only thing inherited is the cover image.
391 for field in ('cover_url', 'cover_by', 'cover_source'):
392 val = self.extra_info.get(field)
397 if inherit and need and self.parent is not None:
398 parent_info = self.parent.cover_info()
399 parent_info.update(info)
403 def parent_cover_changed(self):
404 """Called when parent book's cover image is changed."""
405 if not self.cover_info(inherit=False):
406 if 'cover' not in app_settings.DONT_BUILD:
407 self.cover.build_delay()
408 self.cover_thumb.build_delay()
409 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
410 if format_ not in app_settings.DONT_BUILD:
411 getattr(self, '%s_file' % format_).build_delay()
412 for child in self.children.all():
413 child.parent_cover_changed()
415 def other_versions(self):
416 """Find other versions (i.e. in other languages) of the book."""
417 return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
419 def related_info(self):
420 """Keeps info about related objects (tags, media) in cache field."""
421 if self._related_info is not None:
422 return self._related_info
424 rel = {'tags': {}, 'media': {}}
426 tags = self.tags.filter(category__in=(
427 'author', 'kind', 'genre', 'epoch'))
428 tags = split_tags(tags)
429 for category in tags:
431 for tag in tags[category]:
432 tag_info = {'slug': tag.slug, 'name': tag.name}
433 for lc, ln in settings.LANGUAGES:
434 tag_name = getattr(tag, "name_%s" % lc)
436 tag_info["name_%s" % lc] = tag_name
438 rel['tags'][category] = cat
440 for media_format in BookMedia.formats:
441 rel['media'][media_format] = self.has_media(media_format)
446 parents.append((book.parent.title, book.parent.slug))
448 parents = parents[::-1]
450 rel['parents'] = parents
453 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
456 def related_themes(self):
457 theme_counter = self.theme_counter
458 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
459 for tag in book_themes:
460 tag.count = theme_counter[tag.pk]
463 def reset_tag_counter(self):
467 cache_key = "Book.tag_counter/%d" % self.id
468 permanent_cache.delete(cache_key)
470 self.parent.reset_tag_counter()
473 def tag_counter(self):
475 cache_key = "Book.tag_counter/%d" % self.id
476 tags = permanent_cache.get(cache_key)
482 for child in self.children.all().order_by().iterator():
483 for tag_pk, value in child.tag_counter.iteritems():
484 tags[tag_pk] = tags.get(tag_pk, 0) + value
485 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
489 permanent_cache.set(cache_key, tags)
492 def reset_theme_counter(self):
496 cache_key = "Book.theme_counter/%d" % self.id
497 permanent_cache.delete(cache_key)
499 self.parent.reset_theme_counter()
502 def theme_counter(self):
504 cache_key = "Book.theme_counter/%d" % self.id
505 tags = permanent_cache.get(cache_key)
511 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
512 for tag in fragment.tags.filter(category='theme').order_by().iterator():
513 tags[tag.pk] = tags.get(tag.pk, 0) + 1
516 permanent_cache.set(cache_key, tags)
519 def pretty_title(self, html_links=False):
521 rel_info = book.related_info()
522 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
523 for tag in rel_info['tags'].get('author', ())]
525 logging.info("%s, %s" % (book.slug, unicode(rel_info['tags'].get('author', ()))))
526 if 'parents' in rel_info:
527 books = [(name, Book.create_url(slug))
528 for name, slug in rel_info['parents']]
529 names.extend(reversed(books))
530 names.append((self.title, self.get_absolute_url()))
533 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
535 names = [tag[0] for tag in names]
536 return ', '.join(names)
539 def tagged_top_level(cls, tags):
540 """ Returns top-level books tagged with `tags`.
542 It only returns those books which don't have ancestors which are
543 also tagged with those tags.
546 # get relevant books and their tags
547 objects = cls.tagged.with_all(tags)
548 parents = objects.filter(html_file='').only('slug')
549 # eliminate descendants
550 l_tags = Tag.objects.filter(category='book',
551 slug__in=[book.book_tag_slug() for book in parents.iterator()])
552 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
554 objects = objects.exclude(pk__in=descendants_keys)
559 def book_list(cls, filter=None):
560 """Generates a hierarchical listing of all books.
562 Books are optionally filtered with a test function.
567 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
568 'title', 'parent', 'slug')
570 books = books.filter(filter).distinct()
572 book_ids = set(b['pk'] for b in books.values("pk").iterator())
573 for book in books.iterator():
574 parent = book.parent_id
575 if parent not in book_ids:
577 books_by_parent.setdefault(parent, []).append(book)
579 for book in books.iterator():
580 books_by_parent.setdefault(book.parent_id, []).append(book)
583 books_by_author = SortedDict()
584 for tag in Tag.objects.filter(category='author').iterator():
585 books_by_author[tag] = []
587 for book in books_by_parent.get(None,()):
588 authors = list(book.tags.filter(category='author'))
590 for author in authors:
591 books_by_author[author].append(book)
595 return books_by_author, orphans, books_by_parent
598 "SP": (1, u"szkoła podstawowa"),
599 "SP1": (1, u"szkoła podstawowa"),
600 "SP2": (1, u"szkoła podstawowa"),
601 "P": (1, u"szkoła podstawowa"),
602 "G": (2, u"gimnazjum"),
604 "LP": (3, u"liceum"),
606 def audiences_pl(self):
607 audiences = self.extra_info.get('audiences', [])
608 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
609 return [a[1] for a in audiences]
611 def choose_fragment(self):
612 tag = self.book_tag()
613 fragments = Fragment.tagged.with_any([tag])
614 if fragments.exists():
615 return fragments.order_by('?')[0]
617 return self.parent.choose_fragment()
622 # add the file fields
623 for format_ in Book.formats:
624 field_name = "%s_file" % format_
625 EbookField(format_, _("%s file" % format_.upper()),
626 upload_to=book_upload_path(format_),
627 blank=True, default='').contribute_to_class(Book, field_name)