"""Push tokens (B3, B4). A token belongs to whichever account registered it last.""" from datetime import UTC, datetime from sqlalchemy.ext.asyncio import AsyncSession from app.modules.accounts.models import Account from app.modules.devices.models import Device from app.modules.devices.repository import DeviceRepository class DeviceService: def __init__(self, db: AsyncSession): self.devices = DeviceRepository(db) async def register(self, account: Account, platform: str, push_token: str) -> tuple[Device, bool]: """Returns (device, created); created is False only when this account already had the token.""" now = datetime.now(UTC) device = await self.devices.first_by(push_token=push_token) if device is None: return await self.devices.create(account_id=account.id, platform=platform, push_token=push_token, last_seen_at=now), True existed = device.account_id == account.id await self.devices.update(device, account_id=account.id, platform=platform, last_seen_at=now) return device, not existed async def remove(self, account: Account, push_token: str) -> None: await self.devices.delete_own(account.id, push_token)