Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
495 lines (427 loc) · 15 KB
/
Copy pathworker.js
File metadata and controls
495 lines (427 loc) · 15 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
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
const DEFAULT_BASE_PATH = '/image';
const DEFAULT_MANIFEST_KEY = 'manifest.json';
const DEFAULT_IMAGE_KEY_PREFIX = 'images';
const DEFAULT_MANIFEST_CACHE_SECONDS = 60;
const DEFAULT_STATIC_CACHE_SECONDS = 31536000;
const DEVICE_NAMES = ['pc', 'mobile'];
const IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'webp', 'gif', 'avif']);
const GALLERY_NAME_PATTERN = /^[a-z0-9_-]+$/;
const API_CACHE_CONTROL = 'no-store, no-cache, must-revalidate, proxy-revalidate';
let cachedManifest = null;
let cachedManifestAt = 0;
let cachedManifestKey = '';
function trimSlashes(value) {
return String(value || '').replace(/^\/+|\/+$/g, '');
}
function normalizeBasePath(value) {
const raw = String(value || DEFAULT_BASE_PATH).trim();
const withSlash = raw.startsWith('/') ? raw : `/${raw}`;
return withSlash.replace(/\/+$/g, '') || DEFAULT_BASE_PATH;
}
function normalizeBaseUrl(value, fallback) {
return String(value || fallback).replace(/\/+$/g, '');
}
function imageKeyPrefix(env) {
return trimSlashes(env.IMAGE_KEY_PREFIX || DEFAULT_IMAGE_KEY_PREFIX);
}
function manifestKey(env) {
return trimSlashes(env.MANIFEST_KEY || DEFAULT_MANIFEST_KEY) || DEFAULT_MANIFEST_KEY;
}
function toInt(value, fallback, min = 1) {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed < min) return fallback;
return parsed;
}
function corsHeaders(cacheControl = API_CACHE_CONTROL) {
return {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Range',
'Access-Control-Expose-Headers': 'Location, Content-Length, Content-Type, Cache-Control, ETag',
'Cache-Control': cacheControl
};
}
function apiHeaders(extra = {}) {
return {
...corsHeaders(API_CACHE_CONTROL),
Pragma: 'no-cache',
Expires: '0',
...extra
};
}
function jsonResponse(request, data, status = 200, extraHeaders = {}) {
return new Response(request.method === 'HEAD' ? null : JSON.stringify(data, null, 2), {
status,
headers: apiHeaders({
'Content-Type': 'application/json; charset=utf-8',
...extraHeaders
})
});
}
function errorResponse(request, status, message, extra = {}) {
return jsonResponse(request, { error: message, ...extra }, status);
}
function optionsResponse() {
return new Response(null, {
status: 204,
headers: corsHeaders(API_CACHE_CONTROL)
});
}
function isValidGalleryName(name) {
return typeof name === 'string' && GALLERY_NAME_PATTERN.test(name);
}
function isValidDevice(device) {
return DEVICE_NAMES.includes(device);
}
function parseDevice(value, fallback = 'all') {
if (!value) return fallback;
if (value === 'all' || isValidDevice(value)) return value;
return null;
}
function parseRandomQuery(searchParams) {
const rawType = searchParams.get('type');
const type = ['image', 'json', 'redirect'].includes(rawType) ? rawType : 'redirect';
const deviceValue = searchParams.get('device') || (isValidDevice(rawType) ? rawType : undefined);
return {
device: parseDevice(deviceValue, 'all'),
type
};
}
function parseLimit(value) {
const parsed = Number.parseInt(value, 10);
if (!Number.isFinite(parsed) || parsed < 1) return 100;
return Math.min(parsed, 100);
}
function safeDecode(value) {
try {
return decodeURIComponent(value);
} catch {
return null;
}
}
function extensionFromFilename(filename) {
const match = /\.([a-z0-9]+)$/i.exec(filename || '');
if (!match) return '';
const ext = match[1].toLowerCase();
return ext === 'jpeg' ? 'jpg' : ext;
}
function contentTypeFromFilename(filename) {
const ext = extensionFromFilename(filename);
if (ext === 'jpg') return 'image/jpeg';
if (ext === 'png') return 'image/png';
if (ext === 'webp') return 'image/webp';
if (ext === 'gif') return 'image/gif';
if (ext === 'avif') return 'image/avif';
return 'application/octet-stream';
}
function publicImagePath(env, gallery, device, filename) {
const basePath = normalizeBasePath(env.BASE_PATH);
return `${basePath}/images/${encodeURIComponent(gallery)}/${encodeURIComponent(device)}/${encodeURIComponent(filename)}`;
}
function buildImageKey(env, gallery, device, filename) {
const prefix = imageKeyPrefix(env);
const parts = [prefix, gallery, device, filename].filter(Boolean);
return parts.join('/');
}
function imageUrl(request, env, image) {
const baseUrl = normalizeBaseUrl(env.PUBLIC_BASE_URL, new URL(request.url).origin);
return `${baseUrl}${image.path}`;
}
function normalizeImage(env, image) {
if (!image || !image.gallery || !image.device || !image.filename) return null;
if (!isValidGalleryName(image.gallery) || !isValidDevice(image.device)) return null;
const type = image.type || extensionFromFilename(image.filename);
if (!IMAGE_EXTENSIONS.has(type === 'jpg' ? 'jpg' : type)) return null;
return {
key: image.key || buildImageKey(env, image.gallery, image.device, image.filename),
path: image.path || publicImagePath(env, image.gallery, image.device, image.filename),
gallery: image.gallery,
device: image.device,
filename: image.filename,
size: Number.isFinite(image.size) ? image.size : null,
width: Number.isFinite(image.width) ? image.width : null,
height: Number.isFinite(image.height) ? image.height : null,
type,
mtimeMs: Number.isFinite(image.mtimeMs) ? image.mtimeMs : 0
};
}
function computeGalleries(images, labels = {}) {
const byName = new Map();
for (const image of images) {
if (!byName.has(image.gallery)) {
byName.set(image.gallery, {
name: image.gallery,
label: labels[image.gallery]?.label || labels[image.gallery] || '',
total: 0,
pc: 0,
mobile: 0
});
}
const gallery = byName.get(image.gallery);
gallery.total += 1;
gallery[image.device] += 1;
}
return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
}
function normalizeManifest(env, rawManifest) {
const images = Array.isArray(rawManifest.images)
? rawManifest.images.map((image) => normalizeImage(env, image)).filter(Boolean)
: [];
images.sort((a, b) => b.mtimeMs - a.mtimeMs);
const galleries = Array.isArray(rawManifest.galleries) && rawManifest.galleries.length > 0
? rawManifest.galleries.map((gallery) => ({
name: gallery.name,
label: gallery.label || '',
total: Number.isFinite(gallery.total) ? gallery.total : 0,
pc: Number.isFinite(gallery.pc) ? gallery.pc : 0,
mobile: Number.isFinite(gallery.mobile) ? gallery.mobile : 0
})).filter((gallery) => isValidGalleryName(gallery.name))
: computeGalleries(images, rawManifest.galleryLabels || {});
return {
version: rawManifest.version || 1,
imageCount: Number.isFinite(rawManifest.imageCount) ? rawManifest.imageCount : images.length,
galleryCount: Number.isFinite(rawManifest.galleryCount) ? rawManifest.galleryCount : galleries.length,
galleries,
images,
generatedAt: rawManifest.generatedAt || new Date(0).toISOString()
};
}
async function loadManifest(env, force = false) {
if (!env.IMAGE_BUCKET) {
const error = new Error('R2 bucket binding IMAGE_BUCKET is not configured');
error.status = 500;
throw error;
}
const key = manifestKey(env);
const cacheSeconds = toInt(env.MANIFEST_CACHE_SECONDS, DEFAULT_MANIFEST_CACHE_SECONDS, 0);
const now = Date.now();
if (!force && cacheSeconds > 0 && cachedManifest && cachedManifestKey === key && now - cachedManifestAt < cacheSeconds * 1000) {
return cachedManifest;
}
const object = await env.IMAGE_BUCKET.get(key);
if (!object) {
const error = new Error(`Manifest not found in R2: ${key}`);
error.status = 500;
throw error;
}
let parsed;
try {
parsed = JSON.parse(await object.text());
} catch {
const error = new Error(`Manifest is not valid JSON: ${key}`);
error.status = 500;
throw error;
}
cachedManifest = normalizeManifest(env, parsed);
cachedManifestAt = now;
cachedManifestKey = key;
return cachedManifest;
}
function filterImages(manifest, { gallery, device }) {
let images = manifest.images;
if (gallery) images = images.filter((image) => image.gallery === gallery);
if (device && device !== 'all') images = images.filter((image) => image.device === device);
return images;
}
function randomIndex(length) {
if (length <= 1) return 0;
if (globalThis.crypto?.getRandomValues) {
const value = new Uint32Array(1);
globalThis.crypto.getRandomValues(value);
return value[0] % length;
}
return Math.floor(Math.random() * length);
}
function publicImageJson(request, env, image, total) {
return {
url: imageUrl(request, env, image),
gallery: image.gallery,
device: image.device,
filename: image.filename,
size: image.size,
width: image.width,
height: image.height,
type: image.type,
total
};
}
async function sendR2Image(request, env, image, cacheControl) {
const object = await env.IMAGE_BUCKET.get(image.key);
if (!object) {
return errorResponse(request, 404, '图片文件不存在于 R2', { key: image.key });
}
const headers = new Headers(corsHeaders(cacheControl));
if (typeof object.writeHttpMetadata === 'function') {
object.writeHttpMetadata(headers);
}
if (!headers.has('Content-Type')) {
headers.set('Content-Type', contentTypeFromFilename(image.filename));
}
if (object.httpEtag) {
headers.set('ETag', object.httpEtag);
}
if (object.size && !headers.has('Content-Length')) {
headers.set('Content-Length', String(object.size));
}
return new Response(request.method === 'HEAD' ? null : object.body, {
status: 200,
headers
});
}
function redirectResponse(request, location) {
return new Response(null, {
status: 302,
headers: apiHeaders({ Location: location })
});
}
async function randomHandler(request, env, galleryFromPath) {
const url = new URL(request.url);
const gallery = galleryFromPath || url.searchParams.get('gallery') || '';
const { device, type } = parseRandomQuery(url.searchParams);
if (gallery && !isValidGalleryName(gallery)) {
return errorResponse(request, 400, '非法图库名');
}
if (!device) {
return errorResponse(request, 400, 'device 只能是 pc、mobile 或 all');
}
const manifest = await loadManifest(env);
const images = filterImages(manifest, { gallery, device });
if (images.length === 0) {
return errorResponse(request, 404, '没有可用图片', { total: 0 });
}
const image = images[randomIndex(images.length)];
if (type === 'json') {
return jsonResponse(request, publicImageJson(request, env, image, images.length));
}
if (type === 'image') {
return sendR2Image(request, env, image, API_CACHE_CONTROL);
}
return redirectResponse(request, imageUrl(request, env, image));
}
async function galleriesHandler(request, env) {
const manifest = await loadManifest(env);
return jsonResponse(request, { galleries: manifest.galleries });
}
async function listHandler(request, env) {
const url = new URL(request.url);
const gallery = url.searchParams.get('gallery') || '';
const device = parseDevice(url.searchParams.get('device'), 'all');
if (gallery && !isValidGalleryName(gallery)) {
return errorResponse(request, 400, '非法图库名');
}
if (!device) {
return errorResponse(request, 400, 'device 只能是 pc、mobile 或 all');
}
const limit = parseLimit(url.searchParams.get('limit'));
const manifest = await loadManifest(env);
const images = filterImages(manifest, { gallery, device }).slice(0, limit);
return jsonResponse(request, {
total: images.length,
limit,
images: images.map((image) => {
const { total, ...rest } = publicImageJson(request, env, image, undefined);
return rest;
})
});
}
async function statsHandler(request, env) {
const manifest = await loadManifest(env);
return jsonResponse(request, {
imageCount: manifest.imageCount,
galleryCount: manifest.galleryCount,
galleries: manifest.galleries,
generatedAt: manifest.generatedAt
});
}
async function healthHandler(request, env) {
const manifest = await loadManifest(env);
return jsonResponse(request, {
status: 'ok',
imageCount: manifest.imageCount,
galleryCount: manifest.galleryCount,
timestamp: new Date().toISOString()
});
}
function stripBasePath(pathname, env) {
const basePath = normalizeBasePath(env.BASE_PATH);
if (pathname === basePath) return '/';
if (pathname.startsWith(`${basePath}/`)) return pathname.slice(basePath.length);
return null;
}
function staticImageFromPath(pathname, env) {
const prefix = '/images/';
if (!pathname.startsWith(prefix)) return null;
const parts = pathname.slice(prefix.length).split('/');
if (parts.length !== 3) return null;
const [rawGallery, rawDevice, rawFilename] = parts;
const gallery = safeDecode(rawGallery);
const device = safeDecode(rawDevice);
const filename = safeDecode(rawFilename);
if (!gallery || !device || !filename) return null;
if (!isValidGalleryName(gallery) || !isValidDevice(device)) return null;
if (filename.includes('/') || filename.includes('\\') || filename === '.' || filename === '..') return null;
const type = extensionFromFilename(filename);
if (!IMAGE_EXTENSIONS.has(type)) return null;
return {
key: buildImageKey(env, gallery, device, filename),
path: publicImagePath(env, gallery, device, filename),
gallery,
device,
filename,
type
};
}
async function handleRequest(request, env) {
if (request.method === 'OPTIONS') return optionsResponse();
if (!['GET', 'HEAD'].includes(request.method)) {
return errorResponse(request, 405, 'Method Not Allowed');
}
const url = new URL(request.url);
const pathname = stripBasePath(url.pathname, env);
if (pathname === null) {
return errorResponse(request, 404, 'Not Found');
}
if (pathname === '/' || pathname === '/health') {
return healthHandler(request, env);
}
if (pathname === '/api/random') {
return randomHandler(request, env);
}
if (pathname === '/api/galleries') {
return galleriesHandler(request, env);
}
if (pathname === '/api/list') {
return listHandler(request, env);
}
if (pathname === '/api/stats') {
return statsHandler(request, env);
}
if (pathname.startsWith('/api/')) {
const gallery = safeDecode(pathname.slice('/api/'.length));
if (!gallery || gallery.includes('/')) {
return errorResponse(request, 404, 'Not Found');
}
return randomHandler(request, env, gallery);
}
const staticImage = staticImageFromPath(pathname, env);
if (staticImage) {
const cacheSeconds = toInt(env.STATIC_CACHE_SECONDS, DEFAULT_STATIC_CACHE_SECONDS, 0);
return sendR2Image(request, env, staticImage, `public, max-age=${cacheSeconds}, immutable`);
}
return errorResponse(request, 404, 'Not Found');
}
export default {
async fetch(request, env) {
try {
return await handleRequest(request, env);
} catch (error) {
return errorResponse(request, error.status || 500, error.message || 'Internal Server Error');
}
}
};
export const __workerInternals = {
normalizeManifest,
parseRandomQuery,
staticImageFromPath,
stripBasePath
};