2020-04-02 09:59:28 -04:00
|
|
|
#!/usr/bin/env python3
|
2016-12-15 20:38:44 -05:00
|
|
|
import os
|
2021-05-28 05:00:04 -04:00
|
|
|
from typing import Optional
|
2016-12-15 20:38:44 -05:00
|
|
|
|
2021-05-28 05:00:04 -04:00
|
|
|
from oauth2client import client, tools
|
2016-12-15 20:38:44 -05:00
|
|
|
from oauth2client.file import Storage
|
|
|
|
|
|
|
|
try:
|
|
|
|
import argparse
|
2021-05-28 05:03:46 -04:00
|
|
|
|
|
|
|
flags = argparse.ArgumentParser(
|
|
|
|
parents=[tools.argparser]
|
|
|
|
).parse_args() # type: Optional[argparse.Namespace]
|
2016-12-15 20:38:44 -05:00
|
|
|
except ImportError:
|
|
|
|
flags = None
|
|
|
|
|
|
|
|
# If modifying these scopes, delete your previously saved credentials
|
|
|
|
# at zulip/bots/gcal/
|
|
|
|
# NOTE: When adding more scopes, add them after the previous one in the same field, with a space
|
|
|
|
# seperating them.
|
2021-05-28 05:05:11 -04:00
|
|
|
SCOPES = "https://www.googleapis.com/auth/calendar.readonly"
|
2016-12-15 20:38:44 -05:00
|
|
|
# This file contains the information that google uses to figure out which application is requesting
|
|
|
|
# this client's data.
|
2021-05-28 05:05:11 -04:00
|
|
|
CLIENT_SECRET_FILE = "client_secret.json"
|
|
|
|
APPLICATION_NAME = "Zulip Calendar Bot"
|
|
|
|
HOME_DIR = os.path.expanduser("~")
|
2016-12-15 20:38:44 -05:00
|
|
|
|
2021-05-28 05:03:46 -04:00
|
|
|
|
2020-04-18 18:59:12 -04:00
|
|
|
def get_credentials() -> client.Credentials:
|
2016-12-15 20:38:44 -05:00
|
|
|
"""Gets valid user credentials from storage.
|
|
|
|
|
|
|
|
If nothing has been stored, or if the stored credentials are invalid,
|
|
|
|
the OAuth2 flow is completed to obtain the new credentials.
|
|
|
|
|
|
|
|
Returns:
|
|
|
|
Credentials, the obtained credential.
|
|
|
|
"""
|
|
|
|
|
2021-05-28 05:05:11 -04:00
|
|
|
credential_path = os.path.join(HOME_DIR, "google-credentials.json")
|
2016-12-15 20:38:44 -05:00
|
|
|
|
|
|
|
store = Storage(credential_path)
|
|
|
|
credentials = store.get()
|
|
|
|
if not credentials or credentials.invalid:
|
|
|
|
flow = client.flow_from_clientsecrets(os.path.join(HOME_DIR, CLIENT_SECRET_FILE), SCOPES)
|
|
|
|
flow.user_agent = APPLICATION_NAME
|
|
|
|
if flags:
|
|
|
|
# This attempts to open an authorization page in the default web browser, and asks the user
|
|
|
|
# to grant the bot access to their data. If the user grants permission, the run_flow()
|
|
|
|
# function returns new credentials.
|
|
|
|
credentials = tools.run_flow(flow, store, flags)
|
|
|
|
else: # Needed only for compatibility with Python 2.6
|
|
|
|
credentials = tools.run(flow, store)
|
2021-05-28 05:05:11 -04:00
|
|
|
print("Storing credentials to " + credential_path)
|
2016-12-15 20:38:44 -05:00
|
|
|
|
2021-05-28 05:03:46 -04:00
|
|
|
|
2016-12-15 20:38:44 -05:00
|
|
|
get_credentials()
|