Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / __init__.py @ 78bc0b94

History | View | Annotate | Download (7.1 kB)

1
# Copyright 2011-2012 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 functools import wraps
35
from traceback import format_exc
36
from urllib import quote, unquote
37

    
38
from django.http import HttpResponse
39
from django.utils import simplejson as json
40
from django.conf import settings
41
from django.core.urlresolvers import reverse
42
from django.utils.translation import ugettext as _
43

    
44
from astakos.im.models import AstakosUser, Service, Resource
45
from astakos.im.api.faults import Fault, ItemNotFound, InternalServerError, BadRequest
46
from astakos.im.settings import (
47
    INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED, QUOTAHOLDER_URL)
48

    
49
import logging
50
logger = logging.getLogger(__name__)
51

    
52
format = ('%a, %d %b %Y %H:%M:%S GMT')
53

    
54
absolute = lambda request, url: request.build_absolute_uri(url)
55

    
56

    
57
def render_fault(request, fault):
58
    if isinstance(fault, InternalServerError) and settings.DEBUG:
59
        fault.details = format_exc(fault)
60

    
61
    request.serialization = 'text'
62
    data = fault.message + '\n'
63
    if fault.details:
64
        data += '\n' + fault.details
65
    response = HttpResponse(data, status=fault.code)
66
    response['Content-Length'] = len(response.content)
67
    return response
68

    
69

    
70
def api_method(http_method=None):
71
    """Decorator function for views that implement an API method."""
72
    def decorator(func):
73
        @wraps(func)
74
        def wrapper(request, *args, **kwargs):
75
            try:
76
                if http_method and request.method != http_method:
77
                    raise BadRequest('Method not allowed.')
78
                response = func(request, *args, **kwargs)
79
                return response
80
            except Fault, fault:
81
                return render_fault(request, fault)
82
            except BaseException, e:
83
                logger.exception('Unexpected error: %s' % e)
84
                fault = InternalServerError('Unexpected error')
85
                return render_fault(request, fault)
86
        return wrapper
87
    return decorator
88

    
89

    
90
def get_services_dict():
91
    services = Service.objects.all()
92
    data = tuple({'id': s.pk, 'name': s.name, 'url': s.url, 'icon':
93
                 s.icon} for s in services)
94
    return data
95

    
96
@api_method(http_method=None)
97
def get_services(request):
98
    callback = request.GET.get('callback', None)
99
    mimetype = 'application/json'
100
    data = json.dumps(get_services_dict())
101

    
102
    if callback:
103
        mimetype = 'application/javascript'
104
        data = '%s(%s)' % (callback, data)
105

    
106
    return HttpResponse(content=data, mimetype=mimetype)
107

    
108

    
109
@api_method()
110
def get_menu(request, with_extra_links=False, with_signout=True):
111
    user = request.user
112
    from_location = request.GET.get('location')
113
    index_url = reverse('index')
114
    if from_location:
115
        index_url = "%s?next=%s" % (index_url, from_location)
116

    
117
    l = [{'url': absolute(request, index_url), 'name': _("Sign in")}]
118
    if user.is_authenticated():
119
        l = []
120
        append = l.append
121
        item = MenuItem
122
        item.current_path = absolute(request, request.path)
123
        append(item(
124
               url=absolute(request, reverse('index')),
125
               name=user.email))
126
        if with_extra_links:
127
            append(item(
128
                url=absolute(request, reverse('landing')),
129
                name="Welcome")) 
130
        append(item(url=absolute(request, reverse('edit_profile')),
131
               name="Profile"))
132
        if with_extra_links:
133
            #if EMAILCHANGE_ENABLED:
134
                #append(item(
135
                #      url=absolute(request, reverse('email_change')),
136
                #       name="Change email"))
137
            if INVITATIONS_ENABLED:
138
                append(item(
139
                       url=absolute(request, reverse('invite')),
140
                       name="Invitations"))
141

    
142
            if QUOTAHOLDER_URL:
143
                append(item(
144
                       url=absolute(request, reverse('project_list')),
145
                       name="Projects"))
146
            append(item(
147
                   url=absolute(request, reverse('resource_usage')),
148
                   name="Usage"))
149
            
150
            append(item(
151
                   url=absolute(request, reverse('feedback')),
152
                   name="Contact"))
153
        if with_signout:
154
            append(item(
155
                   url=absolute(request, reverse('logout')),
156
                   name="Sign out"))
157

    
158
    callback = request.GET.get('callback', None)
159
    data = json.dumps(tuple(l))
160
    mimetype = 'application/json'
161

    
162
    if callback:
163
        mimetype = 'application/javascript'
164
        data = '%s(%s)' % (callback, data)
165

    
166
    return HttpResponse(content=data, mimetype=mimetype)
167

    
168

    
169
class MenuItem(dict):
170
    current_path = ''
171

    
172
    def __init__(self, *args, **kwargs):
173
        super(MenuItem, self).__init__(*args, **kwargs)
174
        if kwargs.get('url') or kwargs.get('submenu'):
175
            self.__set_is_active__()
176

    
177
    def __setitem__(self, key, value):
178
        super(MenuItem, self).__setitem__(key, value)
179
        if key in ('url', 'submenu'):
180
            self.__set_is_active__()
181

    
182
    def __set_is_active__(self):
183
        if self.get('is_active'):
184
            return
185
        if self.current_path.startswith(self.get('url')):
186
            self.__setitem__('is_active', True)
187
        else:
188
            submenu = self.get('submenu', ())
189
            current = (i for i in submenu if i.get('url') == self.current_path)
190
            try:
191
                current_node = current.next()
192
                if not current_node.get('is_active'):
193
                    current_node.__setitem__('is_active', True)
194
                self.__setitem__('is_active', True)
195
            except StopIteration:
196
                return
197

    
198
    def __setattribute__(self, name, value):
199
        super(MenuItem, self).__setattribute__(name, value)
200
        if name == 'current_path':
201
            self.__set_is_active__()