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