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

        resource = get_object_or_404(CatalogueResource, vendor=vendor, short_name=name, version=version)
        resource_info = json.loads(resource.json_description)
        if resource_info['doc'] == '':
            raise Http404

        doc_base_url = None
        if resource_info['doc'].startswith(('http://', 'https://')):
            doc_code = _('You can find the userguide of this component in this external <a target="_blank" href="%s">link</a>') % resource_info['doc']
            doc_code = '<div style="margin-top: 10px"><p>%s</p></div>' % doc_code
        else:
            doc_relative_path = url2pathname(resource_info['doc'])
            doc_base_url = force_trailing_slash(urljoin(resource.get_template_url(request=request, for_base=True), pathname2url(os.path.dirname(doc_relative_path))))
            doc_path = os.path.join(catalogue_utils.wgt_deployer.get_base_dir(vendor, name, version), doc_relative_path)

            (doc_filename_root, doc_filename_ext) = os.path.splitext(doc_path)
            localized_doc_path = doc_filename_root + '.' + get_language() + doc_filename_ext

            try:
                doc_code = download_local_file(localized_doc_path).decode('utf-8')
            except:
                try:
                    doc_code = download_local_file(doc_path).decode('utf-8')
                except:
                    msg = _('Error opening the userguide file')
                    doc_code = '<div class="margin-top: 10px"><p>%s</p></div>' % msg

        doc_pre_html = markdown.markdown(doc_code, output_format='xhtml5', extensions=['codehilite', 'fenced_code'])
        doc = clean_html(doc_pre_html, base_url=doc_base_url)
        return HttpResponse(doc, content_type='application/xhtml+xml; charset=UTF-8')
Example #2
0
    def read(self, request, vendor, name, version):

        from_version = request.GET.get('from')
        if from_version is not None:
            try:
                from_version = Version(from_version)
            except:
                return build_error_response(
                    request, 422, _("Missing parameter: template_uri or file"))

        resource = get_object_or_404(CatalogueResource,
                                     vendor=vendor,
                                     short_name=name,
                                     version=version)
        resource_info = resource.get_processed_info(process_urls=False)
        if resource_info['changelog'] == '':
            raise Http404

        doc_relative_path = url2pathname(resource_info['changelog'])
        doc_base_url = force_trailing_slash(
            urljoin(resource.get_template_url(request=request, for_base=True),
                    pathname2url(os.path.dirname(doc_relative_path))))
        doc_path = os.path.join(
            catalogue_utils.wgt_deployer.get_base_dir(vendor, name, version),
            doc_relative_path)

        (doc_filename_root, doc_filename_ext) = os.path.splitext(doc_path)
        localized_doc_path = doc_filename_root + '.' + get_language(
        ) + doc_filename_ext

        try:
            doc_code = download_local_file(localized_doc_path).decode('utf-8')
        except:
            try:
                doc_code = download_local_file(doc_path).decode('utf-8')
            except:
                msg = _('Error opening the changelog file')
                doc_code = '<div class="margin-top: 10px"><p>%s</p></div>' % msg

        doc_pre_html = markdown.markdown(doc_code,
                                         output_format='xhtml5',
                                         extensions=[
                                             'markdown.extensions.codehilite',
                                             'markdown.extensions.fenced_code'
                                         ])

        if from_version:
            doc_pre_html = filter_changelog(doc_pre_html, from_version)
            if doc_pre_html.strip() == '':
                raise Http404

        doc = clean_html(doc_pre_html, base_url=doc_base_url)
        return HttpResponse(
            doc, content_type='application/xhtml+xml; charset=UTF-8')
Example #3
0
    def read(self, request, vendor, name, version):

        resource = get_object_or_404(CatalogueResource,
                                     vendor=vendor,
                                     short_name=name,
                                     version=version)
        resource_info = resource.json_description
        if resource_info['doc'] == '':
            raise Http404

        doc_base_url = None
        if resource_info['doc'].startswith(('http://', 'https://')):
            doc_code = _(
                'You can find the userguide of this component in this external <a target="_blank" href="%s">link</a>'
            ) % resource_info['doc']
            doc_code = '<div style="margin-top: 10px"><p>%s</p></div>' % doc_code
        else:
            doc_relative_path = url2pathname(resource_info['doc'])
            doc_base_url = force_trailing_slash(
                urljoin(
                    resource.get_template_url(request=request, for_base=True),
                    pathname2url(os.path.dirname(doc_relative_path))))
            doc_path = os.path.join(
                catalogue_utils.wgt_deployer.get_base_dir(
                    vendor, name, version), doc_relative_path)

            (doc_filename_root, doc_filename_ext) = os.path.splitext(doc_path)
            localized_doc_path = doc_filename_root + '.' + get_language(
            ) + doc_filename_ext

            try:
                doc_code = download_local_file(localized_doc_path).decode(
                    'utf-8')
            except:
                try:
                    doc_code = download_local_file(doc_path).decode('utf-8')
                except:
                    msg = _('Error opening the userguide file')
                    doc_code = '<div class="margin-top: 10px"><p>%s</p></div>' % msg

        doc_pre_html = markdown.markdown(doc_code,
                                         output_format='xhtml5',
                                         extensions=[
                                             'markdown.extensions.codehilite',
                                             'markdown.extensions.fenced_code'
                                         ])
        doc = clean_html(doc_pre_html, base_url=doc_base_url)
        return HttpResponse(
            doc, content_type='application/xhtml+xml; charset=UTF-8')
    def search_resource(self, vendor, name, version, user):

        if self._name == 'local':
            resources = CatalogueResource.objects.filter(vendor=vendor, short_name=name, version=version)[:1]

            if len(resources) == 1:
                resource = resources[0]
                base_dir = catalogue_utils.wgt_deployer.get_base_dir(vendor, name, version)
                downloaded_file = download_local_file(os.path.join(base_dir, resource.template_uri))

                return {
                    'downloaded_file': downloaded_file,
                }
            else:
                return None
        else:

            path = '/'.join(('catalogue', 'resource', vendor, name, version))
            url = iri_to_uri(urljoin(self._options['url'], path))
            response = requests.get(url)

            if response.status_code == 200:
                data = json.loads(response.content)
                downloaded_file = download_http_content(data['uriTemplate'], user=user)
                return {
                    'downloaded_file': downloaded_file,
                    'template_url': data['uriTemplate'],
                    'packaged': data['packaged']
                }
            else:
                return None
Example #5
0
    def read(self, request, vendor, name, version):

        from_version = request.GET.get('from')
        if from_version is not None:
            try:
                from_version = Version(from_version)
            except:
                return build_error_response(request, 422, _("Missing parameter: template_uri or file"))

        resource = get_object_or_404(CatalogueResource, vendor=vendor, short_name=name, version=version)
        resource_info = resource.get_processed_info(process_urls=False)
        if resource_info['changelog'] == '':
            raise Http404

        doc_relative_path = url2pathname(resource_info['changelog'])
        doc_base_url = force_trailing_slash(urljoin(resource.get_template_url(request=request, for_base=True), pathname2url(os.path.dirname(doc_relative_path))))
        doc_path = os.path.join(catalogue_utils.wgt_deployer.get_base_dir(vendor, name, version), doc_relative_path)

        (doc_filename_root, doc_filename_ext) = os.path.splitext(doc_path)
        localized_doc_path = doc_filename_root + '.' + get_language() + doc_filename_ext

        try:
            doc_code = download_local_file(localized_doc_path).decode('utf-8')
        except:
            try:
                doc_code = download_local_file(doc_path).decode('utf-8')
            except:
                msg = _('Error opening the changelog file')
                doc_code = '<div class="margin-top: 10px"><p>%s</p></div>' % msg

        doc_pre_html = markdown.markdown(doc_code, output_format='xhtml5', extensions=['codehilite', 'fenced_code'])

        if from_version:
            doc_pre_html = filter_changelog(doc_pre_html, from_version)
            if doc_pre_html.strip() == '':
                raise Http404

        doc = clean_html(doc_pre_html, base_url=doc_base_url)
        return HttpResponse(doc, content_type='application/xhtml+xml; charset=UTF-8')
Example #6
0
    def search_resource(self, vendor, name, version, user):

        if self._name == 'local':
            resources = CatalogueResource.objects.filter(vendor=vendor,
                                                         short_name=name,
                                                         version=version)[:1]

            if len(resources) == 1:
                resource = resources[0]
                base_dir = catalogue_utils.wgt_deployer.get_base_dir(
                    vendor, name, version)
                downloaded_file = download_local_file(
                    os.path.join(base_dir, resource.template_uri))

                return {
                    'downloaded_file': downloaded_file,
                }
            else:
                return None
        else:

            path = '/'.join(('catalogue', 'resource', vendor, name, version))
            url = iri_to_uri(urljoin(self._options['url'], path))
            response = requests.get(url)

            if response.status_code == 200:
                data = json.loads(response.content)
                downloaded_file = download_http_content(data['uriTemplate'],
                                                        user=user)
                return {
                    'downloaded_file': downloaded_file,
                    'template_url': data['uriTemplate'],
                    'packaged': data['packaged']
                }
            else:
                return None
Example #7
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 #8
0
def get_resource_data(resource, user, request=None):
    """Gets all the information related to the given resource."""
    resource_info = resource.get_processed_info(request)

    template_uri = get_absolute_reverse_url('wirecloud_catalogue.media',
                                            kwargs={
                                                'vendor': resource.vendor,
                                                'name': resource.short_name,
                                                'version': resource.version,
                                                'file_path':
                                                resource.template_uri
                                            },
                                            request=request)

    wgt_path = os.path.join(
        wgt_deployer.get_base_dir(resource.vendor, resource.short_name,
                                  resource.version), resource.template_uri)
    size = os.path.getsize(wgt_path)

    cdate = resource.creation_date
    creation_timestamp = time.mktime(
        cdate.timetuple()) * 1e3 + cdate.microsecond / 1e3

    longdescription = resource_info['longdescription']
    if longdescription != '':
        longdescription_relative_path = url2pathname(longdescription)
        longdescription_base_url = force_trailing_slash(
            urljoin(
                resource.get_template_url(request=request, for_base=True),
                pathname2url(os.path.dirname(longdescription_relative_path))))
        longdescription_path = os.path.join(
            wgt_deployer.get_base_dir(resource.vendor, resource.short_name,
                                      resource.version),
            longdescription_relative_path)

        (filename_root, filename_ext) = os.path.splitext(longdescription_path)
        localized_longdescription_path = filename_root + '.' + get_language(
        ) + filename_ext

        try:
            description_code = download_local_file(
                localized_longdescription_path).decode('utf-8')
            longdescription = clean_html(markdown.markdown(
                description_code, output_format='xhtml5'),
                                         base_url=longdescription_base_url)
        except Exception:
            try:
                description_code = download_local_file(
                    longdescription_path).decode('utf-8')
                longdescription = clean_html(markdown.markdown(
                    description_code, output_format='xhtml5'),
                                             base_url=longdescription_base_url)
            except Exception:
                longdescription = resource_info['description']

    else:
        longdescription = resource_info['description']

    return {
        'vendor': resource.vendor,
        'name': resource.short_name,
        'version': resource.version,
        'type': resource_info['type'],
        'date': creation_timestamp,
        'permissions': {
            'delete':
            user.is_superuser,
            'uninstall':
            resource.public is False
            and resource.users.filter(pk=user.pk).exists(),
        },
        'authors': resource_info['authors'],
        'contributors': resource_info['contributors'],
        'title': resource_info['title'],
        'description': resource_info['description'],
        'longdescription': longdescription,
        'email': resource_info['email'],
        'image': resource_info['image'],
        'homepage': resource_info['homepage'],
        'doc': resource_info['doc'],
        'changelog': resource_info['changelog'],
        'size': size,
        'uriTemplate': template_uri,
        'license': resource_info['license'],
        'licenseurl': resource_info['licenseurl'],
        'issuetracker': resource_info['issuetracker'],
    }
Example #9
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 #10
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 #11
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 #12
0
def get_resource_data(resource, user, request=None):
    """Gets all the information related to the given resource."""
    resource_info = resource.get_processed_info(request)

    template_uri = get_absolute_reverse_url('wirecloud_catalogue.media', kwargs={
        'vendor': resource.vendor,
        'name': resource.short_name,
        'version': resource.version,
        'file_path': resource.template_uri
    }, request=request)

    wgt_path = os.path.join(wgt_deployer.get_base_dir(resource.vendor, resource.short_name, resource.version), resource.template_uri)
    size = os.path.getsize(wgt_path)

    cdate = resource.creation_date
    creation_timestamp = time.mktime(cdate.timetuple()) * 1e3 + cdate.microsecond / 1e3

    longdescription = resource_info['longdescription']
    if longdescription != '':
        longdescription_relative_path = url2pathname(longdescription)
        longdescription_base_url = force_trailing_slash(urljoin(resource.get_template_url(request=request, for_base=True), pathname2url(os.path.dirname(longdescription_relative_path))))
        longdescription_path = os.path.join(wgt_deployer.get_base_dir(resource.vendor, resource.short_name, resource.version), longdescription_relative_path)

        (filename_root, filename_ext) = os.path.splitext(longdescription_path)
        localized_longdescription_path = filename_root + '.' + get_language() + filename_ext

        try:
            description_code = download_local_file(localized_longdescription_path).decode('utf-8')
            longdescription = clean_html(markdown.markdown(description_code, output_format='xhtml5'), base_url=longdescription_base_url)
        except:
            try:
                description_code = download_local_file(longdescription_path).decode('utf-8')
                longdescription = clean_html(markdown.markdown(description_code, output_format='xhtml5'), base_url=longdescription_base_url)
            except:
                longdescription = resource_info['description']

    else:
        longdescription = resource_info['description']

    return {
        'id': resource.pk,
        'vendor': resource.vendor,
        'name': resource.short_name,
        'version': resource.version,
        'type': resource_info['type'],
        'date': creation_timestamp,
        'permissions': {
            'delete': user.is_superuser,
            'uninstall': resource.public is False and resource.users.filter(pk=user.pk).exists(),
        },
        'authors': resource_info['authors'],
        'contributors': resource_info['contributors'],
        'title': resource_info['title'],
        'description': resource_info['description'],
        'longdescription': longdescription,
        'email': resource_info['email'],
        'image': resource_info['image'],
        'homepage': resource_info['homepage'],
        'doc': resource_info['doc'],
        'changelog': resource_info['changelog'],
        'size': size,
        'uriTemplate': template_uri,
        'license': resource_info['license'],
        'licenseurl': resource_info['licenseurl'],
        'issuetracker': resource_info['issuetracker'],
    }
Example #13
0
def get_resource_data(resource, user, request=None):
    """Gets all the information related to the given resource."""
    resource_info = resource.get_processed_info(request)

    template_uri = get_absolute_reverse_url(
        "wirecloud_catalogue.media",
        kwargs={
            "vendor": resource.vendor,
            "name": resource.short_name,
            "version": resource.version,
            "file_path": resource.template_uri,
        },
        request=request,
    )

    wgt_path = os.path.join(
        wgt_deployer.get_base_dir(resource.vendor, resource.short_name, resource.version), resource.template_uri
    )
    size = os.path.getsize(wgt_path)

    cdate = resource.creation_date
    creation_timestamp = time.mktime(cdate.timetuple()) * 1e3 + cdate.microsecond / 1e3

    longdescription = resource_info["longdescription"]
    if longdescription != "":
        longdescription_relative_path = url2pathname(longdescription)
        longdescription_base_url = force_trailing_slash(
            urljoin(
                resource.get_template_url(request=request, for_base=True),
                pathname2url(os.path.dirname(longdescription_relative_path)),
            )
        )
        longdescription_path = os.path.join(
            wgt_deployer.get_base_dir(resource.vendor, resource.short_name, resource.version),
            longdescription_relative_path,
        )

        (filename_root, filename_ext) = os.path.splitext(longdescription_path)
        localized_longdescription_path = filename_root + "." + get_language() + filename_ext

        try:
            description_code = download_local_file(localized_longdescription_path)
            longdescription = clean_html(
                markdown.markdown(description_code, output_format="xhtml5"), base_url=longdescription_base_url
            )
        except:
            try:
                description_code = download_local_file(longdescription_path)
                longdescription = clean_html(
                    markdown.markdown(description_code, output_format="xhtml5"), base_url=longdescription_base_url
                )
            except:
                longdescription = resource_info["description"]

    else:
        longdescription = resource_info["description"]

    return {
        "id": resource.pk,
        "vendor": resource.vendor,
        "name": resource.short_name,
        "version": resource.version,
        "type": resource_info["type"],
        "date": creation_timestamp,
        "permissions": {
            "delete": user.is_superuser,
            "uninstall": resource.public is False and resource.users.filter(pk=user.pk).exists(),
        },
        "authors": resource_info["authors"],
        "contributors": resource_info["contributors"],
        "title": resource_info["title"],
        "description": resource_info["description"],
        "longdescription": longdescription,
        "email": resource_info["email"],
        "image": resource_info["image"],
        "homepage": resource_info["homepage"],
        "doc": resource_info["doc"],
        "changelog": resource_info["changelog"],
        "size": size,
        "uriTemplate": template_uri,
        "license": resource_info["license"],
        "licenseurl": resource_info["licenseurl"],
        "issuetracker": resource_info["issuetracker"],
    }