Skip to content

Commit

Permalink
webhook events to API
Browse files Browse the repository at this point in the history
  • Loading branch information
voynow committed Nov 13, 2024
1 parent 8f91a2d commit 78cb79b
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 25 deletions.
35 changes: 30 additions & 5 deletions api/src/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import logging
from typing import Optional

from fastapi import Body, Depends, FastAPI, HTTPException
from fastapi import BackgroundTasks, Body, Depends, FastAPI, HTTPException, Request
from src import activities, auth_manager, supabase_client
from src.types.training_week import TrainingWeek
from src.types.user import UserRow
from src.types.webhook import StravaEvent

app = FastAPI()

Expand Down Expand Up @@ -112,9 +113,7 @@ async def get_weekly_summaries(
weekly_summaries = activities.get_weekly_summaries(strava_client)
return {
"success": True,
"weekly_summaries": [
summary.json() for summary in weekly_summaries
],
"weekly_summaries": [summary.json() for summary in weekly_summaries],
}
except Exception as e:
logger.error(f"Failed to get weekly summaries: {e}", exc_info=True)
Expand All @@ -125,7 +124,7 @@ async def get_weekly_summaries(
async def authenticate(code: str, email: Optional[str] = None) -> dict:
"""
Authenticate with Strava code and sign up new users
:param code: Strava authorization code
:param email: User's email (optional)
:return: Dictionary with success status, JWT token and new user flag
Expand All @@ -135,3 +134,29 @@ async def authenticate(code: str, email: Optional[str] = None) -> dict:
except Exception as e:
logger.error(f"Authentication failed: {e}", exc_info=True)
raise HTTPException(status_code=400, detail=str(e))





def process_strava_event(event: StravaEvent):
"""
Process the Strava webhook event. Perform any updates based on the event data.
"""
# Replace this with your Strava-specific logic (e.g., updating training week)
logger.info(f"Processing event: {event}")
# Simulate some processing or call any required functions
# For example, handle_activity_create(user, event)


@app.post("/strava/webhook")
async def strava_webhook(request: Request, background_tasks: BackgroundTasks):
event = await request.json()
logger.info(f"Received Strava webhook event: {event}")

# Validate event and start processing in background
strava_event = StravaEvent(**event)
background_tasks.add_task(process_strava_event, strava_event)

# Immediate response to Strava
return {"status": "received"}
9 changes: 9 additions & 0 deletions api/src/types/webhook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from pydantic import BaseModel


class StravaEvent(BaseModel):
subscription_id: int
aspect_type: str
object_type: str
object_id: int
owner_id: int
6 changes: 1 addition & 5 deletions lambda/src/lambda_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import traceback
import uuid

from src import auth_manager, frontend_router, update_pipeline, webhook_router
from src import frontend_router, update_pipeline
from src.email_manager import send_alert_email

logging.getLogger("openai").setLevel(logging.ERROR)
Expand Down Expand Up @@ -33,10 +33,6 @@ def strategy_router(event: dict) -> dict:
method=event["method"],
payload=event.get("payload"),
)

elif webhook_router.is_strava_webhook_event(event):
return webhook_router.handle_request(event)

elif (
event.get("resources")
and event.get("resources")[0] == os.environ["NIGHTLY_EMAIL_TRIGGER_ARN"]
Expand Down
31 changes: 16 additions & 15 deletions web/src/app/strava_webhook/route.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import AWS from 'aws-sdk';
// web/src/app/strava_webhook/route.tsx
import { NextRequest, NextResponse } from 'next/server';

const sqs = new AWS.SQS({
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: 'us-east-1',
});

export async function GET(request: NextRequest) {
const searchParams = request.nextUrl.searchParams;
const mode = searchParams.get('hub.mode');
Expand All @@ -28,17 +22,24 @@ export async function POST(request: NextRequest) {
const event = await request.json();
console.log(`Received POST request with event: ${JSON.stringify(event)}`);

const params = {
QueueUrl: 'https://sqs.us-east-1.amazonaws.com/498969721544/trackflow-webhook-msg-queue',
MessageBody: JSON.stringify(event),
};

try {
const data = await sqs.sendMessage(params).promise();
console.log(`Message sent to SQS with ID: ${data.MessageId}`);
const response = await fetch('http://trackflow-alb-499532887.us-east-1.elb.amazonaws.com/strava-webhook', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(event),
});

if (!response.ok) {
console.error(`Error sending event to FastAPI: ${response.statusText}`);
return new NextResponse(`Error sending event to FastAPI: ${response.statusText}`, { status: 500 });
}

console.log(`Event successfully sent to FastAPI.`);
} catch (err) {
console.error(`Error sending message to SQS: ${err}`);
console.error(`Error sending event to FastAPI: ${err}`);
return new NextResponse(`Error: ${err}`, { status: 500 });
}

// Immediate response to Strava
return NextResponse.json({}, { status: 200 });
}

0 comments on commit 78cb79b

Please sign in to comment.