merge search into pretty branch
[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 librarian import dcparser, picture
9
10 from django.utils.translation import ugettext_lazy as _
11 from newtagging import managers
12 from os import path
13
14
15 picture_storage = FileSystemStorage(location=path.join(settings.MEDIA_ROOT, 'pictures'), base_url=settings.MEDIA_URL + "pictures/")
16
17
18 class Picture(models.Model):
19     """
20     Picture resource.
21
22     """
23     title       = models.CharField(_('title'), max_length=120)
24     slug        = models.SlugField(_('slug'), max_length=120, db_index=True, unique=True)
25     sort_key    = models.CharField(_('sort key'), max_length=120, db_index=True, editable=False)
26     created_at  = models.DateTimeField(_('creation date'), auto_now_add=True, db_index=True)
27     changed_at  = models.DateTimeField(_('creation date'), auto_now=True, db_index=True)
28     xml_file    = models.FileField('xml_file', upload_to="xml", storage=picture_storage)
29     image_file  = ImageField(_('image_file'), upload_to="images", storage=picture_storage)
30     objects     = models.Manager()
31     tagged      = managers.ModelTaggedItemManager(catalogue.models.Tag)
32     tags        = managers.TagDescriptor(catalogue.models.Tag)
33
34     class AlreadyExists(Exception):
35         pass
36
37     class Meta:
38         ordering = ('sort_key',)
39
40         verbose_name = _('picture')
41         verbose_name_plural = _('pictures')
42
43     URLID_RE = r'[a-z0-9-]+'
44     FILEID_RE = r'[a-z0-9-]+'
45
46     def save(self, force_insert=False, force_update=False, reset_short_html=True, **kwargs):
47         from sortify import sortify
48
49         self.sort_key = sortify(self.title)
50
51         ret = super(Picture, self).save(force_insert, force_update)
52
53         return ret
54
55     def __unicode__(self):
56         return self.title
57
58     @permalink
59     def get_absolute_url(self):
60         return ('picture.views.picture_detail', [self.urlid()])
61
62     def urlid(self):
63         return self.slug
64
65     @classmethod
66     def from_xml_file(cls, xml_file, image_file=None, overwrite=False):
67         """
68         Import xml and it's accompanying image file.
69         """
70         from django.core.files import File
71         from librarian.picture import WLPicture
72         close_xml_file = False
73
74         if not isinstance(xml_file, File):
75             xml_file = File(open(xml_file))
76             close_xml_file = True
77         try:
78             # use librarian to parse meta-data
79             picture_xml = WLPicture.from_file(xml_file)
80
81             picture, created = Picture.objects.get_or_create(slug=picture_xml.slug)
82             if not created and not overwrite:
83                 raise Picture.AlreadyExists('Picture %s already exists' % picture_xml.slug)
84
85             picture.title = picture_xml.picture_info.title
86
87             picture.tags = catalogue.models.Tag.tags_from_info(picture_xml.picture_info)
88
89             if image_file is not None:
90                 img = image_file
91             else:
92                 img = picture_xml.image_file()
93
94             picture.image_file.save(path.basename(picture_xml.image_path), File(img))
95
96             picture.xml_file.save("%s.xml" % picture.slug, File(xml_file))
97             picture.save()
98         finally:
99             if close_xml_file:
100                 xml_file.close()
101         return picture
102
103     @classmethod
104     def picture_list(cls, filter=None):
105         """Generates a hierarchical listing of all pictures
106         Pictures are optionally filtered with a test function.
107         """
108
109         pics = cls.objects.all().order_by('sort_key')\
110             .only('title', 'slug', 'image_file')
111
112         if filter:
113             pics = pics.filter(filter).distinct()
114
115         pics_by_author = SortedDict()
116         orphans = []
117         for tag in catalogue.models.Tag.objects.filter(category='author'):
118             pics_by_author[tag] = []
119
120         for pic in pics:
121             authors = list(pic.tags.filter(category='author'))
122             if authors:
123                 for author in authors:
124                     pics_by_author[author].append(pic)
125             else:
126                 orphans.append(pic)
127
128         return pics_by_author, orphans
129
130     @property
131     def info(self):
132         if not hasattr(self, '_info'):
133             info = dcparser.parse(self.xml_file.path, picture.PictureInfo)
134             self._info = info
135         return self._info