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 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)
77 self.title = unicode(self.title) # ???
79 ret = super(Book, self).save(force_insert, force_update, **kwargs)
82 self.reset_short_html()
87 def get_absolute_url(self):
88 return ('catalogue.views.book_detail', [self.slug])
93 return ('catalogue.views.book_detail', [slug])
99 def book_tag_slug(self):
100 return ('l-' + self.slug)[:120]
103 slug = self.book_tag_slug()
104 book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
106 book_tag.name = self.title[:50]
107 book_tag.sort_key = self.title.lower()
111 def has_media(self, type_):
112 if type_ in Book.formats:
113 return bool(getattr(self, "%s_file" % type_))
115 return self.media.filter(type=type_).exists()
117 def get_media(self, type_):
118 if self.has_media(type_):
119 if type_ in Book.formats:
120 return getattr(self, "%s_file" % type_)
122 return self.media.filter(type=type_)
127 return self.get_media("mp3")
129 return self.get_media("odt")
131 return self.get_media("ogg")
133 return self.get_media("daisy")
135 def reset_short_html(self):
139 type(self).objects.filter(pk=self.pk).update(_related_info=None)
140 # Fragment.short_html relies on book's tags, so reset it here too
141 for fragm in self.fragments.all().iterator():
142 fragm.reset_short_html()
144 def has_description(self):
145 return len(self.description) > 0
146 has_description.short_description = _('description')
147 has_description.boolean = True
150 def has_mp3_file(self):
151 return bool(self.has_media("mp3"))
152 has_mp3_file.short_description = 'MP3'
153 has_mp3_file.boolean = True
155 def has_ogg_file(self):
156 return bool(self.has_media("ogg"))
157 has_ogg_file.short_description = 'OGG'
158 has_ogg_file.boolean = True
160 def has_daisy_file(self):
161 return bool(self.has_media("daisy"))
162 has_daisy_file.short_description = 'DAISY'
163 has_daisy_file.boolean = True
165 def wldocument(self, parse_dublincore=True, inherit=True):
166 from catalogue.import_utils import ORMDocProvider
167 from librarian.parser import WLDocument
169 if inherit and self.parent:
170 meta_fallbacks = self.parent.cover_info()
172 meta_fallbacks = None
174 return WLDocument.from_file(self.xml_file.path,
175 provider=ORMDocProvider(self),
176 parse_dublincore=parse_dublincore,
177 meta_fallbacks=meta_fallbacks)
180 def zip_format(format_):
181 def pretty_file_name(book):
182 return "%s/%s.%s" % (
183 book.extra_info['author'],
187 field_name = "%s_file" % format_
188 books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
189 paths = [(pretty_file_name(b), getattr(b, field_name).path)
190 for b in books.iterator()]
191 return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
193 def zip_audiobooks(self, format_):
194 bm = BookMedia.objects.filter(book=self, type=format_)
195 paths = map(lambda bm: (None, bm.file.path), bm)
196 return create_zip(paths, "%s_%s" % (self.slug, format_))
198 def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
201 index = search.Index()
203 index.index_book(self, book_info)
209 index.index.rollback()
214 def from_xml_file(cls, xml_file, **kwargs):
215 from django.core.files import File
216 from librarian import dcparser
218 # use librarian to parse meta-data
219 book_info = dcparser.parse(xml_file)
221 if not isinstance(xml_file, File):
222 xml_file = File(open(xml_file))
225 return cls.from_text_and_meta(xml_file, book_info, **kwargs)
230 def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
231 dont_build=None, search_index=True,
232 search_index_tags=True):
233 if dont_build is None:
235 dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
237 # check for parts before we do anything
239 if hasattr(book_info, 'parts'):
240 for part_url in book_info.parts:
242 children.append(Book.objects.get(slug=part_url.slug))
243 except Book.DoesNotExist:
244 raise Book.DoesNotExist(_('Book "%s" does not exist.') %
248 book_slug = book_info.url.slug
249 if re.search(r'[^a-z0-9-]', book_slug):
250 raise ValueError('Invalid characters in slug')
251 book, created = Book.objects.get_or_create(slug=book_slug)
258 raise Book.AlreadyExists(_('Book %s already exists') % (
260 # Save shelves for this book
261 book_shelves = list(book.tags.filter(category='set'))
262 old_cover = book.cover_info()
265 book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
267 book.language = book_info.language
268 book.title = book_info.title
269 if book_info.variant_of:
270 book.common_slug = book_info.variant_of.slug
272 book.common_slug = book.slug
273 book.extra_info = book_info.to_dict()
276 meta_tags = Tag.tags_from_info(book_info)
278 book.tags = set(meta_tags + book_shelves)
280 cover_changed = old_cover != book.cover_info()
281 obsolete_children = set(b for b in book.children.all()
282 if b not in children)
283 notify_cover_changed = []
284 for n, child_book in enumerate(children):
285 new_child = child_book.parent != book
286 child_book.parent = book
287 child_book.parent_number = n
289 if new_child or cover_changed:
290 notify_cover_changed.append(child_book)
291 # Disown unfaithful children and let them cope on their own.
292 for child in obsolete_children:
294 child.parent_number = 0
296 tasks.fix_tree_tags.delay(child)
298 notify_cover_changed.append(child)
300 # delete old fragments when overwriting
301 book.fragments.all().delete()
302 # Build HTML, fix the tree tags, build cover.
303 has_own_text = bool(book.html_file.build())
304 tasks.fix_tree_tags.delay(book)
305 if 'cover' not in dont_build:
306 book.cover.build_delay()
308 # No saves behind this point.
311 for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
312 if format_ not in dont_build:
313 getattr(book, '%s_file' % format_).build_delay()
314 for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
315 if format_ not in dont_build:
316 getattr(book, '%s_file' % format_).build_delay()
318 if not settings.NO_SEARCH_INDEX and search_index:
319 tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
321 for child in notify_cover_changed:
322 child.parent_cover_changed()
324 cls.published.send(sender=book)
327 def fix_tree_tags(self):
328 """Fixes the l-tags on the book's subtree.
331 * the book has its parents book-tags,
332 * its fragments have the book's and its parents book-tags,
333 * runs those for every child book too,
334 * touches all relevant tags,
335 * resets tag and theme counter on the book and its ancestry.
337 def fix_subtree(book, parent_tags):
338 affected_tags = set(book.tags)
339 book.tags = list(book.tags.exclude(category='book')) + parent_tags
340 sub_parent_tags = parent_tags + [book.book_tag()]
341 for frag in book.fragments.all():
342 affected_tags.update(frag.tags)
343 frag.tags = list(frag.tags.exclude(category='book')
345 for child in book.children.all():
346 affected_tags.update(fix_subtree(child, sub_parent_tags))
351 while parent is not None:
352 parent_tags.append(parent.book_tag())
353 parent = parent.parent
355 affected_tags = fix_subtree(self, parent_tags)
356 for tag in affected_tags:
360 while book is not None:
361 book.reset_tag_counter()
362 book.reset_theme_counter()
365 def cover_info(self, inherit=True):
366 """Returns a dictionary to serve as fallback for BookInfo.
368 For now, the only thing inherited is the cover image.
372 for field in ('cover_url', 'cover_by', 'cover_source'):
373 val = self.extra_info.get(field)
378 if inherit and need and self.parent is not None:
379 parent_info = self.parent.cover_info()
380 parent_info.update(info)
384 def parent_cover_changed(self):
385 """Called when parent book's cover image is changed."""
386 if not self.cover_info(inherit=False):
387 if 'cover' not in app_settings.DONT_BUILD:
388 self.cover.build_delay()
389 for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
390 if format_ not in app_settings.DONT_BUILD:
391 getattr(self, '%s_file' % format_).build_delay()
392 for child in self.children.all():
393 child.parent_cover_changed()
395 def related_info(self):
396 """Keeps info about related objects (tags, media) in cache field."""
397 if self._related_info is not None:
398 return self._related_info
400 rel = {'tags': {}, 'media': {}}
402 tags = self.tags.filter(category__in=(
403 'author', 'kind', 'genre', 'epoch'))
404 tags = split_tags(tags)
405 for category in tags:
407 for tag in tags[category]:
408 tag_info = {'slug': tag.slug}
409 for lc, ln in settings.LANGUAGES:
410 tag_name = getattr(tag, "name_%s" % lc)
412 tag_info["name_%s" % lc] = tag_name
414 rel['tags'][category] = cat
416 for media_format in BookMedia.formats:
417 rel['media'][media_format] = self.has_media(media_format)
422 parents.append((book.parent.title, book.parent.slug))
424 parents = parents[::-1]
426 rel['parents'] = parents
429 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
432 def related_themes(self):
433 theme_counter = self.theme_counter
434 book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
435 for tag in book_themes:
436 tag.count = theme_counter[tag.pk]
439 def reset_tag_counter(self):
443 cache_key = "Book.tag_counter/%d" % self.id
444 permanent_cache.delete(cache_key)
446 self.parent.reset_tag_counter()
449 def tag_counter(self):
451 cache_key = "Book.tag_counter/%d" % self.id
452 tags = permanent_cache.get(cache_key)
458 for child in self.children.all().order_by().iterator():
459 for tag_pk, value in child.tag_counter.iteritems():
460 tags[tag_pk] = tags.get(tag_pk, 0) + value
461 for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
465 permanent_cache.set(cache_key, tags)
468 def reset_theme_counter(self):
472 cache_key = "Book.theme_counter/%d" % self.id
473 permanent_cache.delete(cache_key)
475 self.parent.reset_theme_counter()
478 def theme_counter(self):
480 cache_key = "Book.theme_counter/%d" % self.id
481 tags = permanent_cache.get(cache_key)
487 for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
488 for tag in fragment.tags.filter(category='theme').order_by().iterator():
489 tags[tag.pk] = tags.get(tag.pk, 0) + 1
492 permanent_cache.set(cache_key, tags)
495 def pretty_title(self, html_links=False):
497 rel_info = book.related_info()
498 names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
499 for tag in rel_info['tags'].get('author', ())]
500 if 'parents' in rel_info:
501 books = [(name, Book.create_url(slug))
502 for name, slug in rel_info['parents']]
503 names.extend(reversed(books))
504 names.append((self.title, self.get_absolute_url()))
507 names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
509 names = [tag[0] for tag in names]
510 return ', '.join(names)
513 def tagged_top_level(cls, tags):
514 """ Returns top-level books tagged with `tags`.
516 It only returns those books which don't have ancestors which are
517 also tagged with those tags.
520 # get relevant books and their tags
521 objects = cls.tagged.with_all(tags)
522 parents = objects.filter(html_file='').only('slug')
523 # eliminate descendants
524 l_tags = Tag.objects.filter(category='book',
525 slug__in=[book.book_tag_slug() for book in parents.iterator()])
526 descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
528 objects = objects.exclude(pk__in=descendants_keys)
533 def book_list(cls, filter=None):
534 """Generates a hierarchical listing of all books.
536 Books are optionally filtered with a test function.
541 books = cls.objects.all().order_by('parent_number', 'sort_key').only(
542 'title', 'parent', 'slug')
544 books = books.filter(filter).distinct()
546 book_ids = set(b['pk'] for b in books.values("pk").iterator())
547 for book in books.iterator():
548 parent = book.parent_id
549 if parent not in book_ids:
551 books_by_parent.setdefault(parent, []).append(book)
553 for book in books.iterator():
554 books_by_parent.setdefault(book.parent_id, []).append(book)
557 books_by_author = SortedDict()
558 for tag in Tag.objects.filter(category='author').iterator():
559 books_by_author[tag] = []
561 for book in books_by_parent.get(None,()):
562 authors = list(book.tags.filter(category='author'))
564 for author in authors:
565 books_by_author[author].append(book)
569 return books_by_author, orphans, books_by_parent
572 "SP": (1, u"szkoła podstawowa"),
573 "SP1": (1, u"szkoła podstawowa"),
574 "SP2": (1, u"szkoła podstawowa"),
575 "P": (1, u"szkoła podstawowa"),
576 "G": (2, u"gimnazjum"),
578 "LP": (3, u"liceum"),
580 def audiences_pl(self):
581 audiences = self.extra_info.get('audiences', [])
582 audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
583 return [a[1] for a in audiences]
585 def choose_fragment(self):
586 tag = self.book_tag()
587 fragments = Fragment.tagged.with_any([tag])
588 if fragments.exists():
589 return fragments.order_by('?')[0]
591 return self.parent.choose_fragment()
596 # add the file fields
597 for format_ in Book.formats:
598 field_name = "%s_file" % format_
599 EbookField(format_, _("%s file" % format_.upper()),
600 upload_to=book_upload_path(format_),
601 blank=True, default='').contribute_to_class(Book, field_name)