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