Update the docs to show how badly are changes needed.
[wolnelektury.git] / apps / catalogue / models / book.py
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.
4 #
5 import re
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 _
13 import jsonfield
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
21
22
23 permanent_cache = get_cache('permanent')
24
25
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,
32             unique=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
44
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']
52
53     parent = models.ForeignKey('self', blank=True, null=True,
54         related_name='children')
55
56     _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
57
58     objects  = models.Manager()
59     tagged   = managers.ModelTaggedItemManager(Tag)
60     tags     = managers.TagDescriptor(Tag)
61
62     html_built = django.dispatch.Signal()
63     published = django.dispatch.Signal()
64
65     class AlreadyExists(Exception):
66         pass
67
68     class Meta:
69         ordering = ('sort_key',)
70         verbose_name = _('book')
71         verbose_name_plural = _('books')
72         app_label = 'catalogue'
73
74     def __unicode__(self):
75         return self.title
76
77     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
78         from sortify import sortify
79
80         self.sort_key = sortify(self.title)
81         self.title = unicode(self.title) # ???
82
83         ret = super(Book, self).save(force_insert, force_update, **kwargs)
84
85         if reset_short_html:
86             self.reset_short_html()
87
88         return ret
89
90     @permalink
91     def get_absolute_url(self):
92         return ('catalogue.views.book_detail', [self.slug])
93
94     @staticmethod
95     @permalink
96     def create_url(slug):
97         return ('catalogue.views.book_detail', [slug])
98
99     @property
100     def name(self):
101         return self.title
102
103     def language_code(self):
104         return constants.LANGUAGES_3TO2.get(self.language, self.language)
105
106     def language_name(self):
107         return dict(settings.LANGUAGES).get(self.language_code(), "")
108
109     def book_tag_slug(self):
110         return ('l-' + self.slug)[:120]
111
112     def book_tag(self):
113         slug = self.book_tag_slug()
114         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
115         if created:
116             book_tag.name = self.title[:50]
117             book_tag.sort_key = self.title.lower()
118             book_tag.save()
119         return book_tag
120
121     def has_media(self, type_):
122         if type_ in Book.formats:
123             return bool(getattr(self, "%s_file" % type_))
124         else:
125             return self.media.filter(type=type_).exists()
126
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_)
131             else:                                             
132                 return self.media.filter(type=type_)
133         else:
134             return None
135
136     def get_mp3(self):
137         return self.get_media("mp3")
138     def get_odt(self):
139         return self.get_media("odt")
140     def get_ogg(self):
141         return self.get_media("ogg")
142     def get_daisy(self):
143         return self.get_media("daisy")                       
144
145     def reset_short_html(self):
146         if self.id is None:
147             return
148
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()
153
154         try: 
155             author = self.tags.filter(category='author')[0].sort_key
156         except IndexError:
157             author = u''
158         type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
159
160
161
162     def has_description(self):
163         return len(self.description) > 0
164     has_description.short_description = _('description')
165     has_description.boolean = True
166
167     # ugly ugly ugly
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
172
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
177
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
182
183     def wldocument(self, parse_dublincore=True, inherit=True):
184         from catalogue.import_utils import ORMDocProvider
185         from librarian.parser import WLDocument
186
187         if inherit and self.parent:
188             meta_fallbacks = self.parent.cover_info()
189         else:
190             meta_fallbacks = None
191
192         return WLDocument.from_file(self.xml_file.path,
193                 provider=ORMDocProvider(self),
194                 parse_dublincore=parse_dublincore,
195                 meta_fallbacks=meta_fallbacks)
196
197     @staticmethod
198     def zip_format(format_):
199         def pretty_file_name(book):
200             return "%s/%s.%s" % (
201                 book.extra_info['author'],
202                 book.slug,
203                 format_)
204
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_])
210
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_))
215
216     def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
217         import search
218         if index is None:
219             index = search.Index()
220         try:
221             index.index_book(self, book_info)
222             if index_tags:
223                 index.index_tags()
224             if commit:
225                 index.index.commit()
226         except Exception, e:
227             index.index.rollback()
228             raise e
229
230
231     @classmethod
232     def from_xml_file(cls, xml_file, **kwargs):
233         from django.core.files import File
234         from librarian import dcparser
235
236         # use librarian to parse meta-data
237         book_info = dcparser.parse(xml_file)
238
239         if not isinstance(xml_file, File):
240             xml_file = File(open(xml_file))
241
242         try:
243             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
244         finally:
245             xml_file.close()
246
247     @classmethod
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:
252             dont_build = set()
253         dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
254
255         # check for parts before we do anything
256         children = []
257         if hasattr(book_info, 'parts'):
258             for part_url in book_info.parts:
259                 try:
260                     children.append(Book.objects.get(slug=part_url.slug))
261                 except Book.DoesNotExist:
262                     raise Book.DoesNotExist(_('Book "%s" does not exist.') %
263                             part_url.slug)
264
265         # Read book metadata
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)
270
271         if created:
272             book_shelves = []
273             old_cover = None
274         else:
275             if not overwrite:
276                 raise Book.AlreadyExists(_('Book %s already exists') % (
277                         book_slug))
278             # Save shelves for this book
279             book_shelves = list(book.tags.filter(category='set'))
280             old_cover = book.cover_info()
281
282         # Save XML file
283         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
284
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
289         else:
290             book.common_slug = book.slug
291         book.extra_info = book_info.to_dict()
292         book.save()
293
294         meta_tags = Tag.tags_from_info(book_info)
295
296         book.tags = set(meta_tags + book_shelves)
297
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
306             child_book.save()
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:
311             child.parent = None
312             child.parent_number = 0
313             child.save()
314             tasks.fix_tree_tags.delay(child)
315             if old_cover:
316                 notify_cover_changed.append(child)
317
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()
326         
327         # No saves behind this point.
328
329         if has_own_text:
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()
336
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)
339
340         for child in notify_cover_changed:
341             child.parent_cover_changed()
342
343         cls.published.send(sender=book)
344         return book
345
346     def fix_tree_tags(self):
347         """Fixes the l-tags on the book's subtree.
348
349         Makes sure that:
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.
355         """
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')
363                                     ) + sub_parent_tags
364             for child in book.children.all():
365                 affected_tags.update(fix_subtree(child, sub_parent_tags))
366             return affected_tags
367
368         parent_tags = []
369         parent = self.parent
370         while parent is not None:
371             parent_tags.append(parent.book_tag())
372             parent = parent.parent
373
374         affected_tags = fix_subtree(self, parent_tags)
375         for tag in affected_tags:
376             tasks.touch_tag(tag)
377
378         book = self
379         while book is not None:
380             book.reset_tag_counter()
381             book.reset_theme_counter()
382             book = book.parent
383
384     def cover_info(self, inherit=True):
385         """Returns a dictionary to serve as fallback for BookInfo.
386
387         For now, the only thing inherited is the cover image.
388         """
389         need = False
390         info = {}
391         for field in ('cover_url', 'cover_by', 'cover_source'):
392             val = self.extra_info.get(field)
393             if val:
394                 info[field] = val
395             else:
396                 need = True
397         if inherit and need and self.parent is not None:
398             parent_info = self.parent.cover_info()
399             parent_info.update(info)
400             info = parent_info
401         return info
402
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()
414
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)
418
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
423         else:
424             rel = {'tags': {}, 'media': {}}
425
426             tags = self.tags.filter(category__in=(
427                     'author', 'kind', 'genre', 'epoch'))
428             tags = split_tags(tags)
429             for category in tags:
430                 cat = []
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)
435                         if tag_name:
436                             tag_info["name_%s" % lc] = tag_name
437                     cat.append(tag_info)
438                 rel['tags'][category] = cat
439
440             for media_format in BookMedia.formats:
441                 rel['media'][media_format] = self.has_media(media_format)
442
443             book = self
444             parents = []
445             while book.parent:
446                 parents.append((book.parent.title, book.parent.slug))
447                 book = book.parent
448             parents = parents[::-1]
449             if parents:
450                 rel['parents'] = parents
451
452             if self.pk:
453                 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
454             return rel
455
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]
461         return book_themes
462
463     def reset_tag_counter(self):
464         if self.id is None:
465             return
466
467         cache_key = "Book.tag_counter/%d" % self.id
468         permanent_cache.delete(cache_key)
469         if self.parent:
470             self.parent.reset_tag_counter()
471
472     @property
473     def tag_counter(self):
474         if self.id:
475             cache_key = "Book.tag_counter/%d" % self.id
476             tags = permanent_cache.get(cache_key)
477         else:
478             tags = None
479
480         if tags is None:
481             tags = {}
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():
486                 tags[tag.pk] = 1
487
488             if self.id:
489                 permanent_cache.set(cache_key, tags)
490         return tags
491
492     def reset_theme_counter(self):
493         if self.id is None:
494             return
495
496         cache_key = "Book.theme_counter/%d" % self.id
497         permanent_cache.delete(cache_key)
498         if self.parent:
499             self.parent.reset_theme_counter()
500
501     @property
502     def theme_counter(self):
503         if self.id:
504             cache_key = "Book.theme_counter/%d" % self.id
505             tags = permanent_cache.get(cache_key)
506         else:
507             tags = None
508
509         if tags is None:
510             tags = {}
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
514
515             if self.id:
516                 permanent_cache.set(cache_key, tags)
517         return tags
518
519     def pretty_title(self, html_links=False):
520         book = self
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', ())]
524         import logging
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()))
531
532         if html_links:
533             names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
534         else:
535             names = [tag[0] for tag in names]
536         return ', '.join(names)
537
538     @classmethod
539     def tagged_top_level(cls, tags):
540         """ Returns top-level books tagged with `tags`.
541
542         It only returns those books which don't have ancestors which are
543         also tagged with those tags.
544
545         """
546         # get relevant books and their tags
547         objects = cls.tagged.with_all(tags)
548         parents = objects.exclude(children=None).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()]
553         if descendants_keys:
554             objects = objects.exclude(pk__in=descendants_keys)
555
556         return objects
557
558     @classmethod
559     def book_list(cls, filter=None):
560         """Generates a hierarchical listing of all books.
561
562         Books are optionally filtered with a test function.
563
564         """
565
566         books_by_parent = {}
567         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
568                 'title', 'parent', 'slug')
569         if filter:
570             books = books.filter(filter).distinct()
571             
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:
576                     parent = None
577                 books_by_parent.setdefault(parent, []).append(book)
578         else:
579             for book in books.iterator():
580                 books_by_parent.setdefault(book.parent_id, []).append(book)
581
582         orphans = []
583         books_by_author = SortedDict()
584         for tag in Tag.objects.filter(category='author').iterator():
585             books_by_author[tag] = []
586
587         for book in books_by_parent.get(None,()):
588             authors = list(book.tags.filter(category='author'))
589             if authors:
590                 for author in authors:
591                     books_by_author[author].append(book)
592             else:
593                 orphans.append(book)
594
595         return books_by_author, orphans, books_by_parent
596
597     _audiences_pl = {
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"),
603         "L": (3, u"liceum"),
604         "LP": (3, u"liceum"),
605     }
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]
610
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]
616         elif self.parent:
617             return self.parent.choose_fragment()
618         else:
619             return None
620
621
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)