Repository navigation
Expand file tree
/
Copy pathpicui.ts
More file actions
423 lines (360 loc) · 11.8 KB
/
Copy pathpicui.ts
File metadata and controls
423 lines (360 loc) · 11.8 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
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
/* eslint-disable no-console */
import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
import type { ImageBucketConfig } from '@/types';
import { getSystemConfig } from './db';
import { fetch as undiciFetch, File, FormData } from 'undici';
import { fetchWithRetry } from './http-retry';
type UploadPayload = {
buffer: Buffer;
extension: string;
filename: string;
mimeType: string;
objectKey: string;
};
type UploadOptions = {
publicBaseUrl?: string;
preferDirectS3Url?: boolean;
};
export type S3CachedObject = {
buffer: Buffer;
contentType: string;
contentLength: number;
etag?: string;
lastModified?: Date;
};
const EXTENSION_BY_MIME: Record<string, string> = {
'image/jpeg': 'jpg',
'image/jpg': 'jpg',
'image/png': 'png',
'image/gif': 'gif',
'image/webp': 'webp',
'image/bmp': 'bmp',
'video/mp4': 'mp4',
'video/mpeg': 'mpeg',
'video/quicktime': 'mov',
'video/webm': 'webm',
};
const s3Clients = new Map<string, S3Client>();
export interface PicUIUploadResponse {
status: boolean;
message: string;
data?: {
links?: {
url?: string;
};
};
}
function normalizeSegment(value: string): string {
return value
.trim()
.replace(/\\/g, '/')
.replace(/^\/+|\/+$/g, '');
}
function normalizeS3ObjectKey(value: string): string {
return value
.trim()
.replace(/\\/g, '/')
.replace(/^\/+/, '')
.split('/')
.filter((segment) => segment && segment !== '.' && segment !== '..')
.join('/');
}
function buildObjectKey(bucket: ImageBucketConfig, filename: string): string {
const normalizedFilename = normalizeSegment(filename).split('/').pop() || filename;
const prefix = normalizeSegment(bucket.pathPrefix || '');
return prefix ? `${prefix}/${normalizedFilename}` : normalizedFilename;
}
function isS3CacheKeyAllowed(bucket: ImageBucketConfig, objectKey: string): boolean {
const normalizedKey = normalizeS3ObjectKey(objectKey);
if (!normalizedKey) return false;
const prefix = normalizeSegment(bucket.pathPrefix || '');
if (!prefix) return true;
return normalizedKey !== prefix && normalizedKey.startsWith(`${prefix}/`);
}
function getExtensionForMime(mimeType: string): string {
return EXTENSION_BY_MIME[mimeType.toLowerCase().split(';')[0]?.trim() || ''] || 'bin';
}
function ensureFilenameExtension(filename: string, extension: string): string {
const trimmed = normalizeSegment(filename).split('/').pop() || `media_${Date.now()}.${extension}`;
if (/\.[a-z0-9]{2,5}$/i.test(trimmed)) return trimmed;
return `${trimmed}.${extension}`;
}
function parseUploadPayload(base64Data: string, filename?: string, bucket?: ImageBucketConfig): UploadPayload {
let mimeType = 'image/jpeg';
let pureBase64 = base64Data;
if (base64Data.startsWith('data:')) {
const matches = base64Data.match(/^data:([^;]+);base64,(.+)$/);
if (matches) {
mimeType = matches[1];
pureBase64 = matches[2];
}
}
const extension = getExtensionForMime(mimeType);
const safeFilename = ensureFilenameExtension(filename?.trim() || `image_${Date.now()}`, extension);
const objectKey = buildObjectKey(bucket || { pathPrefix: '' } as ImageBucketConfig, safeFilename);
return {
buffer: Buffer.from(pureBase64, 'base64'),
extension,
filename: safeFilename,
mimeType,
objectKey,
};
}
function buildUploadPayloadFromBuffer(
buffer: Buffer,
mimeType: string,
filename?: string,
bucket?: ImageBucketConfig
): UploadPayload {
const normalizedMimeType = mimeType.split(';')[0]?.trim().toLowerCase() || 'application/octet-stream';
const extension = getExtensionForMime(normalizedMimeType);
const safeFilename = ensureFilenameExtension(filename?.trim() || `media_${Date.now()}`, extension);
const objectKey = buildObjectKey(bucket || { pathPrefix: '' } as ImageBucketConfig, safeFilename);
return {
buffer,
extension,
filename: safeFilename,
mimeType: normalizedMimeType,
objectKey,
};
}
export function resolveDefaultImageBucket(): Promise<ImageBucketConfig | null> {
return getSystemConfig().then((config) => {
const buckets = config.imageStorage?.buckets || [];
const enabledBuckets = buckets.filter((bucket) => bucket.enabled);
if (enabledBuckets.length === 0) {
return null;
}
if (config.imageStorage?.defaultBucketId) {
const matched = enabledBuckets.find(
(bucket) => bucket.id === config.imageStorage.defaultBucketId
);
if (matched) return matched;
}
return enabledBuckets[0] || null;
});
}
async function resolveS3CacheBucket(bucketId?: string): Promise<ImageBucketConfig | null> {
const config = await getSystemConfig();
const buckets = (config.imageStorage?.buckets || []).filter(
(bucket) => bucket.enabled && bucket.provider === 's3-compatible'
);
if (bucketId) {
return buckets.find((bucket) => bucket.id === bucketId) || null;
}
if (config.imageStorage?.defaultBucketId) {
const defaultBucket = buckets.find((bucket) => bucket.id === config.imageStorage.defaultBucketId);
if (defaultBucket) return defaultBucket;
}
return buckets[0] || null;
}
async function uploadToPicuiBucket(
bucket: ImageBucketConfig,
payload: UploadPayload
): Promise<string | null> {
if (!bucket.baseUrl || !bucket.apiKey) return null;
const buildFormData = () => {
const formData = new FormData();
formData.append('file', new File([payload.buffer], payload.filename, { type: payload.mimeType }));
formData.append('permission', '1');
return formData;
};
const apiUrl = `${bucket.baseUrl.replace(/\/$/, '')}/upload`;
const response = await fetchWithRetry(undiciFetch, apiUrl, () => ({
method: 'POST',
headers: {
Authorization: `Bearer ${bucket.apiKey}`,
Accept: 'application/json',
},
body: buildFormData(),
}));
const data = (await response.json()) as PicUIUploadResponse;
if (!response.ok || !data.status) {
console.error('[ImageBucket] PicUI upload failed:', data.message);
return null;
}
return data.data?.links?.url || null;
}
function getS3Client(bucket: ImageBucketConfig): S3Client {
const cacheKey = [
bucket.id,
bucket.baseUrl,
bucket.region,
bucket.apiKey,
bucket.secretKey,
bucket.forcePathStyle,
].join('|');
const cached = s3Clients.get(cacheKey);
if (cached) return cached;
const client = new S3Client({
region: bucket.region || 'us-east-1',
endpoint: bucket.baseUrl,
forcePathStyle: bucket.forcePathStyle !== false,
credentials: {
accessKeyId: bucket.apiKey,
secretAccessKey: bucket.secretKey || '',
},
});
s3Clients.set(cacheKey, client);
return client;
}
function normalizePublicBaseUrl(value?: string): string {
return (value || process.env.SANHUB_PUBLIC_BASE_URL || process.env.NEXTAUTH_URL || '')
.trim()
.replace(/\/$/, '');
}
function buildPublicPath(path: string, options?: UploadOptions): string {
const publicBaseUrl = normalizePublicBaseUrl(options?.publicBaseUrl);
return publicBaseUrl ? `${publicBaseUrl}${path}` : path;
}
function buildS3CacheUrl(bucket: ImageBucketConfig, objectKey: string, options?: UploadOptions): string {
const params = new URLSearchParams();
params.set('key', objectKey);
params.set('bucket', bucket.id);
return buildPublicPath(`/cache/s3?${params.toString()}`, options);
}
function encodeObjectKey(key: string): string {
return key
.split('/')
.map((segment) => encodeURIComponent(segment))
.join('/');
}
function buildDirectS3PublicUrl(bucket: ImageBucketConfig, objectKey: string): string {
const encodedKey = encodeObjectKey(objectKey);
const publicBaseUrl = bucket.publicBaseUrl?.trim();
if (publicBaseUrl) {
return `${publicBaseUrl.replace(/\/$/, '')}/${encodedKey}`;
}
const baseUrl = bucket.baseUrl.replace(/\/$/, '');
return `${baseUrl}/${bucket.bucketName}/${encodedKey}`;
}
async function uploadToS3Bucket(
bucket: ImageBucketConfig,
payload: UploadPayload,
options?: UploadOptions
): Promise<string | null> {
if (!bucket.baseUrl || !bucket.apiKey || !bucket.secretKey || !bucket.bucketName) {
return null;
}
const client = getS3Client(bucket);
await client.send(
new PutObjectCommand({
Bucket: bucket.bucketName,
Key: payload.objectKey,
Body: payload.buffer,
ContentType: payload.mimeType,
CacheControl: 'public, max-age=31536000, immutable',
})
);
return options?.preferDirectS3Url
? buildDirectS3PublicUrl(bucket, payload.objectKey)
: buildS3CacheUrl(bucket, payload.objectKey, options);
}
async function uploadPayloadToBucket(
bucket: ImageBucketConfig,
payload: UploadPayload,
options?: UploadOptions
): Promise<string | null> {
if (bucket.provider === 's3-compatible') {
return await uploadToS3Bucket(bucket, payload, options);
}
if (!payload.mimeType.startsWith('image/')) {
return null;
}
return await uploadToPicuiBucket(bucket, payload);
}
export async function uploadToImageBucket(
base64Data: string,
filename?: string,
options?: UploadOptions
): Promise<string | null> {
const bucket = await resolveDefaultImageBucket();
if (!bucket) {
console.log('[ImageBucket] No enabled bucket configured, skip upload');
return null;
}
const payload = parseUploadPayload(base64Data, filename, bucket);
try {
return await uploadPayloadToBucket(bucket, payload, options);
} catch (error) {
console.error('[ImageBucket] Upload failed:', error);
return null;
}
}
export async function uploadBufferToImageBucket(
buffer: Buffer,
mimeType: string,
filename?: string,
options?: UploadOptions
): Promise<string | null> {
const bucket = await resolveDefaultImageBucket();
if (!bucket) {
console.log('[ImageBucket] No enabled bucket configured, skip upload');
return null;
}
const payload = buildUploadPayloadFromBuffer(buffer, mimeType, filename, bucket);
try {
return await uploadPayloadToBucket(bucket, payload, options);
} catch (error) {
console.error('[ImageBucket] Upload failed:', error);
return null;
}
}
export async function uploadToPicUI(
base64Data: string,
filename?: string,
options?: UploadOptions
): Promise<string | null> {
return uploadToImageBucket(base64Data, filename, options);
}
export async function uploadImageOrKeepBase64(
base64Data: string,
filename?: string,
options?: UploadOptions
): Promise<string> {
const url = await uploadToImageBucket(base64Data, filename, options);
return url || base64Data;
}
async function streamToBuffer(body: unknown): Promise<Buffer> {
if (!body) return Buffer.alloc(0);
const byteArrayStream = body as { transformToByteArray?: () => Promise<Uint8Array> };
if (typeof byteArrayStream.transformToByteArray === 'function') {
return Buffer.from(await byteArrayStream.transformToByteArray());
}
const chunks: Buffer[] = [];
for await (const chunk of body as AsyncIterable<Uint8Array | Buffer | string>) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
export async function getS3CachedObject(
objectKey: string,
bucketId?: string
): Promise<S3CachedObject> {
const normalizedKey = normalizeS3ObjectKey(objectKey);
if (!normalizedKey) {
throw new Error('S3 key is required');
}
const bucket = await resolveS3CacheBucket(bucketId);
if (!bucket) {
throw new Error('S3 bucket is not configured');
}
if (!isS3CacheKeyAllowed(bucket, normalizedKey)) {
throw new Error('S3 key is outside the configured cache prefix');
}
const client = getS3Client(bucket);
const result = await client.send(
new GetObjectCommand({
Bucket: bucket.bucketName,
Key: normalizedKey,
})
);
const buffer = await streamToBuffer(result.Body);
return {
buffer,
contentType: result.ContentType || 'application/octet-stream',
contentLength: Number(result.ContentLength || buffer.length),
etag: result.ETag,
lastModified: result.LastModified,
};
}