fix #3671: litery alfabetu na liście kolekcji
[wolnelektury.git] / src / 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 from random import randint
7 import re
8 from django.conf import settings
9 from django.db import connection, models, transaction
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 ssify import flush_ssi_includes
18 from newtagging import managers
19 from catalogue import constants
20 from catalogue.fields import EbookField
21 from catalogue.models import Tag, Fragment, BookMedia
22 from catalogue.utils import create_zip
23 from catalogue import app_settings
24 from catalogue import tasks
25
26 bofh_storage = BofhFileSystemStorage()
27
28
29 def _make_upload_to(path):
30     def _upload_to(i, n):
31         return path % i.slug
32     return _upload_to
33
34
35 _cover_upload_to = _make_upload_to('book/cover/%s.jpg')
36 _cover_thumb_upload_to = _make_upload_to('book/cover_thumb/%s.jpg')
37
38
39 def _ebook_upload_to(upload_path):
40     return _make_upload_to(upload_path)
41
42
43 class Book(models.Model):
44     """Represents a book imported from WL-XML."""
45     title = models.CharField(_('title'), max_length=32767)
46     sort_key = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
47     sort_key_author = models.CharField(
48         _('sort key by author'), max_length=120, db_index=True, editable=False, default=u'')
49     slug = models.SlugField(_('slug'), max_length=120, db_index=True, unique=True)
50     common_slug = models.SlugField(_('slug'), max_length=120, db_index=True)
51     language = models.CharField(_('language code'), max_length=3, db_index=True, 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
60     # files generated during publication
61     cover = EbookField(
62         'cover', _('cover'),
63         null=True, blank=True,
64         upload_to=_cover_upload_to,
65         storage=bofh_storage, max_length=255)
66     # Cleaner version of cover for thumbs
67     cover_thumb = EbookField(
68         'cover_thumb', _('cover thumbnail'),
69         null=True, blank=True,
70         upload_to=_cover_thumb_upload_to,
71         max_length=255)
72     ebook_formats = constants.EBOOK_FORMATS
73     formats = ebook_formats + ['html', 'xml']
74
75     parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
76     ancestor = models.ManyToManyField('self', blank=True, editable=False, related_name='descendant', symmetrical=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     short_html_url_name = 'catalogue_book_short'
87
88     class AlreadyExists(Exception):
89         pass
90
91     class Meta:
92         ordering = ('sort_key',)
93         verbose_name = _('book')
94         verbose_name_plural = _('books')
95         app_label = 'catalogue'
96
97     def __unicode__(self):
98         return self.title
99
100     def get_initial(self):
101         try:
102             return re.search(r'\w', self.title, re.U).group(0)
103         except AttributeError:
104             return ''
105
106     def author_str(self):
107         return ", ".join(str(t) for t in self.tags.filter(category='author'))
108
109     def save(self, force_insert=False, force_update=False, **kwargs):
110         from sortify import sortify
111
112         self.sort_key = sortify(self.title)[:120]
113         self.title = unicode(self.title)  # ???
114
115         try:
116             author = self.tags.filter(category='author')[0].sort_key
117         except IndexError:
118             author = u''
119         self.sort_key_author = author
120
121         ret = super(Book, self).save(force_insert, force_update, **kwargs)
122
123         return ret
124
125     @permalink
126     def get_absolute_url(self):
127         return 'catalogue.views.book_detail', [self.slug]
128
129     @staticmethod
130     @permalink
131     def create_url(slug):
132         return 'catalogue.views.book_detail', [slug]
133
134     @property
135     def name(self):
136         return self.title
137
138     def language_code(self):
139         return constants.LANGUAGES_3TO2.get(self.language, self.language)
140
141     def language_name(self):
142         return dict(settings.LANGUAGES).get(self.language_code(), "")
143
144     def has_media(self, type_):
145         if type_ in Book.formats:
146             return bool(getattr(self, "%s_file" % type_))
147         else:
148             return self.media.filter(type=type_).exists()
149
150     def get_media(self, type_):
151         if self.has_media(type_):
152             if type_ in Book.formats:
153                 return getattr(self, "%s_file" % type_)
154             else:
155                 return self.media.filter(type=type_)
156         else:
157             return None
158
159     def get_mp3(self):
160         return self.get_media("mp3")
161
162     def get_odt(self):
163         return self.get_media("odt")
164
165     def get_ogg(self):
166         return self.get_media("ogg")
167
168     def get_daisy(self):
169         return self.get_media("daisy")
170
171     def has_description(self):
172         return len(self.description) > 0
173     has_description.short_description = _('description')
174     has_description.boolean = True
175
176     # ugly ugly ugly
177     def has_mp3_file(self):
178         return bool(self.has_media("mp3"))
179     has_mp3_file.short_description = 'MP3'
180     has_mp3_file.boolean = True
181
182     def has_ogg_file(self):
183         return bool(self.has_media("ogg"))
184     has_ogg_file.short_description = 'OGG'
185     has_ogg_file.boolean = True
186
187     def has_daisy_file(self):
188         return bool(self.has_media("daisy"))
189     has_daisy_file.short_description = 'DAISY'
190     has_daisy_file.boolean = True
191
192     def wldocument(self, parse_dublincore=True, inherit=True):
193         from catalogue.import_utils import ORMDocProvider
194         from librarian.parser import WLDocument
195
196         if inherit and self.parent:
197             meta_fallbacks = self.parent.cover_info()
198         else:
199             meta_fallbacks = None
200
201         return WLDocument.from_file(
202             self.xml_file.path,
203             provider=ORMDocProvider(self),
204             parse_dublincore=parse_dublincore,
205             meta_fallbacks=meta_fallbacks)
206
207     @staticmethod
208     def zip_format(format_):
209         def pretty_file_name(book):
210             return "%s/%s.%s" % (
211                 book.extra_info['author'],
212                 book.slug,
213                 format_)
214
215         field_name = "%s_file" % format_
216         books = Book.objects.filter(parent=None).exclude(**{field_name: ""})
217         paths = [(pretty_file_name(b), getattr(b, field_name).path) for b in books.iterator()]
218         return create_zip(paths, app_settings.FORMAT_ZIPS[format_])
219
220     def zip_audiobooks(self, format_):
221         bm = BookMedia.objects.filter(book=self, type=format_)
222         paths = map(lambda bm: (None, bm.file.path), bm)
223         return create_zip(paths, "%s_%s" % (self.slug, format_))
224
225     def search_index(self, book_info=None, index=None, index_tags=True, commit=True):
226         if index is None:
227             from search.index import Index
228             index = Index()
229         try:
230             index.index_book(self, book_info)
231             if index_tags:
232                 index.index_tags()
233             if commit:
234                 index.index.commit()
235         except Exception, e:
236             index.index.rollback()
237             raise e
238
239     @classmethod
240     def from_xml_file(cls, xml_file, **kwargs):
241         from django.core.files import File
242         from librarian import dcparser
243
244         # use librarian to parse meta-data
245         book_info = dcparser.parse(xml_file)
246
247         if not isinstance(xml_file, File):
248             xml_file = File(open(xml_file))
249
250         try:
251             return cls.from_text_and_meta(xml_file, book_info, **kwargs)
252         finally:
253             xml_file.close()
254
255     @classmethod
256     def from_text_and_meta(cls, raw_file, book_info, overwrite=False, dont_build=None, search_index=True,
257                            search_index_tags=True):
258         if dont_build is None:
259             dont_build = set()
260         dont_build = set.union(set(dont_build), set(app_settings.DONT_BUILD))
261
262         # check for parts before we do anything
263         children = []
264         if hasattr(book_info, 'parts'):
265             for part_url in book_info.parts:
266                 try:
267                     children.append(Book.objects.get(slug=part_url.slug))
268                 except Book.DoesNotExist:
269                     raise Book.DoesNotExist(_('Book "%s" does not exist.') % part_url.slug)
270
271         # Read book metadata
272         book_slug = book_info.url.slug
273         if re.search(r'[^a-z0-9-]', book_slug):
274             raise ValueError('Invalid characters in slug')
275         book, created = Book.objects.get_or_create(slug=book_slug)
276
277         if created:
278             book_shelves = []
279             old_cover = None
280         else:
281             if not overwrite:
282                 raise Book.AlreadyExists(_('Book %s already exists') % book_slug)
283             # Save shelves for this book
284             book_shelves = list(book.tags.filter(category='set'))
285             old_cover = book.cover_info()
286
287         # Save XML file
288         book.xml_file.save('%s.xml' % book.slug, raw_file, save=False)
289
290         book.language = book_info.language
291         book.title = book_info.title
292         if book_info.variant_of:
293             book.common_slug = book_info.variant_of.slug
294         else:
295             book.common_slug = book.slug
296         book.extra_info = book_info.to_dict()
297         book.save()
298
299         meta_tags = Tag.tags_from_info(book_info)
300
301         book.tags = set(meta_tags + book_shelves)
302
303         cover_changed = old_cover != book.cover_info()
304         obsolete_children = set(b for b in book.children.all()
305                                 if b not in children)
306         notify_cover_changed = []
307         for n, child_book in enumerate(children):
308             new_child = child_book.parent != book
309             child_book.parent = book
310             child_book.parent_number = n
311             child_book.save()
312             if new_child or cover_changed:
313                 notify_cover_changed.append(child_book)
314         # Disown unfaithful children and let them cope on their own.
315         for child in obsolete_children:
316             child.parent = None
317             child.parent_number = 0
318             child.save()
319             if old_cover:
320                 notify_cover_changed.append(child)
321
322         cls.repopulate_ancestors()
323         tasks.update_counters.delay()
324
325         # No saves beyond this point.
326
327         # Build cover.
328         if 'cover' not in dont_build:
329             book.cover.build_delay()
330             book.cover_thumb.build_delay()
331
332         # Build HTML and ebooks.
333         book.html_file.build_delay()
334         if not children:
335             for format_ in constants.EBOOK_FORMATS_WITHOUT_CHILDREN:
336                 if format_ not in dont_build:
337                     getattr(book, '%s_file' % format_).build_delay()
338         for format_ in constants.EBOOK_FORMATS_WITH_CHILDREN:
339             if format_ not in dont_build:
340                 getattr(book, '%s_file' % format_).build_delay()
341
342         if not settings.NO_SEARCH_INDEX and search_index:
343             tasks.index_book.delay(book.id, book_info=book_info, index_tags=search_index_tags)
344
345         for child in notify_cover_changed:
346             child.parent_cover_changed()
347
348         cls.published.send(sender=cls, instance=book)
349         return book
350
351     @classmethod
352     @transaction.atomic
353     def repopulate_ancestors(cls):
354         """Fixes the ancestry cache."""
355         # TODO: table names
356         cursor = connection.cursor()
357         if connection.vendor == 'postgres':
358             cursor.execute("TRUNCATE catalogue_book_ancestor")
359             cursor.execute("""
360                 WITH RECURSIVE ancestry AS (
361                     SELECT book.id, book.parent_id
362                     FROM catalogue_book AS book
363                     WHERE book.parent_id IS NOT NULL
364                     UNION
365                     SELECT ancestor.id, book.parent_id
366                     FROM ancestry AS ancestor, catalogue_book AS book
367                     WHERE ancestor.parent_id = book.id
368                         AND book.parent_id IS NOT NULL
369                     )
370                 INSERT INTO catalogue_book_ancestor
371                     (from_book_id, to_book_id)
372                     SELECT id, parent_id
373                     FROM ancestry
374                     ORDER BY id;
375                 """)
376         else:
377             cursor.execute("DELETE FROM catalogue_book_ancestor")
378             for b in cls.objects.exclude(parent=None):
379                 parent = b.parent
380                 while parent is not None:
381                     b.ancestor.add(parent)
382                     parent = parent.parent
383
384     def flush_includes(self, languages=True):
385         if not languages:
386             return
387         if languages is True:
388             languages = [lc for (lc, _ln) in settings.LANGUAGES]
389         flush_ssi_includes([
390             template % (self.pk, lang)
391             for template in [
392                 '/katalog/b/%d/mini.%s.html',
393                 '/katalog/b/%d/mini_nolink.%s.html',
394                 '/katalog/b/%d/short.%s.html',
395                 '/katalog/b/%d/wide.%s.html',
396                 '/api/include/book/%d.%s.json',
397                 '/api/include/book/%d.%s.xml',
398                 ]
399             for lang in languages
400             ])
401
402     def cover_info(self, inherit=True):
403         """Returns a dictionary to serve as fallback for BookInfo.
404
405         For now, the only thing inherited is the cover image.
406         """
407         need = False
408         info = {}
409         for field in ('cover_url', 'cover_by', 'cover_source'):
410             val = self.extra_info.get(field)
411             if val:
412                 info[field] = val
413             else:
414                 need = True
415         if inherit and need and self.parent is not None:
416             parent_info = self.parent.cover_info()
417             parent_info.update(info)
418             info = parent_info
419         return info
420
421     def related_themes(self):
422         return Tag.objects.usage_for_queryset(
423             Fragment.objects.filter(models.Q(book=self) | models.Q(book__ancestor=self)),
424             counts=True).filter(category='theme')
425
426     def parent_cover_changed(self):
427         """Called when parent book's cover image is changed."""
428         if not self.cover_info(inherit=False):
429             if 'cover' not in app_settings.DONT_BUILD:
430                 self.cover.build_delay()
431                 self.cover_thumb.build_delay()
432             for format_ in constants.EBOOK_FORMATS_WITH_COVERS:
433                 if format_ not in app_settings.DONT_BUILD:
434                     getattr(self, '%s_file' % format_).build_delay()
435             for child in self.children.all():
436                 child.parent_cover_changed()
437
438     def other_versions(self):
439         """Find other versions (i.e. in other languages) of the book."""
440         return type(self).objects.filter(common_slug=self.common_slug).exclude(pk=self.pk)
441
442     def parents(self):
443         books = []
444         parent = self.parent
445         while parent is not None:
446             books.insert(0, parent)
447             parent = parent.parent
448         return books
449
450     def pretty_title(self, html_links=False):
451         names = [(tag.name, tag.get_absolute_url()) for tag in self.tags.filter(category='author')]
452         books = self.parents() + [self]
453         names.extend([(b.title, b.get_absolute_url()) for b in books])
454
455         if html_links:
456             names = ['<a href="%s">%s</a>' % (tag[1], tag[0]) for tag in names]
457         else:
458             names = [tag[0] for tag in names]
459         return ', '.join(names)
460
461     @classmethod
462     def tagged_top_level(cls, tags):
463         """ Returns top-level books tagged with `tags`.
464
465         It only returns those books which don't have ancestors which are
466         also tagged with those tags.
467
468         """
469         objects = cls.tagged.with_all(tags)
470         return objects.exclude(ancestor__in=objects)
471
472     @classmethod
473     def book_list(cls, book_filter=None):
474         """Generates a hierarchical listing of all books.
475
476         Books are optionally filtered with a test function.
477
478         """
479
480         books_by_parent = {}
481         books = cls.objects.all().order_by('parent_number', 'sort_key').only(
482                 'title', 'parent', 'slug')
483         if book_filter:
484             books = books.filter(book_filter).distinct()
485
486             book_ids = set(b['pk'] for b in books.values("pk").iterator())
487             for book in books.iterator():
488                 parent = book.parent_id
489                 if parent not in book_ids:
490                     parent = None
491                 books_by_parent.setdefault(parent, []).append(book)
492         else:
493             for book in books.iterator():
494                 books_by_parent.setdefault(book.parent_id, []).append(book)
495
496         orphans = []
497         books_by_author = OrderedDict()
498         for tag in Tag.objects.filter(category='author').iterator():
499             books_by_author[tag] = []
500
501         for book in books_by_parent.get(None, ()):
502             authors = list(book.tags.filter(category='author'))
503             if authors:
504                 for author in authors:
505                     books_by_author[author].append(book)
506             else:
507                 orphans.append(book)
508
509         return books_by_author, orphans, books_by_parent
510
511     _audiences_pl = {
512         "SP": (1, u"szkoła podstawowa"),
513         "SP1": (1, u"szkoła podstawowa"),
514         "SP2": (1, u"szkoła podstawowa"),
515         "P": (1, u"szkoła podstawowa"),
516         "G": (2, u"gimnazjum"),
517         "L": (3, u"liceum"),
518         "LP": (3, u"liceum"),
519     }
520
521     def audiences_pl(self):
522         audiences = self.extra_info.get('audiences', [])
523         audiences = sorted(set([self._audiences_pl.get(a, (99, a)) for a in audiences]))
524         return [a[1] for a in audiences]
525
526     def stage_note(self):
527         stage = self.extra_info.get('stage')
528         if stage and stage < '0.4':
529             return (_('This work needs modernisation'),
530                     reverse('infopage', args=['wymagajace-uwspolczesnienia']))
531         else:
532             return None, None
533
534     def choose_fragment(self):
535         fragments = self.fragments.order_by()
536         fragments_count = fragments.count()
537         if not fragments_count and self.children.exists():
538             fragments = Fragment.objects.filter(book__ancestor=self).order_by()
539             fragments_count = fragments.count()
540         if fragments_count:
541             return fragments[randint(0, fragments_count - 1)]
542         elif self.parent:
543             return self.parent.choose_fragment()
544         else:
545             return None
546
547
548 def add_file_fields():
549     for format_ in Book.formats:
550         field_name = "%s_file" % format_
551         # This weird globals() assignment makes Django migrations comfortable.
552         _upload_to = _ebook_upload_to('book/%s/%%s.%s' % (format_, format_))
553         _upload_to.__name__ = '_%s_upload_to' % format_
554         globals()[_upload_to.__name__] = _upload_to
555
556         EbookField(
557             format_, _("%s file" % format_.upper()),
558             upload_to=_upload_to,
559             storage=bofh_storage,
560             max_length=255,
561             blank=True,
562             default=''
563         ).contribute_to_class(Book, field_name)
564
565 add_file_fields()