Exemple #1
0
def sorted_query(request, collection, query, count=None, **kwargs):
    """
        Main sort method that determines which method of sorting to use
        based on sort parameters found in the request.

        Falls back to sensible defaults if no sorting defined
    """
    search_params = searchParams(request)
    search_params.update(kwargs)
    is_head = count if count is not None else request.method == 'HEAD'

    strategy = search_params.pop('sort_strategy', 'published')
    priority = search_params.pop('sort_priority', 'activity')

    search_params['sort_params'] = SORT_STRATEGIES[strategy][priority]

    if strategy == 'published':
        activities = simple_sort(collection, query, search_params, is_head)

    elif strategy == 'likes':
        search_params['flatten'] = 1
        activities = get_activities_sorted_by_like_count(collection, query, search_params, is_head)

    elif strategy == 'flagged':
        search_params['flatten'] = 1
        activities = get_activities_sorted_by_flagged_first(collection, query, search_params, is_head)

    return activities
Exemple #2
0
def getVisibleUsers(users, request):
    """
        Search users

        Return a list of persons of the system, optionaly filtered using the available
        modifiers.

        The objects returned by this endpoint are intended for user listing and
        searching, so only username and displayName attributes of a person are returned. If you
        need the full profile of a user, use the `GET` endpoint of the `User` resource.
    """
    query = {}

    search_params = searchParams(request)
    filter_fields = ["username", "displayName", "objectType", 'subscribedTo']
    if asbool(search_params.get('twitter_enabled', False)):
        filter_fields.append("twitterUsername")

    found_users = users.search(query, show_fields=filter_fields, sort_by_field="username", flatten=0, **search_params)
    # Filter user results. User

    filtered_users = [user for user in found_users if request.actor.is_allowed_to_see(user)]

    handler = JSONResourceRoot(request, flatten(filtered_users, squash=['subscribedTo']), remaining=found_users.remaining)
    return handler.buildResponse()
Exemple #3
0
def getContexts(contexts, request):
    """
        Get all contexts
    """
    found_contexts = contexts.search({}, flatten=1, **searchParams(request))
    handler = JSONResourceRoot(request, found_contexts)
    return handler.buildResponse()
Exemple #4
0
def getPublicContexts(contexts, request):
    """
        Get all public contexts

        Returns a list of all public subscribable contexts
    """
    found_contexts = contexts.search({'permissions.subscribe': 'public'}, **searchParams(request))

    handler = JSONResourceRoot(request, flatten(found_contexts, squash=['owner', 'creator', 'published']))
    return handler.buildResponse()
Exemple #5
0
def getPushTokensForConversation(tokens, request):
    """
        Return conversation tokens
    """
    cid = request.matchdict['id']
    query = {'talkingIn.id': cid}

    user_tokens = []
    users = request.db.users.search(query, show_fields=["username"], sort_by_field="username", flatten=1)
    usernames = [user['username'] for user in users]

    if usernames:
        user_tokens = tokens.search({'_owner': {'$in': usernames}}, **searchParams(request))

    handler = JSONResourceRoot(request, formatted_tokens(user_tokens))
    return handler.buildResponse()
Exemple #6
0
def getContextComments(context, request):
    """
        Get context activities comments
    """
    is_head = request.method == 'HEAD'

    query = {
        'verb': 'comment',
        'object.inReplyTo.contexts': {
            '$in': [context['hash']]
        }
    }

    comments = request.db.activity.search(query, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(request, comments, stats=is_head)
    return handler.buildResponse()
Exemple #7
0
def getPushTokensForContext(tokens, request):
    """
         Return context tokens
    """

    cid = request.matchdict['hash']
    contexts = MADMaxCollection(request, 'contexts', query_key='hash')
    ctxt = contexts[cid]

    user_tokens = []
    users = ctxt.subscribedUsers()
    usernames = [user['username'] for user in users]

    if usernames:
        user_tokens = tokens.search({'_owner': {'$in': usernames}}, **searchParams(request))

    handler = JSONResourceRoot(request, formatted_tokens(user_tokens))
    return handler.buildResponse()
Exemple #8
0
def getUserSubscriptions(user, request):
    """
        Get all user subscriptions
    """
    subscriptions = user.get('subscribedTo', [])

    search_params = searchParams(request)
    tags = set(search_params.pop('tags', []))

    # XXX Whhen refactoring subscriptions storage to a different collection
    # Change this for a search on subscriptions collection
    if tags:
        filtered_subscriptions = []
        for subscription in subscriptions:
            if tags.intersection(set(subscription.get('tags', []))) == tags:
                filtered_subscriptions.append(subscription)
        subscriptions = filtered_subscriptions

    handler = JSONResourceRoot(request, subscriptions)
    return handler.buildResponse()
Exemple #9
0
def getActiveConversations(message, request):
    """
        Get active conversations inspecting messages
    """
    is_head = request.method == 'HEAD'
    messages = request.db.messages.search({'verb': 'post'}, flatten=1, **searchParams(request))

    conversations = {}
    for message in messages:
        if message['contexts'][0]['id'] not in conversations:
            conversations[message['contexts'][0]['id']] = message['contexts'][0]

    results = []
    for conversation in conversations:
        results.append(conversations[conversation])

    if is_head:
        results = len(results)

    handler = JSONResourceRoot(request, results, stats=is_head)
    return handler.buildResponse()
Exemple #10
0
def getUserComments(user, request):
    """
        Get user comments

        Get all the comments generated by a user anywhere
    """
    query = {
        'object.objectType': 'comment',
        'verb': 'comment',
        'actor.username': user['username']
    }
    is_head = request.method == 'HEAD'
    comments = request.db.activity.search(
        query,
        sort="_id",
        keep_private_fields=False,
        squash=['deletable', 'favorited', 'favorites', 'faavoritesCount'],
        flatten=1,
        count=is_head,
        **searchParams(request))

    handler = JSONResourceRoot(request, comments, stats=is_head)
    return handler.buildResponse()
Exemple #11
0
def getContextSubscriptions(context, request):
    """
        Get all context subscriptions
    """
    found_users = request.db.users.search({"subscribedTo.hash": context['hash']}, flatten=0, show_fields=["username", "subscribedTo"], **searchParams(request))

    def format_subscriptions():
        for user in found_users:
            user_subscription = user.getSubscription(context)
            subscription = {
                'username': user['username'],
                'permissions': user_subscription['permissions'],
                'vetos': user_subscription.get('vetos', []),
                'grants': user_subscription.get('grants', []),
                'hash': user_subscription['hash']
            }
            yield subscription

    handler = JSONResourceRoot(request, format_subscriptions())
    return handler.buildResponse()
Exemple #12
0
def getGlobalActivities(context, request):
    """
        Get global activities

        Returns all post activities generated in the system by anyone.
    """
    is_head = request.method == 'HEAD'
    activities = request.db.activity.search({'verb': 'post'}, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(request, activities, stats=is_head)
    return handler.buildResponse()
Exemple #13
0
def getUserActivities(user, request):
    """
        Get user activities

        Returns all post visible activities generated by a user in his timeline or contexts.
        Include only contexts shared between user and creator if different
    """

    can_list_activities_unsubscribed = isinstance(request.has_permission(list_activities_unsubscribed), ACLAllowed)
    query = visible_user_activities_query(user, request, filter_non_shared=not can_list_activities_unsubscribed)

    is_head = request.method == 'HEAD'
    activities = request.db.activity.search(query, keep_private_fields=False, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(request, activities, stats=is_head)
    return handler.buildResponse()
Exemple #14
0
def getConversationMessages(conversation, request):
    """
        Get all messages from a conversation
    """
    query = {'contexts.id': str(conversation['_id'])}

    # Sorting by _id, as id is indeed the same as published
    messages = request.db.messages.search(query, sort_direction=DESCENDING, sort_by_field="_id", keep_private_fields=False, **searchParams(request))
    inverted = flatten(messages, reverse=True)
    handler = JSONResourceRoot(request, inverted, remaining=messages.remaining)
    return handler.buildResponse()
Exemple #15
0
def getMessages(message, request):
    """
        Get all messages
    """
    is_head = request.method == 'HEAD'
    activities = request.db.messages.search({'verb': 'post'}, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(request, activities, stats=is_head)
    return handler.buildResponse()
Exemple #16
0
def getGlobalComments(comments, request):
    """
        Get global comments
    """
    is_head = request.method == 'HEAD'
    activities = request.db.activity.search({'verb': 'comment'}, flatten=1, count=is_head, **searchParams(request))
    handler = JSONResourceRoot(request, activities, stats=is_head)
    return handler.buildResponse()