Skip to content

Commit

Permalink
Merge pull request #33 from andela/ft-social-share-164047077
Browse files Browse the repository at this point in the history
Ft social share 164047077
  • Loading branch information
Joan Ngatia committed Mar 25, 2019
2 parents 20cdd3d + 382517c commit 81345d4
Show file tree
Hide file tree
Showing 5 changed files with 292 additions and 4 deletions.
154 changes: 154 additions & 0 deletions authors/apps/article/tests/test_share.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
import json

from rest_framework.test import APITestCase, APIClient
from rest_framework.views import status
from django.urls import reverse
import pdb


class TestShareArticle(APITestCase):
"""
Class tests for article .
"""
client = APIClient()

def setUp(self):
""" Creates user and user dictionary for testing."""
self.article = {
"title": "Andela",
"description": "sdsd",
"body": "dsd",
"images": "",
"tag_list":['kelvin','novak']
}
self.article0 = {
"title": "Andela1",
"description": "sdsd1",
"body": "dsd1",
"images": "",
"tag_list":['kelvin','onkundi']
}
self.article2 = {
"title": "Andela",
"description": "sdsd",
"body": "dsd",
"images": "",
"slug": "andela",
"tag_list":['kelvin','onkundi']
}
self.user = {
"user": {
"email": "chirchir@olympians.com",
"username": "chirchir",
"password": "test1234"
}
}

self.user2 = {
"user": {
"email": "chirch@olympians.com",
"username": "chirch",
"password": "test1234"
}
}

self.article1 = {

"description": "sdsd",
"body": "dsd",
"images": "",
"tag_list":['kelvin','novak']

}
create_user = self.client.post(
'/api/users/', self.user, format='json')

create_user2 = self.client.post(
'/api/users/', self.user2, format='json')

self.request_tkn = self.client.post(
'/api/users/login/', self.user, format='json')

self.request_tkn2 = self.client.post(
'/api/users/login/', self.user2, format='json')

token_request = json.loads(self.request_tkn.content)
self.token = token_request["user"]["token"]

token_request2 = json.loads(self.request_tkn2.content)
self.token2 = token_request2["user"]["token"]

create_profile = self.client.post('/api/profile/create_profile/', self.user,
HTTP_AUTHORIZATION='Token ' + self.token,
format='json')

create_profile2 = self.client.post('/api/profile/create_profile/', self.user2,
HTTP_AUTHORIZATION='Token ' + self.token2,
format='json')

def get_share_link(self, slug, provider):
return self.client.get(
reverse(
"share_article",
kwargs={
"slug": slug,
"provider": provider
}),
HTTP_AUTHORIZATION="Token {}".format(self.token)
)
def successful_article(self):
"""Tests a request which belongs to a valid json file for article
:return:
"""
response = self.client.post('/api/articles/', self.article,
HTTP_AUTHORIZATION='Token ' + self.token,
format='json')
result = json.loads(response.content)
return result


def get_article_slug(self):
"""
return a slug appended to an article
"""
return self.successful_article()['article']['slug']

def test_facebook_correct_share(self):

article_slug = self.get_article_slug()
res = self.client.get(
'/api/articles/{}/share/facebook'.format(article_slug),HTTP_AUTHORIZATION='Token ' + self.token)

self.assertEqual(res.status_code, status.HTTP_200_OK)

def test_twitter_correct_share(self):

article_slug = self.get_article_slug()
res = self.client.get(
'/api/articles/{}/share/twitter'.format(article_slug),HTTP_AUTHORIZATION='Token ' + self.token)

self.assertEqual(res.status_code, status.HTTP_200_OK)

def test_reddit_correct_share(self):

article_slug = self.get_article_slug()
res = self.client.get(
'/api/articles/{}/share/reddit'.format(article_slug),HTTP_AUTHORIZATION='Token ' + self.token)

self.assertEqual(res.status_code, status.HTTP_200_OK)

def test_linkedin_correct_share(self):

article_slug = self.get_article_slug()
res = self.client.get(
'/api/articles/{}/share/linked'.format(article_slug),HTTP_AUTHORIZATION='Token ' + self.token)

self.assertEqual(res.status_code, status.HTTP_200_OK)

def test_email_correct_share(self):

article_slug = self.get_article_slug()
res = self.client.get(
'/api/articles/{}/share/linked'.format(article_slug),HTTP_AUTHORIZATION='Token ' + self.token)

self.assertEqual(res.status_code, status.HTTP_200_OK)
9 changes: 5 additions & 4 deletions authors/apps/article/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
from django.urls import path
from .views import (ArticlesAPIView, RetrieveArticleAPIView, LikeAPIView, DislikeAPIView, RateAPIView, FavouriteAPIView, CommentsAPIView,
RetrieveCommentsAPIView, SubCommentAPIView, LikeUnlikeAPIView, CommentDislikeAPIView, BookmarkAPIView, BookmarksAPIView, ReportArticlesView, GetSingleReportView, GetAllReportsViews)

RetrieveCommentsAPIView, SubCommentAPIView, LikeUnlikeAPIView, CommentDislikeAPIView, BookmarkAPIView,
BookmarksAPIView, ReportArticlesView, GetSingleReportView, GetAllReportsViews, SocialShareArticle)

from .views import (ArticlesAPIView, RetrieveArticleAPIView, LikeAPIView, DislikeAPIView, RateAPIView, FavouriteAPIView, CommentsAPIView,
RetrieveCommentsAPIView, SubCommentAPIView, LikeUnlikeAPIView, CommentDislikeAPIView, BookmarkAPIView, BookmarksAPIView)


app_name = "articles"

urlpatterns = [
Expand All @@ -18,12 +19,12 @@
path('articles/<slug>/comments/<pk>', RetrieveCommentsAPIView.as_view()),
path('articles/<slug>/comments/<pk>/subcomment', SubCommentAPIView.as_view()),
path('articles/<slug>/like_comment/<pk>', LikeUnlikeAPIView.as_view()),
path('articles/<slug>/dislike_comment/<pk>',
CommentDislikeAPIView.as_view()),
path('articles/<slug>/dislike_comment/<pk>',CommentDislikeAPIView.as_view()),
path('articles/<slug>/favorite', FavouriteAPIView.as_view()),
path('articles/<slug>/bookmark', BookmarkAPIView.as_view()),
path('bookmarks/', BookmarksAPIView.as_view()),
path('report/<slug>/',ReportArticlesView.as_view()),
path('reports/<slug>/',GetSingleReportView.as_view()),
path('reports/',GetAllReportsViews.as_view()),
path("articles/<str:slug>/share/<str:provider>", SocialShareArticle.as_view() , name="share_article")
]
131 changes: 131 additions & 0 deletions authors/apps/article/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import json

from django.db.utils import IntegrityError
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django_social_share.templatetags import social_share

from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.response import Response
from rest_framework.exceptions import APIException, NotFound, ValidationError
Expand Down Expand Up @@ -376,6 +382,19 @@ def check_profile(self, user_id):
raise APIException(
{"error": "Permission denied! You don't have a profile"})

def check_like(self, serial_data, profile_id, comment_id):
if LikeComment.get_like_status(profile_id, comment_id, 'like') != False:
serial_data['like'] = True
if LikeComment.get_like_status(profile_id, comment_id, 'dislike') != False:
serial_data['dislike'] = True

if 'subcomments' in serial_data:
if len(serial_data['subcomments']) > 0:
for return_data in serial_data['subcomments']:
return_data = CommentVerification.check_like(
self, return_data, profile_id, return_data['id'])

return serial_data

class CommentsAPIView(APIView):
permission_classes = (IsAuthenticated,)
Expand Down Expand Up @@ -725,3 +744,115 @@ def get(self, request):
return Response({"message": "No reports"}, status=status.HTTP_404_NOT_FOUND)
serializer = self.serializer_class(reports, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)


class SocialShareArticle(RetrieveAPIView):
'''
handle social sharing of an article by an authenticated user
'''

permission_classes = (IsAuthenticated,)

def get(self,request,*args,**kwargs):
'''
return a sharable link if you are an authenticated user and
enable the user to redirect to the specified url
'''

#fetch provider specified in the url
provider = kwargs['provider']

context = {'request':request}

#try fetch an article using the provided slug from the database
#if the article does not exist return 404 not found

try:
article = Article.objects.get(slug=kwargs['slug'])

except Article.DoesNotExist:
raise NotFound({
"error": "article was not found"
})

article_url = request.build_absolute_uri(
"{}article/{}".format(
article.slug,
provider
)
)

share_link = self.get_link(context, provider, article, article_url)

if not share_link:
#where provider is invalid,return a provider invalid error
return Response(
{
"error":"provider was invalid"
}
)

return Response(
{
"share":{
"link":share_link,
"provider":provider
}
}, status.HTTP_200_OK
)

def get_link(self,context,provider,article,article_url):
share_link = None

if provider == "facebook":
# get link to redirect for a facebook share

share_link = social_share.post_to_facebook_url(
context,
article_url
)['facebook_url']

elif provider == "twitter":
text = "Read this on Authors Heaven: {}".format(
article.title
)

share_link = social_share.post_to_twitter(
context,
text,
article_url,
link_text='Post this article to twitter'
)['tweet_url']

elif provider == 'reddit':
#share link to reddit platform
share_link = social_share.post_to_reddit_url(
context,
article.title,
article_url
)['reddit_url']

elif provider == 'linkedin':
title = 'Check this article out on Authors Heaven {}'.format(article.title)

#This gets the sharable link for an article to redirect to the linkedin platform

share_link = social_share.post_to_linkedin_url(
context,
title,
article_url
)['linkedin_url']

elif provider == "email":
subtitle = "Wow!An article from Authors Heaven has been shared to you!Read!!"

#get share link for user to redirect to the email platform
share_link = social_share.send_email_url(
context,
subtitle,
article_url,
)['mailto_url']

return share_link


1 change: 1 addition & 0 deletions authors/settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@

'corsheaders',
'django_extensions',
'django_social_share',
'rest_framework',
'oauth2_provider',
'social_django',
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ django-heroku==0.3.1
django-oauth-toolkit==1.2.0
django-rest-framework-social-oauth2==1.1.0
django-rest-swagger==2.2.0
django-social-share==1.3.2
django-taggit==0.24.0
djangorestframework==3.9.1
djangorestframework-stubs==0.3.0
Expand Down

0 comments on commit 81345d4

Please sign in to comment.