优化文件url显示

This commit is contained in:
MarSeventh
2024-09-13 13:17:07 +08:00
parent f8c8e6ff44
commit d72f3d4f4e
2 changed files with 41 additions and 15 deletions

View File

@@ -9,7 +9,7 @@ export async function onRequest(context) { // Contents of context object
next, // used for middleware or to fetch assets
data, // arbitrary space for passing data between middlewares
} = context;
const TgFileID = params.id.split('.')[0]; // 文件 ID
const url = new URL(request.url);
let Referer = request.headers.get('Referer')
if (Referer) {
@@ -39,14 +39,29 @@ export async function onRequest(context) { // Contents of context object
return new Response('Error: Image not found', { status: 404 });
}
if (imgRecord.metadata?.Channel === 'Telegram') {
if (isTgChannel(imgRecord)) {
targetUrl = `https://api.telegram.org/file/bot${env.TG_BOT_TOKEN}/${imgRecord.metadata.TgFilePath}`;
} else {
targetUrl = 'https://telegra.ph/' + url.pathname + url.search;
}
const fileName = imgRecord.metadata?.FileName || 'file';
const fileName = imgRecord.metadata?.FileName || params.id;
const encodedFileName = encodeURIComponent(fileName);
const fileType = imgRecord.metadata?.FileType || 'image/jpeg';
const fileType = imgRecord.metadata?.FileType || null;
//const TgFileID = params.id.split('.')[0]; // 文件 ID
let TgFileID = ''; // Tg的file_id
if (imgRecord.metadata?.Channel === 'Telegram') {
// id为file_id + ext
TgFileID = params.id.split('.')[0];
} else if (imgRecord.metadata?.Channel === 'TelegramNew') {
// id为unique_id + file_name
TgFileID = imgRecord.metadata?.TgFileId;
if (TgFileID === null) {
return new Response('Error: Failed to fetch image', { status: 500 });
}
} else {
// 旧版telegraph
}
const response = await getFileContent(request, imgRecord, TgFileID, params.id, env, url);
if (response === null) {
@@ -56,7 +71,9 @@ export async function onRequest(context) { // Contents of context object
try {
const headers = new Headers(response.headers);
headers.set('Content-Disposition', `inline; filename="${encodedFileName}"`);
headers.set('Content-Type', fileType);
if (fileType) {
headers.set('Content-Type', fileType);
}
const newRes = new Response(response.body, {
status: response.status,
statusText: response.statusText,
@@ -124,7 +141,7 @@ async function getFileContent(request, imgRecord, file_id, store_id, env, url, m
return response;
} else {
// 若为TG渠道更新TgFilePath
if (imgRecord.metadata?.Channel === 'Telegram') {
if (isTgChannel(imgRecord)) {
const filePath = await getFilePath(env, file_id);
if (filePath) {
imgRecord.metadata.TgFilePath = filePath;
@@ -132,7 +149,7 @@ async function getFileContent(request, imgRecord, file_id, store_id, env, url, m
metadata: imgRecord.metadata,
});
// 更新targetUrl
if (imgRecord.metadata?.Channel === 'Telegram') {
if (isTgChannel(imgRecord)) {
targetUrl = `https://api.telegram.org/file/bot${env.TG_BOT_TOKEN}/${imgRecord.metadata.TgFilePath}`;
} else {
targetUrl = 'https://telegra.ph/' + url.pathname + url.search;
@@ -169,3 +186,7 @@ async function getFilePath(env, file_id) {
return null;
}
}
function isTgChannel(imgRecord) {
return imgRecord.metadata?.Channel === 'Telegram' || imgRecord.metadata?.Channel === 'TelegramNew';
}

View File

@@ -142,24 +142,29 @@ export async function onRequestPost(context) { // Contents of context object
const clonedRes = await response.clone().json(); // 等待响应克隆和解析完成
const fileInfo = getFile(clonedRes);
const filePath = await getFilePath(env, fileInfo.file_id);
const time = new Date().getTime();
const id = fileInfo.file_id;
//const fullId = id + '.' + fileExt;
// 构建独一无二的 ID
const unique_index = time + Math.floor(Math.random() * 10000);
const fullId = fileName? unique_index + '_' + fileName : unique_index + '.' + fileExt;
const encodedFullId = encodeURIComponent(fullId);
// 若上传成功,将响应返回给客户端
if (response.ok) {
res = new Response(
JSON.stringify([{ 'src': `/file/${fileInfo.file_id}.${fileExt}` }]),
JSON.stringify([{ 'src': `/file/${fullId}` }]),
{
status: 200,
headers: { 'Content-Type': 'application/json' }
}
);
}
const time = new Date().getTime();
const id = fileInfo.file_id;
const fullId = id + '.' + fileExt;
const apikey = env.ModerateContentApiKey;
if (apikey == undefined || apikey == null || apikey == "") {
await env.img_url.put(fullId, "", {
metadata: { FileName: fileName, FileType: fileType, ListType: "None", Label: "None", TimeStamp: time, Channel: "Telegram", TgFilePath: filePath },
await env.img_url.put(encodedFullId, "", {
metadata: { FileName: fileName, FileType: fileType, ListType: "None", Label: "None", TimeStamp: time, Channel: "TelegramNew", TgFilePath: filePath, TgFileId: id },
});
} else {
try {
@@ -168,8 +173,8 @@ export async function onRequestPost(context) { // Contents of context object
throw new Error(`HTTP error! status: ${fetchResponse.status}`);
}
const moderate_data = await fetchResponse.json();
await env.img_url.put(fullId, "", {
metadata: { FileName: fileName, FileType: fileType, ListType: "None", Label: moderate_data.rating_label, TimeStamp: time, Channel: "Telegram", TgFilePath: filePath },
await env.img_url.put(encodedFullId, "", {
metadata: { FileName: fileName, FileType: fileType, ListType: "None", Label: moderate_data.rating_label, TimeStamp: time, Channel: "TelegramNew", TgFilePath: filePath, TgFileId: id },
});
} catch (error) {
console.error('Moderate Error:', error);