-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLambda code API.py
More file actions
187 lines (164 loc) · 6.39 KB
/
Lambda code API.py
File metadata and controls
187 lines (164 loc) · 6.39 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import json
import boto3
import os
import urllib.parse
import uuid
s3_client = boto3.client('s3')
def lambda_handler(event, context):
print('API Handler invoked - Raw event:', json.dumps(event))
try:
# Parse the request
http_method = event.get('httpMethod', 'GET')
body = {}
# Parse body if present
if 'body' in event and event['body']:
try:
body = json.loads(event['body'])
except:
body = {}
# Handle different endpoints
if http_method == 'OPTIONS':
# CORS preflight response
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET,POST,OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
},
'body': ''
}
elif http_method == 'POST':
action = body.get('action', '')
if action == 'test':
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'message': 'API is working!',
'timestamp': context.aws_request_id,
'endpoint': 'test'
})
}
elif action == 'getPresignedUploadUrl':
return generate_presigned_url_response(body)
else:
return {
'statusCode': 400,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'error': 'Invalid action',
'validActions': ['test', 'getPresignedUploadUrl']
})
}
elif http_method == 'GET':
# Handle GET request for download URLs
query_params = event.get('queryStringParameters', {}) or {}
key = query_params.get('key', '')
if not key:
return {
'statusCode': 400,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'error': 'Key parameter required for downloads',
'example': '/upload?key=processed/job_id/1080p/image.jpg'
})
}
# Generate download URL
output_bucket = os.environ.get('OUTPUT_BUCKET', 'output-bucket-image-compressor')
presigned_url = s3_client.generate_presigned_url(
'get_object',
Params={'Bucket': output_bucket, 'Key': key},
ExpiresIn=3600
)
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({
'url': presigned_url,
'key': key,
'expiresIn': 3600,
'message': 'Download URL generated'
})
}
else:
return {
'statusCode': 405,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({'error': 'Method not allowed'})
}
except Exception as e:
print('Error in Lambda handler:', str(e))
return {
'statusCode': 500,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({'error': str(e), 'message': 'Internal server error'})
}
def generate_presigned_url_response(body):
"""Generate presigned URL for S3 upload"""
try:
file_name = body.get('fileName', 'upload.jpg')
file_type = body.get('fileType', 'image/jpeg')
# Generate unique filename
unique_id = str(uuid.uuid4())[:8]
base_name, ext = os.path.splitext(file_name)
safe_file_name = f"{base_name}_{unique_id}{ext}"
# Get bucket from environment
input_bucket = os.environ.get('INPUT_BUCKET', 'input-bucket-image-compressor')
print(f'Generating presigned URL for {file_name}')
# Generate presigned POST data
presigned_post = s3_client.generate_presigned_post(
Bucket=input_bucket,
Key=f"uploads/{safe_file_name}",
Fields={"Content-Type": file_type},
Conditions=[
["starts-with", "$Content-Type", "image/"],
["content-length-range", 0, 10485760] # 10MB
],
ExpiresIn=3600
)
response_data = {
'uploadUrl': presigned_post['url'],
'fields': presigned_post['fields'],
'fileUrl': f"uploads/{safe_file_name}",
'fileName': safe_file_name,
'message': 'Presigned URL generated successfully',
'expiresIn': 3600
}
return {
'statusCode': 200,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps(response_data)
}
except Exception as e:
print('Error generating presigned URL:', str(e))
return {
'statusCode': 500,
'headers': {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
'body': json.dumps({'error': str(e), 'message': 'Failed to generate upload URL'})
}