def getPosts(request): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id try: data = Friend.objects.filter(Q(user_a=person_id) | Q(user_b=person_id)) friends = [entry.user_a if entry.user_a is not person_id else entry.user_b for entry in data] friends.append(person_id) data = Posts.objects.filter(person_id__in=friends).order_by('pk').values() posts_final = [] for post in data: post_by = PersonSerializer(Person.objects.get(pk=post['person_id'])).data posts_final.append({**PostsSerializer(Posts.objects.get(pk=post['id'])).data,"person":post_by}) if posts_final: return Response(data=posts_final,status=status.HTTP_200_OK) else: return Response(errorResponse("No posts found!"),status=status.HTTP_404_NOT_FOUND) except Friend.DoesNotExist: data = Posts.objects.filter(person_id=person_id) postsSerializer = PostsSerializer(data, many=True) if postsSerializer.data: return Response(data=postsSerializer.data,status=status.HTTP_200_OK) else: return Response(errorResponse("No posts found!"),status=status.HTTP_404_NOT_FOUND)
def getPersonID(request): try: token = request.headers['Authorization'].split()[-1] except [KeyError, Token.DoesNotExist]: return Response(errorResponse(UNAUTHORIZED),status=status.HTTP_401_UNAUTHORIZED) try: return Token.objects.get(token=token).account except Token.DoesNotExist: return Response(errorResponse(INVALID_TOKEN),status=status.HTTP_400_BAD_REQUEST)
def getAuthor(post): # getAuthor returns a person model try: post_author_id = Posts.objects.get(id=post).person_id try: return Person.objects.get(id=post_author_id) except Person.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST) except Posts.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def getPost(post_key): try: data = Posts.objects.get(pk=post_key) post_by = PersonSerializer(Person.objects.get(pk=data.person_id)).data return Response(data={**PostsSerializer(Posts.objects.get(pk=data.id)).data,"person":post_by},status=status.HTTP_200_OK) except Posts.DoesNotExist: return Response(errorResponse("Post not found!"),status=status.HTTP_404_NOT_FOUND)
def getFriendSuggestions(request): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id # We have some friends friends = Friend.objects.filter(Q(user_a=person_id) | Q(user_b=person_id)) # Let's add our current friends id's in list to exclude from suggestions # and then excluding myself too friends_ids = [a.user_b if a.user_a is person_id else a.user_a for a in friends] friends_ids.append(person_id) # Apend people we have already sent friend request into friends_ids to avoid those suggestions try: freqs = FriendRequest.objects.filter(Q(from_user=person_id) | Q(to_user=person_id)) for fr in freqs: if fr.to_user == person_id: friends_ids.append(fr.from_user) else: friends_ids.append(fr.to_user) except FriendRequest.DoesNotExist: pass # limiting the suggestions to 25 to prevent sending whole database persons = list(Person.objects.filter(~Q(id__in=friends_ids))[:25]) if len(persons) > 0: # getting 10 random ids from people we are not friends with # and then serializing them and returning them random_persons_ids = [a.id for a in random.sample(persons,min(len(persons), 10))] random_persons = Person.objects.filter(id__in=random_persons_ids) persons_dict = [PersonSerializer(person).data for person in random_persons] return Response(data=dict(friend_suggestions=persons_dict), status=status.HTTP_200_OK) return Response(errorResponse("No friend suggestions."),status=status.HTTP_204_NO_CONTENT)
def getFriends(request): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id try: data = Friend.objects.filter(Q(user_a=person_id) | Q(user_b=person_id)) friends = [entry.user_a if entry.user_a is not person_id else entry.user_b for entry in data] if friends: persons = Person.objects.filter(id__in=friends) persons_dict = [PersonSerializer(person).data for person in persons] return Response(data=persons_dict, status=status.HTTP_200_OK) return Response(data=errorResponse("No friends found!"),status=status.HTTP_404_NOT_FOUND) except Friend.DoesNotExist: return Response(data=errorResponse("No friends found!"),status=status.HTTP_404_NOT_FOUND)
def __personPosts(pk): person_id = pk data = Posts.objects.filter(person_id=person_id) postsSerializer = PostsSerializer(data, many=True) if postsSerializer.data: return Response(data=postsSerializer.data,status=status.HTTP_200_OK) else: return Response(errorResponse("No posts found!"),status=status.HTTP_404_NOT_FOUND)
def sendFriendRequest(request): if request.method == 'POST': # REQUIRED: 'to_user' field in request person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id req_dict = request.data # Can't send oneself the friend request if req_dict['to_user'] == person_id: return Response(errorResponse("Cannot send friend request to yourself."),status=status.HTTP_400_BAD_REQUEST) # Check if person we are sending request to exist if not Person.objects.filter(pk=req_dict['to_user']).exists(): return Response(errorResponse("Person does not exist."),status=status.HTTP_400_BAD_REQUEST) # Check if a friend request from a same use to same user has already been made try: FriendRequest.objects.get(Q(from_user=person_id) & Q(to_user=req_dict['to_user'])) return Response(errorResponse("Friend request is already sent."),status=status.HTTP_400_BAD_REQUEST) except FriendRequest.DoesNotExist: # Check if these people are already friends try: Friend.objects.get(Q(user_a=person_id) & Q(user_b=req_dict['to_user']) | Q(user_a=req_dict['to_user']) & Q(user_b=person_id)) return Response(errorResponse("Already friends."),status=status.HTTP_400_BAD_REQUEST) except Friend.DoesNotExist: req_dict['from_user'] = person_id req_dict['since'] = datetime.now().timestamp() friendRequestSerializer = FriendRequestSerializer(data=req_dict) if friendRequestSerializer.is_valid(): friendRequestSerializer.save() # make a notification to send notification = Notification( noti=3, person_for=req_dict['to_user'], person_from=req_dict['from_user'], about=0, created=datetime.now().timestamp() ) notification.save() return Response(data=friendRequestSerializer.data,status=status.HTTP_201_CREATED) else: return Response(friendRequestSerializer.errors,status=status.HTTP_400_BAD_REQUEST)
def postOperations(request, pk): if request.method == 'GET': return getPost(pk) elif request.method == 'PUT': return likePost(request, pk) elif request.method == 'POST': return editPost(request, pk) elif request.method == 'DELETE': return deletePost(request, pk) return Response(errorResponse("unable to complete request"),status=status.HTTP_500_INTERNAL_SERVER_ERROR)
def deleteFriendRequest(request,pk): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id friend_request = FriendRequest.objects.get(pk=pk) if (friend_request.from_user == person_id or friend_request.to_user == person_id): friend_request.delete() return Response(data=json.loads('{"action": "success"}'),status=status.HTTP_200_OK) return Response(errorResponse("Bad Request."),status=status.HTTP_400_BAD_REQUEST)
def postNewComment(request, post_id): person = getPersonID(request) if type(person) is Response: return person post = getPost(post_id) if type(post) is Response: return post time_stamp = datetime.now().timestamp() # Filtering if post.person_id != person: # post author themselves are not commenting on their post if isFriends(post.person_id, person) == False: # post author and person trying to comment are not friends # if they are friends then we let the commentator post a comment return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST) commentSerializer = CommentSerializer( data={ 'post_id': post.id, 'person_id': person, 'comment_text': request.data['comment_text'], 'comment_parent': request.data['comment_parent'], 'created': time_stamp, 'updated': time_stamp }) if commentSerializer.is_valid(): commentSerializer.save() try: # make a notification to send p_for = post.person_id if request.data[ 'comment_parent'] == "0" else Comment.objects.get( pk=int(request.data['comment_parent'])).person_id if p_for != person: notification = Notification( noti=1 if request.data['comment_parent'] == "0" else 5, person_for=p_for, person_from=person, about=post.id, created=datetime.now().timestamp()) notification.save() except Comment.DoesNotExist: print("errored") pass return Response(data={ **commentSerializer.data, 'person': PersonSerializer(Person.objects.get(id=person)).data }, status=status.HTTP_201_CREATED) return Response(commentSerializer.errors, status=status.HTTP_400_BAD_REQUEST)
def deletePost(request, post_key): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id post = Posts.objects.get(pk=post_key) if post.person_id == person_id: post.delete() Comment.objects.filter(post_id=post.id).delete() return Response(json.loads('{"action":"success"}'),status=status.HTTP_200_OK) else: return Response(errorResponse(UNAUTHORIZED),status=status.HTTP_401_UNAUTHORIZED)
def actionsComment(request, post_id, pk): person_id = getPersonID(request) if type(person_id) is Response: return person_id if request.method == 'PUT': # Liking a comment comment = Comment.objects.get(pk=pk) if comment.comment_likes: if person_id in comment.comment_likes['persons']: comment.comment_likes['persons'].remove(person_id) else: comment.comment_likes['persons'].append(person_id) else: comment.comment_likes = dict(persons=[(person_id)]) comment.save() # make a notification to send if comment.person_id != person_id: notification = Notification(noti=2, person_for=comment.person_id, person_from=person_id, about=comment.post_id, created=datetime.now().timestamp()) notification.save() return Response(json.loads('{"action":"success"}'), status=status.HTTP_200_OK) elif request.method == 'DELETE': try: comment = Comment.objects.get(pk=pk) if comment.person_id == person_id: comment.delete() return Response(json.loads('{"action":"success"}'), status=status.HTTP_200_OK) except Comment.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST) return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def acceptFriendRequest(request): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id print(request.data) try: friend_request = FriendRequest.objects.get(id=request.data['id']) # Check if person responding to the request is the person request is sent to if friend_request.to_user == person_id: friendSerilizer = FriendSerializer(data= {'user_a':friend_request.from_user, 'user_b': person_id, 'since':datetime.now().timestamp()}) if friendSerilizer.is_valid(): friendSerilizer.save() # make a notification to send notification = Notification( noti=4, person_for=friend_request.from_user, person_from=person_id, about=0, created=datetime.now().timestamp() ) notification.save() friend_request.delete() # Let's check if users had cross friend requested each other # in that case we need to delete the other request as well res = Response(data=friendSerilizer.data,status=status.HTTP_200_OK) try: duplicate_request= FriendRequest.objects.get(from_user=person_id) duplicate_request.delete() except FriendRequest.DoesNotExist: return res return res return Response(errorResponse("Unable to accept friend request."),status=status.HTTP_400_BAD_REQUEST) except FriendRequest.DoesNotExist: return Response(errorResponse("Friend request is invalid."),status=status.HTTP_400_BAD_REQUEST)
def markAsSeen(request, pk): person_id = getPersonID(request) if type(person_id) is Response: return person_id try: notification = Notification.objects.get(pk=pk) notification.seen = 1 notification.save() return Response(json.loads('{"action":"success"}'), status=status.HTTP_200_OK) except Notification.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def editPost(request, post_key): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id post = Posts.objects.get(pk=post_key) if post.person == person_id: post.post_text = request.data['post_text'] post.post_image = request.data['post_image'] post.updated = datetime.now(tz=pytz.utc) post.save() return Response(PostsSerializer(post).data,status=status.HTTP_200_OK) else: return Response(errorResponse(UNAUTHORIZED),status=status.HTTP_401_UNAUTHORIZED)
def getFriendRequests(request): person_id = getPersonID(request) # If person_id type is Response that means we have errored if type(person_id) is Response: return person_id data = FriendRequest.objects.filter(to_user=person_id) friendrequests = [] if data: for fr in data: # Check if person exist or if account id deleted try: persons = Person.objects.get(id=fr.from_user) personSerializer = PersonSerializer(persons) friendrequests.append({**personSerializer.data, **{'from_user': fr.from_user, 'to_user': fr.to_user, 'request_id': fr.id,'since':fr.since}}) except Person.DoesNotExist: FriendRequest.objects.get(pk=fr.id).delete() return Response(data=dict(requests=friendrequests), status=status.HTTP_200_OK) return Response(data=errorResponse("No friend requests!"),status=status.HTTP_200_OK)
def getPostComments(request, post): person = getPersonID(request) if type(person) is Response: return person author = getAuthor(post) if type(author) is Response: return author if isFriends(author.id, person) or author.id == person: # Person can only retrieve comments if they are friends with author or author themselves result = [{ **comment, 'person': PersonSerializer(Person.objects.get(id=comment['person_id'])).data } for comment in Comment.objects.filter( post_id=post).order_by('pk').values()] return Response({"comments": result}, status=status.HTTP_200_OK) return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)
def getPost(post): try: return Posts.objects.get(id=post) except Posts.DoesNotExist: return Response(errorResponse(INVALID_REQUEST), status=status.HTTP_400_BAD_REQUEST)