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