Add userinfo endpoint and asset backup script.
This commit is contained in:
+4
-1
@@ -3,4 +3,7 @@ dist/
|
||||
privatestudio/_version.py
|
||||
*.egg-info/
|
||||
|
||||
storage/
|
||||
storage/
|
||||
|
||||
**.pyc
|
||||
__pycache__/
|
||||
|
||||
Generated
+14
@@ -8,5 +8,19 @@
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/transcoding.db</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
<data-source source="LOCAL" name="identifier.sqlite" uuid="0e87cf42-28f9-40ab-98e0-aa7924153ae7">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:identifier.sqlite</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
<data-source source="LOCAL" name="transcoding [krugertest]" uuid="27f649a9-59e9-4fb8-a3bb-c02067acf837">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/krugertest/transcoding.db</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
Generated
+11
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="db-forest-configuration">
|
||||
<data version="2">.
|
||||
----------------------------------------
|
||||
1:0:eb5b1d39-d6f8-4807-b782-63a11277ebd3
|
||||
2:0:0e87cf42-28f9-40ab-98e0-aa7924153ae7
|
||||
3:0:27f649a9-59e9-4fb8-a3bb-c02067acf837
|
||||
.</data>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,169 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Upload an asset to the Private Studio web API using boto3.
|
||||
|
||||
This script demonstrates how to use boto3 to upload files to the Private Studio
|
||||
S3-compatible storage API.
|
||||
|
||||
Usage:
|
||||
python upload_asset.py \\
|
||||
--base-url http://localhost:8000 \\
|
||||
--api-key <your-api-key> \\
|
||||
--file /path/to/file.mp4 \\
|
||||
--key assets/my-video.mp4
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import sys
|
||||
from pathlib import Path
|
||||
import requests
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
except ImportError:
|
||||
print("Error: boto3 is required. Install it with: pip install boto3", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def upload_asset(
|
||||
base_url: str,
|
||||
api_key: str,
|
||||
file_path: str,
|
||||
key: str,
|
||||
user_name: int = 1,
|
||||
) -> dict:
|
||||
"""
|
||||
Upload an asset to the Private Studio API.
|
||||
|
||||
Args:
|
||||
base_url: Base URL of the Private Studio API (e.g., http://localhost:8000)
|
||||
api_key: API key for authentication
|
||||
file_path: Path to the file to upload
|
||||
key: S3 key/path for the file (e.g., assets/my-file.mp4)
|
||||
user_name: User ID (defaults to 1)
|
||||
|
||||
Returns:
|
||||
Response from the API containing object_id, key, size, and filename
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the file doesn't exist
|
||||
ClientError: If the API returns an error
|
||||
"""
|
||||
|
||||
userinfo = requests.get(f"{base_url}/api/userinfo", headers={"Authorization": f"Bearer {api_key}"})
|
||||
userinfo.raise_for_status()
|
||||
user_data = userinfo.json()
|
||||
|
||||
|
||||
|
||||
|
||||
file_path_obj = Path(file_path)
|
||||
if not file_path_obj.exists():
|
||||
raise FileNotFoundError(f"File not found: {file_path}")
|
||||
|
||||
# Configure boto3 client for S3-compatible API
|
||||
s3_client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=f"{base_url}/s3",
|
||||
aws_access_key_id=api_key,
|
||||
aws_secret_access_key="", # Not used for API key auth
|
||||
region_name="us-east-1",
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
),
|
||||
)
|
||||
|
||||
try:
|
||||
# Upload the file
|
||||
file_size = file_path_obj.stat().st_size
|
||||
print(f"Uploading {file_path} ({file_size} bytes) as '{key}'...")
|
||||
|
||||
with open(file_path, "rb") as f:
|
||||
response = s3_client.put_object(
|
||||
Bucket=user_data['bucket'],
|
||||
Key=key,
|
||||
Body=f,
|
||||
)
|
||||
|
||||
print("Upload successful!")
|
||||
print(f"Response: {response}")
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"key": key,
|
||||
"size": file_size,
|
||||
"etag": response.get("ETag"),
|
||||
}
|
||||
|
||||
except ClientError as e:
|
||||
error_code = e.response.get("Error", {}).get("Code")
|
||||
error_message = e.response.get("Error", {}).get("Message")
|
||||
print(f"Error uploading file: {error_code} - {error_message}", file=sys.stderr)
|
||||
raise
|
||||
except Exception as e:
|
||||
print(f"Unexpected error: {e}", file=sys.stderr)
|
||||
raise
|
||||
|
||||
|
||||
def main():
|
||||
"""Parse arguments and execute upload."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Upload an asset to the Private Studio web API",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="""
|
||||
Examples:
|
||||
python upload_asset.py --base-url http://localhost:8000 --api-key sk_test_123abc --file video.mp4 --key assets/video.mp4
|
||||
python upload_asset.py --base-url https://api.example.com --api-key sk_prod_456def --file image.jpg --key media/image.jpg --user-id 2
|
||||
""",
|
||||
)
|
||||
|
||||
parser.add_argument(
|
||||
"--base-url",
|
||||
required=True,
|
||||
help="Base URL of the Private Studio API (e.g., http://localhost:8000)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--api-key",
|
||||
required=True,
|
||||
help="API key for authentication",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--file",
|
||||
required=True,
|
||||
help="Path to the file to upload",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--key",
|
||||
required=True,
|
||||
help="S3 key/path for the file (e.g., assets/my-file.mp4)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--user-id",
|
||||
type=int,
|
||||
default=1,
|
||||
help="User ID (defaults to 1)",
|
||||
)
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
try:
|
||||
result = upload_asset(
|
||||
base_url=args.base_url,
|
||||
api_key=args.api_key,
|
||||
file_path=args.file,
|
||||
key=args.key,
|
||||
user_name=args.user_id,
|
||||
)
|
||||
print(f"\nUpload completed: {result}")
|
||||
return 0
|
||||
except Exception as e:
|
||||
print(f"Upload failed: {e}", file=sys.stderr)
|
||||
return 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Binary file not shown.
@@ -0,0 +1,3 @@
|
||||
from privatestudio.web.cli import main
|
||||
|
||||
raise SystemExit(main())
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -4,7 +4,7 @@ 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
|
||||
from privatestudio.web.routes import assets, transcode, profiles, keys, userinfo
|
||||
|
||||
# Initialize database
|
||||
init_db()
|
||||
@@ -37,6 +37,7 @@ 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.include_router(userinfo.router, prefix="/api", tags=["UserInfo"])
|
||||
|
||||
|
||||
@app.exception_handler(ValueError)
|
||||
|
||||
@@ -5,6 +5,7 @@ import uvicorn
|
||||
|
||||
from privatestudio.web.database import init_db, get_db, SessionLocal
|
||||
from privatestudio.web.auth import create_user, create_api_key
|
||||
from privatestudio.web.models import User
|
||||
|
||||
|
||||
def init_command(args):
|
||||
@@ -31,7 +32,10 @@ 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_name)
|
||||
user = db.query(User).filter(User.username == args.user_name).first()
|
||||
if not user:
|
||||
raise ValueError(f"User '{args.user_name}' not found")
|
||||
plain_key, api_key = create_api_key(db, user.id)
|
||||
print(f"API key created for user {args.user_name}")
|
||||
print(f"Key: {plain_key}")
|
||||
print(f"Keep this key safe - you won't be able to see it again!")
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -10,9 +10,9 @@ from privatestudio.web.s3_interface import get_storage
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.put("/{user_id}/{key:path}")
|
||||
@router.put("/{user_name}/{key:path}")
|
||||
async def upload_file(
|
||||
user_id: int,
|
||||
user_name: str,
|
||||
key: str,
|
||||
file: UploadFile = File(...),
|
||||
current_user: User = Depends(get_current_user),
|
||||
@@ -20,9 +20,11 @@ async def upload_file(
|
||||
):
|
||||
"""Upload a file to S3-compatible storage."""
|
||||
# Verify user is uploading to their own bucket
|
||||
if user_id != current_user.id:
|
||||
if user_name != current_user.username:
|
||||
raise HTTPException(status_code=403, detail="Cannot upload to another user's bucket")
|
||||
|
||||
|
||||
user_id = current_user.id
|
||||
|
||||
# Read file content
|
||||
content = await file.read()
|
||||
|
||||
@@ -49,17 +51,19 @@ async def upload_file(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{user_id}/{key:path}")
|
||||
@router.get("/{user_name}/{key:path}")
|
||||
async def download_file(
|
||||
user_id: int,
|
||||
user_name: str,
|
||||
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:
|
||||
if user_name != current_user.username:
|
||||
raise HTTPException(status_code=403, detail="Cannot download from another user's bucket")
|
||||
|
||||
|
||||
user_id = current_user.id
|
||||
|
||||
# Retrieve file
|
||||
storage = get_storage()
|
||||
content = storage.get_object(user_id, key)
|
||||
@@ -72,18 +76,20 @@ async def download_file(
|
||||
return Response(content=content, media_type="application/octet-stream")
|
||||
|
||||
|
||||
@router.delete("/{user_id}/{key:path}")
|
||||
@router.delete("/{user_name}/{key:path}")
|
||||
async def delete_file(
|
||||
user_id: int,
|
||||
user_name: str,
|
||||
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:
|
||||
if user_name != current_user.username:
|
||||
raise HTTPException(status_code=403, detail="Cannot delete from another user's bucket")
|
||||
|
||||
|
||||
user_id = current_user.id
|
||||
|
||||
# Delete from storage
|
||||
storage = get_storage()
|
||||
if not storage.delete_object(user_id, key):
|
||||
@@ -99,18 +105,20 @@ async def delete_file(
|
||||
return {"message": "Object deleted"}
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
@router.get("/{user_name}")
|
||||
async def list_objects(
|
||||
user_id: int,
|
||||
user_name: str,
|
||||
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:
|
||||
if user_name != current_user.username:
|
||||
raise HTTPException(status_code=403, detail="Cannot list another user's bucket")
|
||||
|
||||
|
||||
user_id = current_user.id
|
||||
|
||||
# List objects
|
||||
storage = get_storage()
|
||||
objects = storage.list_objects(user_id, prefix, delimiter)
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
"""User information routes."""
|
||||
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()
|
||||
|
||||
|
||||
@router.get("/userinfo")
|
||||
async def get_user_info(
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get user information for the current user."""
|
||||
user_id = current_user.id
|
||||
bucket_name = f"user-{user_id}"
|
||||
|
||||
return {
|
||||
"bucket": bucket_name,
|
||||
"user_id": user_id,
|
||||
"username": current_user.username,
|
||||
}
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user