summaryrefslogtreecommitdiffstats
path: root/apps/patchwork/filters.py
blob: 8c9690eeaf22de4fbe152354ce1bdccea946cc8e (plain)
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# Patchwork - automated patch tracking system
# Copyright (C) 2008 Jeremy Kerr <jk@ozlabs.org>
#
# This file is part of the Patchwork package.
#
# Patchwork is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# Patchwork is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Patchwork; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


from patchwork.models import Person, State
from django.utils.safestring import mark_safe
from django.utils.html import escape
from django.contrib.auth.models import User
from urllib import quote

class Filter(object):
    def __init__(self, filters):
        self.filters = filters
        self.applied = False
        self.forced = False

    def name(self):
        """The 'name' of the filter, to be displayed in the filter UI"""
        return self.name

    def condition(self):
        """The current condition of the filter, to be displayed in the
           filter UI"""
        return self.key

    def key(self):
        """The key for this filter, to appear in the querystring. A key of
           None will remove the param=ley pair from the querystring."""
        return None

    def set_status(self, *kwargs):
        """Views can call this to force a specific filter status. For example,
           a user's todo page needs to setup the delegate filter to show
           that user's delegated patches"""
        pass

    def parse(self, dict):
        if self.param not in dict.keys():
            return
        self._set_key(dict[self.param])

    def url_without_me(self):
        return self.filters.querystring_without_filter(self)

    def form_function(self):
        return 'function(form) { return "unimplemented" }'

    def form(self):
        if self.forced:
            return mark_safe('<input type="hidden" value="%s">%s' % (self.param,
                        self.condition()))
            return self.condition()
        return self._form()

    def kwargs(self):
        return {}

    def __str__(self):
        return '%s: %s' % (self.name, self.kwargs())


class SubmitterFilter(Filter):
    param = 'submitter'
    def __init__(self, filters):
        super(SubmitterFilter, self).__init__(filters)
        self.name = 'Submitter'
        self.person = None
        self.person_match = None

    def _set_key(self, str):
        self.person = None
        self.person_match = None
        submitter_id = None
        try:
            submitter_id = int(str)
        except ValueError:
            pass
        except:
            return

        if submitter_id:
            self.person = Person.objects.get(id = int(str))
            self.applied = True
            return


        people = Person.objects.filter(name__icontains = str)

        if not people:
            return

        self.person_match = str
        self.applied = True

    def kwargs(self):
        if self.person:
            user = self.person.user
            if user:
                return {'submitter__in':
                    Person.objects.filter(user = user).values('pk').query}
            return {'submitter': self.person}

        if self.person_match:
            return {'submitter__name__icontains': self.person_match}
        return {}

    def condition(self):
        if self.person:
            return self.person.name
        elif self.person_match:
            return self.person_match
        return ''

    def _form(self):
        name = ''
        if self.person:
            name = self.person.name
        return mark_safe(('<input onKeyUp="submitter_field_change(this)" ' +
                'name="submitter" id="submitter_input" ' +
                        'value="%s">&nbsp;' % escape(name)) +
                '<select id="submitter_select" ' +
                'disabled="true"></select>')

    def key(self):
        if self.person:
            return self.person.id
        return self.person_match

class StateFilter(Filter):
    param = 'state'
    any_key = '*'
    action_req_str = 'Action Required'

    def __init__(self, filters):
        super(StateFilter, self).__init__(filters)
        self.name = 'State'
        self.state = None
        self.applied = True

    def _set_key(self, str):
        self.state = None

        if str == self.any_key:
            self.applied = False
            return

        try:
            self.state = State.objects.get(id=int(str))
        except:
            return

        self.applied = True

    def kwargs(self):
        if self.state is not None:
            return {'state': self.state}
        else:
            return {'state__in': \
                        State.objects.filter(action_required = True) \
                            .values('pk').query}

    def condition(self):
        if self.state:
            return self.state.name
        return self.action_req_str

    def key(self):
        if self.state is not None:
            return self.state.id
        if not self.applied:
            return '*'
        return None

    def _form(self):
        str = '<select name="%s">' % self.param

        selected = ''
        if not self.applied:
            selected = 'selected'
        str += '<option %s value="%s">any</option>' % (selected, self.any_key)

        selected = ''
        if self.applied and self.state == None:
            selected = 'selected'
        str += '<option %s value="">%s</option>' % \
               (selected, self.action_req_str)

        for state in State.objects.all():
            selected = ''
            if self.state and self.state == state:
                selected = ' selected="true"'

            str += '<option value="%d" %s>%s</option>' % \
                (state.id, selected, state.name)
        str += '</select>'
        return mark_safe(str);

    def form_function(self):
        return 'function(form) { return form.x.value }'

    def url_without_me(self):
        qs = self.filters.querystring_without_filter(self)
        if qs != '?':
            qs += '&'
        return qs + '%s=%s' % (self.param, self.any_key)

class SearchFilter(Filter):
    param = 'q'
    def __init__(self, filters):
        super(SearchFilter, self).__init__(filters)
        self.name = 'Search'
        self.param = 'q'
        self.search = None

    def _set_key(self, str):
        str = str.strip()
        if str == '':
            return
        self.search = str
        self.applied = True

    def kwargs(self):
        return {'name__icontains': self.search}

    def condition(self):
        return self.search

    def key(self):
        return self.search

    def _form(self):
        value = ''
        if self.search:
            value = escape(self.search)
        return mark_safe('<input name="%s" value="%s">' %\
                (self.param, value))

    def form_function(self):
        return mark_safe('function(form) { return form.x.value }')

class ArchiveFilter(Filter):
    param = 'archive'
    def __init__(self, filters):
        super(ArchiveFilter, self).__init__(filters)
        self.name = 'Archived'
        self.archive_state = False
        self.applied = True
        self.param_map = {
            True: 'true',
            False: '',
            None:  'both'
        }
        self.description_map = {
            True: 'Yes',
            False: 'No',
            None: 'Both'
        }

    def _set_key(self, str):
        self.archive_state = False
        self.applied = True
        for (k, v) in self.param_map.iteritems():
            if str == v:
                self.archive_state = k
        if self.archive_state == None:
            self.applied = False

    def kwargs(self):
        if self.archive_state == None:
            return {}
        return {'archived': self.archive_state}

    def condition(self):
        return self.description_map[self.archive_state]

    def key(self):
        if self.archive_state == False:
            return None
        return self.param_map[self.archive_state]

    def _form(self):
        s = ''
        for b in [False, True, None]:
            label = self.description_map[b]
            selected = ''
            if self.archive_state == b:
                selected = 'checked="true"'
            s += ('<input type="radio" name="%(param)s" ' + \
                   '%(selected)s value="%(value)s">%(label)s' + \
                   '&nbsp;&nbsp;&nbsp;&nbsp;') % \
                    {'label': label,
                     'param': self.param,
                     'selected': selected,
                     'value': self.param_map[b]
                    }
        return mark_safe(s)

    def url_without_me(self):
        qs = self.filters.querystring_without_filter(self)
        if qs != '?':
            qs += '&'
        return qs + 'archive=both'


class DelegateFilter(Filter):
    param = 'delegate'
    no_delegate_key = '-'
    no_delegate_str = 'Nobody'
    AnyDelegate = 1

    def __init__(self, filters):
        super(DelegateFilter, self).__init__(filters)
        self.name = 'Delegate'
        self.param = 'delegate'
        self.delegate = None

    def _set_key(self, str):
        if str == self.no_delegate_key:
            self.applied = True
            self.delegate = None
            return

        applied = False
        try:
            self.delegate = User.objects.get(id = str)
            self.applied = True
        except:
            pass

    def kwargs(self):
        if not self.applied:
            return {}
        return {'delegate': self.delegate}

    def condition(self):
        if self.delegate:
            return self.delegate.profile.name()
        return self.no_delegate_str

    def _form(self):
        delegates = User.objects.filter(profile__maintainer_projects =
                self.filters.project)

        str = '<select name="delegate">'

        selected = ''
        if not self.applied:
            selected = 'selected'

        str += '<option %s value="">------</option>' % selected

        selected = ''
        if self.applied and self.delegate is None:
            selected = 'selected'

        str += '<option %s value="%s">%s</option>' % \
                (selected, self.no_delegate_key, self.no_delegate_str)

        for d in delegates:
            selected = ''
            if d == self.delegate:
                selected = ' selected'

            str += '<option %s value="%s">%s</option>' % (selected,
                    d.id, d.profile.name())
        str += '</select>'

        return mark_safe(str)

    def key(self):
        if self.delegate:
            return self.delegate.id
        if self.applied:
            return self.no_delegate_key
        return None

    def set_status(self, *args, **kwargs):
        if 'delegate' in kwargs:
            self.applied = self.forced = True
            self.delegate = kwargs['delegate']
        if self.AnyDelegate in args:
            self.applied = False
            self.forced = True

filterclasses = [SubmitterFilter, \
                 StateFilter,
                 SearchFilter,
                 ArchiveFilter,
                 DelegateFilter]

class Filters:

    def __init__(self, request):
        self._filters = map(lambda c: c(self), filterclasses)
        self.dict = request.GET
        self.project = None

        for f in self._filters:
            f.parse(self.dict)

    def set_project(self, project):
        self.project = project

    def filter_conditions(self):
        kwargs = {}
        for f in self._filters:
            if f.applied:
                kwargs.update(f.kwargs())
        return kwargs

    def apply(self, queryset):
        kwargs = self.filter_conditions()
        if not kwargs:
            return queryset
        return queryset.filter(**kwargs)

    def params(self):
        return [ (f.param, f.key()) for f in self._filters \
                if f.key() is not None ]

    def querystring(self, remove = None):
        params = dict(self.params())

        for (k, v) in self.dict.iteritems():
            if k not in params:
                params[k] = v

        if remove is not None:
            if remove.param in params.keys():
                del params[remove.param]

        pairs = params.iteritems()

        def sanitise(s):
            if not isinstance(s, basestring):
                s = unicode(s)
            return quote(s.encode('utf-8'))

        return '?' + '&'.join(['%s=%s' % (sanitise(k), sanitise(v))
                                    for (k, v) in pairs])

    def querystring_without_filter(self, filter):
        return self.querystring(filter)

    def applied_filters(self):
        return filter(lambda x: x.applied, self._filters)

    def available_filters(self):
        return self._filters

    def set_status(self, filterclass, *args, **kwargs):
        for f in self._filters:
            if isinstance(f, filterclass):
                f.set_status(*args, **kwargs)
                return