def get(self, request, *args, **kwargs): account_type = kwargs.get("account_type") token = request.META.get('HTTP_AUTHORIZATION', None) if account_type not in ('facebook', 'twitter', 'web'): return Response(status=status.HTTP_400_BAD_REQUEST) user_profile = get_user_profile_from_token(token) content_list = UserContent.objects.filter(user=user_profile, source=account_type) pos = 0.0 neg = 0.0 neut = 0.0 for content in content_list: if content.pos_sentiment_rating: pos += float(content.pos_sentiment_rating) if content.neg_sentiment_rating: neg += float(content.neg_sentiment_rating) if content.neut_sentiment_rating: neut += float(content.neut_sentiment_rating) total = pos + neg + neut ppos = 0.0 pneg = 0.0 pneut = 0.0 if total: ppos = (pos / total) pneg = (neg / total) pneut = (neut / total) pos_norm = ppos * 100 neg_norm = pneg * 100 neut_norm = pneut * 100 if pos_norm >= 90: rating = "A*" elif pos_norm >= 80: rating = "B" elif pos_norm >= 70: rating = "C" elif pos_norm >= 60: rating = "D" elif pos_norm >= 50: rating = "E" else: rating = "F" data = { 'positive': pos_norm, 'negative': neg_norm, 'neutral': neut_norm, 'rating': rating, } serializer = AccountDetailSerializer(data) return Response(serializer.data)
def put(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) instance = get_user_profile_from_token(token) serializer = UpdateUserProfileSerializer(instance, data=request.data) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data)
def validate(self, data): code = data.get('code', None) access_token = data.get('access_token', None) client_id = getattr(settings, "FACEBOOK_CLIENT_ID", None) client_secret = getattr(settings, "FACEBOOK_CLIENT_SECRET", None) callback_url = getattr(settings, "FACEBOOK_CALLBACK_URL", None) try: AccessToken.objects.get(token=access_token) except AccessToken.DoesNotExist: raise NotAuthenticated() if not client_id: raise ValidationError(detail={'client_id': 'Cannot find FACEBOOK_CLIENT_ID in django settings'}) if not client_secret: raise ValidationError(detail={'client_secret': 'Cannot find FACEBOOK_CLIENT_SECRET in django settings'}) if not callback_url: raise ValidationError(detail={'callback_url': 'Cannot find FACEBOOK_CALLBACK_URL in django settings'}) if not code: raise ValidationError(detail={'code': 'This field is required.'}) fb_token_url = "https://graph.facebook.com/oauth/access_token?code={}&client_id={}&client_secret={}&redirect_uri={}".format( code, client_id, client_secret, callback_url) fb_access_token_response = r.get(fb_token_url) fb_access_token_response_parts = urlparse.parse_qsl(fb_access_token_response.content) fb_access_token = None for part in fb_access_token_response_parts: if part[0] == 'access_token': fb_access_token = part[1] if not fb_access_token: raise ValidationError(detail={'access_token': 'Could not retrieve Facebook access token'}) user_info_url = "https://graph.facebook.com/v2.5/me?access_token={}&fields=id,name,email,gender".format( fb_access_token) user_info_response = r.get(user_info_url).json() fb_id = user_info_response.get('id') fullname = user_info_response.get('name') user_profile = get_user_profile_from_token("Bearer %s" % access_token) return {'fb_access_token': fb_access_token, 'user_profile': user_profile, 'fb_id': fb_id, 'fullname': fullname, }
def get(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) try: twitter_account = SocialAccount.objects.get(user_profile=user_profile, provider='twitter') except SocialAccount.DoesNotExist: return Response(status=status.HTTP_400_BAD_REQUEST) auth = tweepy.OAuthHandler(settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET) auth.set_access_token(twitter_account.social_token, twitter_account.social_secret) api = tweepy.API(auth) trend_list = api.trends_place(23424975)[0].get("trends")[0:5] or [] insight_list = [] for trend in trend_list: tweets = [] tag = trend["name"] tweet_volume = trend["tweet_volume"] recommendation = "Create a new post relating to %s" % tag insight = { "tag": tag, "tweets": tweets, "recommendation": recommendation, "tweet_volume": tweet_volume, "score": randint(1, 20), } results = api.search(q=tag, count=3) for result in results: screen_name = result.user.screen_name text = result.text tweet_id = result.id favourites_count = result.favorite_count retweets_count = result.retweet_count user_photo_url = result.user.profile_image_url user_followers = result.user.followers_count tweet_data = { "screen_name": screen_name, "text": text, "tweet_id": str(tweet_id), "favourites_count": favourites_count, "retweets_count": retweets_count, "user_photo_url": user_photo_url, "user_followers": user_followers } tweets.append(tweet_data) insight_list.append(insight) return Response(data=insight_list, status=status.HTTP_200_OK)
def post(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) source = kwargs.get("source") or None print source try: scan_user_content.delay(str(user_profile.pk), source) except Exception, e: print e scan_user_content(str(user_profile.pk), source)
def get(self, request, *args, **kwargs): content_type = kwargs.get("content_type") or None if content_type not in ('facebook', 'twitter', 'web'): return Response(status=status.HTTP_400_BAD_REQUEST) sentiment = request.GET.get("sentiment") or None page = request.GET.get("page") or 0 count = request.GET.get("count") or 10 sort = request.GET.get("sort") or None if sort == "neutral": sort_field = '-neut_sentiment_rating' elif sort == "pos": sort_field = '-pos_sentiment_rating' else: sort_field = '-neg_sentiment_rating' page = int(page) if not isinstance(page, int): page = 0 try: count = int(count) except ValueError: count = 10 start = page * int(count) end = start + int(count) if sentiment not in ("pos", "neg", "neutral"): sentiment = None token = request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) if sentiment: queryset = UserContent.objects.filter(user=user_profile, source=content_type, hidden=False, sentiment_label=sentiment).order_by(sort_field)[start:end] else: queryset = UserContent.objects.filter(user=user_profile, source=content_type, hidden=False).order_by( sort_field)[start:end] serializer = self.get_serializer(queryset, many=True) return Response(data=serializer.data)
def validate(self, data): tweet_id = data.get('tweet_id', None) access_token = data.get('access_token', None) user_profile = get_user_profile_from_token(access_token) if not tweet_id: raise ValidationError(detail={'tweet_id': 'This field is required.'}) try: SocialAccount.objects.get(user_profile=user_profile, provider='twitter') except SocialAccount.DoesNotExist: raise ValidationError(detail={'error': 'User profile does not have a twitter account'}) return { 'tweet_id': tweet_id, 'user': user_profile }
def validate(self, data): image_base64 = data.get('image_base64', None) access_token = data.get('access_token', None) name = data.get('name', None) user = get_user_profile_from_token(access_token) if not user: raise NotAuthenticated() if not is_valid_base64(image_base64): raise InvalidBase64() return { 'user': user, 'image_base64': image_base64, 'name': name }
def validate(self, data): verifier = data.get('oauth_verifier', None) request_token = data.get('request_token', None) access_token = data.get('access_token', None) consumer_key = getattr(settings, "TWITTER_CONSUMER_KEY", None) consumer_secret = getattr(settings, "TWITTER_CONSUMER_SECRET", None) callback_url = getattr(settings, "TWITTER_CALLBACK_URL", None) if not consumer_key: raise ValidationError(detail={'client_id': 'Cannot find TWITTER_CONSUMER_KEY in django settings'}) if not consumer_secret: raise ValidationError(detail={'client_secret': 'Cannot find TWITTER_CONSUMER_SECRET in django settings'}) if not callback_url: raise ValidationError(detail={'callback_url': 'Cannot find TWITTER_CALLBACK_URL in django settings'}) if not verifier: raise ValidationError(detail={'oauth_verifier': 'This field is required.'}) if not request_token: raise ValidationError(detail={'request_token': 'This field is required.'}) auth = tweepy.OAuthHandler( settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET ) auth.request_token = request_token key, secret = auth.get_access_token(verifier) try: AccessToken.objects.get(token=access_token) except AccessToken.DoesNotExist: raise NotAuthenticated() url = "https://api.twitter.com/1.1/account/verify_credentials.json?&include_email=true" auth = OAuth1(consumer_key, consumer_secret, key, secret) r = requests.get(url=url, auth=auth) twitter_data = r.json() twitter_id = twitter_data.get('id') user_profile = get_user_profile_from_token("Bearer %s" % access_token) social_username = twitter_data.get('screen_name') or None return { 'key': key, 'secret': secret, 'twitter_id': twitter_id, 'user_profile': user_profile, 'social_username': social_username, }
def validate(self, data): provider = data.get('provider', None) message = data.get('message', None) access_token = data.get('access_token', None) user_profile = get_user_profile_from_token(access_token) if not provider: raise ValidationError(detail={'provider': 'This field is required.'}) if not message: raise ValidationError(detail={'message': 'This field is required.'}) if provider not in ('facebook', 'twitter'): raise ValidationError(detail={'provider': 'Invalid platform, choices are facebook or twitter.'}) try: SocialAccount.objects.get(user_profile=user_profile, provider=provider) except SocialAccount.DoesNotExist: raise ValidationError(detail={'error': 'User profile does not have a %s account' % provider}) return { 'provider': provider, 'message': message, 'user': user_profile }
def list(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) social_account_list = SocialAccount.objects.filter(user_profile=user_profile) queryset = [ { 'account': "web", 'name': "%s %s" % (user_profile.user.first_name, user_profile.user.last_name) } ] for social_account in social_account_list: data = { 'account': social_account.provider, 'name': social_account.social_username or "%s %s" % ( user_profile.user.first_name, user_profile.user.last_name) } queryset.append(data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data)
def get(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) # Get all user contents content_list = UserContent.objects.filter(user=user_profile) pos = 0.0 neg = 0.0 # Sum up total positive and negative scores for content in content_list: if content.pos_sentiment_rating is not None: pos = pos + float(content.pos_sentiment_rating) if content.neg_sentiment_rating is not None: neg = neg + float(content.neg_sentiment_rating) # Total scores and normalise total = pos + neg ppos = 0.0 pneg = 0.0 if total: ppos = (pos / total) pneg = (neg / total) pos_norm = ppos neg_norm = pneg data = { "positive": float("%.3f" % pos_norm), "negative": float("%.3f" % neg_norm) } return Response(data=data, status=status.HTTP_200_OK)
def get(self, request, *args, **kwargs): token = request.META.get('HTTP_AUTHORIZATION', None) instance = get_user_profile_from_token(token) serializer = UserProfileSerializer(instance) return Response(serializer.data)
def get_queryset(self): token = self.request.META.get('HTTP_AUTHORIZATION', None) user_profile = get_user_profile_from_token(token) return Report.objects.filter(user_profile=user_profile)