Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
1276b7a
Update mailer attachments and ics file handling
davinotdavid Feb 23, 2026
1823cdd
Add insert_event method to GoogleClient and format body accordingly
davinotdavid Feb 23, 2026
f965c5d
Split logic between Google accounts vs non-Google accounts
davinotdavid Feb 23, 2026
ce53dc2
Update google connector tests
davinotdavid Feb 23, 2026
bba6711
Add google_calendar_channels table and model repo methods
davinotdavid Feb 24, 2026
1e212e0
Implement Google Calendar's Push Notifications API methods
davinotdavid Feb 24, 2026
ebb8bed
Add POST to /google-calendar as webhook to receive calendar notificat…
davinotdavid Feb 24, 2026
b7452bc
Setup watch channels when connecting a google account
davinotdavid Feb 24, 2026
1b8d5a8
Move google calendar watch methods into its own controller
davinotdavid Feb 24, 2026
6aea4a1
Setup and teadown watch channels when calendar connection changes
davinotdavid Feb 24, 2026
034d50c
Add backfill (to be ran once) and renew (periodically) to maintain ex…
davinotdavid Feb 24, 2026
12ae74d
Add tests
davinotdavid Feb 24, 2026
106fc7e
Fix lint
davinotdavid Feb 25, 2026
2e85bf1
Create google events as tentative and add patch_event method
davinotdavid Mar 6, 2026
8573587
Skip HOLD event for Google events, and confirm through event through …
davinotdavid Mar 6, 2026
d8c1b68
Only care about the declined in webhook
davinotdavid Mar 6, 2026
acfa2d2
Update tests
davinotdavid Mar 6, 2026
46e1f47
Only create watch channels for default connected calendars
davinotdavid Mar 9, 2026
7ad57f8
Add tests for backfill and renew channel commands
davinotdavid Mar 9, 2026
a929403
Fix tests regarding setup and teardown of watch channels during calen…
davinotdavid Mar 9, 2026
195cfa5
Fix schedule tests to not depend on a real clock anymore
davinotdavid Mar 9, 2026
a6e85a0
Remove unnecessary setup_watch_channels_for_connection method
davinotdavid Mar 9, 2026
257c3a7
Revert changes to the ics and mailer
davinotdavid Mar 9, 2026
a46d3f2
Add Subscriber to attendee list with NeedsAction if booking_confirmation
davinotdavid Mar 9, 2026
d60de30
Subscribers actions in Google Calendar should backtrack the booking s…
davinotdavid Mar 10, 2026
18f1c67
Add tests for Susbcribers actions in Google Calendar
davinotdavid Mar 10, 2026
eb03569
Adding the organizer in the google event regardless of booking confir…
davinotdavid Mar 10, 2026
e7d32e6
Also make a remote event when there is no need to require booking con…
davinotdavid Mar 10, 2026
be50f5f
More test coverage
davinotdavid Mar 10, 2026
547b9c9
Add GOOGLE_INVITE_ENABLED env var to control feature
davinotdavid Mar 10, 2026
ce5f105
Add tests for GOOGLE_INVITE_ENABLED fallback into branded emails
davinotdavid Mar 10, 2026
508bb6f
Add or create Zoom meeting link to the invite for Google Invite flows
davinotdavid Mar 10, 2026
72651fd
Update test suite with new coverage for Zoom meeting links
davinotdavid Mar 10, 2026
096abbb
Attempt to fix CodeQL false positive in test
davinotdavid Mar 10, 2026
022371c
No need for a helper function to check for GOOGLE_INVITE_ENABLED
davinotdavid Mar 26, 2026
00b940e
Consolidate 200 successful response in a variable
davinotdavid Mar 26, 2026
ec36a80
Remove early success return in webhook in case the channel don't have…
davinotdavid Mar 26, 2026
3ff14c2
Share code for creating zoom meeting link
davinotdavid Mar 26, 2026
522e171
Update tests
davinotdavid Mar 26, 2026
eb12551
Add GOOGLE_CHANNEL_TTL_IN_SECONDS to safeguard against unexpected API…
davinotdavid Apr 1, 2026
49ecaa0
Better query for google calendars in a schedule
davinotdavid Apr 1, 2026
3b25ac0
Only sync watch channels if GOOGLE_INVITE_ENABLED is True
davinotdavid Apr 1, 2026
a9af4b1
Add state to the google_calendar_channels table, populate it and chec…
davinotdavid Apr 1, 2026
a8de1db
Better returns and erroring logs
davinotdavid Apr 1, 2026
9e669f9
Make db query do the filtering instead of looping myself
davinotdavid Apr 1, 2026
24b59dd
Update tests
davinotdavid Apr 1, 2026
1db272e
Add renewal of google channels to Celery
davinotdavid Apr 1, 2026
29c348d
(Re)fixing the schedule_calendar_ids query
davinotdavid Apr 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions backend/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ APP_ENV=dev
APP_ADMIN_ALLOW_LIST=
APP_SETUP
APP_ALLOW_FIRST_TIME_REGISTER=
# Enable Google Calendar native invites (True/False). Defaults based on APP_ENV if unset.
GOOGLE_INVITE_ENABLED=

# -- BACKEND --
BACKEND_URL=http://localhost:5000
Expand Down Expand Up @@ -95,6 +97,7 @@ GOOGLE_AUTH_CLIENT_ID=
GOOGLE_AUTH_SECRET=
GOOGLE_AUTH_PROJECT_ID=
GOOGLE_AUTH_CALLBACK=http://localhost:5000/google/callback
GOOGLE_CHANNEL_TTL_IN_SECONDS=604800 # 7 days

# -- Zoom API --
ZOOM_API_ENABLED=False
Expand Down
2 changes: 2 additions & 0 deletions backend/.env.test
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ GOOGLE_AUTH_CLIENT_ID=
GOOGLE_AUTH_SECRET=
GOOGLE_AUTH_PROJECT_ID=
GOOGLE_AUTH_CALLBACK=http://localhost:5000/google/callback
GOOGLE_CHANNEL_TTL_IN_SECONDS=604800 # 7 days

# -- TB ACCOUNTS --
TB_ACCOUNTS_CALDAV_URL=https://stage-thundermail.com
Expand All @@ -70,6 +71,7 @@ SIGNED_SECRET=test-secret-pls-ignore
SENTRY_DSN=
# Possible values: prod, dev, test
APP_ENV=test
GOOGLE_INVITE_ENABLED=True
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we have the ability to handle watch channels locally? If not then we should default this to false.

We might want to split the variables for google invites vs handling watch channels though.

# Possible values: password, fxa
AUTH_SCHEME=password

Expand Down
7 changes: 7 additions & 0 deletions backend/src/appointment/celery_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ def create_celery_app() -> Celery:
sentry_sdk.set_extra('CELERY_RESULT_EXPIRES', result_expires)
sentry_sdk.set_extra('CELERY_TASK_ALWAYS_EAGER', task_always_eager)

google_channel_ttl = float(os.getenv('GOOGLE_CHANNEL_TTL_IN_SECONDS', 604800))
google_channel_renew_interval = google_channel_ttl - 86400 # 1 day buffer

app = Celery('appointment')

app.config_from_object({
Expand All @@ -59,6 +62,10 @@ def create_celery_app() -> Celery:
'task': 'appointment.tasks.health.heartbeat',
'schedule': 60.0,
},
'renew-google-channels': {
'task': 'appointment.tasks.google.renew_google_channels',
'schedule': google_channel_renew_interval,
},
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should probably store this outside of this object, but we can do that later.

},
'beat_schedule_filename': 'celerybeat-appointment-schedule',
})
Expand Down
101 changes: 101 additions & 0 deletions backend/src/appointment/commands/backfill_google_channels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
"""One-off command to set up Google Calendar watch channels for existing connected calendars."""

import json
import logging
import uuid
from datetime import datetime, timezone

from google.oauth2.credentials import Credentials

from ..controller.google_watch import get_webhook_url
from ..database import repo, models
from ..dependencies.database import get_engine_and_session
from ..dependencies.google import get_google_client
from ..main import _common_setup


def run():
_common_setup()
google_client = get_google_client()

_, SessionLocal = get_engine_and_session()
db = SessionLocal()

webhook_url = get_webhook_url()
if not webhook_url:
print('BACKEND_URL not set, aborting.')
db.close()
return

# Find connected Google calendars that are the default in a schedule
# and don't yet have a watch channel
schedule_calendar_ids = [
s.calendar_id for s in
db.query(models.Schedule.calendar_id).filter(models.Schedule.calendar_id != None).all() # noqa: E711
]

all_calendars = db.query(models.Calendar).filter(
models.Calendar.provider == models.CalendarProvider.google,
models.Calendar.connected == True, # noqa: E712
models.Calendar.id.in_(schedule_calendar_ids),
).all()

candidates = []
for cal in all_calendars:
existing = repo.google_calendar_channel.get_by_calendar_id(db, cal.id)
if not existing:
candidates.append(cal)

print(f'Found {len(candidates)} connected Google calendar(s) without a watch channel.')

created = 0
skipped = 0
failed = 0

for calendar in candidates:
ext_conn = calendar.external_connection
if not ext_conn or not ext_conn.token:
print(f' Calendar {calendar.id}: no external connection or token, skipping.')
skipped += 1
continue

try:
token = Credentials.from_authorized_user_info(
json.loads(ext_conn.token), google_client.SCOPES
)
except Exception as e:
print(f' Calendar {calendar.id}: failed to parse token ({e}), skipping.')
skipped += 1
continue

try:
state = str(uuid.uuid4())
response = google_client.watch_events(calendar.user, webhook_url, token, state=state)
if not response:
print(f' Calendar {calendar.id}: watch_events returned no response.')
failed += 1
continue

expiration_ms = int(response.get('expiration', 0))
expiration_dt = datetime.fromtimestamp(expiration_ms / 1000, tz=timezone.utc)

sync_token = google_client.get_initial_sync_token(calendar.user, token)

repo.google_calendar_channel.create(
db,
calendar_id=calendar.id,
channel_id=response['id'],
resource_id=response['resourceId'],
expiration=expiration_dt,
state=state,
sync_token=sync_token,
)
created += 1
print(f' Calendar {calendar.id}: channel created (expires {expiration_dt}).')
except Exception as e:
print(f' Calendar {calendar.id}: failed ({e}).')
logging.error(f'[backfill_google_channels] Error for calendar {calendar.id}: {e}')
failed += 1

db.close()
print(f'\nBackfill complete: {created} created, {skipped} skipped, {failed} failed.')
87 changes: 87 additions & 0 deletions backend/src/appointment/commands/renew_google_channels.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""Renew expiring Google Calendar push notification channels.

Run periodically (e.g., daily) to ensure channels don't expire.
Google channels typically last ~7 days, so daily renewal keeps a buffer.
"""

import json
import logging
import uuid
from datetime import datetime, timedelta, timezone

from google.oauth2.credentials import Credentials

from ..controller.google_watch import get_webhook_url
from ..database import repo
from ..dependencies.database import get_engine_and_session
from ..dependencies.google import get_google_client
from ..main import _common_setup


def run():
_common_setup()
google_client = get_google_client()

_, SessionLocal = get_engine_and_session()
db = SessionLocal()

webhook_url = get_webhook_url()
if not webhook_url:
logging.error('[renew_google_channels] BACKEND_URL not set, aborting')
db.close()
return

# Renew channels that expire within the next 24 hours
threshold = datetime.now(tz=timezone.utc) + timedelta(hours=24)
channels = repo.google_calendar_channel.get_expiring(db, before=threshold)

renewed = 0
failed = 0

for channel in channels:
calendar = channel.calendar
if not calendar or not calendar.connected:
repo.google_calendar_channel.delete(db, channel)
continue

external_connection = calendar.external_connection
if not external_connection or not external_connection.token:
repo.google_calendar_channel.delete(db, channel)
continue

token = Credentials.from_authorized_user_info(
json.loads(external_connection.token), google_client.SCOPES
)

# Stop the old channel
try:
google_client.stop_channel(channel.channel_id, channel.resource_id, token)
except Exception as e:
logging.warning(f'[renew_google_channels] Failed to stop old channel {channel.channel_id}: {e}')

# Create a new channel
try:
new_state = str(uuid.uuid4())
response = google_client.watch_events(calendar.user, webhook_url, token, state=new_state)
if response:
expiration_ms = int(response.get('expiration', 0))
expiration_dt = datetime.fromtimestamp(expiration_ms / 1000, tz=timezone.utc)

repo.google_calendar_channel.update_expiration(
db,
channel,
new_channel_id=response['id'],
new_resource_id=response['resourceId'],
new_expiration=expiration_dt,
new_state=new_state,
)
renewed += 1
else:
repo.google_calendar_channel.delete(db, channel)
failed += 1
except Exception as e:
logging.error(f'[renew_google_channels] Failed to renew channel for calendar {calendar.id}: {e}')
failed += 1

db.close()
print(f'Channel renewal complete: {renewed} renewed, {failed} failed, {len(channels)} total processed')
Loading
Loading