1 from datetime import date
2 from functools import wraps
3 from os.path import join
4 from os import listdir, stat
5 from shutil import move, rmtree
6 from django.conf import settings
10 from django.db.models import Count
15 View decorator, which puts tab info on a request.
19 def wrapped(request, *args, **kwargs):
20 request.catalogue_active_tab = tab
21 return f(request, *args, **kwargs)
26 def cached_in_field(field_name):
30 def wrapped(self, *args, **kwargs):
31 value = getattr(self, field_name)
33 value = f(self, *args, **kwargs)
34 type(self)._default_manager.filter(pk=self.pk).update(**{field_name: value})
40 def parse_isodate(isodate):
42 return date(*[int(p) for p in isodate.split('-')])
43 except (AttributeError, TypeError, ValueError):
44 raise ValueError("Not a date in ISO format.")
47 class GalleryMerger(object):
48 def __init__(self, dest_gallery, src_gallery):
49 self.dest = dest_gallery
50 self.src = src_gallery
57 return join(settings.MEDIA_ROOT, settings.IMAGE_DIR, gallery)
61 m = re.match(r"^([0-9])-", name)
63 return int(m.groups()[0])
67 def set_prefix(name, prefix, always=False):
68 m = not always and re.match(r"^([0-9])-", name)
69 return "%1d-%s" % (prefix, m and name[2:] or name)
73 "Check if we have gallery size recorded"
74 return self.dest_size is not None
82 files = listdir(self.path(self.dest))
84 self.dest_size = len(files)
85 files_other = listdir(self.path(self.src))
87 self.src_size = len(files_other)
89 if files and files_other:
91 join(self.path(self.dest), files[-1]),
92 join(self.path(self.src), files_other[0]),
100 renamed_files_other = {}
103 # check if all elements of my files have a prefix
104 files_prefixed = True
106 p = self.get_prefix(f)
108 if p > last_pfx: last_pfx = p
110 files_prefixed = False
113 # if not, add a 0 prefix to them
114 if not files_prefixed:
117 renamed_files[f] = self.set_prefix(f, 0, True)
119 # two cases here - either all are prefixed or not.
120 files_other_prefixed = True
121 for f in files_other:
122 pfx = self.get_prefix(f)
124 if not pfx in prefixes:
126 prefixes[pfx] = last_pfx
127 renamed_files_other[f] = self.set_prefix(f, prefixes[pfx])
129 # ops, not all files here were prefixed.
130 files_other_prefixed = False
133 # just set a 1- prefix to all of them
134 if not files_other_prefixed:
135 for f in files_other:
136 renamed_files_other[f] = self.set_prefix(f, 1, True)
138 # finally, move / rename files.
139 for frm, to in renamed_files.items():
140 move(join(self.path(self.dest), frm),
141 join(self.path(self.dest), to))
142 for frm, to in renamed_files_other.items():
143 move(join(self.path(self.src), frm),
144 join(self.path(self.dest), to))
146 rmtree(join(self.path(self.src)))