-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy path_worker.js
More file actions
1988 lines (1860 loc) · 75.5 KB
/
Copy path_worker.js
File metadata and controls
1988 lines (1860 loc) · 75.5 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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 数据库初始化(首次)
let isDatabaseInitialized = false;
async function initDatabase(config) {
if (isDatabaseInitialized) return;
try {
await config.database
.prepare(
`
CREATE TABLE IF NOT EXISTS files (
url TEXT PRIMARY KEY,
webp_url TEXT UNIQUE,
fileId TEXT NOT NULL,
message_id INTEGER NOT NULL,
created_at INTEGER NOT NULL,
file_name TEXT,
webp_file_name TEXT,
file_size INTEGER,
mime_type TEXT
)
`,
)
.run();
isDatabaseInitialized = true;
} catch (error) {
console.error("[error] Database initialization failed:", error);
throw new Response("数据库初始化失败", { status: 500 });
}
}
// 导出函数
export default {
async fetch(request, env) {
// 环境变量配置
const config = {
domain: env.DOMAIN,
database: env.DATABASE,
username: env.USERNAME || "admin",
password: env.PASSWORD || "admin",
apiToken: env.API_TOKEN || "tgfile-admin",
enableAuth: env.ENABLE_AUTH === "false" ? false : true, // 是否开启身份认证,默认开启
webpEnabled: env.WEBP_ENABLED === "true" ? true : false, // 是否开启 WebP 转换,默认不开启
tgBotToken: env.TG_BOT_TOKEN,
tgChatId: env.TG_CHAT_ID,
tgApiBase: env.TG_API_BASE || "https://api.telegram.org", // 自建 TG Bot API 地址,未设置则回退官方
cookie: Number(env.COOKIE) || 7, // cookie有效期默认为 7
maxSizeMB: Number(env.MAX_SIZE_MB) || 20, // 上传单文件大小默认为20M
};
// 初始化数据库
await initDatabase(config);
const { pathname } = new URL(request.url);
// 统一认证检查
const publicRoutes = ["/config"];
const authRoutes = ["/", "/login"];
const isFileRequest = /\/([\p{L}\p{N}_.%-]+)\.[a-z0-9]+$/iu.test(pathname);
if (config.enableAuth) {
if (!publicRoutes.includes(pathname) && !authRoutes.includes(pathname) && !isFileRequest) {
if (!authenticate(request, config)) {
return Response.redirect(`${new URL(request.url).origin}/`, 302);
}
}
}
if (pathname === "/config") {
const safeConfig = { maxSizeMB: config.maxSizeMB };
return new Response(JSON.stringify(safeConfig), {
headers: { "Content-Type": "application/json" },
});
}
const routes = {
"/": () => handleAuthRequest(request, config),
"/login": () => handleLoginRequest(request, config),
"/upload": () => handleUploadRequest(request, config),
"/admin": () => handleAdminRequest(request, config),
"/delete": () => handleDeleteRequest(request, config),
"/search": () => handleSearchRequest(request, config),
};
const handler = routes[pathname];
if (handler) return await handler();
// 处理文件访问请求
return await handleFileRequest(request, config);
},
};
// 处理身份认证
function authenticate(request, config) {
// 检查 API Token (固定密钥认证)
const authHeader = request.headers.get("Authorization");
if (config.apiToken && authHeader) {
// 提取 Token 值,支持 Bearer 格式或直接 Token
const tokenValue = authHeader.startsWith("Bearer ") ? authHeader.substring(7).trim() : authHeader.trim();
if (tokenValue === config.apiToken) return true;
}
// 检查 Cookie (会话认证,仅在 API Token 认证失败时检查)
const cookies = request.headers.get("Cookie") || "";
const authToken = cookies.match(/auth_token=([^;]+)/); // 获取cookie中的auth_token
if (authToken) {
try {
const tokenData = JSON.parse(atob(authToken[1]));
const now = Date.now();
if (now > tokenData.expiration) return false; // 检查token是否过期
return tokenData.username === config.username; // 如果token有效,返回用户名是否匹配
} catch (error) {
console.error("[error] Authentication token parsing failed:", error);
return false;
}
}
return false; // 两种认证方式都失败
}
// 处理身份验证
async function handleAuthRequest(request, config) {
if (config.enableAuth) {
const isAuthenticated = authenticate(request, config);
if (!isAuthenticated) return handleLoginRequest(request, config); // 认证失败,跳转到登录页面
return handleUploadRequest(request, config); // 认证通过,跳转到上传页面
}
return handleUploadRequest(request, config); // 如果没有启用认证,直接跳转到上传页面
}
// 处理登录
async function handleLoginRequest(request, config) {
if (request.method === "POST") {
const { username, password } = await request.json();
if (username === config.username && password === config.password) {
// 登录成功,设置 cookie 有效期为 config.cookie 天
const expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + config.cookie);
const expirationTimestamp = expirationDate.getTime();
const tokenData = JSON.stringify({
username: config.username,
expiration: expirationTimestamp,
}); // 创建token数据,包含用户名和过期时间
const token = btoa(tokenData);
const cookie = `auth_token=${token}; Path=/; HttpOnly; Secure; Expires=${expirationDate.toUTCString()}`;
return new Response("登录成功", {
status: 200,
headers: {
"Set-Cookie": cookie,
"Content-Type": "text/plain",
},
});
}
return new Response("身份认证失败", { status: 401 });
}
const html = generateLoginPage();
return new Response(html, {
headers: { "Content-Type": "text/html;charset=UTF-8" },
});
}
// 文件大小计算函数
function formatSize(bytes) {
if (bytes === null || bytes === undefined || isNaN(bytes)) return "0.00 B";
let size = Number(bytes);
const units = ["B", "KB", "MB", "GB"];
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(2)} ${units[unitIndex]}`;
}
// 支持预览的文件类型
function getPreviewHtml(url, mimeType) {
const ext = (url.split(".").pop() || "").toLowerCase();
const isImage = ["jpg", "jpeg", "png", "gif", "webp", "svg", "icon"].includes(ext);
const isVideo = ["mp4", "webm"].includes(ext);
const isAudio = ["mp3", "wav", "ogg"].includes(ext);
if (isImage) return `<img src="${url}" alt="预览">`;
if (isVideo) return `<video src="${url}" controls></video>`;
if (isAudio) return `<audio src="${url}" controls></audio>`;
// 按 MIME 类型预览
if (mimeType === "application/pdf") {
return `<iframe src="${url}" style="width:100%;height:100%;border:none;background:rgba(255,255,255,0.3);border-radius:4px;"></iframe>`;
}
if (mimeType && mimeType.startsWith("text/")) {
return `<div class="text-preview" data-url="${url}"><i class="fas fa-file-alt" style="font-size:36px;color:#666"></i><div class="text-preview-hint">文本预览</div></div>`;
}
// 非预览文件类型图标
const iconMap = {
'pdf': 'fa-file-pdf', 'doc': 'fa-file-word', 'docx': 'fa-file-word',
'xls': 'fa-file-excel', 'xlsx': 'fa-file-excel',
'ppt': 'fa-file-powerpoint', 'pptx': 'fa-file-powerpoint',
'zip': 'fa-file-archive', 'rar': 'fa-file-archive', '7z': 'fa-file-archive',
'html': 'fa-file-code', 'css': 'fa-file-code', 'js': 'fa-file-code',
'json': 'fa-file-code', 'xml': 'fa-file-code', 'yaml': 'fa-file-code', 'yml': 'fa-file-code',
'txt': 'fa-file-alt', 'csv': 'fa-file-csv', 'log': 'fa-file-alt',
'md': 'fa-file-alt', 'sql': 'fa-file-code', 'sh': 'fa-file-code', 'bat': 'fa-file-code',
'mp4': 'fa-file-video', 'mkv': 'fa-file-video', 'avi': 'fa-file-video',
'mov': 'fa-file-video', 'wmv': 'fa-file-video',
'mp3': 'fa-file-audio', 'wav': 'fa-file-audio', 'flac': 'fa-file-audio', 'ogg': 'fa-file-audio',
'exe': 'fa-gear', 'dmg': 'fa-compact-disc', 'iso': 'fa-file-archive', 'apk': 'fa-android',
};
const icon = iconMap[ext] || 'fa-file-lines';
const colorMap = {
'fa-file-pdf': '#ff4d4f', 'fa-file-word': '#2b579a', 'fa-file-excel': '#217346',
'fa-file-powerpoint': '#d24726', 'fa-file-archive': '#fadb14', 'fa-file-code': '#e34f26',
'fa-file-alt': '#666', 'fa-file-csv': '#217346',
'fa-file-video': '#722ed1', 'fa-file-audio': '#eb2f96',
'fa-file-lines': '#e8b830', 'fa-gear': '#ff7043', 'fa-compact-disc': '#42a5f5', 'fa-android': '#66bb6a',
};
const color = colorMap[icon] || '#e8b830';
return `<i class="fas ${icon}" style="font-size:48px;color:${color};opacity:0.55"></i>`;
}
// 调用 TG getFile API 获取文件路径,并构造完整的下载 URL
async function getTelegramFileUrl(fileId, config) {
try {
const tgResponse = await fetch(`${config.tgApiBase}/bot${config.tgBotToken}/getFile?file_id=${fileId}`);
if (!tgResponse.ok) return null;
const tgData = await tgResponse.json();
const filePath = tgData.result?.file_path;
if (!filePath) return null;
// 构造完整的 Telegram 下载 URL
return `${config.tgApiBase}/file/bot${config.tgBotToken}/${filePath}`;
} catch (error) {
console.error("[error] Fetching Telegram file URL failed:", error);
return null;
}
}
// 在 Worker 内部对远程图片进行 webp 转换并返回响应(CF Images Worker API)
async function fetchWebpConverted(tgFileUrl) {
return await fetch(tgFileUrl, {
cf: { image: { format: "webp", quality: 80 } },
});
}
// 处理文件上传
async function handleUploadRequest(request, config) {
if (request.method === "GET") {
const html = generateUploadPage();
return new Response(html, {
headers: { "Content-Type": "text/html;charset=UTF-8" },
});
}
try {
const formData = await request.formData();
const file = formData.get("file");
if (!file) throw new Error("未找到文件");
if (file.size > config.maxSizeMB * 1024 * 1024) throw new Error(`文件超过${config.maxSizeMB}MB限制`);
const ext = (file.name.split(".").pop() || "").toLowerCase(); //获取文件扩展名
const [mainType] = file.type.split("/"); // 获取文件主类型
const typeMap = {
image: { method: "sendPhoto", field: "photo" },
video: { method: "sendVideo", field: "video" },
audio: { method: "sendAudio", field: "audio" },
}; // 定义类型映射
let { method = "sendDocument", field = "document" } = typeMap[mainType] || {};
if (["application", "text"].includes(mainType)) {
method = "sendDocument";
field = "document";
}
const tgFormData = new FormData();
tgFormData.append("chat_id", config.tgChatId);
tgFormData.append(field, file, file.name);
const tgResponse = await fetch(`${config.tgApiBase}/bot${config.tgBotToken}/${method}`, {
method: "POST",
body: tgFormData,
});
if (!tgResponse.ok) {
const errorText = await tgResponse.text();
throw new Error(`Telegram API调用失败 (状态码: ${tgResponse.status}): ${errorText}`);
}
const tgData = await tgResponse.json();
const result = tgData.result;
const messageId = result?.message_id;
const fileId =
result?.document?.file_id ||
result?.video?.file_id ||
result?.audio?.file_id ||
(result?.photo && result.photo[result.photo.length - 1]?.file_id);
if (!fileId) throw new Error("未获取到文件ID");
if (!messageId) throw new Error("未获取到tg消息ID");
const time = Date.now();
const timestamp = new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString();
const isConvertibleImage = ["image/jpeg", "image/png", "image/gif"].includes(file.type);
const useWebpMode = config.webpEnabled && isConvertibleImage;
const isImageType = mainType === "image"; // 广义图片(含 webp/svg 等不可转换的)
// 生成文件访问 URL
let originalUrl;
if (isImageType) {
originalUrl = `https://${config.domain}/${time}.${ext}`;
} else {
// 非图片文件使用原文件名,同名文件直接覆盖
const safeName = encodeURIComponent(file.name);
originalUrl = `https://${config.domain}/${safeName}`;
// 清除旧的 DB 记录和缓存,实现覆盖
const old = await config.database
.prepare("SELECT url, webp_url, fileId, message_id FROM files WHERE url = ?")
.bind(originalUrl)
.first();
if (old) {
await config.database.prepare("DELETE FROM files WHERE url = ?").bind(originalUrl).run();
// 尝试清理旧 TG 消息
try {
await fetch(`${config.tgApiBase}/bot${config.tgBotToken}/deleteMessage?chat_id=${config.tgChatId}&message_id=${old.message_id}`);
} catch {}
// 清除 CF 缓存
try {
const cache = caches.default;
await cache.delete(new Request(originalUrl));
if (old.webp_url) await cache.delete(new Request(old.webp_url));
} catch {}
}
}
const webpUrl = useWebpMode ? `https://${config.domain}/${time}.webp` : null;
const finalUrl = useWebpMode ? webpUrl : originalUrl;
const webpFileName = useWebpMode ? file.name.replace(/\.[^/.]+$/, ".webp") : null;
const finalFileName = useWebpMode ? webpFileName : file.name;
await config.database
.prepare(
`
INSERT INTO files (url, webp_url, fileId, message_id, created_at, file_name, webp_file_name, file_size, mime_type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
`,
)
.bind(originalUrl, webpUrl, fileId, messageId, timestamp, file.name, webpFileName, file.size, file.type)
.run();
// 方案A优化版:webp 预转换,测量准确大小并预热缓存
let webpSize = file.size;
if (useWebpMode) {
try {
const tgFileUrl = await getTelegramFileUrl(fileId, config);
if (tgFileUrl) {
const webpResponse = await fetchWebpConverted(tgFileUrl);
if (webpResponse.ok) {
// CF Images 响应不携带 Content-Length,改用读取响应体字节数
const webpBuffer = await webpResponse.arrayBuffer();
webpSize = webpBuffer.byteLength;
// 更新数据库为 webp 实际大小
await config.database
.prepare("UPDATE files SET file_size = ? WHERE url = ?")
.bind(webpSize, originalUrl)
.run();
// 将转换结果写入 CF Cache,首次访问零消耗
const cache = caches.default;
const cacheResponse = new Response(webpBuffer, {
headers: {
"Content-Type": webpResponse.headers.get("Content-Type") || "image/webp",
"Cache-Control": "public, max-age=31536000",
"Access-Control-Allow-Origin": "*",
"Content-Disposition": "inline; filename*=UTF-8''" + encodeURIComponent(webpFileName),
},
});
await cache.put(new Request(webpUrl), cacheResponse);
}
}
} catch (e) {
console.error("[warn] WebP pre-conversion failed, fallback to original size:", e);
}
}
return new Response(JSON.stringify({ status: 1, msg: "✔ 上传成功", url: finalUrl, file: finalFileName, webpSize }), {
status: 200,
headers: { "Content-Type": "application/json" },
});
} catch (error) {
let statusCode = 500;
if (error.message.includes(`文件超过${config.maxSizeMB}MB限制`)) {
statusCode = 400; // 客户端错误:文件大小超限
} else if (error.message.includes("Telegram参数配置错误")) {
statusCode = 502; // 网关错误:与Telegram通信失败
} else if (error.message.includes("未获取到文件ID") || error.message.includes("未获取到tg消息ID")) {
statusCode = 500; // 服务器内部错误:Telegram返回数据异常
} else if (error instanceof TypeError && error.message.includes("Failed to fetch")) {
statusCode = 504; // 网络超时或断网
}
console.error(`[Error] ${error.message}`, error);
return new Response(JSON.stringify({ status: 0, msg: "✘ 上传失败", error: error.message }), {
status: statusCode,
headers: { "Content-Type": "application/json" },
});
}
}
// 处理文件管理和预览
async function handleAdminRequest(request, config) {
try {
const files = await config.database
.prepare(
`SELECT url, webp_url, fileId, message_id, created_at, file_name, webp_file_name, file_size, mime_type
FROM files
ORDER BY created_at DESC`,
)
.all();
const fileList = files.results || [];
const fileCards = fileList
.map((file) => {
const createdAt = new Date(file.created_at).toISOString().replace("T", " ").split(".")[0];
const displayFileSize = formatSize(file.file_size);
let displayUrl = file.url;
let displayFileName = file.file_name;
const isWebpMode = config.webpEnabled && file.webp_url;
if (isWebpMode) {
displayUrl = file.webp_url;
displayFileName = file.webp_file_name;
}
return `
<div class="file-card" data-url="${file.url}">
<div class="file-preview">
${getPreviewHtml(displayUrl, file.mime_type)}
</div>
<div class="file-info">
<div>${displayFileName}</div>
<div>${displayFileSize}</div>
<div>${createdAt}</div>
</div>
<div class="file-actions">
<button class="btn btn-copy" onclick="showQRCode('${displayUrl}')"><i class="fas fa-share"></i> 分享</button>
<a class="btn btn-down" href="${displayUrl}" download="${displayFileName}" target="_blank"><i class="fas fa-download"></i> 下载</a>
<button class="btn btn-delete" onclick="deleteFile('${file.url}')"><i class="fas fa-trash"></i> 删除</button>
</div>
</div>
`;
})
.join("");
// 二维码分享元素
const qrModal = `
<div id="qrModal" class="qr-modal">
<div class="qr-content">
<div id="qrcode"></div>
<div class="qr-buttons">
<button class="qr-copy" onclick="handleCopyUrl()"><i class="fas fa-copy"></i> 复制链接</button>
<button class="qr-close" onclick="closeQRModal()"><i class="fas fa-times"></i> 关闭</button>
</div>
</div>
</div>
`;
const html = generateAdminPage(fileCards, qrModal);
return new Response(html, {
headers: { "Content-Type": "text/html;charset=UTF-8" },
});
} catch (error) {
console.error("[Error]:", error);
return new Response(`服务器内部错误: ${error.message}`, {
status: 500,
headers: { "Content-Type": "text/html" },
});
}
}
// 处理文件搜索
async function handleSearchRequest(request, config) {
try {
const { query } = await request.json();
const searchPattern = `%${query}%`;
const files = await config.database
.prepare(
`SELECT url, webp_url, fileId, message_id, created_at, file_name, webp_file_name, file_size, mime_type
FROM files
WHERE file_name LIKE ? ESCAPE '!'
OR webp_file_name LIKE ? ESCAPE '!'
COLLATE NOCASE
ORDER BY created_at DESC`,
)
.bind(searchPattern, searchPattern)
.all();
return new Response(JSON.stringify({ files: files.results || [] }), {
headers: { "Content-Type": "application/json" },
});
} catch (error) {
console.error("[error] Search request failed:", error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
// 获取文件并缓存
async function handleFileRequest(request, config) {
const cache = caches.default;
const cacheKey = request;
const { pathname } = new URL(request.url);
const isWebpRequest = pathname.toLowerCase().endsWith(".webp");
const lookupColumn = config.webpEnabled && isWebpRequest ? "webp_url" : "url";
const lookupValue = request.url;
try {
// 尝试从缓存中获取
const cachedResponse = await cache.match(cacheKey);
if (cachedResponse) return cachedResponse;
// 从数据库查询文件
const file = await config.database
.prepare(
`SELECT url, webp_url, fileId, message_id, created_at, file_name, webp_file_name, file_size, mime_type
FROM files WHERE ${lookupColumn} = ?`,
)
.bind(lookupValue)
.first();
if (!file) {
return new Response("文件不存在", {
status: 404,
headers: { "Content-Type": "text/plain;charset=UTF-8" },
});
}
// 重定向条件:WebP 启用 AND 请求的是原始 URL, AND 数据库中有 webp_url 记录
if (config.webpEnabled && !isWebpRequest && file.webp_url) {
return Response.redirect(file.webp_url, 301);
}
// 获取 Telegram 文件
const fileUrl = await getTelegramFileUrl(file.fileId, config);
if (!fileUrl) {
return new Response("文件路径无效或获取失败", {
status: 404,
headers: { "Content-Type": "text/plain;charset=UTF-8" },
});
}
let fileResponse;
let contentType = file.mime_type;
const isConvertibleImage = ["image/jpeg", "image/png", "image/gif"].includes(file.mime_type);
const shouldConvert = config.webpEnabled && isWebpRequest && isConvertibleImage;
if (shouldConvert) {
fileResponse = await fetchWebpConverted(fileUrl);
if (fileResponse.ok) contentType = fileResponse.headers.get("Content-Type") || "image/webp";
}
if (!fileResponse || !fileResponse.ok) fileResponse = await fetch(fileUrl);
if (!fileResponse.ok) {
return new Response("下载文件失败", {
status: 500,
headers: { "Content-Type": "text/plain;charset=UTF-8" },
});
}
// 创建响应并缓存 (使用新的 contentType)
let finalFileName = file.file_name;
if (isWebpRequest) finalFileName = finalFileName.replace(/\.[^/.]+$/, ".webp");
const response = new Response(fileResponse.body, {
headers: {
"Content-Type": contentType,
"Cache-Control": "public, max-age=31536000",
"X-Content-Type-Options": "nosniff",
"Access-Control-Allow-Origin": "*",
"Content-Disposition": `inline; filename*=UTF-8''${encodeURIComponent(finalFileName)}`,
},
});
await cache.put(cacheKey, response.clone());
return response;
} catch (error) {
console.error("[error] File request failed:", error);
return new Response("服务器内部错误", {
status: 500,
headers: { "Content-Type": "text/plain;charset=UTF-8" },
});
}
}
// 处理文件删除
async function handleDeleteRequest(request, config) {
try {
const { url } = await request.json();
if (!url || typeof url !== "string") {
return new Response(JSON.stringify({ error: "无效的URL" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
const file = await config.database
.prepare("SELECT fileId, message_id FROM files WHERE url = ? OR webp_url = ?")
.bind(url, url)
.first();
if (!file) {
return new Response(JSON.stringify({ error: "文件不存在" }), {
status: 404,
headers: { "Content-Type": "application/json" },
});
}
const deleteError = await (async () => {
try {
const deleteResponse = await fetch(
`${config.tgApiBase}/bot${config.tgBotToken}/deleteMessage?chat_id=${config.tgChatId}&message_id=${file.message_id}`,
);
if (!deleteResponse.ok) {
const errorData = await deleteResponse.json();
console.error("[error] Telegram message delete failed:", errorData);
if (errorData.description && errorData.description.includes("message to delete not found")) {
return "Telegram消息已不存在,但已从数据库移除";
}
throw new Error(`Telegram 消息删除失败: ${errorData.description}`);
}
return null;
} catch (error) {
return error.message;
}
})();
// 删除数据库表数据,即使Telegram删除失败也会删除数据库记录
await config.database.prepare("DELETE FROM files WHERE url = ? OR webp_url = ?").bind(url, url).run();
return new Response(
JSON.stringify({
success: true,
message: deleteError ? `文件已从数据库删除,但Telegram消息删除失败: ${deleteError}` : "文件删除成功",
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
} catch (error) {
console.error("[error] File delete request failed:", error);
return new Response(JSON.stringify({ error: error.message }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
}
function headLinks() {
return `
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Telegram文件存储与分享平台">
<link rel="shortcut icon" href="https://pan.811520.xyz/2025-02/1739241502-tgfile-favicon.ico" type="image/x-icon">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
`;
}
// HTML版权页
function copyright() {
return `
<p>
<span><i class="fas fa-copyright"></i> 2025 Copyright by Yutian81</span><span>|</span>
<a href="https://github.com/yutian81/CF-tgfile" target="_blank">
<i class="fab fa-github"></i> GitHub Repo</a><span>|</span>
<a href="https://blog.811520.xyz/" target="_blank">
<i class="fas fa-blog"></i> QingYun Blog</a>
</p>
`;
}
// 登录页面生成函数 /login
function generateLoginPage() {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
${headLinks()}
<title>登录</title>
<style>
body {
position: relative;
min-height: 100vh;
margin: 0;
background: #f5f5f5;
background-size: cover;
background-position: center;
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
box-sizing: border-box;
}
.login-container {
background: rgba(255, 255, 255, 0.3);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
padding: 30px 30px 20px 30px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
width: 100%;
max-width: 400px;
z-index: 1;
}
.form-group { margin-bottom: 1rem; }
.input-wrapper { position: relative; display: block; }
.input-wrapper i { position: absolute; left: 12px; top: 50%; transform: translateY(-50%); color: #666; pointer-events: none; }
input {
width: 100%;
padding: 0.75rem 0.75rem 0.75rem 35px;
border: 1px solid rgba(0,0,0,0.1);
border-radius: 8px;
font-size: 1rem;
box-sizing: border-box;
background: rgba(255, 255, 255, 0.6);
color: #333;
outline: none;
}
input:focus { background: rgba(255, 255, 255, 0.5); border-color: #007bff; box-shadow: 0 0 5px rgba(0, 98, 255, 0.5); }
button {
width: 100%;
padding: 0.75rem;
background: #007bff;
color: white;
border: none;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
margin-bottom: 10px;
transition: background 0.3s ease;
}
button:hover { background: #0056b3; }
button:disabled { background: #ccc; cursor: not-allowed; }
.error {
color: #dc3545;
margin-top: 1rem;
font-size: 14px;
display: none;
text-align: center;
}
footer {
position: absolute;
margin-bottom: 30px;
bottom: 0;
left: 0;
width: 100%;
text-align: center;
font-size: 0.85rem;
padding: 10px 0;
background: transparent;
}
footer p {
color: #585858;
display: flex;
justify-content: center;
align-items: center;
flex-wrap: wrap;
gap: 8px;
margin: 0;
}
footer a { color: #585858; text-decoration: none; }
footer a:hover { color: #007BFF; transition: color 0.3s ease; }
/* 通用模态框(毛玻璃) */
.modal-overlay {
position: fixed; inset: 0; z-index: 9999;
background: rgba(0, 0, 0, 0.35);
backdrop-filter: blur(6px); -webkit-backdrop-filter: blur(6px);
display: none; align-items: center; justify-content: center;
opacity: 0; transition: opacity 0.25s ease;
}
.modal-overlay.show { display: flex; opacity: 1; }
.modal-box {
background: rgba(255, 255, 255, 0.65);
backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px);
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 16px;
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.2);
padding: 28px 32px; max-width: 90vw; width: 360px;
text-align: center; color: #222;
transform: scale(0.92); transition: transform 0.25s ease;
}
.modal-overlay.show .modal-box { transform: scale(1); }
.modal-icon { font-size: 42px; margin-bottom: 12px; }
.modal-icon.success { color: #28a745; }
.modal-icon.error { color: #dc3545; }
.modal-icon.warning { color: #ffc107; }
.modal-title { font-size: 18px; font-weight: 600; margin-bottom: 10px; }
.modal-msg { font-size: 14px; line-height: 1.6; margin-bottom: 20px; color: #444; word-break: break-word; }
.modal-btns { display: flex; gap: 10px; justify-content: center; }
.modal-btns button {
padding: 8px 22px; border: none; border-radius: 8px;
font-size: 14px; cursor: pointer; transition: all 0.2s;
}
.modal-btn { background: #007bff; color: #fff; }
.modal-btn:hover { background: #0056b3; }
.modal-btn.secondary { background: rgba(0,0,0,0.08); color: #444; }
.modal-btn.secondary:hover { background: rgba(0,0,0,0.15); }
.modal-btn.danger { background: #dc3545; color: #fff; }
.modal-btn.danger:hover { background: #c82333; }
</style>
</head>
<body>
<div class="login-container">
<h2 style="text-align: center; margin: 0 0 20px 0;"><i class="fab fa-telegram"></i> TG Files 文件管理</h2>
<form id="loginForm">
<div class="form-group">
<div class="input-wrapper">
<i class="fas fa-user"></i>
<input type="text" id="username" placeholder="用户名" required autocomplete="username">
</div>
</div>
<div class="form-group">
<div class="input-wrapper">
<i class="fas fa-key"></i>
<input type="password" id="password" placeholder="密码" required autocomplete="current-password">
</div>
</div>
<button type="submit" id="loginBtn"><i class="fas fa-right-to-bracket"></i> 登录</button>
<div id="error" class="error"></div>
</form>
</div>
<footer>
${copyright()}
</footer>
<script>
async function setBingBackground() {
try {
document.body.style.backgroundImage = \`url('https://bing.by.ccwu.cc/api/daily')\`;
} catch (error) {
console.error('获取背景图失败:', error);
}
}
setBingBackground();
setInterval(setBingBackground, 3600000);
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const loginBtn = document.getElementById('loginBtn');
const errorEl = document.getElementById('error');
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value.trim();
// 状态重置:先禁用按钮再发请求
loginBtn.disabled = true;
loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 登录中...';
errorEl.style.display = 'none';
try {
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
if (response.ok) {
window.location.href = '/upload';
} else {
errorEl.style.display = 'block';
errorEl.innerHTML = '<i class="fas fa-ban"></i> 用户名或密码错误';
// 失败时恢复按钮
loginBtn.disabled = false;
loginBtn.innerHTML = '<i class="fas fa-right-to-bracket"></i> 登录';
}
} catch (err) {
console.error('登录请求失败:', err);
errorEl.style.display = 'block';
errorEl.innerHTML = '<i class="fas fa-clock"></i> 网络错误,请稍后再试';
// 异常时恢复按钮
loginBtn.disabled = false;
loginBtn.innerHTML = '<i class="fas fa-right-to-bracket"></i> 登录';
}
});
// ---------- 通用模态框 ----------
function showModal({icon='success', title='', msg='', btns=null}) {
return new Promise(resolve => {
let overlay = document.getElementById('globalModal');
if (!overlay) {
overlay = document.createElement('div');
overlay.id = 'globalModal';
overlay.className = 'modal-overlay';
overlay.innerHTML = '<div class="modal-box"><div class="modal-icon"></div><div class="modal-title"></div><div class="modal-msg"></div><div class="modal-btns"></div></div>';
document.body.appendChild(overlay);
overlay.addEventListener('click', e => { if (e.target === overlay) { overlay.classList.remove('show'); resolve(false); } });
}
const iconMap = { success:'fa-circle-check', error:'fa-circle-xmark', warning:'fa-triangle-exclamation', info:'fa-circle-info' };
overlay.querySelector('.modal-icon').className = 'modal-icon ' + icon + ' fas ' + (iconMap[icon]||'fa-circle-info');
overlay.querySelector('.modal-title').textContent = title;
overlay.querySelector('.modal-msg').textContent = msg;
const btnBox = overlay.querySelector('.modal-btns'); btnBox.innerHTML = '';
const list = btns || [{text:'确定', type:'primary'}];
list.forEach(b => {
const btn = document.createElement('button');
btn.textContent = b.text;
btn.className = 'modal-btn' + (b.type==='secondary' ? ' secondary' : (b.type==='danger' ? ' danger' : ''));
btn.onclick = () => { overlay.classList.remove('show'); resolve(b.value !== undefined ? b.value : true); };
btnBox.appendChild(btn);
});
overlay.classList.add('show');
});
}
async function showAlert(msg, title='提示', icon='info') { await showModal({icon, title, msg}); }
async function showConfirm(msg, title='确认', icon='warning') {
return await showModal({icon, title, msg, btns:[{text:'取消', type:'secondary', value:false},{text:'确定', type:'primary', value:true}]});
}
</script>
</body>
</html>`;
}
// 生成文件上传页面 /upload
function generateUploadPage() {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
${headLinks()}
<title>文件上传</title>
<style>
body {
font-family: Arial, sans-serif;
transition: background-image 1s ease-in-out;
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background: #f5f5f5;
background-size: cover;
background-position: center;
margin: 0;
}
.container {
width: 95%;
max-width: 800px;
background: rgba(255, 255, 255, 0.3);
backdrop-filter: blur(10px);
-webkit-backdrop-filter: blur(10px);
padding: 30px;
margin: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
box-sizing: border-box;
}
.header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px; }
.admin-link {
background: #007BFF;
padding: 5px 10px;
border: none;
border-radius: 8px;
text-decoration: none;
color: #ffffff;
display: inline-block;
margin-left: auto;
}
.admin-link:hover { background: #0056b3; text-decoration: none; transition: color 0.3s ease; }
.upload-area {
border: 2px dashed rgba(0, 0, 0, 0.15);
padding: 8px;
height: 80px;
display: flex;
align-items: center;
justify-content: center;
text-align: center;
margin: 0 auto;
border-radius: 8px;
transition: all 0.3s;
box-sizing: border-box;
}
.upload-area p { line-height: 2; }
.upload-area.dragover { border-color: #007bff; background: #f8f9fa; }
.preview-area { margin-top: 20px; display: none; overflow-y: auto; min-height: 80px; max-height: 180px; padding-right: 6px; }
.preview-item {
display: flex;
flex-direction: row;
align-items: center;
position: relative;
padding: 10px;
border: 1px solid rgba(0, 0, 0, 0.15);
margin-bottom: 8px;
border-radius: 8px;
box-sizing: border-box;
}
.preview-item img {
width: 100px;
height: 60px;
object-fit: cover;
margin-right: 15px;
border-radius: 4px;
flex-shrink: 0;
}
.preview-item .info { flex-grow: 1; min-width: 0; overflow: hidden; }
.info div:first-child {
font-weight: bold;
white-space: nowrap;
overflow: hidden;
word-break: break-all;
white-space: normal;
font-size: 14px;
}
.progress-bar {
height: 20px;