from datetime import datetime, timezone from uuid import uuid4 from backend.app.core.security import clean_url from backend.app.database import get_connection def create_link(user_id: str, title: str, url: str, comment: str, timestamp: str | None): cleaned_url = clean_url(url) created_at = datetime.now(timezone.utc).isoformat() record = { 'id': str(uuid4()), 'user_id': user_id, 'title': title, 'url': cleaned_url, 'comment': comment, 'timestamp': timestamp or created_at, 'created_at': created_at, 'updated_at': created_at, 'is_public': 1, } with get_connection() as conn: conn.execute( ''' INSERT INTO links (id, user_id, title, url, comment, timestamp, created_at, updated_at, is_public) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ''', ( record['id'], record['user_id'], record['title'], record['url'], record['comment'], record['timestamp'], record['created_at'], record['updated_at'], record['is_public'], ), ) conn.commit() return record def list_public_links(username: str | None = None): with get_connection() as conn: rows = conn.execute( ''' SELECT links.*, users.username, users.avatar_url, users.bio FROM links JOIN users ON users.id = links.user_id WHERE links.is_public = 1 AND (? IS NULL OR users.username = ?) ORDER BY created_at DESC ''', (username, username), ).fetchall() return [dict(row) for row in rows]