From 8ccec7012c4637dbb60be794aec84c1bf57d02c4 Mon Sep 17 00:00:00 2001 From: bobbyvish Date: Mon, 2 Dec 2024 11:51:51 +0530 Subject: [PATCH] refactor: custom command to update social key --- goodtimes/asgi.py | 4 +- goodtimes/services.py | 49 +-------- goodtimes/settings/base.py | 5 +- goodtimes/settings/staging.py | 2 +- .../commands/update_facebook_tokens.py | 103 ++++++++++++++++++ manage_events/views.py | 2 +- templates/manage_events/event_add.html | 1 + 7 files changed, 117 insertions(+), 49 deletions(-) create mode 100644 manage_events/management/commands/update_facebook_tokens.py diff --git a/goodtimes/asgi.py b/goodtimes/asgi.py index eccfdf2..0c06e2b 100644 --- a/goodtimes/asgi.py +++ b/goodtimes/asgi.py @@ -8,13 +8,15 @@ https://docs.djangoproject.com/en/5.0/howto/deployment/asgi/ """ import os +import django +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "goodtimes.settings") +django.setup() from django.urls import path from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from chat.routing import websocket_urlpatterns -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "goodtimes.settings") django_asgi_app = get_asgi_application() application = ProtocolTypeRouter( { diff --git a/goodtimes/services.py b/goodtimes/services.py index 92848f2..940b66f 100644 --- a/goodtimes/services.py +++ b/goodtimes/services.py @@ -695,58 +695,19 @@ class FacebookAPI: self.app_id = settings.FACEBOOK_APP_ID self.app_secret = settings.FACEBOOK_APP_SECRET self.page_id = settings.FACEBOOK_PAGE_ID - self.page_access_token = None - - def _get_short_lived_user_access_token(self): - 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() - print(f"short lived token {response.json()}") - return response.json()['access_token'] - except requests.exceptions.RequestException as e: - print(f"Error getting short-lived user access token: {e}") - return None - - def _get_long_lived_user_access_token(self, short_lived_token): - 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() - print(f"long lived access token : {response.json()}") - return response.json()['access_token'] - except requests.exceptions.RequestException as e: - print(f"Error getting long-lived user access token: {e}") - return None - - def _get_page_access_token(self, long_lived_token): - url = f"https://graph.facebook.com/{self.page_id}?fields=access_token&access_token={long_lived_token}" - response = requests.get(url) - # response.raise_for_status() - print(f"page access token is {response.json()}") - # self.page_access_token = response.json()["access_token"] - - def authenticate(self): - # short_lived_token = self._get_short_lived_user_access_token() - # if not short_lived_token: - # return False - # long_lived_token = self._get_long_lived_user_access_token(short_lived_token) - # if not long_lived_token: - # return False - # self._get_page_access_token(short_lived_token) - self.page_access_token = settings.FACEBOOK_ACCESS_TOKEN - return True + self.graph_api_version = settings.FACEBOOK_GRAPH_VERSION_API + self.access_token = settings.FACEBOOK_ACCESS_TOKEN # long live access token def post_photo(self, image_url, caption): - if not self.page_access_token: + if not self.access_token: print("Page access token not obtained. Call authenticate() first.") return False try: - url = f"https://graph.facebook.com/v20.0/{self.page_id}/photos" + url = f"https://graph.facebook.com/{self.graph_api_version}/{self.page_id}/photos" params = { "message": caption, "url": image_url, - "access_token": self.page_access_token, + "access_token": self.access_token, } response = requests.post(url, params=params) # response.raise_for_status() diff --git a/goodtimes/settings/base.py b/goodtimes/settings/base.py index 5d57fd3..fc658bb 100644 --- a/goodtimes/settings/base.py +++ b/goodtimes/settings/base.py @@ -83,7 +83,7 @@ THIRD_PARTY_APPS = [ "allauth.socialaccount.providers.apple", "allauth.socialaccount.providers.google", "django_filters", - # "django_crontab", + "django_crontab", # "django_celery_results", # "django_celery_beat", ] @@ -336,7 +336,7 @@ CHANNEL_LAYERS = { WEBSOCKET_TIMEOUT = 30 CRONJOBS = [ - # ("0 9 * * 1-5", "manage_games.cron.update_game_status_live"), + # ('0 0 * * *', 'myapp.cron.daily_task >> /path/to/logfile.log 2>&1'), ] GOOGLE_MAPS_API_KEY = env.str("GOOGLE_MAPS_API_KEY") @@ -356,6 +356,7 @@ TWITTER_ACCESS_TOKEN_SECRET = env.str("TWITTER_ACCESS_TOKEN_SECRET") FACEBOOK_APP_ID = env.str("FACEBOOK_APP_ID") FACEBOOK_APP_SECRET = env.str("FACEBOOK_APP_SECRET") FACEBOOK_PAGE_ID = env.str("FACEBOOK_PAGE_ID") +FACEBOOK_GRAPH_VERSION_API = env.str("FACEBOOK_GRAPH_VERSION_API") FACEBOOK_ACCESS_TOKEN = env.str("FACEBOOK_ACCESS_TOKEN") # Instagram Key diff --git a/goodtimes/settings/staging.py b/goodtimes/settings/staging.py index 71641cd..cb67fbc 100644 --- a/goodtimes/settings/staging.py +++ b/goodtimes/settings/staging.py @@ -6,7 +6,7 @@ import colorlog # from logging.handlers import TimedRotatingFileHandler DEBUG = False -ALLOWED_HOSTS = ["staging.goodtimesltd.co.uk", "77.68.8.229"] +ALLOWED_HOSTS = ["staging.goodtimesltd.co.uk", "77.68.8.229",".staging.goodtimesltd.co.uk"] LOGGING_DIR = os.path.join( diff --git a/manage_events/management/commands/update_facebook_tokens.py b/manage_events/management/commands/update_facebook_tokens.py new file mode 100644 index 0000000..901df24 --- /dev/null +++ b/manage_events/management/commands/update_facebook_tokens.py @@ -0,0 +1,103 @@ + +import os +from django.conf import settings +import requests +from dotenv import load_dotenv +from django.core.management.base import BaseCommand + +# Load .env variables +load_dotenv() + +class Command(BaseCommand): + help = 'Update Facebook long-lived access tokens and page access token' + + def __init__(self): + super().__init__() + self.app_id = settings.FACEBOOK_APP_ID + self.app_secret = settings.FACEBOOK_APP_SECRET + self.page_id = settings.FACEBOOK_PAGE_ID + self.graph_api_version = settings.FACEBOOK_GRAPH_VERSION_API + self.page_access_token = settings.FACEBOOK_ACCESS_TOKEN + self.long_lived_token = settings.FACEBOOK_ACCESS_TOKEN + + def handle(self, *args, **kwargs): + """Handle the token refresh and update .env file.""" + if self.refresh_access_tokens(): + self.stdout.write(self.style.SUCCESS("Successfully refreshed Facebook tokens.")) + else: + self.stdout.write(self.style.ERROR("Failed to refresh Facebook tokens.")) + + def _exchange_short_to_long_lived_token(self, short_lived_token): + """Exchange short-lived token for long-lived token.""" + try: + url = f"https://graph.facebook.com/{self.graph_api_version}/oauth/access_token" + params = { + "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, params=params) + response.raise_for_status() + long_lived_token = response.json().get("access_token") + self.stdout.write(self.style.SUCCESS("Successfully exchanged for long-lived user access token.")) + return long_lived_token + except requests.exceptions.RequestException as e: + self.stdout.write(self.style.ERROR(f"Error exchanging short-lived token: {e}")) + return None + + def _get_page_access_token(self, user_token): + """Retrieve Page Access Token.""" + try: + url = f"https://graph.facebook.com/{self.graph_api_version}/{self.page_id}" + params = { + "fields": "access_token", + "access_token": user_token, + } + response = requests.get(url, params=params) + response.raise_for_status() + page_access_token = response.json().get("access_token") + self.stdout.write(self.style.SUCCESS("Successfully obtained page access token.")) + return page_access_token + except requests.exceptions.RequestException as e: + self.stdout.write(self.style.ERROR(f"Error retrieving page access token: {e}")) + return None + + def _update_env_variable(self, key, value): + """Update a variable in the .env file.""" + with open('.env', 'r') as file: + lines = file.readlines() + + with open('.env', 'w') as file: + updated = False + for line in lines: + if line.startswith(key): + file.write(f"{key}={value}\n") + updated = True + else: + file.write(line) + if not updated: + file.write(f"{key}={value}\n") + + def refresh_access_tokens(self): + """Refresh long-lived user access token and page access token.""" + if not self.long_lived_token: + self.stdout.write(self.style.ERROR("No valid long-lived user access token found.")) + return False + + # Refresh long-lived user token (optional, based on expiry) + refreshed_user_token = self._exchange_short_to_long_lived_token(self.long_lived_token) + if refreshed_user_token: + self.long_lived_token = refreshed_user_token + + # Refresh page access token + # page_access_token = self._get_page_access_token(self.long_lived_token) + # if page_access_token: + # self.page_access_token = page_access_token + # # Update tokens in .env file + self._update_env_variable("FACEBOOK_ACCESS_TOKEN", self.long_lived_token) + # self._update_env_variable("FACEBOOK_PAGE_ACCESS_TOKEN", self.page_access_token) + return True + + self.stdout.write(self.style.ERROR("Failed to refresh page access token.")) + return False diff --git a/manage_events/views.py b/manage_events/views.py index be68863..b3f50ce 100644 --- a/manage_events/views.py +++ b/manage_events/views.py @@ -584,7 +584,7 @@ class SocialMediaPostView(generic.View): 'success_messages': success_messages }, status=400) - caption = f"{event.title}\nDuration: {event.start_date} to {event.end_date}\nAddress: {event.venue.address}" + caption = f"Venue: {event.venue.title} \n Event: {event.title}\n Description: {event.description} \n Date: {event.start_date} to {event.end_date}\n Time: {event.from_time} - {event.to_time} \n Address: {event.venue.address}" if platform in ['instagram', 'facebook', 'twitter', 'all']: if platform in ['twitter', 'all']: diff --git a/templates/manage_events/event_add.html b/templates/manage_events/event_add.html index 950a41e..2aeec9e 100644 --- a/templates/manage_events/event_add.html +++ b/templates/manage_events/event_add.html @@ -195,6 +195,7 @@ // Initialize Tagify initializeTagify('#id_tags'); + initializeTagify('#id_key_guest'); // Handle principal change handlePrincipalChange();