def get(self, request, post_id, comment_id=None, format=None): ''' delete a specified comment by its comment_id ''' try: post = Post.objects.filter(id=post_id) if not post.exists(): return HttpResponseNotFound("Post Not Found") post = Post.objects.get(id=post_id) if not checkVisibility(request.user.url, post): return HttpResponseForbidden("You don't have visibility.") comment = Comment.objects.filter(id=comment_id) if not comment.exists(): return HttpResponseNotFound("Comment Not Found") comment = Comment.objects.get(id=comment_id) if request.user.has_perm('owner of comment', comment): comment.delete() return HttpResponseRedirect( reverse('posting:view post details', args=(post_id, )), {}) else: return HttpResponseForbidden( "You must be the owner of this comment.") except Exception as e: return HttpResponseServerError(e)
def getVisiblePosts(requester_url, author_url=None, IsShareImg=False): ''' To a list of visible posts. parameter: requster: an author url of whom the requst on behalf. author: an local author url return: result: a list of visble of posts. ''' bannedType = "_" if IsShareImg else "image" result = [] if author_url: author = Author.objects.get(url=author_url) posts = Post.objects.filter( Q(author=author, unlisted=False) & ~Q(contentType__contains=bannedType)).order_by('-published') else: posts = Post.objects.filter( Q(unlisted=False) & ~Q(contentType__contains=bannedType)).order_by('-published') #Append post to result according to visibility and user's status for post in posts: if checkVisibility(requester_url, post): result.append(post) return result
def post(self, request, post_id, comment_id=None, format=None): """ Create a comment to a given Post Id. """ try: post_host = request.POST.get('post_origin', None) if post_host: post_host = post_host.split('posts/')[0] #Target post on remote server if post_host and not post_host == settings.HOSTNAME: nodes = ServerNode.objects.filter( host_url__startswith=post_host) if nodes.exists(): post, _ = getRemotePost(post_id, nodes, request.user.url) if not post: friends = [] friend_objs = getAllFriends(request.user.id) for obj in friend_objs: friends.append(obj.url) node = nodes[0] post, _ = getRemoteFOAFPost(node, post_id, request.user, friends) if post: remote_comment = Comment( comment=request.POST['comment'], author=request.user, post=post, contentType=request.POST['contentType']) if postRemotePostComment(remote_comment, request.user.url): return HttpResponseRedirect( reverse('posting:view post details', args=(post_id, )), {}) else: return HttpResponseForbidden( "Remote comment failed.") return HttpResponseNotFound("Post Not Found") #Target post on local server else: post = Post.objects.filter(id=post_id) if not post.exists(): return HttpResponseNotFound("Post not found.") post = post[0] if not checkVisibility(request.user.url, post): return HttpResponseForbidden("You don't have visibility.") serializer = CommentSerializer(data=request.POST, context={ 'author': request.user, 'post': post }) if serializer.is_valid(raise_exception=True): serializer.save() return HttpResponseRedirect( reverse('posting:view post details', args=(post_id, )), {}) else: return Response("Comment save failed. Invalid data") except Exception as e: return HttpResponseServerError(e)
def getVisiblePosts(requester, author=None): result = set() #the current user hasn't login yet, show some random public posts if requester.is_anonymous or requester.host != settings.HOSTNAME: if author: return list( Post.objects.filter(author=author, visibility='PUBLIC', unlisted=False).order_by('-published')) else: return list( Post.objects.filter(visibility='PUBLIC', unlisted=False).order_by('-published')) #only check onef author's posts or all posts remote_visibile_posts = set() if author: #Get all remote visibile post of author node = ServerNode.objects.filter(host_url__startswith=author.host) node = node[0] if node.exists() else None if node: remote_visibile_posts = getRemoteAuthorPosts( author.id, requester.url, node) local_posts = Post.objects.filter( author=author, unlisted=False).order_by('-published') else: #Get all remote visibile post nodes = ServerNode.objects.all() remote_visibile_posts = getRemoteVisiblePost(nodes, requester.url) local_posts = Post.objects.filter( unlisted=False).order_by('-published') #Get all local visibile post for post in local_posts: if checkVisibility(requester.url, post): result.add(post) if author == requester: unlisted_posts = Post.objects.filter(author=author, unlisted=True) for post in unlisted_posts: result.add(post) result.update(remote_visibile_posts) return list(result)
def get(self, request, post_id, format=None): """ Return a detail of post by given Post Id. """ post = Post.objects.filter(id=post_id) #Remote request if not post.exists(): nodes = ServerNode.objects.all() if nodes.exists(): post, comments = getRemotePost(post_id, nodes, request.user.url) if not post: friends_obj = getAllFriends(request.user.id) friends = [] for obj in friends_obj: friends.append(obj.url) nodes = ServerNode.objects.all() if nodes.exists(): for node in nodes: post, comments = getRemoteFOAFPost( node, post_id, request.user, friends) if post: print(post.author) break if not post: return HttpResponseNotFound("Post not found") #Local request else: post = post[0] if not checkVisibility(request.user.url, post): return HttpResponseForbidden("You don't have visibility.") comments = Comment.objects.filter(post=post) context = { 'post': post, 'comment_list': comments[:10], } return render(request, "posting/post-details.html", context)
def handle_comments(request, post_id): ''' GET: To get comments from visible posts POST: To add a comment to the visible post. ''' #Handler GET requests if request.method == 'GET': try: if not 'HTTP_X_USER_ID' in request.META.keys(): return HttpResponseForbidden( "Who's requesting posts? Put author's url in request headers under 'x-user-id'" ) requester_url = request.META.get('HTTP_X_USER_ID') #Get the post specified by request post = Post.objects.filter(id=post_id) if not post.exists(): return HttpResponseNotFound("Post Not Found.") post = post[0] #Reject request if anonymous user or user does not have visibility if not checkVisibility(requester_url, post): return HttpResponseForbidden(b"You dont have visibility.") #Valid request -> get comments data and return in response paginator = CustomPagination() comments = Comment.objects.filter(post=post).order_by('-published') try: comments = paginator.paginate_queryset(comments, request) except Exception as e: return HttpResponseNotFound(e) serializer = CommentSerializer(comments, many=True) response = paginator.get_paginated_response(query="comments", data_name='comments', data=serializer.data) return response #Server error when handling reqeust except Exception as e: return HttpResponseServerError(e) #Handler POST requests (add a comment to the post) elif request.method == 'POST': #Initialize response context context = { "query": "addComment", "success": False, "message": "Comment not Allowed", } try: #Parse comment form data from request data = json.loads(request.body) if not ('post' in data.keys() and 'comment' in data.keys() and 'author' in data['comment'].keys()): return Response(context, status=403) post_info = data['post'] comment_info = data['comment'] author_info = comment_info['author'] author_info['id'] = author_info['id'].split('author/')[-1] author_info['email'] = "{}@remote_user.com".format( author_info['id']) #Get target post object on local server post_id = post_info.split('posts/')[-1] post = Post.objects.filter(id=post_id) if not post.exists(): return Response(context, status=403) post = post[0] #Check if comment author has visibility of post requester_url = author_info['url'] #Check visibility if not checkVisibility(requester_url, post): return Response(context, status=403) #Get comment author object on local server comment_author, _ = Author.objects.get_or_create(**author_info) comment_info['author'] = comment_author comment_info['post'] = post new_comment = Comment.objects.filter(**comment_info) if new_comment.exists(): return Response(context, status=403) #Create a comment as required new_comment = Comment.objects.create(**comment_info) if new_comment: #return success response context['success'] = True context['message'] = "Comment Added" return Response(context, status=200) #comment create failed. else: return Response(context, status=403) #Server error when handling request except Exception as e: return HttpResponseServerError(e) #Method not allowed else: return HttpResponseNotAllowed()
def view_single_post(request, post_id): ''' GET: To get a single visiable post by given post id ''' if request.method == 'GET': try: if not 'HTTP_X_USER_ID' in request.META.keys(): return HttpResponseForbidden( "Who's requesting posts? Put author info in request headers under 'x-user-id'" ) requester_url = request.META.get('HTTP_X_USER_ID') #Get the post specified by request post = Post.objects.filter(id=post_id) if not post.exists(): return HttpResponseNotFound("Post Not Found.") post = post[0] #Case 1: User has visibility if checkVisibility(requester_url, post): serializer = PostSerializer(post) response = {} response['query'] = 'posts' #response['count'] = 1 response['post'] = serializer.data return Response(response) #Case 2: User does not have visibility else: return HttpResponseForbidden( b"You dont have visibility to this post.") #Server error when handling request except Exception as e: return HttpResponseServerError(e) #Ask for a FOAF post if request.method == 'POST': try: #Parse data from request data = json.loads(request.body) #Validate request body if not ('postid' in data.keys() and 'url' in data.keys() and 'author' in data.keys() and 'friends' in data.keys()): return Response("Invalid request data", status=403) #Get the post specified by request post = Post.objects.filter(id=data['postid']) if not post.exists(): return HttpResponseNotFound("Post Not Found.") post = post[0] if not post.visibility == "FOAF": return HttpResponseForbidden( "Please POST to this API view only for FOAF post request.") #Frist Check -> get friends of requestor A from A's server friends = data['friends'] node = ServerNode.objects.filter( host_url__startswith=data['author']['host']) if not node.exists(): return HttpResponseForbidden( "Requestor does not have visiblity of post.") node = node[0] friendsRequestor = checkRemoteFriendslist(node, data['author']['url'], friends) # friendsRequestor = friends #Second check -> get friends of post author B from B's server friendsAuthor = [] friends = getAllFriends(post.author.id) for friend in friends: friendsAuthor.append(friend.url) #Third check -> get friendslist A intersects friendslist B as common friends #check until one of these common friends' servers confirm that A is a friend. friendsInCommom = list(set(friendsAuthor) & set(friendsRequestor)) hasVisibility = False for friend_url in friendsInCommom: host = friend_url.split('author')[0] node = ServerNode.objects.filter(host_url__startswith=host) if node.exists(): node = node[0] #once it is verified via the 3 hosts -> approve request. if checkRemoteFriendship(node, friend_url, data['author']['url']): hasVisibility = True break #Case 1: User has visibility if hasVisibility: serializer = PostSerializer(post) response = {} response['query'] = 'posts' response['post'] = serializer.data return Response(response) #Case 2: User does not have visibility else: return HttpResponseForbidden( "You dont have visibility to this post.") except Exception as e: print(e) return HttpResponseServerError(e) #Method not allowed return HttpResponseNotAllowed()