summaryrefslogtreecommitdiffstats
path: root/packages/views/signoff.py
blob: e57b4d9aab9a2266c4a943745b7202bd617fb269 (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
from datetime import datetime
from operator import attrgetter

from django import forms
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.models import User
from django.core.serializers.json import DjangoJSONEncoder
from django.db import transaction
from django.http import HttpResponse, Http404
from django.shortcuts import get_list_or_404, redirect, render
from django.utils import simplejson
from django.views.decorators.cache import never_cache
from django.views.generic.simple import direct_to_template

from main.models import Package, Arch, Repo
from ..models import SignoffSpecification, Signoff
from ..utils import (get_signoff_groups, approved_by_signoffs,
        PackageSignoffGroup)

@permission_required('main.change_package')
@never_cache
def signoffs(request):
    signoff_groups = sorted(get_signoff_groups(), key=attrgetter('pkgbase'))
    for group in signoff_groups:
        group.user = request.user

    context = {
        'signoff_groups': signoff_groups,
        'arches': Arch.objects.all(),
        'repo_names': sorted(set(g.target_repo for g in signoff_groups)),
    }
    return direct_to_template(request, 'packages/signoffs.html', context)

@permission_required('main.change_package')
@never_cache
def signoff_package(request, name, repo, arch, revoke=False):
    packages = get_list_or_404(Package, pkgbase=name,
            arch__name=arch, repo__name__iexact=repo, repo__testing=True)
    package = packages[0]

    spec = SignoffSpecification.objects.get_or_default_from_package(package)

    if revoke:
        try:
            signoff = Signoff.objects.get_from_package(
                    package, request.user, False)
        except Signoff.DoesNotExist:
            raise Http404
        signoff.revoked = datetime.utcnow()
        signoff.save()
        created = False
    else:
        # ensure we should even be accepting signoffs
        if spec.known_bad or not spec.enabled:
            return render(request, '403.html', status=403)
        signoff, created = Signoff.objects.get_or_create_from_package(
                package, request.user)

    all_signoffs = Signoff.objects.for_package(package)

    if request.is_ajax():
        data = {
            'created': created,
            'revoked': bool(signoff.revoked),
            'approved': approved_by_signoffs(all_signoffs, spec),
            'required': spec.required,
            'enabled': spec.enabled,
            'known_bad': spec.known_bad,
            'user': str(request.user),
        }
        return HttpResponse(simplejson.dumps(data, ensure_ascii=False),
                mimetype='application/json')

    return redirect('package-signoffs')

class SignoffOptionsForm(forms.ModelForm):
    apply_all = forms.BooleanField(required=False,
        help_text="Apply these options to all architectures?")

    class Meta:
        model = SignoffSpecification
        fields = ('required', 'enabled', 'known_bad', 'comments')

def _signoff_options_all(request, name, repo):
    seen_ids = set()
    with transaction.commit_on_success():
        # find or create a specification for all architectures, then
        # graft the form data onto them
        packages = Package.objects.filter(pkgbase=name,
            repo__name__iexact=repo, repo__testing=True)
        for package in packages:
            try:
                spec = SignoffSpecification.objects.get_from_package(package)
                if spec.pk in seen_ids:
                    continue
            except SignoffSpecification.DoesNotExist:
                spec = SignoffSpecification(pkgbase=package.pkgbase,
                        pkgver=package.pkgver, pkgrel=package.pkgrel,
                        epoch=package.epoch, arch=package.arch,
                        repo=package.repo)

            if spec.user is None:
                spec.user = request.user

            form = SignoffOptionsForm(request.POST, instance=spec)
            if form.is_valid():
                form.save()
            seen_ids.add(form.instance.pk)

@permission_required('main.change_package')
@never_cache
def signoff_options(request, name, repo, arch):
    packages = get_list_or_404(Package, pkgbase=name,
            arch__name=arch, repo__name__iexact=repo, repo__testing=True)
    package = packages[0]

    if request.user != package.packager and \
            request.user not in package.maintainers:
        return render(request, '403.html', status=403)

    try:
        spec = SignoffSpecification.objects.get_from_package(package)
    except SignoffSpecification.DoesNotExist:
        # create a fake one, but don't save it just yet
        spec = SignoffSpecification(pkgbase=package.pkgbase,
                pkgver=package.pkgver, pkgrel=package.pkgrel,
                epoch=package.epoch, arch=package.arch, repo=package.repo)

    if spec.user is None:
        spec.user = request.user

    if request.POST:
        form = SignoffOptionsForm(request.POST, instance=spec)
        if form.is_valid():
            if form.cleaned_data['apply_all']:
                _signoff_options_all(request, name, repo)
            else:
                form.save()
            return redirect('package-signoffs')
    else:
        form = SignoffOptionsForm(instance=spec)

    context = {
        'packages': packages,
        'package': package,
        'form': form,
    }
    return direct_to_template(request, 'packages/signoff_options.html', context)

class SignoffJSONEncoder(DjangoJSONEncoder):
    '''Base JSONEncoder extended to handle all serialization of all classes
    related to signoffs.'''
    signoff_group_attrs = ['arch', 'last_update', 'maintainers', 'packager',
            'pkgbase', 'repo', 'signoffs', 'target_repo', 'version']
    signoff_spec_attrs = ['required', 'enabled', 'known_bad', 'comments']
    signoff_attrs = ['user', 'created', 'revoked']

    def default(self, obj):
        if isinstance(obj, PackageSignoffGroup):
            data = dict((attr, getattr(obj, attr))
                    for attr in self.signoff_group_attrs)
            data['pkgnames'] = [p.pkgname for p in obj.packages]
            data['package_count'] = len(obj.packages)
            data['approved'] = obj.approved()
            data.update((attr, getattr(obj.specification, attr))
                    for attr in self.signoff_spec_attrs)
            return data
        elif isinstance(obj, Signoff):
            data = dict((attr, getattr(obj, attr))
                    for attr in self.signoff_attrs)
            return data
        elif isinstance(obj, Arch) or isinstance(obj, Repo):
            return unicode(obj)
        elif isinstance(obj, User):
            return obj.username
        elif isinstance(obj, set):
            return list(obj)
        return super(SignoffJSONEncoder, self).default(obj)

@permission_required('main.change_package')
@never_cache
def signoffs_json(request):
    signoff_groups = sorted(get_signoff_groups(), key=attrgetter('pkgbase'))
    data = {
        'version': 1,
        'signoff_groups': signoff_groups,
    }
    to_json = simplejson.dumps(data, ensure_ascii=False,
            cls=SignoffJSONEncoder)
    response = HttpResponse(to_json, mimetype='application/json')
    return response

# vim: set ts=4 sw=4 et: