eksplicit mapping af envs
This commit is contained in:
0
backend/app/__init__.py
Normal file
0
backend/app/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
0
backend/app/api/__init__.py
Normal file
9
backend/app/api/health.py
Normal file
9
backend/app/api/health.py
Normal file
@@ -0,0 +1,9 @@
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health() -> JSONResponse:
|
||||
return JSONResponse({"status": "ok"})
|
||||
19
backend/app/api/match.py
Normal file
19
backend/app/api/match.py
Normal file
@@ -0,0 +1,19 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.match import MatchRequest, MatchResult
|
||||
from app.services import match_service, stats_service
|
||||
|
||||
router = APIRouter(tags=["match"])
|
||||
|
||||
|
||||
@router.post("", response_model=MatchResult)
|
||||
async def attempt_match(
|
||||
body: MatchRequest,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> MatchResult:
|
||||
result = await match_service.attempt_match(body.own_token, body.detected_token)
|
||||
if result["match"]:
|
||||
await stats_service.increment_matches(db)
|
||||
return MatchResult(**result)
|
||||
18
backend/app/api/session.py
Normal file
18
backend/app/api/session.py
Normal file
@@ -0,0 +1,18 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.session import SessionCreate, SessionResponse
|
||||
from app.services import session_service, stats_service
|
||||
|
||||
router = APIRouter(tags=["session"])
|
||||
|
||||
|
||||
@router.post("", response_model=SessionResponse)
|
||||
async def create_session(
|
||||
body: SessionCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
) -> SessionResponse:
|
||||
result = await session_service.create_session(body.ble_token, body.interests)
|
||||
await stats_service.increment_sessions(db)
|
||||
return SessionResponse(**result)
|
||||
14
backend/app/api/stats.py
Normal file
14
backend/app/api/stats.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.stats import StatsResponse
|
||||
from app.services import stats_service
|
||||
|
||||
router = APIRouter(tags=["stats"])
|
||||
|
||||
|
||||
@router.get("", response_model=StatsResponse)
|
||||
async def get_stats(db: AsyncSession = Depends(get_db)) -> StatsResponse:
|
||||
data = await stats_service.get_stats(db)
|
||||
return StatsResponse(**data)
|
||||
16
backend/app/api/ws.py
Normal file
16
backend/app/api/ws.py
Normal file
@@ -0,0 +1,16 @@
|
||||
from fastapi import APIRouter, WebSocket, WebSocketDisconnect
|
||||
|
||||
from app.services.ws_manager import manager
|
||||
|
||||
router = APIRouter(tags=["websocket"])
|
||||
|
||||
|
||||
@router.websocket("/ws/{ble_token}")
|
||||
async def websocket_endpoint(websocket: WebSocket, ble_token: str) -> None:
|
||||
await manager.connect(ble_token, websocket)
|
||||
try:
|
||||
while True:
|
||||
# Keep the connection alive; nudges are pushed server-side.
|
||||
await websocket.receive_text()
|
||||
except WebSocketDisconnect:
|
||||
manager.disconnect(ble_token)
|
||||
3
backend/app/core/__init__.py
Normal file
3
backend/app/core/__init__.py
Normal file
@@ -0,0 +1,3 @@
|
||||
from app.core.config import settings # noqa: F401
|
||||
from app.core.database import get_db # noqa: F401
|
||||
from app.core.redis import get_client # noqa: F401
|
||||
13
backend/app/core/config.py
Normal file
13
backend/app/core/config.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
redis_url: str = "redis://localhost:6379"
|
||||
database_url: str = "postgresql+asyncpg://sighej:sighej@localhost/sighej"
|
||||
session_ttl_seconds: int = 7200
|
||||
allowed_origins: list[str] = ["http://localhost:3000"]
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8")
|
||||
|
||||
|
||||
settings = Settings()
|
||||
21
backend/app/core/database.py
Normal file
21
backend/app/core/database.py
Normal file
@@ -0,0 +1,21 @@
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from sqlalchemy.orm import DeclarativeBase
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(settings.database_url, echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
||||
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
|
||||
async def create_tables() -> None:
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
|
||||
|
||||
async def get_db() -> AsyncSession:
|
||||
async with AsyncSessionLocal() as session:
|
||||
yield session
|
||||
16
backend/app/core/redis.py
Normal file
16
backend/app/core/redis.py
Normal file
@@ -0,0 +1,16 @@
|
||||
import redis.asyncio as redis
|
||||
|
||||
from app.core.config import settings
|
||||
|
||||
_pool: redis.ConnectionPool | None = None
|
||||
|
||||
|
||||
def get_pool() -> redis.ConnectionPool:
|
||||
global _pool
|
||||
if _pool is None:
|
||||
_pool = redis.ConnectionPool.from_url(settings.redis_url, decode_responses=True)
|
||||
return _pool
|
||||
|
||||
|
||||
def get_client() -> redis.Redis:
|
||||
return redis.Redis(connection_pool=get_pool())
|
||||
34
backend/app/main.py
Normal file
34
backend/app/main.py
Normal file
@@ -0,0 +1,34 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.api import health, session, match, ws, stats
|
||||
from app.core.config import settings
|
||||
from app.core.database import create_tables
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
await create_tables()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Social Proximity API",
|
||||
version="0.1.0",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=settings.allowed_origins,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(health.router)
|
||||
app.include_router(session.router, prefix="/session")
|
||||
app.include_router(match.router, prefix="/match")
|
||||
app.include_router(ws.router)
|
||||
app.include_router(stats.router, prefix="/stats")
|
||||
0
backend/app/models/__init__.py
Normal file
0
backend/app/models/__init__.py
Normal file
20
backend/app/models/db_models.py
Normal file
20
backend/app/models/db_models.py
Normal file
@@ -0,0 +1,20 @@
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.core.database import Base
|
||||
|
||||
|
||||
class DailyStat(Base):
|
||||
__tablename__ = "daily_stats"
|
||||
|
||||
date: Mapped[sa.Date] = mapped_column(sa.Date, primary_key=True)
|
||||
total_sessions: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
total_matches: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
|
||||
|
||||
class InterestCategoryCount(Base):
|
||||
__tablename__ = "interest_category_counts"
|
||||
|
||||
date: Mapped[sa.Date] = mapped_column(sa.Date, primary_key=True)
|
||||
category: Mapped[str] = mapped_column(sa.String(64), primary_key=True)
|
||||
count: Mapped[int] = mapped_column(sa.Integer, default=0)
|
||||
12
backend/app/models/match.py
Normal file
12
backend/app/models/match.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class MatchRequest(BaseModel):
|
||||
own_token: str
|
||||
detected_token: str
|
||||
|
||||
|
||||
class MatchResult(BaseModel):
|
||||
match: bool
|
||||
shared_interests: list[str]
|
||||
nudge_sent: bool
|
||||
13
backend/app/models/session.py
Normal file
13
backend/app/models/session.py
Normal file
@@ -0,0 +1,13 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class SessionCreate(BaseModel):
|
||||
ble_token: str = Field(..., min_length=1, max_length=128)
|
||||
interests: list[str] = Field(..., min_length=1, max_length=20)
|
||||
|
||||
|
||||
class SessionResponse(BaseModel):
|
||||
session_id: str
|
||||
expires_at: datetime
|
||||
8
backend/app/models/stats.py
Normal file
8
backend/app/models/stats.py
Normal file
@@ -0,0 +1,8 @@
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class StatsResponse(BaseModel):
|
||||
total_sessions_today: int
|
||||
total_matches_today: int
|
||||
active_sessions_now: int
|
||||
top_interest_categories: list[str]
|
||||
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