Using slug from identifier.url instead of generating it from title for newly imported...
[wolnelektury.git] / apps / catalogue / models.py
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
9
10 from newtagging.models import TagBase
11 from newtagging import managers
12
13 from librarian import html, dcparser
14
15
16 TAG_CATEGORIES = (
17     ('author', _('author')),
18     ('epoch', _('epoch')),
19     ('kind', _('kind')),
20     ('genre', _('genre')),
21     ('theme', _('theme')),
22     ('set', _('set')),
23 )
24
25
26 class TagSubcategoryManager(models.Manager):
27     def __init__(self, subcategory):
28         super(TagSubcategoryManager, self).__init__()
29         self.subcategory = subcategory
30         
31     def get_query_set(self):
32         return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
33
34
35 class Tag(TagBase):
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'))
43         
44     user = models.ForeignKey(User, blank=True, null=True)
45     
46     def has_description(self):
47         return len(self.description) > 0
48     has_description.short_description = _('description')
49     has_description.boolean = True
50
51     @permalink
52     def get_absolute_url(self):
53         return ('catalogue.views.tagged_object_list', [self.slug])
54     
55     class Meta:
56         ordering = ('sort_key',)
57         verbose_name = _('tag')
58         verbose_name_plural = _('tags')
59     
60     def __unicode__(self):
61         return self.name
62
63     @staticmethod
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]
68         else:
69             return TagBase.get_tag_list(tags)
70
71
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)
78     
79     # Formats
80     xml_file = models.FileField(_('XML file'), upload_to='books/xml', blank=True)
81     html_file = models.FileField(_('HTML file'), upload_to='books/html', blank=True)
82     pdf_file = models.FileField(_('PDF file'), upload_to='books/pdf', blank=True)
83     odt_file = models.FileField(_('ODT file'), upload_to='books/odt', blank=True)
84     txt_file = models.FileField(_('TXT file'), upload_to='books/txt', blank=True)
85     
86     parent = models.ForeignKey('self', blank=True, null=True, related_name='children')
87     
88     objects = models.Manager()
89     tagged = managers.ModelTaggedItemManager(Tag)
90     tags = managers.TagDescriptor(Tag)
91     
92     def short_html(self):
93         if len(self._short_html):
94             return mark_safe(self._short_html)
95         else:
96             tags = self.tags.filter(~Q(category__in=('set', 'theme')))
97             tags = [u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) for tag in tags]
98
99             formats = []
100             if self.html_file:
101                 formats.append(u'<a href="%s">Czytaj online</a>' % self.html_file.url)
102             if self.pdf_file:
103                 formats.append(u'<a href="%s">Plik PDF</a>' % self.pdf_file.url)
104             if self.odt_file:
105                 formats.append(u'<a href="%s">Plik ODT</a>' % self.odt_file.url)
106             
107             self._short_html = unicode(render_to_string('catalogue/book_short.html',
108                 {'book': self, 'tags': tags, 'formats': formats}))
109             self.save()
110             return mark_safe(self._short_html)
111     
112     def has_description(self):
113         return len(self.description) > 0
114     has_description.short_description = _('description')
115     has_description.boolean = True
116     
117     def has_pdf_file(self):
118         return bool(self.pdf_file)
119     has_pdf_file.short_description = 'PDF'
120     has_pdf_file.boolean = True
121     
122     def has_odt_file(self):
123         return bool(self.odt_file)
124     has_odt_file.short_description = 'ODT'
125     has_odt_file.boolean = True
126     
127     def has_html_file(self):
128         return bool(self.html_file)
129     has_html_file.short_description = 'HTML'
130     has_html_file.boolean = True
131
132     @staticmethod
133     def from_xml_file(xml_file):
134         from tempfile import NamedTemporaryFile
135         from slughifi import slughifi
136         from markupstring import MarkupString
137         
138         # Read book metadata
139         book_info = dcparser.parse(xml_file)
140         book_base, book_slug = book_info.url.rsplit('/', 1)
141         book = Book(title=book_info.title, slug=book_slug)
142         book.save()
143         
144         book_tags = []
145         for category in ('kind', 'genre', 'author', 'epoch'):    
146             tag_name = getattr(book_info, category)
147             tag_sort_key = tag_name
148             if category == 'author':
149                 tag_sort_key = tag_name.last_name
150                 tag_name = ' '.join(tag_name.first_names) + ' ' + tag_name.last_name
151             tag, created = Tag.objects.get_or_create(name=tag_name,
152                 slug=slughifi(tag_name), sort_key=slughifi(tag_sort_key), category=category)
153             tag.save()
154             book_tags.append(tag)
155         book.tags = book_tags
156         
157         if hasattr(book_info, 'parts'):
158             for part_url in book_info.parts:
159                 base, slug = part_url.rsplit('/', 1)
160                 child_book = Book.objects.get(slug=slug)
161                 child_book.parent = book
162                 child_book.save()
163         
164         # Save XML and HTML files
165         book.xml_file.save('%s.xml' % book.slug, File(file(xml_file)), save=False)
166         
167         html_file = NamedTemporaryFile()
168         html.transform(book.xml_file.path, html_file)
169         book.html_file.save('%s.html' % book.slug, File(html_file), save=False)
170         
171         # Extract fragments
172         closed_fragments, open_fragments = html.extract_fragments(book.html_file.path)
173         book_themes = []
174         for fragment in closed_fragments.values():
175             text = fragment.to_string()
176             short_text = ''
177             if (len(MarkupString(text)) > 240):
178                 short_text = unicode(MarkupString(text)[:160])
179             new_fragment = Fragment(text=text, short_text=short_text, anchor=fragment.id, book=book)
180                 
181             theme_names = [s.strip() for s in fragment.themes.split(',')]
182             themes = []
183             for theme_name in theme_names:
184                 tag, created = Tag.objects.get_or_create(name=theme_name,
185                     slug=slughifi(theme_name), sort_key=slughifi(theme_name), category='theme')
186                 tag.save()
187                 themes.append(tag)
188             new_fragment.save()
189             new_fragment.tags = list(book.tags) + themes
190             book_themes += themes
191         
192         book_themes = set(book_themes)
193         book.tags = list(book.tags) + list(book_themes)
194         return book.save()
195     
196     @permalink
197     def get_absolute_url(self):
198         return ('catalogue.views.book_detail', [self.slug])
199         
200     class Meta:
201         ordering = ('title',)
202         verbose_name = _('book')
203         verbose_name_plural = _('books')
204
205     def __unicode__(self):
206         return self.title
207
208
209 class Fragment(models.Model):
210     text = models.TextField()
211     short_text = models.TextField(editable=False)
212     _short_html = models.TextField(editable=False)
213     anchor = models.CharField(max_length=120)
214     book = models.ForeignKey(Book, related_name='fragments')
215
216     objects = models.Manager()
217     tagged = managers.ModelTaggedItemManager(Tag)
218     tags = managers.TagDescriptor(Tag)
219     
220     def short_html(self):
221         if len(self._short_html):
222             return mark_safe(self._short_html)
223         else:
224             book_authors = [u'<a href="%s">%s</a>' % (tag.get_absolute_url(), tag.name) 
225                 for tag in self.book.tags if tag.category == 'author']
226             
227             self._short_html = unicode(render_to_string('catalogue/fragment_short.html',
228                 {'fragment': self, 'book': self.book, 'book_authors': book_authors}))
229             self.save()
230             return mark_safe(self._short_html)
231         
232     class Meta:
233         ordering = ('book', 'anchor',)
234         verbose_name = _('fragment')
235         verbose_name_plural = _('fragments')
236