Skip to content

Commit

Permalink
优化文件url显示
Browse files Browse the repository at this point in the history
  • Loading branch information
MarSeventh committed Sep 13, 2024
1 parent f8c8e6f commit d72f3d4
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 15 deletions.
35 changes: 28 additions & 7 deletions functions/file/[id].js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand All @@ -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,
Expand Down Expand Up @@ -124,15 +141,15 @@ 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;
await env.img_url.put(store_id, "", {
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;
Expand Down Expand Up @@ -169,3 +186,7 @@ async function getFilePath(env, file_id) {
return null;
}
}

function isTgChannel(imgRecord) {
return imgRecord.metadata?.Channel === 'Telegram' || imgRecord.metadata?.Channel === 'TelegramNew';
}
21 changes: 13 additions & 8 deletions functions/upload.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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);
Expand Down

0 comments on commit d72f3d4

Please sign in to comment.