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