def get_all_user(self, request, *args, **kwargs): """ Get local and remote users except request user. """ update_db(True, False) queryset = User.objects.filter(is_superuser=0).exclude( id__in=get_nodes_user_ids()) if not request.user.is_anonymous: queryset = queryset.exclude(id=request.user.id) serializer = AuthorSerializer(queryset, many=True) return Response(serializer.data, status=status.HTTP_200_OK)
def visible_posts(self, request, *args, **kwargs): """ http://service/author/posts (posts that are visible to the currently authenticated user) """ if (not request.user.is_anonymous and request.user.id not in get_nodes_user_ids()): update_db(True, True, request.user) filtered_posts = get_visible_posts(Post.objects.filter(unlisted=False), self.request.user) paged_posts = self.paginate_queryset( filtered_posts.order_by("-published")) serializer = PostSerializer(paged_posts, many=True) return self.get_paginated_response(serializer.data)
def get_friends_of(self, request, *args, **kwargs): """ get all friends of a user ask a service GET http://service/author/<authorid>/friends/ """ response_body = {"query": "friends", "authors": []} author_id = kwargs["AUTHOR_ID"] author = User.objects.filter(id=author_id).first() if not author: response_body["error"] = ("author does not exist.", ) return Response(response_body, status=status.HTTP_404_NOT_FOUND) else: update_db(True, False, author) friend_ids = Friend.objects.filter(f1Id=author.id, status="A").values_list("f2Id", flat=True) friends = User.objects.filter(id__in=list(friend_ids)) for user in friends: response_body["authors"].append(f"{user.host}author/{user.id}") return Response(response_body, status=status.HTTP_200_OK)
def create(self, request, *args, **kwargs): try: update_db(True, False) author_data = request.data["author"] author_data["id"] = author_data["id"].split("/")[-1] friend_data = request.data["friend"] friend_data["id"] = friend_data["id"].split("/")[-1] author = None friend = None node = Node.objects.filter(user=self.request.user).first() if node: # request from remote node if node.host == REMOTE_HOST1: author = User.objects.filter( non_uuid_id=author_data["id"]).first() else: author = get_user(author_data["id"]) friend = User.objects.filter(id=friend_data["id"]).first() if not author or author.host != node.host: raise Exception("Author does not exist") if not friend or friend.host != DEFAULT_HOST: raise Exception("Friend does not exist") else: # request from local user author = User.objects.filter(id=author_data["id"]).first() friend = User.objects.filter(id=friend_data["id"]).first() if not author: raise Exception("Author does not exist") if not friend: raise Exception("Friend does not exist") if author != self.request.user: return Response(status=status.HTTP_403_FORBIDDEN) if author == friend: raise Exception("Author and Friend can not be the same user") # check if author and friend are already friends if Friend.objects.filter(f1Id=author, f2Id=friend, status="A").exists(): return Response( {"Error": "'author' and 'friend' are already friends"}, status=status.HTTP_409_CONFLICT, ) # check if author already sent friend request to friend if Friend.objects.filter(f1Id=author, f2Id=friend, status="U", isCopy=False).exists(): return Response( { "Error": "'author' has already sent the friend request to 'friend'" }, status=status.HTTP_409_CONFLICT, ) data = {"status": "U"} if Friend.objects.filter(f1Id=friend, f2Id=author, status="U", isCopy=False).exists(): # they both sent request to each other, automatically accept data = {"status": "A"} else: if not node and friend.host != DEFAULT_HOST: # request is sending from local user to remote user if not send_friend_request(author, friend): raise Exception("Bad Request") serializer1 = FriendSerializer(data=data) serializer2 = FriendSerializer(data=data) if serializer1.is_valid( raise_exception=True) and serializer2.is_valid( raise_exception=True): serializer1.save(f1Id=author, f2Id=friend, isCopy=False) serializer2.save(f1Id=friend, f2Id=author, isCopy=True) return Response(status=status.HTTP_201_CREATED) except Exception as e: response_body = {"error": str(e)} return Response(data=response_body, status=status.HTTP_400_BAD_REQUEST)
def post_comments(self, request, *args, **kwargs): """ # POST to http://service/posts/{POST_ID}/comments """ response_data = { "query": "addComment", "success": "", "message": "", } try: post_id = kwargs["POST_ID"] post = Post.objects.filter(id=post_id).first() if not post: raise Exception("Not Found") except: response_data["success"] = "false" response_data["message"] = "Post does not exist" return Response(response_data, status=status.HTTP_404_NOT_FOUND) else: try: if is_post_visible_to(post, request.user): try: comment = request.data["comment"].copy() if Comment.objects.filter(id=comment["id"]).exists(): raise Exception("Comment id already exists.") author_data = comment.pop("author") author_data["id"] = author_data["id"].split("/")[-1] update_db(True, False) author = None if author_data["host"] == REMOTE_HOST1: author = User.objects.filter( non_uuid_id=int(author_data["id"])).first() else: author = User.objects.filter( id=author_data["id"]).first() if not author: raise Exception("Author not found") serializer = CommentSerializer(data=comment) if serializer.is_valid(): if post.origin == DEFAULT_HOST: serializer.save(author=author, post=post) response_data["success"] = "true" response_data["message"] = "Comment Added" return Response(response_data, status=status.HTTP_201_CREATED) else: # send request if send_remote_comments(comment, post, author): response_data["success"] = "true" response_data["message"] = "Comment Added" return Response( response_data, status=status.HTTP_201_CREATED) else: raise Exception("Remote server failed.") else: raise Exception("Bad request body") except Exception as e: response_data["success"] = "false" response_data[ "message"] = f"{str(type(e).__name__)}:{str(e)}" return Response(response_data, status=status.HTTP_400_BAD_REQUEST) else: response_data["success"] = "false" response_data["message"] = "Comment not allowed" return Response(response_data, status=status.HTTP_403_FORBIDDEN) except Exception as e: utils.print_warning(f"{type(e).__name__} {str(e)}")