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