-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.js
265 lines (229 loc) · 7.92 KB
/
handler.js
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/* eslint-disable no-await-in-loop */
const axios = require('axios');
const { parse: parseFileName, join } = require('path');
const s3client = require('@aws-sdk/client-s3');
const fs = require('fs/promises');
const sharp = require('sharp');
const path = require('path');
const resizeImage = async (inputFile, outputFile) => {
await sharp(inputFile)
.jpeg({ quality: 50, progressive: true })
.toFile(outputFile);
};
const downloadFromS3 = async ({ file, bucket, region }) => {
console.log(
`[DownloadFromS3] Starting download from S3. File: ${file}, Bucket: ${bucket}, Region: ${region}`
);
const s3 = new s3client.S3Client({ region });
const data = await s3.send(
new s3client.GetObjectCommand({
Bucket: bucket,
Key: file,
})
);
const endFileName = join('/', 'tmp', file);
const parsedFileName = parseFileName(endFileName);
await fs.mkdir(parsedFileName.dir, { recursive: true });
await fs.writeFile(join('/', 'tmp', file), data.Body);
console.log(
`[DownloadFromS3] Download from S3 completed. File: ${file}, Bucket: ${bucket}, Region: ${region}`
);
return data.Metadata;
};
const uploadToS3 = async ({ file, key, bucket, region }) => {
console.log(
`[UploadToS3] Starting upload to S3. File: ${file}, Key: ${key}, Bucket: ${bucket}, Region: ${region}`
);
const s3 = new s3client.S3Client({ region });
const body = await fs.readFile(join('/', 'tmp', file));
await s3.send(
new s3client.PutObjectCommand({
Bucket: bucket,
Key: key,
Body: body,
})
);
console.log(
`[UploadToS3] Upload to S3 completed. File: ${file}, Key: ${key}, Bucket: ${bucket}, Region: ${region}`
);
};
const notify = ({ filename, size, newFilename }) =>
new Promise((resolve, reject) => {
const url = `${process.env.NOTIFY_API_URL}/assets/notify/file`;
const data = { filename, size };
if (newFilename && newFilename.length) data.newFilename = newFilename;
console.log('url:', url);
console.log({ data });
setTimeout(async () => {
try {
const response = await axios.put(url, data);
console.log(`Status: ${response.status}`);
console.log('Body: ', response.data);
resolve(response);
} catch (error) {
console.error(`Error: ${error}`);
reject(error);
}
}, 2000);
});
const resizeOriginalImage = async (
{ inputFile, bucket, region, filename, metadata },
quality = 99
) => {
let stats = await fs.stat(inputFile);
let currentQuality = quality;
let changeFormat = '';
let deleted = false;
const tempFile = `${inputFile}.tmp`;
const originalFormat = path.extname(inputFile).slice(1);
let endFileName = '';
const maxSize = Number(metadata?.maxsize) * 1000000;
console.log('stats:', stats);
console.log('metadata maxSize:', metadata, maxSize);
console.log('inputFile:', inputFile, 'filename:', filename);
while (stats.size > maxSize) {
console.log(
'size',
stats.size,
'quality:',
currentQuality,
'originalFormat:',
originalFormat
);
if (originalFormat === 'png') {
if (!deleted) {
const s3 = new s3client.S3Client({ region });
await s3.send(
new s3client.DeleteObjectCommand({
Bucket: bucket,
Key: filename,
})
);
deleted = true;
}
await sharp(inputFile)
.jpeg({
quality: currentQuality,
progressive: true,
})
.toFile(tempFile);
changeFormat = 'jpeg';
} else {
await sharp(inputFile)
.toFormat(originalFormat, {
quality: currentQuality,
progressive: true,
})
.toFile(tempFile);
}
stats = await fs.stat(tempFile);
if (stats.size > maxSize) {
currentQuality -= 1;
if (currentQuality === 0) {
throw new Error('Unable to reduce file size under 10MB');
}
} else {
const parsedFileName = parseFileName(filename);
const newFilename = changeFormat?.length
? `${parsedFileName.name}.${changeFormat}`
: filename;
const pathFileName = changeFormat?.length
? join('/', 'tmp', `${parsedFileName.name}.${changeFormat}`)
: join('/', 'tmp', filename);
await fs.rename(tempFile, pathFileName);
endFileName = join(
parsedFileName.dir,
`${parsedFileName.name}.${changeFormat?.length ? changeFormat : originalFormat}`
);
console.log('newFilename:', newFilename);
console.log('pathFileName:', pathFileName);
console.log('endFileName:', endFileName);
await uploadToS3({
file: newFilename,
key: endFileName,
bucket,
region,
});
}
}
await notify({ filename, size: stats.size, newFilename: endFileName });
};
const generateThumb = async ({ filename, bucket, region }) => {
console.log(
`[GenerateThumb] Starting thumbnail generation. Filename: ${filename}, Bucket: ${bucket}, Region: ${region}`
);
const metadata = await downloadFromS3({
file: filename,
bucket,
region,
});
const parsedFileName = parseFileName(filename);
const thumbFilename = `${parsedFileName.name}_thumb.jpg`;
await resizeImage(
join('/', 'tmp', filename),
join('/', 'tmp', thumbFilename)
);
const endFileName = join(parsedFileName.dir, thumbFilename);
await uploadToS3({
file: thumbFilename,
key: endFileName,
bucket,
region,
});
const originalFile = join('/', 'tmp', filename);
if (metadata?.maxsize)
await resizeOriginalImage({
inputFile: originalFile,
bucket,
region,
filename,
metadata,
});
console.log(
`[GenerateThumb] Thumbnail generation completed. Filename: ${filename}, Bucket: ${bucket}, Region: ${region}`
);
};
module.exports.postprocess = async (event) => {
await Promise.all(
event.Records.map((record) =>
generateThumb({
filename: record.s3.object.key,
bucket: record.s3.bucket.name,
region: record.awsRegion,
})
)
);
};
const deleteThumb = async ({ filename, bucket, region }) => {
try {
console.log(
`[DeleteThumb] Starting thumbnail deletion. Filename: ${filename}, Bucket: ${bucket}, Region: ${region}`
);
const parsedFileName = parseFileName(filename);
const thumbFilename = `${parsedFileName.name}_thumb.jpg`;
const endFileName = join(parsedFileName.dir, thumbFilename);
const s3 = new s3client.S3Client({ region });
await s3.send(
new s3client.DeleteObjectCommand({
Bucket: bucket,
Key: endFileName,
})
);
console.log(
`[DeleteThumb] Thumbnail deletion completed. Filename: ${endFileName}, Bucket: ${bucket}, Region: ${region}`
);
} catch (error) {
console.log(error);
}
};
module.exports.postdelete = async (event) => {
await Promise.all(
event.Records.map((record) =>
deleteThumb({
filename: record.s3.object.key,
bucket: record.s3.bucket.name,
region: record.awsRegion,
})
)
);
};