50 lines
1.6 KiB
Python
50 lines
1.6 KiB
Python
import os
|
|
import boto3
|
|
import uuid
|
|
import mimetypes
|
|
from urllib.parse import urljoin
|
|
import requests
|
|
|
|
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
|
|
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
|
|
AWS_STORAGE_BUCKET_NAME = os.getenv("AWS_STORAGE_BUCKET_NAME")
|
|
S3_ENDPOINT_URL = os.getenv("S3_ENDPOINT_URL")
|
|
S3_REGION = os.getenv("S3_REGION", "us-east-1")
|
|
MEDIA_BASE_PATH = os.getenv("MEDIA_BASE_PATH", "instagram")
|
|
|
|
session = boto3.session.Session()
|
|
s3 = session.client(
|
|
service_name="s3",
|
|
aws_access_key_id=AWS_ACCESS_KEY_ID,
|
|
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
|
|
endpoint_url=S3_ENDPOINT_URL,
|
|
region_name=S3_REGION,
|
|
)
|
|
|
|
|
|
def upload_media_from_url(media_url: str, seller_id: str, post_id: str) -> str | None:
|
|
try:
|
|
response = requests.get(media_url, stream=True, timeout=10)
|
|
response.raise_for_status()
|
|
|
|
content_type = response.headers.get("Content-Type", "")
|
|
ext = mimetypes.guess_extension(content_type) or ".jpg"
|
|
if ext in [".jpe", ".jfif", ".bin"]:
|
|
ext = ".jpg"
|
|
|
|
filename = f"{uuid.uuid4()}{ext}"
|
|
s3_path = f"{MEDIA_BASE_PATH}/{seller_id}/{post_id}/{filename}"
|
|
|
|
s3.upload_fileobj(
|
|
response.raw,
|
|
Bucket=AWS_STORAGE_BUCKET_NAME,
|
|
Key=s3_path,
|
|
ExtraArgs={"ACL": "public-read", "ContentType": content_type}
|
|
)
|
|
|
|
public_url = f"{S3_ENDPOINT_URL}/{AWS_STORAGE_BUCKET_NAME}/{s3_path}"
|
|
return public_url
|
|
|
|
except Exception as e:
|
|
print(f"❌ Failed to upload media from {media_url}: {e}")
|
|
return None |