12 KiB
12 KiB
Subtask: File Upload and Attachments
Parent Task: Decomp/002 Subtask ID: Decomp/002-07 Dependencies: Decomp/002-01 (Database Schema), Decomp/002-03 (Message Delivery)
Description
Implement file upload functionality supporting images, videos, audio, and documents. Store files efficiently, generate thumbnails for images, and attach files to messages.
Requirements
- Upload files via HTTP multipart/form-data
- Support images (PNG, JPG, GIF, WebP)
- Support videos (MP4, WebM)
- Support audio (MP3, OGG, WAV)
- Support documents (PDF, TXT, etc.)
- Generate thumbnails for images
- Store file metadata in database
- Return file URL for attaching to messages
- File size limits (8MB for regular, 50MB for Nitro)
- Virus scanning (optional)
Technical Specifications
Storage backend: S3-compatible (or local filesystem for development)
File upload handler:
import os
import uuid
import hashlib
from typing import Optional, Tuple
from fastapi import UploadFile, File, HTTPException
from PIL import Image
import io
class FileUploadHandler:
"""Handle file uploads and storage."""
# Size limits
MAX_FILE_SIZE = 8 * 1024 * 1024 # 8MB
MAX_NITRO_FILE_SIZE = 50 * 1024 * 1024 # 50MB
MAX_IMAGE_DIMENSION = 4096
# Allowed content types
ALLOWED_IMAGES = ["image/png", "image/jpeg", "image/gif", "image/webp"]
ALLOWED_VIDEOS = ["video/mp4", "video/webm", "video/quicktime"]
ALLOWED_AUDIO = ["audio/mpeg", "audio/ogg", "audio/wav"]
ALLOWED_DOCUMENTS = ["application/pdf", "text/plain"]
def __init__(self, storage_backend, db_pool):
self.storage = storage_backend
self.db = db_pool
async def upload_file(
self,
file: UploadFile,
user_id: int,
is_nitro: bool = False
) -> dict:
"""
Upload a file and return metadata.
Returns:
{
"id": str,
"filename": str,
"content_type": str,
"size_bytes": int,
"url": str,
"preview_url": str or None,
"width": int or None,
"height": int or None
}
"""
# Check file size
max_size = self.MAX_NITRO_FILE_SIZE if is_nitro else self.MAX_FILE_SIZE
content = await file.read()
if len(content) > max_size:
raise HTTPException(
status_code=413,
detail=f"File too large (max {max_size // (1024*1024)}MB)"
)
# Validate content type
content_type = file.content_type or self._detect_content_type(content, file.filename)
if not self._is_allowed_type(content_type):
raise HTTPException(status_code=415, detail="File type not allowed")
# Generate unique filename
file_id = uuid.uuid4()
ext = os.path.splitext(file.filename or "")[1]
storage_path = f"uploads/{user_id}/{file_id}{ext}"
# Get file dimensions for images/videos
width, height = None, None
preview_url = None
if content_type.startswith("image/"):
width, height, preview_path = await self._process_image(
content, storage_path, file_id
)
if preview_path:
await self.storage.upload(preview_path, content)
preview_url = await self.storage.get_url(preview_path)
elif content_type.startswith("video/"):
width, height = await self._get_video_dimensions(content)
# Upload file
await self.storage.upload(storage_path, content)
url = await self.storage.get_url(storage_path)
# Save to database
async with self.db.acquire() as conn:
attachment_id = await conn.fetchval(
"""INSERT INTO attachments
(message_id, filename, content_type, size_bytes,
storage_path, width, height, is_spoiler)
VALUES (NULL, $1, $2, $3, $4, $5, $6, FALSE)
RETURNING id""",
file.filename or "unknown", content_type, len(content),
storage_path, width, height
)
return {
"id": str(attachment_id),
"filename": file.filename,
"content_type": content_type,
"size_bytes": len(content),
"url": url,
"preview_url": preview_url,
"width": width,
"height": height
}
async def _process_image(
self,
content: bytes,
storage_path: str,
file_id: uuid.UUID
) -> Tuple[Optional[int], Optional[int], Optional[str]]:
"""Process image: resize if needed, generate preview."""
try:
img = Image.open(io.BytesIO(content))
# Get original dimensions
width, height = img.size
# Check if resize needed
if width > self.MAX_IMAGE_DIMENSION or height > self.MAX_IMAGE_DIMENSION:
img.thumbnail((self.MAX_IMAGE_DIMENSION, self.MAX_IMAGE_DIMENSION))
output = io.BytesIO()
img.save(output, format="PNG")
content = output.getvalue()
# Generate thumbnail preview
preview_path = f"previews/{file_id}.png"
thumbnail = img.copy()
thumbnail.thumbnail((320, 320))
output = io.BytesIO()
thumbnail.save(output, format="PNG")
preview_content = output.getvalue()
# Store preview content separately
# (In production, upload preview to storage)
return width, height, preview_path
except Exception as e:
logger.error(f"Error processing image: {e}")
return None, None, None
async def _get_video_dimensions(self, content: bytes) -> Tuple[Optional[int], Optional[int]]:
"""Get video dimensions using ffmpeg or similar."""
# Implementation would use ffmpeg subprocess
return None, None
def _detect_content_type(self, content: bytes, filename: str) -> str:
"""Detect content type from file magic bytes."""
# Simple detection using magic bytes
if content.startswith(b'\x89PNG\r\n\x1a\n'):
return "image/png"
elif content.startswith(b'\xff\xd8\xff'):
return "image/jpeg"
elif content.startswith(b'GIF87a') or content.startswith(b'GIF89a'):
return "image/gif"
elif content.startswith(b'RIFF') and b'WEBP' in content[:12]:
return "image/webp"
elif content.startswith(b'%PDF'):
return "application/pdf"
else:
# Guess from filename
ext = os.path.splitext(filename or "")[1].lower()
mime_map = {
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.mp3': 'audio/mpeg',
'.ogg': 'audio/ogg',
'.wav': 'audio/wav',
'.pdf': 'application/pdf',
'.txt': 'text/plain',
}
return mime_map.get(ext, 'application/octet-stream')
def _is_allowed_type(self, content_type: str) -> bool:
"""Check if content type is allowed."""
all_allowed = (
self.ALLOWED_IMAGES +
self.ALLOWED_VIDEOS +
self.ALLOWED_AUDIO +
self.ALLOWED_DOCUMENTS
)
return content_type in all_allowed
async def attach_to_message(
self,
attachment_id: int,
message_id: int
) -> bool:
"""Link an attachment to a message."""
async with self.db.acquire() as conn:
result = await conn.execute(
"UPDATE attachments SET message_id = $1 WHERE id = $2",
message_id, attachment_id
)
return result != "UPDATE 0"
async def get_attachment(self, attachment_id: int) -> Optional[dict]:
"""Get attachment metadata."""
async with self.db.acquire() as conn:
row = await conn.fetchrow(
"SELECT * FROM attachments WHERE id = $1",
attachment_id
)
if not row:
return None
return {
"id": str(row["id"]),
"filename": row["filename"],
"content_type": row["content_type"],
"size_bytes": row["size_bytes"],
"url": await self.storage.get_url(row["storage_path"]),
"width": row["width"],
"height": row["height"],
"is_spoiler": row["is_spoiler"]
}
HTTP API endpoint:
from fastapi import Depends
@app.post("/api/v1attachments/upload")
async def upload_file(
file: UploadFile = File(...),
current_user: User = Depends(get_current_user)
):
"""Upload a file."""
handler = FileUploadHandler(storage_backend, db_pool)
result = await handler.upload_file(
file,
current_user.id,
is_nitro=current_user.is_nitro
)
return result
@app.get("/api/v1/attachments/{attachment_id}")
async def get_attachment(attachment_id: int):
"""Get attachment metadata."""
handler = FileUploadHandler(storage_backend, db_pool)
result = await handler.get_attachment(attachment_id)
if not result:
raise HTTPException(status_code=404, detail="Attachment not found")
return result
Storage backend interface:
class StorageBackend:
"""Interface for file storage (S3 or local)."""
async def upload(self, path: str, content: bytes):
"""Upload file to storage."""
raise NotImplementedError
async def download(self, path: str) -> bytes:
"""Download file from storage."""
raise NotImplementedError
async def delete(self, path: str):
"""Delete file from storage."""
raise NotImplementedError
async def get_url(self, path: str) -> str:
"""Get public URL for file."""
raise NotImplementedError
class S3Storage(StorageBackend):
"""S3-compatible storage backend."""
def __init__(self, bucket: str, region: str):
self.bucket = bucket
self.region = region
self.client = ... # boto3 or aiobotocore client
async def upload(self, path: str, content: bytes):
await self.client.put_object(
Bucket=self.bucket,
Key=path,
Body=content
)
async def get_url(self, path: str) -> str:
return f"https://{self.bucket}.s3.{self.region}.amazonaws.com/{path}"
class LocalStorage(StorageBackend):
"""Local filesystem storage for development."""
def __init__(self, base_path: str):
self.base_path = base_path
async def upload(self, path: str, content: bytes):
full_path = os.path.join(self.base_path, path)
os.makedirs(os.path.dirname(full_path), exist_ok=True)
with open(full_path, 'wb') as f:
f.write(content)
async def get_url(self, path: str) -> str:
return f"/files/{path}"
Acceptance Criteria
- File upload succeeds for allowed types
- File size limit enforced
- Image thumbnails generated
- Attachment metadata stored correctly
- Attachment can be linked to message
- Invalid content types rejected
- File URL is accessible
Notes
Trade-offs:
- S3 vs local storage: S3 for production, local for development
- Thumbnail generation: Synchronous for simplicity, can be async
Performance:
- Use CDN for file delivery
- Consider lazy loading previews
Alternatives considered:
- Store files in database: Rejected, bloats database
- External hosting (imgur): Rejected, want control