File size: 3,521 Bytes
3bb9361
bc81c34
3bb9361
 
 
 
 
bc81c34
 
 
 
 
3bb9361
 
 
 
 
 
bc81c34
 
3bb9361
 
bc81c34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bb9361
bc81c34
 
 
 
 
 
 
 
 
3bb9361
bc81c34
3bb9361
bc81c34
 
 
 
 
3bb9361
bc81c34
 
 
 
 
 
 
3bb9361
bc81c34
 
 
 
 
 
 
 
 
 
3bb9361
bc81c34
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import boto3

# AWS credentials (if not set in environment variables or AWS CLI config)
from dotenv import load_dotenv
import os
import sys
from utils import doc_processing
import mimetypes
from pathlib import Path
from django.conf import settings

BASE_DIR = Path(__file__).resolve().parent.parent.parent

# Load .env file
load_dotenv()
# Access variables
AWS_ACCESS_KEY_ID = os.getenv("AWS_ACCESS_KEY_ID")
AWS_SECRET_ACCESS_KEY = os.getenv("AWS_SECRET_ACCESS_KEY")
print("AWS_ACCESS_KEY_ID", AWS_ACCESS_KEY_ID)
print("AWS_SECRET_ACCESS_KEY", AWS_SECRET_ACCESS_KEY)
# Initialize S3 client

# class s3_client:
#     def __init__(self):
#         self.aws_access_key_id = AWS_ACCESS_KEY_ID
#         self.aws_secret_access_key = AWS_SECRET_ACCESS_KEY

#     def initialize(self):
#         return boto3.client(
#                 's3',
#                 aws_access_key_id=self.aws_access_key_id,
#                 aws_secret_access_key=self.aws_secret_access_key
#                             )

#     def upload_file(self,local_file_path, bucket_name,folder_name,file_name):
#         try:
#             client = self.initialize()
#             client.upload_file(local_file_path, bucket_name, f"{folder_name}/{file_name}")
#             print(f"File uploaded successfully to {bucket_name}/{folder_name}{file_name}")
#             url = f"https://edgekycdocs.s3.eu-north-1.amazonaws.com/{folder_name}/{file_name}"
#             print("file url",url)
#             return {"status": 200, "message":"file uploaded successfully" , "url" : url}
#         except Exception as e:
#             print("Error uploading file:", e)
#             return {"status": 400, "message":e}


class S3Client:
    def __init__(self):
        self.aws_access_key_id = settings.AWS_ACCESS_KEY_ID
        self.aws_secret_access_key = settings.AWS_SECRET_ACCESS_KEY
        self.s3_client = boto3.client(
            "s3",
            aws_access_key_id=self.aws_access_key_id,
            aws_secret_access_key=self.aws_secret_access_key,
        )

    def upload_file(self, local_file_path, bucket_name, folder_name, file_name):
        try:
            file_key = f"{folder_name}/{file_name}"

            # Determine the MIME type dynamically
            # Determine the correct MIME type
            content_type, _ = mimetypes.guess_type(local_file_path)
            if content_type is None:
                content_type = "application/octet-stream"  # Default fallback

            # Explicitly handle common file types
            if file_name.lower().endswith(
                (".pdf", ".jpg", ".jpeg", ".png", ".gif", ".webp")
            ):
                content_type = (
                    mimetypes.guess_type(file_name)[0] or "application/octet-stream"
                )

            # Upload with correct Content-Type
            self.s3_client.upload_file(
                local_file_path,
                bucket_name,
                file_key,
                ExtraArgs={
                    "ContentDisposition": "inline",  # Ensure inline display
                    "ContentType": content_type,
                },
            )

            file_url = f"https://{bucket_name}.s3.amazonaws.com/{file_key}"
            print(f"Uploading {file_name} with ContentType: {content_type}")
            return {
                "status": 200,
                "message": "File uploaded successfully",
                "url": file_url,
            }
        except Exception as e:
            return {"status": 400, "message": str(e)}