Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / views / util.py @ 9fb7a900

History | View | Annotate | Download (11.1 kB)

1
# Copyright 2011, 2012, 2013 GRNET S.A. All rights reserved.
2
#
3
# Redistribution and use in source and binary forms, with or
4
# without modification, are permitted provided that the following
5
# conditions are met:
6
#
7
#   1. Redistributions of source code must retain the above
8
#      copyright notice, this list of conditions and the following
9
#      disclaimer.
10
#
11
#   2. Redistributions in binary form must reproduce the above
12
#      copyright notice, this list of conditions and the following
13
#      disclaimer in the documentation and/or other materials
14
#      provided with the distribution.
15
#
16
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
17
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
19
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
20
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
23
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
24
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
26
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27
# POSSIBILITY OF SUCH DAMAGE.
28
#
29
# The views and conclusions contained in the software and
30
# documentation are those of the authors and should not be
31
# interpreted as representing official policies, either expressed
32
# or implied, of GRNET S.A.
33

    
34
from django.contrib import messages
35
from django.contrib.auth.views import redirect_to_login
36
from django.core.exceptions import PermissionDenied
37
from django.core.xheaders import populate_xheaders
38
from django.http import HttpResponse
39
from django.shortcuts import redirect
40
from django.template import RequestContext, loader as template_loader
41
from django.utils.translation import ugettext as _
42
from django.views.generic.create_update import apply_extra_context, \
43
    get_model_and_form_class, lookup_object
44

    
45
from synnefo.lib.ordereddict import OrderedDict
46

    
47
from snf_django.lib.db.transaction import commit_on_success_strict
48

    
49
from astakos.im import presentation
50
from astakos.im.util import model_to_dict
51
from astakos.im.models import Resource
52
import astakos.im.messages as astakos_messages
53
import logging
54

    
55
logger = logging.getLogger(__name__)
56

    
57

    
58
class ExceptionHandler(object):
59
    def __init__(self, request):
60
        self.request = request
61

    
62
    def __enter__(self):
63
        pass
64

    
65
    def __exit__(self, exc_type, value, traceback):
66
        if value is not None:  # exception
67
            logger.exception(value)
68
            m = _(astakos_messages.GENERIC_ERROR)
69
            messages.error(self.request, m)
70
            return True  # suppress exception
71

    
72

    
73
def render_response(template, tab=None, status=200, context_instance=None, **kwargs):
74
    """
75
    Calls ``django.template.loader.render_to_string`` with an additional ``tab``
76
    keyword argument and returns an ``django.http.HttpResponse`` with the
77
    specified ``status``.
78
    """
79
    if tab is None:
80
        tab = template.partition('_')[0].partition('.html')[0]
81
    kwargs.setdefault('tab', tab)
82
    html = template_loader.render_to_string(
83
        template, kwargs, context_instance=context_instance)
84
    response = HttpResponse(html, status=status)
85
    return response
86

    
87
@commit_on_success_strict()
88
def _create_object(request, model=None, template_name=None,
89
        template_loader=template_loader, extra_context=None, post_save_redirect=None,
90
        login_required=False, context_processors=None, form_class=None,
91
        msg=None):
92
    """
93
    Based of django.views.generic.create_update.create_object which displays a
94
    summary page before creating the object.
95
    """
96
    response = None
97

    
98
    if extra_context is None: extra_context = {}
99
    if login_required and not request.user.is_authenticated():
100
        return redirect_to_login(request.path)
101
    try:
102

    
103
        model, form_class = get_model_and_form_class(model, form_class)
104
        extra_context['edit'] = 0
105
        if request.method == 'POST':
106
            form = form_class(request.POST, request.FILES)
107
            if form.is_valid():
108
                verify = request.GET.get('verify')
109
                edit = request.GET.get('edit')
110
                if verify == '1':
111
                    extra_context['show_form'] = False
112
                    extra_context['form_data'] = form.cleaned_data
113
                elif edit == '1':
114
                    extra_context['show_form'] = True
115
                else:
116
                    new_object = form.save()
117
                    if not msg:
118
                        msg = _("The %(verbose_name)s was created successfully.")
119
                    msg = msg % model._meta.__dict__
120
                    messages.success(request, msg, fail_silently=True)
121
                    response = redirect(post_save_redirect, new_object)
122
        else:
123
            form = form_class()
124
    except (IOError, PermissionDenied), e:
125
        messages.error(request, e)
126
        return None
127
    else:
128
        if response == None:
129
            # Create the template, context, response
130
            if not template_name:
131
                template_name = "%s/%s_form.html" %\
132
                     (model._meta.app_label, model._meta.object_name.lower())
133
            t = template_loader.get_template(template_name)
134
            c = RequestContext(request, {
135
                'form': form
136
            }, context_processors)
137
            apply_extra_context(extra_context, c)
138
            response = HttpResponse(t.render(c))
139
        return response
140

    
141
@commit_on_success_strict()
142
def _update_object(request, model=None, object_id=None, slug=None,
143
        slug_field='slug', template_name=None, template_loader=template_loader,
144
        extra_context=None, post_save_redirect=None, login_required=False,
145
        context_processors=None, template_object_name='object',
146
        form_class=None, msg=None):
147
    """
148
    Based of django.views.generic.create_update.update_object which displays a
149
    summary page before updating the object.
150
    """
151
    response = None
152

    
153
    if extra_context is None: extra_context = {}
154
    if login_required and not request.user.is_authenticated():
155
        return redirect_to_login(request.path)
156

    
157
    try:
158
        model, form_class = get_model_and_form_class(model, form_class)
159
        obj = lookup_object(model, object_id, slug, slug_field)
160

    
161
        if request.method == 'POST':
162
            form = form_class(request.POST, request.FILES, instance=obj)
163
            if form.is_valid():
164
                verify = request.GET.get('verify')
165
                edit = request.GET.get('edit')
166
                if verify == '1':
167
                    extra_context['show_form'] = False
168
                    extra_context['form_data'] = form.cleaned_data
169
                elif edit == '1':
170
                    extra_context['show_form'] = True
171
                else:
172
                    obj = form.save()
173
                    if not msg:
174
                        msg = _("The %(verbose_name)s was created successfully.")
175
                    msg = msg % model._meta.__dict__
176
                    messages.success(request, msg, fail_silently=True)
177
                    response = redirect(post_save_redirect, obj)
178
        else:
179
            form = form_class(instance=obj)
180
    except (IOError, PermissionDenied), e:
181
        messages.error(request, e)
182
        return None
183
    else:
184
        if response == None:
185
            if not template_name:
186
                template_name = "%s/%s_form.html" %\
187
                    (model._meta.app_label, model._meta.object_name.lower())
188
            t = template_loader.get_template(template_name)
189
            c = RequestContext(request, {
190
                'form': form,
191
                template_object_name: obj,
192
            }, context_processors)
193
            apply_extra_context(extra_context, c)
194
            response = HttpResponse(t.render(c))
195
            populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.attname))
196
        return response
197

    
198
def _resources_catalog(for_project=False, for_usage=False):
199
    """
200
    `resource_catalog` contains a list of tuples. Each tuple contains the group
201
    key the resource is assigned to and resources list of dicts that contain
202
    resource information.
203
    `resource_groups` contains information about the groups
204
    """
205
    # presentation data
206
    resources_meta = presentation.RESOURCES
207
    resource_groups = resources_meta.get('groups', {})
208
    resource_catalog = ()
209
    resource_keys = []
210

    
211
    # resources in database
212
    resource_details = map(lambda obj: model_to_dict(obj, exclude=[]),
213
                           Resource.objects.all())
214
    # initialize resource_catalog to contain all group/resource information
215
    for r in resource_details:
216
        if not r.get('group') in resource_groups:
217
            resource_groups[r.get('group')] = {'icon': 'unknown'}
218

    
219
    resource_keys = [r.get('str_repr') for r in resource_details]
220
    resource_catalog = [[g, filter(lambda r: r.get('group', '') == g,
221
                                   resource_details)] for g in resource_groups]
222

    
223
    # order groups, also include unknown groups
224
    groups_order = resources_meta.get('groups_order')
225
    for g in resource_groups.keys():
226
        if not g in groups_order:
227
            groups_order.append(g)
228

    
229
    # order resources, also include unknown resources
230
    resources_order = resources_meta.get('resources_order')
231
    for r in resource_keys:
232
        if not r in resources_order:
233
            resources_order.append(r)
234

    
235
    # sort catalog groups
236
    resource_catalog = sorted(resource_catalog,
237
                              key=lambda g: groups_order.index(g[0]))
238

    
239
    # sort groups
240
    def groupindex(g):
241
        return groups_order.index(g[0])
242
    resource_groups_list = sorted([(k, v) for k, v in resource_groups.items()],
243
                                  key=groupindex)
244
    resource_groups = OrderedDict(resource_groups_list)
245

    
246
    # sort resources
247
    def resourceindex(r):
248
        return resources_order.index(r['str_repr'])
249

    
250
    for index, group in enumerate(resource_catalog):
251
        resource_catalog[index][1] = sorted(resource_catalog[index][1],
252
                                            key=resourceindex)
253
        if len(resource_catalog[index][1]) == 0:
254
            resource_catalog.pop(index)
255
            for gindex, g in enumerate(resource_groups):
256
                if g[0] == group[0]:
257
                    resource_groups.pop(gindex)
258

    
259
    # filter out resources which user cannot request in a project application
260
    exclude = resources_meta.get('exclude_from_usage', [])
261
    for group_index, group_resources in enumerate(list(resource_catalog)):
262
        group, resources = group_resources
263
        for index, resource in list(enumerate(resources)):
264
            if for_project and not resource.get('allow_in_projects'):
265
                resources.remove(resource)
266
            if resource.get('str_repr') in exclude and for_usage:
267
                resources.remove(resource)
268

    
269
    # cleanup empty groups
270
    for group_index, group_resources in enumerate(list(resource_catalog)):
271
        group, resources = group_resources
272
        if len(resources) == 0:
273
            resource_catalog.pop(group_index)
274
            resource_groups.pop(group)
275

    
276

    
277
    return resource_catalog, resource_groups