Editor update - trimming down toolbar
[redakcja.git] / apps / catalogue / helpers.py
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
7 import re
8 import filecmp
9
10 from django.db.models import Count
11
12
13 def active_tab(tab):
14     """
15         View decorator, which puts tab info on a request.
16     """
17     def wrapper(f):
18         @wraps(f)
19         def wrapped(request, *args, **kwargs):
20             request.catalogue_active_tab = tab
21             return f(request, *args, **kwargs)
22         return wrapped
23     return wrapper
24
25
26 def cached_in_field(field_name):
27     def decorator(f):
28         @property
29         @wraps(f)
30         def wrapped(self, *args, **kwargs):
31             value = getattr(self, field_name)
32             if value is None:
33                 value = f(self, *args, **kwargs)
34                 type(self)._default_manager.filter(pk=self.pk).update(**{field_name: value})
35             return value
36         return wrapped
37     return decorator
38
39
40 def parse_isodate(isodate):
41     try:
42         return date(*[int(p) for p in isodate.split('-')])
43     except (AttributeError, TypeError, ValueError):
44         raise ValueError("Not a date in ISO format.")
45
46
47 class GalleryMerger(object):
48     def __init__(self, dest_gallery, src_gallery):
49         self.dest = dest_gallery
50         self.src = src_gallery
51         self.dest_size = None
52         self.src_size = None
53         self.num_deleted = 0
54
55     @staticmethod
56     def path(gallery):
57         return join(settings.MEDIA_ROOT, settings.IMAGE_DIR, gallery)
58
59     @staticmethod
60     def get_prefix(name):
61         m = re.match(r"^([0-9])-", name)
62         if m:
63             return int(m.groups()[0])
64         return None
65
66     @staticmethod
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)
70
71     @property
72     def was_merged(self):
73         "Check if we have gallery size recorded"
74         return self.dest_size is not None
75
76     def merge(self):
77         if not self.dest:
78             return self.src
79         if not self.src:
80             return self.dest
81
82         files = listdir(self.path(self.dest))
83         files.sort()
84         self.dest_size = len(files)
85         files_other = listdir(self.path(self.src))
86         files_other.sort()
87         self.src_size = len(files_other)
88
89         if files and files_other:
90             print "compare %s with %s" % (files[-1], files_other[0])
91             if filecmp.cmp(
92                     join(self.path(self.dest), files[-1]),
93                     join(self.path(self.src), files_other[0]),
94                     False
95                     ):
96                 files_other.pop(0)
97                 self.num_deleted = 1
98
99         prefixes = {}
100         renamed_files = {}
101         renamed_files_other = {}
102         last_pfx = -1
103
104         # check if all elements of my files have a prefix
105         files_prefixed = True
106         for f in files:
107             p = self.get_prefix(f)
108             if p:
109                 if p > last_pfx: last_pfx = p
110             else:
111                 files_prefixed = False
112                 break
113
114         # if not, add a 0 prefix to them
115         if not files_prefixed:
116             prefixes[0] = 0
117             for f in files:
118                 renamed_files[f] = self.set_prefix(f, 0, True)
119
120         # two cases here - either all are prefixed or not.
121         files_other_prefixed = True
122         for f in files_other:
123             pfx = self.get_prefix(f)
124             if pfx is not None:
125                 if not pfx in prefixes:
126                     last_pfx += 1
127                     prefixes[pfx] = last_pfx
128                 renamed_files_other[f] = self.set_prefix(f, prefixes[pfx])
129             else:
130                 # ops, not all files here were prefixed.
131                 files_other_prefixed = False
132                 break
133
134         # just set a 1- prefix to all of them
135         if not files_other_prefixed:
136             for f in files_other:
137                 renamed_files_other[f] = self.set_prefix(f, 1, True)
138
139         # finally, move / rename files.
140         for frm, to in renamed_files.items():
141             move(join(self.path(self.dest), frm),
142                         join(self.path(self.dest), to))
143         for frm, to in renamed_files_other.items():
144             move(join(self.path(self.src), frm),
145                         join(self.path(self.dest), to))            
146
147         rmtree(join(self.path(self.src)))
148         return self.dest