1 # -*- coding: utf-8 -*-
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.
6 from django.contrib.auth.models import User
7 from django.core.urlresolvers import reverse
8 from django.db import models
9 from django.utils.translation import ugettext_lazy as _
10 from django.db.utils import IntegrityError
12 from slughifi import slughifi
14 from dvcs import models as dvcs_models
15 from catalogue.xml_tools import compile_text, split_xml
18 logger = logging.getLogger("fnp.catalogue")
21 class Book(models.Model):
22 """ A document edited on the wiki """
24 title = models.CharField(_('title'), max_length=255, db_index=True)
25 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
26 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
28 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
29 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
31 class NoTextError(BaseException):
35 ordering = ['parent_number', 'title']
36 verbose_name = _('book')
37 verbose_name_plural = _('books')
38 permissions = [('can_pubmark', 'Can mark for publishing')]
40 def __unicode__(self):
43 def get_absolute_url(self):
44 return reverse("catalogue_book", args=[self.slug])
47 def import_xml_text(cls, text=u'', creator=None, previous_book=None,
50 texts = split_xml(text)
52 instance = previous_book
54 instance = cls(*args, **kwargs)
57 # if there are more parts, set the rest to empty strings
58 book_len = len(instance)
59 for i in range(book_len - len(texts)):
60 texts.append(u'pusta część %d' % (i + 1), u'')
63 for i, (title, text) in enumerate(texts):
65 title = u'część %d' % (i + 1)
67 slug = slughifi(title)
75 chunk = instance.add(slug, title, creator, adjust_slug=True)
77 chunk.commit(text, author=creator)
82 def create(cls, creator=None, text=u'', *args, **kwargs):
84 >>> Book.create(slug='x', text='abc').materialize()
87 instance = cls(*args, **kwargs)
89 instance[0].commit(text, author=creator)
93 return iter(self.chunk_set.all())
95 def __getitem__(self, chunk):
96 return self.chunk_set.all()[chunk]
99 return self.chunk_set.count()
101 def __nonzero__(self):
103 Necessary so that __len__ isn't used for bool evaluation.
107 def get_current_changes(self, publishable=True):
109 Returns a list containing one Change for every Chunk in the Book.
110 Takes the most recent revision (publishable, if set).
111 Throws an error, if a proper revision is unavailable for a Chunk.
114 changes = [chunk.publishable() for chunk in self]
116 changes = [chunk.head for chunk in self if chunk.head is not None]
118 raise self.NoTextError('Some chunks have no available text.')
121 def materialize(self, publishable=False, changes=None):
123 Get full text of the document compiled from chunks.
124 Takes the current versions of all texts
125 or versions most recently tagged for publishing,
126 or a specified iterable changes.
129 changes = self.get_current_changes(publishable)
130 return compile_text(change.materialize() for change in changes)
132 def publishable(self):
133 if not self.chunk_set.exists():
136 if not chunk.publishable():
140 def publish(self, user):
142 Publishes a book on behalf of a (local) user.
144 from apiclient import api_call
146 changes = self.get_current_changes(publishable=True)
147 book_xml = book.materialize(changes=changes)
148 #api_call(user, "books", {"book_xml": book_xml})
150 br = BookPublishRecord.objects.create(book=self, user=user)
152 ChunkPublishRecord.objects.create(book_record=br, change=c)
154 def make_chunk_slug(self, proposed):
156 Finds a chunk slug not yet used in the book.
158 slugs = set(c.slug for c in self)
161 while new_slug in slugs:
162 new_slug = "%s-%d" % (proposed, i)
166 def append(self, other):
167 """Add all chunks of another book to self."""
168 number = self[len(self) - 1].number + 1
169 single = len(other) == 1
171 # move chunk to new book
173 chunk.number = number
175 # try some title guessing
176 if other.title.startswith(self.title):
177 other_title_part = other.title[len(self.title):].lstrip(' /')
179 other_title_part = other.title
182 # special treatment for appending one-parters:
183 # just use the guessed title and original book slug
184 chunk.comment = other_title_part
185 if other.slug.startswith(self.slug):
186 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
188 chunk_slug = other.slug
189 chunk.slug = self.make_chunk_slug(chunk_slug)
191 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
192 chunk.slug = self.make_chunk_slug(chunk.slug)
197 def add(self, *args, **kwargs):
198 """Add a new chunk at the end."""
199 return self.chunk_set.reverse()[0].split(*args, **kwargs)
202 def listener_create(sender, instance, created, **kwargs):
204 instance.chunk_set.create(number=1, slug='1')
206 models.signals.post_save.connect(Book.listener_create, sender=Book)
209 class Chunk(dvcs_models.Document):
210 """ An editable chunk of text. Every Book text is divided into chunks. """
212 book = models.ForeignKey(Book, editable=False)
213 number = models.IntegerField()
214 slug = models.SlugField()
215 comment = models.CharField(max_length=255, blank=True)
218 unique_together = [['book', 'number'], ['book', 'slug']]
219 ordering = ['number']
221 def __unicode__(self):
222 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
224 def get_absolute_url(self):
225 return reverse("wiki_editor", args=[self.book.slug, self.slug])
228 def get(cls, slug, chunk=None):
230 return cls.objects.get(book__slug=slug, number=1)
232 return cls.objects.get(book__slug=slug, slug=chunk)
234 def pretty_name(self, book_length=None):
235 title = self.book.title
237 title += ", %s" % self.comment
239 title += " (%d/%d)" % (self.number, book_length)
242 def split(self, slug, comment='', creator=None, adjust_slug=False):
243 """ Create an empty chunk after this one """
244 self.book.chunk_set.filter(number__gt=self.number).update(
245 number=models.F('number')+1)
251 new_chunk = self.book.chunk_set.create(number=self.number+1,
252 creator=creator, slug=new_slug, comment=comment)
253 except IntegrityError:
256 new_slug = "%s_%d" % (slug, tries)
261 def listener_saved(sender, instance, created, **kwargs):
263 # save book so that its _list_html is reset
266 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
269 class BookPublishRecord(models.Model):
271 A record left after publishing a Book.
274 book = models.ForeignKey(Book)
275 timestamp = models.DateTimeField(auto_now_add=True)
276 user = models.ForeignKey(User)
279 ordering = ['-timestamp']
282 class ChunkPublishRecord(models.Model):
284 BookPublishRecord details for each Chunk.
287 book_record = models.ForeignKey(BookPublishRecord)
288 change = models.ForeignKey(Chunk.change_model)