a97a040044c734b5dd9b67e772cb6c11f7462886
[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         assert isinstance(dest_gallery, str)
50         assert isinstance(src_gallery, str)
51         self.dest = dest_gallery
52         self.src = src_gallery
53         self.dest_size = None
54         self.src_size = None
55         self.num_deleted = 0
56
57     @staticmethod
58     def path(gallery):
59         return join(settings.MEDIA_ROOT, settings.IMAGE_DIR, gallery)
60
61     @staticmethod
62     def get_prefix(name):
63         m = re.match(r"^([0-9])-", name)
64         if m:
65             return int(m.groups()[0])
66         return None
67
68     @staticmethod
69     def set_prefix(name, prefix, always=False):
70         m = not always and re.match(r"^([0-9])-", name)
71         return "%1d-%s" % (prefix, m and name[2:] or name)
72
73     def merge(self):
74         if not self.dest:
75             return self.src
76         if not self.src:
77             return self.dest
78
79         files = listdir(self.path(self.dest))
80         self.dest_size = len(files)
81         files_other = listdir(self.path(self.src))
82         self.src_size = len(files_other)
83
84         if files and files_other:
85             print "compare %s with %s" % (files[-1], files_other[0])
86             if filecmp.cmp(
87                     join(self.path(self.dest), files[-1]),
88                     join(self.path(self.src), files_other[0]),
89                     False
90                     ):
91                 files_other.pop(0)
92                 self.num_deleted = 1
93
94         prefixes = {}
95         renamed_files = {}
96         renamed_files_other = {}
97         last_pfx = -1
98
99         # check if all elements of my files have a prefix
100         files_prefixed = True
101         for f in files:
102             p = self.get_prefix(f)
103             if p:
104                 if p > last_pfx: last_pfx = p
105             else:
106                 files_prefixed = False
107                 break
108
109         # if not, add a 0 prefix to them
110         if not files_prefixed:
111             prefixes[0] = 0
112             for f in files:
113                 renamed_files[f] = self.set_prefix(f, 0, True)
114
115         # two cases here - either all are prefixed or not.
116         files_other_prefixed = True
117         for f in files_other:
118             pfx = self.get_prefix(f)
119             if pfx is not None:
120                 if not pfx in prefixes:
121                     last_pfx += 1
122                     prefixes[pfx] = last_pfx
123                 renamed_files_other[f] = self.set_prefix(f, prefixes[pfx])
124             else:
125                 # ops, not all files here were prefixed.
126                 files_other_prefixed = False
127                 break
128
129         # just set a 1- prefix to all of them
130         if not files_other_prefixed:
131             for f in files_other:
132                 renamed_files_other[f] = self.set_prefix(f, 1, True)
133
134         # finally, move / rename files.
135         from nose.tools import set_trace
136         #        set_trace()
137         for frm, to in renamed_files.items():
138             move(join(self.path(self.dest), frm),
139                         join(self.path(self.dest), to))
140         for frm, to in renamed_files_other.items():
141             move(join(self.path(self.src), frm),
142                         join(self.path(self.dest), to))            
143
144         rmtree(join(self.path(self.src)))
145         return self.dest