Exemplo n.º 1
0
    def read(self, request, org, name, version):
        # Get resource model
        try:
            organization = Organization.objects.get(name=org)
            resource = WStore_resource.objects.get(provider=organization, name=name, version=version)
        except:
            return build_response(request, 404, 'Resource not found')

        # Check resource state
        if resource.state == 'deleted':
            return build_response(request, 404, 'Resource not found')

        # Get offering where the resource is included
        response = []

        try:
            for off in resource.offerings:
                offering = Offering.objects.get(pk=off)

                if offering.state == 'published':
                    response.append(get_offering_info(offering, request.user))
        except Exception as e:
            return build_response(request, 400, unicode(e))

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
Exemplo n.º 2
0
    def read(self, request):

        site = get_current_site(request)
        context = Context.objects.get(site=site)

        response = []
        for off in context.top_rated:
            offering = Offering.objects.get(pk=off)
            response.append(get_offering_info(offering, request.user))

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json;charset=UTF-8')
Exemplo n.º 3
0
    def read(self, request):
        logger.debug("NewestCollection.read()")
        site = get_current_site(request)
        context = Context.objects.get(site=site)

        response = []
        for off in context.newest:
            offering = Offering.objects.get(pk=off)
            response.append(get_offering_info(offering, request.user))

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json')
Exemplo n.º 4
0
    def read(self, request):

        site = get_current_site(request)
        context = Context.objects.get(site=site)

        response = []
        for off in context.top_rated:
            offering = Offering.objects.get(pk=off)
            response.append(get_offering_info(offering, request.user))

        return HttpResponse(json.dumps(response), status=200, mimetype='application/json;charset=UTF-8')
Exemplo n.º 5
0
    def read(self, request):

        # Get the token
        token = request.GET.get('ID', '')

        site = get_current_site(request)
        context = Context.objects.get(site=site)

        if token not in context.user_refs:
            return render(request, 'err_msg.html', {
                'title': 'Token not found',
                'message': 'The token provided for identifying the purchase is not valid or has expired.'
            })

        info = context.user_refs[token]

        # Get the user and the offering
        user = User.objects.get(pk=info['user'])
        request.user = user

        id_ = info['offering']

        context.save()

        # Load the offering info
        try:
            offering = Offering.objects.get(pk=id_)
        except:
            return render(request, 'err_msg.html', {
                'title': 'Offering not found',
                'message': 'The requested offering does not exists.'
            })

        offering_info = get_offering_info(offering, user)

        # Check that the offering can be purchased
        if offering.state != 'published':
            return render(request, 'err_msg.html', {
                'title': 'Error',
                'message': 'The offering cannot be acquired'
            })

        from django.conf import settings

        # Create the context
        context = {
            'offering_info': mark_safe(json.dumps(offering_info)),
            'oil': settings.OILAUTH,
            'portal': settings.PORTALINSTANCE
        }

        # Return the form to purchase the offering
        return render(request, 'store/purchase_form.html', context)
Exemplo n.º 6
0
    def read(self, request, organization, name, version):
        user = request.user
        try:
            org = Organization.objects.get(name=organization)
            offering = Offering.objects.get(name=name, owner_organization=org, version=version)
        except:
            return build_response(request, 404, 'Not found')

        try:
            result = get_offering_info(offering, user)
        except Exception, e:
            return build_response(request, 400, e.message)
Exemplo n.º 7
0
    def read(self, request):

        # Get the token
        token = request.GET.get('ID', '')

        site = get_current_site(request)
        context = Context.objects.get(site=site)

        if not token in context.user_refs:
            return render(request, 'err_msg.html', {
                'title': 'Token not found',
                'message': 'The used token for identifying the purchase is not valid or has expired.'
            })

        info = context.user_refs[token]

        # Get the user and the offering
        user = User.objects.get(pk=info['user'])
        request.user = user

        id_ = info['offering']

        context.save()

        # Load the offering info
        try:
            offering = Offering.objects.get(pk=id_)
        except:
            return render(request, 'err_msg.html', {
                'title': 'Offering not found',
                'message': 'The requested offering does not exists.'
            })

        offering_info = get_offering_info(offering, user)

        # Check that the offering can be purchased
        if offering.state != 'published':
            return render(request, 'err_msg.html', {
                'title': 'Error',
                'message': 'The offering cannot be acquired'
            })

        from django.conf import settings

        # Create the context
        context = {
            'offering_info': mark_safe(json.dumps(offering_info)),
            'oil': settings.OILAUTH,
            'portal': settings.PORTALINSTANCE
        }

        # Return the form to purchase the offering
        return render(request, 'store/purchase_form.html', context)
Exemplo n.º 8
0
    def read(self, request, organization, name, version):
        user = request.user
        try:
            offering, org = _get_offering(organization, name, version)
        except ObjectDoesNotExist as e:
            return build_response(request, 404, unicode(e))
        except Exception as e:
            return build_response(request, 400, unicode(e))

        try:
            result = get_offering_info(offering, user)
        except Exception, e:
            return build_response(request, 400, unicode(e))
Exemplo n.º 9
0
def home_details(request, org, name, version):
    context = _load_home_context(request)

    context['loader'] = 'details'
    try:
        owner_org = Organization.objects.get(name=org)
        offering = Offering.objects.get(owner_organization=owner_org, name=name, version=version)
        offering_info = get_offering_info(offering, request.user)
    except:
        return build_response(request, 404, 'Not found')

    context['info'] = mark_safe(json.dumps(offering_info))
    return render(request, 'index.html', context)
Exemplo n.º 10
0
    def read(self, request, organization, name, version):
        user = request.user
        try:
            offering, org = _get_offering(organization, name, version)
        except ObjectDoesNotExist as e:
            return build_response(request, 404, unicode(e))
        except Exception as e:
            return build_response(request, 400, unicode(e))

        try:
            result = get_offering_info(offering, user)
        except Exception, e:
            return build_response(request, 400, unicode(e))
Exemplo n.º 11
0
def home_details(request, org, name, version):
    context = _load_home_context(request)

    context['loader'] = 'details'
    try:
        owner_org = Organization.objects.get(name=org)
        offering = Offering.objects.get(owner_organization=owner_org,
                                        name=name,
                                        version=version)
        offering_info = get_offering_info(offering, request.user)
    except:
        return build_response(request, 404, 'Not found')

    context['info'] = mark_safe(json.dumps(offering_info))
    return render(request, 'index.html', context)
Exemplo n.º 12
0
    def read(self, request):

        # Get the token
        token = request.GET.get('ID')

        site = get_current_site(request)
        context = Context.objects.get(site=site)

        info = context.user_refs[token]

        # Get the user and the offering
        user = User.objects.get(pk=info['user'])
        request.user = user

        id_ = info['offering']

        context.save()

        # Load the offering info
        try:
            offering = Offering.objects.get(pk=id_)
        except:
            return build_response(request, 404, 'Not found')
        offering_info = get_offering_info(offering, user)

        # Check that the offering can be purchased
        if offering.state != 'published':
            return build_response(request, 400, 'The offering cannot be purchased')

        from django.conf import settings

        # Create the context
        context = {
            'offering_info': mark_safe(json.dumps(offering_info)),
            'oil': settings.OILAUTH
        }

        # Return the form to purchase the offering
        return render(request, 'store/purchase_form.html', context)
Exemplo n.º 13
0
    def full_text_search(self, user, text, state=None, count=False, pagination=None, sort=None):
        """
        Performs a full text search over the search index allowing for counting, filtering
        by state, paginating and sorting.
        """

        if not os.path.exists(self._index_path) or os.listdir(self._index_path) == []:
            raise Exception('The index does not exist')

        # Get the index reader
        index = open_dir(self._index_path)

        with index.searcher() as searcher:

            # Create the query
            query_ = QueryParser('content', index.schema).parse(unicode(text))

            # If an state has been defined filter the result
            if state:
                if state == 'all':  # All user owned offerings
                    filter_ = query.Term('owner', unicode(user.userprofile.current_organization.pk))
                elif state == 'purchased':  # Purchased offerings
                    filter_ = query.Term('purchaser', user.userprofile.current_organization.pk)
                elif state == 'uploaded' or state == 'deleted':  # Uploaded or deleted offerings owned by the user
                    filter_ = query.Term('state', state) & query.Term('owner', unicode(user.userprofile.current_organization.pk))
                else:
                    raise ValueError('Invalid state')
            else:
                # If state is not included the default behaviour is returning
                # published offerings
                filter_ = query.Term('state', 'published')

            # Create sorting params if needed
            if sort:
                if sort == 'popularity' or sort == 'date':
                    reverse = True
                elif sort == 'name':
                    reverse = False
                else:
                    raise ValueError('Undefined sorting')

            # If pagination has been defined, limit the results
            if pagination:
                # Validate pagination fields
                if not isinstance(pagination, dict):
                    raise TypeError('Invalid pagination type')

                if not 'start' in pagination or not 'limit' in pagination:
                    raise ValueError('Missing required field in pagination')

                if not isinstance(pagination['start'], int) or not isinstance(pagination['limit'], int):
                    raise TypeError('Invalid pagination params type')

                if pagination['start'] < 1:
                    raise ValueError('Start param must be higher than 0')

                if pagination['limit'] < 0:
                    raise ValueError('Limit param must be positive')

                search_params = (query_, )
                search_kwparams = {
                    'filter': filter_,
                }

                if sort:
                    search_kwparams['sortedby'] = sort
                    search_kwparams['reverse'] = reverse

                # Check limits
                search_len = len(searcher.search(*search_params, **search_kwparams))

                if pagination['start'] > search_len:
                    search_result = []
                else:
                    search_params = (query_, pagination['start'])
                    search_kwparams['pagelen'] = pagination['limit']
                    search_result = searcher.search_page(*search_params, **search_kwparams)
            else:
                if sort:
                    search_result = searcher.search(query_, filter=filter_, limit=None, sortedby=sort, reverse=reverse)
                else:
                    search_result = searcher.search(query_, filter=filter_, limit=None)
                

            result = []
            # The get_offering_info method is imported inside this method in order to avoid a cross-reference import error
            from wstore.offerings.offerings_management import get_offering_info


            if not count:
                for hit in search_result:

                    # Get the offerings
                    offering = Offering.objects.get(pk=hit['id'])
                    result.append(get_offering_info(offering, user))
            else:
                result = {'number': len(search_result)}

        return result
Exemplo n.º 14
0
    def full_text_search(self,
                         user,
                         text,
                         state=None,
                         count=False,
                         pagination=None,
                         sort=None):
        """
        Performs a full text search over the search index allowing for counting, filtering
        by state, paginating and sorting.
        """

        if not os.path.exists(self._index_path) or os.listdir(
                self._index_path) == []:
            raise Exception('The index does not exist')

        # Get the index reader
        index = open_dir(self._index_path)

        with index.searcher() as searcher:

            # Create the query
            query_ = QueryParser('content', index.schema).parse(unicode(text))

            # If an state has been defined filter the result
            if state:
                # Validate state
                for st in state:
                    if not st in [
                            'purchased', 'uploaded', 'deleted', 'published'
                    ]:
                        raise ValueError('Invalid state')

                if 'purchased' in state:
                    filter_ = query.Term(
                        'purchaser', user.userprofile.current_organization.pk)
                else:
                    filter_ = query.Term(
                        'owner',
                        unicode(user.userprofile.current_organization.pk))

                    state_filter = None
                    for st in state:
                        if not state_filter:
                            state_filter = query.Term('state', st)
                        else:
                            state_filter = state_filter | query.Term(
                                'state', st)

                    filter_ = filter_ & state_filter
            else:
                # If state is not included the default behaviour is returning
                # published offerings
                filter_ = query.Term('state', 'published')

            # Create sorting params if needed
            if sort:
                if sort == 'popularity' or sort == 'date':
                    reverse = True
                elif sort == 'name':
                    reverse = False
                else:
                    raise ValueError('Undefined sorting')

            # If pagination has been defined, limit the results
            if pagination:
                # Validate pagination fields
                if not isinstance(pagination, dict):
                    raise TypeError('Invalid pagination type')

                if not 'start' in pagination or not 'limit' in pagination:
                    raise ValueError('Missing required field in pagination')

                if not isinstance(pagination['start'], int) or not isinstance(
                        pagination['limit'], int):
                    raise TypeError('Invalid pagination params type')

                if pagination['start'] < 1:
                    raise ValueError('Start param must be higher than 0')

                if pagination['limit'] < 0:
                    raise ValueError('Limit param must be positive')

                search_params = (query_, )
                search_kwparams = {
                    'filter': filter_,
                }

                if sort:
                    search_kwparams['sortedby'] = sort
                    search_kwparams['reverse'] = reverse

                # Check limits
                search_len = len(
                    searcher.search(*search_params, **search_kwparams))

                if pagination['start'] > search_len:
                    search_result = []
                else:
                    search_params = (query_, pagination['start'])
                    search_kwparams['pagelen'] = pagination['limit']
                    search_result = searcher.search_page(
                        *search_params, **search_kwparams)
            else:
                if sort:
                    search_result = searcher.search(query_,
                                                    filter=filter_,
                                                    limit=None,
                                                    sortedby=sort,
                                                    reverse=reverse)
                else:
                    search_result = searcher.search(query_,
                                                    filter=filter_,
                                                    limit=None)

            result = []
            # The get_offering_info method is imported inside this method in order to avoid a cross-reference import error
            from wstore.offerings.offerings_management import get_offering_info

            if not count:
                for hit in search_result:

                    # Get the offerings
                    offering = Offering.objects.get(pk=hit['id'])
                    result.append(get_offering_info(offering, user))
            else:
                result = {'number': len(search_result)}

        return result
Exemplo n.º 15
0
    def read(self, request, tag):
        # Get query params
        action = request.GET.get('action', None)
        start = request.GET.get('start', None)
        limit = request.GET.get('limit', None)
        sort = request.GET.get('sort', None)
        state = request.GET.get('filter', None)

        # Check action format
        if action and not (isinstance(action, str)
                           or isinstance(action, unicode)):
            return build_response(request, 400, 'Invalid action format')

        # Validate action
        if action and action != 'count':
            return build_response(request, 400, 'Invalid action')

        if action and (start or limit or sort):
            return build_response(
                request, 400, 'Actions cannot be combined with pagination')

        # Validate pagination
        if (start and not limit) or (not start and limit):
            return build_response(request, 400,
                                  'Both pagination params are required')

        if start and limit and (not start.isnumeric()
                                or not limit.isnumeric()):
            return build_response(request, 400,
                                  'Invalid format in pagination parameters')
        elif start and limit:
            start = int(start)
            limit = int(limit)

        if start and limit and (start < 1 or limit < 1):
            return build_response(
                request, 400,
                'Pagination params must be equal or greater that 1')

        # Validate sorting
        allowed_sorting = ['name', 'date', 'popularity']
        if sort and (not isinstance(sort, str)
                     and not isinstance(sort, unicode)):
            return build_response(request, 400, 'Invalid sorting format')

        if sort and not sort in allowed_sorting:
            return build_response(request, 400, 'Invalid sorting value')

        # Validate state
        if state and state != 'published' and state != 'purchased':
            return build_response(request, 400, 'Invalid filter')

        try:
            # Build tag manager
            tm = TagManager()

            # Select action
            if action == 'count':
                response = {'number': tm.count_offerings(tag)}
            else:
                offerings = tm.search_by_tag(tag)

                response = []
                # Get offering info
                for off in offerings:
                    offering_info = get_offering_info(off, request.user)

                    if not state and offering_info['state'] != 'published'\
                    and offering_info['state'] != 'purchased' and offering_info['state'] != 'rated':
                        continue

                    response.append(offering_info)

                # Sort offerings if needed
                if sort:
                    rev = True
                    if sort == 'name':
                        rev = False
                    elif sort == 'date':
                        sort = 'publication_date'
                    elif sort == 'popularity':
                        sort = 'rating'

                    response = sorted(response,
                                      key=lambda off: off[sort],
                                      reverse=rev)

                # If sort was needed pagination must be done after sorting
                if start and limit:
                    response = response[start - 1:(limit + (start - 1))]

        except Exception as e:
            return build_response(request, 400, unicode(e))

        # Create response
        return HttpResponse(json.dumps(response),
                            status=200,
                            mimetype='application/json; charset=utf-8')
Exemplo n.º 16
0
    def read(self, request, tag):
        # Get query params
        action = request.GET.get('action', None)
        start = request.GET.get('start', None)
        limit = request.GET.get('limit', None)
        sort = request.GET.get('sort', None)
        state = request.GET.get('filter', None)

        # Check action format
        if action and not (isinstance(action,str) or isinstance(action,unicode)):
            return build_response(request, 400, 'Invalid action format')

        # Validate action
        if action and action != 'count':
            return build_response(request, 400, 'Invalid action')

        if action and (start or limit or sort):
            return build_response(request, 400, 'Actions cannot be combined with pagination')

        # Validate pagination
        if (start and not limit) or (not start and limit):
            return build_response(request, 400, 'Both pagination params are required')

        if start and limit and (not start.isnumeric() or not limit.isnumeric()):
            return build_response(request, 400, 'Invalid format in pagination parameters')
        elif start and limit:
            start = int(start)
            limit = int(limit)

        if start and limit and (start < 1 or limit < 1):
            return build_response(request, 400, 'Pagination params must be equal or greater that 1')

        # Validate sorting
        allowed_sorting = ['name', 'date', 'popularity']
        if sort and (not isinstance(sort, str) and not isinstance(sort, unicode)):
            return build_response(request, 400, 'Invalid sorting format')

        if sort and not sort in allowed_sorting:
            return build_response(request, 400, 'Invalid sorting value')

        # Validate state
        if state and state != 'published' and state != 'purchased':
            return build_response(request, 400, 'Invalid filter')

        try:
            # Build tag manager
            tm = TagManager()

            # Select action
            if action == 'count':
                response = {
                    'number': tm.count_offerings(tag)
                }
            else:
                offerings = tm.search_by_tag(tag)

                response = []
                # Get offering info
                for off in offerings:
                    offering_info = get_offering_info(off, request.user)

                    if not state and offering_info['state'] != 'published'\
                    and offering_info['state'] != 'purchased' and offering_info['state'] != 'rated':
                        continue

                    response.append(offering_info)

                # Sort offerings if needed
                if sort:
                    rev = True
                    if sort == 'name':
                        rev = False
                    elif sort == 'date':
                        sort = 'publication_date'
                    elif sort == 'popularity':
                        sort = 'rating'

                    response = sorted(response, key=lambda off: off[sort], reverse=rev)

                # If sort was needed pagination must be done after sorting
                if start and limit:
                    response = response[start - 1: (limit + (start - 1))]

        except Exception as e:
            return build_response(request, 400, unicode(e))

        # Create response
        return HttpResponse(json.dumps(response), status=200, mimetype='application/json; charset=utf-8')