code style
[redakcja.git] / apps / catalogue / helpers.py
1 # -*- coding: utf-8 -*-
2 from datetime import date
3 from functools import wraps
4 from os.path import join
5 from os import listdir
6 from shutil import move, rmtree
7 from django.conf import settings
8 import re
9 import filecmp
10
11
12 def active_tab(tab):
13     """
14         View decorator, which puts tab info on a request.
15     """
16     def wrapper(f):
17         @wraps(f)
18         def wrapped(request, *args, **kwargs):
19             request.catalogue_active_tab = tab
20             return f(request, *args, **kwargs)
21         return wrapped
22     return wrapper
23
24
25 def cached_in_field(field_name):
26     def decorator(f):
27         @property
28         @wraps(f)
29         def wrapped(self, *args, **kwargs):
30             value = getattr(self, field_name)
31             if value is None:
32                 value = f(self, *args, **kwargs)
33                 type(self)._default_manager.filter(pk=self.pk).update(**{field_name: value})
34             return value
35         return wrapped
36     return decorator
37
38
39 def parse_isodate(isodate):
40     try:
41         return date(*[int(p) for p in isodate.split('-')])
42     except (AttributeError, TypeError, ValueError):
43         raise ValueError("Not a date in ISO format.")
44
45
46 class GalleryMerger(object):
47     def __init__(self, dest_gallery, src_gallery):
48         self.dest = dest_gallery
49         self.src = src_gallery
50         self.dest_size = None
51         self.src_size = None
52         self.num_deleted = 0
53
54     @staticmethod
55     def path(gallery):
56         return join(settings.MEDIA_ROOT, settings.IMAGE_DIR, gallery)
57
58     @staticmethod
59     def get_prefix(name):
60         m = re.match(r"^([0-9])-", name)
61         if m:
62             return int(m.groups()[0])
63         return None
64
65     @staticmethod
66     def set_prefix(name, prefix, always=False):
67         m = not always and re.match(r"^([0-9])-", name)
68         return "%1d-%s" % (prefix, m and name[2:] or name)
69
70     @property
71     def was_merged(self):
72         """Check if we have gallery size recorded"""
73         return self.dest_size is not None
74
75     def merge(self):
76         if not self.dest:
77             return self.src
78         if not self.src:
79             return self.dest
80
81         files = listdir(self.path(self.dest))
82         files.sort()
83         self.dest_size = len(files)
84         files_other = listdir(self.path(self.src))
85         files_other.sort()
86         self.src_size = len(files_other)
87
88         if files and files_other:
89             print "compare %s with %s" % (files[-1], files_other[0])
90             if filecmp.cmp(
91                     join(self.path(self.dest), files[-1]),
92                     join(self.path(self.src), files_other[0]),
93                     False
94                     ):
95                 files_other.pop(0)
96                 self.num_deleted = 1
97
98         prefixes = {}
99         renamed_files = {}
100         renamed_files_other = {}
101         last_pfx = -1
102
103         # check if all elements of my files have a prefix
104         files_prefixed = True
105         for f in files:
106             p = self.get_prefix(f)
107             if p:
108                 if p > last_pfx:
109                     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 pfx not 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), join(self.path(self.dest), to))
142         for frm, to in renamed_files_other.items():
143             move(join(self.path(self.src), frm), join(self.path(self.dest), to))
144
145         rmtree(join(self.path(self.src)))
146         return self.dest