Exemple #1
0
 def put(self, request, id):
     tweet = self.get_object(id)
     serialize = TweetSerializer(tweet, data=request.data)
     if serialize.is_valid():
         serialize.save()
         return Response(serialize.data)
     return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #2
0
 def post(self, request):
     request.data["created_by"] = request.user.id
     serialize = TweetSerializer(data=request.data)
     if serialize.is_valid():
         serialize.save()
         return Response(serialize.data, status=status.HTTP_201_CREATED)
     return Response(serialize.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #3
0
def tweet_action_view(request, *args, **kwargs):
    ''' The actions are: like, unlike, and retweet. ID is required'''
    # print(request.POST, request.data)
    serializer = TweetActionSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        data = serializer.validated_data
        tweet_id = data.get("id")
        action = data.get("action")
        content = data.get("content")
        qs = Tweet.objects.filter(id=tweet_id)
        if not qs.exists():
            return Response({}, status=404)
        obj = qs.first()
        if action == "like":
            obj.likes.add(request.user)
            serializer = TweetSerializer(obj)
            return Response(serializer.data, status=200)
        elif action == "unlike":
            obj.likes.remove(request.user)
            serializer = TweetSerializer(obj)
            return Response(serializer.data, status=200)
        elif action == "retweet":
            parent_obj = obj
            new_tweet = Tweet.objects.create(user=request.user,
                                             parent=parent_obj,
                                             content=content)
            serializer = TweetSerializer(new_tweet)
            return Response(serializer.data, status=201)
    return Response({"message": "Action Happened"}, status=200)
    def get_tweetsSearch(self, request, pk=None):
        user = request.user
        search = request.data['search']
        tweets = Tweet.objects.exclude(user=user.id).filter(
            content__icontains=search)
        retweets = Retweet.objects.exclude(user=user.id).filter(
            content__icontains=search)
        #Se unen los querySets
        results_list = list(chain(tweets, retweets))
        #Se filtran por fechas
        sorted_list = sorted(results_list,
                             key=lambda instance: instance.date,
                             reverse=True)
        # Build the list with items based on the FeedItemSerializer fields
        results = list()
        for entry in sorted_list:
            item_type = entry.__class__.__name__.lower()

            if isinstance(entry, Tweet):
                serializer = TweetSerializer(entry,
                                             context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(serializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    None,
                    'retweet_id':
                    None
                })
            if isinstance(entry, Retweet):
                serializer = TweetSerializer(entry.originalTweet,
                                             context={'request': request})

                retweetSerializer = RetweetSerializer(
                    entry, context={'request': request})
                userSerializer = UserSerializer(entry.user,
                                                context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(retweetSerializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    userSerializer.data,
                    'retweet_id':
                    retweetSerializer.data['id']
                })

        return (Response(results))
    def get_savedTweets(self, request, pk=None):
        user = self.get_object()
        #Se consultan los tweets y retweets de todos los usuarios en la lista
        tweets = Tweet.objects.filter(id__in=SavedTweet.objects.filter(
            user=user.id).order_by('date').values('tweet'))
        retweets = Retweet.objects.filter(id__in=SavedTweet.objects.filter(
            user=user.id).order_by('date').values('retweet'))
        #Se unen los querySets
        results_list = list(chain(tweets, retweets))
        #Se filtran por fechas
        sorted_list = sorted(results_list,
                             key=lambda instance: instance.date,
                             reverse=True)
        # Build the list with items based on the FeedItemSerializer fields
        results = list()
        for entry in sorted_list:
            item_type = entry.__class__.__name__.lower()

            if isinstance(entry, Tweet):
                serializer = TweetSerializer(entry,
                                             context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(serializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    None,
                    'retweet_id':
                    None
                })
            if isinstance(entry, Retweet):
                serializer = TweetSerializer(entry.originalTweet,
                                             context={'request': request})

                retweetSerializer = RetweetSerializer(
                    entry, context={'request': request})
                userSerializer = UserSerializer(entry.user,
                                                context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(retweetSerializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    userSerializer.data,
                    'retweet_id':
                    retweetSerializer.data['id']
                })

        return (Response(results))
Exemple #6
0
def get_tweets(query):
    r = api_request().get('https://api.twitter.com/1.1/search/tweets.json' +
                          query,
                          headers={'Authorization': 'Bearer ' + token()})

    for status in r.json().get('statuses'):
        serializer = TweetSerializer(data=parse(status))
        if serializer.is_valid():
            serializer.save()

    next_query = r.json().get('search_metadata').get('next_results')
    if next_query:
        get_tweets.delay(next_query)
Exemple #7
0
def tweet_detail_view(request, tweet_id, *args, **kwargs):
    qs = Tweet.objects.filter(id=tweet_id)
    if not qs.exists():
        return Response({}, status=404)
    obj = qs.first()
    serializer = TweetSerializer(obj)
    return Response(serializer.data, status=200)
Exemple #8
0
def tweet_detail_view(request, tweet_id, *args, **kwargs):
    query_set = Tweet.objects.filter(id=tweet_id)
    if not query_set:
        return Response({}, status=404)
    tweet = query_set.first()
    serializer = TweetSerializer(tweet)
    return Response(serializer.data, status=200)
Exemple #9
0
def tweet_action_view(request, *args, **kwargs):
    serializer = TweetActionSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        data = serializer.validated_data
        tweet_id = data.get('id')
        action = data.get('action')
        content = data.get('content')
        query_set = Tweet.objects.filter(id=tweet_id)
        if not query_set:
            return Response({}, status=404)
        tweet = query_set.first()
        if action == 'like':
            tweet.likes.add(request.user)
            status = 200
        elif action == 'unlike':
            tweet.likes.remove(request.user)
            status = 200
        elif action == 'retweet':
            tweet = Tweet.objects.create(user=request.user,
                                         parent=tweet,
                                         content=content)
            status = 201
        serializer = TweetSerializer(tweet)
        return Response(serializer.data, status=status)
    return Response({}, status=200)
 def to_representation(self, instance):
     data = super().to_representation(instance)
     request = self.context.get("request")
     data['originalTweet'] = TweetSerializer(
         Tweet.objects.get(pk=data['originalTweet']),context={'request':request}).data
     data['user'] = UserSerializer(
         User.objects.get(pk=data['user']),context={'request':request}).data
     return data
Exemple #11
0
def bookmakrs(request):
    bookmakrs = []
    for v in request.data['user_bookmarks']:
        tweet = Tweet.objects.get(id=v['tweet_id'])
        bookmakrs.append(tweet)
    print(bookmakrs)
    serializer = TweetSerializer(bookmakrs, many=True)
    return Response(serializer.data)
Exemple #12
0
def get_paginated_queryset_response(qs, request):
    paginator = PageNumberPagination()
    paginator.page_size = 20
    paginated_qs = paginator.paginate_queryset(qs, request)
    serializer = TweetSerializer(paginated_qs,
                                 many=True,
                                 context={"request": request})
    return paginator.get_paginated_response(
        serializer.data)  # Response( serializer.data, status=200)
Exemple #13
0
 def to_representation(self, instance):
     data = super().to_representation(instance)
     data['user'] = UserSerializer(User.objects.get(pk=data['user'])).data
     if (data['tweet']):
         data['tweet'] = TweetSerializer(
             Tweet.objects.get(pk=data['tweet'])).data
     if (data['retweet']):
         data['retweet'] = RetweetSerializer(
             Retweet.objects.get(pk=data['retweet'])).data
     return data
Exemple #14
0
    def test_get_all_tweet(self):
        """Test retrieve all tweets created till now"""
        Tweet.objects.create(**self.tweet_data)
        Tweet.objects.create(user=self.user, context='another tweet')
        response = self.client.get(TWEET_URL)
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        tweets = Tweet.objects.all()
        serializer = TweetSerializer(tweets, many=True)
        self.assertEqual(serializer.data, response.data)
Exemple #15
0
def following(request):
    following = []

    for v in request.data['userTo']:
        tweets = Tweet.objects.all().filter(user_id=v['user_to'])
        for v in tweets:
            following.append(v)
    
    serializer = TweetSerializer(following, many=True)
    return Response(serializer.data)
Exemple #16
0
class UserSerializered(serializers.ModelSerializer):
    tweets = TweetSerializer(many=True, read_only=True)
    user_comments = CommentSerializer(many=True, read_only=True)
    user_likes = LikeSerializer(many=True, read_only=True)
    userFrom = FollowerSerializer(many=True, read_only=True)
    userTo = FollowerSerializer(many=True, read_only=True)
    user_bookmarks = FavouriteSerializer(many=True, read_only=True)

    class Meta:
        model = User
        fields = ('id', 'email', 'name', 'image', 'tweets', 'user_comments',
                  'user_likes', 'userFrom', 'userTo', 'user_bookmarks')
Exemple #17
0
    def tweets(self, request, *args, **kwargs):
        """List of tweets"""
        user = self.get_object()
        queryset = Tweet.objects.filter(user=user)
        page = self.paginate_queryset(queryset)

        context = self.get_serializer_context()
        serializer = TweetSerializer(page, many=True, context=context)
        result = self.get_paginated_response(serializer.data)
        data = result.data

        return Response(data, status=status.HTTP_200_OK)
Exemple #18
0
def tweet_feed_view(request, *args, **kwargs):
    panigator = PageNumberPagination()
    panigator.page_size = 20
    user = request.user
    profiles = user.following.all()
    followed_users_id = []
    if profiles.exists():
        followed_users_id = [x.user.id for x in profiles]
    followed_users_id.append(user.id)
    qs = Tweet.objects.filter(user__id__in=followed_users_id)
    panigator_qs = panigator.paginate_queryset(qs, request)
    serializer = TweetSerializer(panigator_qs, many=True)
    return panigator.get_paginated_response(serializer.data)
Exemple #19
0
def get_tweet_view(request):
  try:
    tweets_list = get_tweet()
    
    # Shuffle tweets
    random.shuffle(tweets_list)
 
  except Tweet.DoesNotExist:
    return Response(status=status.HTTP_404_NOT_FOUND)

  if request.method == "GET":
    serializers = TweetSerializer(tweets_list, many=True)
    return Response(serializers.data)
Exemple #20
0
def tweet_action_view(request, *args, **kwargs):
    '''
    id is required.
    Action options are: like, unlike, retweet
    '''
    print(
        f"\nTWEET Action View request {request} \nargs -> {args} kwargs -> {kwargs}"
    )
    serializer = TweetActionSerializer(data=request.data)
    if serializer.is_valid(raise_exception=True):
        data = serializer.validated_data
        tweet_id = data.get("id")
        action = data.get("action")
        content = data.get("content")
        qs = Tweet.objects.filter(id=tweet_id)
        print(
            f"\nserializer {serializer} \ndata -> {data} tweet_id -> {tweet_id} \naction {action} content {content} "
        )
        if not qs.exists():
            return Response({}, status=404)
        obj = qs.first()
        if action == "like":
            obj.likes.add(request.user)
            serializer = TweetSerializer(obj)
            return Response(serializer.data, status=200)
        elif action == "unlike":
            obj.likes.remove(request.user)
            serializer = TweetSerializer(obj)
            return Response(serializer.data, status=200)
        elif action == "retweet":
            new_tweet = Tweet.objects.create(user=request.user,
                                             parent=obj,
                                             content=content)
            serializer = TweetSerializer(new_tweet)
            return Response(serializer.data, status=201)
    return Response({}, status=200)
Exemple #21
0
def tweet_detail(request, tid, format=None):
    """
    Retrieve, update or delete a tweet instance.
    """
    try:
        tweet = Tweet.objects.get(id=tid)
    except Tweet.DoesNotExist:
        return Response(status=status.HTTP_404_NOT_FOUND)

    if request.method == 'GET':
        serializer = TweetSerializer(tweet)
        return Response(serializer.data)

    elif request.method == 'DELETE':
        tweet.delete()
        return Response(status=status.HTTP_204_NO_CONTENT)
Exemple #22
0
def tweet_list(request, format=None):
    """
    List all tweets, or create a new tweet.
    """
    if request.method == 'GET':
        tweets = Tweet.objects.all()
        serializer = TweetSerializer(tweets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = TweetSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Exemple #23
0
    def get(self, request, format=None):
        week_previous = timezone.now() - timedelta(days=7)

        tweets_by_hour = Tweet.objects.filter(created_at__gte=week_previous) \
            .annotate(hour=TruncHour('created_at')) \
            .values('hour').annotate(count=Count('id')) \
            .values('hour', 'count').order_by('hour')

        most_retweeted = Tweet.objects.raw("""
            select distinct on (date(created_at at time zone 'US/Central')) *
            from tweets_tweet where created_at > NOW() - INTERVAL '7 days'
            order by (date(created_at at time zone 'US/Central')), retweet_count desc;
        """)
        most_retweeted_by_day = []
        for record in most_retweeted:
            most_retweeted_by_day.append(TweetSerializer(record).data)

        return Response({
            'tweets_by_hour': tweets_by_hour,
            'most_retweeted_by_day': most_retweeted_by_day
        })
Exemple #24
0
def get_paginated_queryset_response(queryset, request):
    paginator = PageNumberPagination()
    paginator.page_size = 10
    paginated_queryset = paginator.paginate_queryset(queryset, request)
    serializer = TweetSerializer(paginated_queryset, many=True)
    return paginator.get_paginated_response(serializer.data)
Exemple #25
0
def details(request):
    tweet = Tweet.objects.get(id=request.data['id'])
    serializer = TweetSerializer(tweet, many=False)
    return Response(serializer.data)
Exemple #26
0
 def get(self, request):
     tweets = Tweet.objects.filter(created_by=request.user)
     serialize = TweetSerializer(tweets, many=True)
     return Response(serialize.data)
Exemple #27
0
 def get(self, request, id):
     tweet = self.get_object(id)
     serialize = TweetSerializer(tweet)
     return Response(serialize.data)
    def get_followingTweets(self, request, pk=None):

        user = self.get_object()
        #Se guardan los ids de los usuarios que sigue el usuario
        following = Follower.objects.filter(userFollower=user.id)
        usersFollowing = [userF.userFollowing.id for userF in following]

        #Se consultan los tweets y retweets de todos los usuarios en la lista
        #Se agrega el id del usuario
        usersFollowing.append(user.id)
        tweets = Tweet.objects.filter(user__in=usersFollowing)
        retweets = Retweet.objects.exclude(originalTweet__in=tweets).exclude(
            user=user.id).filter(user__in=usersFollowing)

        #Se unen los querySets
        results_list = list(chain(tweets, retweets))
        #Se filtran por fechas
        sorted_list = sorted(results_list,
                             key=lambda instance: instance.date,
                             reverse=True)
        # Build the list with items based on the FeedItemSerializer fields
        results = list()
        for entry in sorted_list:
            item_type = entry.__class__.__name__.lower()

            if isinstance(entry, Tweet):
                serializer = TweetSerializer(entry,
                                             context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(serializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    None,
                    'retweet_id':
                    None
                })
            if isinstance(entry, Retweet):
                serializer = TweetSerializer(entry.originalTweet,
                                             context={'request': request})

                retweetSerializer = RetweetSerializer(
                    entry, context={'request': request})
                userSerializer = UserSerializer(entry.user,
                                                context={'request': request})
                results.append({
                    'id':
                    item_type + '-' + str(retweetSerializer.data['id']),
                    'itemType':
                    item_type,
                    'data':
                    serializer.data,
                    'user_retweet':
                    userSerializer.data,
                    'retweet_id':
                    retweetSerializer.data['id']
                })

        return (Response(results))
Exemple #29
0
def tweet_list_view(request, *args, **kwargs):
    qs = Tweet.objects.all()
    username = request.GET.get('username')  # ?username=Justin
    if username != None:
        #qs = qs.by_username(username)
        qs = qs.filter(user__username=username)
    serializer = TweetSerializer(qs, many=True, context={"request": request})
    #return get_paginated_queryset_response(qs, request)
    return Response(serializer.data, status=200)


# def tweet_create_view_pure_django(request, *args, **kwargs):
#     '''
#     REST API Create View -> DRF
#     '''
#     user = request.user
#     if not request.user.is_authenticated:
#         user = None
#         if request.is_ajax():
#             return JsonResponse({}, status=401)
#         return redirect(settings.LOGIN_URL)
#     form = TweetForm(request.POST or None)
#     next_url = request.POST.get("next") or None
#     if form.is_valid():
#         obj = form.save(commit=False)
#         # do other form related logic
#         obj.user = user
#         obj.save()
#         if request.is_ajax():
#             return JsonResponse(obj.serialize(), status=201) # 201 == created items
#         if next_url != None and is_safe_url(next_url, ALLOWED_HOSTS):
#             return redirect(next_url)
#         form = TweetForm()
#     if form.errors:
#         if request.is_ajax():
#             return JsonResponse(form.errors, status=400)
#     return render(request, 'components/form.html', context={"form": form})

# def tweet_list_view_pure_django(request, *args, **kwargs):
#     """
#     REST API VIEW
#     Consume by JavaScript or Swift/Java/iOS/Andriod
#     return json data
#     """
#     qs = Tweet.objects.all()
#     tweets_list = [x.serialize() for x in qs]
#     data = {
#         "isUser": False,
#         "response": tweets_list
#     }
#     return JsonResponse(data)

# def tweet_detail_view_pure_django(request, tweet_id, *args, **kwargs):
#     """
#     REST API VIEW
#     Consume by JavaScript or Swift/Java/iOS/Andriod
#     return json data
#     """
#     data = {
#         "id": tweet_id,
#     }
#     status = 200
#     try:
#         obj = Tweet.objects.get(id=tweet_id)
#         data['content'] = obj.content
#     except:
#         data['message'] = "Not found"
#         status = 404
#     return JsonResponse(data, status=status) # json.dumps content_type='application/json'
Exemple #30
0
def details(request):
    tweeeeeets = Tweet.objects.get(pk=request.data['pk'])
    # console.log('dssss', myaccount)
    serializer = TweetSerializer(tweeeeeets, many=False)
    return Response(serializer.data)