+from dvcs import models as dvcs_models
+from wiki.xml_tools import compile_text
+
+import logging
+logger = logging.getLogger("fnp.wiki")
+
+
+class Book(models.Model):
+ """ A document edited on the wiki """
+
+ title = models.CharField(_('title'), max_length=255)
+ slug = models.SlugField(_('slug'), max_length=128, unique=True)
+ gallery = models.CharField(_('scan gallery name'), max_length=255, blank=True)
+
+ parent = models.ForeignKey('self', null=True, blank=True, verbose_name=_('parent'), related_name="children")
+ parent_number = models.IntegerField(_('parent number'), null=True, blank=True, db_index=True)
+
+ _list_html = models.TextField(editable=False, null=True)
+
+ class NoTextError(BaseException):
+ pass
+
+ class Meta:
+ ordering = ['parent_number', 'title']
+ verbose_name = _('book')
+ verbose_name_plural = _('books')
+
+ def __unicode__(self):
+ return self.title
+
+ def get_absolute_url(self):
+ return reverse("wiki_book", args=[self.slug])
+
+ def save(self, reset_list_html=True, *args, **kwargs):
+ if reset_list_html:
+ self._list_html = None
+ return super(Book, self).save(*args, **kwargs)
+
+ @classmethod
+ def create(cls, creator=None, text=u'', *args, **kwargs):
+ """
+ >>> Book.create(slug='x', text='abc').materialize()
+ 'abc'
+ """
+ instance = cls(*args, **kwargs)
+ instance.save()
+ instance[0].commit(author=creator, text=text)
+ return instance
+
+ def __iter__(self):
+ return iter(self.chunk_set.all())
+
+ def __getitem__(self, chunk):
+ return self.chunk_set.all()[chunk]
+
+ def __len__(self):
+ return self.chunk_set.count()
+
+ def list_html(self):
+ if self._list_html is None:
+ print 'rendering', self.title
+ self._list_html = render_to_string('wiki/document_list_item.html',
+ {'book': self})
+ self.save(reset_list_html=False)
+ return mark_safe(self._list_html)
+
+ @staticmethod
+ def publish_tag():
+ return dvcs_models.Tag.get('publish')
+
+ def materialize(self, tag=None):
+ """
+ Get full text of the document compiled from chunks.
+ Takes the current versions of all texts
+ or versions most recently tagged by a given tag.
+ """
+ if tag:
+ changes = [chunk.last_tagged(tag) for chunk in self]