Statistics
| Branch: | Tag: | Revision:

root / snf-astakos-app / astakos / im / api / __init__.py @ 9a4600b7

History | View | Annotate | Download (9 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 (
46
    Fault, ItemNotFound, InternalServerError, BadRequest)
47
from astakos.im.settings import (
48
    INVITATIONS_ENABLED, COOKIE_NAME, EMAILCHANGE_ENABLED, QUOTAHOLDER_URL)
49
from astakos.im.forms import FeedbackForm
50
from astakos.im.functions import send_feedback as send_feedback_func
51

    
52
import logging
53
logger = logging.getLogger(__name__)
54

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

    
57
absolute = lambda request, url: request.build_absolute_uri(url)
58

    
59

    
60
def render_fault(request, fault):
61
    if isinstance(fault, InternalServerError) and settings.DEBUG:
62
        fault.details = format_exc(fault)
63

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

    
72

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

    
92

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

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

    
105
    if callback:
106
        mimetype = 'application/javascript'
107
        data = '%s(%s)' % (callback, data)
108

    
109
    return HttpResponse(content=data, mimetype=mimetype)
110

    
111

    
112
@api_method()
113
def get_menu(request, with_extra_links=False, with_signout=True):
114
    user = request.user
115
    from_location = request.GET.get('location')
116
    index_url = reverse('index')
117

    
118
    l = [{'url': absolute(request, index_url), 'name': _("Sign in")}]
119
    if user.is_authenticated():
120
        l = []
121
        append = l.append
122
        item = MenuItem
123
        item.current_path = absolute(request, request.path)
124
        append(item(
125
               url=absolute(request, reverse('index')),
126
               name=user.email))
127
        if with_extra_links:
128
            append(item(
129
                url=absolute(request, reverse('landing')),
130
                name="Overview"))
131
        if with_signout:
132
            append(item(
133
                   url=absolute(request, reverse('edit_profile')),
134
                   name="Dashboard"))
135
        if with_extra_links:
136
            append(item(url=absolute(request, reverse('edit_profile')),
137
                    name="Profile"))
138

    
139
        if with_extra_links:
140
            if INVITATIONS_ENABLED:
141
                append(item(
142
                       url=absolute(request, reverse('invite')),
143
                       name="Invitations"))
144

    
145

    
146
            append(item(
147
                   url=absolute(request, reverse('resource_usage')),
148
                   name="Usage"))
149
            if QUOTAHOLDER_URL:
150
                append(item(
151
                       url=absolute(request, reverse('project_list')),
152
                       name="Projects"))
153
            #append(item(
154
                #url=absolute(request, reverse('api_access')),
155
                #name="API Access"))
156

    
157
            append(item(
158
                   url=absolute(request, reverse('feedback')),
159
                   name="Contact"))
160
        if with_signout:
161
            append(item(
162
                   url=absolute(request, reverse('logout')),
163
                   name="Sign out"))
164

    
165
    callback = request.GET.get('callback', None)
166
    data = json.dumps(tuple(l))
167
    mimetype = 'application/json'
168

    
169
    if callback:
170
        mimetype = 'application/javascript'
171
        data = '%s(%s)' % (callback, data)
172

    
173
    return HttpResponse(content=data, mimetype=mimetype)
174

    
175

    
176
class MenuItem(dict):
177
    current_path = ''
178

    
179
    def __init__(self, *args, **kwargs):
180
        super(MenuItem, self).__init__(*args, **kwargs)
181
        if kwargs.get('url') or kwargs.get('submenu'):
182
            self.__set_is_active__()
183

    
184
    def __setitem__(self, key, value):
185
        super(MenuItem, self).__setitem__(key, value)
186
        if key in ('url', 'submenu'):
187
            self.__set_is_active__()
188

    
189
    def __set_is_active__(self):
190
        if self.get('is_active'):
191
            return
192
        if self.current_path.startswith(self.get('url')):
193
            self.__setitem__('is_active', True)
194
        else:
195
            submenu = self.get('submenu', ())
196
            current = (i for i in submenu if i.get('url') == self.current_path)
197
            try:
198
                current_node = current.next()
199
                if not current_node.get('is_active'):
200
                    current_node.__setitem__('is_active', True)
201
                self.__setitem__('is_active', True)
202
            except StopIteration:
203
                return
204

    
205
    def __setattribute__(self, name, value):
206
        super(MenuItem, self).__setattribute__(name, value)
207
        if name == 'current_path':
208
            self.__set_is_active__()
209

    
210
def __get_uuid_displayname_catalogs(request, user_call=True):
211
    # Normal Response Codes: 200
212
    # Error Response Codes: badRequest (400)
213

    
214
    try:
215
        input_data = json.loads(request.raw_post_data)
216
    except:
217
        raise BadRequest('Request body should be json formatted.')
218
    else:
219
        uuids = input_data.get('uuids', [])
220
        if uuids == None and user_call:
221
            uuids = []
222
        displaynames = input_data.get('displaynames', [])
223
        if displaynames == None and user_call:
224
            displaynames = []
225
        d  = {'uuid_catalog':AstakosUser.objects.uuid_catalog(uuids),
226
              'displayname_catalog':AstakosUser.objects.displayname_catalog(displaynames)}
227

    
228
        response = HttpResponse()
229
        response.status = 200
230
        response.content = json.dumps(d)
231
        response['Content-Type'] = 'application/json; charset=UTF-8'
232
        response['Content-Length'] = len(response.content)
233
        return response
234

    
235
def __send_feedback(request, email_template_name='im/feedback_mail.txt', user=None):
236
    if not user:
237
        auth_token = request.POST.get('auth', '')
238
        if not auth_token:
239
            raise BadRequest('Missing user authentication')
240

    
241
        try:
242
            user = AstakosUser.objects.get(auth_token=auth_token)
243
        except AstakosUser.DoesNotExist:
244
            raise BadRequest('Invalid user authentication')
245

    
246
    form = FeedbackForm(request.POST)
247
    if not form.is_valid():
248
        raise BadRequest('Invalid data')
249

    
250
    msg = form.cleaned_data['feedback_msg']
251
    data = form.cleaned_data['feedback_data']
252
    try:
253
        send_feedback_func(msg, data, user, email_template_name)
254
    except:
255
        return HttpResponse(status=502)
256
    return HttpResponse(status=200)