From 2748200c597f15d3915885fe96417e6af44be3dd Mon Sep 17 00:00:00 2001 From: MarSeventh <1193267292@qq.com> Date: Fri, 20 Dec 2024 19:18:55 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96random=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E7=9A=84=E8=AF=BB=E5=8F=96=E7=AD=96=E7=95=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + functions/api/randomFileList.js | 67 --------------------------------- functions/file/[id].js | 8 ++-- functions/login.js | 20 ---------- functions/random.js | 47 ++++++++++++++++++++++- 5 files changed, 50 insertions(+), 93 deletions(-) delete mode 100644 functions/api/randomFileList.js delete mode 100644 functions/login.js diff --git a/README.md b/README.md index fd8175e6..4be50228 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,7 @@ Add Features: - 管理端批量操作支持按照用户选择的顺序进行([#issue124](https://github.com/MarSeventh/CloudFlare-ImgBed/issues/124)) - `random`接口优化,减少KV操作次数,增加`content`参数,支持返回指定类型的文件 - 接入CloudFlare Cache API,提升 list 相关接口访问速度 +- 正常读取返回图片的CDN缓存时间从1年调整为7天,防止缓存清除不成功的情况下图片长时间内仍可以访问的问题 ## 2024.12.14 diff --git a/functions/api/randomFileList.js b/functions/api/randomFileList.js deleted file mode 100644 index b73574ac..00000000 --- a/functions/api/randomFileList.js +++ /dev/null @@ -1,67 +0,0 @@ -export async function onRequest(context) { - // Contents of context object - const { - request, // same as existing Worker API - env, // same as existing Worker API - params, // if filename includes [id] or [[path]] - waitUntil, // same as ctx.waitUntil in existing Worker API - next, // used for middleware or to fetch assets - data, // arbitrary space for passing data between middlewares - } = context; - - // 检查是否启用了随机图功能 - if (env.AllowRandom != "true") { - return new Response(JSON.stringify({ error: "Random is disabled" }), { status: 403 }); - } - - // 检查是否配置了KV数据库 - if (typeof env.img_url == "undefined" || env.img_url == null || env.img_url == "") { - return new Response('Error: Please configure KV database', { status: 500 }); - } - - // 看缓存中是否有记录,有则直接返回 - const cache = caches.default; - const cacheRes = await cache.match(request.url); - if (cacheRes) { - return cacheRes; - } - - // 缓存未命中 - let allRecords = []; - let cursor = null; - - do { - const records = await env.img_url.list({ - limit: 1000, - cursor, - }); - // 除去records中key以manage@开头的记录 - records.keys = records.keys.filter(item => !item.name.startsWith("manage@")); - // 保留metadata中fileType为image或video的记录 - records.keys = records.keys.filter(item => item.metadata?.FileType?.includes("image") || item.metadata?.FileType?.includes("video")); - allRecords.push(...records.keys); - cursor = records.cursor; - } while (cursor); - - // 仅保留记录的name和metadata中的FileType字段 - allRecords = allRecords.map(item => { - return { - name: item.name, - FileType: item.metadata?.FileType - } - }); - - // 返回所有记录 - const info = JSON.stringify(allRecords); - const res = new Response(info,{ - headers: { - "Content-Type": "application/json", - } - }); - - // 缓存结果,缓存时间为24小时 - await cache.put(request.url, res.clone(), { - expirationTtl: 24 * 60 * 60 - }); - return res; -} \ No newline at end of file diff --git a/functions/file/[id].js b/functions/file/[id].js index fd4b207b..8ef94018 100644 --- a/functions/file/[id].js +++ b/functions/file/[id].js @@ -76,11 +76,11 @@ export async function onRequest(context) { // Contents of context object if (fileType) { headers.set('Content-Type', fileType); } - // 根据Referer设置CDN缓存策略,如果是从/或/dashboard等访问,则仅允许浏览器缓存;否则设置为public,缓存时间为1年 + // 根据Referer设置CDN缓存策略,如果是从/或/dashboard等访问,则仅允许浏览器缓存;否则设置为public,缓存时间为7天 if (Referer && Referer.includes(url.origin)) { headers.set('Cache-Control', 'private, max-age=86400'); } else { - headers.set('Cache-Control', 'public, max-age=31536000'); + headers.set('Cache-Control', 'public, max-age=604800'); } // 返回图片 @@ -136,11 +136,11 @@ export async function onRequest(context) { // Contents of context object if (fileType) { headers.set('Content-Type', fileType); } - // 根据Referer设置CDN缓存策略,如果是从/或/dashboard等访问,则仅允许浏览器缓存;否则设置为public,缓存时间为1年 + // 根据Referer设置CDN缓存策略,如果是从/或/dashboard等访问,则仅允许浏览器缓存;否则设置为public,缓存时间为7天 if (Referer && Referer.includes(url.origin)) { headers.set('Cache-Control', 'private, max-age=86400'); } else { - headers.set('Cache-Control', 'public, max-age=31536000'); + headers.set('Cache-Control', 'public, max-age=604800'); } const newRes = new Response(response.body, { diff --git a/functions/login.js b/functions/login.js deleted file mode 100644 index b9f9413c..00000000 --- a/functions/login.js +++ /dev/null @@ -1,20 +0,0 @@ -export async function onRequestPost(context) { - // Contents of context object - const { - request, // same as existing Worker API - env, // same as existing Worker API - params, // if filename includes [id] or [[path]] - waitUntil, // same as ctx.waitUntil in existing Worker API - next, // used for middleware or to fetch assets - data, // arbitrary space for passing data between middlewares - } = context; - //从POST请求中获取authCode - const jsonRequest = await request.json(); - const authCode = jsonRequest.authCode; - //验证authCode - if (env.AUTH_CODE !== undefined && authCode !== env.AUTH_CODE) { - return new Response('Unauthorized', { status: 401 }) - } - //返回登录成功 - return new Response('Login success', { status: 200 }) -} \ No newline at end of file diff --git a/functions/random.js b/functions/random.js index 929e81d9..1fc8454a 100644 --- a/functions/random.js +++ b/functions/random.js @@ -29,8 +29,7 @@ export async function onRequest(context) { } // 调用randomFileList接口,读取KV数据库中的所有记录 - let allRecords = []; - allRecords = JSON.parse(await fetch(requestUrl.origin + '/api/randomFileList').then(res => res.text())); + let allRecords = await getRandomFileList(env, requestUrl); // 筛选出符合fileType要求的记录 allRecords = allRecords.filter(item => { return fileType.some(type => item.FileType.includes(type)) }); @@ -73,3 +72,47 @@ export async function onRequest(context) { } } } + +async function getRandomFileList(env, url) { + // 检查缓存中是否有记录,有则直接返回 + const cache = caches.default; + const cacheRes = await cache.match(`${url.origin}/api/randomFileList`); + if (cacheRes) { + return JSON.parse(await cacheRes.text()); + } + + let allRecords = []; + let cursor = null; + + do { + const records = await env.img_url.list({ + limit: 1000, + cursor, + }); + // 除去records中key以manage@开头的记录 + records.keys = records.keys.filter(item => !item.name.startsWith("manage@")); + // 保留metadata中fileType为image或video的记录 + records.keys = records.keys.filter(item => item.metadata?.FileType?.includes("image") || item.metadata?.FileType?.includes("video")); + allRecords.push(...records.keys); + cursor = records.cursor; + } while (cursor); + + // 仅保留记录的name和metadata中的FileType字段 + allRecords = allRecords.map(item => { + return { + name: item.name, + FileType: item.metadata?.FileType + } + }); + + // 缓存结果,缓存时间为24小时 + await cache.put(`${url.origin}/api/randomFileList`, new Response(JSON.stringify(allRecords), { + headers: { + "Content-Type": "application/json", + } + }), { + expirationTtl: 24 * 60 * 60 + }); + + return allRecords; +} \ No newline at end of file