01f9b8d48feccca64663a4799e42803b8428d5e7
[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, images_path=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             img = picture_xml.image_file()
90             try:
91                 picture.image_file.save(path.basename(picture_xml.image_path), File(img))
92             finally:
93                 img.close()
94
95             picture.xml_file.save("%s.xml" % picture.slug, File(xml_file))
96             picture.save()
97         finally:
98             if close_xml_file:
99                 xml_file.close()
100         return picture
101
102     @classmethod
103     def picture_list(cls, filter=None):
104         """Generates a hierarchical listing of all pictures
105         Pictures are optionally filtered with a test function.
106         """
107
108         pics = cls.objects.all().order_by('sort_key')\
109             .only('title', 'slug', 'image_file')
110
111         if filter:
112             pics = pics.filter(filter).distinct()
113
114         pics_by_author = SortedDict()
115         orphans = []
116         for tag in catalogue.models.Tag.objects.filter(category='author'):
117             pics_by_author[tag] = []
118
119         for pic in pics:
120             authors = list(pic.tags.filter(category='author'))
121             if authors:
122                 for author in authors:
123                     pics_by_author[author].append(pic)
124             else:
125                 orphans.append(pic)
126
127         return pics_by_author, orphans
128
129     @property
130     def info(self):
131         if not hasattr(self, '_info'):
132             info = dcparser.parse(self.xml_file.path, picture.PictureInfo)
133             self._info = info
134         return self._info