refactor: custom command to update social key

This commit is contained in:
bobbyvish
2024-12-02 11:51:51 +05:30
parent 3f263b2af5
commit 8ccec7012c
7 changed files with 117 additions and 49 deletions

View File

@@ -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(
{

View File

@@ -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()

View File

@@ -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

View File

@@ -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(

View File

@@ -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

View File

@@ -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']:

View File

@@ -195,6 +195,7 @@
// Initialize Tagify
initializeTagify('#id_tags');
initializeTagify('#id_key_guest');
// Handle principal change
handlePrincipalChange();