You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

49 lines
1.9 KiB
Python

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, Resource # type: ignore
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( # type: ignore
settings.google_token_file, GOOGLE_SCOPES
)
if not creds.has_scopes(GOOGLE_SCOPES): # type: ignore
creds = None
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token: # type: ignore
creds.refresh(Request()) # type: ignore
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( # type: ignore
settings.google_client_secrets_file, GOOGLE_SCOPES
)
creds = flow.run_local_server(port=0) # type: ignore
with open(settings.google_token_file, "w", encoding="utf-8") as token_file:
token_file.write(creds.to_json()) # type: ignore
return creds # type: ignore
def build_gmail_service(settings: Settings) -> Resource:
creds = get_google_credentials(settings)
return build("gmail", "v1", credentials=creds, cache_discovery=False) # type: ignore
def build_calendar_service(settings: Settings) -> Resource:
creds = get_google_credentials(settings)
return build("calendar", "v3", credentials=creds, cache_discovery=False) # type: ignore