habulaj commited on
Commit
bb722bb
·
verified ·
1 Parent(s): f8788d9

Create notifications.py

Browse files
Files changed (1) hide show
  1. routes/notifications.py +98 -0
routes/notifications.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import aiohttp
3
+ from fastapi import APIRouter, HTTPException, Header
4
+ from pydantic import BaseModel
5
+ from google.oauth2 import service_account
6
+ from google.auth.transport.requests import Request
7
+
8
+ router = APIRouter()
9
+
10
+ # Supabase Config
11
+ SUPABASE_URL = "https://ussxqnifefkgkaumjann.supabase.co"
12
+ SUPABASE_KEY = os.getenv("SUPA_KEY")
13
+ SUPABASE_SERVICE_KEY = os.getenv("SUPA_SERVICE_KEY")
14
+
15
+ if not SUPABASE_KEY or not SUPABASE_SERVICE_KEY:
16
+ raise ValueError("❌ SUPA_KEY or SUPA_SERVICE_KEY not set in environment!")
17
+
18
+ SUPABASE_HEADERS = {
19
+ "apikey": SUPABASE_SERVICE_KEY,
20
+ "Authorization": f"Bearer {SUPABASE_SERVICE_KEY}",
21
+ "Content-Type": "application/json"
22
+ }
23
+
24
+ # Firebase config
25
+ SERVICE_ACCOUNT_FILE = './closetcoach-2d50b-firebase-adminsdk-fbsvc-7fcccbacb1.json'
26
+ FCM_PROJECT_ID = "closetcoach-2d50b"
27
+
28
+ # Request body
29
+ class SimpleNotification(BaseModel):
30
+ target: str # "all" or user ID
31
+ title: str
32
+ content: str
33
+ image_url: str = ""
34
+
35
+ # Firebase Auth
36
+ def get_fcm_access_token():
37
+ credentials = service_account.Credentials.from_service_account_file(
38
+ SERVICE_ACCOUNT_FILE
39
+ )
40
+ scoped = credentials.with_scopes(
41
+ ['https://www.googleapis.com/auth/firebase.messaging']
42
+ )
43
+ scoped.refresh(Request())
44
+ return scoped.token
45
+
46
+ # Fetch user info from Supabase
47
+ async def get_user(user_id: str):
48
+ url = f"{SUPABASE_URL}/rest/v1/User?id=eq.{user_id}&select=id,token_fcm,manage_notifications"
49
+ async with aiohttp.ClientSession() as session:
50
+ async with session.get(url, headers=SUPABASE_HEADERS) as resp:
51
+ if resp.status != 200:
52
+ raise HTTPException(status_code=resp.status, detail="Failed to fetch user info")
53
+ data = await resp.json()
54
+ return data[0] if data else None
55
+
56
+ @router.post("/send-global-notification")
57
+ async def send_global_notification(
58
+ payload: SimpleNotification,
59
+ user_id: str = Header(..., alias="User-id")
60
+ ):
61
+ # Autorização
62
+ sender = await get_user(user_id)
63
+ if not sender or not sender.get("manage_notifications"):
64
+ raise HTTPException(status_code=403, detail="Not authorized to send notifications")
65
+
66
+ message = {
67
+ "notification": {
68
+ "title": payload.title,
69
+ "body": payload.content
70
+ }
71
+ }
72
+
73
+ if payload.image_url:
74
+ message["notification"]["image"] = payload.image_url
75
+
76
+ if payload.target == "all":
77
+ message["topic"] = "all"
78
+ else:
79
+ # Busca o token FCM do usuário de destino
80
+ target_user = await get_user(payload.target)
81
+ if not target_user or not target_user.get("token_fcm"):
82
+ raise HTTPException(status_code=404, detail="Target user or FCM token not found")
83
+ message["token"] = target_user["token_fcm"]
84
+
85
+ # Enviar para Firebase
86
+ access_token = get_fcm_access_token()
87
+ headers = {
88
+ "Authorization": f"Bearer {access_token}",
89
+ "Content-Type": "application/json"
90
+ }
91
+ url = f"https://fcm.googleapis.com/v1/projects/{FCM_PROJECT_ID}/messages:send"
92
+
93
+ async with aiohttp.ClientSession() as session:
94
+ async with session.post(url, headers=headers, json={"message": message}) as resp:
95
+ response_text = await resp.text()
96
+ if resp.status != 200:
97
+ raise HTTPException(status_code=resp.status, detail=f"FCM error: {response_text}")
98
+ return {"detail": "Notification sent successfully"}