diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..30cf57e
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,10 @@
+# Default ignored files
+/shelf/
+/workspace.xml
+# Editor-based HTTP Client requests
+/httpRequests/
+# Ignored default folder with query files
+/queries/
+# Datasource local storage ignored files
+/dataSources/
+/dataSources.local.xml
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..eb5df17
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..591699b
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..94a25f7
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/DEPLOYMENT.md b/DEPLOYMENT.md
new file mode 100644
index 0000000..1a12929
--- /dev/null
+++ b/DEPLOYMENT.md
@@ -0,0 +1,354 @@
+# Private Studio - Video Transcoding Web Service
+
+A FastAPI-based video transcoding management service with S3-compatible file uploads, API key authentication, and per-user resource isolation.
+
+## Features
+
+- **S3-Compatible Interface**: Upload, download, delete, and list files using S3-compatible HTTP endpoints
+- **API Key Authentication**: Secure bearer token authentication with per-user isolation
+- **YAML-Based Transcode API**: Request transcode jobs and manage encoding profiles via YAML
+- **SQLite Database**: Lightweight file-based database with SQLAlchemy ORM
+- **User Management**: Create users and API keys via CLI
+
+## Installation
+
+Install the package with all dependencies:
+
+```bash
+pip install -e .
+```
+
+Or install development dependencies:
+
+```bash
+pip install -e ".[dev]"
+```
+
+## Quick Start
+
+### 1. Initialize Database
+
+```bash
+ps-serve init
+```
+
+This creates a `transcoding.db` file in the current directory.
+
+### 2. Create a User
+
+```bash
+ps-serve create-user myuser
+```
+
+### 3. Create an API Key
+
+```bash
+ps-serve create-key 1
+```
+
+This outputs an API key that should be kept secret:
+
+```
+API key created for user 1
+Key: 4YXDJoXf26auwGFQPKB6aB-kY6HxbkKPJzmWFbs7cnM
+Keep this key safe - you won't be able to see it again!
+```
+
+### 4. Start the Server
+
+```bash
+ps-serve serve
+```
+
+The server will start at `http://localhost:8000`
+
+## Configuration
+
+Environment variables:
+
+- `DATABASE_URL`: SQLite database path (default: `./transcoding.db`)
+- `STORAGE_PATH`: File storage directory (default: `./storage`)
+- `SERVER_HOST`: Server host address (default: `0.0.0.0`)
+- `SERVER_PORT`: Server port (default: `8000`)
+- `SQL_ECHO`: Enable SQL query logging (default: `false`)
+
+Example:
+
+```bash
+export DATABASE_URL="sqlite:///./my_transcoding.db"
+export STORAGE_PATH="./media"
+ps-serve serve --host 127.0.0.1 --port 8080
+```
+
+## API Usage
+
+### Authentication
+
+All endpoints require an API key via Bearer token:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" http://localhost:8000/api/keys
+```
+
+### S3-Compatible File Operations
+
+Upload a file:
+
+```bash
+curl -X PUT \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -F "file=@video.mp4" \
+ http://localhost:8000/s3/1/videos/video.mp4
+```
+
+Download a file:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/s3/1/videos/video.mp4 \
+ -o video.mp4
+```
+
+List files:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/s3/1
+```
+
+Delete a file:
+
+```bash
+curl -X DELETE \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/s3/1/videos/video.mp4
+```
+
+### Transcode Profile Management
+
+Create a profile:
+
+```bash
+curl -X POST \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/yaml" \
+ -d @profile.yaml \
+ http://localhost:8000/api/profiles?name=my-profile
+```
+
+Where `profile.yaml`:
+
+```yaml
+profiles:
+ hd:
+ resolution: "1280x720"
+ bitrate: "2500k"
+ fps: 30
+ sd:
+ resolution: "854x480"
+ bitrate: "1000k"
+ fps: 30
+```
+
+List profiles:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/profiles
+```
+
+### Transcode Job Requests
+
+Request a transcode job with a stored profile:
+
+```bash
+curl -X POST \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/yaml" \
+ -d 'asset: video.mp4
+profile: my-profile' \
+ http://localhost:8000/api/transcode
+```
+
+Or with an inline profile:
+
+```bash
+curl -X POST \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ -H "Content-Type: application/yaml" \
+ -d 'asset: video.mp4
+profile:
+ profiles:
+ hd:
+ resolution: "1280x720"
+ bitrate: "2500k"' \
+ http://localhost:8000/api/transcode
+```
+
+Get job status:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/transcode/1
+```
+
+List jobs:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/transcode
+```
+
+List jobs by status:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/transcode?status=pending
+```
+
+### API Key Management
+
+Create an API key:
+
+```bash
+curl -X POST \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/keys
+```
+
+List keys:
+
+```bash
+curl -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/keys
+```
+
+Revoke a key:
+
+```bash
+curl -X DELETE \
+ -H "Authorization: Bearer YOUR_API_KEY" \
+ http://localhost:8000/api/keys/KEY_ID
+```
+
+## Testing
+
+Run the test suite:
+
+```bash
+pytest tests/test_web.py -v
+```
+
+## Database Schema
+
+### Users
+
+- `id`: Primary key
+- `username`: Unique username
+- `created_at`: Creation timestamp
+
+### API Keys
+
+- `id`: Primary key
+- `key_hash`: SHA256 hash of the API key
+- `user_id`: Foreign key to users
+- `created_at`: Creation timestamp
+- `is_active`: Whether the key is active
+
+### Uploaded Assets
+
+- `id`: Primary key
+- `user_id`: Foreign key to users
+- `filename`: Original filename
+- `size`: File size in bytes
+- `s3_path`: Path relative to storage root
+- `upload_timestamp`: Upload time
+
+### Transcode Profiles
+
+- `id`: Primary key
+- `user_id`: Foreign key to users
+- `name`: Profile name
+- `profile_definition`: YAML definition as string
+- `created_at`: Creation timestamp
+
+### Transcode Jobs
+
+- `id`: Primary key
+- `user_id`: Foreign key to users
+- `asset_id`: Foreign key to uploaded_assets
+- `profile_id`: Foreign key to transcode_profiles (nullable for inline profiles)
+- `status`: Job status (pending, in_progress, completed, failed)
+- `requested_at`: Request timestamp
+- `completed_at`: Completion timestamp (nullable)
+
+### Packaging Jobs
+
+- `id`: Primary key
+- `user_id`: Foreign key to users
+- `transcode_job_id`: Foreign key to transcode_jobs
+- `status`: Job status (pending, in_progress, completed, failed)
+- `requested_at`: Request timestamp
+- `completed_at`: Completion timestamp (nullable)
+
+### Transcoded Assets
+
+- `id`: Primary key
+- `user_id`: Foreign key to users
+- `transcode_job_id`: Foreign key to transcode_jobs
+- `filename`: Output filename
+- `s3_path`: Path relative to storage root
+- `format`: Output format (e.g., "mp4", "audio")
+- `created_at`: Creation timestamp
+
+## Architecture
+
+### Authentication
+
+API keys are stored as SHA256 hashes in the database and validated via FastAPI's HTTPBearer security scheme. Each authenticated endpoint receives the user context automatically.
+
+### Per-User Isolation
+
+All resources (assets, profiles, jobs) are scoped to the authenticated user. Users can only access their own resources, enforced at the database query level.
+
+### File Storage
+
+Files are stored on disk in user-specific directories under `STORAGE_PATH`:
+
+```
+storage/
+├── 1/ (user 1)
+│ ├── video1.mp4
+│ └── video2.mp4
+└── 2/ (user 2)
+ └── presentation.mp4
+```
+
+Symlink traversal attacks are prevented by validating file paths.
+
+## Development
+
+### Enable Auto-Reload
+
+```bash
+ps-serve serve --reload
+```
+
+### View SQL Queries
+
+```bash
+export SQL_ECHO=true
+ps-serve serve
+```
+
+### Run Tests
+
+```bash
+pytest tests/test_web.py -v
+```
+
+With coverage:
+
+```bash
+pytest tests/test_web.py --cov=privatestudio.web --cov-report=html
+```
diff --git a/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025-py3-none-any.whl b/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025-py3-none-any.whl
new file mode 100644
index 0000000..f34d325
Binary files /dev/null and b/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025-py3-none-any.whl differ
diff --git a/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025.tar.gz b/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025.tar.gz
new file mode 100644
index 0000000..e167b23
Binary files /dev/null and b/dist/privatestudio-0.2.dev0+gf637e34ea.d20261025.tar.gz differ
diff --git a/privatestudio.egg-info/PKG-INFO b/privatestudio.egg-info/PKG-INFO
new file mode 100644
index 0000000..a785d04
--- /dev/null
+++ b/privatestudio.egg-info/PKG-INFO
@@ -0,0 +1,59 @@
+Metadata-Version: 2.4
+Name: privatestudio
+Version: 0.2.dev1+g72b4fcc10.d20261026
+Summary: Video transcoding tools with multi-profile H.264 encoding support
+Requires-Python: >=3.8
+Description-Content-Type: text/markdown
+Requires-Dist: PyYAML>=6.0
+Requires-Dist: FastAPI>=0.100.0
+Requires-Dist: uvicorn[standard]>=0.23.0
+Requires-Dist: SQLAlchemy>=2.0.0
+Requires-Dist: python-multipart>=0.0.5
+Provides-Extra: dev
+Requires-Dist: pytest>=7.0; extra == "dev"
+Requires-Dist: pytest-cov>=4.0; extra == "dev"
+Requires-Dist: httpx>=0.27.0; extra == "dev"
+
+To output individual MP4 files for subsequent Bento4 packaging, you need to ensure the video streams are perfectly aligned. This requires forcing fixed GOP sizes (Keyframe intervals) and disabling scene-change detection.
+The FFmpeg Command
+This command takes input.mp4 and splits it into three separate, fragmented-friendly MP4 files (1080p, 720p, and 480p) plus one standalone audio track:
+
+```bash
+ffmpeg -y -i input.mp4 \
+-map 0:v:0 -map 0:v:0 -map 0:v:0 -map 0:a:0 \
+-g 72 -keyint_min 72 -sc_threshold 0 \
+-c:v:0 libx264 -b:v:0 5000k -maxrate:v:0 5350k -bufsize:v:0 7500k -filter:v:0 "scale=-2:1080" -an output_1080p.mp4 \
+-c:v:1 libx264 -b:v:1 2800k -maxrate:v:1 2996k -bufsize:v:1 4200k -filter:v:1 "scale=-2:720" -an output_720p.mp4 \
+-c:v:2 libx264 -b:v:2 1400k -maxrate:v:2 1498k -bufsize:v:2 2100k -filter:v:2 "scale=-2:480" -an output_480p.mp4 \
+-c:a aac -b:a 128k -vn output_audio.mp4
+```
+
+## Critical Settings for Bento4
+ * -g 72 -keyint_min 72: Forces a keyframe exactly every 72 frames. At 24fps, this yields an exact 3-second fragment duration.
+ * -sc_threshold 0: Disables adaptive scene-change keyframes. Without this, your streams will have misaligned keyframes, and Bento4 will fail to package them as a single adaptive HLS stream.
+ * -an and -vn: Separates the audio from the video files. Bento4 handles multiplexing and packaging best when audio and video tracks are fed as distinct source files.
+
+
+# Configuring for quicksync
+
+1:N transcoding workflow that leverages the GPU hardware filter scale_qsv. This reads the input frame once, scales it on the Intel GPU, and encodes both outputs simultaneously.
+
+```bash
+ffmpeg -hwaccel qsv -c:v h264_qsv -i input.mp4 \
+ -filter_complex "[0:v]split=2[s1][s2]; \
+ [s1]scale_qsv=w=1280:h=720[v720]; \
+ [s2]scale_qsv=w=854:h=480[v480]" \
+ -map "[v720]" -c:v h264_qsv -b:v 2500k -maxrate 2500k -bufsize 5000k \
+ -g 60 -keyint_min 60 -sc_threshold 0 -forced-idr 1 -an video_720p.mp4 \
+ -map "[v480]" -c:v h264_qsv -b:v 1000k -maxrate 1000k -bufsize 2000k \
+ -g 60 -keyint_min 60 -sc_threshold 0 -forced-idr 1 -an video_480p.mp4 \
+ -map 0:a? -c:a aac -b:a 128k audio.mp4
+```
+
+Key Argument Explanations:
+ * -hwaccel qsv -c:v h264_qsv: Invokes hardware decoding and initialization.
+ * scale_qsv=w=...:h=...: Tells the Intel GPU to handle the video resizing directly inside the Quick Sync processing pipeline.
+ * -g 60 -keyint_min 60: Dictates the GOP size (assuming a 30fps input video, a GOP of 60 forces a keyframe exactly every 2 seconds).
+ * -sc_threshold 0: Disables scene change detection to ensure keyframes are purely fixed.
+ * -forced-idr 1: Forces the QSV encoder to use actual IDR frames instead of basic I-frames at the GOP boundary, which is necessary for fragmenting tools.
+ * -an: Strips audio out of the video streams so Bento4 can package them as clean, isolated tracks.
diff --git a/privatestudio.egg-info/SOURCES.txt b/privatestudio.egg-info/SOURCES.txt
new file mode 100644
index 0000000..71945bd
--- /dev/null
+++ b/privatestudio.egg-info/SOURCES.txt
@@ -0,0 +1,15 @@
+notes.md
+pyproject.toml
+privatestudio/__init__.py
+privatestudio/_version.py
+privatestudio/transcode.py
+privatestudio.egg-info/PKG-INFO
+privatestudio.egg-info/SOURCES.txt
+privatestudio.egg-info/dependency_links.txt
+privatestudio.egg-info/entry_points.txt
+privatestudio.egg-info/requires.txt
+privatestudio.egg-info/scm_file_list.json
+privatestudio.egg-info/scm_version.json
+privatestudio.egg-info/top_level.txt
+profiles/default.yaml
+tests/test_web.py
\ No newline at end of file
diff --git a/privatestudio.egg-info/dependency_links.txt b/privatestudio.egg-info/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/privatestudio.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/privatestudio.egg-info/entry_points.txt b/privatestudio.egg-info/entry_points.txt
new file mode 100644
index 0000000..d91cd01
--- /dev/null
+++ b/privatestudio.egg-info/entry_points.txt
@@ -0,0 +1,3 @@
+[console_scripts]
+ps-serve = privatestudio.web.cli:main
+ps-transcode = privatestudio.transcode:main
diff --git a/privatestudio.egg-info/requires.txt b/privatestudio.egg-info/requires.txt
new file mode 100644
index 0000000..aaa6780
--- /dev/null
+++ b/privatestudio.egg-info/requires.txt
@@ -0,0 +1,10 @@
+PyYAML>=6.0
+FastAPI>=0.100.0
+uvicorn[standard]>=0.23.0
+SQLAlchemy>=2.0.0
+python-multipart>=0.0.5
+
+[dev]
+pytest>=7.0
+pytest-cov>=4.0
+httpx>=0.27.0
diff --git a/privatestudio.egg-info/scm_file_list.json b/privatestudio.egg-info/scm_file_list.json
new file mode 100644
index 0000000..aa53a69
--- /dev/null
+++ b/privatestudio.egg-info/scm_file_list.json
@@ -0,0 +1,9 @@
+{
+ "files": [
+ "notes.md",
+ "privatestudio/__init__.py",
+ "privatestudio/transcode.py",
+ "profiles/default.yaml",
+ "pyproject.toml"
+ ]
+}
diff --git a/privatestudio.egg-info/scm_version.json b/privatestudio.egg-info/scm_version.json
new file mode 100644
index 0000000..8c09689
--- /dev/null
+++ b/privatestudio.egg-info/scm_version.json
@@ -0,0 +1,8 @@
+{
+ "tag": "0.1",
+ "distance": 1,
+ "node": "g72b4fcc1071dc2a9395829c3e8ac257cfd93a127",
+ "dirty": true,
+ "branch": "main",
+ "node_date": "2026-10-26"
+}
diff --git a/privatestudio.egg-info/top_level.txt b/privatestudio.egg-info/top_level.txt
new file mode 100644
index 0000000..25063ab
--- /dev/null
+++ b/privatestudio.egg-info/top_level.txt
@@ -0,0 +1 @@
+privatestudio
diff --git a/privatestudio/__pycache__/__init__.cpython-313.pyc b/privatestudio/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000..5f4494e
Binary files /dev/null and b/privatestudio/__pycache__/__init__.cpython-313.pyc differ
diff --git a/privatestudio/_version.py b/privatestudio/_version.py
new file mode 100644
index 0000000..ef74ff3
--- /dev/null
+++ b/privatestudio/_version.py
@@ -0,0 +1,24 @@
+# file generated by vcs-versioning
+# don't change, don't track in version control
+from __future__ import annotations
+
+__all__ = [
+ "__version__",
+ "__version_tuple__",
+ "version",
+ "version_tuple",
+ "__commit_id__",
+ "commit_id",
+]
+
+version: str
+__version__: str
+__version_tuple__: tuple[int | str, ...]
+version_tuple: tuple[int | str, ...]
+commit_id: str | None
+__commit_id__: str | None
+
+__version__ = version = '0.2.dev1+g72b4fcc10.d20261026'
+__version_tuple__ = version_tuple = (0, 2, 'dev1', 'g72b4fcc10.d20261026')
+
+__commit_id__ = commit_id = 'g72b4fcc10'
diff --git a/privatestudio/web/__init__.py b/privatestudio/web/__init__.py
new file mode 100644
index 0000000..739198c
--- /dev/null
+++ b/privatestudio/web/__init__.py
@@ -0,0 +1 @@
+"""Web service for video transcoding management."""
diff --git a/privatestudio/web/__pycache__/__init__.cpython-313.pyc b/privatestudio/web/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000..b44e122
Binary files /dev/null and b/privatestudio/web/__pycache__/__init__.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/app.cpython-313.pyc b/privatestudio/web/__pycache__/app.cpython-313.pyc
new file mode 100644
index 0000000..d0dcfc3
Binary files /dev/null and b/privatestudio/web/__pycache__/app.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/auth.cpython-313.pyc b/privatestudio/web/__pycache__/auth.cpython-313.pyc
new file mode 100644
index 0000000..44c55b8
Binary files /dev/null and b/privatestudio/web/__pycache__/auth.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/cli.cpython-313.pyc b/privatestudio/web/__pycache__/cli.cpython-313.pyc
new file mode 100644
index 0000000..2036ea6
Binary files /dev/null and b/privatestudio/web/__pycache__/cli.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/database.cpython-313.pyc b/privatestudio/web/__pycache__/database.cpython-313.pyc
new file mode 100644
index 0000000..e7ba111
Binary files /dev/null and b/privatestudio/web/__pycache__/database.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/models.cpython-313.pyc b/privatestudio/web/__pycache__/models.cpython-313.pyc
new file mode 100644
index 0000000..58245c3
Binary files /dev/null and b/privatestudio/web/__pycache__/models.cpython-313.pyc differ
diff --git a/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc b/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc
new file mode 100644
index 0000000..60bd017
Binary files /dev/null and b/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc differ
diff --git a/privatestudio/web/app.py b/privatestudio/web/app.py
new file mode 100644
index 0000000..a4d2244
--- /dev/null
+++ b/privatestudio/web/app.py
@@ -0,0 +1,50 @@
+"""FastAPI application setup and configuration."""
+from fastapi import FastAPI
+from fastapi.middleware.cors import CORSMiddleware
+from fastapi.responses import JSONResponse
+
+from privatestudio.web.database import init_db
+from privatestudio.web.routes import assets, transcode, profiles, keys
+
+# Initialize database
+init_db()
+
+# Create FastAPI app
+app = FastAPI(
+ title="Private Studio",
+ description="Video transcoding web service with S3-compatible interface",
+ version="0.1.0",
+)
+
+# Add CORS middleware
+app.add_middleware(
+ CORSMiddleware,
+ allow_origins=["*"], # Configure in production
+ allow_credentials=True,
+ allow_methods=["*"],
+ allow_headers=["*"],
+)
+
+
+@app.get("/health")
+async def health_check():
+ """Health check endpoint."""
+ return {"status": "ok"}
+
+
+# Include routes
+app.include_router(keys.router, prefix="/api", tags=["Keys"])
+app.include_router(assets.router, prefix="/s3", tags=["S3"])
+app.include_router(transcode.router, prefix="/api", tags=["Transcode"])
+app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
+
+
+@app.exception_handler(ValueError)
+async def value_error_handler(request, exc):
+ """Handle ValueError exceptions."""
+ return JSONResponse(status_code=400, content={"detail": str(exc)})
+
+
+if __name__ == "__main__":
+ import uvicorn
+ uvicorn.run(app, host="0.0.0.0", port=8000)
diff --git a/privatestudio/web/auth.py b/privatestudio/web/auth.py
new file mode 100644
index 0000000..0541214
--- /dev/null
+++ b/privatestudio/web/auth.py
@@ -0,0 +1,124 @@
+"""API key authentication and user management."""
+import secrets
+import hashlib
+import hmac
+from fastapi import Depends, HTTPException, status
+from fastapi.security import HTTPBearer
+from sqlalchemy.orm import Session
+
+from privatestudio.web.models import User, APIKey
+from privatestudio.web.database import get_db
+
+
+def hash_api_key(key: str) -> str:
+ """Hash an API key using SHA256."""
+ return hashlib.sha256(key.encode()).hexdigest()
+
+
+def verify_api_key(plain_key: str, hashed_key: str) -> bool:
+ """Verify a plain API key against its hash."""
+ return hmac.compare_digest(hash_api_key(plain_key), hashed_key)
+
+
+def generate_api_key() -> str:
+ """Generate a random API key."""
+ return secrets.token_urlsafe(32)
+
+
+def create_user(db: Session, username: str) -> User:
+ """Create a new user account."""
+ # Check if user already exists
+ existing_user = db.query(User).filter(User.username == username).first()
+ if existing_user:
+ raise ValueError(f"User '{username}' already exists")
+
+ user = User(username=username)
+ db.add(user)
+ db.commit()
+ db.refresh(user)
+ return user
+
+
+def create_api_key(db: Session, user_id: int) -> tuple[str, APIKey]:
+ """
+ Create a new API key for a user.
+
+ Returns: (plain_key, api_key_record)
+ The plain key should be given to the user and never stored. Only the hash is saved.
+ """
+ plain_key = generate_api_key()
+ key_hash = hash_api_key(plain_key)
+
+ api_key = APIKey(key_hash=key_hash, user_id=user_id, is_active=True)
+ db.add(api_key)
+ db.commit()
+ db.refresh(api_key)
+
+ return plain_key, api_key
+
+
+def revoke_api_key(db: Session, key_id: int):
+ """Revoke an API key by marking it inactive."""
+ api_key = db.query(APIKey).filter(APIKey.id == key_id).first()
+ if not api_key:
+ raise ValueError(f"API key {key_id} not found")
+
+ api_key.is_active = False
+ db.commit()
+
+
+def get_current_user(
+ credentials: HTTPBearer = Depends(HTTPBearer()),
+ db: Session = Depends(get_db),
+) -> User:
+ """
+ FastAPI dependency to validate API key and return authenticated user.
+
+ Usage:
+ @app.get("/api/assets")
+ def list_assets(current_user: User = Depends(get_current_user)):
+ ...
+ """
+ if credentials is None:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Missing credentials",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ token = credentials.credentials
+
+ # Find the API key in the database
+ api_keys = db.query(APIKey).all()
+
+ # Verify the token against each key's hash
+ matching_key = None
+ for key in api_keys:
+ if verify_api_key(token, key.key_hash):
+ matching_key = key
+ break
+
+ if not matching_key:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="Invalid API key",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ if not matching_key.is_active:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="API key is revoked",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ # Get the user
+ user = db.query(User).filter(User.id == matching_key.user_id).first()
+ if not user:
+ raise HTTPException(
+ status_code=status.HTTP_401_UNAUTHORIZED,
+ detail="User not found",
+ headers={"WWW-Authenticate": "Bearer"},
+ )
+
+ return user
diff --git a/privatestudio/web/cli.py b/privatestudio/web/cli.py
new file mode 100644
index 0000000..21b4157
--- /dev/null
+++ b/privatestudio/web/cli.py
@@ -0,0 +1,103 @@
+"""CLI entry point for the video transcoding web service."""
+import argparse
+import os
+import uvicorn
+
+from privatestudio.web.database import init_db, get_db, SessionLocal
+from privatestudio.web.auth import create_user, create_api_key
+
+
+def init_command(args):
+ """Initialize the database."""
+ init_db()
+ print("Database initialized")
+
+
+def create_user_command(args):
+ """Create a new user account."""
+ db = SessionLocal()
+ try:
+ user = create_user(db, args.username)
+ print(f"User created: {args.username} (ID: {user.id})")
+ except ValueError as e:
+ print(f"Error: {e}")
+ return 1
+ finally:
+ db.close()
+ return 0
+
+
+def create_key_command(args):
+ """Create an API key for a user."""
+ db = SessionLocal()
+ try:
+ plain_key, api_key = create_api_key(db, args.user_id)
+ print(f"API key created for user {args.user_id}")
+ print(f"Key: {plain_key}")
+ print(f"Keep this key safe - you won't be able to see it again!")
+ except ValueError as e:
+ print(f"Error: {e}")
+ return 1
+ finally:
+ db.close()
+ return 0
+
+
+def serve_command(args):
+ """Start the web server."""
+ host = args.host or os.environ.get("SERVER_HOST", "0.0.0.0")
+ port = args.port or int(os.environ.get("SERVER_PORT", "8000"))
+
+ # Initialize database if needed
+ init_db()
+
+ print(f"Starting server at {host}:{port}")
+ uvicorn.run(
+ "privatestudio.web.app:app",
+ host=host,
+ port=port,
+ reload=args.reload,
+ log_level=args.log_level,
+ )
+
+
+def main():
+ """Main entry point for CLI."""
+ parser = argparse.ArgumentParser(
+ description="Private Studio - Video transcoding web service",
+ )
+ subparsers = parser.add_subparsers(dest="command", help="Command to run")
+
+ # Init command
+ init_parser = subparsers.add_parser("init", help="Initialize the database")
+ init_parser.set_defaults(func=init_command)
+
+ # Create user command
+ user_parser = subparsers.add_parser("create-user", help="Create a new user")
+ user_parser.add_argument("username", help="Username for the new account")
+ user_parser.set_defaults(func=create_user_command)
+
+ # Create key command
+ key_parser = subparsers.add_parser("create-key", help="Create an API key for a user")
+ key_parser.add_argument("user_id", type=int, help="User ID")
+ key_parser.set_defaults(func=create_key_command)
+
+ # Serve command
+ serve_parser = subparsers.add_parser("serve", help="Start the web server")
+ serve_parser.add_argument("--host", default=None, help="Server host (default: 0.0.0.0)")
+ serve_parser.add_argument("--port", type=int, default=None, help="Server port (default: 8000)")
+ serve_parser.add_argument("--reload", action="store_true", help="Enable auto-reload on code changes")
+ serve_parser.add_argument("--log-level", default="info", help="Log level (default: info)")
+ serve_parser.set_defaults(func=serve_command)
+
+ args = parser.parse_args()
+
+ if not hasattr(args, "func"):
+ parser.print_help()
+ return 1
+
+ return args.func(args) or 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/privatestudio/web/database.py b/privatestudio/web/database.py
new file mode 100644
index 0000000..98555bb
--- /dev/null
+++ b/privatestudio/web/database.py
@@ -0,0 +1,39 @@
+"""SQLAlchemy database configuration and session management."""
+import os
+from sqlalchemy import create_engine
+from sqlalchemy.orm import sessionmaker, Session
+from sqlalchemy.pool import StaticPool
+
+from privatestudio.web.models import Base
+
+# Get database path from environment, default to ./transcoding.db
+DATABASE_URL = os.environ.get("DATABASE_URL", "sqlite:///./transcoding.db")
+
+# Create engine with appropriate settings for SQLite
+engine = create_engine(
+ DATABASE_URL,
+ connect_args={"check_same_thread": False} if "sqlite" in DATABASE_URL else {},
+ poolclass=StaticPool if "sqlite" in DATABASE_URL else None,
+ echo=os.environ.get("SQL_ECHO", "false").lower() == "true",
+)
+
+SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
+
+
+def get_db() -> Session:
+ """Dependency for FastAPI to get database session."""
+ db = SessionLocal()
+ try:
+ yield db
+ finally:
+ db.close()
+
+
+def init_db():
+ """Initialize database tables."""
+ Base.metadata.create_all(bind=engine)
+
+
+def drop_db():
+ """Drop all database tables (for testing)."""
+ Base.metadata.drop_all(bind=engine)
diff --git a/privatestudio/web/models.py b/privatestudio/web/models.py
new file mode 100644
index 0000000..2162dab
--- /dev/null
+++ b/privatestudio/web/models.py
@@ -0,0 +1,122 @@
+"""SQLAlchemy ORM models for video transcoding service."""
+from datetime import datetime
+from sqlalchemy import Column, Integer, String, DateTime, ForeignKey, Boolean, Text
+from sqlalchemy.ext.declarative import declarative_base
+from sqlalchemy.orm import relationship
+
+Base = declarative_base()
+
+
+class User(Base):
+ """User account for API access."""
+ __tablename__ = "users"
+
+ id = Column(Integer, primary_key=True)
+ username = Column(String(255), unique=True, nullable=False, index=True)
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+
+ # Relationships
+ api_keys = relationship("APIKey", back_populates="user", cascade="all, delete-orphan")
+ uploaded_assets = relationship("UploadedAsset", back_populates="user", cascade="all, delete-orphan")
+ transcode_profiles = relationship("TranscodeProfile", back_populates="user", cascade="all, delete-orphan")
+ transcode_jobs = relationship("TranscodeJob", back_populates="user", cascade="all, delete-orphan")
+ packaging_jobs = relationship("PackagingJob", back_populates="user", cascade="all, delete-orphan")
+ transcoded_assets = relationship("TranscodedAsset", back_populates="user", cascade="all, delete-orphan")
+
+
+class APIKey(Base):
+ """API key for authentication."""
+ __tablename__ = "api_keys"
+
+ id = Column(Integer, primary_key=True)
+ key_hash = Column(String(255), unique=True, nullable=False, index=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+ is_active = Column(Boolean, default=True, nullable=False)
+
+ # Relationships
+ user = relationship("User", back_populates="api_keys")
+
+
+class UploadedAsset(Base):
+ """Uploaded video file."""
+ __tablename__ = "uploaded_assets"
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
+ filename = Column(String(255), nullable=False)
+ size = Column(Integer, nullable=False) # File size in bytes
+ s3_path = Column(String(255), nullable=False) # Path relative to storage root
+ upload_timestamp = Column(DateTime, nullable=False, default=datetime.utcnow)
+
+ # Relationships
+ user = relationship("User", back_populates="uploaded_assets")
+ transcode_jobs = relationship("TranscodeJob", back_populates="uploaded_asset", cascade="all, delete-orphan")
+
+
+class TranscodeProfile(Base):
+ """Predefined encoding profile."""
+ __tablename__ = "transcode_profiles"
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
+ name = Column(String(255), nullable=False)
+ profile_definition = Column(Text, nullable=False) # YAML definition as string
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+
+ # Relationships
+ user = relationship("User", back_populates="transcode_profiles")
+ transcode_jobs = relationship("TranscodeJob", back_populates="transcode_profile")
+
+
+class TranscodeJob(Base):
+ """Requested transcode operation."""
+ __tablename__ = "transcode_jobs"
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
+ asset_id = Column(Integer, ForeignKey("uploaded_assets.id"), nullable=False)
+ profile_id = Column(Integer, ForeignKey("transcode_profiles.id"), nullable=True) # Null if inline profile used
+ status = Column(String(50), nullable=False, default="pending") # pending, in_progress, completed, failed
+ requested_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+ completed_at = Column(DateTime, nullable=True)
+
+ # Relationships
+ user = relationship("User", back_populates="transcode_jobs")
+ uploaded_asset = relationship("UploadedAsset", back_populates="transcode_jobs")
+ transcode_profile = relationship("TranscodeProfile", back_populates="transcode_jobs")
+ transcoded_assets = relationship("TranscodedAsset", back_populates="transcode_job", cascade="all, delete-orphan")
+ packaging_jobs = relationship("PackagingJob", back_populates="transcode_job", cascade="all, delete-orphan")
+
+
+class PackagingJob(Base):
+ """Requested packaging operation."""
+ __tablename__ = "packaging_jobs"
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
+ transcode_job_id = Column(Integer, ForeignKey("transcode_jobs.id"), nullable=False)
+ status = Column(String(50), nullable=False, default="pending") # pending, in_progress, completed, failed
+ requested_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+ completed_at = Column(DateTime, nullable=True)
+
+ # Relationships
+ user = relationship("User", back_populates="packaging_jobs")
+ transcode_job = relationship("TranscodeJob", back_populates="packaging_jobs")
+
+
+class TranscodedAsset(Base):
+ """Output file from transcode job."""
+ __tablename__ = "transcoded_assets"
+
+ id = Column(Integer, primary_key=True)
+ user_id = Column(Integer, ForeignKey("users.id"), nullable=False, index=True)
+ transcode_job_id = Column(Integer, ForeignKey("transcode_jobs.id"), nullable=False)
+ filename = Column(String(255), nullable=False)
+ s3_path = Column(String(255), nullable=False) # Path relative to storage root
+ format = Column(String(50), nullable=False) # e.g., "mp4", "audio"
+ created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
+
+ # Relationships
+ user = relationship("User", back_populates="transcoded_assets")
+ transcode_job = relationship("TranscodeJob", back_populates="transcoded_assets")
diff --git a/privatestudio/web/routes/__init__.py b/privatestudio/web/routes/__init__.py
new file mode 100644
index 0000000..1d3b629
--- /dev/null
+++ b/privatestudio/web/routes/__init__.py
@@ -0,0 +1 @@
+"""API route handlers."""
diff --git a/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc b/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000..3a0d5ec
Binary files /dev/null and b/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc differ
diff --git a/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc b/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc
new file mode 100644
index 0000000..2253d4b
Binary files /dev/null and b/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc differ
diff --git a/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc b/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc
new file mode 100644
index 0000000..9ea5e64
Binary files /dev/null and b/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc differ
diff --git a/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc b/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc
new file mode 100644
index 0000000..bca7e65
Binary files /dev/null and b/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc differ
diff --git a/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc b/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc
new file mode 100644
index 0000000..a5a4286
Binary files /dev/null and b/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc differ
diff --git a/privatestudio/web/routes/assets.py b/privatestudio/web/routes/assets.py
new file mode 100644
index 0000000..91ceba5
--- /dev/null
+++ b/privatestudio/web/routes/assets.py
@@ -0,0 +1,122 @@
+"""S3-compatible file upload/download/delete/list endpoints."""
+from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile
+from sqlalchemy.orm import Session
+
+from privatestudio.web.database import get_db
+from privatestudio.web.models import User, UploadedAsset
+from privatestudio.web.auth import get_current_user
+from privatestudio.web.s3_interface import get_storage
+
+router = APIRouter()
+
+
+@router.put("/{user_id}/{key:path}")
+async def upload_file(
+ user_id: int,
+ key: str,
+ file: UploadFile = File(...),
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Upload a file to S3-compatible storage."""
+ # Verify user is uploading to their own bucket
+ if user_id != current_user.id:
+ raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
+
+ # Read file content
+ content = await file.read()
+
+ # Store file
+ storage = get_storage()
+ storage.put_object(user_id, key, content)
+
+ # Record in database
+ asset = UploadedAsset(
+ user_id=user_id,
+ filename=file.filename or key.split("/")[-1],
+ size=len(content),
+ s3_path=key,
+ )
+ db.add(asset)
+ db.commit()
+ db.refresh(asset)
+
+ return {
+ "object_id": asset.id,
+ "key": key,
+ "size": len(content),
+ "filename": asset.filename,
+ }
+
+
+@router.get("/{user_id}/{key:path}")
+async def download_file(
+ user_id: int,
+ key: str,
+ current_user: User = Depends(get_current_user),
+):
+ """Download a file from S3-compatible storage."""
+ # Verify user is downloading from their own bucket
+ if user_id != current_user.id:
+ raise HTTPException(status_code=403, detail="Cannot download from another user's bucket")
+
+ # Retrieve file
+ storage = get_storage()
+ content = storage.get_object(user_id, key)
+
+ if content is None:
+ raise HTTPException(status_code=404, detail="Object not found")
+
+ # Return as binary content
+ from fastapi.responses import Response
+ return Response(content=content, media_type="application/octet-stream")
+
+
+@router.delete("/{user_id}/{key:path}")
+async def delete_file(
+ user_id: int,
+ key: str,
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Delete a file from S3-compatible storage."""
+ # Verify user is deleting from their own bucket
+ if user_id != current_user.id:
+ raise HTTPException(status_code=403, detail="Cannot delete from another user's bucket")
+
+ # Delete from storage
+ storage = get_storage()
+ if not storage.delete_object(user_id, key):
+ raise HTTPException(status_code=404, detail="Object not found")
+
+ # Delete from database
+ db.query(UploadedAsset).filter(
+ UploadedAsset.user_id == user_id,
+ UploadedAsset.s3_path == key,
+ ).delete()
+ db.commit()
+
+ return {"message": "Object deleted"}
+
+
+@router.get("/{user_id}")
+async def list_objects(
+ user_id: int,
+ prefix: str = Query(""),
+ delimiter: str = Query(""),
+ current_user: User = Depends(get_current_user),
+):
+ """List objects in a user's bucket (S3-compatible)."""
+ # Verify user is listing their own bucket
+ if user_id != current_user.id:
+ raise HTTPException(status_code=403, detail="Cannot list another user's bucket")
+
+ # List objects
+ storage = get_storage()
+ objects = storage.list_objects(user_id, prefix, delimiter)
+
+ return {
+ "bucket": f"user-{user_id}",
+ "prefix": prefix,
+ "contents": [{"key": key} for key in objects],
+ }
diff --git a/privatestudio/web/routes/keys.py b/privatestudio/web/routes/keys.py
new file mode 100644
index 0000000..eca3986
--- /dev/null
+++ b/privatestudio/web/routes/keys.py
@@ -0,0 +1,89 @@
+"""API key management endpoints."""
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.orm import Session
+from pydantic import BaseModel
+
+from privatestudio.web.database import get_db
+from privatestudio.web.models import User, APIKey
+from privatestudio.web.auth import get_current_user, create_api_key, revoke_api_key
+
+router = APIRouter()
+
+
+class APIKeyCreate(BaseModel):
+ """Request model for creating an API key."""
+ pass # No parameters needed
+
+
+class APIKeyResponse(BaseModel):
+ """Response model for API key."""
+ id: int
+ created_at: str
+
+ class Config:
+ from_attributes = True
+
+
+class APIKeyCreateResponse(APIKeyResponse):
+ """Response model for creating an API key (includes the plain key)."""
+ key: str
+
+
+class APIKeyList(BaseModel):
+ """Response model for listing API keys."""
+ id: int
+ created_at: str
+ is_active: bool
+
+ class Config:
+ from_attributes = True
+
+
+@router.post("/keys", response_model=APIKeyCreateResponse)
+def create_api_key_endpoint(
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Create a new API key for the authenticated user."""
+ plain_key, api_key_record = create_api_key(db, current_user.id)
+ return APIKeyCreateResponse(
+ id=api_key_record.id,
+ key=plain_key,
+ created_at=api_key_record.created_at.isoformat(),
+ )
+
+
+@router.get("/keys", response_model=list[APIKeyList])
+def list_api_keys(
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """List all API keys for the authenticated user."""
+ keys = db.query(APIKey).filter(APIKey.user_id == current_user.id).all()
+ return [
+ APIKeyList(
+ id=key.id,
+ created_at=key.created_at.isoformat(),
+ is_active=key.is_active,
+ )
+ for key in keys
+ ]
+
+
+@router.delete("/keys/{key_id}")
+def revoke_api_key_endpoint(
+ key_id: int,
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Revoke an API key (mark it as inactive)."""
+ # Verify the key belongs to the current user
+ api_key = db.query(APIKey).filter(APIKey.id == key_id).first()
+ if not api_key:
+ raise HTTPException(status_code=404, detail="API key not found")
+
+ if api_key.user_id != current_user.id:
+ raise HTTPException(status_code=403, detail="Cannot revoke someone else's API key")
+
+ revoke_api_key(db, key_id)
+ return {"message": "API key revoked"}
diff --git a/privatestudio/web/routes/profiles.py b/privatestudio/web/routes/profiles.py
new file mode 100644
index 0000000..52ea3d1
--- /dev/null
+++ b/privatestudio/web/routes/profiles.py
@@ -0,0 +1,118 @@
+"""Transcode profile management endpoints."""
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.orm import Session
+from pydantic import BaseModel
+import yaml
+
+from privatestudio.web.database import get_db
+from privatestudio.web.models import User, TranscodeProfile
+from privatestudio.web.auth import get_current_user
+
+router = APIRouter()
+
+
+class ProfileResponse(BaseModel):
+ """Response model for transcode profile."""
+ id: int
+ name: str
+ profile_definition: str
+ created_at: str
+
+ class Config:
+ from_attributes = True
+
+
+@router.post("/profiles")
+def create_profile(
+ name: str,
+ body: str, # Raw YAML body
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """
+ Create a new transcode profile.
+
+ The request body should contain the YAML profile definition.
+ """
+ # Validate YAML
+ try:
+ profile_data = yaml.safe_load(body)
+ if not isinstance(profile_data, dict):
+ raise ValueError("Profile definition must be a YAML mapping")
+ if "profiles" not in profile_data:
+ raise ValueError("Profile definition must contain a 'profiles' section")
+ except yaml.YAMLError as e:
+ raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
+
+ # Check if profile name already exists for this user
+ existing = db.query(TranscodeProfile).filter(
+ TranscodeProfile.user_id == current_user.id,
+ TranscodeProfile.name == name,
+ ).first()
+
+ if existing:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail=f"Profile '{name}' already exists",
+ )
+
+ # Create profile
+ profile = TranscodeProfile(
+ user_id=current_user.id,
+ name=name,
+ profile_definition=body,
+ )
+ db.add(profile)
+ db.commit()
+ db.refresh(profile)
+
+ return ProfileResponse(
+ id=profile.id,
+ name=profile.name,
+ profile_definition=profile.profile_definition,
+ created_at=profile.created_at.isoformat(),
+ )
+
+
+@router.get("/profiles", response_model=list[ProfileResponse])
+def list_profiles(
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """List all transcode profiles for the current user."""
+ profiles = db.query(TranscodeProfile).filter(
+ TranscodeProfile.user_id == current_user.id
+ ).all()
+
+ return [
+ ProfileResponse(
+ id=p.id,
+ name=p.name,
+ profile_definition=p.profile_definition,
+ created_at=p.created_at.isoformat(),
+ )
+ for p in profiles
+ ]
+
+
+@router.get("/profiles/{profile_id}", response_model=ProfileResponse)
+def get_profile(
+ profile_id: int,
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Get a specific transcode profile."""
+ profile = db.query(TranscodeProfile).filter(
+ TranscodeProfile.id == profile_id,
+ TranscodeProfile.user_id == current_user.id,
+ ).first()
+
+ if not profile:
+ raise HTTPException(status_code=404, detail="Profile not found")
+
+ return ProfileResponse(
+ id=profile.id,
+ name=profile.name,
+ profile_definition=profile.profile_definition,
+ created_at=profile.created_at.isoformat(),
+ )
diff --git a/privatestudio/web/routes/transcode.py b/privatestudio/web/routes/transcode.py
new file mode 100644
index 0000000..e99a0bc
--- /dev/null
+++ b/privatestudio/web/routes/transcode.py
@@ -0,0 +1,181 @@
+"""YAML-based transcode job request endpoints."""
+from fastapi import APIRouter, Depends, HTTPException, status
+from sqlalchemy.orm import Session
+from pydantic import BaseModel
+import yaml
+
+from privatestudio.web.database import get_db
+from privatestudio.web.models import User, TranscodeJob, UploadedAsset, TranscodeProfile
+from privatestudio.web.auth import get_current_user
+
+router = APIRouter()
+
+
+class TranscodeJobResponse(BaseModel):
+ """Response model for transcode job."""
+ id: int
+ asset_id: int
+ profile_id: int | None
+ status: str
+ requested_at: str
+
+ class Config:
+ from_attributes = True
+
+
+@router.post("/transcode")
+def request_transcode(
+ body: str, # Raw YAML body
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """
+ Request a transcode job with YAML definition.
+
+ The request body should contain YAML like:
+ ```yaml
+ asset: "video.mp4" # Asset name or ID
+ profile: "hd-profile" # Profile name, or inline profile definition
+ ```
+
+ Or with inline profile:
+ ```yaml
+ asset: "video.mp4"
+ profile:
+ profiles:
+ hd:
+ resolution: "1280x720"
+ bitrate: "2500k"
+ ```
+ """
+ # Parse YAML
+ try:
+ request_data = yaml.safe_load(body)
+ if not isinstance(request_data, dict):
+ raise ValueError("Request must be a YAML mapping")
+ except yaml.YAMLError as e:
+ raise HTTPException(status_code=400, detail=f"Invalid YAML: {e}")
+
+ # Get asset
+ asset_ref = request_data.get("asset")
+ if not asset_ref:
+ raise HTTPException(status_code=400, detail="Request must specify 'asset'")
+
+ # Try to find asset by name or ID
+ asset = None
+ try:
+ asset_id = int(asset_ref)
+ asset = db.query(UploadedAsset).filter(
+ UploadedAsset.id == asset_id,
+ UploadedAsset.user_id == current_user.id,
+ ).first()
+ except ValueError:
+ # Not an ID, try as filename
+ asset = db.query(UploadedAsset).filter(
+ UploadedAsset.filename == asset_ref,
+ UploadedAsset.user_id == current_user.id,
+ ).first()
+
+ if not asset:
+ raise HTTPException(status_code=404, detail=f"Asset '{asset_ref}' not found")
+
+ # Get or validate profile
+ profile_ref = request_data.get("profile")
+ if not profile_ref:
+ raise HTTPException(status_code=400, detail="Request must specify 'profile'")
+
+ profile_id = None
+ profile_definition = None
+
+ if isinstance(profile_ref, str):
+ # Profile name reference
+ profile = db.query(TranscodeProfile).filter(
+ TranscodeProfile.name == profile_ref,
+ TranscodeProfile.user_id == current_user.id,
+ ).first()
+
+ if not profile:
+ raise HTTPException(status_code=404, detail=f"Profile '{profile_ref}' not found")
+
+ profile_id = profile.id
+ profile_definition = profile.profile_definition
+ elif isinstance(profile_ref, dict):
+ # Inline profile definition
+ try:
+ # Validate it has a 'profiles' section
+ if "profiles" not in profile_ref:
+ raise ValueError("Inline profile must contain a 'profiles' section")
+ profile_definition = yaml.dump(profile_ref)
+ except Exception as e:
+ raise HTTPException(status_code=400, detail=f"Invalid profile definition: {e}")
+ else:
+ raise HTTPException(status_code=400, detail="Profile must be a string (name) or object (definition)")
+
+ # Create transcode job
+ job = TranscodeJob(
+ user_id=current_user.id,
+ asset_id=asset.id,
+ profile_id=profile_id,
+ status="pending",
+ )
+ db.add(job)
+ db.commit()
+ db.refresh(job)
+
+ return TranscodeJobResponse(
+ id=job.id,
+ asset_id=job.asset_id,
+ profile_id=job.profile_id,
+ status=job.status,
+ requested_at=job.requested_at.isoformat(),
+ )
+
+
+@router.get("/transcode/{job_id}", response_model=TranscodeJobResponse)
+def get_transcode_job(
+ job_id: int,
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """Get status of a transcode job."""
+ job = db.query(TranscodeJob).filter(
+ TranscodeJob.id == job_id,
+ TranscodeJob.user_id == current_user.id,
+ ).first()
+
+ if not job:
+ raise HTTPException(status_code=404, detail="Job not found")
+
+ return TranscodeJobResponse(
+ id=job.id,
+ asset_id=job.asset_id,
+ profile_id=job.profile_id,
+ status=job.status,
+ requested_at=job.requested_at.isoformat(),
+ )
+
+
+@router.get("/transcode", response_model=list[TranscodeJobResponse])
+def list_transcode_jobs(
+ status: str | None = None,
+ current_user: User = Depends(get_current_user),
+ db: Session = Depends(get_db),
+):
+ """List transcode jobs for the current user."""
+ query = db.query(TranscodeJob).filter(TranscodeJob.user_id == current_user.id)
+
+ if status:
+ query = query.filter(TranscodeJob.status == status)
+
+ jobs = query.all()
+
+ return [
+ TranscodeJobResponse(
+ id=job.id,
+ asset_id=job.asset_id,
+ profile_id=job.profile_id,
+ status=job.status,
+ requested_at=job.requested_at.isoformat(),
+ )
+ for job in jobs
+ ]
diff --git a/privatestudio/web/s3_interface.py b/privatestudio/web/s3_interface.py
new file mode 100644
index 0000000..a525c13
--- /dev/null
+++ b/privatestudio/web/s3_interface.py
@@ -0,0 +1,101 @@
+"""S3-compatible file storage handler."""
+import os
+from pathlib import Path
+from typing import Optional
+
+
+class S3FileStorage:
+ """Local file storage backend with S3-compatible interface."""
+
+ def __init__(self, base_path: str = "./storage"):
+ """Initialize storage with base path."""
+ self.base_path = Path(base_path)
+ self.base_path.mkdir(parents=True, exist_ok=True)
+
+ def _get_user_path(self, user_id: int) -> Path:
+ """Get the storage path for a user."""
+ user_path = self.base_path / str(user_id)
+ user_path.mkdir(parents=True, exist_ok=True)
+ return user_path
+
+ def _get_file_path(self, user_id: int, key: str) -> Path:
+ """Get the full file path for a key, ensuring it's within user directory."""
+ user_path = self._get_user_path(user_id)
+ user_path_resolved = user_path.resolve()
+ file_path = (user_path / key).resolve()
+
+ # Security check: ensure file is within user directory
+ if not str(file_path).startswith(str(user_path_resolved)):
+ raise ValueError(f"Invalid key: {key}")
+
+ return file_path
+
+ def put_object(self, user_id: int, key: str, data: bytes) -> None:
+ """Store a file."""
+ file_path = self._get_file_path(user_id, key)
+ file_path.parent.mkdir(parents=True, exist_ok=True)
+ file_path.write_bytes(data)
+
+ def get_object(self, user_id: int, key: str) -> Optional[bytes]:
+ """Retrieve a file."""
+ file_path = self._get_file_path(user_id, key)
+ if file_path.exists():
+ return file_path.read_bytes()
+ return None
+
+ def delete_object(self, user_id: int, key: str) -> bool:
+ """Delete a file. Returns True if deleted, False if not found."""
+ file_path = self._get_file_path(user_id, key)
+ if file_path.exists():
+ file_path.unlink()
+ return True
+ return False
+
+ def list_objects(self, user_id: int, prefix: str = "", delimiter: str = "") -> list[str]:
+ """List objects for a user, optionally with prefix/delimiter."""
+ user_path = self._get_user_path(user_id)
+
+ if delimiter == "/":
+ # Return only direct children
+ items = []
+ for item in user_path.iterdir():
+ rel_path = item.relative_to(user_path).as_posix()
+ if item.is_dir():
+ rel_path += "/"
+ if not prefix or rel_path.startswith(prefix):
+ items.append(rel_path)
+ return sorted(items)
+ else:
+ # Recursively list all files
+ items = []
+ for item in user_path.rglob("*"):
+ if item.is_file():
+ rel_path = item.relative_to(user_path).as_posix()
+ if not prefix or rel_path.startswith(prefix):
+ items.append(rel_path)
+ return sorted(items)
+
+ def get_object_size(self, user_id: int, key: str) -> Optional[int]:
+ """Get the size of a file in bytes."""
+ file_path = self._get_file_path(user_id, key)
+ if file_path.exists():
+ return file_path.stat().st_size
+ return None
+
+ def object_exists(self, user_id: int, key: str) -> bool:
+ """Check if an object exists."""
+ file_path = self._get_file_path(user_id, key)
+ return file_path.exists()
+
+
+# Global storage instance
+_storage_instance: Optional[S3FileStorage] = None
+
+
+def get_storage() -> S3FileStorage:
+ """Get or create the global storage instance."""
+ global _storage_instance
+ if _storage_instance is None:
+ base_path = os.environ.get("STORAGE_PATH", "./storage")
+ _storage_instance = S3FileStorage(base_path)
+ return _storage_instance
diff --git a/pyproject.toml b/pyproject.toml
index 92893a8..e0e82da 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -9,6 +9,10 @@ readme = "notes.md"
requires-python = ">=3.8"
dependencies = [
"PyYAML>=6.0",
+ "FastAPI>=0.100.0",
+ "uvicorn[standard]>=0.23.0",
+ "SQLAlchemy>=2.0.0",
+ "python-multipart>=0.0.5",
]
dynamic = ["version"]
@@ -16,10 +20,12 @@ dynamic = ["version"]
dev = [
"pytest>=7.0",
"pytest-cov>=4.0",
+ "httpx>=0.27.0",
]
[project.scripts]
ps-transcode = "privatestudio.transcode:main"
+ps-serve = "privatestudio.web.cli:main"
[tool.setuptools]
packages = ["privatestudio"]
diff --git a/tests/__init__.py b/tests/__init__.py
new file mode 100644
index 0000000..dbf4260
--- /dev/null
+++ b/tests/__init__.py
@@ -0,0 +1 @@
+"""Tests for privatestudio."""
diff --git a/tests/__pycache__/__init__.cpython-313.pyc b/tests/__pycache__/__init__.cpython-313.pyc
new file mode 100644
index 0000000..52137ac
Binary files /dev/null and b/tests/__pycache__/__init__.cpython-313.pyc differ
diff --git a/tests/__pycache__/test_web.cpython-313-pytest-9.1.1.pyc b/tests/__pycache__/test_web.cpython-313-pytest-9.1.1.pyc
new file mode 100644
index 0000000..4a4b207
Binary files /dev/null and b/tests/__pycache__/test_web.cpython-313-pytest-9.1.1.pyc differ
diff --git a/tests/test_web.py b/tests/test_web.py
new file mode 100644
index 0000000..03e0bdf
--- /dev/null
+++ b/tests/test_web.py
@@ -0,0 +1,228 @@
+"""Integration tests for the video transcoding web service."""
+import pytest
+from fastapi.testclient import TestClient
+from sqlalchemy import create_engine, event
+from sqlalchemy.orm import sessionmaker
+from sqlalchemy.pool import StaticPool
+
+from privatestudio.web.app import app
+from privatestudio.web.database import get_db
+from privatestudio.web.models import Base
+from privatestudio.web.auth import create_user, create_api_key
+
+
+# Use in-memory SQLite for testing with StaticPool
+engine = create_engine(
+ "sqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+)
+
+TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
+
+
+def override_get_db():
+ try:
+ db = TestingSessionLocal()
+ yield db
+ finally:
+ db.close()
+
+
+app.dependency_overrides[get_db] = override_get_db
+
+client = TestClient(app)
+
+
+@pytest.fixture(scope="function", autouse=True)
+def reset_db():
+ """Reset database before each test."""
+ Base.metadata.drop_all(bind=engine)
+ Base.metadata.create_all(bind=engine)
+ yield
+ Base.metadata.drop_all(bind=engine)
+
+
+@pytest.fixture
+def test_user_and_key():
+ """Create a test user and API key."""
+ db = TestingSessionLocal()
+ try:
+ user = create_user(db, "testuser")
+ plain_key, api_key = create_api_key(db, user.id)
+ user_id = user.id # Store before closing session
+ return user_id, plain_key
+ finally:
+ db.close()
+
+
+def test_health_check():
+ """Test health check endpoint."""
+ response = client.get("/health")
+ assert response.status_code == 200
+ assert response.json() == {"status": "ok"}
+
+
+def test_create_api_key(test_user_and_key):
+ """Test creating an API key via endpoint."""
+ user_id, plain_key = test_user_and_key
+
+ response = client.post(
+ "/api/keys",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert "id" in data
+ assert "key" in data
+ assert "created_at" in data
+
+
+def test_list_api_keys(test_user_and_key):
+ """Test listing API keys."""
+ user_id, plain_key = test_user_and_key
+
+ response = client.get(
+ "/api/keys",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert isinstance(data, list)
+ assert len(data) > 0
+ assert data[0]["is_active"] is True
+
+
+def test_authentication_required():
+ """Test that endpoints require authentication."""
+ response = client.get("/api/keys")
+ assert response.status_code in [401, 403] # Accept both
+
+
+def test_invalid_api_key():
+ """Test invalid API key."""
+ response = client.get(
+ "/api/keys",
+ headers={"Authorization": "Bearer invalid_key"},
+ )
+ assert response.status_code == 401
+
+
+def test_upload_file(test_user_and_key):
+ """Test file upload to S3 interface."""
+ user_id, plain_key = test_user_and_key
+
+ # Upload a file
+ response = client.put(
+ f"/s3/{user_id}/test.mp4",
+ files={"file": ("test.mp4", b"test file content", "video/mp4")},
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert data["key"] == "test.mp4"
+ assert data["size"] == len(b"test file content")
+
+
+def test_download_file(test_user_and_key):
+ """Test file download from S3 interface."""
+ user_id, plain_key = test_user_and_key
+
+ # Upload a file first
+ client.put(
+ f"/s3/{user_id}/test.mp4",
+ files={"file": ("test.mp4", b"test file content", "video/mp4")},
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+
+ # Download it
+ response = client.get(
+ f"/s3/{user_id}/test.mp4",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+ assert response.content == b"test file content"
+
+
+def test_delete_file(test_user_and_key):
+ """Test file deletion from S3 interface."""
+ user_id, plain_key = test_user_and_key
+
+ # Upload a file first
+ client.put(
+ f"/s3/{user_id}/test.mp4",
+ files={"file": ("test.mp4", b"test file content", "video/mp4")},
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+
+ # Delete it
+ response = client.delete(
+ f"/s3/{user_id}/test.mp4",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+
+ # Verify it's gone
+ response = client.get(
+ f"/s3/{user_id}/test.mp4",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 404
+
+
+def test_list_objects(test_user_and_key):
+ """Test listing objects in S3 bucket."""
+ user_id, plain_key = test_user_and_key
+
+ # Upload a couple files
+ client.put(
+ f"/s3/{user_id}/test1.mp4",
+ files={"file": ("test1.mp4", b"content1", "video/mp4")},
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ client.put(
+ f"/s3/{user_id}/test2.mp4",
+ files={"file": ("test2.mp4", b"content2", "video/mp4")},
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+
+ # List objects
+ response = client.get(
+ f"/s3/{user_id}",
+ headers={"Authorization": f"Bearer {plain_key}"},
+ )
+ assert response.status_code == 200
+ data = response.json()
+ assert len(data["contents"]) == 2
+
+
+def test_per_user_isolation(test_user_and_key):
+ """Test that users can't access each other's resources."""
+ user1_id, key1 = test_user_and_key
+
+ # Create second user
+ db = TestingSessionLocal()
+ try:
+ user2 = create_user(db, "testuser2")
+ plain_key2, _ = create_api_key(db, user2.id)
+ user2_id = user2.id
+ finally:
+ db.close()
+
+ # User1 uploads a file
+ client.put(
+ f"/s3/{user1_id}/private.mp4",
+ files={"file": ("private.mp4", b"user1 content", "video/mp4")},
+ headers={"Authorization": f"Bearer {key1}"},
+ )
+
+ # User2 tries to download user1's file
+ response = client.get(
+ f"/s3/{user1_id}/private.mp4",
+ headers={"Authorization": f"Bearer {plain_key2}"},
+ )
+ assert response.status_code == 403
+
+
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])
diff --git a/transcoding.db b/transcoding.db
new file mode 100644
index 0000000..8ff39fa
Binary files /dev/null and b/transcoding.db differ