Skip to content

Commit

Permalink
Fixed some stuff, refactored some stuff
Browse files Browse the repository at this point in the history
  • Loading branch information
imaegg11 committed Dec 28, 2024
1 parent 10bc5a5 commit 5634a16
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 51 deletions.
7 changes: 5 additions & 2 deletions core/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,11 @@ class DailyAnnoucementAdminForm(forms.ModelForm):

def clean(self):
cleaned_data = super().clean()

# TODO: Validate start and end date using function DailyAnnoucements.validate_annoucement_date()
start_date = cleaned_data.get("start_date")
end_date = cleaned_data.get("end_date")

if start_date != None and end_date != None and start_date > end_date:
raise forms.ValidationError({"start_date": "Start date cannot be after end date"})

class AnnouncementAdminForm(forms.ModelForm):
status = forms.ChoiceField(
Expand Down
48 changes: 29 additions & 19 deletions core/management/commands/auth_google.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from core.tasks import load_client
from pathlib import Path
import gspread

Expand All @@ -12,25 +13,34 @@ def handle(self, *args, **options):

CLIENT_PATH = SECRETS_PATH + "/client_secret.json"
AUTHORIZED_PATH = SECRETS_PATH + "/authorized_user.json"

client, error_msg, client_path_exists = load_client()

if error_msg != None:
if not client_path_exists:
raise CommandError(error_msg)
elif Path(AUTHORIZED_PATH).is_file():
user = input(f"Delete authorized_user.json located at {AUTHORIZED_PATH}? [Y/n] ")
if user.strip().lower() not in ["yes", "y", ""]:
raise CommandError("Failed to authenticate")

Path(AUTHORIZED_PATH).unlink()

try:
scopes = gspread.auth.READONLY_SCOPES

gspread.oauth(
credentials_filename=CLIENT_PATH,
authorized_user_filename=AUTHORIZED_PATH,
scopes=scopes,
)
except Exception as e:
raise CommandError("Failed to authenticate")

self.stdout.write(
self.style.SUCCESS("Successfully authenticated")
)

scopes = gspread.auth.READONLY_SCOPES

if not Path(settings.SECRETS_PATH).is_dir():
raise CommandError(f"{SECRETS_PATH} directory does not exist")

if not Path(CLIENT_PATH).is_file():
raise CommandError(f"{CLIENT_PATH} file does not exist")

try:
gspread.oauth(
credentials_filename=CLIENT_PATH,
authorized_user_filename=AUTHORIZED_PATH,
scopes=scopes,
)

self.stdout.write(
self.style.SUCCESS("Successfully authenticated")
)

except Exception as e:
raise CommandError("Failed to authenticate")

9 changes: 2 additions & 7 deletions core/models/post.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,17 +203,12 @@ class DailyAnnoucement(models.Model):
creation_date = models.DateTimeField(auto_now_add=True)

def __str__(self) -> str:
return f"{self.organization} Annoucement"
return self.content[:75]

@classmethod
def get_todays_annoucements(cls) -> QuerySet:
def get_todays_annoucements(cls) -> QuerySet[Self]:
return cls.objects.filter(start_date__lte=timezone.now(), end_date__gte=timezone.now())

# TODO: Implement function
@staticmethod
def validate_annoucement_date(start_date, end_date):
pass

class Post(models.Model):
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
Expand Down
53 changes: 36 additions & 17 deletions core/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,49 +243,70 @@ def notif_single(self, recipient_id: int, msg_kwargs):
del u.expo_notif_tokens[token]
u.save()

@app.task
def fetch_annoucements():
if settings.GOOGLE_SHEET_KEY == "" or settings.GOOGLE_SHEET_KEY == None:
return

def load_client() -> tuple[gspread.Client | None, str | None, bool]:
"""
Returns a client from authorized_user.json file
:returns: Tuple with the client, error message and
whether the client secret file exists
"""
CLIENT_PATH = settings.SECRETS_PATH + "/client_secret.json"
AUTHORIZED_PATH = settings.SECRETS_PATH + "/authorized_user.json"

if not Path(settings.SECRETS_PATH).is_dir():
logger.warning(f"Fetch Annoucements: {settings.SECRETS_PATH} directory does not exist")
return
return (None, f"{settings.SECRETS_PATH} directory does not exist", False)

if not Path(CLIENT_PATH).is_file():
logger.warning(f"Fetch Annoucements: {CLIENT_PATH} does not exist")
return
return (None, f"{CLIENT_PATH} does not exist", False)

client = None
scopes = gspread.auth.READONLY_SCOPES

if Path(AUTHORIZED_PATH).is_file():
creds = Credentials.from_authorized_user_file(AUTHORIZED_PATH, scopes)
creds = None

try:
creds = Credentials.from_authorized_user_file(AUTHORIZED_PATH, scopes)
except Exception as e:
return (None, "Failed to load credentials", True)

if not creds.valid and creds.expired and creds.refresh_token:

try:
creds.refresh(Request())
except Exception as e:
logger.warning("Fetch Annoucements: Failed to refresh credentials")
return
return (None, "Failed to refresh credentials", True)

with open(AUTHORIZED_PATH, "w") as f:
f.write(creds.to_json())

try:
client = gspread.authorize(creds)
except Exception as e:
logger.warning("Fetch Annoucements: Failed to authorize credentials")
return
return (None, "Failed to authorize credentials", True)

return (client, None, False)

else:
logger.warning("Fetch Annoucements: Please run auth_google command to authenticate google account")
return
return (None, "No file to load client from", True)

@app.task
def fetch_annoucements():
if settings.GOOGLE_SHEET_KEY == "" or settings.GOOGLE_SHEET_KEY == None:
logger.warning(f"Fetch Annoucements: GOOGLE_SHEET_KEY is empty")
return

client, error_msg, client_path_exists = load_client()

if error_msg != None:
if client_path_exists:
logger.warning(f"Fetch Annoucements: {error_msg} - Run auth_google to fix")
else:
logger.warning(f"Fetch Annoucements: {error_msg}")

return

worksheet = None

try:
Expand All @@ -312,8 +333,6 @@ def fetch_annoucements():
"content": data[8]
}

# TODO: Validate start and end date using function DailyAnnoucements.validate_annoucement_date()

DailyAnnoucement.objects.get_or_create(**parsed_data)
except:
logger.warning(f"Fetch Annoucements: Failed to read, parse or create object for row {row_counter}")
Expand Down
7 changes: 1 addition & 6 deletions metropolis/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,9 +600,4 @@ def set_maintenance():
THEME_LOGO = THEMES[CURRENT_THEME]["logo"]
THEME_CSS = THEMES[CURRENT_THEME]["theme"]

SPECTACULAR_SETTINGS.update(SWAGGER_UI_FAVICON_HREF=THEME_LOGO)

# Daily Annoucment

GOOGLE_SHEET_KEY = ""
SECRETS_PATH = ""
SPECTACULAR_SETTINGS.update(SWAGGER_UI_FAVICON_HREF=THEME_LOGO)

0 comments on commit 5634a16

Please sign in to comment.