diff --git a/.gitignore b/.gitignore index 551933d..be08989 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,7 @@ dist/ privatestudio/_version.py *.egg-info/ -storage/ \ No newline at end of file +storage/ + +**.pyc +__pycache__/ diff --git a/.idea/dataSources.xml b/.idea/dataSources.xml index 8d0be2e..dfddde4 100644 --- a/.idea/dataSources.xml +++ b/.idea/dataSources.xml @@ -8,5 +8,19 @@ jdbc:sqlite:$PROJECT_DIR$/transcoding.db $ProjectFileDir$ + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:identifier.sqlite + $ProjectFileDir$ + + + sqlite.xerial + true + org.sqlite.JDBC + jdbc:sqlite:$PROJECT_DIR$/krugertest/transcoding.db + $ProjectFileDir$ + \ No newline at end of file diff --git a/.idea/db-forest-config.xml b/.idea/db-forest-config.xml new file mode 100644 index 0000000..ccf165c --- /dev/null +++ b/.idea/db-forest-config.xml @@ -0,0 +1,11 @@ + + + + . + ---------------------------------------- + 1:0:eb5b1d39-d6f8-4807-b782-63a11277ebd3 + 2:0:0e87cf42-28f9-40ab-98e0-aa7924153ae7 + 3:0:27f649a9-59e9-4fb8-a3bb-c02067acf837 + . + + \ No newline at end of file diff --git a/client-examples/upload_asset_backup.py b/client-examples/upload_asset_backup.py new file mode 100644 index 0000000..7160753 --- /dev/null +++ b/client-examples/upload_asset_backup.py @@ -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 \\ + --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()) diff --git a/privatestudio/__pycache__/__init__.cpython-313.pyc b/privatestudio/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 5f4494e..0000000 Binary files a/privatestudio/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__main__.py b/privatestudio/web/__main__.py new file mode 100644 index 0000000..232cefb --- /dev/null +++ b/privatestudio/web/__main__.py @@ -0,0 +1,3 @@ +from privatestudio.web.cli import main + +raise SystemExit(main()) diff --git a/privatestudio/web/__pycache__/__init__.cpython-313.pyc b/privatestudio/web/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index b44e122..0000000 Binary files a/privatestudio/web/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/app.cpython-313.pyc b/privatestudio/web/__pycache__/app.cpython-313.pyc deleted file mode 100644 index d0dcfc3..0000000 Binary files a/privatestudio/web/__pycache__/app.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/auth.cpython-313.pyc b/privatestudio/web/__pycache__/auth.cpython-313.pyc deleted file mode 100644 index 73db91b..0000000 Binary files a/privatestudio/web/__pycache__/auth.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/cli.cpython-313.pyc b/privatestudio/web/__pycache__/cli.cpython-313.pyc deleted file mode 100644 index 2036ea6..0000000 Binary files a/privatestudio/web/__pycache__/cli.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/database.cpython-313.pyc b/privatestudio/web/__pycache__/database.cpython-313.pyc deleted file mode 100644 index e7ba111..0000000 Binary files a/privatestudio/web/__pycache__/database.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/models.cpython-313.pyc b/privatestudio/web/__pycache__/models.cpython-313.pyc deleted file mode 100644 index 58245c3..0000000 Binary files a/privatestudio/web/__pycache__/models.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc b/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc deleted file mode 100644 index 60bd017..0000000 Binary files a/privatestudio/web/__pycache__/s3_interface.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/app.py b/privatestudio/web/app.py index a4d2244..204eba8 100644 --- a/privatestudio/web/app.py +++ b/privatestudio/web/app.py @@ -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) diff --git a/privatestudio/web/cli.py b/privatestudio/web/cli.py index 0748fe8..5f32816 100644 --- a/privatestudio/web/cli.py +++ b/privatestudio/web/cli.py @@ -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!") diff --git a/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc b/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 3a0d5ec..0000000 Binary files a/privatestudio/web/routes/__pycache__/__init__.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc b/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc deleted file mode 100644 index 2253d4b..0000000 Binary files a/privatestudio/web/routes/__pycache__/assets.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc b/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc deleted file mode 100644 index 9ea5e64..0000000 Binary files a/privatestudio/web/routes/__pycache__/keys.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc b/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc deleted file mode 100644 index bca7e65..0000000 Binary files a/privatestudio/web/routes/__pycache__/profiles.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc b/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc deleted file mode 100644 index a5a4286..0000000 Binary files a/privatestudio/web/routes/__pycache__/transcode.cpython-313.pyc and /dev/null differ diff --git a/privatestudio/web/routes/assets.py b/privatestudio/web/routes/assets.py index 91ceba5..7f3107d 100644 --- a/privatestudio/web/routes/assets.py +++ b/privatestudio/web/routes/assets.py @@ -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) diff --git a/privatestudio/web/routes/userinfo.py b/privatestudio/web/routes/userinfo.py new file mode 100644 index 0000000..ddb6c8a --- /dev/null +++ b/privatestudio/web/routes/userinfo.py @@ -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, + } + diff --git a/tests/__pycache__/__init__.cpython-313.pyc b/tests/__pycache__/__init__.cpython-313.pyc deleted file mode 100644 index 52137ac..0000000 Binary files a/tests/__pycache__/__init__.cpython-313.pyc and /dev/null 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 deleted file mode 100644 index 4a4b207..0000000 Binary files a/tests/__pycache__/test_web.cpython-313-pytest-9.1.1.pyc and /dev/null differ