def request_friendship(request):
    """Sends a friend request."""
    context = RequestContext(request)

    if request.method == 'POST':
        if request.user.is_authenticated():
            friend_requestee = request.POST['friend_requestee']
            friend_user = User.objects.get(username=friend_requestee)
            friend = Author.objects.get(user=friend_user)
            requester = Author.objects.get(user=request.user)

            if '__' not in friend.user.username:
                # local author
                status = FriendRequest.make_request(requester, friend)
            else:
                print 'HERE'
                # remote author
                status = post_friend_request(requester, friend)
                if status:
                    status = FriendRequest.make_request(requester, friend)

            if status:
                messages.info(request, 'Friend request sent successfully')
            else:
                messages.error(request, 'Error sending a friend request')

            return redirect('/author/friends')
        else:
            _render_error('login.html', 'Please log in.', context)
def request_friendship(request):
    """Sends a friend request."""
    context = RequestContext(request)

    if request.method == 'POST':
        if request.user.is_authenticated():
            friend_requestee = request.POST['friend_requestee']
            friend_user = User.objects.get(username=friend_requestee)
            friend = Author.objects.get(user=friend_user)
            requester = Author.objects.get(user=request.user)

            if '__' not in friend.user.username:
                # local author
                status = FriendRequest.make_request(requester, friend)
            else:
                print 'HERE'
                # remote author
                status = post_friend_request(requester, friend)
                if status:
                    status = FriendRequest.make_request(requester, friend)

            if status:
                messages.info(request, 'Friend request sent successfully')
            else:
                messages.error(request, 'Error sending a friend request')

            return redirect('/author/friends')
        else:
            _render_error('login.html', 'Please log in.', context)
def friend_request_list(request):
    """Displays a list of users that the author sent a friend requst to."""
    context = RequestContext(request)

    if request.method == 'GET':
        if request.user.is_authenticated():
            request_list = []
            sent_list = []
            friend_list = []
            rlShow = True
            slShow = True
            flShow = True
            rUser = Author.objects.get(user=request.user)
            #friendJ = get_is_friend('2356e331-ef78-402f-b880-240269f7a93f', '52e7ace8-3723-4a7d-8abc-d4228ff5dced')
            for author in FriendRequest.received_requests(rUser):
                # check if it is a remote author
                info = {
                    "displayname": author.get_username(),
                    "username": author.user.username,
                    "userID": author.get_uuid(),
                    "host": author.get_host()
                }
                request_list.append(info)
            for author in FriendRequest.sent_requests(rUser):
                if '__' in author.user.username:
                    isFriend = get_is_friend(rUser, author)
                info = {
                    "displayname": author.get_username(),
                    "username": author.user.username,
                    "userID": author.get_uuid(),
                    "host": author.get_host()
                }
                sent_list.append(info)
            for author in FriendRequest.get_friends(rUser):
                info = {
                    "displayname": author.user.username,
                    "username": author.user.username,
                    "userID": author.get_uuid(),
                    "host": author.get_host()
                }
                friend_list.append(info)
            if not request_list:
                rlShow = False
            if not sent_list:
                slShow = False
            if not friend_list:
                flShow = False
            context = RequestContext(
                request, {
                    'requestList': request_list,
                    'sentList': sent_list,
                    'friendList': friend_list,
                    'rlShow': rlShow,
                    'slShow': slShow,
                    'flShow': flShow
                })
        else:
            _render_error('login.html', 'Please log in.', context)

    return render_to_response('friendRequests.html', context)
def getVisibleToAuthor(viewer=None,
                       author=None,
                       time_line=False,
                       localOnly=False):
    resultList = []
    if author is None:
        postList = Post.objects.all()
    else:
        postList = Post.objects.filter(author=author)

    for post in postList:
        if post.isViewable(viewer, post.author):
            # if we are should timeline only, then we need to check whether or not the
            # two are friends
            if post.content_type == Post.MARK_DOWN:
                post.content = markdown.markdown(post.content,
                                                 safe_mode='escape')

            if time_line:
                if (viewer == post.author
                        or FriendRequest.is_friend(viewer, post.author)
                        or FriendRequest.is_following_or_made_request(
                            viewer, post.author)):
                    resultList.append(get_post_json(post))
            else:
                resultList.append(get_post_json(post))

    if localOnly is False:
        if not time_line:
            remote_posts = remote_helper.api_getPublicPost()
            for post in remote_posts:
                if post['content-type'] == Post.MARK_DOWN:
                    post['content_type'] = Post.MARK_DOWN
                    post['content'] = markdown.markdown(post['content'],
                                                        safe_mode='escape')
        else:
            friend_posts = []
            authorID = author.get_uuid() if author is not None else None
            remote_posts = remote_helper.api_getPostByAuthorID(
                viewer, authorID)

            for post in remote_posts:
                if post['content-type'] == Post.MARK_DOWN:
                    post['content_type'] = Post.MARK_DOWN
                    post['content'] = markdown.markdown(post['content'],
                                                        safe_mode='escape')

                author = post['author']
                author = Author.objects.filter(uuid=author['id'])
                if len(author) > 0:
                    author = author.first()
                    if FriendRequest.is_following_or_made_request(
                            author, viewer) or FriendRequest.is_friend(
                                author, viewer):
                        friend_posts.append(post)
            remote_posts = friend_posts

        resultList.extend(remote_posts)

    return resultList
def getVisibleToAuthor(viewer=None, author=None, time_line=False, localOnly=False):
    resultList = []
    if author is None:
        postList = Post.objects.all()
    else:
        postList = Post.objects.filter(author=author)

    for post in postList:
        if post.isViewable(viewer, post.author):
            # if we are should timeline only, then we need to check whether or not the
            # two are friends
            if post.content_type == Post.MARK_DOWN:
                post.content = markdown.markdown(post.content,
                                                 safe_mode='escape')

            if time_line:
                if (viewer == post.author or FriendRequest.is_friend(viewer, post.author) or
                        FriendRequest.is_following_or_made_request(viewer, post.author)):
                    resultList.append(get_post_json(post))
            else:
                resultList.append(get_post_json(post))

    if localOnly is False:
        if not time_line:
            remote_posts = remote_helper.api_getPublicPost()
            for post in remote_posts:
                if post['content-type'] == Post.MARK_DOWN:
                    post['content_type'] = Post.MARK_DOWN
                    post['content'] = markdown.markdown(post['content'],
                                     safe_mode='escape')
        else:
            friend_posts = []
            authorID = author.get_uuid() if author is not None else None
            remote_posts = remote_helper.api_getPostByAuthorID(viewer, authorID)

            for post in remote_posts:
                if post['content-type'] == Post.MARK_DOWN:
                    post['content_type'] = Post.MARK_DOWN
                    post['content'] = markdown.markdown(post['content'],
                                     safe_mode='escape')

                author = post['author']
                author = Author.objects.filter(uuid=author['id'])
                if len(author) > 0:
                    author = author.first()
                    if FriendRequest.is_following_or_made_request(author, viewer) or FriendRequest.is_friend(author, viewer):
                        friend_posts.append(post)
            remote_posts = friend_posts

        resultList.extend(remote_posts)

    return resultList
 def test_is_following(self):
     """Testing if a user is following another"""
     c = Client()
     user1 = User.objects.get(username="******")
     user2 = User.objects.get(username="******")
     author1 = Author.objects.get(user=user1)
     author2 = Author.objects.get(user=user2)
     response = FriendRequest.make_request(author1, author2)
     response2 = FriendRequest.is_following(author1, author2)
     response3 = FriendRequest.is_following(author2, author1)
     self.assertEquals(True, response)
     self.assertEquals(True, response2)
     self.assertEquals(False, response3)
 def test_is_following(self):
     """Testing if a user is following another"""
     c = Client()
     user1 = User.objects.get(username="******")
     user2 = User.objects.get(username="******")
     author1 = Author.objects.get(user=user1)
     author2 = Author.objects.get(user=user2)
     response = FriendRequest.make_request(author1, author2)
     response2 = FriendRequest.is_following(author1, author2)
     response3 = FriendRequest.is_following(author2, author1)
     self.assertEquals(True, response)
     self.assertEquals(True, response2)
     self.assertEquals(False, response3)
def friend_request_list(request):
    """Displays a list of users that the author sent a friend requst to."""
    context = RequestContext(request)

    if request.method == 'GET':
        if request.user.is_authenticated():
            request_list = []
            sent_list = []
            friend_list = []
            rlShow = True
            slShow = True
            flShow = True
            rUser = Author.objects.get(user = request.user)
            #friendJ = get_is_friend('2356e331-ef78-402f-b880-240269f7a93f', '52e7ace8-3723-4a7d-8abc-d4228ff5dced')
            for author in FriendRequest.received_requests(rUser):
                # check if it is a remote author
                info = {"displayname": author.get_username(),
                        "username": author.user.username,
                        "userID": author.get_uuid(),
                        "host": author.get_host()}
                request_list.append(info)
            for author in FriendRequest.sent_requests(rUser):
                if '__' in author.user.username:
                    isFriend = get_is_friend(rUser, author)
                info = {"displayname": author.get_username(),
                        "username": author.user.username,
                        "userID": author.get_uuid(),
                        "host": author.get_host()}
                sent_list.append(info)
            for author in FriendRequest.get_friends(rUser):
                info = {"displayname": author.user.username,
                        "username": author.user.username,
                        "userID": author.get_uuid(),
                        "host": author.get_host()}
                friend_list.append(info)
            if not request_list:
                rlShow = False
            if not sent_list:
                slShow = False
            if not friend_list:
                flShow = False
            context = RequestContext(request, {'requestList': request_list,
                                               'sentList': sent_list,
                                               'friendList':friend_list,
                                               'rlShow': rlShow,
                                               'slShow':slShow,
                                               'flShow':flShow})
        else:
            _render_error('login.html', 'Please log in.', context)

    return render_to_response('friendRequests.html', context)
 def test_are_friends(self):
     """Testing if correctly identifies two authors as friends or not"""
     user1 = User.objects.get(username="******")
     user2 = User.objects.get(username="******")
     author1 = Author.objects.get(user=user1)
     author2 = Author.objects.get(user=user2)
     response = FriendRequest.make_request(author1, author2)
     response2 = FriendRequest.is_friend(author1, author2)
     response3 = FriendRequest.accept_request(author2, author1)
     response4 = FriendRequest.is_friend(author1, author2)
     response5 = FriendRequest.is_friend(author2, author1)
     self.assertEquals(True, response)
     self.assertEquals(False, response2)
     self.assertEquals(True, response3)
     self.assertEquals(True, response4)
     self.assertEquals(True, response5)
 def test_are_friends(self):
     """Testing if correctly identifies two authors as friends or not"""
     user1 = User.objects.get(username="******")
     user2 = User.objects.get(username="******")
     author1 = Author.objects.get(user=user1)
     author2 = Author.objects.get(user=user2)
     response = FriendRequest.make_request(author1, author2)
     response2 = FriendRequest.is_friend(author1, author2)
     response3 = FriendRequest.accept_request(author2, author1)
     response4 = FriendRequest.is_friend(author1, author2)
     response5 = FriendRequest.is_friend(author2, author1)
     self.assertEquals(True, response)
     self.assertEquals(False, response2)
     self.assertEquals(True, response3)
     self.assertEquals(True, response4)
     self.assertEquals(True, response5)
    def test_friend_list(self):
        """Testing if successfully returns a list of friends"""
        c = Client()
        c.login(username='******', password='******')
        user1 = User.objects.get(username="******")
        user2 = User.objects.get(username="******")
        author1 = Author.objects.get(user=user1)
        author2 = Author.objects.get(user=user2)
        response = FriendRequest.make_request(author2, author1)
        response2 = FriendRequest.accept_request(author1, author2)

        url = '/author/' + str(user1.id) + '/Friends'
        response = c.get(url)
        self.assertEquals(response.status_code, 200)
        response = response.context['friendList']
        response = response.split(':')
        self.assertEquals(response, ['myuser2'])
    def test_friend_list(self):
        """Testing if successfully returns a list of friends"""
        c = Client()
        c.login(username='******', password='******')
        user1 = User.objects.get(username="******")
        user2 = User.objects.get(username="******")
        author1 = Author.objects.get(user=user1)
        author2 = Author.objects.get(user=user2)
        response = FriendRequest.make_request(author2, author1)
        response2 = FriendRequest.accept_request(author1, author2)

        url = '/author/' + str(user1.id) + '/Friends'
        response = c.get(url)
        self.assertEquals(response.status_code, 200)
        response=response.context['friendList']
        response=response.split(':')
        self.assertEquals(response, ['myuser2'])
def follow(request):
    context = RequestContext(request)
    if request.method == 'POST':
        if request.user.is_authenticated():
            followee = request.POST['followee']
            followee = User.objects.get(username=followee)
            followee2 = Author.objects.get(user=followee)
            author = Author.objects.get(user=request.user)
            status = FriendRequest.follow(author, followee2)
            if status:
                messages.info(request, 'New Follower')
            return redirect('/', context)
    else:
        _render_error('login.html', 'Please log in.', context)
    def isViewable(self, viewer, author):

        visibility = self.visibility

        if visibility == Post.PRIVATE:
            return viewer == author
        elif visibility == Post.ANOTHER_AUTHOR:
            post_entry = VisibleToAuthor.objects.filter(
                visibleAuthor=viewer, post=self)
            return post_entry.exists() or viewer == author
        elif visibility == Post.FRIENDS:
            return FriendRequest.is_friend(viewer, author) or viewer == author
        elif visibility == Post.FOAF:
            friendOfFriends = []
            friends = FriendRequest.get_friends(author)
            for friend in friends:
                friendOfFriends += FriendRequest.get_friends(friend)
            return viewer in friendOfFriends or viewer == author or FriendRequest.is_friend(viewer, author)
        elif visibility == Post.SERVERONLY:
            return viewer.host == author.host or viewer == author
        else:
            # Assuming that the visibility type is public
            return True
def follow(request):
    context = RequestContext(request)
    if request.method == 'POST':
        if request.user.is_authenticated():
            followee = request.POST['followee']
            followee = User.objects.get(username=followee)
            followee2 = Author.objects.get(user=followee)
            author = Author.objects.get(user=request.user)
            status = FriendRequest.follow(author, followee2)
            if status:
                messages.info(request, 'New Follower')
            return redirect('/', context)
    else:
        _render_error('login.html', 'Please log in.', context)
def is_friend(request, user_id1, user_id2):
    """Return whether the provided two users are friends.

    This responds with a JSON of the following content:

    {
        "query": "friends",
        "authors": [
            "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
            "8d919f29c12e8f97bcbbd34cc908f19ab9496989"
        ],
        # or NO
        "friends":"YES"
    }
    """
    if request.method == 'GET':
        try:
            response = {
                'query': 'friends',
                'authors': [
                    user_id1,
                    user_id2
                ],
                'friends': 'NO'
            }

            author1 = Author.objects.filter(uuid=user_id1)
            author2 = Author.objects.filter(uuid=user_id2)

            if len(author1) > 0 and len(author2) > 0:
                # We're only expecting one author
                author1 = author1[0]
                author2 = author2[0]

                status = FriendRequest.is_friend(author1, author2)
                if status:
                    response['friends'] = 'YES'

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
Esempio n. 17
0
    def isViewable(self, viewer, author):

        visibility = self.visibility

        if visibility == Post.PRIVATE:
            return viewer == author
        elif visibility == Post.ANOTHER_AUTHOR:
            post_entry = VisibleToAuthor.objects.filter(visibleAuthor=viewer,
                                                        post=self)
            return post_entry.exists() or viewer == author
        elif visibility == Post.FRIENDS:
            return FriendRequest.is_friend(viewer, author) or viewer == author
        elif visibility == Post.FOAF:
            friendOfFriends = []
            friends = FriendRequest.get_friends(author)
            for friend in friends:
                friendOfFriends += FriendRequest.get_friends(friend)
            return viewer in friendOfFriends or viewer == author or FriendRequest.is_friend(
                viewer, author)
        elif visibility == Post.SERVERONLY:
            return viewer.host == author.host or viewer == author
        else:
            # Assuming that the visibility type is public
            return True
def unfriend(request):
    context = RequestContext(request)
    if request.method == 'POST':
        if request.user.is_authenticated():
            friendToUnfriend = request.POST['unfriender']
            print(friendToUnfriend)
            requester = User.objects.get(username=friendToUnfriend)
            requester2 = Author.objects.get(user=requester)
            author = Author.objects.get(user=request.user)
            print(author)
            status = FriendRequest.unfriend(author, requester2)
            if status:
                messages.info(request, 'Successfully unbefriended')
            return redirect('/author/friends', context)
        else:
            _render_error('login.html', 'Please log in.', context)
def unfriend(request):
    context = RequestContext(request)
    if request.method == 'POST':
        if request.user.is_authenticated():
            friendToUnfriend = request.POST['unfriender']
            print(friendToUnfriend)
            requester = User.objects.get(username=friendToUnfriend)
            requester2 = Author.objects.get(user=requester)
            author = Author.objects.get(user=request.user)
            print(author)
            status = FriendRequest.unfriend(author, requester2)
            if status:
                messages.info(request, 'Successfully unbefriended')
            return redirect('/author/friends', context)
        else:
            _render_error('login.html', 'Please log in.', context)
def accept_friendship(request):
    """Handles a post request to accept a friend request."""
    context = RequestContext(request)

    if request.method == 'POST':
        if request.user.is_authenticated():
            friend_requester = request.POST['friend_requester']
            requester = User.objects.get(username=friend_requester)
            requester2 = Author.objects.get(user=requester)
            author = Author.objects.get(user=request.user)
            status = FriendRequest.accept_request(requester2, author)
            print(status)
            if status:
                messages.info(request, 'Friend request has been accepted.')
            return redirect('/author/friends', context)
        else:
            _render_error('login.html', 'Please log in.', context)
Esempio n. 21
0
def is_friend(request, user_id1, user_id2):
    """Return whether the provided two users are friends.

    This responds with a JSON of the following content:

    {
        "query": "friends",
        "authors": [
            "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
            "8d919f29c12e8f97bcbbd34cc908f19ab9496989"
        ],
        # or NO
        "friends":"YES"
    }
    """
    if request.method == 'GET':
        try:
            response = {
                'query': 'friends',
                'authors': [user_id1, user_id2],
                'friends': 'NO'
            }

            author1 = Author.objects.filter(uuid=user_id1)
            author2 = Author.objects.filter(uuid=user_id2)

            if len(author1) > 0 and len(author2) > 0:
                # We're only expecting one author
                author1 = author1[0]
                author2 = author2[0]

                status = FriendRequest.is_friend(author1, author2)
                if status:
                    response['friends'] = 'YES'

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
def accept_friendship(request):
    """Handles a post request to accept a friend request."""
    context = RequestContext(request)

    if request.method == 'POST':
        if request.user.is_authenticated():
            friend_requester = request.POST['friend_requester']
            requester = User.objects.get(username=friend_requester)
            requester2 = Author.objects.get(user=requester)
            author = Author.objects.get(user=request.user)
            status = FriendRequest.accept_request(requester2, author)
            print(status)
            if status:
                messages.info(request, 'Friend request has been accepted.')
            return redirect('/author/friends', context)
        else:
            _render_error('login.html', 'Please log in.', context)
Esempio n. 23
0
def foafResponse(request, user_id):
    """
    This responds with the following JSON:
    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "friends": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "11c3783f15f7ade03430303573098f0d4d20797b",
        ]
    }
    """
    if request.method == 'POST':
        try:
            #author = Author.objects.filter(uuid=user_id)
            request_data = json.loads(request.body)
            author = request_data["author"]
            if len(author[0]) > 0:
                #uuid = request_data['author']
                friends = []

                for i in request_data["authors"]:
                    if FriendRequest.is_friend(i, author):
                        friends.append(i)

                friends = list(set(friends) & set(request_data["authors"]))
                response = {
                    'query': 'friends',
                    'author': author,
                    'friends': friends
                }

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
def friend_list(request, author):
    """Gets the user's friends."""
    context = RequestContext(request)
    print("here")
    a = []
    # get_friends_in_list(author, a)
    print("here2")
    if request.method == 'GET':
        if request.user.is_authenticated():
            friend_usernames = []
            author = Author.objects.get(user=request.user)
            friend_list = FriendRequest.get_friends(author)

            for friend in friend_list:
                friend_usernames.append(friend.user)

            context = RequestContext(request, {'friendList': friend_usernames})
        else:
            _render_error('login.html', 'Please log in.', context)
    return render_to_response('friends.html', context)
def friend_list(request, author):
    """Gets the user's friends."""
    context = RequestContext(request)
    print("here")
    a = []
   # get_friends_in_list(author, a)
    print("here2")
    if request.method == 'GET':
        if request.user.is_authenticated():
            friend_usernames = []
            author = Author.objects.get(user=request.user)
            friend_list = FriendRequest.get_friends(author)

            for friend in friend_list:
                friend_usernames.append(friend.user)

            context = RequestContext(request, {'friendList': friend_usernames})
        else:
            _render_error('login.html', 'Please log in.', context)
    return render_to_response('friends.html', context)
def foafResponse(request, user_id):
    """
    This responds with the following JSON:
    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "friends": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "11c3783f15f7ade03430303573098f0d4d20797b",
        ]
    }
    """
    if request.method == 'POST':
        try:
            #author = Author.objects.filter(uuid=user_id)
            request_data= json.loads(request.body)
            author = request_data["author"]
            if len(author[0])>0:
                #uuid = request_data['author']
                friends=[]

                for i in request_data["authors"]:
                    if FriendRequest.is_friend(i, author):
                        friends.append(i)

                friends = list(set(friends) & set(request_data["authors"]))
                response = {'query': 'friends','author': author,'friends': friends}

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
def friends(request, user_id):
    """Return whether anyone in the list is a friend

    This expects a POST request with the following content:

    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "authors": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "31cc28a8fbc05787d0470cdbd62ea0474764b0ae",
            "1af17e947f387a2d8c09a807271bd094e8eff077",
            "77cb4f546b280ea905a6fdd99977cd090613994a",
            "11c3783f15f7ade03430303573098f0d4d20797b",
            "bd9ef9619c7241112d2a2b79505f736fc8d7f43e",
            "0169a8ebf3cb3bd7f092603564873e12cce9d4c5",
            "2130905fd0de94c3379e04839cd9f6889ba2b52c",
            "b32c9e0b5fcf85f46b9ce2ba89b2068b57d4641b",
            "fe45075b93d06c833bb25d5a6dfe669cfde3f99d",
            "e28e59a9612c369717f66f53f3e014b341857601",
            "b36e52d6aaee9285220f94fc321407a44e4dc622",
            "584a9739ea459ce4aae5a88827d970196fb27769",
            "96b3b5a70cd9591c73760bd8669aa5bd7cc689c5",
            "6465678d0a409b96829fd64d0894132966e97eee",
            "695c780ea2815bc94c54782f5046dfa4e325f875",
            "8743f7511a1a569e4e9dacbb25e27395629ba5c0",
            "539b65f2d76d0327dc45bf6354cda535d6f8ed02",
            "c55670261253c5ce25e22b47a34629dd15e819d4"
        ]
    }

    This responds with the following JSON:
    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "friends": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "11c3783f15f7ade03430303573098f0d4d20797b",
        ]
    }
    """
    if request.method == 'POST':
        try:
            request_data = json.loads(request.body)

            uuid = request_data['author']
            author = Author.objects.filter(uuid=uuid)

            if len(author) > 0:
                # We're only expecting one author
                author = author[0]

                friends = FriendRequest.get_friends(author)
                uuids = [friend.uuid for friend in friends]
                friends = list(set(uuids) & set(request_data['authors']))

                response = {
                    'query': 'friends',
                    'author': author.uuid,
                    'friends': friends
                }

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
Esempio n. 28
0
def friend_request(request):
    """Makes a friend request.

    This expects a POST request with the following JSON as the content:

    {
        "query": "friendrequest",
        "author": {
            "id": "8d919f29c12e8f97bcbbd34cc908f19ab9496989",
            "host": "http://127.0.0.1:5454/",
            "displayname": "Greg"
        },
        "friend": {
            "id":"9de17f29c12e8f97bcbbd34cc908f1baba40658e",
            "host":"http://127.0.0.1:5454/",
            "displayname":"Lara",
            "url":"http://127.0.0.1:5454/author/
                   9de17f29c12e8f97bcbbd34cc908f1baba40658e"
        }
    }

    If all is well, this responds with a 200 OK.
    """
    if request.method == 'POST':
        try:
            try:
                request_data = json.loads(request.body)

                uuid_author = request_data['author']['id']
                uuid_friend = request_data['friend']['id']
                host_author = request_data['author']['host']
                host_friend = request_data['friend']['host']
                display_author = request_data['author']['displayname']
            except Exception as e:
                return HttpResponse('Bad JSON format: %s' % e.message,
                                    content_type='text/plain',
                                    status=400)

            author = Author.objects.filter(uuid=uuid_author)
            friend = Author.objects.filter(uuid=uuid_friend)

            if len(friend) == 0:
                return HttpResponse('The friend uuid must exist on our server',
                                    content_type='text/plain',
                                    status=400)

            if len(author) == 0:
                # We need to create this author, since it doesn't currently
                # exist.
                try:
                    author = author_utils.createRemoteUser(
                        displayName=display_author,
                        host=host_author,
                        uuid=uuid_author)
                except Exception as e:
                    return HttpResponse(e.message,
                                        content_type='text/plain',
                                        status=500)

            author = author[0]
            friend = friend[0]

            if friend.host != LOCAL_HOST:
                return HttpResponse('The friend must be a user on our server',
                                    content_type='text/plain',
                                    status=400)

            if FriendRequest.make_request(author, friend):
                return HttpResponse(status=200)
            else:
                return HttpResponse(
                    'Could not make friend request for '
                    'author %s at %s and friend %s at %s. '
                    'The friend request has already been '
                    'made.' %
                    (uuid_author, host_author, uuid_friend, host_friend),
                    content_type='text/plain',
                    status=500)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
def search(request):
    """Returns a list of authors.

    The returned list of authors contains their username, first_name,
    and last_name.
    """
    context = RequestContext(request)

    if request.method == 'POST':
        search_value = request.POST['searchValue']

        author_info = []

        if search_value == '*' or search_value is None:
            users = User.objects.all()
        else:
            # query all values containing search results
            users = User.objects.filter(
                Q(username__contains=search_value) & ~Q(username=request.user))

        results = 0
        # setting each author search information
        for user in users:
            results += 1
            try:
                friend = False
                sent = False
                received = False
                sent = False
                follow = False
                sentList = []
                receivedList = []
                rUser = Author.objects.get(user=request.user)
                author = Author.objects.get(user=user)
                friend = FriendRequest.is_friend(rUser, author)
                follow = FriendRequest.is_following(rUser, author)
                sentList = FriendRequest.sent_requests(rUser)
                if sentList:
                    if author in sentList:
                        sent = True
                receivedList = FriendRequest.received_requests(rUser)
                if receivedList:
                    if author in receivedList:
                        received = True
                user_info = {
                    "displayname": author.get_username(),
                    "userName": author.user.username,
                    "userID": author.get_uuid(),
                    "host": author.get_host(),
                    "friend": friend,
                    "sent": sent,
                    "received": received,
                    "follow": follow
                }

                author_info.append(user_info)
            except:
                pass
        print("context")
        context = RequestContext(
            request, {
                'searchValue': search_value,
                'authorInfo': author_info,
                'results': results
            })

    return render_to_response('searchResults.html', context)
def friend_request(request):
    """Makes a friend request.

    This expects a POST request with the following JSON as the content:

    {
        "query": "friendrequest",
        "author": {
            "id": "8d919f29c12e8f97bcbbd34cc908f19ab9496989",
            "host": "http://127.0.0.1:5454/",
            "displayname": "Greg"
        },
        "friend": {
            "id":"9de17f29c12e8f97bcbbd34cc908f1baba40658e",
            "host":"http://127.0.0.1:5454/",
            "displayname":"Lara",
            "url":"http://127.0.0.1:5454/author/
                   9de17f29c12e8f97bcbbd34cc908f1baba40658e"
        }
    }

    If all is well, this responds with a 200 OK.
    """
    if request.method == 'POST':
        try:
            try:
                request_data = json.loads(request.body)

                uuid_author = request_data['author']['id']
                uuid_friend = request_data['friend']['id']
                host_author = request_data['author']['host']
                host_friend = request_data['friend']['host']
                display_author = request_data['author']['displayname']
            except Exception as e:
                return HttpResponse('Bad JSON format: %s' % e.message,
                                    content_type='text/plain',
                                    status=400)

            author = Author.objects.filter(uuid=uuid_author)
            friend = Author.objects.filter(uuid=uuid_friend)

            if len(friend) == 0:
                return HttpResponse('The friend uuid must exist on our server',
                                    content_type='text/plain',
                                    status=400)

            if len(author) == 0:
                # We need to create this author, since it doesn't currently
                # exist.
                try:
                    author = author_utils.createRemoteUser(displayName=display_author,
                                                           host=host_author,
                                                           uuid=uuid_author)
                except Exception as e:
                    return HttpResponse(e.message,
                                        content_type='text/plain',
                                        status=500)

            author = author[0]
            friend = friend[0]

            if friend.host != LOCAL_HOST:
                return HttpResponse('The friend must be a user on our server',
                                    content_type='text/plain',
                                    status=400)

            if FriendRequest.make_request(author, friend):
                return HttpResponse(status=200)
            else:
                return HttpResponse('Could not make friend request for '
                                    'author %s at %s and friend %s at %s. '
                                    'The friend request has already been '
                                    'made.'
                                    % (uuid_author, host_author,
                                       uuid_friend, host_friend),
                                    content_type='text/plain',
                                    status=500)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
Esempio n. 31
0
def friends(request, user_id):
    """Return whether anyone in the list is a friend

    This expects a POST request with the following content:

    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "authors": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "31cc28a8fbc05787d0470cdbd62ea0474764b0ae",
            "1af17e947f387a2d8c09a807271bd094e8eff077",
            "77cb4f546b280ea905a6fdd99977cd090613994a",
            "11c3783f15f7ade03430303573098f0d4d20797b",
            "bd9ef9619c7241112d2a2b79505f736fc8d7f43e",
            "0169a8ebf3cb3bd7f092603564873e12cce9d4c5",
            "2130905fd0de94c3379e04839cd9f6889ba2b52c",
            "b32c9e0b5fcf85f46b9ce2ba89b2068b57d4641b",
            "fe45075b93d06c833bb25d5a6dfe669cfde3f99d",
            "e28e59a9612c369717f66f53f3e014b341857601",
            "b36e52d6aaee9285220f94fc321407a44e4dc622",
            "584a9739ea459ce4aae5a88827d970196fb27769",
            "96b3b5a70cd9591c73760bd8669aa5bd7cc689c5",
            "6465678d0a409b96829fd64d0894132966e97eee",
            "695c780ea2815bc94c54782f5046dfa4e325f875",
            "8743f7511a1a569e4e9dacbb25e27395629ba5c0",
            "539b65f2d76d0327dc45bf6354cda535d6f8ed02",
            "c55670261253c5ce25e22b47a34629dd15e819d4"
        ]
    }

    This responds with the following JSON:
    {
        "query": "friends",
        "author": "9de17f29c12e8f97bcbbd34cc908f1baba40658e",
        "friends": [
            "7deee0684811f22b384ccb5991b2ca7e78abacde",
            "11c3783f15f7ade03430303573098f0d4d20797b",
        ]
    }
    """
    if request.method == 'POST':
        try:
            request_data = json.loads(request.body)

            uuid = request_data['author']
            author = Author.objects.filter(uuid=uuid)

            if len(author) > 0:
                # We're only expecting one author
                author = author[0]

                friends = FriendRequest.get_friends(author)
                uuids = [friend.uuid for friend in friends]
                friends = list(set(uuids) & set(request_data['authors']))

                response = {
                    'query': 'friends',
                    'author': author.uuid,
                    'friends': friends
                }

                return HttpResponse(json.dumps(response),
                                    content_type='application/json',
                                    status=200)
            else:
                return HttpResponse(status=404)
        except Exception as e:
            return HttpResponse(e.message,
                                content_type='text/plain',
                                status=500)
    else:
        return HttpResponse(status=405)
def search(request):
    """Returns a list of authors.

    The returned list of authors contains their username, first_name,
    and last_name.
    """
    context = RequestContext(request)

    if request.method == 'POST':
        search_value = request.POST['searchValue']

        author_info = []

        if search_value == '*' or search_value is None:
            users = User.objects.all()
        else:
            # query all values containing search results
            users = User.objects.filter(Q(username__contains=search_value) &
                                        ~Q(username=request.user))

        results = 0
        # setting each author search information
        for user in users:
            results += 1
            try:
                friend = False
                sent = False
                received = False
                sent = False
                follow = False
                sentList = []
                receivedList = []
                rUser = Author.objects.get(user = request.user)
                author = Author.objects.get(user=user)
                friend = FriendRequest.is_friend(rUser, author)
                follow = FriendRequest.is_following(rUser, author)
                sentList = FriendRequest.sent_requests(rUser)
                if sentList:
                    if author in sentList:
                        sent = True
                receivedList = FriendRequest.received_requests(rUser)
                if receivedList:
                    if author in receivedList:
                        received = True
                user_info = {"displayname": author.get_username(),
                             "userName": author.user.username,
                             "userID": author.get_uuid(),
                             "host": author.get_host(),
                             "friend": friend,
                             "sent": sent,
                             "received": received,
                             "follow": follow}

                author_info.append(user_info)
            except:
                pass
        print("context")
        context = RequestContext(request, {'searchValue': search_value,
                                           'authorInfo': author_info,
                                           'results': results})

    return render_to_response('searchResults.html', context)