Initial commit: Test GLM project
This commit is contained in:
@@ -0,0 +1,366 @@
|
||||
# Subtask: Message Reactions System
|
||||
|
||||
**Parent Task**: Decomp/002
|
||||
**Subtask ID**: Decomp/002-05
|
||||
**Dependencies**: Decomp/002-01 (Database Schema), Decomp/002-02 (WebSocket Manager)
|
||||
|
||||
## Description
|
||||
|
||||
Implement message reactions with support for both unicode emojis and custom emojis. Handle adding, removing reactions, and broadcasting reaction events. Support multiple reactions per user per message.
|
||||
|
||||
## Requirements
|
||||
|
||||
- Add reaction to message
|
||||
- Remove reaction from message
|
||||
- Custom emoji support
|
||||
- Multiple reactions per user per message
|
||||
- Broadcast reaction events to channel
|
||||
- Prevent duplicate reactions
|
||||
- Show reaction counts
|
||||
|
||||
## Technical Specifications
|
||||
|
||||
**Reaction handler**:
|
||||
```python
|
||||
from typing import Optional, List
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class ReactionEvent:
|
||||
"""A reaction add/remove event."""
|
||||
message_id: int
|
||||
user_id: int
|
||||
emoji: str
|
||||
emoji_type: str # 'unicode' or 'custom'
|
||||
event_type: str # 'add' or 'remove'
|
||||
|
||||
class ReactionHandler:
|
||||
"""Handle message reactions."""
|
||||
|
||||
def __init__(self, ws_manager: WebSocketManager, db_pool):
|
||||
self.ws_manager = ws_manager
|
||||
self.db = db_pool
|
||||
|
||||
async def add_reaction(
|
||||
self,
|
||||
message_id: int,
|
||||
user_id: int,
|
||||
emoji: str,
|
||||
emoji_type: str = "unicode"
|
||||
) -> Optional[dict]:
|
||||
"""
|
||||
Add a reaction to a message.
|
||||
|
||||
Returns reaction data if successful, None if failed.
|
||||
"""
|
||||
# Validate emoji
|
||||
if emoji_type == "unicode":
|
||||
if not self._is_valid_emoji(emoji):
|
||||
return None
|
||||
elif emoji_type == "custom":
|
||||
# Check if custom emoji exists
|
||||
if not await self._custom_emoji_exists(emoji):
|
||||
return None
|
||||
|
||||
async with self.db.acquire() as conn:
|
||||
# Check if message exists
|
||||
message = await conn.fetchrow(
|
||||
"SELECT channel_id FROM messages WHERE id = $1",
|
||||
message_id
|
||||
)
|
||||
if not message:
|
||||
return None
|
||||
|
||||
channel_id = message["channel_id"]
|
||||
|
||||
# Check for duplicate reaction
|
||||
existing = await conn.fetchrow(
|
||||
"""SELECT id FROM message_reactions
|
||||
WHERE message_id = $1 AND user_id = $2 AND emoji = $3""",
|
||||
message_id, user_id, emoji
|
||||
)
|
||||
if existing:
|
||||
# Already reacted, return existing
|
||||
return await self._get_reaction_data(message_id, emoji)
|
||||
|
||||
# Add reaction
|
||||
await conn.execute(
|
||||
"""INSERT INTO message_reactions
|
||||
(message_id, user_id, emoji, emoji_type)
|
||||
VALUES ($1, $2, $3, $4)""",
|
||||
message_id, user_id, emoji, emoji_type
|
||||
)
|
||||
|
||||
# Get reaction data with count
|
||||
reaction_data = await self._get_reaction_data(message_id, emoji)
|
||||
|
||||
# Broadcast to channel
|
||||
await self.ws_manager.broadcast_to_channel(
|
||||
channel_id,
|
||||
{
|
||||
"type": "MESSAGE_REACTION_ADD",
|
||||
"data": {
|
||||
"message_id": str(message_id),
|
||||
"user_id": str(user_id),
|
||||
**reaction_data
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return reaction_data
|
||||
|
||||
async def remove_reaction(
|
||||
self,
|
||||
message_id: int,
|
||||
user_id: int,
|
||||
emoji: str
|
||||
) -> bool:
|
||||
"""
|
||||
Remove a reaction from a message.
|
||||
|
||||
Returns True if removed, False if not found.
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
# Get channel_id for broadcasting
|
||||
message = await conn.fetchrow(
|
||||
"SELECT channel_id FROM messages WHERE id = $1",
|
||||
message_id
|
||||
)
|
||||
if not message:
|
||||
return False
|
||||
|
||||
channel_id = message["channel_id"]
|
||||
|
||||
# Remove reaction
|
||||
result = await conn.execute(
|
||||
"""DELETE FROM message_reactions
|
||||
WHERE message_id = $1 AND user_id = $2 AND emoji = $3""",
|
||||
message_id, user_id, emoji
|
||||
)
|
||||
|
||||
if result == "DELETE 0":
|
||||
return False
|
||||
|
||||
# Get remaining count
|
||||
count = await conn.fetchval(
|
||||
"""SELECT COUNT(*) FROM message_reactions
|
||||
WHERE message_id = $1 AND emoji = $2""",
|
||||
message_id, emoji
|
||||
)
|
||||
|
||||
# Broadcast removal
|
||||
await self.ws_manager.broadcast_to_channel(
|
||||
channel_id,
|
||||
{
|
||||
"type": "MESSAGE_REACTION_REMOVE",
|
||||
"data": {
|
||||
"message_id": str(message_id),
|
||||
"user_id": str(user_id),
|
||||
"emoji": emoji,
|
||||
"count": count
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def get_reactions(self, message_id: int) -> List[dict]:
|
||||
"""Get all reactions for a message."""
|
||||
async with self.db.acquire() as conn:
|
||||
rows = await conn.fetch(
|
||||
"""SELECT
|
||||
emoji,
|
||||
emoji_type,
|
||||
COUNT(*) as count,
|
||||
array_agg(user_id) as user_ids
|
||||
FROM message_reactions
|
||||
WHERE message_id = $1
|
||||
GROUP BY emoji, emoji_type
|
||||
ORDER BY count DESC, emoji""",
|
||||
message_id
|
||||
)
|
||||
|
||||
return [
|
||||
{
|
||||
"emoji": row["emoji"],
|
||||
"emoji_type": row["emoji_type"],
|
||||
"count": row["count"],
|
||||
"user_ids": [str(uid) for uid in row["user_ids"]]
|
||||
}
|
||||
for row in rows
|
||||
]
|
||||
|
||||
async def clear_reactions(
|
||||
self,
|
||||
message_id: int,
|
||||
emoji: Optional[str] = None
|
||||
) -> bool:
|
||||
"""
|
||||
Clear reactions from a message.
|
||||
If emoji specified, only clear that emoji.
|
||||
Otherwise clear all reactions.
|
||||
"""
|
||||
async with self.db.acquire() as conn:
|
||||
# Get channel_id
|
||||
message = await conn.fetchrow(
|
||||
"SELECT channel_id FROM messages WHERE id = $1",
|
||||
message_id
|
||||
)
|
||||
if not message:
|
||||
return False
|
||||
|
||||
channel_id = message["channel_id"]
|
||||
|
||||
if emoji:
|
||||
await conn.execute(
|
||||
"""DELETE FROM message_reactions
|
||||
WHERE message_id = $1 AND emoji = $2""",
|
||||
message_id, emoji
|
||||
)
|
||||
else:
|
||||
await conn.execute(
|
||||
"DELETE FROM message_reactions WHERE message_id = $1",
|
||||
message_id
|
||||
)
|
||||
|
||||
# Broadcast clear event
|
||||
await self.ws_manager.broadcast_to_channel(
|
||||
channel_id,
|
||||
{
|
||||
"type": "MESSAGE_REACTION_REMOVE_ALL",
|
||||
"data": {
|
||||
"message_id": str(message_id),
|
||||
"emoji": emoji
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return True
|
||||
|
||||
async def _get_reaction_data(self, message_id: int, emoji: str) -> dict:
|
||||
"""Get reaction data with count."""
|
||||
async with self.db.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""SELECT
|
||||
emoji,
|
||||
emoji_type,
|
||||
COUNT(*) as count
|
||||
FROM message_reactions
|
||||
WHERE message_id = $1 AND emoji = $2
|
||||
GROUP BY emoji, emoji_type""",
|
||||
message_id, emoji
|
||||
)
|
||||
|
||||
if not row:
|
||||
return {}
|
||||
|
||||
return {
|
||||
"emoji": row["emoji"],
|
||||
"emoji_type": row["emoji_type"],
|
||||
"count": row["count"]
|
||||
}
|
||||
|
||||
def _is_valid_emoji(self, emoji: str) -> bool:
|
||||
"""Validate unicode emoji."""
|
||||
import emoji as emoji_lib
|
||||
return emoji_lib.is_emoji(emoji)
|
||||
|
||||
async def _custom_emoji_exists(self, emoji_id: str) -> bool:
|
||||
"""Check if custom emoji exists in server."""
|
||||
# Implementation depends on custom emoji storage
|
||||
return True
|
||||
```
|
||||
|
||||
**WebSocket message format**:
|
||||
```javascript
|
||||
// Add reaction
|
||||
{
|
||||
"type": "REACTION_ADD",
|
||||
"message_id": "123456789",
|
||||
"emoji": "👍",
|
||||
"emoji_type": "unicode"
|
||||
}
|
||||
|
||||
// Remove reaction
|
||||
{
|
||||
"type": "REACTION_REMOVE",
|
||||
"message_id": "123456789",
|
||||
"emoji": "👍"
|
||||
}
|
||||
```
|
||||
|
||||
**HTTP API endpoints**:
|
||||
```python
|
||||
from fastapi import HTTPException
|
||||
|
||||
@app.put("/api/v1/messages/{message_id}/reactions")
|
||||
async def add_reaction(
|
||||
message_id: int,
|
||||
emoji: str,
|
||||
emoji_type: str = "unicode",
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Add reaction to message."""
|
||||
handler = ReactionHandler(ws_manager, db_pool)
|
||||
result = await handler.add_reaction(message_id, current_user.id, emoji, emoji_type)
|
||||
if not result:
|
||||
raise HTTPException(status_code=400, detail="Could not add reaction")
|
||||
return result
|
||||
|
||||
@app.delete("/api/v1/messages/{message_id}/reactions/{emoji}")
|
||||
async def remove_reaction(
|
||||
message_id: int,
|
||||
emoji: str,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Remove reaction from message."""
|
||||
handler = ReactionHandler(ws_manager, db_pool)
|
||||
success = await handler.remove_reaction(message_id, current_user.id, emoji)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Reaction not found")
|
||||
return {"success": True}
|
||||
|
||||
@app.get("/api/v1/messages/{message_id}/reactions")
|
||||
async def get_reactions(message_id: int):
|
||||
"""Get all reactions for a message."""
|
||||
handler = ReactionHandler(ws_manager, db_pool)
|
||||
return await handler.get_reactions(message_id)
|
||||
|
||||
@app.delete("/api/v1/messages/{message_id}/reactions")
|
||||
async def clear_reactions(
|
||||
message_id: int,
|
||||
emoji: Optional[str] = None,
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
"""Clear reactions from message (admin only or message author)."""
|
||||
handler = ReactionHandler(ws_manager, db_pool)
|
||||
# Add permission check
|
||||
success = await handler.clear_reactions(message_id, emoji)
|
||||
if not success:
|
||||
raise HTTPException(status_code=404, detail="Message not found")
|
||||
return {"success": True}
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- [ ] User can add reaction to message
|
||||
- [ ] User can remove their reaction
|
||||
- [ ] Duplicate reactions prevented
|
||||
- [ ] Reaction count updates correctly
|
||||
- [ ] Reaction events broadcast to channel
|
||||
- [ ] Unicode emoji validation works
|
||||
- [ ] Custom emoji support functional
|
||||
|
||||
## Notes
|
||||
|
||||
**Trade-offs**:
|
||||
- Multiple same emoji per user: Prevented via unique constraint
|
||||
- Reaction storage: Separate table allows unlimited reactions per message
|
||||
|
||||
**Performance**:
|
||||
- Index on (message_id, emoji, user_id) for fast lookups
|
||||
- Count queries grouped by emoji for efficient aggregation
|
||||
|
||||
**Alternatives considered**:
|
||||
- Embedded reactions in message JSONB: Rejected, harder to query and aggregate
|
||||
- Single reaction per user: Rejected, users may want to react multiple times with different emojis
|
||||
Reference in New Issue
Block a user