feat: share heaps and folders with other users, fix auth and vision pipeline

Sharing:
- New HeapShare and FolderShare models with read/write permissions
- Sharing API router (CRUD for heap and folder shares)
- Heap endpoints accept shared access (photo_ids, add/remove with write)
- Photo list drops user_id filter in shared context, adds owner_username
- Media serving (thumb/original/proxy) falls back to share check on 404
- ShareDialog component for managing shares from kebab menus
- HeapsPanel shows "Shared with me" section for shared heaps
- LeftSidebar shows "Shared with me" section for shared folders
- Owner badge on PhotoThumbnail for photos from other users

Auth:
- Access token default bumped to 1 year, refresh to 10 years
- Refresh token persisted in localStorage (survives page reload)
- Timer-based refresh replaced with 401 axios interceptor

Vision pipeline fixes:
- Bootstrap sets Redis ready key even on partial export failure
- Export functions run conditionally (only for actually missing models)
- _load_thumb handles multi-user path (/data/thumbs/{user_id}/{photo_id}/)
- can_access_photo_via_share uses single subquery instead of N+1 loop

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
root
2026-04-13 10:59:07 +02:00
parent f090a809a9
commit edd569d095
20 changed files with 1247 additions and 87 deletions

View File

@@ -26,7 +26,11 @@ from app.models.tags import photo_tags
from app.schemas.photos import PhotoResponse, PhotoUpdate, PhotoListResponse, BulkAction
from app.services.exif_writer import ExifWriteError, write_taken_at
from app.services.date_guess import has_date_warning as compute_date_warning
from app.dependencies import get_current_user, get_current_user_media, get_user_photo
from app.dependencies import (
get_current_user, get_current_user_media, get_user_photo,
get_user_or_shared_heap, get_user_or_shared_folder,
can_access_photo_via_share,
)
from app.config import settings
router = APIRouter()
@@ -56,10 +60,34 @@ async def list_photos(
):
"""List photos with filters and pagination"""
# Determine if this request is for shared content. When viewing a
# shared heap or folder the user_id filter is replaced by the
# heap/folder join that already encodes authorization.
is_shared_context = False
if heap_id:
try:
_heap, _perm = await get_user_or_shared_heap(heap_id, current_user, db)
if _perm != "owner":
is_shared_context = True
except Exception:
raise HTTPException(status_code=404, detail="Heap not found")
if folder_id and not is_shared_context:
try:
_folder, _perm = await get_user_or_shared_folder(folder_id, current_user, db)
if _perm != "owner":
is_shared_context = True
except Exception:
raise HTTPException(status_code=404, detail="Folder not found")
# Build query — eager-load tags so the response can include them
# without an N+1 round-trip per photo. Scoped to the current user.
query = select(Photo).options(selectinload(Photo.tags)).where(Photo.user_id == current_user.id)
# without an N+1 round-trip per photo. Scoped to the current user
# unless we're in a shared context (scoped by heap/folder instead).
query = select(Photo).options(selectinload(Photo.tags))
if not is_shared_context:
query = query.where(Photo.user_id == current_user.id)
# Apply filters
filters = []
@@ -299,6 +327,17 @@ async def list_photos(
# Convert to response, attaching tags inline so the frontend can group
# client-side without a second round-trip.
# In shared context, resolve owner usernames for photos from other users.
owner_cache: dict[str, str] = {} # user_id → username
if is_shared_context:
other_user_ids = {p.user_id for p in photos if p.user_id != current_user.id}
if other_user_ids:
from app.models.user import User as UserModel
user_result = await db.execute(
select(UserModel.id, UserModel.username).where(UserModel.id.in_(other_user_ids))
)
owner_cache = {uid: uname for uid, uname in user_result.all()}
photo_dicts = []
for photo in photos:
d = PhotoResponse.from_orm(photo).dict()
@@ -306,6 +345,8 @@ async def list_photos(
{"id": t.id, "name": t.name, "color": t.color}
for t in (photo.tags or [])
]
if is_shared_context and photo.user_id != current_user.id:
d["owner_username"] = owner_cache.get(photo.user_id)
photo_dicts.append(d)
response = {
@@ -500,6 +541,33 @@ async def remove_photo_tag(
await db.commit()
return None
async def _get_photo_with_share_fallback(
photo_id: str, user: User, db: AsyncSession,
) -> Photo:
"""Fetch a photo the user owns, or one they can access via a share.
The fast path (owned photo) does a single indexed query. The share
fallback only runs when the first query returns nothing — this
happens only for shared photos, not during normal browsing.
"""
# Fast path — owned photo (single indexed query, no extra joins).
result = await db.execute(
select(Photo).where(Photo.id == photo_id, Photo.user_id == user.id)
)
photo = result.scalar_one_or_none()
if photo:
return photo
# Slow path — check share access (only for shared photos).
if await can_access_photo_via_share(photo_id, user, db):
result = await db.execute(
select(Photo).where(Photo.id == photo_id)
)
photo = result.scalar_one_or_none()
if photo:
return photo
raise HTTPException(status_code=404, detail="Photo not found")
@router.get("/{photo_id}/thumb/{size}")
async def get_thumbnail(
photo_id: str,
@@ -512,7 +580,7 @@ async def get_thumbnail(
if size not in ['small', 'medium', 'large']:
raise HTTPException(status_code=400, detail="Invalid thumbnail size")
photo = await get_user_photo(photo_id, current_user, db)
photo = await _get_photo_with_share_fallback(photo_id, current_user, db)
# Check if thumbnail exists, generate if not.
# User-prefixed path for isolation.
@@ -596,7 +664,7 @@ async def get_original(
current_user: User = Depends(get_current_user_media),
):
"""Serve original file (download for RAW, inline for web-safe formats)"""
photo = await get_user_photo(photo_id, current_user, db)
photo = await _get_photo_with_share_fallback(photo_id, current_user, db)
if not os.path.exists(photo.filepath):
raise HTTPException(status_code=404, detail="File not found")
@@ -699,7 +767,7 @@ async def get_proxy(
current_user: User = Depends(get_current_user_media),
):
"""Serve a full-resolution WebP proxy for non-web-safe formats."""
photo = await get_user_photo(photo_id, current_user, db)
photo = await _get_photo_with_share_fallback(photo_id, current_user, db)
if not os.path.exists(photo.filepath):
raise HTTPException(status_code=404, detail="File not found")