Merge branch 'obrazy' into rwd
[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     ebook_formats = constants.EBOOK_FORMATS
48     formats = ebook_formats + ['html', 'xml']
49
50     parent = models.ForeignKey('self', blank=True, null=True,
51         related_name='children')
52
53     _related_info = jsonfield.JSONField(blank=True, null=True, editable=False)
54
55     objects  = models.Manager()
56     tagged   = managers.ModelTaggedItemManager(Tag)
57     tags     = managers.TagDescriptor(Tag)
58
59     html_built = django.dispatch.Signal()
60     published = django.dispatch.Signal()
61
62     class AlreadyExists(Exception):
63         pass
64
65     class Meta:
66         ordering = ('sort_key',)
67         verbose_name = _('book')
68         verbose_name_plural = _('books')
69         app_label = 'catalogue'
70
71     def __unicode__(self):
72         return self.title
73
74     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
75         from sortify import sortify
76
77         self.sort_key = sortify(self.title)
78         self.title = unicode(self.title) # ???
79
80         ret = super(Book, self).save(force_insert, force_update, **kwargs)
81
82         if reset_short_html:
83             self.reset_short_html()
84
85         return ret
86
87     @permalink
88     def get_absolute_url(self):
89         return ('catalogue.views.book_detail', [self.slug])
90
91     @staticmethod
92     @permalink
93     def create_url(slug):
94         return ('catalogue.views.book_detail', [slug])
95
96     @property
97     def name(self):
98         return self.title
99
100     def language_code(self):
101         return constants.LANGUAGES_3TO2.get(self.language, self.language)
102
103     def language_name(self):
104         return dict(settings.LANGUAGES).get(self.language_code(), "")
105
106     def book_tag_slug(self):
107         return ('l-' + self.slug)[:120]
108
109     def book_tag(self):
110         slug = self.book_tag_slug()
111         book_tag, created = Tag.objects.get_or_create(slug=slug, category='book')
112         if created:
113             book_tag.name = self.title[:50]
114             book_tag.sort_key = self.title.lower()
115             book_tag.save()
116         return book_tag
117
118     def has_media(self, type_):
119         if type_ in Book.formats:
120             return bool(getattr(self, "%s_file" % type_))
121         else:
122             return self.media.filter(type=type_).exists()
123
124     def get_media(self, type_):
125         if self.has_media(type_):
126             if type_ in Book.formats:
127                 return getattr(self, "%s_file" % type_)
128             else:                                             
129                 return self.media.filter(type=type_)
130         else:
131             return None
132
133     def get_mp3(self):
134         return self.get_media("mp3")
135     def get_odt(self):
136         return self.get_media("odt")
137     def get_ogg(self):
138         return self.get_media("ogg")
139     def get_daisy(self):
140         return self.get_media("daisy")                       
141
142     def reset_short_html(self):
143         if self.id is None:
144             return
145
146         type(self).objects.filter(pk=self.pk).update(_related_info=None)
147         # Fragment.short_html relies on book's tags, so reset it here too
148         for fragm in self.fragments.all().iterator():
149             fragm.reset_short_html()
150
151         try: 
152             author = self.tags.filter(category='author')[0].sort_key
153         except IndexError:
154             author = u''
155         type(self).objects.filter(pk=self.pk).update(sort_key_author=author)
156
157
158
159     def has_description(self):
160         return len(self.description) > 0
161     has_description.short_description = _('description')
162     has_description.boolean = True
163
164     # ugly ugly ugly
165     def has_mp3_file(self):
166         return bool(self.has_media("mp3"))
167     has_mp3_file.short_description = 'MP3'
168     has_mp3_file.boolean = True
169
170     def has_ogg_file(self):
171         return bool(self.has_media("ogg"))
172     has_ogg_file.short_description = 'OGG'
173     has_ogg_file.boolean = True
174
175     def has_daisy_file(self):
176         return bool(self.has_media("daisy"))
177     has_daisy_file.short_description = 'DAISY'
178     has_daisy_file.boolean = True
179
180     def wldocument(self, parse_dublincore=True, inherit=True):
181         from catalogue.import_utils import ORMDocProvider
182         from librarian.parser import WLDocument
183
184         if inherit and self.parent:
185             meta_fallbacks = self.parent.cover_info()
186         else:
187             meta_fallbacks = None
188
189         return WLDocument.from_file(self.xml_file.path,
190                 provider=ORMDocProvider(self),
191                 parse_dublincore=parse_dublincore,
192                 meta_fallbacks=meta_fallbacks)
193
194     @staticmethod
195     def zip_format(format_):
196         def pretty_file_name(book):
197             return "%s/%s.%s" % (
198                 book.extra_info['author'],
199                 book.slug,
200                 format_)
201
202         field_name = "%s_file" % format_
203         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
204         paths = [(pretty_file_name(b), getattr(b, field_name).path)
205                     for b in books.iterator()]
206         return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
207
208     def zip_audiobooks(self, format_):
209         bm = BookMedia.objects.filter(book=self, type=format_)
210         paths = map(lambda bm: (None, bm.file.path), bm)
211         return create_zip(paths, "%s_%s" % (self.slug, format_))
212
213     def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
214         import search
215         if index is None:
216             index = search.Index()
217         try:
218             index.index_book(self, book_info)
219             if index_tags:
220                 index.index_tags()
221             if commit:
222                 index.index.commit()
223         except Exception, e:
224             index.index.rollback()
225             raise e
226
227
228     @classmethod
229     def from_xml_file(cls, xml_file, **kwargs):
230         from django.core.files import File
231         from librarian import dcparser
232
233         # use librarian to parse meta-data
234         book_info = dcparser.parse(xml_file)
235
236         if not isinstance(xml_file, File):
237             xml_file = File(open(xml_file))
238
239         try:
240             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
241         finally:
242             xml_file.close()
243
244     @classmethod
245     def from_text_and_meta(cls, raw_file, book_info, overwrite=False,
246             dont_build=None, search_index=True,
247             search_index_tags=True):
248         if dont_build is None:
249             dont_build = set()
250         dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
251
252         # check for parts before we do anything
253         children = []
254         if hasattr(book_info, 'parts'):
255             for part_url in book_info.parts:
256                 try:
257                     children.append(Book.objects.get(slug=part_url.slug))
258                 except Book.DoesNotExist:
259                     raise Book.DoesNotExist(_('Book "%s" does not exist.') %
260                             part_url.slug)
261
262         # Read book metadata
263         book_slug = book_info.url.slug
264         if re.search(r'[^a-z0-9-]', book_slug):
265             raise ValueError('Invalid characters in slug')
266         book, created = Book.objects.get_or_create(slug=book_slug)
267
268         if created:
269             book_shelves = []
270             old_cover = None
271         else:
272             if not overwrite:
273                 raise Book.AlreadyExists(_('Book %s already exists') % (
274                         book_slug))
275             # Save shelves for this book
276             book_shelves = list(book.tags.filter(category='set'))
277             old_cover = book.cover_info()
278
279         # Save XML file
280         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
281
282         book.language = book_info.language
283         book.title = book_info.title
284         if book_info.variant_of:
285             book.common_slug = book_info.variant_of.slug
286         else:
287             book.common_slug = book.slug
288         book.extra_info = book_info.to_dict()
289         book.save()
290
291         meta_tags = Tag.tags_from_info(book_info)
292
293         book.tags = set(meta_tags + book_shelves)
294
295         cover_changed = old_cover != book.cover_info()
296         obsolete_children = set(b for b in book.children.all()
297                                 if b not in children)
298         notify_cover_changed = []
299         for n, child_book in enumerate(children):
300             new_child = child_book.parent != book
301             child_book.parent = book
302             child_book.parent_number = n
303             child_book.save()
304             if new_child or cover_changed:
305                 notify_cover_changed.append(child_book)
306         # Disown unfaithful children and let them cope on their own.
307         for child in obsolete_children:
308             child.parent = None
309             child.parent_number = 0
310             child.save()
311             tasks.fix_tree_tags.delay(child)
312             if old_cover:
313                 notify_cover_changed.append(child)
314
315         # delete old fragments when overwriting
316         book.fragments.all().delete()
317         # Build HTML, fix the tree tags, build cover.
318         has_own_text = bool(book.html_file.build())
319         tasks.fix_tree_tags.delay(book)
320         if 'cover' not in dont_build:
321             book.cover.build_delay()
322         
323         # No saves behind this point.
324
325         if has_own_text:
326             for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
327                 if format_ not in dont_build:
328                     getattr(book, '%s_file' % format_).build_delay()
329         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
330             if format_ not in dont_build:
331                 getattr(book, '%s_file' % format_).build_delay()
332
333         if not settings.NO_SEARCH_INDEX and search_index:
334             tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
335
336         for child in notify_cover_changed:
337             child.parent_cover_changed()
338
339         cls.published.send(sender=book)
340         return book
341
342     def fix_tree_tags(self):
343         """Fixes the l-tags on the book's subtree.
344
345         Makes sure that:
346         * the book has its parents book-tags,
347         * its fragments have the book's and its parents book-tags,
348         * runs those for every child book too,
349         * touches all relevant tags,
350         * resets tag and theme counter on the book and its ancestry.
351         """
352         def fix_subtree(book, parent_tags):
353             affected_tags = set(book.tags)
354             book.tags = list(book.tags.exclude(category='book')) + parent_tags
355             sub_parent_tags = parent_tags + [book.book_tag()]
356             for frag in book.fragments.all():
357                 affected_tags.update(frag.tags)
358                 frag.tags = list(frag.tags.exclude(category='book')
359                                     ) + sub_parent_tags
360             for child in book.children.all():
361                 affected_tags.update(fix_subtree(child, sub_parent_tags))
362             return affected_tags
363
364         parent_tags = []
365         parent = self.parent
366         while parent is not None:
367             parent_tags.append(parent.book_tag())
368             parent = parent.parent
369
370         affected_tags = fix_subtree(self, parent_tags)
371         for tag in affected_tags:
372             tasks.touch_tag(tag)
373
374         book = self
375         while book is not None:
376             book.reset_tag_counter()
377             book.reset_theme_counter()
378             book = book.parent
379
380     def cover_info(self, inherit=True):
381         """Returns a dictionary to serve as fallback for BookInfo.
382
383         For now, the only thing inherited is the cover image.
384         """
385         need = False
386         info = {}
387         for field in ('cover_url', 'cover_by', 'cover_source'):
388             val = self.extra_info.get(field)
389             if val:
390                 info[field] = val
391             else:
392                 need = True
393         if inherit and need and self.parent is not None:
394             parent_info = self.parent.cover_info()
395             parent_info.update(info)
396             info = parent_info
397         return info
398
399     def parent_cover_changed(self):
400         """Called when parent book's cover image is changed."""
401         if not self.cover_info(inherit=False):
402             if 'cover' not in app_settings.DONT_BUILD:
403                 self.cover.build_delay()
404             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
405                 if format_ not in app_settings.DONT_BUILD:
406                     getattr(self, '%s_file' % format_).build_delay()
407             for child in self.children.all():
408                 child.parent_cover_changed()
409
410     def other_versions(self):
411         """Find other versions (i.e. in other languages) of the book."""
412         return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
413
414     def related_info(self):
415         """Keeps info about related objects (tags, media) in cache field."""
416         if self._related_info is not None:
417             return self._related_info
418         else:
419             rel = {'tags': {}, 'media': {}}
420
421             tags = self.tags.filter(category__in=(
422                     'author', 'kind', 'genre', 'epoch'))
423             tags = split_tags(tags)
424             for category in tags:
425                 cat = []
426                 for tag in tags[category]:
427                     tag_info = {'slug': tag.slug, 'name': tag.name}
428                     for lc, ln in settings.LANGUAGES:
429                         tag_name = getattr(tag, "name_%s" % lc)
430                         if tag_name:
431                             tag_info["name_%s" % lc] = tag_name
432                     cat.append(tag_info)
433                 rel['tags'][category] = cat
434
435             for media_format in BookMedia.formats:
436                 rel['media'][media_format] = self.has_media(media_format)
437
438             book = self
439             parents = []
440             while book.parent:
441                 parents.append((book.parent.title, book.parent.slug))
442                 book = book.parent
443             parents = parents[::-1]
444             if parents:
445                 rel['parents'] = parents
446
447             if self.pk:
448                 type(self).objects.filter(pk=self.pk).update(_related_info=rel)
449             return rel
450
451     def related_themes(self):
452         theme_counter = self.theme_counter
453         book_themes = list(Tag.objects.filter(pk__in=theme_counter.keys()))
454         for tag in book_themes:
455             tag.count = theme_counter[tag.pk]
456         return book_themes
457
458     def reset_tag_counter(self):
459         if self.id is None:
460             return
461
462         cache_key = "Book.tag_counter/%d" % self.id
463         permanent_cache.delete(cache_key)
464         if self.parent:
465             self.parent.reset_tag_counter()
466
467     @property
468     def tag_counter(self):
469         if self.id:
470             cache_key = "Book.tag_counter/%d" % self.id
471             tags = permanent_cache.get(cache_key)
472         else:
473             tags = None
474
475         if tags is None:
476             tags = {}
477             for child in self.children.all().order_by().iterator():
478                 for tag_pk, value in child.tag_counter.iteritems():
479                     tags[tag_pk] = tags.get(tag_pk, 0) + value
480             for tag in self.tags.exclude(category__in=('book', 'theme', 'set')).order_by().iterator():
481                 tags[tag.pk] = 1
482
483             if self.id:
484                 permanent_cache.set(cache_key, tags)
485         return tags
486
487     def reset_theme_counter(self):
488         if self.id is None:
489             return
490
491         cache_key = "Book.theme_counter/%d" % self.id
492         permanent_cache.delete(cache_key)
493         if self.parent:
494             self.parent.reset_theme_counter()
495
496     @property
497     def theme_counter(self):
498         if self.id:
499             cache_key = "Book.theme_counter/%d" % self.id
500             tags = permanent_cache.get(cache_key)
501         else:
502             tags = None
503
504         if tags is None:
505             tags = {}
506             for fragment in Fragment.tagged.with_any([self.book_tag()]).order_by().iterator():
507                 for tag in fragment.tags.filter(category='theme').order_by().iterator():
508                     tags[tag.pk] = tags.get(tag.pk, 0) + 1
509
510             if self.id:
511                 permanent_cache.set(cache_key, tags)
512         return tags
513
514     def pretty_title(self, html_links=False):
515         book = self
516         rel_info = book.related_info()
517         names = [(related_tag_name(tag), Tag.create_url('author', tag['slug']))
518                     for tag in rel_info['tags'].get('author', ())]
519         import logging
520         logging.info("%s, %s" % (book.slug, unicode(rel_info['tags'].get('author', ()))))
521         if 'parents' in rel_info:
522             books = [(name, Book.create_url(slug))
523                         for name, slug in rel_info['parents']]
524             names.extend(reversed(books))
525         names.append((self.title, self.get_absolute_url()))
526
527         if html_links:
528             names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
529         else:
530             names = [tag[0] for tag in names]
531         return ', '.join(names)
532
533     @classmethod
534     def tagged_top_level(cls, tags):
535         """ Returns top-level books tagged with `tags`.
536
537         It only returns those books which don't have ancestors which are
538         also tagged with those tags.
539
540         """
541         # get relevant books and their tags
542         objects = cls.tagged.with_all(tags)
543         parents = objects.filter(html_file='').only('slug')
544         # eliminate descendants
545         l_tags = Tag.objects.filter(category='book',
546             slug__in=[book.book_tag_slug() for book in parents.iterator()])
547         descendants_keys = [book.pk for book in cls.tagged.with_any(l_tags).only('pk').iterator()]
548         if descendants_keys:
549             objects = objects.exclude(pk__in=descendants_keys)
550
551         return objects
552
553     @classmethod
554     def book_list(cls, filter=None):
555         """Generates a hierarchical listing of all books.
556
557         Books are optionally filtered with a test function.
558
559         """
560
561         books_by_parent = {}
562         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
563                 'title', 'parent', 'slug')
564         if filter:
565             books = books.filter(filter).distinct()
566             
567             book_ids = set(b['pk'] for b in books.values("pk").iterator())
568             for book in books.iterator():
569                 parent = book.parent_id
570                 if parent not in book_ids:
571                     parent = None
572                 books_by_parent.setdefault(parent, []).append(book)
573         else:
574             for book in books.iterator():
575                 books_by_parent.setdefault(book.parent_id, []).append(book)
576
577         orphans = []
578         books_by_author = SortedDict()
579         for tag in Tag.objects.filter(category='author').iterator():
580             books_by_author[tag] = []
581
582         for book in books_by_parent.get(None,()):
583             authors = list(book.tags.filter(category='author'))
584             if authors:
585                 for author in authors:
586                     books_by_author[author].append(book)
587             else:
588                 orphans.append(book)
589
590         return books_by_author, orphans, books_by_parent
591
592     _audiences_pl = {
593         "SP": (1, u"szkoła podstawowa"),
594         "SP1": (1, u"szkoła podstawowa"),
595         "SP2": (1, u"szkoła podstawowa"),
596         "P": (1, u"szkoła podstawowa"),
597         "G": (2, u"gimnazjum"),
598         "L": (3, u"liceum"),
599         "LP": (3, u"liceum"),
600     }
601     def audiences_pl(self):
602         audiences = self.extra_info.get('audiences', [])
603         audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
604         return [a[1] for a in audiences]
605
606     def choose_fragment(self):
607         tag = self.book_tag()
608         fragments = Fragment.tagged.with_any([tag])
609         if fragments.exists():
610             return fragments.order_by('?')[0]
611         elif self.parent:
612             return self.parent.choose_fragment()
613         else:
614             return None
615
616
617 # add the file fields
618 for format_ in Book.formats:
619     field_name = "%s_file" % format_
620     EbookField(format_, _("%s file" % format_.upper()),
621             upload_to=book_upload_path(format_),
622             blank=True, default='').contribute_to_class(Book, field_name)