Example #1
0
    def read(self, request, vendor, name, version):

        widget = get_object_or_404(
            Widget, resource__vendor=vendor, resource__short_name=name, resource__version=version
        )
        if not widget.is_available_for(request.user):
            raise Http403()

        # check if the xhtml code has been cached
        if widget.xhtml.cacheable:

            cache_key = widget.xhtml.get_cache_key(get_current_domain(request))
            cache_entry = cache.get(cache_key)
            if cache_entry is not None:
                response = HttpResponse(cache_entry["code"], mimetype="%s; charset=UTF-8" % cache_entry["content_type"])
                patch_cache_headers(response, cache_entry["timestamp"], cache_entry["timeout"])
                return response

        # process xhtml
        xhtml = widget.xhtml

        content_type = xhtml.content_type
        if not content_type:
            content_type = "text/html"

        force_base = False
        base_url = xhtml.url
        if not base_url.startswith(("http://", "https://")):
            base_url = get_absolute_reverse_url(
                "wirecloud_showcase.media", args=(base_url.split("/", 4)), request=request
            )
            force_base = True

        code = xhtml.code
        if not xhtml.cacheable or code == "":
            try:
                if xhtml.url.startswith(("http://", "https://")):
                    code = downloader.download_http_content(urljoin(base_url, xhtml.url), user=request.user)
                else:
                    code = downloader.download_http_content(
                        "file://" + os.path.join(showcase_utils.wgt_deployer.root_dir, xhtml.url), user=request.user
                    )

            except Exception, e:
                # FIXME: Send the error or use the cached original code?
                msg = _("XHTML code is not accessible: %(errorMsg)s") % {"errorMsg": e.message}
                return HttpResponse(get_xml_error_response(msg), mimetype="application/xml; charset=UTF-8")
Example #2
0
    def __call__(self, request, *args, **kwargs):

        request_method = request.method.upper()
        if request_method not in self.permitted_methods:
            return HttpResponseNotAllowed(self.permitted_methods)

        try:
            response = getattr(self, METHOD_MAPPING[request_method])(request, *args, **kwargs)
        except (Http404, PermissionDenied):
            raise
        except HttpBadCredentials as e:
            return build_auth_error_response(request, e.message, e.error_info)
        except ErrorResponse as e:
            return e.response

        if request_method in ("HEAD", "GET"):
            patch_cache_headers(response)

        return response
Example #3
0
    def read(self, request, vendor, name, version):

        resource = get_object_or_404(CatalogueResource.objects.select_related('widget__xhtml'), vendor=vendor, short_name=name, version=version)
        if not resource.is_available_for(request.user):
            raise Http403()

        if resource.resource_type() != 'widget':
            raise Http404()

        widget_info = json.loads(resource.json_description)

        # check if the xhtml code has been cached
        if widget_info['code_cacheable'] is True:

            cache_key = resource.widget.xhtml.get_cache_key(get_current_domain(request))
            cache_entry = cache.get(cache_key)
            if cache_entry is not None:
                response = HttpResponse(cache_entry['code'], mimetype=cache_entry['mimetype'])
                patch_cache_headers(response, cache_entry['timestamp'], cache_entry['timeout'])
                return response

        # process xhtml
        xhtml = resource.widget.xhtml
        content_type = widget_info.get('code_content_type', 'text/html')
        charset = widget_info.get('code_charset', 'utf-8')

        force_base = False
        base_url = xhtml.url
        if not base_url.startswith(('http://', 'https://')):
            base_url = get_absolute_reverse_url('wirecloud_showcase.media', args=(base_url.split('/', 4)), request=request)
            force_base = True

        code = xhtml.code
        if not xhtml.cacheable or code == '':
            try:
                if xhtml.url.startswith(('http://', 'https://')):
                    code = downloader.download_http_content(urljoin(base_url, xhtml.url), user=request.user)
                else:
                    code = downloader.download_http_content('file://' + os.path.join(showcase_utils.wgt_deployer.root_dir, url2pathname(xhtml.url)), user=request.user)

            except Exception, e:
                msg = _("XHTML code is not accessible: %(errorMsg)s") % {'errorMsg': e.message}
                return build_error_response(request, 502, msg)
Example #4
0
    def __call__(self, request, *args, **kwargs):

        request_method = request.method.upper()
        if request_method not in self.permitted_methods:
            return HttpResponseNotAllowed(self.permitted_methods)

        try:
            response = getattr(self,
                               METHOD_MAPPING[request_method])(request, *args,
                                                               **kwargs)
        except (Http404, PermissionDenied):
            raise
        except HttpBadCredentials as e:
            return build_auth_error_response(request, e.message, e.error_info)
        except ErrorResponse as e:
            return e.response

        if request_method in ('HEAD', 'GET'):
            patch_cache_headers(response)

        return response
Example #5
0
    def read(self, request, vendor, name, version):

        resource = get_object_or_404(CatalogueResource.objects.select_related('widget__xhtml'), vendor=vendor, short_name=name, version=version)
        # For now, all widgets are freely accessible/distributable
        #if not resource.is_available_for(request.user):
        #    return build_error_response(request, 403, "Forbidden")

        if resource.resource_type() != 'widget':
            raise Http404()

        mode = request.GET.get('mode', 'classic')
        widget_info = json.loads(resource.json_description)

        # check if the xhtml code has been cached
        if widget_info['contents']['cacheable'] is True:

            cache_key = resource.widget.xhtml.get_cache_key(get_current_domain(request), mode)
            cache_entry = cache.get(cache_key)
            if cache_entry is not None:
                response = HttpResponse(cache_entry['code'], content_type=cache_entry['content_type'])
                patch_cache_headers(response, cache_entry['timestamp'], cache_entry['timeout'])
                return response

        # process xhtml
        xhtml = resource.widget.xhtml
        content_type = widget_info['contents'].get('contenttype', 'text/html')
        charset = widget_info['contents'].get('charset', 'utf-8')

        force_base = False
        base_url = xhtml.url
        if not base_url.startswith(('http://', 'https://')):
            # Newer versions of Django urlencode urls created using reverse
            # Fix double encoding
            base_url = urlunquote(base_url)
            base_url = get_absolute_reverse_url('wirecloud.showcase_media', args=(base_url.split('/', 4)), request=request)
            force_base = True

        code = xhtml.code
        if not xhtml.cacheable or code == '':
            try:
                if xhtml.url.startswith(('http://', 'https://')):
                    code = download_http_content(urljoin(base_url, xhtml.url), user=request.user)
                else:
                    code = download_local_file(os.path.join(showcase_utils.wgt_deployer.root_dir, url2pathname(xhtml.url)))

            except Exception as e:
                return build_response(request, 502, {'error_msg': _("(X)HTML code is not accessible"), 'details': "%s" % e}, WIDGET_ERROR_FORMATTERS)
        else:
            # Code contents comes as unicode from persistence, we need bytes
            code = code.encode(charset)

        if xhtml.cacheable and (xhtml.code == '' or xhtml.code_timestamp is None):
            try:
                xhtml.code = code.decode(charset)
            except UnicodeDecodeError:
                msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
                return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)

            xhtml.code_timestamp = time.time() * 1000
            xhtml.save()
        elif not xhtml.cacheable and xhtml.code != '':
            xhtml.code = ''
            xhtml.code_timestamp = None
            xhtml.save()

        try:
            code = fix_widget_code(code, base_url, content_type, request, charset, xhtml.use_platform_style, process_requirements(widget_info['requirements']), force_base, mode)
        except UnicodeDecodeError:
            msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
            return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)
        except Exception as e:
            msg = _('Error processing widget code')
            return build_response(request, 502, {'error_msg': msg, 'details':"%s" % e}, WIDGET_ERROR_FORMATTERS)

        if xhtml.cacheable:
            cache_timeout = 31536000  # 1 year
            cache_entry = {
                'code': code,
                'content_type': '%s; charset=%s' % (content_type, charset),
                'timestamp': xhtml.code_timestamp,
                'timeout': cache_timeout,
            }
            cache.set(cache_key, cache_entry, cache_timeout)
        else:
            cache_timeout = 0

        response = HttpResponse(code, content_type='%s; charset=%s' % (content_type, charset))
        patch_cache_headers(response, xhtml.code_timestamp, cache_timeout)
        return response
Example #6
0
def feature_collection(request):
    features = get_active_features_info()

    response = HttpResponse(json.dumps(features, sort_keys=True),
                            content_type='application/json; charset=UTF-8')
    return patch_cache_headers(response)
Example #7
0
def feature_collection(request):
    features = get_active_features_info()

    response = HttpResponse(json.dumps(features, sort_keys=True), content_type='application/json; charset=UTF-8')
    return patch_cache_headers(response)
Example #8
0
def process_widget_code(request, resource):

    mode = request.GET.get('mode', 'classic')
    theme = request.GET.get('theme', get_active_theme_name())
    widget_info = json.loads(resource.json_description)

    # check if the xhtml code has been cached
    if widget_info['contents']['cacheable'] is True:

        cache_key = resource.widget.xhtml.get_cache_key(get_current_domain(request), mode, theme)
        cache_entry = cache.get(cache_key)
        if cache_entry is not None:
            response = HttpResponse(cache_entry['code'], content_type=cache_entry['content_type'])
            patch_cache_headers(response, cache_entry['timestamp'], cache_entry['timeout'])
            return response

    # process xhtml
    xhtml = resource.widget.xhtml
    content_type = widget_info['contents'].get('contenttype', 'text/html')
    charset = widget_info['contents'].get('charset', 'utf-8')

    code = xhtml.code
    if not xhtml.cacheable or code == '':
        try:
            code = download_local_file(os.path.join(showcase_utils.wgt_deployer.root_dir, url2pathname(xhtml.url)))

        except Exception as e:
            if isinstance(e, IOError) and e.errno == errno.ENOENT:
                return build_response(request, 404, {'error_msg': _("Widget code not found"), 'details': "%s" % e}, WIDGET_ERROR_FORMATTERS)
            else:
                return build_response(request, 500, {'error_msg': _("Error reading widget code"), 'details': "%s" % e}, WIDGET_ERROR_FORMATTERS)
    else:
        # Code contents comes as unicode from persistence, we need bytes
        code = code.encode(charset)

    if xhtml.cacheable and (xhtml.code == '' or xhtml.code_timestamp is None):
        try:
            xhtml.code = code.decode(charset)
        except UnicodeDecodeError:
            msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
            return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)

        xhtml.code_timestamp = time.time() * 1000
        xhtml.save()

    try:
        code = fix_widget_code(code, content_type, request, charset, xhtml.use_platform_style, process_requirements(widget_info['requirements']), mode, theme)
    except UnicodeDecodeError:
        msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
        return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)
    except Exception as e:
        msg = _('Error processing widget code')
        return build_response(request, 502, {'error_msg': msg, 'details':"%s" % e}, WIDGET_ERROR_FORMATTERS)

    if xhtml.cacheable:
        cache_timeout = 31536000  # 1 year
        cache_entry = {
            'code': code,
            'content_type': '%s; charset=%s' % (content_type, charset),
            'timestamp': xhtml.code_timestamp,
            'timeout': cache_timeout,
        }
        cache.set(cache_key, cache_entry, cache_timeout)
    else:
        cache_timeout = 0

    response = HttpResponse(code, content_type='%s; charset=%s' % (content_type, charset))
    patch_cache_headers(response, xhtml.code_timestamp, cache_timeout)
    return response
Example #9
0
    def read(self, request, vendor, name, version):

        resource = get_object_or_404(CatalogueResource.objects.select_related('widget__xhtml'), vendor=vendor, short_name=name, version=version)
        # For now, all widgets are freely accessible/distributable
        #if not resource.is_available_for(request.user):
        #    return build_error_response(request, 403, "Forbidden")

        if resource.resource_type() != 'widget':
            raise Http404()

        mode = request.GET.get('mode', 'classic')
        widget_info = json.loads(resource.json_description)

        # check if the xhtml code has been cached
        if widget_info['contents']['cacheable'] is True:

            cache_key = resource.widget.xhtml.get_cache_key(get_current_domain(request), mode)
            cache_entry = cache.get(cache_key)
            if cache_entry is not None:
                response = HttpResponse(cache_entry['code'], content_type=cache_entry['content_type'])
                patch_cache_headers(response, cache_entry['timestamp'], cache_entry['timeout'])
                return response

        # process xhtml
        xhtml = resource.widget.xhtml
        content_type = widget_info['contents'].get('contenttype', 'text/html')
        charset = widget_info['contents'].get('charset', 'utf-8')

        force_base = False
        base_url = xhtml.url
        if not base_url.startswith(('http://', 'https://')):
            # Newer versions of Django urlencode urls created using reverse
            # Fix double encoding
            base_url = urlunquote(base_url)
            base_url = get_absolute_reverse_url('wirecloud.showcase_media', args=(base_url.split('/', 3)), request=request)
            force_base = True

        code = xhtml.code
        if not xhtml.cacheable or code == '':
            try:
                if xhtml.url.startswith(('http://', 'https://')):
                    code = download_http_content(urljoin(base_url, xhtml.url), user=request.user)
                else:
                    code = download_local_file(os.path.join(showcase_utils.wgt_deployer.root_dir, url2pathname(xhtml.url)))

            except Exception as e:
                return build_response(request, 502, {'error_msg': _("(X)HTML code is not accessible"), 'details': "%s" % e}, WIDGET_ERROR_FORMATTERS)
        else:
            # Code contents comes as unicode from persistence, we need bytes
            code = code.encode(charset)

        if xhtml.cacheable and (xhtml.code == '' or xhtml.code_timestamp is None):
            try:
                xhtml.code = code.decode(charset)
            except UnicodeDecodeError:
                msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
                return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)

            xhtml.code_timestamp = time.time() * 1000
            xhtml.save()
        elif not xhtml.cacheable and xhtml.code != '':
            xhtml.code = ''
            xhtml.code_timestamp = None
            xhtml.save()

        try:
            code = fix_widget_code(code, base_url, content_type, request, charset, xhtml.use_platform_style, process_requirements(widget_info['requirements']), force_base, mode)
        except UnicodeDecodeError:
            msg = _('Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).') % {'charset': charset}
            return build_response(request, 502, {'error_msg': msg}, WIDGET_ERROR_FORMATTERS)
        except Exception as e:
            msg = _('Error processing widget code')
            return build_response(request, 502, {'error_msg': msg, 'details':"%s" % e}, WIDGET_ERROR_FORMATTERS)

        if xhtml.cacheable:
            cache_timeout = 31536000  # 1 year
            cache_entry = {
                'code': code,
                'content_type': '%s; charset=%s' % (content_type, charset),
                'timestamp': xhtml.code_timestamp,
                'timeout': cache_timeout,
            }
            cache.set(cache_key, cache_entry, cache_timeout)
        else:
            cache_timeout = 0

        response = HttpResponse(code, content_type='%s; charset=%s' % (content_type, charset))
        patch_cache_headers(response, xhtml.code_timestamp, cache_timeout)
        return response
Example #10
0
def process_widget_code(request, resource):

    mode = request.GET.get('mode', 'classic')
    theme = request.GET.get('theme', get_active_theme_name())
    widget_info = json.loads(resource.json_description)

    # check if the xhtml code has been cached
    if widget_info['contents']['cacheable'] is True:

        cache_key = resource.widget.xhtml.get_cache_key(
            get_current_domain(request), mode, theme)
        cache_entry = cache.get(cache_key)
        if cache_entry is not None:
            response = HttpResponse(cache_entry['code'],
                                    content_type=cache_entry['content_type'])
            patch_cache_headers(response, cache_entry['timestamp'],
                                cache_entry['timeout'])
            return response

    # process xhtml
    xhtml = resource.widget.xhtml
    content_type = widget_info['contents'].get('contenttype', 'text/html')
    charset = widget_info['contents'].get('charset', 'utf-8')

    code = xhtml.code
    if not xhtml.cacheable or code == '':
        try:
            code = download_local_file(
                os.path.join(showcase_utils.wgt_deployer.root_dir,
                             url2pathname(xhtml.url)))

        except Exception as e:
            if isinstance(e, IOError) and e.errno == errno.ENOENT:
                return build_response(request, 404, {
                    'error_msg': _("Widget code not found"),
                    'details': "%s" % e
                }, WIDGET_ERROR_FORMATTERS)
            else:
                return build_response(
                    request, 500, {
                        'error_msg': _("Error reading widget code"),
                        'details': "%s" % e
                    }, WIDGET_ERROR_FORMATTERS)
    else:
        # Code contents comes as unicode from persistence, we need bytes
        code = code.encode(charset)

    if xhtml.cacheable and (xhtml.code == '' or xhtml.code_timestamp is None):
        try:
            xhtml.code = code.decode(charset)
        except UnicodeDecodeError:
            msg = _(
                'Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).'
            ) % {
                'charset': charset
            }
            return build_response(request, 502, {'error_msg': msg},
                                  WIDGET_ERROR_FORMATTERS)

        xhtml.code_timestamp = time.time() * 1000
        xhtml.save()

    try:
        code = fix_widget_code(
            code, content_type, request, charset, xhtml.use_platform_style,
            process_requirements(widget_info['requirements']), mode, theme)
    except UnicodeDecodeError:
        msg = _(
            'Widget code was not encoded using the specified charset (%(charset)s as stated in the widget description file).'
        ) % {
            'charset': charset
        }
        return build_response(request, 502, {'error_msg': msg},
                              WIDGET_ERROR_FORMATTERS)
    except Exception as e:
        msg = _('Error processing widget code')
        return build_response(request, 502, {
            'error_msg': msg,
            'details': "%s" % e
        }, WIDGET_ERROR_FORMATTERS)

    if xhtml.cacheable:
        cache_timeout = 31536000  # 1 year
        cache_entry = {
            'code': code,
            'content_type': '%s; charset=%s' % (content_type, charset),
            'timestamp': xhtml.code_timestamp,
            'timeout': cache_timeout,
        }
        cache.set(cache_key, cache_entry, cache_timeout)
    else:
        cache_timeout = 0

    response = HttpResponse(code,
                            content_type='%s; charset=%s' %
                            (content_type, charset))
    patch_cache_headers(response, xhtml.code_timestamp, cache_timeout)
    return response
Example #11
0
            return build_error_response(request, 502, msg % {'charset': charset})

        if xhtml.cacheable:
            cache_timeout = 31536000  # 1 year
            cache_entry = {
                'code': code,
                'mimetype': '%s; charset=%s' % (content_type, charset),
                'timestamp': xhtml.code_timestamp,
                'timeout': cache_timeout,
            }
            cache.set(cache_key, cache_entry, cache_timeout)
        else:
            cache_timeout = 0

        response = HttpResponse(code, mimetype='%s; charset=%s' % (content_type, charset))
        patch_cache_headers(response, xhtml.code_timestamp, cache_timeout)
        return response


@require_GET
def serve_showcase_media(request, vendor, name, version, file_path):

    resource = get_object_or_404(CatalogueResource, vendor=vendor, short_name=name, version=version)
    if not resource.is_available_for(request.user):
        return HttpResponseForbidden()

    base_dir = showcase_utils.wgt_deployer.get_base_dir(vendor, name, version)
    local_path = os.path.join(base_dir, url2pathname(file_path))

    if not os.path.isfile(local_path):
        return HttpResponse(status=404)