Files
blechreiz-website/eventplanner_gcal/views.py

102 lines
2.9 KiB
Python

"""
Views for Google Calendar integration management.
"""
import logging
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
from .google_sync import (
check_if_google_callback_is_valid,
sync_from_google_to_local,
sync_from_local_to_google,
)
from .models import UserGCalCoupling
logger = logging.getLogger(__name__)
def run_sync(request):
"""Manually trigger a sync from local to Google Calendar."""
sync_from_local_to_google()
return redirect("/")
def manage(request):
"""
View for managing Google Calendar integration settings.
Allows users to enable/disable GCal sync and configure their email.
"""
if request.method == "POST":
activate = request.POST.get("activate", "0")
if activate == "1":
# Enable GCal coupling
email = request.POST.get("email", "")
if email:
UserGCalCoupling.objects.filter(user=request.user).delete()
coupling = UserGCalCoupling(user=request.user, email=email)
coupling.save()
sync_from_local_to_google()
else:
# Disable GCal coupling
UserGCalCoupling.objects.filter(user=request.user).delete()
sync_from_local_to_google()
context = {}
user_coupling = UserGCalCoupling.objects.filter(user=request.user)
context["enabled"] = user_coupling.exists()
if user_coupling.count() > 1:
logger.warning(
f"User {request.user.username} has multiple GCal couplings. "
"This should not happen."
)
if user_coupling.exists():
context["mail"] = user_coupling.first().email
return render(request, "eventplanner_gcal/management.html", context)
@csrf_exempt
def gcal_api_callback(request):
"""
Callback endpoint for Google Calendar push notifications.
This is called by Google when calendar events are updated.
"""
token = request.META.get("HTTP_X_GOOG_CHANNEL_TOKEN", "")
channel_id = request.META.get("HTTP_X_GOOG_CHANNEL_ID", "")
resource_id = request.META.get("HTTP_X_GOOG_RESOURCE_ID", "")
valid = check_if_google_callback_is_valid(token, channel_id, resource_id)
if not valid:
logger.warning(
f"Received invalid GCal callback: token={token}, "
f"channel_id={channel_id}, resource_id={resource_id}"
)
return HttpResponse("<h1>Old Channel - no update triggered</h1>")
logger.info(
f"Received Google Callback with headers - "
f"Token: {token}, ID: {channel_id}, ResID: {resource_id}"
)
result = sync_from_google_to_local()
logger.info(
f"Finished processing callback from GCal - New Information present: {result}"
)
return HttpResponse("<h1>Callback successful</h1>")
# Backwards compatibility aliases
runSync = run_sync
gcalApiCallback = gcal_api_callback