-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
543 lines (465 loc) · 18 KB
/
index.ts
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
import { PluginOptions } from './types.js';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { ExpirationStatus, GetObjectCommand, ObjectCannedACL, PutObjectCommand, S3 } from '@aws-sdk/client-s3';
import { AdminForthPlugin, AdminForthResourceColumn, AdminForthResource, Filters, IAdminForth, IHttpServer, suggestIfTypo } from "adminforth";
import { Readable } from "stream";
import { RateLimiter } from "adminforth";
const ADMINFORTH_NOT_YET_USED_TAG = 'adminforth-candidate-for-cleanup';
export default class UploadPlugin extends AdminForthPlugin {
options: PluginOptions;
adminforth!: IAdminForth;
constructor(options: PluginOptions) {
super(options, import.meta.url);
this.options = options;
}
instanceUniqueRepresentation(pluginOptions: any) : string {
return `${pluginOptions.pathColumnName}`;
}
async setupLifecycleRule() {
// check that lifecyle rule "adminforth-unused-cleaner" exists
const CLEANUP_RULE_ID = 'adminforth-unused-cleaner';
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
// check bucket exists
const bucketExists = s3.headBucket({ Bucket: this.options.s3Bucket })
if (!bucketExists) {
throw new Error(`Bucket ${this.options.s3Bucket} does not exist`);
}
// check that lifecycle rule exists
let ruleExists: boolean = false;
try {
const lifecycleConfig: any = await s3.getBucketLifecycleConfiguration({ Bucket: this.options.s3Bucket });
ruleExists = lifecycleConfig.Rules.some((rule: any) => rule.ID === CLEANUP_RULE_ID);
} catch (e: any) {
if (e.name !== 'NoSuchLifecycleConfiguration') {
console.error(`⛔ Error checking lifecycle configuration, please check keys have permissions to
getBucketLifecycleConfiguration on bucket ${this.options.s3Bucket} in region ${this.options.s3Region}. Exception:`, e);
throw e;
} else {
ruleExists = false;
}
}
if (!ruleExists) {
// create
// rule deletes object has tag adminforth-candidate-for-cleanup = true after 2 days
const params = {
Bucket: this.options.s3Bucket,
LifecycleConfiguration: {
Rules: [
{
ID: CLEANUP_RULE_ID,
Status: ExpirationStatus.Enabled,
Filter: {
Tag: {
Key: ADMINFORTH_NOT_YET_USED_TAG,
Value: 'true'
}
},
Expiration: {
Days: 2
}
}
]
}
};
await s3.putBucketLifecycleConfiguration(params);
}
}
async genPreviewUrl(record: any, s3: S3) {
if (this.options.preview?.previewUrl) {
record[`previewUrl_${this.pluginInstanceId}`] = this.options.preview.previewUrl({ s3Path: record[this.options.pathColumnName] });
return;
}
const previewUrl = await await getSignedUrl(s3, new GetObjectCommand({
Bucket: this.options.s3Bucket,
Key: record[this.options.pathColumnName],
}));
record[`previewUrl_${this.pluginInstanceId}`] = previewUrl;
}
async modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource) {
super.modifyResourceConfig(adminforth, resourceConfig);
// after column to store the path of the uploaded file, add new VirtualColumn,
// show only in edit and create views
// use component uploader.vue
const { pathColumnName } = this.options;
const pathColumnIndex = resourceConfig.columns.findIndex((column: any) => column.name === pathColumnName);
if (pathColumnIndex === -1) {
throw new Error(`Column with name "${pathColumnName}" not found in resource "${resourceConfig.label}"`);
}
if (this.options.generation?.fieldsForContext) {
this.options.generation?.fieldsForContext.forEach((field: string) => {
if (!resourceConfig.columns.find((column: any) => column.name === field)) {
const similar = suggestIfTypo(resourceConfig.columns.map((column: any) => column.name), field);
throw new Error(`Field "${field}" specified in fieldsForContext not found in
resource "${resourceConfig.label}". ${similar ? `Did you mean "${similar}"?` : ''}`);
}
});
}
const pluginFrontendOptions = {
allowedExtensions: this.options.allowedFileExtensions,
maxFileSize: this.options.maxFileSize,
pluginInstanceId: this.pluginInstanceId,
resourceLabel: resourceConfig.label,
generateImages: this.options.generation ? true : false,
pathColumnLabel: resourceConfig.columns[pathColumnIndex].label,
fieldsForContext: this.options.generation?.fieldsForContext,
maxWidth: this.options.preview?.maxWidth,
};
// define components which will be imported from other components
this.componentPath('imageGenerator.vue');
const virtualColumn: AdminForthResourceColumn = {
virtual: true,
name: `uploader_${this.pluginInstanceId}`,
components: {
edit: {
file: this.componentPath('uploader.vue'),
meta: pluginFrontendOptions,
},
create: {
file: this.componentPath('uploader.vue'),
meta: pluginFrontendOptions,
},
},
showIn: {
create: true,
edit: true,
list: false,
show: false,
filter: false,
}
};
if (!resourceConfig.columns[pathColumnIndex].components) {
resourceConfig.columns[pathColumnIndex].components = {};
}
if (this.options.preview?.showInList || this.options.preview?.showInList === undefined) {
// add preview column to list
resourceConfig.columns[pathColumnIndex].components.list = {
file: this.componentPath('preview.vue'),
meta: pluginFrontendOptions,
};
}
if (this.options.preview?.showInShow || this.options.preview?.showInShow === undefined) {
resourceConfig.columns[pathColumnIndex].components.show = {
file: this.componentPath('preview.vue'),
meta: pluginFrontendOptions,
};
}
// insert virtual column after path column if it is not already there
const virtualColumnIndex = resourceConfig.columns.findIndex((column: any) => column.name === virtualColumn.name);
if (virtualColumnIndex === -1) {
resourceConfig.columns.splice(pathColumnIndex + 1, 0, virtualColumn);
}
// if showIn of path column has 'create' or 'edit' remove it
const pathColumn = resourceConfig.columns[pathColumnIndex];
if (pathColumn.showIn && (pathColumn.showIn.create || pathColumn.showIn.edit)) {
pathColumn.showIn = { ...pathColumn.showIn, create: false, edit: false };
}
virtualColumn.required = pathColumn.required;
virtualColumn.label = pathColumn.label;
virtualColumn.editingNote = pathColumn.editingNote;
// ** HOOKS FOR CREATE **//
// add beforeSave hook to save virtual column to path column
resourceConfig.hooks.create.beforeSave.push(async ({ record }: { record: any }) => {
if (record[virtualColumn.name]) {
record[pathColumnName] = record[virtualColumn.name];
delete record[virtualColumn.name];
}
return { ok: true };
});
// in afterSave hook, aremove tag adminforth-not-yet-used from the file
resourceConfig.hooks.create.afterSave.push(async ({ record }: { record: any }) => {
process.env.HEAVY_DEBUG && console.log('💾💾 after save ', record?.id);
if (record[pathColumnName]) {
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
process.env.HEAVY_DEBUG && console.log('🪥🪥 remove ObjectTagging', record[pathColumnName]);
// let it crash if it fails: this is a new file which just was uploaded.
await s3.putObjectTagging({
Bucket: this.options.s3Bucket,
Key: record[pathColumnName],
Tagging: {
TagSet: []
}
});
}
return { ok: true };
});
// ** HOOKS FOR SHOW **//
// add show hook to get presigned URL
resourceConfig.hooks.show.afterDatasourceResponse.push(async ({ response }: { response: any }) => {
const record = response[0];
if (!record) {
return { ok: true };
}
if (record[pathColumnName]) {
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
await this.genPreviewUrl(record, s3);
}
return { ok: true };
});
// ** HOOKS FOR LIST **//
if (this.options.preview?.showInList || this.options.preview?.showInList === undefined) {
resourceConfig.hooks.list.afterDatasourceResponse.push(async ({ response }: { response: any }) => {
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
await Promise.all(response.map(async (record: any) => {
if (record[this.options.pathColumnName]) {
await this.genPreviewUrl(record, s3);
}
}));
return { ok: true };
})
}
// ** HOOKS FOR DELETE **//
// add delete hook which sets tag adminforth-candidate-for-cleanup to true
resourceConfig.hooks.delete.afterSave.push(async ({ record }: { record: any }) => {
if (record[pathColumnName]) {
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
try {
await s3.putObjectTagging({
Bucket: this.options.s3Bucket,
Key: record[pathColumnName],
Tagging: {
TagSet: [
{
Key: ADMINFORTH_NOT_YET_USED_TAG,
Value: 'true'
}
]
}
});
} catch (e) {
// file might be e.g. already deleted, so we catch error
console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${record[pathColumnName]}. File will not be auto-cleaned up`, e);
}
}
return { ok: true };
});
// ** HOOKS FOR EDIT **//
// beforeSave
resourceConfig.hooks.edit.beforeSave.push(async ({ record }: { record: any }) => {
// null is when value is removed
if (record[virtualColumn.name] || record[virtualColumn.name] === null) {
record[pathColumnName] = record[virtualColumn.name];
}
return { ok: true };
})
// add edit postSave hook to delete old file and remove tag from new file
resourceConfig.hooks.edit.afterSave.push(async ({ updates, oldRecord }: { updates: any, oldRecord: any }) => {
if (updates[virtualColumn.name] || updates[virtualColumn.name] === null) {
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
if (oldRecord[pathColumnName]) {
// put tag to delete old file
try {
await s3.putObjectTagging({
Bucket: this.options.s3Bucket,
Key: oldRecord[pathColumnName],
Tagging: {
TagSet: [
{
Key: ADMINFORTH_NOT_YET_USED_TAG,
Value: 'true'
}
]
}
});
} catch (e) {
// file might be e.g. already deleted, so we catch error
console.error(`Error setting tag ${ADMINFORTH_NOT_YET_USED_TAG} to true for object ${oldRecord[pathColumnName]}. File will not be auto-cleaned up`, e);
}
}
if (updates[virtualColumn.name] !== null) {
// remove tag from new file
// in this case we let it crash if it fails: this is a new file which just was uploaded.
await s3.putObjectTagging({
Bucket: this.options.s3Bucket,
Key: updates[pathColumnName],
Tagging: {
TagSet: []
}
});
}
}
return { ok: true };
});
}
validateConfigAfterDiscover(adminforth: IAdminForth, resourceConfig: any) {
this.adminforth = adminforth;
// called here because modifyResourceConfig can be called in build time where there is no environment and AWS secrets
this.setupLifecycleRule();
}
setupEndpoints(server: IHttpServer) {
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/get_s3_upload_url`,
handler: async ({ body }) => {
const { originalFilename, contentType, size, originalExtension, recordPk } = body;
if (this.options.allowedFileExtensions && !this.options.allowedFileExtensions.includes(originalExtension)) {
return {
error: `File extension "${originalExtension}" is not allowed, allowed extensions are: ${this.options.allowedFileExtensions.join(', ')}`
};
}
let record = undefined;
if (recordPk) {
// get record by recordPk
const pkName = this.resourceConfig.columns.find((column: any) => column.primaryKey)?.name;
record = await this.adminforth.resource(this.resourceConfig.resourceId).get(
[Filters.EQ(pkName, recordPk)]
)
}
const s3Path: string = this.options.s3Path({ originalFilename, originalExtension, contentType, record });
if (s3Path.startsWith('/')) {
throw new Error('s3Path should not start with /, please adjust s3path function to not return / at the start of the path');
}
const s3 = new S3({
credentials: {
accessKeyId: this.options.s3AccessKeyId,
secretAccessKey: this.options.s3SecretAccessKey,
},
region: this.options.s3Region,
});
const tagline = `${ADMINFORTH_NOT_YET_USED_TAG}=true`;
const params = {
Bucket: this.options.s3Bucket,
Key: s3Path,
ContentType: contentType,
ACL: (this.options.s3ACL || 'private') as ObjectCannedACL,
Tagging: tagline,
};
const uploadUrl = await await getSignedUrl(s3, new PutObjectCommand(params), {
expiresIn: 1800,
unhoistableHeaders: new Set(['x-amz-tagging']),
});
let previewUrl;
if (this.options.preview?.previewUrl) {
previewUrl = this.options.preview.previewUrl({ s3Path });
} else if (this.options.s3ACL === 'public-read') {
previewUrl = `https://${this.options.s3Bucket}.s3.${this.options.s3Region}.amazonaws.com/${s3Path}`;
} else {
previewUrl = await getSignedUrl(s3, new GetObjectCommand({
Bucket: this.options.s3Bucket,
Key: s3Path,
}));
}
return {
uploadUrl,
s3Path,
tagline,
previewUrl,
};
}
});
// generation: {
// provider: 'openai-dall-e',
// countToGenerate: 3,
// openAiOptions: {
// model: 'dall-e-3',
// size: '1792x1024',
// apiKey: process.env.OPENAI_API_KEY as string,
// },
// },
// curl https://api.openai.com/v1/images/generations \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer $OPENAI_API_KEY" \
// -d '{
// "model": "dall-e-3",
// "prompt": "A cute baby sea otter",
// "n": 1,
// "size": "1024x1024"
// }'
server.endpoint({
method: 'POST',
path: `/plugin/${this.pluginInstanceId}/generate_images`,
handler: async ({ body, headers }) => {
const { prompt } = body;
if (this.options.generation.provider !== 'openai-dall-e') {
throw new Error(`Provider ${this.options.generation.provider} is not supported`);
}
if (this.options.generation.rateLimit?.limit) {
// rate limit
const { error } = RateLimiter.checkRateLimit(
this.pluginInstanceId,
this.options.generation.rateLimit?.limit,
this.adminforth.auth.getClientIp(headers),
);
if (error) {
return { error: this.options.generation.rateLimit.errorMessage };
}
}
const { model, size, apiKey } = this.options.generation.openAiOptions;
const url = 'https://api.openai.com/v1/images/generations';
let error = null;
const images = await Promise.all(
(new Array(this.options.generation.countToGenerate)).fill(0).map(async () => {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
body: JSON.stringify({
model,
prompt,
n: 1,
size,
})
});
const json = await response.json();
if (json.error) {
console.error('Error generating image', json.error);
error = json.error;
return;
}
return json;
})
);
return { error, images };
}
});
server.endpoint({
method: 'GET',
path: `/plugin/${this.pluginInstanceId}/cors-proxy`,
handler: async ({ query, response }) => {
const { url } = query;
const resp = await fetch(url);
response.setHeader('Content-Type', resp.headers.get('Content-Type'));
//@ts-ignore
Readable.fromWeb( resp.body ).pipe( response.blobStream() );
return null
}
});
}
}