1 # -*- coding: utf-8 -*-
2 from django.db import models
3 from django.db.models import permalink, Q
4 from django.utils.translation import ugettext_lazy as _
5 from django.contrib.auth.models import User
6 from django.core.files import File
7 from django.template.loader import render_to_string
8 from django.utils.safestring import mark_safe
10 from newtagging.models import TagBase
11 from newtagging import managers
13 from librarian import html, dcparser
17 ('author', _('author')),
18 ('epoch', _('epoch')),
20 ('genre', _('genre')),
21 ('theme', _('theme')),
26 class TagSubcategoryManager(models.Manager):
27 def __init__(self, subcategory):
28 super(TagSubcategoryManager, self).__init__()
29 self.subcategory = subcategory
31 def get_query_set(self):
32 return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
36 name = models.CharField(_('name'), max_length=50, unique=True, db_index=True)
37 slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)
38 sort_key = models.SlugField(_('sort key'), max_length=120, db_index=True)
39 category = models.CharField(_('category'), max_length=50, blank=False, null=False,
40 db_index=True, choices=TAG_CATEGORIES)
41 description = models.TextField(_('description'), blank=True)
42 main_page = models.BooleanField(_('main page'), default=False, db_index=True, help_text=_('Show tag on main page'))
44 user = models.ForeignKey(User, blank=True, null=True)
46 def has_description(self):
47 return len(self.description) > 0
48 has_description.short_description = _('description')
49 has_description.boolean = True
52 def get_absolute_url(self):
53 return ('catalogue.views.tagged_object_list', [self.slug])
56 ordering = ('sort_key',)
57 verbose_name = _('tag')
58 verbose_name_plural = _('tags')
60 def __unicode__(self):
64 def get_tag_list(tags):
65 if isinstance(tags, basestring):
66 tag_slugs = tags.split('/')
67 return [Tag.objects.get(slug=slug) for slug in tag_slugs]
69 return TagBase.get_tag_list(tags)
72 class Book(models.Model):
73 title = models.CharField(_('title'), max_length=120)
74 slug = models.SlugField(_('slug'), max_length=120, unique=True, db_index=True)
75 description = models.TextField(_('description'), blank=True)
76 created_at = models.DateTimeField(_('creation date'), auto_now=True)
77 _short_html = models.TextField(_('short HTML'), editable=False)
80 xml_file = models.FileField(_('XML file'), upload_to='books/xml', blank=True)
81 pdf_file = models.FileField(_('PDF file'), upload_to='books/pdf', blank=True)
82 odt_file = models.FileField(_('ODT file'), upload_to='books/odt', blank=True)
83 html_file = models.FileField(_('HTML file'), upload_to='books/html', blank=True)
85 parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
87 objects = models.Manager()
88 tagged = managers.ModelTaggedItemManager(Tag)
89 tags = managers.TagDescriptor(Tag)
92 if len(self._short_html):
93 return mark_safe(self._short_html)
95 tags = self.tags.filter(~Q(category__in=('set', 'theme')))
96 tags = [u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in tags]
100 formats.append(u'<a href="%s">Czytaj online</a>' % self.html_file.url)
102 formats.append(u'<a href="%s">Plik PDF</a>' % self.pdf_file.url)
104 formats.append(u'<a href="%s">Plik ODT</a>' % self.odt_file.url)
106 self._short_html = unicode(render_to_string('catalogue/book_short.html',
107 {'book': self, 'tags': tags, 'formats': formats}))
109 return mark_safe(self._short_html)
111 def has_description(self):
112 return len(self.description) > 0
113 has_description.short_description = _('description')
114 has_description.boolean = True
116 def has_pdf_file(self):
117 return bool(self.pdf_file)
118 has_pdf_file.short_description = 'PDF'
119 has_pdf_file.boolean = True
121 def has_odt_file(self):
122 return bool(self.odt_file)
123 has_odt_file.short_description = 'ODT'
124 has_odt_file.boolean = True
126 def has_html_file(self):
127 return bool(self.html_file)
128 has_html_file.short_description = 'HTML'
129 has_html_file.boolean = True
132 def from_xml_file(xml_file):
133 from tempfile import NamedTemporaryFile
134 from slughifi import slughifi
135 from markupstring import MarkupString
138 book_info = dcparser.parse(xml_file)
139 book = Book(title=book_info.title, slug=slughifi(book_info.title))
143 for category in ('kind', 'genre', 'author', 'epoch'):
144 tag_name = getattr(book_info, category)
145 tag_sort_key = tag_name
146 if category == 'author':
147 tag_sort_key = tag_name.last_name
148 tag_name = ' '.join(tag_name.first_names) + ' ' + tag_name.last_name
149 tag, created = Tag.objects.get_or_create(name=tag_name,
150 slug=slughifi(tag_name), sort_key=slughifi(tag_sort_key), category=category)
152 book_tags.append(tag)
153 book.tags = book_tags
155 if hasattr(book_info, 'parts'):
156 for part_url in book_info.parts:
157 base, slug = part_url.rsplit('/', 1)
158 child_book = Book.objects.get(slug=slug)
159 child_book.parent = book
162 # Save XML and HTML files
163 book.xml_file.save('%s.xml' % book.slug, File(file(xml_file)), save=False)
165 html_file = NamedTemporaryFile()
166 html.transform(book.xml_file.path, html_file)
167 book.html_file.save('%s.html' % book.slug, File(html_file), save=False)
170 closed_fragments, open_fragments = html.extract_fragments(book.html_file.path)
172 for fragment in closed_fragments.values():
173 text = fragment.to_string()
175 if (len(MarkupString(text)) > 240):
176 short_text = unicode(MarkupString(text)[:160])
177 new_fragment = Fragment(text=text, short_text=short_text, anchor=fragment.id, book=book)
179 theme_names = [s.strip() for s in fragment.themes.split(',')]
181 for theme_name in theme_names:
182 tag, created = Tag.objects.get_or_create(name=theme_name,
183 slug=slughifi(theme_name), sort_key=slughifi(theme_name), category='theme')
187 new_fragment.tags = list(book.tags) + themes
188 book_themes += themes
190 book_themes = set(book_themes)
191 book.tags = list(book.tags) + list(book_themes)
195 def get_absolute_url(self):
196 return ('catalogue.views.book_detail', [self.slug])
199 ordering = ('title',)
200 verbose_name = _('book')
201 verbose_name_plural = _('books')
203 def __unicode__(self):
207 class Fragment(models.Model):
208 text = models.TextField()
209 short_text = models.TextField(editable=False)
210 _short_html = models.TextField(editable=False)
211 anchor = models.CharField(max_length=120)
212 book = models.ForeignKey(Book, related_name='fragments')
214 objects = models.Manager()
215 tagged = managers.ModelTaggedItemManager(Tag)
216 tags = managers.TagDescriptor(Tag)
218 def short_html(self):
219 if len(self._short_html):
220 return mark_safe(self._short_html)
222 book_authors = [u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name)
223 for tag in self.book.tags if tag.category == 'author']
225 self._short_html = unicode(render_to_string('catalogue/fragment_short.html',
226 {'fragment': self, 'book': self.book, 'book_authors': book_authors}))
228 return mark_safe(self._short_html)
231 ordering = ('book', 'anchor',)
232 verbose_name = _('fragment')
233 verbose_name_plural = _('fragments')