├── google_calendar_to_sqlite ├── __init__.py ├── utils.py └── cli.py ├── .gitignore ├── tests └── test_google_calendar_to_sqlite.py ├── .github └── workflows │ ├── test.yml │ └── publish.yml ├── setup.py ├── README.md └── LICENSE /google_calendar_to_sqlite/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | venv 6 | .eggs 7 | .pytest_cache 8 | *.egg-info 9 | .DS_Store 10 | auth.json 11 | -------------------------------------------------------------------------------- /tests/test_google_calendar_to_sqlite.py: -------------------------------------------------------------------------------- 1 | from click.testing import CliRunner 2 | from google_calendar_to_sqlite.cli import cli 3 | 4 | 5 | def test_version(): 6 | runner = CliRunner() 7 | with runner.isolated_filesystem(): 8 | result = runner.invoke(cli, ["--version"]) 9 | assert result.exit_code == 0 10 | assert result.output.startswith("cli, version ") 11 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Test 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | strategy: 9 | matrix: 10 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] 11 | steps: 12 | - uses: actions/checkout@v3 13 | - name: Set up Python ${{ matrix.python-version }} 14 | uses: actions/setup-python@v3 15 | with: 16 | python-version: ${{ matrix.python-version }} 17 | - uses: actions/cache@v3 18 | name: Configure pip caching 19 | with: 20 | path: ~/.cache/pip 21 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 22 | restore-keys: | 23 | ${{ runner.os }}-pip- 24 | - name: Install dependencies 25 | run: | 26 | pip install -e '.[test]' 27 | - name: Run tests 28 | run: | 29 | pytest 30 | - name: Check if cog needs to be run 31 | run: | 32 | cog --check README.md 33 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | import os 3 | 4 | VERSION = "0.1a0" 5 | 6 | 7 | def get_long_description(): 8 | with open( 9 | os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md"), 10 | encoding="utf8", 11 | ) as fp: 12 | return fp.read() 13 | 14 | 15 | setup( 16 | name="google-calendar-to-sqlite", 17 | description="Create a SQLite database containing your data from Google Calendar", 18 | long_description=get_long_description(), 19 | long_description_content_type="text/markdown", 20 | author="Simon Willison", 21 | url="https://github.com/simonw/google-calendar-to-sqlite", 22 | project_urls={ 23 | "Issues": "https://github.com/simonw/google-calendar-to-sqlite/issues", 24 | "CI": "https://github.com/simonw/google-calendar-to-sqlite/actions", 25 | "Changelog": "https://github.com/simonw/google-calendar-to-sqlite/releases", 26 | }, 27 | license="Apache License, Version 2.0", 28 | version=VERSION, 29 | packages=["google_calendar_to_sqlite"], 30 | entry_points=""" 31 | [console_scripts] 32 | google-calendar-to-sqlite=google_calendar_to_sqlite.cli:cli 33 | """, 34 | install_requires=["click", "httpx", "sqlite-utils"], 35 | extras_require={"test": ["pytest", "pytest-httpx", "pytest-mock", "cogapp"]}, 36 | python_requires=">=3.6", 37 | ) 38 | -------------------------------------------------------------------------------- /.github/workflows/publish.yml: -------------------------------------------------------------------------------- 1 | name: Publish Python Package 2 | 3 | on: 4 | release: 5 | types: [created] 6 | 7 | jobs: 8 | test: 9 | runs-on: ubuntu-latest 10 | strategy: 11 | matrix: 12 | python-version: ["3.6", "3.7", "3.8", "3.9", "3.10"] 13 | steps: 14 | - uses: actions/checkout@v3 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v3 17 | with: 18 | python-version: ${{ matrix.python-version }} 19 | - uses: actions/cache@v3 20 | name: Configure pip caching 21 | with: 22 | path: ~/.cache/pip 23 | key: ${{ runner.os }}-pip-${{ hashFiles('**/setup.py') }} 24 | restore-keys: | 25 | ${{ runner.os }}-pip- 26 | - name: Install dependencies 27 | run: | 28 | pip install -e '.[test]' 29 | - name: Run tests 30 | run: | 31 | pytest 32 | deploy: 33 | runs-on: ubuntu-latest 34 | needs: [test] 35 | steps: 36 | - uses: actions/checkout@v3 37 | - name: Set up Python 38 | uses: actions/setup-python@v2 39 | with: 40 | python-version: "3.10" 41 | - uses: actions/cache@v3 42 | name: Configure pip caching 43 | with: 44 | path: ~/.cache/pip 45 | key: ${{ runner.os }}-publish-pip-${{ hashFiles('**/setup.py') }} 46 | restore-keys: | 47 | ${{ runner.os }}-publish-pip- 48 | - name: Install dependencies 49 | run: | 50 | pip install setuptools wheel twine build 51 | - name: Publish 52 | env: 53 | TWINE_USERNAME: __token__ 54 | TWINE_PASSWORD: ${{ secrets.PYPI_TOKEN }} 55 | run: | 56 | python -m build 57 | twine upload dist/* 58 | 59 | -------------------------------------------------------------------------------- /google_calendar_to_sqlite/utils.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | import click 3 | import httpx 4 | import itertools 5 | from time import sleep 6 | 7 | 8 | class APIClient: 9 | class Error(click.ClickException): 10 | pass 11 | 12 | timeout = 30.0 13 | 14 | def __init__(self, refresh_token, client_id, client_secret, logger=None): 15 | self.refresh_token = refresh_token 16 | self.access_token = None 17 | self.client_id = client_id 18 | self.client_secret = client_secret 19 | self.log = logger or (lambda s: None) 20 | 21 | def get_access_token(self, force_refresh=False): 22 | if self.access_token and not force_refresh: 23 | return self.access_token 24 | url = "https://www.googleapis.com/oauth2/v4/token" 25 | self.log("POST {}".format(url)) 26 | data = httpx.post( 27 | url, 28 | data={ 29 | "grant_type": "refresh_token", 30 | "refresh_token": self.refresh_token, 31 | "client_id": self.client_id, 32 | "client_secret": self.client_secret, 33 | }, 34 | timeout=self.timeout, 35 | ).json() 36 | if "error" in data: 37 | raise self.Error(str(data)) 38 | self.access_token = data["access_token"] 39 | return self.access_token 40 | 41 | def get( 42 | self, 43 | url, 44 | params=None, 45 | headers=None, 46 | allow_token_refresh=True, 47 | transport_retries=2, 48 | ): 49 | headers = headers or {} 50 | headers["Authorization"] = "Bearer {}".format(self.get_access_token()) 51 | self.log("GET: {} {}".format(url, params or "").strip()) 52 | try: 53 | response = httpx.get( 54 | url, params=params, headers=headers, timeout=self.timeout 55 | ) 56 | except httpx.TransportError as ex: 57 | if transport_retries: 58 | sleep(2) 59 | self.log(" Got {}, retrying".format(ex.__class__.__name__)) 60 | return self.get( 61 | url, 62 | params, 63 | headers, 64 | allow_token_refresh=allow_token_refresh, 65 | transport_retries=transport_retries - 1, 66 | ) 67 | else: 68 | raise 69 | 70 | if response.status_code == 401 and allow_token_refresh: 71 | # Try again after refreshing the token 72 | self.get_access_token(force_refresh=True) 73 | return self.get(url, params, headers, allow_token_refresh=False) 74 | return response 75 | 76 | def post(self, url, data=None, headers=None, allow_token_refresh=True): 77 | headers = headers or {} 78 | headers["Authorization"] = "Bearer {}".format(self.get_access_token()) 79 | self.log("POST: {}".format(url)) 80 | response = httpx.post(url, data=data, headers=headers, timeout=self.timeout) 81 | if response.status_code == 403 and allow_token_refresh: 82 | self.get_access_token(force_refresh=True) 83 | return self.post(url, data, headers, allow_token_refresh=False) 84 | return response 85 | 86 | @contextmanager 87 | def stream(self, method, url, params=None): 88 | with httpx.stream( 89 | method, 90 | url, 91 | params=params, 92 | headers={"Authorization": "Bearer {}".format(self.get_access_token())}, 93 | ) as stream: 94 | yield stream 95 | 96 | 97 | def paginate_all(client, url, pagination_key): 98 | next_page_token = None 99 | while True: 100 | params = {} 101 | if next_page_token is not None: 102 | params["pageToken"] = next_page_token 103 | response = client.get( 104 | url, 105 | params=params, 106 | ) 107 | data = response.json() 108 | if response.status_code != 200: 109 | raise click.ClickException(json.dumps(data, indent=4)) 110 | # Paginate using the specified key and nextPageToken 111 | if pagination_key not in data: 112 | raise click.ClickException( 113 | "paginate key {} not found in {}".format( 114 | repr(pagination_key), repr(list(data.keys())) 115 | ) 116 | ) 117 | yield from data[pagination_key] 118 | 119 | next_page_token = data.get("nextPageToken") 120 | if not next_page_token: 121 | break 122 | 123 | 124 | def flatten_keys(d, keys=None): 125 | for key, value in d.items(): 126 | if isinstance(value, dict) and keys is not None and key in keys: 127 | for key2, value2 in flatten_keys(value): 128 | yield key + "_" + key2, value2 129 | else: 130 | yield key, value 131 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # google-calendar-to-sqlite 2 | 3 | [![PyPI](https://img.shields.io/pypi/v/google-calendar-to-sqlite.svg)](https://pypi.org/project/google-calendar-to-sqlite/) 4 | [![Changelog](https://img.shields.io/github/v/release/simonw/google-calendar-to-sqlite?include_prereleases&label=changelog)](https://github.com/simonw/google-calendar-to-sqlite/releases) 5 | [![Tests](https://github.com/simonw/google-calendar-to-sqlite/workflows/Test/badge.svg)](https://github.com/simonw/google-calendar-to-sqlite/actions?query=workflow%3ATest) 6 | [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/simonw/google-calendar-to-sqlite/blob/master/LICENSE) 7 | 8 | Create a SQLite database containing your data from [Google Calendar](https://www.google.com/calendar) 9 | 10 | This lets you use SQL to analyze your Google Calendar data, using [Datasette](https://datasette.io/) or the SQLite command-line tool or any other SQLite database browsing software. 11 | 12 | ## Installation 13 | 14 | Install this tool using `pip`: 15 | 16 | pip install google-calendar-to-sqlite 17 | 18 | ## Quickstart 19 | 20 | Authenticate with Google Calendar by running: 21 | 22 | google-calendar-to-sqlite auth 23 | 24 | Now create a SQLite database containing your calendar data with: 25 | 26 | google-calendar-to-sqlite events calendar.db your-email@gmail.com 27 | 28 | You can pass one or more calendar IDs - these look like email addresses. Your primary Gmail account corresponds to your personal calendar. 29 | 30 | If you pass no calendar IDs this will fetch events from all of your calendars: 31 | 32 | google-calendar-to-sqlite events calendar.db 33 | 34 | This command will create an `events` table with a row for each event. Repeating events will appoar only once, with their recurrence rules stored in the `recurrence` column. 35 | 36 | You can explore the resulting database using [Datasette](https://datasette.io/): 37 | 38 | $ pip install datasette 39 | $ datasette calendar.db 40 | INFO: Started server process [24661] 41 | INFO: Uvicorn running on http://127.0.0.1:8001 42 | 43 | ## See a list of calendars 44 | 45 | You can see a list of your calendars using: 46 | 47 | google-calendar-to-sqlite calendars 48 | 49 | This will output their ID and name to the terminal: 50 | 51 | $ google-calendar-to-sqlite calendars 52 | Work: 2mcbt9bcthbvsm21j4rp4drhs8@group.calendar.google.com 53 | Simon Stanford Classes: tsblj5a6il733cd92kv08crkrg@group.calendar.google.com 54 | Pillar Point Stewards: tqhbk05br2h57kcd0gebbt9nmoq3iebt@import.calendar.google.com 55 | Holidays in United States: en.usa#holiday@group.v.calendar.google.com 56 | 57 | If you add a database filename that list will be used to populate a detailed `calendars` table: 58 | 59 | google-calendar-to-sqlite calendars calendar.db 60 | 61 | Events in that same database will have foreign keys back to the calendar they belong to. 62 | 63 | ## Authentication 64 | 65 | > :warning: **This application has not yet been verified by Google** - you may find you are unable to authenticate until that verification is complete. 66 | > 67 | > You can work around this issue by [creating your own OAuth client ID key](https://til.simonwillison.net/googlecloud/google-oauth-cli-application) and passing it to the `auth` command using `--google-client-id` and `--google-client-secret`. 68 | 69 | First, authenticate with Google Calendar using the `auth` command: 70 | 71 | $ google-calendar-to-sqlite auth 72 | Visit the following URL to authenticate with Google Calendar 73 | 74 | https://accounts.google.com/o/oauth2/v2/auth?... 75 | 76 | Then return here and paste in the resulting code: 77 | Paste code here: 78 | 79 | Follow the link, sign in with Google Calendar and then copy and paste the resulting code back into the tool. 80 | 81 | This will save an authentication token to the file called `auth.json` in the current directory. 82 | 83 | To specify a different location for that file, use the `--auth` option: 84 | 85 | google-calendar-to-sqlite auth --auth ~/google-calendar-auth.json 86 | 87 | Full `--help`: 88 | 89 | 100 | ``` 101 | Usage: google-calendar-to-sqlite auth [OPTIONS] 102 | 103 | Authenticate user and save credentials 104 | 105 | Options: 106 | -a, --auth FILE Path to save token, defaults to auth.json 107 | --google-client-id TEXT Custom Google client ID 108 | --google-client-secret TEXT Custom Google client secret 109 | --scope TEXT Custom token scope 110 | --help Show this message and exit. 111 | 112 | ``` 113 | 114 | 115 | To revoke the token that is stored in `auth.json`, such that it cannot be used to access Google Calendar in the future, run the `revoke` command: 116 | 117 | google-calendar-to-sqlite revoke 118 | 119 | Or if your token is stored in another location: 120 | 121 | google-calendar-to-sqlite revoke -a ~/google-calendar-auth.json 122 | 123 | You will need to obtain a fresh token using the `auth` command in order to continue using this tool. 124 | 125 | 126 | ## Database schema 127 | 128 | The database created by this tool has the following schema: 129 | 130 | ```sql 131 | CREATE TABLE [calendars] ( 132 | [id] TEXT PRIMARY KEY, 133 | [name] TEXT, 134 | [description] TEXT, 135 | [kind] TEXT, 136 | [etag] TEXT, 137 | [summary] TEXT, 138 | [timeZone] TEXT, 139 | [colorId] TEXT, 140 | [backgroundColor] TEXT, 141 | [foregroundColor] TEXT, 142 | [accessRole] TEXT, 143 | [defaultReminders] TEXT, 144 | [conferenceProperties] TEXT, 145 | [location] TEXT, 146 | [selected] INTEGER, 147 | [summaryOverride] TEXT, 148 | [notificationSettings] TEXT, 149 | [primary] INTEGER 150 | ); 151 | CREATE TABLE [events] ( 152 | [id] TEXT PRIMARY KEY, 153 | [summary] TEXT, 154 | [location] TEXT, 155 | [start_dateTime] TEXT, 156 | [end_dateTime] TEXT, 157 | [description] TEXT, 158 | [calendar_id] TEXT REFERENCES [calendars]([id]), 159 | [kind] TEXT, 160 | [etag] TEXT, 161 | [status] TEXT, 162 | [htmlLink] TEXT, 163 | [created] TEXT, 164 | [updated] TEXT, 165 | [creator] TEXT, 166 | [organizer] TEXT, 167 | [iCalUID] TEXT, 168 | [sequence] INTEGER, 169 | [reminders] TEXT, 170 | [eventType] TEXT, 171 | [attendees] TEXT, 172 | [recurringEventId] TEXT, 173 | [originalStartTime] TEXT, 174 | [start_date] TEXT, 175 | [end_date] TEXT, 176 | [transparency] TEXT, 177 | [start_timeZone] TEXT, 178 | [end_timeZone] TEXT, 179 | [recurrence] TEXT, 180 | [guestsCanInviteOthers] INTEGER, 181 | [extendedProperties] TEXT, 182 | [colorId] TEXT, 183 | [hangoutLink] TEXT, 184 | [conferenceData] TEXT, 185 | [visibility] TEXT, 186 | [privateCopy] INTEGER, 187 | [guestsCanSeeOtherGuests] INTEGER, 188 | [attachments] TEXT 189 | ); 190 | ``` 191 | 192 | ## Privacy policy 193 | 194 | This tool requests access to your Google Calendar account in order to retrieve events from your calendar and store them in a local SQLite database file on your machine. 195 | 196 | The credentials used to access your account are stored in the `auth.json` file on your computer. The data retrieved from Google Calendar is also stored only on your own personal computer. 197 | 198 | At no point do the developers of this tool gain access to any of your data. 199 | 200 | ## Development 201 | 202 | To contribute to this tool, first checkout the code. Then create a new virtual environment: 203 | 204 | cd google-calendar-to-sqlite 205 | python -m venv venv 206 | source venv/bin/activate 207 | 208 | Or if you are using `pipenv`: 209 | 210 | pipenv shell 211 | 212 | Now install the dependencies and test dependencies: 213 | 214 | pip install -e '.[test]' 215 | 216 | To run the tests: 217 | 218 | pytest 219 | -------------------------------------------------------------------------------- /google_calendar_to_sqlite/cli.py: -------------------------------------------------------------------------------- 1 | from os import access 2 | import click 3 | from http.server import BaseHTTPRequestHandler, HTTPServer 4 | import httpx 5 | import itertools 6 | import json 7 | import pathlib 8 | import sqlite_utils 9 | import sys 10 | import textwrap 11 | import urllib.parse 12 | from .utils import ( 13 | APIClient, 14 | paginate_all, 15 | flatten_keys, 16 | ) 17 | 18 | GOOGLE_CLIENT_ID = ( 19 | "184325416553-nu5ci563v36rmj9opdl7mah786anbkrq.apps.googleusercontent.com" 20 | ) 21 | # It's OK to publish this secret in application source code 22 | GOOGLE_CLIENT_SECRET = "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" 23 | DEFAULT_SCOPE = "https://www.googleapis.com/auth/calendar.readonly" 24 | 25 | 26 | def start_auth_url(google_client_id, scope): 27 | return "https://accounts.google.com/o/oauth2/v2/auth?" + urllib.parse.urlencode( 28 | { 29 | "access_type": "offline", 30 | "client_id": google_client_id, 31 | "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", 32 | "response_type": "code", 33 | "scope": scope, 34 | } 35 | ) 36 | 37 | 38 | @click.group() 39 | @click.version_option() 40 | def cli(): 41 | "Create a SQLite database containing your data from Google Calendar" 42 | 43 | 44 | @cli.command() 45 | @click.argument( 46 | "database", 47 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 48 | required=False, 49 | ) 50 | @click.option( 51 | "-a", 52 | "--auth", 53 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 54 | default="auth.json", 55 | help="Path to load token, defaults to auth.json", 56 | ) 57 | @click.option( 58 | "-v", 59 | "--verbose", 60 | is_flag=True, 61 | help="Send verbose output to stderr", 62 | ) 63 | def calendars(database, auth, verbose): 64 | db = sqlite_utils.Database(database or ":memory:") 65 | kwargs = load_tokens(auth) 66 | if verbose: 67 | kwargs["logger"] = lambda s: click.echo(s, err=True) 68 | client = APIClient(**kwargs) 69 | url = "https://www.googleapis.com/calendar/v3/users/me/calendarList" 70 | calendars = paginate_all(client, url, "items") 71 | db["calendars"].upsert_all( 72 | (dict(calendar, name=calendar["summary"]) for calendar in calendars), 73 | pk="id", 74 | column_order=("id", "name", "description"), 75 | ) 76 | click.echo( 77 | "\n".join( 78 | "{name}: {id}".format(**calendar) for calendar in db["calendars"].rows 79 | ) 80 | ) 81 | 82 | 83 | @cli.command() 84 | @click.argument( 85 | "database", 86 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 87 | ) 88 | @click.argument("calendars", nargs=-1) 89 | @click.option( 90 | "-a", 91 | "--auth", 92 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 93 | default="auth.json", 94 | help="Path to load token, defaults to auth.json", 95 | ) 96 | @click.option( 97 | "-v", 98 | "--verbose", 99 | is_flag=True, 100 | help="Send verbose output to stderr", 101 | ) 102 | def events(database, calendars, auth, verbose): 103 | db = sqlite_utils.Database(database) 104 | kwargs = load_tokens(auth) 105 | if verbose: 106 | kwargs["logger"] = lambda s: click.echo(s, err=True) 107 | client = APIClient(**kwargs) 108 | 109 | if not calendars: 110 | # Do all of them 111 | calendars = [ 112 | c["id"] 113 | for c in client.get( 114 | "https://www.googleapis.com/calendar/v3/users/me/calendarList" 115 | ).json()["items"] 116 | ] 117 | 118 | for calendar_id in calendars: 119 | url = "https://www.googleapis.com/calendar/v3/calendars/{}/events".format( 120 | calendar_id 121 | ) 122 | events = paginate_all(client, url, "items") 123 | db["calendars"].upsert( 124 | { 125 | "id": calendar_id, 126 | }, 127 | pk="id", 128 | ) 129 | # Flatten specific keys 130 | events = ( 131 | dict(flatten_keys(dict(event, calendar_id=calendar_id), ("start", "end"))) 132 | for event in events 133 | ) 134 | db["events"].insert_all( 135 | events, 136 | pk="id", 137 | column_order=( 138 | "id", 139 | "summary", 140 | "location", 141 | "start_dateTime", 142 | "end_dateTime", 143 | "description", 144 | "calendar_id", 145 | ), 146 | alter=True, 147 | foreign_keys=(("calendar_id", "calendars", "id"),), 148 | ) 149 | 150 | 151 | @cli.command() 152 | @click.option( 153 | "-a", 154 | "--auth", 155 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 156 | default="auth.json", 157 | help="Path to save token, defaults to auth.json", 158 | ) 159 | @click.option("--google-client-id", help="Custom Google client ID") 160 | @click.option("--google-client-secret", help="Custom Google client secret") 161 | @click.option("--scope", help="Custom token scope") 162 | def auth(auth, google_client_id, google_client_secret, scope): 163 | "Authenticate user and save credentials" 164 | if google_client_id is None: 165 | google_client_id = GOOGLE_CLIENT_ID 166 | if google_client_secret is None: 167 | google_client_secret = GOOGLE_CLIENT_SECRET 168 | if scope is None: 169 | scope = DEFAULT_SCOPE 170 | 171 | click.echo("Visit the following URL to authenticate with Google Calendar") 172 | click.echo("") 173 | click.echo(start_auth_url(google_client_id, scope)) 174 | click.echo("") 175 | click.echo("Then return here and paste in the resulting code:") 176 | copied_code = click.prompt("Paste code here", hide_input=True) 177 | response = httpx.post( 178 | "https://www.googleapis.com/oauth2/v4/token", 179 | data={ 180 | "code": copied_code, 181 | "client_id": google_client_id, 182 | "client_secret": google_client_secret, 183 | "redirect_uri": "urn:ietf:wg:oauth:2.0:oob", 184 | "grant_type": "authorization_code", 185 | }, 186 | ) 187 | tokens = response.json() 188 | if "error" in tokens: 189 | message = "{error}: {error_description}".format(**tokens) 190 | raise click.ClickException(message) 191 | if "refresh_token" not in tokens: 192 | raise click.ClickException("No refresh_token in response") 193 | # Read existing file and add refresh_token to it 194 | try: 195 | auth_data = json.load(open(auth)) 196 | except (ValueError, FileNotFoundError): 197 | auth_data = {} 198 | info = {"refresh_token": tokens["refresh_token"]} 199 | if google_client_id != GOOGLE_CLIENT_ID: 200 | info["google_client_id"] = google_client_id 201 | if google_client_secret != GOOGLE_CLIENT_SECRET: 202 | info["google_client_secret"] = google_client_secret 203 | if scope != DEFAULT_SCOPE: 204 | info["scope"] = scope 205 | auth_data["google-calendar-to-sqlite"] = info 206 | with open(auth, "w") as fp: 207 | fp.write(json.dumps(auth_data, indent=4)) 208 | # chmod 600 to avoid other users on the shared machine reading it 209 | pathlib.Path(auth).chmod(0o600) 210 | 211 | 212 | @cli.command() 213 | @click.option( 214 | "-a", 215 | "--auth", 216 | type=click.Path(file_okay=True, dir_okay=False, allow_dash=False), 217 | default="auth.json", 218 | help="Path to load token, defaults to auth.json", 219 | ) 220 | def revoke(auth): 221 | "Revoke the token stored in auth.json" 222 | tokens = load_tokens(auth) 223 | response = httpx.get( 224 | "https://accounts.google.com/o/oauth2/revoke", 225 | params={ 226 | "token": tokens["refresh_token"], 227 | }, 228 | ) 229 | if "error" in response.json(): 230 | raise click.ClickException(response.json()["error"]) 231 | 232 | 233 | def load_tokens(auth): 234 | try: 235 | token_info = json.load(open(auth))["google-calendar-to-sqlite"] 236 | except (KeyError, FileNotFoundError): 237 | raise click.ClickException( 238 | "Could not find google-calendar-to-sqlite in auth.json" 239 | ) 240 | return { 241 | "refresh_token": token_info["refresh_token"], 242 | "client_id": token_info.get("google_client_id", GOOGLE_CLIENT_ID), 243 | "client_secret": token_info.get("google_client_secret", GOOGLE_CLIENT_SECRET), 244 | } 245 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------