37 lines
1.4 KiB
Python
Raw Normal View History

2025-11-10 15:46:40 +01:00
from fastapi import Request
from starlette.middleware.base import BaseHTTPMiddleware
from ..billing.usage_tracker import UsageTracker
2025-11-13 23:22:05 +01:00
2025-11-10 15:46:40 +01:00
class UsageTrackingMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
response = await call_next(request)
2025-11-13 23:22:05 +01:00
if hasattr(request.state, "user") and request.state.user:
2025-11-10 15:46:40 +01:00
user = request.state.user
2025-11-13 23:22:05 +01:00
if (
request.method in ["POST", "PUT"]
and "/files/upload" in request.url.path
):
content_length = response.headers.get("content-length")
2025-11-10 15:46:40 +01:00
if content_length:
await UsageTracker.track_bandwidth(
user=user,
amount_bytes=int(content_length),
2025-11-13 23:22:05 +01:00
direction="up",
metadata={"path": request.url.path},
2025-11-10 15:46:40 +01:00
)
2025-11-13 23:22:05 +01:00
elif request.method == "GET" and "/files/download" in request.url.path:
content_length = response.headers.get("content-length")
2025-11-10 15:46:40 +01:00
if content_length:
await UsageTracker.track_bandwidth(
user=user,
amount_bytes=int(content_length),
2025-11-13 23:22:05 +01:00
direction="down",
metadata={"path": request.url.path},
2025-11-10 15:46:40 +01:00
)
return response