371 lines
12 KiB
Markdown
371 lines
12 KiB
Markdown
# Subtask: User Presence System
|
|
|
|
**Parent Task**: Decomp/002
|
|
**Subtask ID**: Decomp/002-06
|
|
**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager)
|
|
|
|
## Description
|
|
|
|
Implement real-time user presence tracking showing online/idle/dnd/offline status. Handle status updates, activity tracking (playing X, listening to Y), and broadcast presence changes to friends/guild members.
|
|
|
|
## Requirements
|
|
|
|
- Track user online/offline status
|
|
- Support idle, dnd (do not disturb), invisible statuses
|
|
- Activity display (playing game, listening to music)
|
|
- Broadcast presence to relevant users
|
|
- Handle multiple devices per user
|
|
- Presence should reflect last activity across all devices
|
|
- "Last seen" timestamp for offline users
|
|
|
|
## Technical Specifications
|
|
|
|
**Presence handler**:
|
|
```python
|
|
from datetime import datetime, timezone, timedelta
|
|
from enum import Enum
|
|
from typing import Optional, Dict, Set, List
|
|
import asyncio
|
|
import json
|
|
|
|
class PresenceStatus(str, Enum):
|
|
ONLINE = "online"
|
|
IDLE = "idle"
|
|
DND = "dnd"
|
|
OFFLINE = "offline"
|
|
INVISIBLE = "invisible"
|
|
|
|
class PresenceHandler:
|
|
"""
|
|
Handle user presence tracking and broadcasting.
|
|
|
|
Presence is determined by:
|
|
1. WebSocket connection state (online/offline)
|
|
2. Last activity timestamp (idle)
|
|
3. User-set status (dnd, invisible)
|
|
"""
|
|
|
|
# Idle thresholds
|
|
IDLE_THRESHOLD = timedelta(minutes=5) # 5 minutes of inactivity = idle
|
|
OFFLINE_THRESHOLD = timedelta(minutes=10) # 10 minutes = offline
|
|
|
|
def __init__(self, ws_manager: WebSocketManager, db_pool):
|
|
self.ws_manager = ws_manager
|
|
self.db = db_pool
|
|
self._cleanup_task: Optional[asyncio.Task] = None
|
|
|
|
async def start(self):
|
|
"""Start presence cleanup task."""
|
|
self._cleanup_task = asyncio.create_task(self._cleanup_loop())
|
|
|
|
async def update_presence(
|
|
self,
|
|
user_id: int,
|
|
status: Optional[PresenceStatus] = None,
|
|
activities: Optional[List[dict]] = None,
|
|
connection_id: Optional[str] = None
|
|
):
|
|
"""
|
|
Update user presence and broadcast to relevant users.
|
|
|
|
Args:
|
|
user_id: User to update
|
|
status: New status (None = auto-detect)
|
|
activities: List of activities (games, music)
|
|
connection_id: Connection triggering update
|
|
"""
|
|
current_time = datetime.now(timezone.utc)
|
|
|
|
# Get current user state
|
|
async with self.db.acquire() as conn:
|
|
presence_row = await conn.fetchrow(
|
|
"SELECT * FROM user_presence WHERE user_id = $1",
|
|
user_id
|
|
)
|
|
|
|
current_status = PresenceStatus.OFFLINE
|
|
current_activities = []
|
|
|
|
if presence_row:
|
|
current_status = PresenceStatus(presence_row["status"])
|
|
current_activities = presence_row.get("activities", [])
|
|
|
|
# Determine new status
|
|
if status:
|
|
new_status = status
|
|
else:
|
|
# Auto-detect based on connections
|
|
user_conns = self.ws_manager.user_connections.get(user_id, set())
|
|
if user_conns:
|
|
# User has connections, check last activity
|
|
latest_activity = None
|
|
for conn_id in user_conns:
|
|
if conn_id in self.ws_manager.connections:
|
|
conn = self.ws_manager.connections[conn_id]
|
|
if latest_activity is None or conn.last_ping > latest_activity:
|
|
latest_activity = conn.last_ping
|
|
|
|
if latest_activity:
|
|
time_since = current_time - latest_activity
|
|
if time_since > self.OFFLINE_THRESHOLD:
|
|
new_status = PresenceStatus.OFFLINE
|
|
elif time_since > self.IDLE_THRESHOLD:
|
|
new_status = PresenceStatus.IDLE
|
|
else:
|
|
new_status = PresenceStatus.ONLINE
|
|
else:
|
|
new_status = PresenceStatus.ONLINE
|
|
else:
|
|
new_status = PresenceStatus.OFFLINE
|
|
|
|
# Invisible users appear offline to others
|
|
display_status = PresenceStatus.OFFLINE if new_status == PresenceStatus.INVISIBLE else new_status
|
|
new_activities = activities or current_activities
|
|
|
|
# Update database
|
|
await conn.execute(
|
|
"""INSERT INTO user_presence (user_id, status, last_updated, activities)
|
|
VALUES ($1, $2, $3, $4)
|
|
ON CONFLICT (user_id) DO UPDATE
|
|
SET status = $2, last_updated = $3, activities = $4""",
|
|
user_id, new_status.value, current_time, json.dumps(new_activities)
|
|
)
|
|
|
|
# Also update users.last_seen_at
|
|
await conn.execute(
|
|
"UPDATE users SET last_seen_at = $1 WHERE id = $2",
|
|
current_time, user_id
|
|
)
|
|
|
|
# Broadcast to relevant users
|
|
await self._broadcast_presence_change(
|
|
user_id,
|
|
display_status,
|
|
new_activities
|
|
)
|
|
|
|
async def get_presence(self, user_ids: List[int]) -> Dict[int, dict]:
|
|
"""
|
|
Get presence status for multiple users.
|
|
|
|
Returns:
|
|
{user_id: {status, activities, last_seen}}
|
|
"""
|
|
if not user_ids:
|
|
return {}
|
|
|
|
async with self.db.acquire() as conn:
|
|
rows = await conn.fetch(
|
|
"""SELECT up.user_id, up.status, up.activities, up.last_updated,
|
|
u.last_seen_at
|
|
FROM user_presence up
|
|
JOIN users u ON up.user_id = u.id
|
|
WHERE up.user_id = ANY($1)""",
|
|
user_ids
|
|
)
|
|
|
|
result = {}
|
|
for row in rows:
|
|
status = PresenceStatus(row["status"])
|
|
# Handle invisible - show as offline
|
|
display_status = PresenceStatus.OFFLINE if status == PresenceStatus.INVISIBLE else status
|
|
|
|
result[row["user_id"]] = {
|
|
"status": display_status.value,
|
|
"activities": row.get("activities", []),
|
|
"last_seen": row["last_seen_at"].isoformat() if row["last_seen_at"] else None
|
|
}
|
|
|
|
# Fill in offline users not in presence table
|
|
for uid in user_ids:
|
|
if uid not in result:
|
|
result[uid] = {
|
|
"status": PresenceStatus.OFFLINE.value,
|
|
"activities": [],
|
|
"last_seen": None
|
|
}
|
|
|
|
return result
|
|
|
|
async def set_status(
|
|
self,
|
|
user_id: int,
|
|
status: PresenceStatus,
|
|
activities: Optional[List[dict]] = None
|
|
):
|
|
"""
|
|
Manually set user status.
|
|
|
|
Activities format:
|
|
[
|
|
{"type": "playing", "name": "Game Name"},
|
|
{"type": "listening", "name": "Song Name"},
|
|
{"type": "watching", "name": "Show Name"}
|
|
]
|
|
"""
|
|
await self.update_presence(
|
|
user_id=user_id,
|
|
status=status,
|
|
activities=activities
|
|
)
|
|
|
|
async def _broadcast_presence_change(
|
|
self,
|
|
user_id: int,
|
|
status: PresenceStatus,
|
|
activities: List[dict]
|
|
):
|
|
"""
|
|
Broadcast presence change to users who should see it.
|
|
|
|
Relevant users:
|
|
- Users in same servers
|
|
- Users in DM channels
|
|
"""
|
|
# Get user's servers and DM partners
|
|
async with self.db.acquire() as conn:
|
|
# Get server members who should see this
|
|
server_member_ids = await conn.fetch(
|
|
"""SELECT DISTINCT sm.user_id
|
|
FROM server_members sm
|
|
JOIN servers s ON sm.server_id = s.id
|
|
WHERE sm.server_id IN (
|
|
SELECT server_id FROM server_members WHERE user_id = $1
|
|
)
|
|
AND sm.user_id != $1""",
|
|
user_id
|
|
)
|
|
|
|
# Get DM partners
|
|
dm_partner_ids = await conn.fetch(
|
|
"""SELECT DISTINCT dcm.user_id
|
|
FROM dm_channel_members dcm
|
|
WHERE dcm.channel_id IN (
|
|
SELECT channel_id FROM dm_channel_members WHERE user_id = $1
|
|
)
|
|
AND dcm.user_id != $1""",
|
|
user_id
|
|
)
|
|
|
|
# Combine and deduplicate
|
|
target_ids = set(r["user_id"] for r in server_member_ids) | set(r["user_id"] for r in dm_partner_ids)
|
|
|
|
# Send to all online users in target set
|
|
presence_data = {
|
|
"type": "PRESENCE_UPDATE",
|
|
"data": {
|
|
"user_id": str(user_id),
|
|
"status": status.value,
|
|
"activities": activities
|
|
}
|
|
}
|
|
|
|
for target_id in target_ids:
|
|
await self.ws_manager.send_to_user(target_id, presence_data)
|
|
|
|
async def _cleanup_loop(self):
|
|
"""Periodic cleanup of stale presence data."""
|
|
while True:
|
|
try:
|
|
await self._cleanup_stale_presence()
|
|
await asyncio.sleep(60) # Run every minute
|
|
except Exception as e:
|
|
logger.error(f"Error in presence cleanup: {e}")
|
|
|
|
async def _cleanup_stale_presence(self):
|
|
"""Mark inactive users as offline."""
|
|
cutoff_time = datetime.now(timezone.utc) - self.OFFLINE_THRESHOLD
|
|
|
|
async with self.db.acquire() as conn:
|
|
# Find users who should be offline but aren't
|
|
await conn.execute(
|
|
"""UPDATE user_presence
|
|
SET status = 'offline'
|
|
WHERE status IN ('online', 'idle', 'dnd')
|
|
AND last_updated < $1""",
|
|
cutoff_time
|
|
)
|
|
```
|
|
|
|
**WebSocket message format**:
|
|
```javascript
|
|
// Client requests to set status
|
|
{
|
|
"type": "PRESENCE_UPDATE",
|
|
"status": "dnd",
|
|
"activities": [
|
|
{"type": "playing", "name": "Game Name"}
|
|
]
|
|
}
|
|
|
|
// Server broadcasts presence updates
|
|
{
|
|
"type": "PRESENCE_UPDATE",
|
|
"data": {
|
|
"user_id": "123",
|
|
"status": "online",
|
|
"activities": []
|
|
}
|
|
}
|
|
```
|
|
|
|
**Integration with WebSocket manager**:
|
|
```python
|
|
# When user connects
|
|
await presence_handler.update_presence(user_id, PresenceStatus.ONLINE)
|
|
|
|
# When user disconnects (check for remaining connections)
|
|
await presence_handler.update_presence(user_id)
|
|
|
|
# Periodic activity updates (on user interaction)
|
|
async def on_user_activity(connection_id: str):
|
|
state = ws_manager.connections[connection_id]
|
|
state.last_ping = datetime.now(timezone.utc)
|
|
await presence_handler.update_presence(state.user_id)
|
|
```
|
|
|
|
**HTTP API**:
|
|
```python
|
|
@app.get("/api/v1/users/{user_id}/presence")
|
|
async def get_user_presence(user_id: int):
|
|
"""Get presence status for a user."""
|
|
handler = PresenceHandler(ws_manager, db_pool)
|
|
result = await handler.get_presence([user_id])
|
|
return result.get(user_id, {"status": "offline"})
|
|
|
|
@app.post("/api/v1/users/@me/presence")
|
|
async def set_my_presence(
|
|
status: PresenceStatus,
|
|
activities: Optional[List[dict]] = None,
|
|
current_user: User = Depends(get_current_user)
|
|
):
|
|
"""Set my presence status."""
|
|
handler = PresenceHandler(ws_manager, db_pool)
|
|
await handler.set_status(current_user.id, status, activities)
|
|
return {"success": True}
|
|
```
|
|
|
|
## Acceptance Criteria
|
|
|
|
- [ ] User appears online when connected
|
|
- [ ] User goes idle after 5 minutes of inactivity
|
|
- [ ] User goes offline after 10 minutes or disconnect
|
|
- [ ] Presence changes broadcast to server members
|
|
- [ ] DND status prevents notifications
|
|
- [ ] Invisible status shows user as offline to others
|
|
- [ ] Activities display correctly
|
|
|
|
## Notes
|
|
|
|
**Trade-offs**:
|
|
- Idle timeout: 5 minutes balances responsiveness and accuracy
|
|
- Separate presence table vs users column: Separate table for efficiency
|
|
|
|
**Performance**:
|
|
- Presence queries batched for efficiency
|
|
- Only broadcast to online users
|
|
|
|
**Alternatives considered**:
|
|
- Redis-only presence: Rejected, want persistence
|
|
- Presence per server: Rejected, global presence simpler
|