import os from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from app.config import GOOGLE_SCOPES, Settings def get_google_credentials(settings: Settings) -> Credentials: creds = None if os.path.exists(settings.google_token_file): creds = Credentials.from_authorized_user_file( settings.google_token_file, GOOGLE_SCOPES ) if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: if not os.path.exists(settings.google_client_secrets_file): raise FileNotFoundError( f"Missing OAuth client file at {settings.google_client_secrets_file}. " "Create Google OAuth desktop credentials and save the JSON at this path." ) flow = InstalledAppFlow.from_client_secrets_file( settings.google_client_secrets_file, GOOGLE_SCOPES ) creds = flow.run_local_server(port=0) with open(settings.google_token_file, "w", encoding="utf-8") as token_file: token_file.write(creds.to_json()) return creds def build_gmail_service(settings: Settings): creds = get_google_credentials(settings) return build("gmail", "v1", credentials=creds, cache_discovery=False) def build_calendar_service(settings: Settings): creds = get_google_credentials(settings) return build("calendar", "v3", credentials=creds, cache_discovery=False)