Beispiel #1
0
    def test_returns_parse_results(self, parse, pyramid_request):
        parse.return_value = {"foo": "bar"}
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result == {"foo": "bar"}
Beispiel #2
0
    def test_returns_parse_results(self, parse, pyramid_request):
        parse.return_value = {"foo": "bar"}
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result == {"foo": "bar"}
Beispiel #3
0
    def test_returns_parse_results(self, parse, pyramid_request):
        parse.return_value = {'foo': 'bar'}
        pyramid_request.GET['q'] = 'giraffe'

        result = extract(pyramid_request, parse=parse)

        assert result == {'foo': 'bar'}
Beispiel #4
0
    def test_returns_parse_results(self, parse, pyramid_request):
        parse.return_value = {'foo': 'bar'}
        pyramid_request.GET['q'] = 'giraffe'

        result = extract(pyramid_request, parse=parse)

        assert result == {'foo': 'bar'}
Beispiel #5
0
    def search(self):
        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result["opts"] = {"search_groupname": self.group.name}

        if self.request.authenticated_user not in self.group.members:
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user["user"] == userid:
                    return user["count"]
            return 0

        q = query.extract(self.request)
        users_aggregation = result["search_results"].aggregations.get("users", [])
        members = [
            {
                "username": u.username,
                "userid": u.userid,
                "count": user_annotation_count(users_aggregation, u.userid),
                "faceted_by": _faceted_by_user(self.request, u.username, q),
            }
            for u in self.group.members
        ]
        members = sorted(members, key=lambda k: k["username"].lower())

        group_annotation_count = None
        if self.request.feature("total_shared_annotations"):
            group_annotation_count = self.request.find_service(name="annotation_stats").group_annotation_count(
                self.group.pubid
            )

        result["stats"] = {"annotation_count": group_annotation_count}

        result["group"] = {
            "created": self.group.created.strftime("%B, %Y"),
            "description": self.group.description,
            "name": self.group.name,
            "pubid": self.group.pubid,
            "url": self.request.route_url("group_read", pubid=self.group.pubid, slug=self.group.slug),
            "members": members,
        }

        if self.request.has_permission("admin", self.group):
            result["group_edit_url"] = self.request.route_url("group_edit", pubid=self.group.pubid)

        result["more_info"] = "more_info" in self.request.params

        if not result.get("q"):
            result["zero_message"] = Markup(
                _("The group “{name}” has not made any annotations yet.").format(name=Markup.escape(self.group.name))
            )

        return result
Beispiel #6
0
def search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    q = query.extract(request)

    # Check whether a redirect is required
    query.check_url(request, q)

    page_size = request.params.get('page_size', PAGE_SIZE)
    try:
        page_size = int(page_size)
    except ValueError:
        page_size = PAGE_SIZE

    # Fetch results
    result = query.execute(request, q, page_size=page_size)

    groups_suggestions = []

    if request.authenticated_user:
        for group in request.authenticated_user.groups:
            groups_suggestions.append({
                'name': group.name,
                'pubid': group.pubid
                })

    def tag_link(tag):
        q = parser.unparse({'tag': tag})
        return request.route_url('activity.search', _query=[('q', q)])

    def username_from_id(userid):
        parts = split_user(userid)
        return parts['username']

    def user_link(userid):
        username=username_from_id(userid)
        return request.route_url('activity.user_search', username=username)

    return {
        'aggregations': result.aggregations,
        'groups_suggestions': groups_suggestions,
        'page': paginate(request, result.total, page_size=page_size),
        'pretty_link': pretty_link,
        'q': request.params.get('q', ''),
        'tag_link': tag_link,
        'timeframes': result.timeframes,
        'total': result.total,
        'user_link': user_link,
        'username_from_id': username_from_id,
    }
Beispiel #7
0
def group_search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    result = search(request)

    pubid = request.matchdict['pubid']
    result['opts'] = {'search_groupname': pubid}

    try:
        group = request.db.query(models.Group).filter_by(pubid=pubid).one()
    except exc.NoResultFound:
        return result

    result['opts']['search_groupname'] = group.name

    if request.authenticated_user not in group.members:
        return result

    def user_annotation_count(aggregation, userid):
        for user in aggregation:
            if user['user'] == userid:
                return user['count']
        return 0

    q = query.extract(request)
    users_aggregation = result.get('aggregations', {}).get('users', [])
    members = [{'username': u.username,
                'userid': u.userid,
                'count': user_annotation_count(users_aggregation, u.userid),
                'faceted_by': _faceted_by_user(request, u.username, q)}
               for u in group.members]
    members = sorted(members, key=lambda k: k['username'].lower())

    result['group'] = {
        'created': group.created.strftime('%B, %Y'),
        'description': group.description,
        'name': group.name,
        'pubid': group.pubid,
        'url': request.route_url('group_read',
                                 pubid=group.pubid,
                                 slug=group.slug),
        'members': members,
    }

    if request.has_permission('admin', group):
        result['group_edit_url'] = request.route_url('group_edit', pubid=pubid)

    result['more_info'] = 'more_info' in request.params

    return result
Beispiel #8
0
    def test_overrides_user_term_for_user_search_requests(self, parse, pyramid_request):
        """
        If the query sent to a user search page includes a user, we override
        it, because otherwise we'll display the union of the results for those
        two users, which makes no sense.
        """
        parse.return_value = MultiDict({"foo": "bar", "user": "******"})
        pyramid_request.matched_route.name = "activity.user_search"
        pyramid_request.matchdict["username"] = "******"
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {"foo": ["bar"], "user": ["josiah"]}
Beispiel #9
0
    def test_overrides_user_term_for_user_search_requests(self, parse, pyramid_request):
        """
        If the query sent to a user search page includes a user, we override
        it, because otherwise we'll display the union of the results for those
        two users, which makes no sense.
        """
        parse.return_value = MultiDict({"foo": "bar", "user": "******"})
        pyramid_request.matched_route.name = "activity.user_search"
        pyramid_request.matchdict["username"] = "******"
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {"foo": ["bar"], "user": ["josiah"]}
Beispiel #10
0
    def search(self):
        q = query.extract(self.request)

        # Check whether a redirect is required.
        query.check_url(self.request, q)

        page_size = self.request.params.get('page_size', PAGE_SIZE)
        try:
            page_size = int(page_size)
        except ValueError:
            page_size = PAGE_SIZE

        # Fetch results.
        results = query.execute(self.request, q, page_size=page_size)

        groups_suggestions = []

        if self.request.user:
            for group in self.request.user.groups:
                groups_suggestions.append({
                    'name': group.name,
                    'pubid': group.pubid
                })

        def tag_link(tag):
            q = parser.unparse({'tag': tag})
            return self.request.route_url('activity.search', _query=[('q', q)])

        def username_from_id(userid):
            parts = split_user(userid)
            return parts['username']

        def user_link(userid):
            username = username_from_id(userid)
            return self.request.route_url('activity.user_search',
                                          username=username)

        return {
            'search_results': results,
            'groups_suggestions': groups_suggestions,
            'page': paginate(self.request, results.total, page_size=page_size),
            'pretty_link': pretty_link,
            'q': self.request.params.get('q', ''),
            'tag_link': tag_link,
            'user_link': user_link,
            'username_from_id': username_from_id,
            # The message that is shown (only) if there's no search results.
            'zero_message': _('No annotations matched your search.'),
        }
Beispiel #11
0
    def search(self):
        q = query.extract(self.request)

        # Check whether a redirect is required.
        query.check_url(self.request, q)

        page_size = self.request.params.get('page_size', PAGE_SIZE)
        try:
            page_size = int(page_size)
        except ValueError:
            page_size = PAGE_SIZE

        # Fetch results.
        results = query.execute(self.request, q, page_size=page_size)

        groups_suggestions = []

        if self.request.user:
            for group in self.request.user.groups:
                groups_suggestions.append({
                    'name': group.name,
                    'pubid': group.pubid
                })

        def tag_link(tag):
            q = parser.unparse({'tag': tag})
            return self.request.route_url('activity.search', _query=[('q', q)])

        def username_from_id(userid):
            parts = split_user(userid)
            return parts['username']

        def user_link(userid):
            username = username_from_id(userid)
            return self.request.route_url('activity.user_search',
                                          username=username)

        return {
            'search_results': results,
            'groups_suggestions': groups_suggestions,
            'page': paginate(self.request, results.total, page_size=page_size),
            'pretty_link': pretty_link,
            'q': self.request.params.get('q', ''),
            'tag_link': tag_link,
            'user_link': user_link,
            'username_from_id': username_from_id,
            # The message that is shown (only) if there's no search results.
            'zero_message': _('No annotations matched your search.'),
        }
Beispiel #12
0
    def test_overrides_user_term_for_user_search_requests(self, parse, pyramid_request):
        """
        If the query sent to a user search page includes a user, we override
        it, because otherwise we'll display the union of the results for those
        two users, which makes no sense.
        """
        parse.return_value = MultiDict({'foo': 'bar',
                                        'user': '******'})
        pyramid_request.matched_route.name = 'activity.user_search'
        pyramid_request.matchdict['username'] = '******'
        pyramid_request.GET['q'] = 'giraffe'

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {'foo': ['bar'],
                                          'user': ['josiah']}
Beispiel #13
0
    def test_overrides_group_term_for_group_search_requests(
        self, parse, pyramid_request
    ):
        """
        If the query sent to a group search page includes a group, we override
        it, because otherwise we'll display the union of the results for those
        two groups, which makes no sense.
        """
        parse.return_value = MultiDict({"foo": "bar", "group": "whattheusersent"})
        pyramid_request.matched_route.name = "group_read"
        pyramid_request.matchdict["pubid"] = "abcd1234"
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {"foo": ["bar"], "group": ["abcd1234"]}
Beispiel #14
0
    def test_overrides_user_term_for_user_search_requests(self, parse, pyramid_request):
        """
        If the query sent to a user search page includes a user, we override
        it, because otherwise we'll display the union of the results for those
        two users, which makes no sense.
        """
        parse.return_value = MultiDict({'foo': 'bar',
                                        'user': '******'})
        pyramid_request.matched_route.name = 'activity.user_search'
        pyramid_request.matchdict['username'] = '******'
        pyramid_request.GET['q'] = 'giraffe'

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {'foo': ['bar'],
                                          'user': ['josiah']}
Beispiel #15
0
    def test_overrides_group_term_for_group_search_requests(self, parse, pyramid_request):
        """
        If the query sent to a group search page includes a group, we override
        it, because otherwise we'll display the union of the results for those
        two groups, which makes no sense.
        """
        parse.return_value = MultiDict({'foo': 'bar',
                                        'group': 'whattheusersent'})
        pyramid_request.matched_route.name = 'group_read'
        pyramid_request.matchdict['pubid'] = 'abcd1234'
        pyramid_request.GET['q'] = 'giraffe'

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {'foo': ['bar'],
                                          'group': ['abcd1234']}
Beispiel #16
0
    def test_overrides_group_term_for_group_search_requests(
        self, parse, pyramid_request
    ):
        """
        If the query sent to a group search page includes a group, we override
        it, because otherwise we'll display the union of the results for those
        two groups, which makes no sense.
        """
        parse.return_value = MultiDict({"foo": "bar", "group": "whattheusersent"})
        pyramid_request.matched_route.name = "group_read"
        pyramid_request.matchdict["pubid"] = "abcd1234"
        pyramid_request.GET["q"] = "giraffe"

        result = extract(pyramid_request, parse=parse)

        assert result.dict_of_lists() == {"foo": ["bar"], "group": ["abcd1234"]}
Beispiel #17
0
    def search(self):
        q = query.extract(self.request)

        # Check whether a redirect is required.
        query.check_url(self.request, q)

        page_size = self.request.params.get("page_size", PAGE_SIZE)
        try:
            page_size = int(page_size)
        except ValueError:
            page_size = PAGE_SIZE

        # Fetch results.
        results = query.execute(self.request, q, page_size=page_size)

        groups_suggestions = []

        if self.request.authenticated_user:
            for group in self.request.authenticated_user.groups:
                groups_suggestions.append({"name": group.name, "pubid": group.pubid})

        def tag_link(tag):
            q = parser.unparse({"tag": tag})
            return self.request.route_url("activity.search", _query=[("q", q)])

        def username_from_id(userid):
            parts = split_user(userid)
            return parts["username"]

        def user_link(userid):
            username = username_from_id(userid)
            return self.request.route_url("activity.user_search", username=username)

        return {
            "search_results": results,
            "groups_suggestions": groups_suggestions,
            "page": paginate(self.request, results.total, page_size=page_size),
            "pretty_link": pretty_link,
            "q": self.request.params.get("q", ""),
            "tag_link": tag_link,
            "user_link": user_link,
            "username_from_id": username_from_id,
            # The message that is shown (only) if there's no search results.
            "zero_message": _("No annotations matched your search."),
        }
Beispiel #18
0
def search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    q = query.extract(request)

    # Check whether a redirect is required
    query.check_url(request, q)

    # Fetch results
    result = query.execute(request, q, page_size=PAGE_SIZE)

    return {
        'total': result.total,
        'aggregations': result.aggregations,
        'timeframes': result.timeframes,
        'page': paginate(request, result.total, page_size=PAGE_SIZE),
    }
Beispiel #19
0
def search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    q = query.extract(request)
    if q is None:
        return {}

    # Check whether a redirect is required
    query.check_url(request, q)

    # Fetch results
    result = query.execute(request, q)

    return {
        'q': request.params['q'],
        'total': result.total,
        'aggregations': result.aggregations,
        'timeframes': result.timeframes,
        'page': paginate(request, result.total),
    }
Beispiel #20
0
def search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    q = query.extract(request)

    # Check whether a redirect is required
    query.check_url(request, q)

    page_size = request.params.get('page_size', PAGE_SIZE)
    try:
        page_size = int(page_size)
    except ValueError:
        page_size = PAGE_SIZE

    # Fetch results
    result = query.execute(request, q, page_size=page_size)

    for user in result.aggregations.get('users', []):
        user['username'] = util.user.split_user(user['user'])['username']
        user['userid'] = user['user']
        user['faceted_by'] = _faceted_by_user(request, user['username'], q)
        del user['user']

    groups_suggestions = []

    if request.authenticated_user:
        for group in request.authenticated_user.groups:
            groups_suggestions.append({
                'name': group.name,
                'pubid': group.pubid
                })
    return {
        'total': result.total,
        'aggregations': result.aggregations,
        'groups_suggestions': groups_suggestions,
        'timeframes': result.timeframes,
        'page': paginate(request, result.total, page_size=page_size),
    }
Beispiel #21
0
def search(request):
    if not request.feature('search_page'):
        raise httpexceptions.HTTPNotFound()

    q = query.extract(request)

    # Check whether a redirect is required
    query.check_url(request, q)

    page_size = request.params.get('page_size', PAGE_SIZE)
    try:
        page_size = int(page_size)
    except ValueError:
        page_size = PAGE_SIZE

    # Fetch results
    result = query.execute(request, q, page_size=page_size)

    return {
        'total': result.total,
        'aggregations': result.aggregations,
        'timeframes': result.timeframes,
        'page': paginate(request, result.total, page_size=page_size),
    }
Beispiel #22
0
    def search(self):
        # If the user is just logged-in in 10 seconds, create JWT grant tokens
        # for each JWT clients.
        user = self.request.user
        grant_tokens = []
        if user is not None and \
           datetime.utcnow() < user.last_login_date + timedelta(seconds=10):
            clients = self.request.db.query(AuthClient) \
                                     .order_by(AuthClient.name.asc()) \
                                     .all()
            for client in clients:
                if client.secret is not None:
                    grant_tokens.append(
                        self._create_grant_token(user.username, client))

        q = query.extract(self.request)

        # Check whether a redirect is required.
        query.check_url(self.request, q)

        page_size = self.request.params.get('page_size', PAGE_SIZE)
        try:
            page_size = int(page_size)
        except ValueError:
            page_size = PAGE_SIZE

        # Fetch results.
        results = query.execute(self.request, q, page_size=page_size)

        groups_suggestions = []

        if self.request.user:
            for group in self.request.user.groups:
                groups_suggestions.append({
                    'name': group.name,
                    'pubid': group.pubid
                })

        def tag_link(tag):
            q = parser.unparse({'tag': tag})
            return self.request.route_url('activity.search', _query=[('q', q)])

        def username_from_id(userid):
            parts = split_user(userid)
            return parts['username']

        def user_link(userid):
            username = username_from_id(userid)
            return self.request.route_url('activity.user_search',
                                          username=username)

        return {
            'search_results': results,
            'groups_suggestions': groups_suggestions,
            'page': paginate(self.request, results.total, page_size=page_size),
            'pretty_link': pretty_link,
            'q': self.request.params.get('q', ''),
            'tag_link': tag_link,
            'user_link': user_link,
            'username_from_id': username_from_id,
            # The message that is shown (only) if there's no search results.
            'zero_message': _('No annotations matched your search.'),
            'grant_tokens': enumerate(grant_tokens),
        }
Beispiel #23
0
 def __init__(self, request):
     self.request = request
     # Cache a copy of the extracted query params for the child controllers to use if needed.
     self.parsed_query_params = query.extract(self.request)
Beispiel #24
0
    def test_returns_none_if_q_not_in_params(self, parse, pyramid_request):
        result = extract(pyramid_request, parse=parse)

        assert result is None
Beispiel #25
0
    def search(self):
        result = self._check_access_permissions()
        if result is not None:
            return result

        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result['opts'] = {'search_groupname': self.group.name}

        # If the group has read access only for members  and the user is not in that list
        # return without extra info.
        if self.group.readable_by == ReadableBy.members and (
                self.request.user not in self.group.members):
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user['user'] == userid:
                    return user['count']
            return 0

        q = query.extract(self.request)
        members = []
        moderators = []
        users_aggregation = result['search_results'].aggregations.get(
            'users', [])
        # If the group has members provide a list of member info,
        # otherwise provide a list of moderator info instead.
        if self.group.members:
            members = [{
                'username':
                u.username,
                'userid':
                u.userid,
                'count':
                user_annotation_count(users_aggregation, u.userid),
                'faceted_by':
                _faceted_by_user(self.request, u.username, q)
            } for u in self.group.members]
            members = sorted(members, key=lambda k: k['username'].lower())
        else:
            moderators = []
            if self.group.creator:
                # Pass a list of moderators, anticipating that [self.group.creator]
                # will change to an actual list of moderators at some point.
                moderators = [{
                    'username':
                    u.username,
                    'userid':
                    u.userid,
                    'count':
                    user_annotation_count(users_aggregation, u.userid),
                    'faceted_by':
                    _faceted_by_user(self.request, u.username, q)
                } for u in [self.group.creator]]
                moderators = sorted(moderators,
                                    key=lambda k: k['username'].lower())

        group_annotation_count = self.request.find_service(
            name='annotation_stats').group_annotation_count(self.group.pubid)

        result['stats'] = {
            'annotation_count': group_annotation_count,
        }

        result['group'] = {
            'created':
            utc_us_style_date(self.group.created),
            'description':
            self.group.description,
            'name':
            self.group.name,
            'pubid':
            self.group.pubid,
            'url':
            self.request.route_url('group_read',
                                   pubid=self.group.pubid,
                                   slug=self.group.slug),
            'members':
            members,
            'creator':
            self.group.creator.userid if self.group.creator else None,
            'share_subtitle':
            _('Share group'),
            'share_msg':
            _('Sharing the link lets people view this group:'),
        }

        if self.group.type == 'private':
            result['group']['share_subtitle'] = _('Invite new members')
            result['group']['share_msg'] = _(
                'Sharing the link lets people join this group:')

        result['group_users_args'] = [
            _('Members'),
            moderators if self.group.type == 'open' else members,
            result['group']['creator'],
        ]

        if self.request.has_permission('admin', self.group):
            result['group_edit_url'] = self.request.route_url(
                'group_edit', pubid=self.group.pubid)

        result['more_info'] = 'more_info' in self.request.params

        if not result.get('q'):
            result['zero_message'] = Markup(
                _('The group “{name}” has not made any annotations yet.').
                format(name=Markup.escape(self.group.name)))

        result['show_leave_button'] = self.request.user in self.group.members

        return result
Beispiel #26
0
    def search(self):
        result = self._check_access_permissions()
        if result is not None:
            return result

        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result['opts'] = {'search_groupname': self.group.name}

        # If the group has read access only for members  and the user is not in that list
        # return without extra info.
        if self.group.readable_by == ReadableBy.members and (self.request.user not in self.group.members):
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user['user'] == userid:
                    return user['count']
            return 0

        q = query.extract(self.request)
        members = []
        moderators = []
        users_aggregation = result['search_results'].aggregations.get('users', [])
        # If the group has members provide a list of member info,
        # otherwise provide a list of moderator info instead.
        if self.group.members:
            members = [{'username': u.username,
                        'userid': u.userid,
                        'count': user_annotation_count(users_aggregation,
                                                       u.userid),
                        'faceted_by': _faceted_by_user(self.request,
                                                       u.username,
                                                       q)}
                       for u in self.group.members]
            members = sorted(members, key=lambda k: k['username'].lower())
        else:
            moderators = []
            if self.group.creator:
                # Pass a list of moderators, anticipating that [self.group.creator]
                # will change to an actual list of moderators at some point.
                moderators = [{'username': u.username,
                               'userid': u.userid,
                               'count': user_annotation_count(users_aggregation,
                                                              u.userid),
                               'faceted_by': _faceted_by_user(self.request,
                                                              u.username,
                                                              q)}
                              for u in [self.group.creator]]
                moderators = sorted(moderators, key=lambda k: k['username'].lower())

        group_annotation_count = self.request.find_service(name='annotation_stats').group_annotation_count(self.group.pubid)

        result['stats'] = {
            'annotation_count': group_annotation_count,
        }
        result['group'] = {
            'created': utc_us_style_date(self.group.created),
            'description': self.group.description,
            'name': self.group.name,
            'pubid': self.group.pubid,
            'url': self.request.route_url('group_read',
                                          pubid=self.group.pubid,
                                          slug=self.group.slug),
            'share_subtitle': _('Share group'),
            'share_msg': _('Sharing the link lets people view this group:'),
            'organization': {'name': self.group.organization.name,
                             'logo': self._organization_context.logo}
        }

        if self.group.type == 'private':
            result['group']['share_subtitle'] = _('Invite new members')
            result['group']['share_msg'] = _('Sharing the link lets people join this group:')

        result['group_users_args'] = [
            _('Members'),
            moderators if self.group.type == 'open' else members,
            self.group.creator.userid if self.group.creator else None,
        ]

        if self.request.has_permission('admin', self.group):
            result['group_edit_url'] = self.request.route_url(
                'group_edit', pubid=self.group.pubid)

        result['more_info'] = 'more_info' in self.request.params

        if not result.get('q'):
            result['zero_message'] = Markup(_(
                'The group “{name}” has not made any annotations yet.').format(
                    name=Markup.escape(self.group.name)))

        result['show_leave_button'] = self.request.user in self.group.members

        return result
Beispiel #27
0
 def test_returns_empty_results_when_q_param_is_missing(
     self, parse, pyramid_request
 ):
     result = extract(pyramid_request, parse=parse)
     assert result == parse.return_value
Beispiel #28
0
    def test_parses_param_value_with_parser(self, parse, pyramid_request):
        pyramid_request.GET["q"] = "giraffe"

        extract(pyramid_request, parse=parse)

        parse.assert_called_once_with("giraffe")
Beispiel #29
0
    def search(self):
        result = self._check_access_permissions()
        if result is not None:
            return result

        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result['opts'] = {'search_groupname': self.group.name}

        # If the group has a concept of members (aka joinable_by is not None)
        # and the user is not in the list of members, return without extra info.
        if self.group.joinable_by and (self.request.user not in self.group.members):
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user['user'] == userid:
                    return user['count']
            return 0

        q = query.extract(self.request)
        members = None
        moderators = None
        users_aggregation = result['search_results'].aggregations.get('users', [])
        # If the group has a concept of members provide a list of member info,
        # otherwise provide a list of moderator info instead.
        if self.group.joinable_by:
            members = [{'username': u.username,
                        'userid': u.userid,
                        'count': user_annotation_count(users_aggregation,
                                                       u.userid),
                        'faceted_by': _faceted_by_user(self.request,
                                                       u.username,
                                                       q)}
                       for u in self.group.members]
            members = sorted(members, key=lambda k: k['username'].lower())
        else:
            moderators = []
            if self.group.creator:
                # Pass a list of moderators, anticipating that [self.group.creator]
                # will change to an actual list of moderators at some point.
                moderators = [{'username': u.username,
                               'userid': u.userid,
                               'count': user_annotation_count(users_aggregation,
                                                              u.userid),
                               'faceted_by': _faceted_by_user(self.request,
                                                              u.username,
                                                              q)}
                              for u in [self.group.creator]]
                moderators = sorted(moderators, key=lambda k: k['username'].lower())

        group_annotation_count = self.request.find_service(name='annotation_stats').group_annotation_count(self.group.pubid)

        result['stats'] = {
            'annotation_count': group_annotation_count,
        }
        result['group'] = {
            'created': self.group.created.strftime('%B, %Y'),
            'description': self.group.description,
            'name': self.group.name,
            'pubid': self.group.pubid,
            'url': self.request.route_url('group_read',
                                          pubid=self.group.pubid,
                                          slug=self.group.slug),
            'members': members,
            'moderators': moderators,
            'creator': self.group.creator.userid if self.group.creator else None,
        }
        if self.request.has_permission('admin', self.group):
            result['group_edit_url'] = self.request.route_url(
                'group_edit', pubid=self.group.pubid)

        result['more_info'] = 'more_info' in self.request.params

        if not result.get('q'):
            result['zero_message'] = Markup(_(
                'The group “{name}” has not made any annotations yet.').format(
                    name=Markup.escape(self.group.name)))

        return result
Beispiel #30
0
 def test_returns_empty_results_when_q_param_is_missing(
         self, parse, pyramid_request):
     result = extract(pyramid_request, parse=parse)
     assert result == parse.return_value
Beispiel #31
0
    def test_parses_param_value_with_parser(self, parse, pyramid_request):
        pyramid_request.GET['q'] = 'giraffe'

        extract(pyramid_request, parse=parse)

        parse.assert_called_once_with('giraffe')
Beispiel #32
0
    def search(self):
        result = self._check_access_permissions()
        if result is not None:
            return result

        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result['opts'] = {'search_groupname': self.group.name}

        if self.request.user not in self.group.members:
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user['user'] == userid:
                    return user['count']
            return 0

        q = query.extract(self.request)
        users_aggregation = result['search_results'].aggregations.get('users', [])
        members = [{'username': u.username,
                    'userid': u.userid,
                    'count': user_annotation_count(users_aggregation,
                                                   u.userid),
                    'faceted_by': _faceted_by_user(self.request,
                                                   u.username,
                                                   q)}
                   for u in self.group.members]
        members = sorted(members, key=lambda k: k['username'].lower())

        group_annotation_count = self.request.find_service(name='annotation_stats').group_annotation_count(self.group.pubid)

        result['stats'] = {
            'annotation_count': group_annotation_count,
        }

        result['group'] = {
            'created': self.group.created.strftime('%B, %Y'),
            'description': self.group.description,
            'name': self.group.name,
            'pubid': self.group.pubid,
            'url': self.request.route_url('group_read',
                                          pubid=self.group.pubid,
                                          slug=self.group.slug),
            'members': members,
        }

        if self.request.has_permission('admin', self.group):
            result['group_edit_url'] = self.request.route_url(
                'group_edit', pubid=self.group.pubid)

        result['more_info'] = 'more_info' in self.request.params

        if not result.get('q'):
            result['zero_message'] = Markup(_(
                'The group “{name}” has not made any annotations yet.').format(
                    name=Markup.escape(self.group.name)))

        return result
Beispiel #33
0
    def search(self):
        result = self._check_access_permissions()
        if result is not None:
            return result

        check_slug(self.group, self.request)

        result = super(GroupSearchController, self).search()

        result['opts'] = {'search_groupname': self.group.name}

        if self.request.user not in self.group.members:
            return result

        def user_annotation_count(aggregation, userid):
            for user in aggregation:
                if user['user'] == userid:
                    return user['count']
            return 0

        q = query.extract(self.request)
        users_aggregation = result['search_results'].aggregations.get('users', [])
        members = [{'username': u.username,
                    'userid': u.userid,
                    'count': user_annotation_count(users_aggregation,
                                                   u.userid),
                    'faceted_by': _faceted_by_user(self.request,
                                                   u.username,
                                                   q)}
                   for u in self.group.members]
        members = sorted(members, key=lambda k: k['username'].lower())

        group_annotation_count = None
        if self.request.feature('total_shared_annotations'):
            group_annotation_count = self.request.find_service(name='annotation_stats').group_annotation_count(self.group.pubid)

        result['stats'] = {
            'annotation_count': group_annotation_count,
        }

        result['group'] = {
            'created': self.group.created.strftime('%B, %Y'),
            'description': self.group.description,
            'name': self.group.name,
            'pubid': self.group.pubid,
            'url': self.request.route_url('group_read',
                                          pubid=self.group.pubid,
                                          slug=self.group.slug),
            'members': members,
        }

        if self.request.has_permission('admin', self.group):
            result['group_edit_url'] = self.request.route_url(
                'group_edit', pubid=self.group.pubid)

        result['more_info'] = 'more_info' in self.request.params

        if not result.get('q'):
            result['zero_message'] = Markup(_(
                'The group “{name}” has not made any annotations yet.').format(
                    name=Markup.escape(self.group.name)))

        return result
Beispiel #34
0
    def test_parses_param_value_with_parser(self, parse, pyramid_request):
        pyramid_request.GET["q"] = "giraffe"

        extract(pyramid_request, parse=parse)

        parse.assert_called_once_with("giraffe")
Beispiel #35
0
    def test_parses_param_value_with_parser(self, parse, pyramid_request):
        pyramid_request.GET['q'] = 'giraffe'

        extract(pyramid_request, parse=parse)

        parse.assert_called_once_with('giraffe')
Beispiel #36
0
 def __init__(self, request):
     self.request = request
     # Cache a copy of the extracted query params for the child controllers to use if needed.
     self.parsed_query_params = query.extract(self.request)