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