summaryrefslogtreecommitdiff
path: root/horizon/dashboards/nova/containers/forms.py
blob: e0bfc9b3d4527d03b44ee348085a451658f5c29b (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
# vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging

from django import shortcuts
from django.contrib import messages
from django.core import validators
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _

from horizon import api
from horizon import exceptions
from horizon import forms


LOG = logging.getLogger(__name__)


no_slash_validator = validators.RegexValidator(r'^(?u)[^/]+$',
                                               _("Slash is not an allowed "
                                                 "character."),
                                               code="noslash")


class CreateContainer(forms.SelfHandlingForm):
    parent = forms.CharField(max_length=255,
                             required=False,
                             widget=forms.HiddenInput)
    name = forms.CharField(max_length=255,
                           label=_("Container Name"),
                           validators=[no_slash_validator])

    def handle(self, request, data):
        try:
            if not data['parent']:
                # Create a container
                api.swift_create_container(request, data["name"])
                messages.success(request, _("Container created successfully."))
            else:
                # Create a pseudo-folder
                container, slash, remainder = data['parent'].partition("/")
                remainder = remainder.rstrip("/")
                subfolder_name = "/".join([bit for bit
                                           in (remainder, data['name'])
                                           if bit])
                api.swift_create_subfolder(request,
                                           container,
                                           subfolder_name)
                messages.success(request, _("Folder created successfully."))
                url = "horizon:nova:containers:object_index"
                if remainder:
                    remainder = remainder.rstrip("/")
                    remainder += "/"
                return shortcuts.redirect(url, container, remainder)

        except:
            exceptions.handle(request, _('Unable to create container.'))

        return shortcuts.redirect("horizon:nova:containers:index")


class UploadObject(forms.SelfHandlingForm):
    path = forms.CharField(max_length=255,
                           required=False,
                           widget=forms.HiddenInput)
    name = forms.CharField(max_length=255,
                           label=_("Object Name"),
                           validators=[no_slash_validator])
    object_file = forms.FileField(label=_("File"))
    container_name = forms.CharField(widget=forms.HiddenInput())

    def handle(self, request, data):
        object_file = self.files['object_file']
        if data['path']:
            object_path = "/".join([data['path'].rstrip("/"), data['name']])
        else:
            object_path = data['name']
        try:
            obj = api.swift_upload_object(request,
                                          data['container_name'],
                                          object_path,
                                          object_file)
            obj.metadata['orig-filename'] = object_file.name
            obj.sync_metadata()
            messages.success(request, _("Object was successfully uploaded."))
        except:
            exceptions.handle(request, _("Unable to upload object."))
        return shortcuts.redirect("horizon:nova:containers:object_index",
                                  data['container_name'], data['path'])


class CopyObject(forms.SelfHandlingForm):
    new_container_name = forms.ChoiceField(label=_("Destination container"),
                                           validators=[no_slash_validator])
    path = forms.CharField(max_length=255, required=False)
    new_object_name = forms.CharField(max_length=255,
                                      label=_("Destination object name"),
                                      validators=[no_slash_validator])
    orig_container_name = forms.CharField(widget=forms.HiddenInput())
    orig_object_name = forms.CharField(widget=forms.HiddenInput())

    def __init__(self, *args, **kwargs):
        containers = kwargs.pop('containers')
        super(CopyObject, self).__init__(*args, **kwargs)
        self.fields['new_container_name'].choices = containers

    def handle(self, request, data):
        object_index = "horizon:nova:containers:object_index"
        orig_container = data['orig_container_name']
        orig_object = data['orig_object_name']
        new_container = data['new_container_name']
        new_object = data['new_object_name']
        new_path = "%s%s" % (data['path'], new_object)

        # Iteratively make sure all the directory markers exist.
        if data['path']:
            path_component = ""
            for bit in data['path'].split("/"):
                path_component += bit
                try:
                    api.swift.swift_create_subfolder(request,
                                                     new_container,
                                                     path_component)
                except:
                    redirect = reverse(object_index, args=(orig_container,))
                    exceptions.handle(request,
                                      _("Unable to copy object."),
                                      redirect=redirect)
                path_component += "/"

        # Now copy the object itself.
        try:
            api.swift_copy_object(request,
                                  orig_container,
                                  orig_object,
                                  new_container,
                                  new_path)
            dest = "%s/%s" % (new_container, data['path'])
            vals = {"dest": dest.rstrip("/"),
                    "orig": orig_object.split("/")[-1],
                    "new": new_object}
            messages.success(request,
                             _('Copied "%(orig)s" to "%(dest)s" as "%(new)s".')
                             % vals)
        except exceptions.HorizonException, exc:
            messages.error(request, exc)
            return shortcuts.redirect(object_index, orig_container)
        except:
            redirect = reverse(object_index, args=(orig_container,))
            exceptions.handle(request,
                              _("Unable to copy object."),
                              redirect=redirect)
        return shortcuts.redirect(object_index, new_container, data['path'])