habulaj commited on
Commit
3ab8f33
·
verified ·
1 Parent(s): dd8915e

Update routes/sendnotifications.py

Browse files
Files changed (1) hide show
  1. routes/sendnotifications.py +73 -22
routes/sendnotifications.py CHANGED
@@ -125,29 +125,80 @@ async def send_notification(
125
  follower_id = await verify_user_token(user_token)
126
  target_user_id = data.target_user_id
127
 
128
- if data.keyword == "follow":
129
- # verifica se usuário alvo existe e tem token
130
- target_user = await get_user_info(target_user_id)
131
- if not target_user or not target_user.get("token_fcm"):
132
- raise HTTPException(status_code=404, detail="Usuário alvo ou token FCM não encontrado")
133
 
134
- # verifica se a relação de follow existe mesmo
135
- if not await check_follow_exists(follower_id, target_user_id):
136
- raise HTTPException(status_code=403, detail="Relação de follow não encontrada")
137
-
138
- # pega nome do follower para notificação
139
- follower = await get_user_info(follower_id)
140
- if not follower or not follower.get("name"):
141
- raise HTTPException(status_code=404, detail="Usuário follower não encontrado")
142
-
143
- follower_name = format_name(follower["name"])
144
-
145
- title = "Novo seguidor!"
146
- body = f"{follower_name} começou a seguir você."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
 
148
- fcm_response = await send_fcm_notification(title, body, target_user["token_fcm"])
 
 
 
 
 
149
 
150
- return {"detail": "Notificação de follow enviada com sucesso", "fcm_response": fcm_response}
 
 
 
 
 
151
 
152
- else:
153
- raise HTTPException(status_code=400, detail="Keyword não suportada")
 
125
  follower_id = await verify_user_token(user_token)
126
  target_user_id = data.target_user_id
127
 
128
+ if data.keyword != "follow":
129
+ raise HTTPException(status_code=400, detail="Unsupported keyword")
 
 
 
130
 
131
+ async with aiohttp.ClientSession() as session:
132
+ # Busca usuário alvo
133
+ target_user_resp = await session.get(
134
+ f"{SUPABASE_URL}/rest/v1/User?select=name,token_fcm&id=eq.{target_user_id}",
135
+ headers=SUPABASE_ROLE_HEADERS
136
+ )
137
+ if target_user_resp.status != 200:
138
+ raise HTTPException(status_code=500, detail="Failed to fetch target user")
139
+ target_users = await target_user_resp.json()
140
+ if not target_users or not target_users[0].get("token_fcm"):
141
+ raise HTTPException(status_code=404, detail="Target user or FCM token not found")
142
+ target_user = target_users[0]
143
+
144
+ # Verifica se follow existe
145
+ follow_resp = await session.get(
146
+ f"{SUPABASE_URL}/rest/v1/followers?select=id&follower_id=eq.{follower_id}&following_id=eq.{target_user_id}",
147
+ headers=SUPABASE_ROLE_HEADERS
148
+ )
149
+ if follow_resp.status != 200:
150
+ raise HTTPException(status_code=500, detail="Failed to verify follow relationship")
151
+ follow_exists = len(await follow_resp.json()) > 0
152
+ if not follow_exists:
153
+ raise HTTPException(status_code=403, detail="Follow relationship does not exist")
154
+
155
+ # Busca dados do follower
156
+ follower_resp = await session.get(
157
+ f"{SUPABASE_URL}/rest/v1/User?select=name&id=eq.{follower_id}",
158
+ headers=SUPABASE_ROLE_HEADERS
159
+ )
160
+ if follower_resp.status != 200:
161
+ raise HTTPException(status_code=500, detail="Failed to fetch follower user")
162
+ followers = await follower_resp.json()
163
+ if not followers or not followers[0].get("name"):
164
+ raise HTTPException(status_code=404, detail="Follower user not found")
165
+ follower_name = format_name(followers[0]["name"])
166
+
167
+ # Monta notificação
168
+ title = "🎉 New Follower!"
169
+ body = f"{follower_name} started following you."
170
+
171
+ # Envio da notificação com collapse_key para evitar spam
172
+ payload = {
173
+ "message": {
174
+ "notification": {
175
+ "title": title,
176
+ "body": body,
177
+ },
178
+ "token": target_user["token_fcm"],
179
+ "android": {
180
+ "collapse_key": f"follow_{follower_id}_{target_user_id}"
181
+ },
182
+ "apns": {
183
+ "headers": {
184
+ "apns-collapse-id": f"follow_{follower_id}_{target_user_id}"
185
+ }
186
+ }
187
+ }
188
+ }
189
 
190
+ access_token = get_access_token()
191
+ headers = {
192
+ "Authorization": f"Bearer {access_token}",
193
+ "Content-Type": "application/json"
194
+ }
195
+ url = f"https://fcm.googleapis.com/v1/projects/{FCM_PROJECT_ID}/messages:send"
196
 
197
+ async with aiohttp.ClientSession() as session:
198
+ async with session.post(url, headers=headers, json=payload) as resp:
199
+ resp_text = await resp.text()
200
+ if resp.status != 200:
201
+ raise HTTPException(status_code=resp.status, detail=f"FCM error: {resp_text}")
202
+ fcm_response = await resp.json()
203
 
204
+ return {"detail": "Follow notification sent successfully", "fcm_response": fcm_response}