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