1 # This file is part of FNP-Redakcja, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from datetime import date
5 from functools import wraps
6 from os.path import join
7 from os import listdir, stat
8 from shutil import move, rmtree
9 from django.conf import settings
13 from django.db.models import Count
18 View decorator, which puts tab info on a request.
22 def wrapped(request, *args, **kwargs):
23 request.catalogue_active_tab = tab
24 return f(request, *args, **kwargs)
29 def cached_in_field(field_name):
33 def wrapped(self, *args, **kwargs):
34 value = getattr(self, field_name)
36 value = f(self, *args, **kwargs)
37 type(self)._default_manager.filter(pk=self.pk).update(**{field_name: value})
43 def parse_isodate(isodate):
45 return date(*[int(p) for p in isodate.split('-')])
46 except (AttributeError, TypeError, ValueError):
47 raise ValueError("Not a date in ISO format.")
50 class GalleryMerger(object):
51 def __init__(self, dest_gallery, src_gallery):
52 self.dest = dest_gallery
53 self.src = src_gallery
60 return join(settings.MEDIA_ROOT, settings.IMAGE_DIR, gallery)
64 m = re.match(r"^([0-9])-", name)
66 return int(m.groups()[0])
70 def set_prefix(name, prefix, always=False):
71 m = not always and re.match(r"^([0-9])-", name)
72 return "%1d-%s" % (prefix, m and name[2:] or name)
76 "Check if we have gallery size recorded"
77 return self.dest_size is not None
85 files = listdir(self.path(self.dest))
87 self.dest_size = len(files)
88 files_other = listdir(self.path(self.src))
90 self.src_size = len(files_other)
92 if files and files_other:
94 join(self.path(self.dest), files[-1]),
95 join(self.path(self.src), files_other[0]),
103 renamed_files_other = {}
106 # check if all elements of my files have a prefix
107 files_prefixed = True
109 p = self.get_prefix(f)
111 if p > last_pfx: last_pfx = p
113 files_prefixed = False
116 # if not, add a 0 prefix to them
117 if not files_prefixed:
120 renamed_files[f] = self.set_prefix(f, 0, True)
122 # two cases here - either all are prefixed or not.
123 files_other_prefixed = True
124 for f in files_other:
125 pfx = self.get_prefix(f)
127 if not pfx in prefixes:
129 prefixes[pfx] = last_pfx
130 renamed_files_other[f] = self.set_prefix(f, prefixes[pfx])
132 # ops, not all files here were prefixed.
133 files_other_prefixed = False
136 # just set a 1- prefix to all of them
137 if not files_other_prefixed:
138 for f in files_other:
139 renamed_files_other[f] = self.set_prefix(f, 1, True)
141 # finally, move / rename files.
142 for frm, to in renamed_files.items():
143 move(join(self.path(self.dest), frm),
144 join(self.path(self.dest), to))
145 for frm, to in renamed_files_other.items():
146 move(join(self.path(self.src), frm),
147 join(self.path(self.dest), to))
149 rmtree(join(self.path(self.src)))