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 _
11 from dvcs import models as dvcs_models
12 from catalogue.xml_tools import compile_text
15 logger = logging.getLogger("fnp.catalogue")
18 class Book(models.Model):
19 """ A document edited on the wiki """
21 title = models.CharField(_('title'), max_length=255, db_index=True)
22 slug = models.SlugField(_('slug'), max_length=128, unique=True, db_index=True)
23 gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
25 parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
26 parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
28 class NoTextError(BaseException):
32 ordering = ['parent_number', 'title']
33 verbose_name = _('book')
34 verbose_name_plural = _('books')
35 permissions = [('can_pubmark', 'Can mark for publishing')]
37 def __unicode__(self):
40 def get_absolute_url(self):
41 return reverse("catalogue_book", args=[self.slug])
44 def create(cls, creator=None, text=u'', *args, **kwargs):
46 >>> Book.create(slug='x', text='abc').materialize()
49 instance = cls(*args, **kwargs)
51 instance[0].commit(author=creator, text=text)
55 return iter(self.chunk_set.all())
57 def __getitem__(self, chunk):
58 return self.chunk_set.all()[chunk]
61 return self.chunk_set.count()
63 def __nonzero__(self):
65 Necessary so that __len__ isn't used for bool evaluation.
69 def get_current_changes(self, publishable=True):
71 Returns a list containing one Change for every Chunk in the Book.
72 Takes the most recent revision (publishable, if set).
73 Throws an error, if a proper revision is unavailable for a Chunk.
76 changes = [chunk.publishable() for chunk in self]
78 changes = [chunk.head for chunk in self]
80 raise self.NoTextError('Some chunks have no available text.')
83 def materialize(self, publishable=False, changes=None):
85 Get full text of the document compiled from chunks.
86 Takes the current versions of all texts
87 or versions most recently tagged for publishing,
88 or a specified iterable changes.
91 changes = self.get_current_changes(publishable)
92 return compile_text(change.materialize() for change in changes)
94 def publishable(self):
95 if not self.chunk_set.exists():
98 if not chunk.publishable():
102 def publish(self, user):
104 Publishes a book on behalf of a (local) user.
106 from apiclient import api_call
108 changes = self.get_current_changes(publishable=True)
109 book_xml = book.materialize(changes=changes)
110 #api_call(user, "books", {"book_xml": book_xml})
112 br = BookPublishRecord.objects.create(book=self, user=user)
114 ChunkPublishRecord.objects.create(book_record=br, change=c)
116 def make_chunk_slug(self, proposed):
118 Finds a chunk slug not yet used in the book.
120 slugs = set(c.slug for c in self)
123 while new_slug in slugs:
124 new_slug = "%s-%d" % (proposed, i)
128 def append(self, other):
129 number = self[len(self) - 1].number + 1
130 single = len(other) == 1
132 # move chunk to new book
134 chunk.number = number
136 # try some title guessing
137 if other.title.startswith(self.title):
138 other_title_part = other.title[len(self.title):].lstrip(' /')
140 other_title_part = other.title
143 # special treatment for appending one-parters:
144 # just use the guessed title and original book slug
145 chunk.comment = other_title_part
146 if other.slug.startswith(self.slug):
147 chunk_slug = other.slug[len(self.slug):].lstrip('-_')
149 chunk_slug = other.slug
150 chunk.slug = self.make_chunk_slug(chunk_slug)
152 chunk.comment = "%s, %s" % (other_title_part, chunk.comment)
153 chunk.slug = self.make_chunk_slug(chunk.slug)
159 def listener_create(sender, instance, created, **kwargs):
161 instance.chunk_set.create(number=1, slug='1')
163 models.signals.post_save.connect(Book.listener_create, sender=Book)
166 class Chunk(dvcs_models.Document):
167 """ An editable chunk of text. Every Book text is divided into chunks. """
169 book = models.ForeignKey(Book, editable=False)
170 number = models.IntegerField()
171 slug = models.SlugField()
172 comment = models.CharField(max_length=255, blank=True)
175 unique_together = [['book', 'number'], ['book', 'slug']]
176 ordering = ['number']
178 def __unicode__(self):
179 return "%d-%d: %s" % (self.book_id, self.number, self.comment)
181 def get_absolute_url(self):
182 return reverse("wiki_editor", args=[self.book.slug, self.slug])
185 def get(cls, slug, chunk=None):
187 return cls.objects.get(book__slug=slug, number=1)
189 return cls.objects.get(book__slug=slug, slug=chunk)
191 def pretty_name(self, book_length=None):
192 title = self.book.title
194 title += ", %s" % self.comment
196 title += " (%d/%d)" % (self.number, book_length)
199 def split(self, slug, comment='', creator=None):
200 """ Create an empty chunk after this one """
201 self.book.chunk_set.filter(number__gt=self.number).update(
202 number=models.F('number')+1)
203 new_chunk = self.book.chunk_set.create(number=self.number+1,
204 creator=creator, slug=slug, comment=comment)
208 def listener_saved(sender, instance, created, **kwargs):
210 # save book so that its _list_html is reset
213 models.signals.post_save.connect(Chunk.listener_saved, sender=Chunk)
216 class BookPublishRecord(models.Model):
218 A record left after publishing a Book.
221 book = models.ForeignKey(Book)
222 timestamp = models.DateTimeField(auto_now_add=True)
223 user = models.ForeignKey(User)
226 ordering = ['-timestamp']
229 class ChunkPublishRecord(models.Model):
231 BookPublishRecord details for each Chunk.
234 book_record = models.ForeignKey(BookPublishRecord)
235 change = models.ForeignKey(Chunk.change_model)