Files
ds-chat/backend/app/schemas/message.py
T
ksmithandClaude Sonnet 5 760d2cf5dd Add URL previews for chat messages (#43)
Slack/Discord-style link unfurling: the first http(s) URL in a message's
content gets a small preview card (title/description/image/site name)
fetched from the page's Open Graph tags.

Backend:
- Message.preview_url (extracted at create/edit time, cheap regex, no
  I/O) points at a link_previews cache row keyed by URL -- the same URL
  posted in different messages/rooms fetches once, and a failed fetch is
  cached too so a dead URL isn't retried on every reference.
- The actual fetch runs in a background asyncio.create_task from
  broadcast_new_message/broadcast_message_update, on its own DB session,
  so a slow third-party site never delays message delivery. A separate
  "link_preview" WS envelope carries the result once it resolves.
- SSRF protection reuses app/services/ssrf.py's validate_target_url
  (renamed from UnsafeWebhookUrlError to UnsafeUrlError now that it's
  shared with webhooks), but re-validates before every hop of a redirect
  chain rather than once up front -- redirects are followed manually so
  each intermediate URL is checked before it's ever connected to.
- Parsed with stdlib html.parser -- no new dependency.

Frontend: a LinkPreviewCard rendered under message content when present,
patched into state live via the new WS envelope and included in message
history for reloads.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-17 17:50:55 -06:00

46 lines
936 B
Python

import uuid
from datetime import datetime
from pydantic import BaseModel, ConfigDict
class ReactionSummary(BaseModel):
emoji: str
count: int
user_ids: list[str]
class MessageFileInfo(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
filename: str
size_bytes: int
content_type: str
class LinkPreviewInfo(BaseModel):
model_config = ConfigDict(from_attributes=True)
url: str
title: str | None
description: str | None
image_url: str | None
site_name: str | None
class MessageRead(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: uuid.UUID
room_id: uuid.UUID
user_id: uuid.UUID
username: str
content: str | None
image_id: uuid.UUID | None
file: MessageFileInfo | None
link_preview: LinkPreviewInfo | None
reactions: list[ReactionSummary]
created_at: datetime
edited_at: datetime | None