コード例 #1
0
def getContextAvatar(context, request):
    """
    """
    urlHash = request.matchdict['urlHash']
    AVATAR_FOLDER = request.registry.settings.get('avatar_folder')
    context_image_filename = '%s/%s.jpg' % (AVATAR_FOLDER, urlHash)

    if not os.path.exists(context_image_filename):
        mmdb = MADMaxDB(context.db)
        found_context = mmdb.contexts.getItemsByurlHash(urlHash)
        if len(found_context) > 0:
            twitter_username = found_context[0]['twitterUsername']
            downloadTwitterUserImage(twitter_username, context_image_filename)

    if os.path.exists(context_image_filename):
        filename = urlHash
        # Calculate time since last download and set if we have to redownload or not
        modification_time = os.path.getmtime(context_image_filename)
        hours_since_last_modification = (time.time() -
                                         modification_time) / 60 / 60
        if hours_since_last_modification > 3:
            mmdb = MADMaxDB(context.db)
            found_context = mmdb.contexts.getItemsByurlHash(urlHash)
            twitter_username = found_context[0]['twitterUsername']
            downloadTwitterUserImage(twitter_username, context_image_filename)
    else:
        context_image_filename = '%s/missing.jpg' % (AVATAR_FOLDER)

    data = open(context_image_filename).read()
    image = Response(data, status_int=200)
    image.content_type = 'image/jpeg'
    return image
コード例 #2
0
def getContexts(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    contexts = mmdb.contexts.dump(flatten=1)
    handler = JSONResourceRoot(contexts)
    return handler.buildResponse()
コード例 #3
0
def getActivities(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    activities = mmdb.activity.dump(flatten=1)
    handler = JSONResourceRoot(activities)
    return handler.buildResponse()
コード例 #4
0
def getUsers(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    users = mmdb.users.dump(flatten=1)
    handler = JSONResourceRoot(users)
    return handler.buildResponse()
コード例 #5
0
def deleteUser(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    userid = request.matchdict.get('id', None)
    try:
        found_user = mmdb.users[userid]
    except:
        raise ObjectNotFound, "There's no user with id: %s" % userid

    found_user.delete()
    return HTTPNoContent()
コード例 #6
0
def deleteActivity(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    activityid = request.matchdict.get('id', None)
    try:
        found_activity = mmdb.activity[activityid]
    except:
        raise ObjectNotFound, "There's no activity with id: %s" % activityid

    found_activity.delete()
    return HTTPNoContent()
コード例 #7
0
def getContext(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    urlhash = request.matchdict.get('urlHash', None)
    found_context = mmdb.contexts.getItemsByurlHash(urlhash)

    if not found_context:
        raise ObjectNotFound, "There's no context matching this url hash: %s" % urlhash

    handler = JSONResourceEntity(found_context[0].flatten())
    return handler.buildResponse()
コード例 #8
0
def getUserTimeline(context, request):
    """
         /people/{username}/timeline

         Retorna totes les activitats d'un usuari
    """
    actor = request.actor
    is_context_resource = 'timeline/contexts' in request.path
    is_follows_resource = 'timeline/follows' in request.path

    mmdb = MADMaxDB(context.db)

    actor_query = {'actor._id': actor['_id']}

    # Add the activity of the people that the user follows
    actors_followings = []
    for following in actor['following']['items']:
        followed_person = mmdb.users.getItemsByusername(
            following['username'])[0]
        if followed_person:
            actors_followings.append({'actor._id': followed_person['_id']})

    # Add the activity of the people that posts to a particular context
    contexts_followings = []
    for subscribed in actor['subscribedTo']['items']:
        contexts_followings.append({'contexts.url': subscribed['url']})

    query_items = []

    if not is_follows_resource and not is_context_resource:
        query_items.append(actor_query)
        query_items += actors_followings
        query_items += contexts_followings

    if is_context_resource:
        query_items += contexts_followings

    if is_follows_resource:
        query_items += contexts_followings

    if query_items:
        query = {'$or': query_items}
        query['verb'] = 'post'
        activities = mmdb.activity.search(query,
                                          sort="_id",
                                          flatten=1,
                                          **searchParams(request))
    else:
        activities = []

    handler = JSONResourceRoot(activities)
    return handler.buildResponse()
コード例 #9
0
def getUserActivities(context, request):
    """
         /people/{username}/activities

         Retorna all activities generated by a user
    """

    mmdb = MADMaxDB(context.db)
    query = {'actor._id': request.actor['_id']}
    activities = mmdb.activity.search(query, sort="_id", flatten=1)

    handler = JSONResourceRoot(activities)
    return handler.buildResponse()
コード例 #10
0
def getActivity(context, request):
    """
         /activities/{activity}

         Mostra una activitat
    """

    mmdb = MADMaxDB(context.db)
    activity_oid = request.matchdict['activity']
    activity = mmdb.activity[activity_oid].flatten()

    handler = JSONResourceEntity(activity)
    return handler.buildResponse()
コード例 #11
0
def DeleteContext(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    urlhash = request.matchdict.get('urlHash', None)
    found_context = mmdb.contexts.getItemsByurlHash(urlhash)

    if not found_context:
        raise ObjectNotFound, "There's no context matching this url hash: %s" % urlhash

    found_context[0].delete()
    found_context[0].removeUserSubscriptions()
    return HTTPNoContent()
コード例 #12
0
def deleteContext(context, request):
    """
    """
    mmdb = MADMaxDB(context.db)
    contextid = request.matchdict.get('id', None)
    try:
        found_context = mmdb.contexts[contextid]
    except:
        raise ObjectNotFound, "There's no context with id: %s" % contextid

    found_context.delete()

    # XXX in admin too ?
    #found_context[0].removeUserSubscriptions()
    return HTTPNoContent()
コード例 #13
0
def getActivityComments(context, request):
    """
    """
    activityid = request.matchdict['activity']

    mmdb = MADMaxDB(context.db)
    refering_activity = mmdb.activity[activityid]
    #cond1 = {'object.objectType' : 'comment'}
    #cond2 = {'object.inReplyTo._id' : refering_activity['_id']}
    #query = {'$and' : [ cond1, cond2 ] }
    #activities = mmdb.activity.search(query, sort="_id", limit=10, flatten=1)

    #handler = JSONResourceRoot(activities)
    replies = refering_activity.get('replies', {})
    items = replies.get('items', [])
    flatten(items)
    handler = JSONResourceRoot(items)
    return handler.buildResponse()
コード例 #14
0
def addActivityComment(context, request):
    """
    POST /activities/{activity}/comments
    """
    #XXX TODO ara només es tracta la primera activitat,
    # s'ha de iterar si es vol que el comentari sigui de N activitats
    activityid = request.matchdict['activity']

    mmdb = MADMaxDB(context.db)
    refering_activity = mmdb.activity[activityid]

    # Prepare rest parameters to be merged with post data
    rest_params = {
        'verb': 'comment',
        'object': {
            'inReplyTo': [{
                '_id': ObjectId(activityid),
                'objectType': refering_activity.object['objectType']
            }]
        }
    }

    # Initialize a Activity object from the request
    newactivity = Activity()
    newactivity.fromRequest(request, rest_params=rest_params)

    code = 201
    newactivity_oid = newactivity.insert()
    newactivity['_id'] = newactivity_oid

    comment = dict(newactivity.object)
    comment['published'] = newactivity.published
    comment['author'] = request.actor
    comment['id'] = newactivity._id
    del comment['inReplyTo']

    refering_activity.addComment(comment)

    handler = JSONResourceEntity(newactivity.flatten(), status_code=code)
    return handler.buildResponse()
コード例 #15
0
def getActivities(context, request):
    """
         /activities

         Retorna all activities, optionaly filtered by context
    """
    urlhash = request.params.get('context', None)
    if not urlhash:
        raise MissingField, 'You have to specify one context'

    mmdb = MADMaxDB(context.db)

    # subscribed contexts with read permission
    subscribed = [
        context.get('url')
        for context in request.actor.subscribedTo.get('items', [])
        if 'read' in context.get('permissions', [])
    ]

    # get the defined read context
    rcontext = mmdb.contexts.getItemsByurlHash(urlhash)[0]
    url = rcontext.url

    # regex query to find all contexts within url
    escaped = re.escape(url)
    url_regex = {'$regex': '^%s' % escaped}

    # search all contexts with public read permissions within url
    query = {'permissions.read': 'public', 'url': url_regex}
    public = [
        result.url
        for result in mmdb.contexts.search(query, show_fields=['url'])
    ]

    query = {}  # Search
    query.update({'verb': 'post'})  # 'post' activities
    query.update({'contexts.url': url_regex})  # equal or child of url

    contexts_query = []
    if subscribed:
        subscribed_query = {
            'contexts.url': {
                '$in': subscribed
            }
        }  # that are subscribed contexts
        contexts_query.append(subscribed_query)  # with read permission

    if public:  # OR
        public_query = {'contexts.url': {'$in': public}}
        contexts_query.append(public_query)  # pubic contexts

    if contexts_query:
        query.update({'$or': contexts_query})
        activities = mmdb.activity.search(query,
                                          sort="_id",
                                          flatten=1,
                                          **searchParams(request))
    else:
        # we have no public contexts and we are not subscribed to any context, so we
        # won't get anything
        activities = []

    # pass the read context as a extension to the resource
    handler = JSONResourceRoot(activities,
                               extension=dict(context=rcontext.flatten()))
    return handler.buildResponse()
コード例 #16
0
    def replacement(*args, **kwargs):
        nkargs = [a for a in args]
        context, request = isinstance(
            nkargs[0], Root) and tuple(nkargs) or tuple(nkargs[::-1])

        actor = None
        mmdb = MADMaxDB(context.db)
        admin_ws = [('admin_users', 'GET'), ('admin_activities', 'GET'),
                    ('admin_contexts', 'GET'), ('admin_user', 'DELETE'),
                    ('admin_activity', 'DELETE'), ('admin_context', 'DELETE')]
        allowed_ws_without_username = admin_ws + [('contexts', 'POST'),
                                                  ('context', 'GET'),
                                                  ('context', 'PUT'),
                                                  ('context', 'DELETE')]
        allowed_ws_without_actor = [('user', 'POST')
                                    ] + allowed_ws_without_username

        # If Oauth authorization is used, The actor that will perform the actions will be
        # the one specified in oauth headers, so for routes that match username
        # parameter in the URI, we only allow this username to be the same as oauth username
        # for validation purposes. Same thing from actor defined in post request body
        if isOauth(request):
            oauth_username = getUsernameFromXOAuth(request)
            rest_username = getUsernameFromURI(request)

            # XXX TODO Define cases where oauth_username MAY/CAN be different
            # to rest_username/post_username
            if rest_username and oauth_username != rest_username:
                raise Unauthorized, "You don't have permission to access %s resources" % (
                    rest_username)
            post_username = getUsernameFromPOSTBody(request)
            if post_username and oauth_username != post_username:
                raise Unauthorized, "You don't have permission to access %s resources" % (
                    post_username)
            # If user validation is successfull, try to load the oauth User from DB
            try:
                actor = mmdb.users.getItemsByusername(oauth_username)[0]
            except:
                raise UnknownUserError, 'Unknown user "%s"' % oauth_username

        # If Basic auth is used, actor username can be any username, as we are
        # impersonating him. We will search for this username in several places:

        elif isBasic(request):
            actorType = 'person'
            #Try to get the username from the REST URI
            username = getUsernameFromURI(request)
            #Try to get the username from the POST body
            if not username and request.method == 'POST':
                username = getUsernameFromPOSTBody(request)

            # If no actor specified anywhere, raise an error
            # except when allowed not having a username
            # or when adding a context activity
            if not username:
                if (request.matched_route.name,
                        request.method) == ('admin_context_activities',
                                            'POST'):
                    contexthash = getUrlHashFromURI(request)
                    actorType = 'context'
                elif not ((request.matched_route.name, request.method)
                          in allowed_ws_without_username):
                    raise UnknownUserError, 'No user specified as actor'

            # Raise only if we are NOT adding a user or a context. These are the only cases
            # Were we permit not specifing an ator:
            #   - Creating a user, beacause the user doesn't exists
            #   - Creating a context, because context is actor-agnostic
            #   - Getting a context, because context is actor-agnostic

            #try to load the user actor from DB
            if actorType == 'person':
                try:
                    actor = mmdb.users.getItemsByusername(username)[0]
                except:
                    if not ((request.matched_route.name, request.method)
                            in allowed_ws_without_actor):
                        raise UnknownUserError, 'Unknown actor identified by username: %s' % username

            #try to load the context actor from DB
            if actorType == 'context':
                try:
                    actor = mmdb.contexts.getItemsByurlHash(contexthash)[0]
                except:
                    raise UnknownUserError, 'Unknown actor identified by context : %s' % contexthash

        # Raise an error if no authentication present
        else:
            raise Unauthorized, "There are no supported authentication methods present in this request"

        # If we arrive at this point, we have a valid user in actor.
        # (Except in the case of a new users explained 10 lines up)
        # Define a callable to prepare the actor in order to inject it in the request

        def getActor(request):
            try:
                if isinstance(actor, User):
                    actor.setdefault('displayName', actor['username'])
                if isinstance(actor, Context):
                    actor.setdefault('displayName', actor['url'])
                return actor
            except:
                return None

        request.set_property(getActor, name='actor', reify=True)

        response = func(*args, **kwargs)
        return response