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 as 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
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 slug = models.SlugField(_('slug'), max_length=120, db_index=True,
32 common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
33 language = models.CharField(_('language code'), max_length=3, db_index=True,
34 default=app_settings.DEFAULT_LANGUAGE)
35 description = models.TextField(_('description'), blank=True)
36 created_at = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
37 changed_at = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
38 parent_number = models.IntegerField(_('parent number'), default=0)
39 extra_info = jsonfield.JSONField(_('extra information'), default='{}')
40 gazeta_link = models.CharField(blank=True, max_length=240)
41 wiki_link = models.CharField(blank=True, max_length=240)
42 # files generated during publication
44 cover = EbookField('cover', _('cover'),
45 upload_to=book_upload_path('jpg'), null=True, blank=True)
46 ebook_formats = constants.EBOOK_FORMATS
47 formats = ebook_formats + ['html', 'xml']
49 parent = models.ForeignKey('self', blank=True, null=True,
50 related_name='children')
52 _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
54 objects = models.Manager()
55 tagged = managers.ModelTaggedItemManager(Tag)
56 tags = managers.TagDescriptor(Tag)
58 html_built = django.dispatch.Signal()
59 published = django.dispatch.Signal()
61 class AlreadyExists(Exception):
65 ordering = ('sort_key',)
66 verbose_name = _('book')
67 verbose_name_plural = _('books')
68 app_label = 'catalogue'
70 def __unicode__(self):
73 def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
74 from sortify import sortify
76 self.sort_key = sortify(self.title)
78 ret = super(Book, self).save(force_insert, force_update)
81 self.reset_short_html()
86 def get_absolute_url(self):
87 return ('catalogue.views.book_detail', [self.slug])
93 def book_tag_slug(self):
94 return ('l-' + self.slug)[:120]
97 slug = self.book_tag_slug()
98 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
100 book_tag.name = self.title[:50]
101 book_tag.sort_key = self.title.lower()
105 def has_media(self, type_):
106 if type_ in Book.formats:
107 return bool(getattr(self, "%s_file" % type_))
109 return self.media.filter(type=type_).exists()
111 def get_media(self, type_):
112 if self.has_media(type_):
113 if type_ in Book.formats:
114 return getattr(self, "%s_file" % type_)
116 return self.media.filter(type=type_)
121 return self.get_media("mp3")
123 return self.get_media("odt")
125 return self.get_media("ogg")
127 return self.get_media("daisy")
129 def reset_short_html(self):
133 type(self).objects.filter(pk=self.pk).update(_related_info=None)
134 # Fragment.short_html relies on book's tags, so reset it here too
135 for fragm in self.fragments.all().iterator():
136 fragm.reset_short_html()
138 def has_description(self):
139 return len(self.description) > 0
140 has_description.short_description = _('description')
141 has_description.boolean = True
144 def has_mp3_file(self):
145 return bool(self.has_media("mp3"))
146 has_mp3_file.short_description = 'MP3'
147 has_mp3_file.boolean = True
149 def has_ogg_file(self):
150 return bool(self.has_media("ogg"))
151 has_ogg_file.short_description = 'OGG'
152 has_ogg_file.boolean = True
154 def has_daisy_file(self):
155 return bool(self.has_media("daisy"))
156 has_daisy_file.short_description = 'DAISY'
157 has_daisy_file.boolean = True
159 def wldocument(self, parse_dublincore=True, inherit=True):
160 from catalogue.import_utils import ORMDocProvider
161 from librarian.parser import WLDocument
163 if inherit and self.parent:
164 meta_fallbacks = self.parent.cover_info()
166 meta_fallbacks = None
168 return WLDocument.from_file(self.xml_file.path,
169 provider=ORMDocProvider(self),
170 parse_dublincore=parse_dublincore,
171 meta_fallbacks=meta_fallbacks)
174 def zip_format(format_):
175 def pretty_file_name(book):
176 return "%s/%s.%s" % (
177 book.extra_info['author'],
181 field_name = "%s_file" % format_
182 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
183 paths = [(pretty_file_name(b), getattr(b, field_name).path)
184 for b in books.iterator()]
185 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
187 def zip_audiobooks(self, format_):
188 bm = BookMedia.objects.filter(book=self, type=format_)
189 paths = map(lambda bm: (None, bm.file.path), bm)
190 return create_zip(paths, "%s_%s" % (self.slug, format_))
192 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
195 index = search.Index()
197 index.index_book(self, book_info)
203 index.index.rollback()
208 def from_xml_file(cls, xml_file, **kwargs):
209 from django.core.files import File
210 from librarian import dcparser
212 # use librarian to parse meta-data
213 book_info = dcparser.parse(xml_file)
215 if not isinstance(xml_file, File):
216 xml_file = File(open(xml_file))
219 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
224 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
225 dont_build=None, search_index=True,
226 search_index_tags=True):
227 if dont_build is None:
229 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
231 # check for parts before we do anything
233 if hasattr(book_info, 'parts'):
234 for part_url in book_info.parts:
236 children.append(Book.objects.get(slug=part_url.slug))
237 except Book.DoesNotExist:
238 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
242 book_slug = book_info.url.slug
243 if re.search(r'[^a-z0-9-]', book_slug):
244 raise ValueError('Invalid characters in slug')
245 book, created = Book.objects.get_or_create(slug=book_slug)
252 raise Book.AlreadyExists(_('Book %s already exists') % (
254 # Save shelves for this book
255 book_shelves = list(book.tags.filter(category='set'))
256 old_cover = book.cover_info()
259 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
261 book.language = book_info.language
262 book.title = book_info.title
263 if book_info.variant_of:
264 book.common_slug = book_info.variant_of.slug
266 book.common_slug = book.slug
267 book.extra_info = book_info.to_dict()
270 meta_tags = Tag.tags_from_info(book_info)
272 book.tags = set(meta_tags + book_shelves)
274 cover_changed = old_cover != book.cover_info()
275 obsolete_children = set(b for b in book.children.all()
276 if b not in children)
277 notify_cover_changed = []
278 for n, child_book in enumerate(children):
279 new_child = child_book.parent != book
280 child_book.parent = book
281 child_book.parent_number = n
283 if new_child or cover_changed:
284 notify_cover_changed.append(child_book)
285 # Disown unfaithful children and let them cope on their own.
286 for child in obsolete_children:
288 child.parent_number = 0
290 tasks.fix_tree_tags.delay(child)
292 notify_cover_changed.append(child)
294 # delete old fragments when overwriting
295 book.fragments.all().delete()
296 # Build HTML, fix the tree tags, build cover.
297 has_own_text = bool(book.html_file.build())
298 tasks.fix_tree_tags.delay(book)
299 if 'cover' not in dont_build:
300 book.cover.build_delay()
302 # No saves behind this point.
305 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
306 if format_ not in dont_build:
307 getattr(book, '%s_file' % format_).build_delay()
308 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
309 if format_ not in dont_build:
310 getattr(book, '%s_file' % format_).build_delay()
312 if not settings.NO_SEARCH_INDEX and search_index:
313 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
315 for child in notify_cover_changed:
316 child.parent_cover_changed()
318 cls.published.send(sender=book)
321 def fix_tree_tags(self):
322 """Fixes the l-tags on the book's subtree.
325 * the book has its parents book-tags,
326 * its fragments have the book's and its parents book-tags,
327 * runs those for every child book too,
328 * touches all relevant tags,
329 * resets tag and theme counter on the book and its ancestry.
331 def fix_subtree(book, parent_tags):
332 affected_tags = set(book.tags)
333 book.tags = list(book.tags.exclude(category='book')) + parent_tags
334 sub_parent_tags = parent_tags + [book.book_tag()]
335 for frag in book.fragments.all():
336 affected_tags.update(frag.tags)
337 frag.tags = list(frag.tags.exclude(category='book')
339 for child in book.children.all():
340 affected_tags.update(fix_subtree(child, sub_parent_tags))
345 while parent is not None:
346 parent_tags.append(parent.book_tag())
347 parent = parent.parent
349 affected_tags = fix_subtree(self, parent_tags)
350 for tag in affected_tags:
354 while book is not None:
355 book.reset_tag_counter()
356 book.reset_theme_counter()
359 def cover_info(self, inherit=True):
360 """Returns a dictionary to serve as fallback for BookInfo.
362 For now, the only thing inherited is the cover image.
366 for field in ('cover_url', 'cover_by', 'cover_source'):
367 val = self.extra_info.get(field)
372 if inherit and need and self.parent is not None:
373 parent_info = self.parent.cover_info()
374 parent_info.update(info)
378 def parent_cover_changed(self):
379 """Called when parent book's cover image is changed."""
380 if not self.cover_info(inherit=False):
381 if 'cover' not in app_settings.DONT_BUILD:
382 self.cover.build_delay()
383 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
384 if format_ not in app_settings.DONT_BUILD:
385 getattr(self, '%s_file' % format_).build_delay()
386 for child in self.children.all():
387 child.parent_cover_changed()
389 def related_info(self):
390 """Keeps info about related objects (tags, media) in cache field."""
391 if self._related_info is not None:
392 return self._related_info
394 rel = {'tags': {}, 'media': {}}
396 tags = self.tags.filter(category__in=(
397 'author', 'kind', 'genre', 'epoch'))
398 tags = split_tags(tags)
399 for category in tags:
400 rel['tags'][category] = [
401 (t.name, t.slug) for t in tags[category]]
403 for media_format in BookMedia.formats:
404 rel['media'][media_format] = self.has_media(media_format)
409 parents.append((book.parent.title, book.parent.slug))
411 parents = parents[::-1]
413 rel['parents'] = parents
416 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
419 def related_themes(self):
420 theme_counter = self.theme_counter
421 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
422 for tag in book_themes:
423 tag.count = theme_counter[tag.pk]
426 def reset_tag_counter(self):
430 cache_key = "Book.tag_counter/%d" % self.id
431 permanent_cache.delete(cache_key)
433 self.parent.reset_tag_counter()
436 def tag_counter(self):
438 cache_key = "Book.tag_counter/%d" % self.id
439 tags = permanent_cache.get(cache_key)
445 for child in self.children.all().order_by().iterator():
446 for tag_pk, value in child.tag_counter.iteritems():
447 tags[tag_pk] = tags.get(tag_pk, 0) + value
448 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
452 permanent_cache.set(cache_key, tags)
455 def reset_theme_counter(self):
459 cache_key = "Book.theme_counter/%d" % self.id
460 permanent_cache.delete(cache_key)
462 self.parent.reset_theme_counter()
465 def theme_counter(self):
467 cache_key = "Book.theme_counter/%d" % self.id
468 tags = permanent_cache.get(cache_key)
474 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
475 for tag in fragment.tags.filter(category='theme').order_by().iterator():
476 tags[tag.pk] = tags.get(tag.pk, 0) + 1
479 permanent_cache.set(cache_key, tags)
482 def pretty_title(self, html_links=False):
484 names = list(book.tags.filter(category='author'))
490 names.extend(reversed(books))
493 names = ['<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in names]
495 names = [tag.name for tag in names]
497 return ', '.join(names)
500 def tagged_top_level(cls, tags):
501 """ Returns top-level books tagged with `tags`.
503 It only returns those books which don't have ancestors which are
504 also tagged with those tags.
507 # get relevant books and their tags
508 objects = cls.tagged.with_all(tags)
509 # eliminate descendants
510 l_tags = Tag.objects.filter(category='book',
511 slug__in=[book.book_tag_slug() for book in objects.iterator()])
512 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).iterator()]
514 objects = objects.exclude(pk__in=descendants_keys)
519 def book_list(cls, filter=None):
520 """Generates a hierarchical listing of all books.
522 Books are optionally filtered with a test function.
527 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
528 'title', 'parent', 'slug')
530 books = books.filter(filter).distinct()
532 book_ids = set(b['pk'] for b in books.values("pk").iterator())
533 for book in books.iterator():
534 parent = book.parent_id
535 if parent not in book_ids:
537 books_by_parent.setdefault(parent, []).append(book)
539 for book in books.iterator():
540 books_by_parent.setdefault(book.parent_id, []).append(book)
543 books_by_author = SortedDict()
544 for tag in Tag.objects.filter(category='author').iterator():
545 books_by_author[tag] = []
547 for book in books_by_parent.get(None,()):
548 authors = list(book.tags.filter(category='author'))
550 for author in authors:
551 books_by_author[author].append(book)
555 return books_by_author, orphans, books_by_parent
558 "SP1": (1, u"szkoła podstawowa"),
559 "SP2": (1, u"szkoła podstawowa"),
560 "P": (1, u"szkoła podstawowa"),
561 "G": (2, u"gimnazjum"),
563 "LP": (3, u"liceum"),
565 def audiences_pl(self):
566 audiences = self.extra_info.get('audiences', [])
567 audiences = sorted(set([self._audiences_pl[a] for a in audiences]))
568 return [a[1] for a in audiences]
570 def choose_fragment(self):
571 tag = self.book_tag()
572 fragments = Fragment.tagged.with_any([tag])
573 if fragments.exists():
574 return fragments.order_by('?')[0]
576 return self.parent.choose_fragment()
581 # add the file fields
582 for format_ in Book.formats:
583 field_name = "%s_file" % format_
584 EbookField(format_, _("%s file" % format_.upper()),
585 upload_to=book_upload_path(format_),
586 blank=True, default='').contribute_to_class(Book, field_name)