1e54ffe355aaefe0a1bb91e5bc9cf9d7c17fe7f9
[wolnelektury.git] / catalogue / models.py
1 # -*- coding: utf-8 -*-
2 from django.db import models
3 from django.db.models import permalink
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
8 from newtagging.models import TagBase
9 from newtagging import managers
10
11 from librarian import html
12
13
14 TAG_CATEGORIES = (
15     ('author', _('author')),
16     ('epoch', _('epoch')),
17     ('kind', _('kind')),
18     ('genre', _('genre')),
19     ('theme', _('theme')),
20     ('set', _('set')),
21 )
22
23
24 class TagSubcategoryManager(models.Manager):
25     def __init__(self, subcategory):
26         super(TagSubcategoryManager, self).__init__()
27         self.subcategory = subcategory
28         
29     def get_query_set(self):
30         return super(TagSubcategoryManager, self).get_query_set().filter(category=self.subcategory)
31
32
33 class Tag(TagBase):
34     name = models.CharField(_('name'), max_length=50, unique=True, db_index=True)
35     slug = models.SlugField(_('slug'), unique=True, db_index=True)
36     sort_key = models.SlugField(_('sort key'), db_index=True)
37     category = models.CharField(_('category'), max_length=50, blank=False, null=False, 
38         db_index=True, choices=TAG_CATEGORIES)
39     description = models.TextField(blank=True)
40     
41     user = models.ForeignKey(User, blank=True, null=True)
42     
43     def has_description(self):
44         return len(self.description) > 0
45     has_description.short_description = _('Has description')
46     has_description.boolean = True
47
48     @permalink
49     def get_absolute_url(self):
50         return ('catalogue.views.tagged_book_list', [self.slug])
51     
52     class Meta:
53         ordering = ('sort_key',)
54         verbose_name = _('tag')
55         verbose_name_plural = _('tags')
56     
57     def __unicode__(self):
58         return self.name
59
60     @staticmethod
61     def get_tag_list(tags):
62         if isinstance(tags, basestring):
63             tag_slugs = tags.split('/')
64             return [Tag.objects.get(slug=slug) for slug in tag_slugs]
65         else:
66             return TagBase.get_tag_list(tags)
67
68
69 class Book(models.Model):
70     title = models.CharField(_('title'), max_length=120)
71     slug = models.SlugField(_('slug'), unique=True, db_index=True)
72     description = models.TextField(_('description'), blank=True)
73     created_at = models.DateTimeField(_('creation date'), auto_now=True)
74     
75     # Formats
76     xml_file = models.FileField(_('XML file'), upload_to='books/xml', blank=True)
77     pdf_file = models.FileField(_('PDF file'), upload_to='books/pdf', blank=True)
78     odt_file = models.FileField(_('ODT file'), upload_to='books/odt', blank=True)
79     html_file = models.FileField(_('HTML file'), upload_to='books/html', blank=True)
80     
81     objects = managers.ModelTaggedItemManager(Tag)
82     tags = managers.TagDescriptor(Tag)
83     
84     def has_description(self):
85         return len(self.description) > 0
86     has_description.short_description = _('description')
87     has_description.boolean = True
88     
89     def has_pdf_file(self):
90         return bool(self.pdf_file)
91     has_pdf_file.short_description = 'PDF'
92     has_pdf_file.boolean = True
93     
94     def has_odt_file(self):
95         return bool(self.odt_file)
96     has_odt_file.short_description = 'ODT'
97     has_odt_file.boolean = True
98     
99     def has_html_file(self):
100         return bool(self.html_file)
101     has_html_file.short_description = 'HTML'
102     has_html_file.boolean = True
103
104     @staticmethod
105     def from_xml_file(xml_file):
106         from tempfile import NamedTemporaryFile
107         from slughifi import slughifi
108         import dcparser
109         
110         book_info = dcparser.parse(xml_file)
111         book = Book(title=book_info.title, slug=slughifi(book_info.title))
112         book.save()
113         
114         book_tags = []
115         for category in ('kind', 'genre', 'author', 'epoch'):    
116             tag_name = getattr(book_info, category)
117             tag_sort_key = tag_name
118             if category == 'author':
119                 tag_sort_key = tag_name.last_name
120                 tag_name = ' '.join(tag_name.first_names) + ' ' + tag_name.last_name
121             tag, created = Tag.objects.get_or_create(name=tag_name,
122                 slug=slughifi(tag_name), sort_key=slughifi(tag_sort_key), category=category)
123             tag.save()
124             book_tags.append(tag)
125         book.tags = book_tags
126         
127         # Save XML and HTML files
128         book.xml_file.save('%s.xml' % book.slug, File(file(xml_file)), save=False)
129         
130         html_file = NamedTemporaryFile()
131         html.transform(book.xml_file.path, html_file)
132         book.html_file.save('%s.html' % book.slug, File(html_file), save=False)
133         
134         # Extract fragments
135         closed_fragments, open_fragments = html.extract_fragments(book.html_file.path)
136         book_themes = []
137         for fragment in closed_fragments.values():
138             new_fragment = Fragment(html=fragment.to_string(), short_html=fragment.to_string(),
139                 anchor=fragment.id, book=book)
140                 
141             theme_names = [s.strip() for s in fragment.themes.split(',')]
142             themes = []
143             for theme_name in theme_names:
144                 tag, created = Tag.objects.get_or_create(name=theme_name,
145                     slug=slughifi(theme_name), sort_key=slughifi(theme_name), category='theme')
146                 tag.save()
147                 themes.append(tag)
148             new_fragment.save()
149             new_fragment.tags = list(book.tags) + themes
150             book_themes += themes
151         
152         book_themes = set(book_themes)
153         book.tags = list(book.tags) + list(book_themes)
154         return book.save()
155     
156     @permalink
157     def get_absolute_url(self):
158         return ('catalogue.views.book_detail', [self.slug])
159         
160     class Meta:
161         ordering = ('title',)
162         verbose_name = _('book')
163         verbose_name_plural = _('books')
164
165     def __unicode__(self):
166         return self.title
167
168
169 class Fragment(models.Model):
170     html = models.TextField()
171     short_html = models.TextField()
172     anchor = models.IntegerField()
173     book = models.ForeignKey(Book, related_name='fragments')
174     
175     objects = managers.ModelTaggedItemManager(Tag)
176     tags = managers.TagDescriptor(Tag)
177     
178     class Meta:
179         ordering = ('book', 'anchor',)
180         verbose_name = _('fragment')
181         verbose_name_plural = _('fragments')
182