Skip to content

gcal_setup

Google Calendar API authorization.

get_new_token(client_secret_file, scopes)

Get a new user token.

Parameters:

Name Type Description Default
client_secret_file str

description

required
scopes list[str]

description

required

Returns:

Name Type Description
credentials

description

Source code in ncal/gcal_setup.py
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
def get_new_token(client_secret_file: str, scopes: list[str]):
    """Get a new user token.

    Args:
        client_secret_file: _description_
        scopes: _description_

    Returns:
        credentials: _description_
    """
    flow = InstalledAppFlow.from_client_secrets_file(client_secret_file, scopes)
    credentials = flow.run_local_server(
        host="localhost",
        port=8080,
        authorization_prompt_message="Please visit this URL: {url}",
        success_message="The auth flow is complete; you may close this window.",
        open_browser=False,
    )

    return credentials

setup_google_api(calendar_id, client_secret_file, token_file)

Set up the Google Calendar API interface.

Parameters:

Name Type Description Default
calendar_id str required
client_secret_file str required
token_file str required

Returns:

Type Description
tuple[Resource, Any]

tuple[googleapiclient.discovery.Resource, Any]:

Source code in ncal/gcal_setup.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
def setup_google_api(
    calendar_id: str, client_secret_file: str, token_file: str
) -> tuple[Resource, Any]:
    """Set up the Google Calendar API interface.

    Args:
        calendar_id (str):
        client_secret_file (str):
        token_file (str):

    Returns:
        tuple[googleapiclient.discovery.Resource, Any]:
    """
    # credentials from json file.
    credentials = None
    if os.path.isfile(token_file):
        credentials = Credentials.from_authorized_user_file(token_file)
    if not credentials or not credentials.valid:
        # use refresh token if available
        if credentials and credentials.expired and credentials.refresh_token:
            try:
                credentials.refresh(Request())
            except google.auth.exceptions.RefreshError:
                logging.error("Failed to refresh credentials.")
                credentials = get_new_token(client_secret_file, SCOPES)
        # If no valid credentials are available, let the user log in.
        else:
            credentials = get_new_token(client_secret_file, SCOPES)
        # Save the credentials for the next run
        with open(token_file, "w") as token:
            token.write(credentials.to_json())

    # Build the service object.
    service = build("calendar", "v3", credentials=credentials)
    calendar = service.calendars()

    return (service, calendar)
Back to top