Spaces:
Sleeping
Sleeping
sync: μ΅μ λ°±μλ μ½λ λκΈ°ν (detect-only, plans, save, push μλν¬μΈνΈ μΆκ°)
59a1470 Download api/push.py from BOWOWEEEEE/pill-advisor-backend: direct link, hf CLI and curl.
- Browser
- Download file 5.91 kB
-
https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/push.py
- Command line
-
hf download hf://spaces/BOWOWEEEEE/pill-advisor-backend/api/push.py
-
curl -L -o push.py https://huggingface.co/spaces/BOWOWEEEEE/pill-advisor-backend/resolve/main/api/push.py
5.91 kB
| """λΈλΌμ°μ Web Push(λ³΅μ½ μλ¦Ό) API. | |
| VAPID ν€λ μ½λμ νλμ½λ©νμ§ λ§κ³ νκ²½λ³μλ‘ μ£Όμ νλ€. | |
| `/Users/apple/Documents/GitHub/pill-advisor/.env` (λ° Render λμ보λ)μ μλλ₯Ό μΆκ°: | |
| VAPID_PUBLIC_KEY=... # base64url νμ P-256 곡κ°ν€ (μλ λͺ λ ΉμΌλ‘ μμ±) | |
| VAPID_PRIVATE_KEY=... # PEM νμ κ°μΈν€ (μλ λͺ λ ΉμΌλ‘ μμ±) | |
| VAPID_SUBJECT=mailto:beomjinkim2000@gmail.com # (μ ν) νΈμ μλΉμ€ μ°λ½μ² | |
| ν€ μμ± (base64url 곡κ°ν€ μΆλ ₯): | |
| cd web/backend && pip install pywebpush cryptography | |
| python3 -c " | |
| from py_vapid import Vapid | |
| import base64 | |
| from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat | |
| v = Vapid() | |
| v.generate_keys() | |
| raw = v.public_key.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) | |
| print('VAPID_PRIVATE_KEY:', v.serialize_private_key().decode().strip()) | |
| print('VAPID_PUBLIC_KEY:', base64.urlsafe_b64encode(raw).rstrip(b'=').decode()) | |
| " | |
| μ£Όμ: PushManager.subscribe(applicationServerKey)λ base64url νμμ raw P-256 곡κ°ν€λ₯Ό | |
| μꡬνλ€. PEM νμμ λ£μΌλ©΄ ꡬλ μ λ°νμ μλ¬κ° λ°μνλ€. | |
| VAPID_PUBLIC_KEY νκ²½λ³μμλ λ°λμ base64url νμ κ°μ λ£μ κ². | |
| """ | |
| import base64 | |
| import json | |
| import os | |
| from typing import Any | |
| import supabase as sb | |
| from fastapi import APIRouter, Header, HTTPException | |
| from pydantic import BaseModel | |
| from services.auth import auth as _auth | |
| router = APIRouter() | |
| VAPID_PRIVATE_KEY = os.environ.get("VAPID_PRIVATE_KEY", "") | |
| VAPID_SUBJECT = os.environ.get("VAPID_SUBJECT", "mailto:beomjinkim2000@gmail.com") | |
| # PEM νμμΌλ‘ λ€μ΄μ¨ κ²½μ° base64urlλ‘ μλ λ³ν (μλͺ»λ νκ²½λ³μ μ€μ μ λν λ°©μ΄) | |
| _raw_public_key = os.environ.get("VAPID_PUBLIC_KEY", "") | |
| def _normalize_public_key(key: str) -> str: | |
| """PEM λλ base64url 곡κ°ν€λ₯Ό λΈλΌμ°μ μ© base64url(unpadded)λ‘ μ κ·ν.""" | |
| if not key: | |
| return "" | |
| if key.startswith("-----"): | |
| try: | |
| from cryptography.hazmat.primitives.serialization import ( | |
| Encoding, | |
| PublicFormat, | |
| load_pem_public_key, | |
| ) | |
| pub = load_pem_public_key(key.encode()) | |
| raw = pub.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint) | |
| return base64.urlsafe_b64encode(raw).rstrip(b"=").decode() | |
| except Exception: | |
| return key | |
| return key | |
| VAPID_PUBLIC_KEY = _normalize_public_key(_raw_public_key) | |
| class PushKeys(BaseModel): | |
| p256dh: str | |
| auth: str | |
| class SubscribeRequest(BaseModel): | |
| endpoint: str | |
| keys: PushKeys | |
| async def get_public_key() -> dict[str, str]: | |
| """νλ‘ νΈκ° PushManager.subscribe(applicationServerKey)μ μ¬μ©ν VAPID 곡κ°ν€(base64url).""" | |
| if not VAPID_PUBLIC_KEY: | |
| raise HTTPException(status_code=503, detail="νΈμ μλ¦Όμ΄ μ€μ λμ§ μμμ΅λλ€.") | |
| return {"public_key": VAPID_PUBLIC_KEY} | |
| async def subscribe( | |
| data: SubscribeRequest, | |
| authorization: str = Header(...), | |
| ) -> dict[str, Any]: | |
| """λΈλΌμ°μ ꡬλ μ 보λ₯Ό μ μ₯(λλ κ°±μ )νλ€. (user_id, endpoint) λ¨μλ‘ λ©±λ±.""" | |
| db, user_id = _auth(authorization) | |
| result = ( | |
| db.table("push_subscriptions") | |
| .upsert( | |
| { | |
| "user_id": user_id, | |
| "endpoint": data.endpoint, | |
| "p256dh": data.keys.p256dh, | |
| "auth_key": data.keys.auth, | |
| }, | |
| on_conflict="user_id,endpoint", | |
| ) | |
| .execute() | |
| ) | |
| if not result.data: | |
| raise HTTPException(status_code=500, detail="ꡬλ μ μ₯ μ€ν¨") | |
| return {"subscribed": True, "id": result.data[0]["id"]} | |
| async def send_test(authorization: str = Header(...)) -> dict[str, Any]: | |
| """λ³ΈμΈμ λͺ¨λ ꡬλ λ¨λ§λ‘ ν μ€νΈ μλ¦Όμ μ μ‘νλ€.""" | |
| if not VAPID_PRIVATE_KEY: | |
| raise HTTPException(status_code=503, detail="νΈμ μλ¦Όμ΄ μ€μ λμ§ μμμ΅λλ€.") | |
| db, user_id = _auth(authorization) | |
| subs = ( | |
| db.table("push_subscriptions").select("*").eq("user_id", user_id).execute() | |
| ) | |
| rows = subs.data or [] | |
| if not rows: | |
| raise HTTPException(status_code=404, detail="λ±λ‘λ μλ¦Ό ꡬλ μ΄ μμ΅λλ€.") | |
| payload = json.dumps( | |
| { | |
| "title": "λ³΅μ½ μλ¦Ό ν μ€νΈ", | |
| "body": "μλ¦Όμ΄ μ μμ μΌλ‘ μ€μ λμμ΄μ! π", | |
| "url": "/home", | |
| } | |
| ) | |
| sent, failed = 0, 0 | |
| for row in rows: | |
| if _send_web_push(row, payload, db, user_id): | |
| sent += 1 | |
| else: | |
| failed += 1 | |
| return {"sent": sent, "failed": failed} | |
| def _send_web_push( | |
| row: dict, payload: str, db: sb.Client, user_id: str | |
| ) -> bool: | |
| """λ¨μΌ ꡬλ μΌλ‘ μΉ νΈμλ₯Ό μ μ‘νλ€. λ§λ£(404/410) ꡬλ μ μμ νλ€.""" | |
| # pywebpush λ μ ν μμ‘΄μ± β λ―Έμ€μΉ νκ²½μμ import μ μ± κΈ°λμ΄ λ§νμ§ μλλ‘ μ§μ° import. | |
| from pywebpush import WebPushException, webpush | |
| subscription_info = { | |
| "endpoint": row["endpoint"], | |
| "keys": {"p256dh": row["p256dh"], "auth": row["auth_key"]}, | |
| } | |
| try: | |
| webpush( | |
| subscription_info=subscription_info, | |
| data=payload, | |
| vapid_private_key=VAPID_PRIVATE_KEY, | |
| vapid_claims={"sub": VAPID_SUBJECT}, | |
| ) | |
| return True | |
| except WebPushException as e: | |
| status = getattr(getattr(e, "response", None), "status_code", None) | |
| if status in (404, 410): | |
| db.table("push_subscriptions").delete().eq("user_id", user_id).eq( | |
| "endpoint", row["endpoint"] | |
| ).execute() | |
| return False | |
| except Exception: | |
| return False | |