parent
506e879334
commit
6ef3f1c6f7
@ -0,0 +1,57 @@
|
||||
# Push notifications
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Body
|
||||
import pymongo
|
||||
|
||||
import app.config as config
|
||||
from app.models import User, HTTPError, PushSubscription
|
||||
from app.routes.utils import get_current_user
|
||||
|
||||
# Database setup
|
||||
client = pymongo.MongoClient(config.MONGODB_URL, username=config.MONGODB_USERNAME, password=config.MONGODB_PASSWORD)
|
||||
db = client[config.MONGODB_DATABASE]
|
||||
|
||||
users_collection = db["users"]
|
||||
|
||||
push_router = APIRouter(
|
||||
tags=["Push"]
|
||||
)
|
||||
|
||||
@push_router.post(
|
||||
path="/push/subscribe",
|
||||
responses={401: {"model": HTTPError}}
|
||||
)
|
||||
async def subscribe(subscription: PushSubscription, current_user: User = Depends(get_current_user)):
|
||||
user_exists = users_collection.find_one({"username": current_user.username})
|
||||
if not user_exists:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="User not found"
|
||||
)
|
||||
|
||||
# Convert the subscription to a JSON string
|
||||
subscription_str = subscription.model_dump_json()
|
||||
|
||||
# Check if the subscription is already in the database
|
||||
if users_collection.find_one({"push_subscriptions": subscription_str}):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Subscription already exists"
|
||||
)
|
||||
|
||||
# Check if already has a subscription
|
||||
if user_exists.get("push_subscriptions"):
|
||||
# Add another subscription
|
||||
users_collection.update_one(
|
||||
{"username": current_user.username},
|
||||
{"$push": {"push_subscriptions": subscription_str}}
|
||||
)
|
||||
else:
|
||||
# Add the subscription
|
||||
users_collection.update_one(
|
||||
{"username": current_user.username},
|
||||
{"$set": {"push_subscriptions": [subscription_str]}}
|
||||
)
|
||||
|
||||
return {
|
||||
"message": "Push subscription successful"
|
||||
}
|
Loading…
Reference in new issue