eksplicit mapping af envs
This commit is contained in:
0
backend/app/services/__init__.py
Normal file
0
backend/app/services/__init__.py
Normal file
38
backend/app/services/match_service.py
Normal file
38
backend/app/services/match_service.py
Normal file
@@ -0,0 +1,38 @@
|
||||
from app.services.session_service import get_session
|
||||
from app.services.ws_manager import manager
|
||||
|
||||
|
||||
async def attempt_match(own_token: str, detected_token: str) -> dict:
|
||||
"""
|
||||
Check if two nearby users share interests and both consent.
|
||||
Sends a WebSocket nudge to both if matched.
|
||||
"""
|
||||
own_session = await get_session(own_token)
|
||||
other_session = await get_session(detected_token)
|
||||
|
||||
if own_session is None or other_session is None:
|
||||
return {"match": False, "shared_interests": [], "nudge_sent": False}
|
||||
|
||||
own_interests = set(own_session.get("interests", []))
|
||||
other_interests = set(other_session.get("interests", []))
|
||||
shared = list(own_interests & other_interests)
|
||||
|
||||
if not shared:
|
||||
return {"match": False, "shared_interests": [], "nudge_sent": False}
|
||||
|
||||
nudge = {
|
||||
"type": "nudge",
|
||||
"shared_interests": shared,
|
||||
"message": f"Someone nearby shares your interest in {_format_interests(shared)}.",
|
||||
}
|
||||
|
||||
await manager.send(own_token, nudge)
|
||||
await manager.send(detected_token, nudge)
|
||||
|
||||
return {"match": True, "shared_interests": shared, "nudge_sent": True}
|
||||
|
||||
|
||||
def _format_interests(interests: list[str]) -> str:
|
||||
if len(interests) == 1:
|
||||
return interests[0]
|
||||
return ", ".join(interests[:-1]) + " and " + interests[-1]
|
||||
39
backend/app/services/session_service.py
Normal file
39
backend/app/services/session_service.py
Normal file
@@ -0,0 +1,39 @@
|
||||
import json
|
||||
import uuid
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.redis import get_client
|
||||
|
||||
|
||||
async def create_session(ble_token: str, interests: list[str]) -> dict:
|
||||
"""Store an ephemeral BLE session in Redis with TTL."""
|
||||
client = get_client()
|
||||
session_id = str(uuid.uuid4())
|
||||
expires_at = datetime.now(UTC) + timedelta(seconds=settings.session_ttl_seconds)
|
||||
|
||||
payload = json.dumps({
|
||||
"session_id": session_id,
|
||||
"interests": interests,
|
||||
"created_at": datetime.now(UTC).isoformat(),
|
||||
})
|
||||
|
||||
await client.setex(f"session:{ble_token}", settings.session_ttl_seconds, payload)
|
||||
|
||||
return {"session_id": session_id, "expires_at": expires_at}
|
||||
|
||||
|
||||
async def get_session(ble_token: str) -> dict | None:
|
||||
"""Retrieve a session by BLE token. Returns None if expired or not found."""
|
||||
client = get_client()
|
||||
raw = await client.get(f"session:{ble_token}")
|
||||
if raw is None:
|
||||
return None
|
||||
return json.loads(raw)
|
||||
|
||||
|
||||
async def count_active_sessions() -> int:
|
||||
"""Return number of active (non-expired) sessions."""
|
||||
client = get_client()
|
||||
keys = await client.keys("session:*")
|
||||
return len(keys)
|
||||
60
backend/app/services/stats_service.py
Normal file
60
backend/app/services/stats_service.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from datetime import UTC, date, datetime
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.models.db_models import DailyStat, InterestCategoryCount
|
||||
from app.services.session_service import count_active_sessions
|
||||
|
||||
|
||||
async def get_stats(db: AsyncSession) -> dict:
|
||||
"""Return anonymised aggregate stats for the admin dashboard."""
|
||||
today = date.today()
|
||||
|
||||
row = await db.scalar(
|
||||
sa.select(DailyStat).where(DailyStat.date == today)
|
||||
)
|
||||
|
||||
top_categories_rows = await db.scalars(
|
||||
sa.select(InterestCategoryCount)
|
||||
.where(InterestCategoryCount.date == today)
|
||||
.order_by(InterestCategoryCount.count.desc())
|
||||
.limit(5)
|
||||
)
|
||||
top_categories = [r.category for r in top_categories_rows]
|
||||
active = await count_active_sessions()
|
||||
|
||||
return {
|
||||
"total_sessions_today": row.total_sessions if row else 0,
|
||||
"total_matches_today": row.total_matches if row else 0,
|
||||
"active_sessions_now": active,
|
||||
"top_interest_categories": top_categories,
|
||||
}
|
||||
|
||||
|
||||
async def increment_sessions(db: AsyncSession) -> None:
|
||||
"""Increment daily session counter. Called when a new session is created."""
|
||||
today = date.today()
|
||||
await db.execute(
|
||||
sa.dialects.postgresql.insert(DailyStat)
|
||||
.values(date=today, total_sessions=1, total_matches=0)
|
||||
.on_conflict_do_update(
|
||||
index_elements=["date"],
|
||||
set_={"total_sessions": DailyStat.total_sessions + 1},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
|
||||
async def increment_matches(db: AsyncSession) -> None:
|
||||
"""Increment daily match counter. Called on a successful match."""
|
||||
today = date.today()
|
||||
await db.execute(
|
||||
sa.dialects.postgresql.insert(DailyStat)
|
||||
.values(date=today, total_sessions=0, total_matches=1)
|
||||
.on_conflict_do_update(
|
||||
index_elements=["date"],
|
||||
set_={"total_matches": DailyStat.total_matches + 1},
|
||||
)
|
||||
)
|
||||
await db.commit()
|
||||
25
backend/app/services/ws_manager.py
Normal file
25
backend/app/services/ws_manager.py
Normal file
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
|
||||
from fastapi import WebSocket
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""Manages active WebSocket connections keyed by BLE token."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._connections: dict[str, WebSocket] = {}
|
||||
|
||||
async def connect(self, token: str, websocket: WebSocket) -> None:
|
||||
await websocket.accept()
|
||||
self._connections[token] = websocket
|
||||
|
||||
def disconnect(self, token: str) -> None:
|
||||
self._connections.pop(token, None)
|
||||
|
||||
async def send(self, token: str, message: dict) -> None:
|
||||
websocket = self._connections.get(token)
|
||||
if websocket is not None:
|
||||
await websocket.send_text(json.dumps(message))
|
||||
|
||||
|
||||
manager = ConnectionManager()
|
||||
Reference in New Issue
Block a user