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