#!/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())