76 lines
2.5 KiB
Python
76 lines
2.5 KiB
Python
from __future__ import annotations
|
|||
|
|
|
||
|
|
from fastapi import APIRouter, status
|
||
|
|
from sqlalchemy import select
|
||
|
|
|
||
|
|
from sakura_cloud.api.deps import CurrentUser, DbSession
|
||
|
|
from sakura_cloud.models.mixins import utc_now
|
||
|
|
from sakura_cloud.models.push import PushDeviceToken
|
||
|
|
from sakura_cloud.schemas.common import ApiResponse
|
||
|
|
from sakura_cloud.schemas.push import PushDeviceTokenOut, PushTokenRegister, PushTokenUnregister
|
||
|
|
|
||
|
|
|
||
|
|
router = APIRouter()
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/register-token", response_model=ApiResponse[PushDeviceTokenOut], status_code=status.HTTP_201_CREATED)
|
||
|
|
def register_token(
|
||
|
|
payload: PushTokenRegister,
|
||
|
|
current_user: CurrentUser,
|
||
|
|
db: DbSession,
|
||
|
|
) -> ApiResponse[PushDeviceTokenOut]:
|
||
|
|
row = db.scalar(
|
||
|
|
select(PushDeviceToken).where(
|
||
|
|
PushDeviceToken.user_id == current_user.id,
|
||
|
|
PushDeviceToken.device_id == payload.device_id,
|
||
|
|
)
|
||
|
|
)
|
||
|
|
now = utc_now()
|
||
|
|
if row is None:
|
||
|
|
row = PushDeviceToken(
|
||
|
|
user_id=current_user.id,
|
||
|
|
device_id=payload.device_id,
|
||
|
|
platform=payload.platform,
|
||
|
|
fcm_token=payload.fcm_token,
|
||
|
|
is_active=True,
|
||
|
|
last_seen_at=now,
|
||
|
|
)
|
||
|
|
db.add(row)
|
||
|
|
else:
|
||
|
|
row.platform = payload.platform
|
||
|
|
row.fcm_token = payload.fcm_token
|
||
|
|
row.is_active = True
|
||
|
|
row.last_seen_at = now
|
||
|
|
|
||
|
|
db.commit()
|
||
|
|
db.refresh(row)
|
||
|
|
return ApiResponse(code=201, message="registered", data=PushDeviceTokenOut.model_validate(row))
|
||
|
|
|
||
|
|
|
||
|
|
@router.post("/unregister-token", response_model=ApiResponse[dict[str, bool]])
|
||
|
|
def unregister_token(
|
||
|
|
payload: PushTokenUnregister,
|
||
|
|
current_user: CurrentUser,
|
||
|
|
db: DbSession,
|
||
|
|
) -> ApiResponse[dict[str, bool]]:
|
||
|
|
row = db.scalar(
|
||
|
|
select(PushDeviceToken).where(
|
||
|
|
PushDeviceToken.user_id == current_user.id,
|
||
|
|
PushDeviceToken.device_id == payload.device_id,
|
||
|
|
)
|
||
|
|
)
|
||
|
|
if row is not None:
|
||
|
|
row.is_active = False
|
||
|
|
row.last_seen_at = utc_now()
|
||
|
|
db.commit()
|
||
|
|
return ApiResponse(message="unregistered", data={"ok": True})
|
||
|
|
|
||
|
|
|
||
|
|
@router.get("/devices", response_model=ApiResponse[list[PushDeviceTokenOut]])
|
||
|
|
def list_devices(current_user: CurrentUser, db: DbSession) -> ApiResponse[list[PushDeviceTokenOut]]:
|
||
|
|
rows = db.scalars(
|
||
|
|
select(PushDeviceToken)
|
||
|
|
.where(PushDeviceToken.user_id == current_user.id)
|
||
|
|
.order_by(PushDeviceToken.last_seen_at.desc().nullslast(), PushDeviceToken.updated_at.desc())
|
||
|
|
).all()
|
||
|
|
return ApiResponse(data=[PushDeviceTokenOut.model_validate(row) for row in rows])
|