| 16 | |
| 17 | |
| 18 | def build_presigned_url(args: argparse.Namespace) -> tuple[str, Optional[str]]: |
| 19 | if args.presigned_url: |
| 20 | return args.presigned_url, (args.download_url or None) |
| 21 | |
| 22 | if boto3 is None: |
| 23 | raise RuntimeError("boto3 is required to auto-generate presigned URL, please install boto3/aioboto3.") |
| 24 | if BotoConfig is None: |
| 25 | raise RuntimeError("botocore is required to configure S3 client.") |
| 26 | |
| 27 | bucket = args.s3_bucket or os.getenv("S3_BUCKET", "") |
| 28 | if not bucket: |
| 29 | raise ValueError("Missing S3 bucket. Set --s3_bucket or env S3_BUCKET.") |
| 30 | |
| 31 | object_key = args.s3_object_key |
| 32 | if not object_key: |
| 33 | key_prefix = (args.s3_key_prefix or os.getenv("S3_BASE_PATH", "lightx2v/sync")).strip("/") |
| 34 | object_name = f"{uuid.uuid4().hex}.png" |
| 35 | object_key = f"{key_prefix}/{object_name}" if key_prefix else object_name |
| 36 | |
| 37 | region = args.s3_region or os.getenv("AWS_DEFAULT_REGION", "us-east-1") |
| 38 | access_key = args.s3_access_key or os.getenv("AWS_ACCESS_KEY_ID") |
| 39 | secret_key = args.s3_secret_key or os.getenv("AWS_SECRET_ACCESS_KEY") |
| 40 | session_token = args.s3_session_token or os.getenv("AWS_SESSION_TOKEN") |
| 41 | addressing_style = (args.s3_addressing_style or os.getenv("S3_ADDRESSING_STYLE", "auto")).strip().lower() |
| 42 | if addressing_style not in {"auto", "path", "virtual"}: |
| 43 | raise ValueError("--s3_addressing_style must be one of: auto, path, virtual") |
| 44 | signature_version = (args.s3_signature_version or os.getenv("S3_SIGNATURE_VERSION", "s3v4")).strip() |
| 45 | |
| 46 | client_kwargs: Dict[str, Any] = { |
| 47 | "service_name": "s3", |
| 48 | "region_name": region, |
| 49 | "config": BotoConfig( |
| 50 | signature_version=signature_version, |
| 51 | s3={"addressing_style": addressing_style}, |
| 52 | ), |
| 53 | } |
| 54 | if args.s3_endpoint_url: |
| 55 | client_kwargs["endpoint_url"] = args.s3_endpoint_url |
| 56 | if access_key and secret_key: |
| 57 | client_kwargs["aws_access_key_id"] = access_key |
| 58 | client_kwargs["aws_secret_access_key"] = secret_key |
| 59 | if session_token: |
| 60 | client_kwargs["aws_session_token"] = session_token |
| 61 | |
| 62 | s3_client = boto3.client(**client_kwargs) |
| 63 | put_presigned_url = s3_client.generate_presigned_url( |
| 64 | ClientMethod="put_object", |
| 65 | Params={"Bucket": bucket, "Key": object_key}, |
| 66 | ExpiresIn=args.presign_expires, |
| 67 | HttpMethod="PUT", |
| 68 | ) |
| 69 | get_presigned_url = s3_client.generate_presigned_url( |
| 70 | ClientMethod="get_object", |
| 71 | Params={"Bucket": bucket, "Key": object_key}, |
| 72 | ExpiresIn=args.presign_expires, |
| 73 | HttpMethod="GET", |
| 74 | ) |
| 75 | print(f"Generated presigned URL for s3://{bucket}/{object_key}") |