f87b2bf908b02afe6c3af5217caab894fe2b462f
[wolnelektury.git] / apps / picture / models.py
1 from django.db import models
2 import catalogue.models
3 from django.db.models import permalink
4 from sorl.thumbnail import ImageField
5 from django.conf import settings
6 from django.core.files.storage import FileSystemStorage
7 from django.utils.datastructures import SortedDict
8 from django.template.loader import render_to_string
9 from django.core.cache import cache
10 from catalogue.utils import split_tags
11 from django.utils.safestring import mark_safe
12 from librarian import dcparser, picture
13 from slughifi import slughifi
14
15 from django.utils.translation import ugettext_lazy as _
16 from newtagging import managers
17 from os import path
18
19
20 picture_storage = FileSystemStorage(location=path.join(settings.MEDIA_ROOT, 'pictures'), base_url=settings.MEDIA_URL + "pictures/")
21
22
23 class Picture(models.Model):
24     """
25     Picture resource.
26
27     """
28     title       = models.CharField(_('title'), max_length=120)
29     slug        = models.SlugField(_('slug'), max_length=120, db_index=True, unique=True)
30     sort_key    = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
31     created_at  = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
32     changed_at  = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
33     xml_file    = models.FileField('xml_file', upload_to="xml", storage=picture_storage)
34     image_file  = ImageField(_('image_file'), upload_to="images", storage=picture_storage)
35     objects     = models.Manager()
36     tagged      = managers.ModelTaggedItemManager(catalogue.models.Tag)
37     tags        = managers.TagDescriptor(catalogue.models.Tag)
38
39     class AlreadyExists(Exception):
40         pass
41
42     class Meta:
43         ordering = ('sort_key',)
44
45         verbose_name = _('picture')
46         verbose_name_plural = _('pictures')
47
48     URLID_RE = r'[a-z0-9-]+'
49     FILEID_RE = r'[a-z0-9-]+'
50
51     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
52         from sortify import sortify
53
54         self.sort_key = sortify(self.title)
55
56         ret = super(Picture, self).save(force_insert, force_update)
57
58         if reset_short_html:
59             self.reset_short_html()
60
61         return ret
62
63     def __unicode__(self):
64         return self.title
65
66     @permalink
67     def get_absolute_url(self):
68         return ('picture.views.picture_detail', [self.urlid()])
69
70     def urlid(self):
71         return self.slug
72
73     @classmethod
74     def from_xml_file(cls, xml_file, image_file=None, overwrite=False):
75         """
76         Import xml and it's accompanying image file.
77         """
78         from sortify import sortify
79         from django.core.files import File
80         from librarian.picture import WLPicture
81         close_xml_file = False
82
83         class SimpleImageStore(object):
84             def path(self_, slug, mime_type):
85                 """Returns the image file. Ignores slug ad mime_type."""
86                 return image_file
87
88         if not isinstance(xml_file, File):
89             xml_file = File(open(xml_file))
90             close_xml_file = True
91         try:
92             # use librarian to parse meta-data
93             picture_xml = WLPicture.from_file(xml_file,
94                     image_store=SimpleImageStore)
95
96             pict, created = Picture.objects.get_or_create(slug=picture_xml.slug)
97             if not created and not overwrite:
98                 raise Picture.AlreadyExists('Picture %s already exists' % picture_xml.slug)
99
100             pict.title = picture_xml.picture_info.title
101
102             #            from nose.tools import set_trace; set_trace()
103             motif_tags = set()
104             for part in picture_xml.partiter():
105                 for motif in part['themes']:
106                     tag, created = catalogue.models.Tag.objects.get_or_create(slug=slughifi(motif), category='theme')
107                     if created:
108                         tag.name = motif
109                         tag.sort_key = sortify(tag.name)
110                         tag.save()
111                     motif_tags.add(tag)
112
113             pict.tags = catalogue.models.Tag.tags_from_info(picture_xml.picture_info) + \
114                 list(motif_tags)
115
116             if image_file is not None:
117                 img = image_file
118             else:
119                 img = picture_xml.image_file()
120
121             # FIXME: hardcoded extension
122             picture.image_file.save("%s.jpg" % picture.slug, File(img))
123
124             pict.xml_file.save("%s.xml" % pict.slug, File(xml_file))
125             pict.save()
126         finally:
127             if close_xml_file:
128                 xml_file.close()
129         return pict
130
131     @classmethod
132     def picture_list(cls, filter=None):
133         """Generates a hierarchical listing of all pictures
134         Pictures are optionally filtered with a test function.
135         """
136
137         pics = cls.objects.all().order_by('sort_key')\
138             .only('title', 'slug', 'image_file')
139
140         if filter:
141             pics = pics.filter(filter).distinct()
142
143         pics_by_author = SortedDict()
144         orphans = []
145         for tag in catalogue.models.Tag.objects.filter(category='author'):
146             pics_by_author[tag] = []
147
148         for pic in pics:
149             authors = list(pic.tags.filter(category='author'))
150             if authors:
151                 for author in authors:
152                     pics_by_author[author].append(pic)
153             else:
154                 orphans.append(pic)
155
156         return pics_by_author, orphans
157
158     @property
159     def info(self):
160         if not hasattr(self, '_info'):
161             info = dcparser.parse(self.xml_file.path, picture.PictureInfo)
162             self._info = info
163         return self._info
164
165     def reset_short_html(self):
166         if self.id is None:
167             return
168
169         cache_key = "Picture.short_html/%d" % (self.id)
170         cache.delete(cache_key)
171
172     def short_html(self):
173         if self.id:
174             cache_key = "Picture.short_html/%d" % (self.id)
175             short_html = cache.get(cache_key)
176         else:
177             short_html = None
178
179         if short_html is not None:
180             return mark_safe(short_html)
181         else:
182             tags = self.tags.filter(category__in=('author', 'kind', 'epoch'))
183             tags = split_tags(tags)
184
185             short_html = unicode(render_to_string('picture/picture_short.html',
186                 {'picture': self, 'tags': tags}))
187
188             if self.id:
189                 cache.set(cache_key, short_html, catalogue.models.CACHE_FOREVER)
190             return mark_safe(short_html)