/
handler.py
294 lines (263 loc) · 9.58 KB
/
handler.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
""" Low level faceted criteria API
"""
import logging
from persistent.list import PersistentList
from zope.component import getUtility
from zope.interface import implementer
from zope.annotation.interfaces import IAnnotations
from zope.schema.interfaces import IVocabularyFactory
from zope.schema.interfaces import ConstraintNotSatisfied
from eea.facetednavigation.criteria.utils import fix_string
from eea.facetednavigation.config import ANNO_CRITERIA
from eea.facetednavigation.widgets.storage import Criterion
from eea.facetednavigation.interfaces import IWidgetsInfo
from eea.facetednavigation.settings.interfaces import IDontInheritConfiguration
from eea.facetednavigation.criteria.interfaces import ICriteria
logger = logging.getLogger("eea.facetednavigation")
@implementer(ICriteria)
class Criteria(object):
""" Handle criteria
"""
def __init__(self, context):
""" Handle criteria
"""
# LinguaPlone support
if IDontInheritConfiguration.providedBy(context):
self.context = context
else:
canonical = getattr(context, 'getCanonical', None)
if canonical:
self.context = canonical()
else:
self.context = context
self.criteria = self._criteria()
def _criteria(self):
""" Get criteria from annotations
"""
anno = IAnnotations(self.context)
criteria = anno.get(ANNO_CRITERIA, None)
if criteria is None:
anno[ANNO_CRITERIA] = PersistentList()
return anno[ANNO_CRITERIA]
def _update(self, values):
""" Update criteria
"""
anno = IAnnotations(self.context)
anno[ANNO_CRITERIA] = PersistentList(values)
self.criteria = anno[ANNO_CRITERIA]
#
# Getters
#
def newid(self):
""" Get new id
"""
return Criterion().getId()
def get(self, key, default=None):
""" Get criterion
"""
for cid, cvalue in self.items():
if key == cid:
return cvalue
return default
def keys(self):
""" Criteria keys
"""
return [criterion.getId() for criterion in self.criteria]
def values(self):
""" Criteria values
"""
return [criterion for criterion in self.criteria]
def items(self):
""" Criteria items
"""
return [(criterion.getId(), criterion) for criterion in self.criteria]
#
# Setters
#
def add(self, wid, position, section='default', **kwargs):
""" Add criterion
"""
widget = self.widget(wid)
if not widget:
raise NameError("Widget type '%s' is undefined" % wid)
properties = {}
criteria = self.criteria
taken_ids = [criterion.getId() for criterion in criteria]
properties['_taken_ids_'] = taken_ids
if '_cid_' in kwargs:
properties['_cid_'] = kwargs.pop('_cid_')
criterion = Criterion(widget=wid, position=position,
section=section, **properties)
# insert the new criterion at the right place in criteria
voc = getUtility(IVocabularyFactory,
'eea.faceted.vocabularies.WidgetPositions')
# we need to take into account position and section
positions = []
for term in voc(self.context):
positions.append('{0}_default'.format(term.value))
positions.append('{0}_advanced'.format(term.value))
# will be inserted at the end by default
insert_index = len(criteria)
crit_pos_sect = '{0}_{1}'.format(position, section)
for index, stored_criterion in enumerate(criteria):
stored_crit_pos_sect = '{0}_{1}'.format(stored_criterion.position,
stored_criterion.section)
if (positions.index(crit_pos_sect) <
positions.index(stored_crit_pos_sect)):
insert_index = index
break
criteria.insert(insert_index, criterion)
cid = criterion.getId()
if kwargs:
self.edit(cid, **kwargs)
return cid
def delete(self, cid):
""" Delete criteria by given ids
"""
if not cid:
raise TypeError('delete takes exactly one argument (0 given)')
for index, criterion in enumerate(self.criteria):
criterion_id = criterion.getId()
if criterion_id == cid:
self.criteria.pop(index)
return
raise KeyError(cid)
def edit(self, cid, **properties):
""" Update criterion properties
"""
criterion = self.get(cid)
if not criterion:
raise KeyError(cid)
wid = properties.get('widget', None)
schema = self.schema(wid=wid, cid=cid)
criteria = {}
for key, value in properties.items():
if key not in schema:
continue
if not value:
continue
if isinstance(value, (list, tuple)):
value_type = schema[key].value_type
value = [fix_string(x) for x in value]
value = [value_type.fromUnicode(x) for x in value]
elif isinstance(value, (str, unicode)):
value = schema[key].fromUnicode(value)
criteria[key] = value
criterion.update(**criteria)
self.criteria._p_changed = 1
def upgrade(self, cid):
""" Upgrade criterion properties
"""
criterion = self.get(cid)
if not criterion:
return
properties = criterion.__dict__
wid = properties.get('widget', None)
schema = self.schema(wid=wid, cid=cid)
if not schema:
return
criteria = {}
for key, value in properties.items():
if key not in schema:
continue
if isinstance(value, (list, tuple)):
value_type = schema[key].value_type
value = [fix_string(x) for x in value]
value = [value_type.fromUnicode(x) for x in value]
elif isinstance(value, (str, unicode)):
value = fix_string(value)
try:
value = schema[key].fromUnicode(value)
except ConstraintNotSatisfied, err:
logger.exception(err)
continue
except AttributeError, err:
value_type = schema[key].value_type
value = [value_type.fromUnicode(value)]
except ValueError, err:
logger.exception(err)
# Cleanup OLD broken values from criterion
if getattr(criterion, key, None) == value:
logger.warn(
"%s: Cleaning up broken %s:%s from criterion %s",
self.context.absolute_url(), key, value, cid)
delattr(criterion, key)
continue
except Exception, err:
logger.warn(
"%s: Could not upgrade %s: %s from criterion %s",
self.context.absolute_url(), key, value, cid)
logger.exception(err)
continue
criteria[key] = value
criterion.update(**criteria)
self.criteria._p_changed = 1
#
# Position
#
def up(self, cid):
""" Move criterion up
"""
insert = None
index = 0
for index, criterion in enumerate(self.criteria):
if criterion.getId() == cid:
insert = self.criteria.pop(index)
break
if not insert:
raise KeyError(cid)
if index > 0:
index -= 1
self.criteria.insert(index, insert)
def down(self, cid):
""" Move criterion down
"""
insert = None
index = 0
for index, criterion in enumerate(self.criteria):
if criterion.getId() == cid:
insert = self.criteria.pop(index)
break
if not insert:
raise KeyError(cid)
index += 1
self.criteria.insert(index, insert)
def position(self, **kwargs):
""" Update criteria position from given lists
"""
voc = getUtility(IVocabularyFactory,
'eea.faceted.vocabularies.WidgetPositions')
positions = ((term.value, kwargs.get(term.value, []))
for term in voc(self.context))
res = []
for position, cids in positions:
if isinstance(cids, (str, unicode)):
cids = [cids]
for cid in cids:
criterion = self.get(cid)
criterion.update(position=position)
res.append(criterion)
self._update(res)
#
# Utils
#
def widget(self, wid=None, cid=None):
""" Return widget by given wid or from criterion by given cid
"""
if not wid:
criterion = self.get(cid)
if not criterion:
raise KeyError(cid)
wid = criterion.get('widget')
info = getUtility(IWidgetsInfo)
return info.widget(wid)
def schema(self, wid=None, cid=None):
""" Return widget schema by given wid or from criterion by given cid
"""
if not wid:
criterion = self.get(cid)
if not criterion:
raise KeyError(cid)
wid = criterion.get('widget')
info = getUtility(IWidgetsInfo)
return info.schema(wid)