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