l10n
[redakcja.git] / apps / catalogue / models / book.py
1 # -*- coding: utf-8 -*-
2 #
3 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
4 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
5 #
6 from django.contrib.sites.models import Site
7 from django.db import models
8 from django.template.loader import render_to_string
9 from django.utils.translation import ugettext_lazy as _
10 from slughifi import slughifi
11 from librarian import NoDublinCore, ParseError, ValidationError
12 from librarian.dcparser import BookInfo
13
14 import apiclient
15 from catalogue.helpers import cached_in_field
16 from catalogue.models import BookPublishRecord, ChunkPublishRecord
17 from catalogue.signals import post_publish
18 from catalogue.tasks import refresh_instance
19 from catalogue.xml_tools import compile_text, split_xml
20
21
22 class Book(models.Model):
23     """ A document edited on the wiki """
24
25     title = models.CharField(_('title'), max_length=255, db_index=True)
26     slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
27     gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
28
29     #wl_slug = models.CharField(_('title'), max_length=255, null=True, db_index=True, editable=False)
30     parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
31     parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
32
33     # Cache
34     _short_html = models.TextField(null=True, blank=True, editable=False)
35     _single = models.NullBooleanField(editable=False, db_index=True)
36     _new_publishable = models.NullBooleanField(editable=False)
37     _published = models.NullBooleanField(editable=False)
38
39     # Managers
40     objects = models.Manager()
41
42     class NoTextError(BaseException):
43         pass
44
45     class Meta:
46         app_label = 'catalogue'
47         ordering = ['parent_number', 'title']
48         verbose_name = _('book')
49         verbose_name_plural = _('books')
50
51
52     # Representing
53     # ============
54
55     def __iter__(self):
56         return iter(self.chunk_set.all())
57
58     def __getitem__(self, chunk):
59         return self.chunk_set.all()[chunk]
60
61     def __len__(self):
62         return self.chunk_set.count()
63
64     def __nonzero__(self):
65         """
66             Necessary so that __len__ isn't used for bool evaluation.
67         """
68         return True
69
70     def __unicode__(self):
71         return self.title
72
73     @models.permalink
74     def get_absolute_url(self):
75         return ("catalogue_book", [self.slug])
76
77
78     # Creating & manipulating
79     # =======================
80
81     @classmethod
82     def create(cls, creator, text, *args, **kwargs):
83         b = cls.objects.create(*args, **kwargs)
84         b.chunk_set.all().update(creator=creator)
85         b[0].commit(text, author=creator)
86         return b
87
88     def add(self, *args, **kwargs):
89         """Add a new chunk at the end."""
90         return self.chunk_set.reverse()[0].split(*args, **kwargs)
91
92     @classmethod
93     def import_xml_text(cls, text=u'', previous_book=None,
94                 commit_args=None, **kwargs):
95         """Imports a book from XML, splitting it into chunks as necessary."""
96         texts = split_xml(text)
97         if previous_book:
98             instance = previous_book
99         else:
100             instance = cls(**kwargs)
101             instance.save()
102
103         # if there are more parts, set the rest to empty strings
104         book_len = len(instance)
105         for i in range(book_len - len(texts)):
106             texts.append((u'pusta część %d' % (i + 1), u''))
107
108         i = 0
109         for i, (title, text) in enumerate(texts):
110             if not title:
111                 title = u'część %d' % (i + 1)
112
113             slug = slughifi(title)
114
115             if i < book_len:
116                 chunk = instance[i]
117                 chunk.slug = slug[:50]
118                 chunk.title = title[:255]
119                 chunk.save()
120             else:
121                 chunk = instance.add(slug, title)
122
123             chunk.commit(text, **commit_args)
124
125         return instance
126
127     def make_chunk_slug(self, proposed):
128         """ 
129             Finds a chunk slug not yet used in the book.
130         """
131         slugs = set(c.slug for c in self)
132         i = 1
133         new_slug = proposed
134         while new_slug in slugs:
135             new_slug = "%s_%d" % (proposed, i)
136             i += 1
137         return new_slug
138
139     def append(self, other, slugs=None, titles=None):
140         """Add all chunks of another book to self."""
141         number = self[len(self) - 1].number + 1
142         len_other = len(other)
143         single = len_other == 1
144
145         if slugs is not None:
146             assert len(slugs) == len_other
147         if titles is not None:
148             assert len(titles) == len_other
149             if slugs is None:
150                 slugs = [slughifi(t) for t in titles]
151
152         for i, chunk in enumerate(other):
153             # move chunk to new book
154             chunk.book = self
155             chunk.number = number
156
157             if titles is None:
158                 # try some title guessing
159                 if other.title.startswith(self.title):
160                     other_title_part = other.title[len(self.title):].lstrip(' /')
161                 else:
162                     other_title_part = other.title
163
164                 if single:
165                     # special treatment for appending one-parters:
166                     # just use the guessed title and original book slug
167                     chunk.title = other_title_part
168                     if other.slug.startswith(self.slug):
169                         chunk_slug = other.slug[len(self.slug):].lstrip('-_')
170                     else:
171                         chunk_slug = other.slug
172                     chunk.slug = self.make_chunk_slug(chunk_slug)
173                 else:
174                     chunk.title = "%s, %s" % (other_title_part, chunk.title)
175             else:
176                 chunk.slug = slugs[i]
177                 chunk.title = titles[i]
178
179             chunk.slug = self.make_chunk_slug(chunk.slug)
180             chunk.save()
181             number += 1
182         other.delete()
183
184
185     # State & cache
186     # =============
187
188     def last_published(self):
189         try:
190             return self.publish_log.all()[0].timestamp
191         except IndexError:
192             return None
193
194     def assert_publishable(self):
195         assert self.chunk_set.exists(), _('No chunks in the book.')
196         try:
197             changes = self.get_current_changes(publishable=True)
198         except self.NoTextError:
199             raise AssertionError(_('Not all chunks have publishable revisions.'))
200         book_xml = self.materialize(changes=changes)
201
202         try:
203             bi = BookInfo.from_string(book_xml.encode('utf-8'))
204         except ParseError, e:
205             raise AssertionError(_('Invalid XML') + ': ' + str(e))
206         except NoDublinCore:
207             raise AssertionError(_('No Dublin Core found.'))
208         except ValidationError, e:
209             raise AssertionError(_('Invalid Dublin Core') + ': ' + str(e))
210
211         valid_about = "http://%s%s" % (Site.objects.get_current().domain, self.get_absolute_url())
212         assert bi.about == valid_about, _("rdf:about is not") + " " + valid_about
213
214     def hidden(self):
215         return self.slug.startswith('.')
216
217     def is_new_publishable(self):
218         """Checks if book is ready for publishing.
219
220         Returns True if there is a publishable version newer than the one
221         already published.
222
223         """
224         new_publishable = False
225         if not self.chunk_set.exists():
226             return False
227         for chunk in self:
228             change = chunk.publishable()
229             if not change:
230                 return False
231             if not new_publishable and not change.publish_log.exists():
232                 new_publishable = True
233         return new_publishable
234     new_publishable = cached_in_field('_new_publishable')(is_new_publishable)
235
236     def is_published(self):
237         return self.publish_log.exists()
238     published = cached_in_field('_published')(is_published)
239
240     def is_single(self):
241         return len(self) == 1
242     single = cached_in_field('_single')(is_single)
243
244     @cached_in_field('_short_html')
245     def short_html(self):
246         return render_to_string('catalogue/book_list/book.html', {'book': self})
247
248     def touch(self):
249         update = {
250             "_new_publishable": self.is_new_publishable(),
251             "_published": self.is_published(),
252             "_single": self.is_single(),
253             "_short_html": None,
254         }
255         Book.objects.filter(pk=self.pk).update(**update)
256         refresh_instance(self)
257
258     def refresh(self):
259         """This should be done offline."""
260         self.short_html
261         self.single
262         self.new_publishable
263         self.published
264
265     # Materializing & publishing
266     # ==========================
267
268     def get_current_changes(self, publishable=True):
269         """
270             Returns a list containing one Change for every Chunk in the Book.
271             Takes the most recent revision (publishable, if set).
272             Throws an error, if a proper revision is unavailable for a Chunk.
273         """
274         if publishable:
275             changes = [chunk.publishable() for chunk in self]
276         else:
277             changes = [chunk.head for chunk in self if chunk.head is not None]
278         if None in changes:
279             raise self.NoTextError('Some chunks have no available text.')
280         return changes
281
282     def materialize(self, publishable=False, changes=None):
283         """ 
284             Get full text of the document compiled from chunks.
285             Takes the current versions of all texts
286             or versions most recently tagged for publishing,
287             or a specified iterable changes.
288         """
289         if changes is None:
290             changes = self.get_current_changes(publishable)
291         return compile_text(change.materialize() for change in changes)
292
293     def publish(self, user):
294         """
295             Publishes a book on behalf of a (local) user.
296         """
297         self.assert_publishable()
298         changes = self.get_current_changes(publishable=True)
299         book_xml = self.materialize(changes=changes)
300         apiclient.api_call(user, "books/", {"book_xml": book_xml})
301         # record the publish
302         br = BookPublishRecord.objects.create(book=self, user=user)
303         for c in changes:
304             ChunkPublishRecord.objects.create(book_record=br, change=c)
305         post_publish.send(sender=br)