refactor(social media):change message of success and failure in social media response

This commit is contained in:
bobbyvish
2024-07-25 16:45:20 +05:30
parent 33030ca728
commit a68f114f99
6 changed files with 77 additions and 38 deletions

View File

@@ -884,7 +884,7 @@ class FacebookAPI:
try:
url = f"https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id={self.app_id}&client_secret={self.app_secret}"
response = requests.get(url)
response.raise_for_status()
# response.raise_for_status()
print(f"short lived token {response.json()}")
return response.json()['access_token']
except requests.exceptions.RequestException as e:
@@ -895,7 +895,7 @@ class FacebookAPI:
try:
url = f"https://graph.facebook.com/v20.0/oauth/access_token?grant_type=fb_exchange_token&client_id={self.app_id}&client_secret={self.app_secret}&fb_exchange_token={short_lived_token}"
response = requests.get(url)
response.raise_for_status()
# response.raise_for_status()
print(f"long lived access token : {response.json()}")
return response.json()['access_token']
except requests.exceptions.RequestException as e:
@@ -932,14 +932,14 @@ class FacebookAPI:
"access_token": self.page_access_token,
}
response = requests.post(url, params=params)
response.raise_for_status()
# response.raise_for_status()
result = response.json()
if "id" not in result:
print(f"Error posting photo: {result}")
return False
print(f"Data posted successfully. Post Id: {result['id']}")
return True
except requests.exceptions.RequestException as e:
except Exception as e:
print(f"Error posting photo: {e}")
return False
@@ -953,7 +953,7 @@ class FacebookPoster:
return {'success': False, 'message': 'Error posting photo. Authenticate failed'}
result = self.facebook_api.post_photo(image_url, caption)
if not result:
return {'success': False, 'message': 'Error posting photo'}
return {'success': False, 'message': 'Error posting photo in Facebook'}
return {'success': True, 'message': 'Photo posted successfully'}
@@ -1026,7 +1026,7 @@ class InstagramAPI:
response.raise_for_status()
print(f"Page access token: {response.json()}")
return response.json()["access_token"]
except requests.exceptions.RequestException as e:
except Exception as e:
print(f"Error getting page access token: {e}")
return None
@@ -1042,7 +1042,6 @@ class InstagramAPI:
return True
def post_image_with_caption(self, image_path, caption):
image_path="https://admin.goodtimesltd.co.uk/static/img/goodtimes.png"
if not self.page_access_token:
print("Page access token not obtained. Call Authenticate() first.")
return False
@@ -1054,9 +1053,9 @@ class InstagramAPI:
"access_token": self.page_access_token
}
response = requests.post(url, data=params)
response.raise_for_status()
# response.raise_for_status()
result = response.json()
print(f"Post image with caption result: {result['id']}")
print(f"Post image with caption result: {result}")
url = f"https://graph.facebook.com/v20.0/{self.page_id}/media_publish"
params = {
@@ -1064,10 +1063,10 @@ class InstagramAPI:
"access_token": self.page_access_token
}
response = requests.post(url, params=params)
response.raise_for_status()
# response.raise_for_status()
result = response.json()
return True
except requests.exceptions.RequestException as e:
except Exception as e:
print(f"Error posting photo on instagram: {e}")
return False
@@ -1082,5 +1081,5 @@ class InstagramPoster:
return {'success': False, 'message': 'Error posting photo. Authenticate failed'}
result = self.instagram_api.post_image_with_caption(image_path, caption)
if not result:
return {'success': False, 'message': 'Error posting photo.'}
return {'success': False, 'message': 'Error posting photo in Instagram.'}
return {'success': True, 'message': 'Photo posted successfully'}

View File

@@ -59,8 +59,6 @@ class JsonResponseUtil:
response_data["errors"] = errors
return JsonResponse(response_data, status=status)
class RandomGenerator:
@staticmethod
def number(start, end):

View File

@@ -15,8 +15,7 @@ class Command(BaseCommand):
if not event.image:
self.stdout.write(self.style.ERROR("No image found."))
base_domain = settings.BASE_DOMAIN
image_path = f"{base_domain}{event.image.url}"
image_path = f"{settings.BASE_DOMAIN}{event.image.url}"
print(f"complete path of image {image_path}")
caption = f"{event.title}\nDuration: {event.start_date} to {event.end_date}\nAddress: {event.venue.address}"

View File

@@ -16,9 +16,8 @@ class Command(BaseCommand):
if not event.image:
self.stdout.write(self.style.ERROR("No image found."))
# base_domain = settings.BASE_DOMAIN
# image_path = f"{base_domain}{event.image.url}"
image_path = event.image.url
image_path = f"{settings.BASE_DOMAIN}{event.image.url}"
# image_path = event.image.url
print(f"complete path of image {image_path}")
caption = f"{event.title}\nDuration: {event.start_date} to {event.end_date}\nAddress: {event.venue.address}"

View File

@@ -533,7 +533,7 @@ class CustomerVenueFilterView(LoginRequiredMixin, generic.View):
User = get_user_model()
from .report import generate_event_report, generate_event_report_pdf_three
from django.http import HttpResponse
from django.http import HttpResponse, JsonResponse
class GenerateEventReportView(generic.View):
@@ -561,45 +561,70 @@ class SocialMediaPostView(generic.View):
event_id = kwargs.get("id")
print(platform, event_id)
errors = []
success_messages = []
try:
event = Event.objects.get(id=event_id)
except Event.DoesNotExist:
errors.append("Event does not exist")
return JsonResponseUtil.error(message=errors, errors=errors)
return JsonResponse({
'message': "Error in posting to social media",
'errors': errors,
'success_messages': success_messages
}, status=400)
if not event.active:
errors.append("Event is not active")
return JsonResponseUtil.error(message=errors, errors=errors)
return JsonResponse({
'message': "Error in posting to social media",
'errors': errors,
'success_messages': success_messages
}, status=400)
caption = f"{event.title}\nDuration: {event.start_date} to {event.end_date}\nAddress: {event.venue.address}"
print(f"image url and caption is {caption}")
if platform in ['instagram', 'facebook', 'twitter', 'all']:
if platform in ['instagram', 'facebook', 'twitter', 'all']:
if platform in ['twitter', 'all']:
image_url = event.image.path
twitter_api = TwitterAPI()
twitter_poster = TwitterPoster(twitter_api)
result = twitter_poster.post_image_with_caption(image_url, caption)
if not result['success']:
errors.append(result['message'])
if result['success']:
success_messages.append("Posted to Twitter successfully")
else:
errors.append("Fail to post on Twitter")
image_url = request.build_absolute_uri(event.image.url) # fb and insta require complete path with domain
image_url = request.build_absolute_uri(event.image.url)
if platform in ['facebook', 'all']:
facebook_api = FacebookAPI()
facebook_poster = FacebookPoster(facebook_api)
result = facebook_poster.post_photo(image_url, caption)
if not result["success"]:
errors.append(result["message"])
if result["success"]:
success_messages.append("Posted to Facebook successfully")
else:
errors.append("Fail to post on Facebook")
if platform in ['instagram', 'all']:
instagram_api = InstagramAPI()
instagram_poster = InstagramPoster(instagram_api)
result = instagram_poster.post_image_with_caption(image_url, caption)
if not result["success"]:
errors.append(result["message"])
if result["success"]:
success_messages.append("Posted to Instagram successfully")
else:
errors.append("Fail to post on Instagram")
if not errors:
return JsonResponseUtil.success(message='Post Successful')
return JsonResponse({'message': 'Post Successful', 'errors': errors, 'success_messages': success_messages})
return JsonResponseUtil.error(message=errors, errors=errors)
if errors and success_messages:
return JsonResponse({
'message': 'Some posts succeeded while others failed',
'errors': errors,
'success_messages': success_messages
}, status=200)
return JsonResponse({
'message': 'Error in posting to social media',
'errors': errors,
'success_messages': success_messages
}, status=400)

View File

@@ -252,26 +252,43 @@
console.log(response);
Swal.close();
if (response.status === 200) {
if (response.success_messages && response.errors && response.errors.length === 0) {
let successMessages = response.success_messages.join("<br>");
Swal.fire({
icon: "success",
title: "Success",
text: response.message
html: response.message + "<br>" + successMessages
});
} else if (response.status === 403) {
} else if (response.errors && response.success_messages) {
let errorMessages = response.errors.join("<br>");
let successMessages = response.success_messages.join("<br>");
Swal.fire({
icon: "warning",
title: "Partial Success",
html: response.message + "<br>Successes:<br>" + successMessages + "<br>Failures:<br>" + errorMessages
});
} else if (response.errors) {
let errorMessages = response.errors.join("<br>");
Swal.fire({
icon: "error",
title: "Failures",
html: response.message + "<br>" + errorMessages
});
} else {
Swal.fire({
icon: "error",
title: "Error",
text: response.message
text: "Unknown error occurred"
});
}
},
error: function(xhr, status, error) {
Swal.close();
var errorMessage = xhr.responseJSON && xhr.responseJSON.message ? xhr.responseJSON.message : "Something went wrong. Please try again later.";
Swal.fire({
icon: "error",
title: "Error",
text: "Something went wrong. Please try again later."
text: errorMessage
});
}
});
@@ -280,5 +297,7 @@
});
});
</script>
{%endblock javascript%}