File: views.py

package info (click to toggle)
freedombox 26.2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 82,976 kB
  • sloc: python: 48,504; javascript: 1,736; xml: 481; makefile: 290; sh: 167; php: 32
file content (153 lines) | stat: -rw-r--r-- 5,008 bytes parent folder | download | duplicates (6)
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
# SPDX-License-Identifier: AGPL-3.0-or-later
"""Django views for Gitweb."""

from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.http import Http404
from django.shortcuts import redirect
from django.template.response import TemplateResponse
from django.urls import reverse_lazy
from django.utils.translation import gettext as _
from django.views.generic import FormView

from plinth import app as app_module
from plinth import views
from plinth.modules import gitweb

from . import privileged
from .forms import CreateRepoForm, EditRepoForm


class GitwebAppView(views.AppView):
    """Serve configuration page."""

    app_id = 'gitweb'
    template_name = 'gitweb_configure.html'

    def get_context_data(self, *args, **kwargs):
        """Add repositories to the context data."""
        context = super().get_context_data(*args, **kwargs)
        repos = gitweb.get_repo_list()
        context['repos'] = repos
        context['cloning'] = any('clone_progress' in repo for repo in repos)
        if context['cloning']:
            context['refresh_page_sec'] = 3

        return context


class CreateRepoView(SuccessMessageMixin, FormView):
    """View to create a new repository."""

    form_class = CreateRepoForm
    prefix = 'gitweb'
    template_name = 'form.html'
    success_url = reverse_lazy('gitweb:index')
    success_message = _('Repository created.')

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Create Repository')
        return context

    def form_valid(self, form):
        """Create the repository on valid form submission."""
        form_data = {}
        for key, value in form.cleaned_data.items():
            if value is None:
                form_data[key] = ''
            else:
                form_data[key] = value
        try:
            gitweb.create_repo(form_data['name'], form_data['description'],
                               form_data['owner'], form_data['is_private'])
        except Exception as error:
            self.success_message = ''
            messages.error(
                self.request, "{0} {1}".format(
                    _('An error occurred while creating the repository.'),
                    error))
        else:
            app_module.App.get('gitweb').update_service_access()

        return super().form_valid(form)


class EditRepoView(SuccessMessageMixin, FormView):
    """View to edit an existing repository."""

    form_class = EditRepoForm
    prefix = 'gitweb'
    template_name = 'form.html'
    success_url = reverse_lazy('gitweb:index')
    success_message = _('Repository edited.')

    def get_context_data(self, **kwargs):
        """Return additional context for rendering the template."""
        context = super().get_context_data(**kwargs)
        context['title'] = _('Edit repository')
        return context

    def get_initial(self):
        """Load information about repository being edited."""
        name = self.kwargs['name']
        for repo in gitweb.get_repo_list():
            if repo['name'] == name and 'clone_progress' not in repo:
                break
        else:
            raise Http404

        return gitweb.repo_info(name)

    def form_valid(self, form):
        """Edit the repo on valid form submission."""
        if form.initial != form.cleaned_data:
            form_data = {}
            for key, value in form.cleaned_data.items():
                if value is None:
                    form_data[key] = ''
                else:
                    form_data[key] = value

            try:
                gitweb.edit_repo(form.initial, form_data)
            except Exception:
                messages.error(self.request,
                               _('An error occurred during configuration.'))
        app_module.App.get('gitweb').update_service_access()

        return super().form_valid(form)


def delete(request, name):
    """Handle deleting repositories, showing a confirmation dialog first.

    On GET, display a confirmation page.
    On POST, delete the repository.
    """
    for repo in gitweb.get_repo_list():
        if repo['name'] == name and 'clone_progress' not in repo:
            break
    else:
        raise Http404

    app = app_module.App.get('gitweb')
    if request.method == 'POST':
        try:
            privileged.delete_repo(name)
            messages.success(request, _('{name} deleted.').format(name=name))
        except Exception as error:
            messages.error(
                request,
                _('Could not delete {name}: {error}').format(
                    name=name, error=error),
            )
        app.update_service_access()

        return redirect(reverse_lazy('gitweb:index'))

    return TemplateResponse(request, 'gitweb_delete.html', {
        'title': app.info.name,
        'name': name
    })