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 OrderedDict
7 from django.conf import settings
8 from django.core.cache import caches
9 from django.db import models
10 from django.db.models import permalink
11 import django.dispatch
12 from django.contrib.contenttypes.fields import GenericRelation
13 from django.core.urlresolvers import reverse
14 from django.utils.translation import ugettext_lazy as _
16 from fnpdjango.storage import BofhFileSystemStorage
17 from catalogue import constants
18 from catalogue.fields import EbookField
19 from catalogue.models import Tag, Fragment, BookMedia
20 from catalogue.utils import create_zip, split_tags, related_tag_name
21 from catalogue import app_settings
22 from catalogue import tasks
23 from newtagging import managers
25 bofh_storage = BofhFileSystemStorage()
27 permanent_cache = caches['permanent']
30 def _cover_upload_to(i, n):
31 return 'book/cover/%s.jpg' % i.slug
33 def _cover_thumb_upload_to(i, n):
34 return 'book/cover_thumb/%s.jpg' % i.slug,
36 def _ebook_upload_to(upload_path):
38 return upload_path % i.slug
42 class Book(models.Model):
43 """Represents a book imported from WL-XML."""
44 title = models.CharField(_('title'), max_length=120)
45 sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
46 sort_key_author = models.CharField(_('sort key by author'), max_length=120, db_index=True, editable=False, default=u'')
47 slug = models.SlugField(_('slug'), max_length=120, db_index=True,
49 common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
50 language = models.CharField(_('language code'), max_length=3, db_index=True,
51 default=app_settings.DEFAULT_LANGUAGE)
52 description = models.TextField(_('description'), blank=True)
53 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
54 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
55 parent_number = models.IntegerField(_('parent number'), default=0)
56 extra_info = jsonfield.JSONField(_('extra information'), default={})
57 gazeta_link = models.CharField(blank=True, max_length=240)
58 wiki_link = models.CharField(blank=True, max_length=240)
59 # files generated during publication
61 cover = EbookField('cover', _('cover'),
62 null=True, blank=True,
63 upload_to=_cover_upload_to,
64 storage=bofh_storage, max_length=255)
65 # Cleaner version of cover for thumbs
66 cover_thumb = EbookField('cover_thumb', _('cover thumbnail'),
67 null=True, blank=True,
68 upload_to=_cover_thumb_upload_to,
70 ebook_formats = constants.EBOOK_FORMATS
71 formats = ebook_formats + ['html', 'xml']
73 parent = models.ForeignKey('self', blank=True, null=True,
74 related_name='children')
76 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
78 objects = models.Manager()
79 tagged = managers.ModelTaggedItemManager(Tag)
80 tags = managers.TagDescriptor(Tag)
81 tag_relations = GenericRelation(Tag.intermediary_table_model)
83 html_built = django.dispatch.Signal()
84 published = django.dispatch.Signal()
86 class AlreadyExists(Exception):
90 ordering = ('sort_key',)
91 verbose_name = _('book')
92 verbose_name_plural = _('books')
93 app_label = 'catalogue'
95 def __unicode__(self):
98 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
99 from sortify import sortify
101 self.sort_key = sortify(self.title)
102 self.title = unicode(self.title) # ???
104 ret = super(Book, self).save(force_insert, force_update, **kwargs)
107 self.reset_short_html()
112 def get_absolute_url(self):
113 return ('catalogue.views.book_detail', [self.slug])
117 def create_url(slug):
118 return ('catalogue.views.book_detail', [slug])
124 def language_code(self):
125 return constants.LANGUAGES_3TO2.get(self.language, self.language)
127 def language_name(self):
128 return dict(settings.LANGUAGES).get(self.language_code(), "")
130 def book_tag_slug(self):
131 return ('l-' + self.slug)[:120]
134 slug = self.book_tag_slug()
135 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
137 book_tag.name = self.title[:50]
138 book_tag.sort_key = self.title.lower()
142 def has_media(self, type_):
143 if type_ in Book.formats:
144 return bool(getattr(self, "%s_file" % type_))
146 return self.media.filter(type=type_).exists()
148 def get_media(self, type_):
149 if self.has_media(type_):
150 if type_ in Book.formats:
151 return getattr(self, "%s_file" % type_)
153 return self.media.filter(type=type_)
158 return self.get_media("mp3")
160 return self.get_media("odt")
162 return self.get_media("ogg")
164 return self.get_media("daisy")
166 def reset_short_html(self):
170 type(self).objects.filter(pk=self.pk).update(_related_info=None)
171 # Fragment.short_html relies on book's tags, so reset it here too
172 for fragm in self.fragments.all().iterator():
173 fragm.reset_short_html()
176 author = self.tags.filter(category='author')[0].sort_key
179 type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
183 def has_description(self):
184 return len(self.description) > 0
185 has_description.short_description = _('description')
186 has_description.boolean = True
189 def has_mp3_file(self):
190 return bool(self.has_media("mp3"))
191 has_mp3_file.short_description = 'MP3'
192 has_mp3_file.boolean = True
194 def has_ogg_file(self):
195 return bool(self.has_media("ogg"))
196 has_ogg_file.short_description = 'OGG'
197 has_ogg_file.boolean = True
199 def has_daisy_file(self):
200 return bool(self.has_media("daisy"))
201 has_daisy_file.short_description = 'DAISY'
202 has_daisy_file.boolean = True
204 def wldocument(self, parse_dublincore=True, inherit=True):
205 from catalogue.import_utils import ORMDocProvider
206 from librarian.parser import WLDocument
208 if inherit and self.parent:
209 meta_fallbacks = self.parent.cover_info()
211 meta_fallbacks = None
213 return WLDocument.from_file(self.xml_file.path,
214 provider=ORMDocProvider(self),
215 parse_dublincore=parse_dublincore,
216 meta_fallbacks=meta_fallbacks)
219 def zip_format(format_):
220 def pretty_file_name(book):
221 return "%s/%s.%s" % (
222 book.extra_info['author'],
226 field_name = "%s_file" % format_
227 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
228 paths = [(pretty_file_name(b), getattr(b, field_name).path)
229 for b in books.iterator()]
230 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
232 def zip_audiobooks(self, format_):
233 bm = BookMedia.objects.filter(book=self, type=format_)
234 paths = map(lambda bm: (None, bm.file.path), bm)
235 return create_zip(paths, "%s_%s" % (self.slug, format_))
237 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
239 from search.index import Index
242 index.index_book(self, book_info)
248 index.index.rollback()
253 def from_xml_file(cls, xml_file, **kwargs):
254 from django.core.files import File
255 from librarian import dcparser
257 # use librarian to parse meta-data
258 book_info = dcparser.parse(xml_file)
260 if not isinstance(xml_file, File):
261 xml_file = File(open(xml_file))
264 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
269 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
270 dont_build=None, search_index=True,
271 search_index_tags=True):
272 if dont_build is None:
274 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
276 # check for parts before we do anything
278 if hasattr(book_info, 'parts'):
279 for part_url in book_info.parts:
281 children.append(Book.objects.get(slug=part_url.slug))
282 except Book.DoesNotExist:
283 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
287 book_slug = book_info.url.slug
288 if re.search(r'[^a-z0-9-]', book_slug):
289 raise ValueError('Invalid characters in slug')
290 book, created = Book.objects.get_or_create(slug=book_slug)
297 raise Book.AlreadyExists(_('Book %s already exists') % (
299 # Save shelves for this book
300 book_shelves = list(book.tags.filter(category='set'))
301 old_cover = book.cover_info()
304 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
306 book.language = book_info.language
307 book.title = book_info.title
308 if book_info.variant_of:
309 book.common_slug = book_info.variant_of.slug
311 book.common_slug = book.slug
312 book.extra_info = book_info.to_dict()
315 meta_tags = Tag.tags_from_info(book_info)
317 book.tags = set(meta_tags + book_shelves)
319 cover_changed = old_cover != book.cover_info()
320 obsolete_children = set(b for b in book.children.all()
321 if b not in children)
322 notify_cover_changed = []
323 for n, child_book in enumerate(children):
324 new_child = child_book.parent != book
325 child_book.parent = book
326 child_book.parent_number = n
328 if new_child or cover_changed:
329 notify_cover_changed.append(child_book)
330 # Disown unfaithful children and let them cope on their own.
331 for child in obsolete_children:
333 child.parent_number = 0
335 tasks.fix_tree_tags.delay(child)
337 notify_cover_changed.append(child)
339 # No saves beyond this point.
342 if 'cover' not in dont_build:
343 book.cover.build_delay()
344 book.cover_thumb.build_delay()
346 # Build HTML and ebooks.
347 book.html_file.build_delay()
349 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
350 if format_ not in dont_build:
351 getattr(book, '%s_file' % format_).build_delay()
352 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
353 if format_ not in dont_build:
354 getattr(book, '%s_file' % format_).build_delay()
356 if not settings.NO_SEARCH_INDEX and search_index:
357 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
359 for child in notify_cover_changed:
360 child.parent_cover_changed()
362 cls.published.send(sender=book)
365 def fix_tree_tags(self):
366 """Fixes the l-tags on the book's subtree.
369 * the book has its parents book-tags,
370 * its fragments have the book's and its parents book-tags,
371 * runs those for every child book too,
372 * touches all relevant tags,
373 * resets tag and theme counter on the book and its ancestry.
375 def fix_subtree(book, parent_tags):
376 affected_tags = set(book.tags)
377 book.tags = list(book.tags.exclude(category='book')) + parent_tags
378 sub_parent_tags = parent_tags + [book.book_tag()]
379 for frag in book.fragments.all():
380 affected_tags.update(frag.tags)
381 frag.tags = list(frag.tags.exclude(category='book')
383 for child in book.children.all():
384 affected_tags.update(fix_subtree(child, sub_parent_tags))
389 while parent is not None:
390 parent_tags.append(parent.book_tag())
391 parent = parent.parent
393 affected_tags = fix_subtree(self, parent_tags)
394 for tag in affected_tags:
398 while book is not None:
399 book.reset_tag_counter()
400 book.reset_theme_counter()
403 def cover_info(self, inherit=True):
404 """Returns a dictionary to serve as fallback for BookInfo.
406 For now, the only thing inherited is the cover image.
410 for field in ('cover_url', 'cover_by', 'cover_source'):
411 val = self.extra_info.get(field)
416 if inherit and need and self.parent is not None:
417 parent_info = self.parent.cover_info()
418 parent_info.update(info)
422 def parent_cover_changed(self):
423 """Called when parent book's cover image is changed."""
424 if not self.cover_info(inherit=False):
425 if 'cover' not in app_settings.DONT_BUILD:
426 self.cover.build_delay()
427 self.cover_thumb.build_delay()
428 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
429 if format_ not in app_settings.DONT_BUILD:
430 getattr(self, '%s_file' % format_).build_delay()
431 for child in self.children.all():
432 child.parent_cover_changed()
434 def other_versions(self):
435 """Find other versions (i.e. in other languages) of the book."""
436 return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
438 def related_info(self):
439 """Keeps info about related objects (tags, media) in cache field."""
440 if self._related_info is not None:
441 return self._related_info
443 rel = {'tags': {}, 'media': {}}
445 tags = self.tags.filter(category__in=(
446 'author', 'kind', 'genre', 'epoch'))
447 tags = split_tags(tags)
448 for category in tags:
450 for tag in tags[category]:
451 tag_info = {'slug': tag.slug, 'name': tag.name}
452 for lc, ln in settings.LANGUAGES:
453 tag_name = getattr(tag, "name_%s" % lc)
455 tag_info["name_%s" % lc] = tag_name
457 rel['tags'][category] = cat
459 for media_format in BookMedia.formats:
460 rel['media'][media_format] = self.has_media(media_format)
465 parents.append((book.parent.title, book.parent.slug))
467 parents = parents[::-1]
469 rel['parents'] = parents
472 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
475 def related_themes(self):
476 theme_counter = self.theme_counter
477 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
478 for tag in book_themes:
479 tag.count = theme_counter[tag.pk]
482 def reset_tag_counter(self):
486 cache_key = "Book.tag_counter/%d" % self.id
487 permanent_cache.delete(cache_key)
489 self.parent.reset_tag_counter()
492 def tag_counter(self):
494 cache_key = "Book.tag_counter/%d" % self.id
495 tags = permanent_cache.get(cache_key)
501 for child in self.children.all().order_by().iterator():
502 for tag_pk, value in child.tag_counter.iteritems():
503 tags[tag_pk] = tags.get(tag_pk, 0) + value
504 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
508 permanent_cache.set(cache_key, tags)
511 def reset_theme_counter(self):
515 cache_key = "Book.theme_counter/%d" % self.id
516 permanent_cache.delete(cache_key)
518 self.parent.reset_theme_counter()
521 def theme_counter(self):
523 cache_key = "Book.theme_counter/%d" % self.id
524 tags = permanent_cache.get(cache_key)
530 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
531 for tag in fragment.tags.filter(category='theme').order_by().iterator():
532 tags[tag.pk] = tags.get(tag.pk, 0) + 1
535 permanent_cache.set(cache_key, tags)
538 def pretty_title(self, html_links=False):
540 rel_info = book.related_info()
541 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
542 for tag in rel_info['tags'].get('author', ())]
543 if 'parents' in rel_info:
544 books = [(name, Book.create_url(slug))
545 for name, slug in rel_info['parents']]
546 names.extend(reversed(books))
547 names.append((self.title, self.get_absolute_url()))
550 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
552 names = [tag[0] for tag in names]
553 return ', '.join(names)
556 def tagged_top_level(cls, tags):
557 """ Returns top-level books tagged with `tags`.
559 It only returns those books which don't have ancestors which are
560 also tagged with those tags.
563 # get relevant books and their tags
564 objects = cls.tagged.with_all(tags)
565 parents = objects.exclude(children=None).only('slug')
566 # eliminate descendants
567 l_tags = Tag.objects.filter(category='book',
568 slug__in=[book.book_tag_slug() for book in parents.iterator()])
569 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
571 objects = objects.exclude(pk__in=descendants_keys)
576 def book_list(cls, filter=None):
577 """Generates a hierarchical listing of all books.
579 Books are optionally filtered with a test function.
584 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
585 'title', 'parent', 'slug')
587 books = books.filter(filter).distinct()
589 book_ids = set(b['pk'] for b in books.values("pk").iterator())
590 for book in books.iterator():
591 parent = book.parent_id
592 if parent not in book_ids:
594 books_by_parent.setdefault(parent, []).append(book)
596 for book in books.iterator():
597 books_by_parent.setdefault(book.parent_id, []).append(book)
600 books_by_author = OrderedDict()
601 for tag in Tag.objects.filter(category='author').iterator():
602 books_by_author[tag] = []
604 for book in books_by_parent.get(None, ()):
605 authors = list(book.tags.filter(category='author'))
607 for author in authors:
608 books_by_author[author].append(book)
612 return books_by_author, orphans, books_by_parent
615 "SP": (1, u"szkoła podstawowa"),
616 "SP1": (1, u"szkoła podstawowa"),
617 "SP2": (1, u"szkoła podstawowa"),
618 "P": (1, u"szkoła podstawowa"),
619 "G": (2, u"gimnazjum"),
621 "LP": (3, u"liceum"),
623 def audiences_pl(self):
624 audiences = self.extra_info.get('audiences', [])
625 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
626 return [a[1] for a in audiences]
628 def stage_note(self):
629 stage = self.extra_info.get('stage')
630 if stage and stage < '0.4':
631 return (_('This work needs modernisation'),
632 reverse('infopage', args=['wymagajace-uwspolczesnienia']))
636 def choose_fragment(self):
637 tag = self.book_tag()
638 fragments = Fragment.tagged.with_any([tag])
639 if fragments.exists():
640 return fragments.order_by('?')[0]
642 return self.parent.choose_fragment()
646 # add the file fields
647 for format_ in Book.formats:
648 field_name = "%s_file" % format_
649 # This weird globals() assignment makes Django migrations comfortable.
650 _upload_to = _ebook_upload_to('book/%s/%%s.%s' % (format_, format_))
651 _upload_to.__name__ = '_%s_upload_to' % format_
652 globals()[_upload_to.__name__] = _upload_to
654 EbookField(format_, _("%s file" % format_.upper()),
655 upload_to=_upload_to,
656 storage=bofh_storage,
660 ).contribute_to_class(Book, field_name)