-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.html
1175 lines (1106 loc) · 34.7 KB
/
index.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>D-File</title>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/1.1.3/axios.min.js"></script>
<script src="https://unpkg.com/js-base64"></script>
<link
rel="shortcut icon"
type="image/x-icon"
href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAMxJREFUOE+t06FuAkEQxvH/FxpegUoeovXUoOobJLapRDaw2T1b21qwoNGUB8BW45jwDmQJENIj3F2vd0wyZjL7m2QmK2qGar7nCLSGsadIF2hfgOLTvGZFQ47A/Xt0iFFG45jI5Kp+x9acfg71v4Dc4YKHTdDqDHSAQ2ZFzKkvLdH3LyDegGYqixcsvHkt0sDiXxcRz+Y1rw7AiwVN6wB9CxpXB8SreX1VByIDS/RRBxhaonACXGyzYwo8lrzEmgZP5rS+zWcqOTWzbQ96PEURUT++WAAAAABJRU5ErkJggg=="
/>
<!-- <script src="https://cdn.bootcdn.net/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script> -->
<!-- <script src="https://cdn.jsdelivr.net/npm/[email protected]/base64.min.js"></script> -->
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
padding: 20px 0 10px;
background: #000;
color: #fff;
}
body {
font-size: 16px;
max-width: 80%;
margin: 0 auto;
}
h2 {
margin-bottom: 10px;
}
.back {
display: inline-block;
border: 1px solid #ff9000;
padding: 4px 12px;
font-size: 15px;
font-weight: normal;
cursor: pointer;
margin-left: 20px;
margin-top: 0;
background: #ff9000;
color: #000;
border-radius: 3px;
transition: all 0.2s;
}
.back:hover {
background: #000;
color: #ff9000;
}
input.back {
cursor: auto;
background: #1b1b1b;
border: 1px solid #333;
color: #fff;
}
.ftr {
float: right;
}
.file_list li {
line-height: 40px;
border-bottom: 1px solid #333;
display: flex;
align-items: center;
padding: 6px 0;
}
.w50 .file_list li {
float: left;
width: 31%;
margin-right: 2%;
}
.w50 .file_list li span.sha {
display: none;
}
.file_list li:before {
content: "其他";
background: #1b1b1b;
color: #fff;
min-width: 40px;
padding: 0 10px;
line-height: 26px;
height: 26px;
font-size: 13px;
margin-right: 8px;
text-align: center;
border-radius: 3px;
}
.file_list li.dir:before {
content: "文件夹";
background: #ff9000;
color: #000;
}
.file_list li.img:before {
content: "图片";
background: #ff9000;
color: #000;
}
.file_list li.video:before {
content: "视频";
background: #ff9000;
color: #000;
}
.file_list li.music:before {
content: "音频";
background: #ff9000;
color: #000;
}
.file_list li.code:before {
content: "代码";
background: #ff9000;
color: #000;
}
.file_list li.zip:before {
content: "压缩包";
background: #ff9000;
color: #000;
}
.file_list li.doc:before {
content: "Word";
background: #ff9000;
color: #000;
}
.file_list li.xls:before {
content: "Excel";
background: #ff9000;
color: #000;
}
.file_list li.ppt:before {
content: "PPT";
background: #ff9000;
color: #000;
}
.file_list li.pdf:before {
content: "PDF";
background: #ff9000;
color: #000;
}
.file_list li.txt:before {
content: "文本";
background: #ff9000;
color: #000;
}
.file_list li img {
margin-right: 6px;
display: inline-block;
vertical-align: middle;
}
.file_list li a {
color: #fff;
text-decoration: none;
flex: 1;
width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.file_list li.dir a {
text-decoration: underline;
color: #ff9000;
font-weight: bold;
}
.file_list li.dir .del {
visibility: hidden;
pointer-events: none;
}
.file_list li span {
color: #999;
font-size: 14px;
}
.file_list li span.sha {
min-width: 350px;
display: inline-block;
}
.file_list li span.size {
width: 80px;
display: inline-block;
}
.file_list li i {
border: 1px solid #ff9000;
padding: 4px 12px;
font-size: 14px;
font-style: normal;
cursor: pointer;
margin-left: 10px;
line-height: 20px;
background: #ff9000;
color: #000;
border-radius: 3px;
transition: all 0.2s;
}
.file_list li i:hover {
background: #000;
color: #ff9000;
}
.file-img {
width: 60px;
max-height: 60px;
}
li {
list-style-type: none;
}
@media screen and (max-width: 700px) {
body {
max-width: 95%;
padding: 0 10px;
}
.file_list li span {
display: none !important;
}
.back.ftr {
display: none;
}
input#search {
display: inline-block;
margin: 10px 0 0;
min-width: 200px;
}
button {
margin-top: 6px;
}
.file_list li {
width: 100% !important;
margin-right: 0 !important;
float: none !important;
}
h2 {
font-size: 16px;
}
.back {
padding: 2px 8px;
font-size: 13px;
margin-left: 10px;
}
#rootdm {
min-width: 200px;
width: 100%;
margin-bottom: 10px;
}
#btn-wrap {
display: flex;
flex-wrap: wrap;
gap: 5px;
margin-top: 5px;
}
#btn-wrap button {
margin: 0;
font-size: 13px;
padding: 2px 8px;
}
}
input {
background: #1b1b1b;
outline: none;
line-height: 26px;
border: 1px solid #333;
padding: 0 10px;
display: inline-block;
min-width: 280px;
margin-top: 6px;
color: #fff;
border-radius: 3px;
}
button {
outline: none;
background: #1b1b1b;
border: 1px solid #333;
display: inline-block;
margin-left: 10px;
line-height: 18px;
padding: 4px 10px;
cursor: pointer;
color: #fff;
border-radius: 3px;
transition: all 0.2s;
}
button:hover {
border-color: #ff9000;
}
button span {
color: #ff9000;
display: block;
}
#file {
display: none;
}
h4 {
overflow: hidden;
margin-bottom: 20px;
}
h2 {
padding: 10px 0;
margin-bottom: 10px;
border-bottom: 1px solid #333;
overflow: hidden;
}
.tip {
color: #999;
font-size: 12px;
margin-left: 20px;
}
i {
font-style: normal;
}
.hide {
display: none !important;
}
#loading {
position: fixed;
width: 100vw;
height: 100vh;
left: 0;
top: 0;
background: rgba(0, 0, 0, 0.8);
display: flex;
align-items: center;
justify-content: center;
color: #ff9000;
z-index: 9;
font-size: 20px;
}
.drag-hint {
background: rgba(255, 144, 0, 0.1);
padding: 8px;
border-radius: 4px;
margin-bottom: 15px;
border: 1px dashed #ff9000;
color: #ff9000;
text-align: center;
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { opacity: 0.6; }
50% { opacity: 1; }
100% { opacity: 0.6; }
}
#drop-zone {
transition: all 0.3s ease;
position: relative;
}
#drop-zone.dragover {
background: rgba(255, 144, 0, 0.1) !important;
}
#drop-zone.dragover:after {
content: '可以拖放多个文件到这里上传';
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 24px;
color: #ff9000;
pointer-events: none;
}
.empty-folder-hint {
text-align: center;
padding: 40px 20px;
border: 2px dashed #ff9000;
border-radius: 8px;
margin: 20px 0;
background: rgba(255, 144, 0, 0.05);
transition: all 0.3s ease;
}
.empty-folder-hint:hover {
background: rgba(255, 144, 0, 0.1);
}
.empty-folder-hint i {
font-size: 40px;
color: #ff9000;
margin-bottom: 15px;
display: block;
}
@media screen and (max-width: 700px) {
#drop-zone.dragover:after {
font-size: 16px;
}
}
#btn-wrap {
display: flex;
flex-wrap: wrap;
gap: 8px;
padding: 10px;
max-width: 100%;
margin-top: 10px;
}
#btn-wrap button {
display: inline-flex;
justify-content: space-between;
align-items: center;
padding: 6px 12px;
border: 1px solid #30363d;
border-radius: 6px;
background: #21262d;
color: #c9d1d9;
cursor: pointer;
transition: all 0.2s ease;
min-width: 120px;
max-width: 180px;
flex: 0 1 auto;
}
#btn-wrap button:hover {
background: #30363d;
transform: translateY(-2px);
}
#btn-wrap button.active {
border-color: #58a6ff;
background: #1f6feb;
}
.speed-info {
font-size: 12px;
color: #8b949e;
white-space: nowrap;
padding-left: 8px;
border-left: 1px solid #30363d;
}
@media (max-width: 768px) {
#btn-wrap {
gap: 6px;
padding: 8px 0;
}
#btn-wrap button {
min-width: auto;
padding: 4px 8px;
font-size: 12px;
}
.cdn-name {
font-size: 12px;
}
.speed-info {
font-size: 11px;
padding-left: 6px;
}
}
.cdn-name {
font-size: 13px;
margin-right: 8px;
white-space: nowrap;
}
h4 {
display: flex;
flex-direction: column;
gap: 10px;
margin-bottom: 20px;
}
#rootdm {
width: 100%;
max-width: 100%;
margin: 0;
}
#btn-wrap {
flex: 2;
min-width: 300px;
}
</style>
</head>
<body>
<div id="drop-zone" style="min-height: calc(100vh - 200px); position: relative;" ondrop="handleDrop(event)" ondragover="handleDragOver(event)" ondragleave="handleDragLeave(event)">
<div class="drag-hint">
💡 支持拖拽上传:直接将文件拖放到页面任意位置即可上传
</div>
<p style="margin: 0">
版本号: 20250101-1
<span class="tip">测试延迟请在根目录上传<b>init.jpg</b>(50kb以内)</span>
</p>
<h4>
根域名: <input type="text" value="" id="rootdm" />
<div style="display: inline-block" id="btn-wrap"></div>
</h4>
<input type="file" id="file" class="filepond" name="filepond" />
<h2>
当前目录:<i id="repo"></i>
<span onclick="addDir()" class="back">新建目录</span>
<span onclick="document.getElementById('file').click()" class="back"
>上传文件</span
>
<span onclick="dirBack()" class="back">←返回</span>
<span onclick="refresh()" class="back ftr">刷新</span>
<span onclick="toggleWrap()" class="back ftr">分列</span>
<span onclick="updateToken()" class="back ftr">设置Token</span>
<span onclick="updateRepo()" class="back ftr">设置Repo</span>
<input
type="text"
class="back ftr"
id="search"
placeholder="关键词搜索, 回车确认"
onkeyup="search(event)"
/>
<!-- <span onclick="history.go(-1)" class="back">返回</span> -->
</h2>
<div id="file_wrap">
<ul class="file_list" id="file_list">
加载中...
</ul>
</div>
<div id="loading" class="hide">处理中...</div>
<script>
window.baseRepo = localStorage.getItem("GIT_REPO") || "dhjz/file";
window.baseToken = localStorage.getItem("GIT_TOKEN") || "";
if (!baseToken) alert("请先设置仓库和token");
function toggleWrap() {
var wrap = document.getElementById("file_wrap");
wrap.className = wrap.className ? "" : "w50";
}
let urls = [
{
name: "本站",
url: (() => {
// 获取基础URL
const baseUrl = location.origin + location.pathname.replace(/\/[^/]*$/, '/');
console.log('Generated base URL:', baseUrl);
return baseUrl;
})()
},
{ name: "gitmirror", url: `https://raw.gitmirror.com/${baseRepo}/master/` },
{ name: "jsdelivr", url: `https://gcore.jsdelivr.net/gh/${baseRepo}@master/` },
{ name: "jsdelivr1", url: `https://cdn.jsdelivr.net/gh/${baseRepo}/` },
{ name: "fxxk", url: `https://github.fxxk.dedyn.io/https://raw.githubusercontent.com/${baseRepo}/master/` },
{ name: "gh-proxy", url: `https://gh-proxy.com/https://raw.githubusercontent.com/${baseRepo}/master/` },
{ name: "ghproxy", url: `https://ghproxy.cc/https://raw.githubusercontent.com/${baseRepo}/master/` },
{ name: "gh.api", url: `https://gh.api.99988866.xyz/https://raw.githubusercontent.com/${baseRepo}/master/` },
{ name: "ghproxy.net", url: `https://ghproxy.net/https://raw.githubusercontent.com/${baseRepo}/master/` }
];
// 添加调试日志
console.log('All CDN URLs:', urls.map(u => ({name: u.name, url: u.url})));
function initBtn() {
let btnEl = document.getElementById("btn-wrap");
btnEl.innerHTML = ''; // 清空现有内容
urls.forEach((temp, j) => {
const btn = document.createElement("button");
btn.innerHTML = `
<span class="cdn-name">${temp.name}</span>
<span class="speed-info" id="btn${j}">测速中...</span>
`;
let ig = new Image();
ig.src = temp.url + "init.jpg?t=" + new Date().getTime();
let start = new Date().getTime();
ig.onload = function () {
const speed = new Date().getTime() - start;
const speedEl = document.getElementById(`btn${j}`);
speedEl.innerHTML = speed + "ms";
speedEl.style.color = speed < 1000 ? '#7ee787' : '#8b949e';
};
ig.onerror = function () {
const speedEl = document.getElementById(`btn${j}`);
speedEl.innerHTML = "失败";
speedEl.style.color = '#f85149';
};
btn.onclick = function () {
btnEl.querySelectorAll('button').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
document.getElementById("rootdm").value = temp.url;
initFileList();
};
btnEl.appendChild(btn);
});
}
initBtn();
window.request = axios.create({
baseURL: "https://api.github.com/",
timeout: 10000,
headers: {
Authorization: "Bearer " + baseToken,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
},
});
request.interceptors.response.use(
function (response) {
console.log("请求成功", response);
hideLoading();
return response;
},
function (error) {
hideLoading();
return Promise.reject(error);
}
);
window.paths = [];
window.en = Base64.encode;
window.de = Base64.decode;
window.fileList = [];
function initFileList(searchVal) {
let rootdm = document.getElementById("rootdm").value || "";
let tempList = window.fileList;
if (searchVal && searchVal.trim()) {
tempList = window.fileList.filter((item) =>
item.name.includes(searchVal.trim())
);
}
if (window.fileList.length) {
document.getElementById("file_list").innerHTML = tempList
.map((item) => {
// 正确处理文件路径中的空格
const encodedPath = item.path.replace(/ /g, '%20');
return `<li class="file ${item.ftype}">
<a target="_blank" href="${rootdm}${encodedPath}" onclick="getDir('${
item.type == "dir" ? encodedPath : ""
}', false, event)">${item.name}</a><span class='sha'>${
item.sha
}</span><span class="size">${getUnit(item.size)}</span>
<i onclick="delOne('${item.path}', '${
item.sha
}')" class="del">删除</i>
</li>`;
})
.join("");
} else {
document.getElementById("file_list").innerHTML = `
<div class="empty-folder-hint">
<i>📁</i>
<p>当前文件夹为空</p>
<p style="margin-top: 10px; font-size: 14px; color: #999;">
拖放文件到这里上传,或点击顶部的"上传文件"按钮
</p>
</div>
`;
}
document.getElementById("repo").innerHTML =
baseRepo + "/" + (paths.length ? paths[paths.length - 1] : "");
}
// 初始化根目录
if (baseToken) getDir("", true);
function getDir(path, isRoot, event, isBack) {
if (!path && !isRoot) return;
if (event) event.preventDefault();
showLoading();
getContent(path + "?t=" + new Date().getTime()).then((data) => {
console.log(data);
window.fileList = (data || [])
.filter((d) => d.name != "init.jpg")
.map((item) => {
item.ftype = getType(item.name);
if (item.type == "dir") item.ftype = "dir";
return item;
});
window.fileList.sort((a, b) => (a.type < b.type ? -1 : 1));
if (path && !isBack) paths.push(path);
initFileList();
});
}
function addDir() {
const val = prompt("请输入新建目录名称, 基于根目录, 不以/开头", "");
if (val) {
putDir(val);
}
}
function dirBack() {
if (!paths.length) return alert("已经是根目录了!");
paths.pop();
if (paths.length) {
getDir(paths[paths.length - 1], false, null, true);
} else {
getDir("", true, null, true);
}
}
function refresh() {
if (paths.length) {
getDir(paths[paths.length - 1], false, null, true);
} else {
getDir("", true, null, true);
}
}
function search(e) {
if (e.keyCode == 13) {
initFileList(document.getElementById("search").value);
}
}
function delOne(path, sha) {
if (path == "index.html") return alert("主页index.html不能被删除!");
if (window.confirm("是否确认删除改文件: " + path)) {
delFile(path, sha, true);
}
}
// putContent('ip.txt', base64Str)
document.getElementById("file").addEventListener("input", (e) => {
const file = e.target.files[0];
if (file)
putFile(
paths.length
? paths[paths.length - 1] + "/" + file.name
: file.name,
file
);
document.getElementById("file").value = "";
});
function updateRepo() {
const val = prompt(
"请输入仓库 {owner}/{repo}",
localStorage.getItem("GIT_REPO") || "dhjz/file"
);
if (val) localStorage.setItem("GIT_REPO", val) || location.reload();
}
function updateToken() {
const val = prompt(
"请输入token",
localStorage.getItem("GIT_TOKEN") || ""
);
if (val) localStorage.setItem("GIT_TOKEN", val) || location.reload();
}
function getSha(path) {
return new Promise((reso, rej) => {
request
.get(`/repos/${baseRepo}/contents/${path}`)
.then((res) => reso(res.data.sha))
.catch(() => reso(null));
});
}
function getContent(path, isFull) {
if (isFull) return request.get(`/repos/${baseRepo}/contents/${path}`);
return new Promise((reso, rej) => {
request
.get(`/repos/${baseRepo}/contents/${path}`)
.then((res) => {
if (Array.isArray(res.data)) return reso(res.data);
reso(Base64.decode(res.data.content));
})
.catch(() => {
console.log("not exit file: " + path);
reso(null);
});
});
}
function putContent(path, content) {
const data = {
message: now() + " update " + path,
content: Base64.encode(content),
};
getSha(path).then((sha) => {
if (sha) data.sha = sha;
request.put(`/repos/${baseRepo}/contents/${path}`, data);
});
}
function putDir(path) {
const data = {
message: now() + " create dir " + path,
content: "",
};
getContent(path).then((res) => {
if (Array.isArray(res)) return alert("该目录已存在");
request
.put(
`/repos/${baseRepo}/contents/${path}${
path.endsWith("/") ? "" : "/"
}.init`,
data
)
.then(() => {
alert("新建目录成功: " + path);
refresh();
});
});
}
function delFile(path, sha, isTip) {
// getSha(path).then((sha) => {
// }).catch((e) => console.log('not exit file: ' + path))
request
.delete(`/repos/${baseRepo}/contents/${path}`, {
params: {
message: now() + " del " + path,
sha,
},
})
.then(() => {
if (isTip) alert("删除文件成功:" + path);
refresh();
});
}
// 添加文件上传队列管理
class UploadQueue {
constructor(concurrency = 3) {
this.queue = [];
this.running = 0;
this.concurrency = concurrency;
this.results = [];
}
add(file, targetPath) {
return new Promise((resolve, reject) => {
this.queue.push({
file,
targetPath,
resolve,
reject,
retries: 0
});
this.processNext();
});
}
async processNext() {
if (this.running >= this.concurrency || this.queue.length === 0) return;
this.running++;
const task = this.queue.shift();
const { file, targetPath, resolve, reject, retries } = task;
try {
await this.uploadFile(file, targetPath, retries);
this.results.push({ success: true, file: file.name });
resolve();
} catch (error) {
console.error(`上传失败 (重试次数: ${retries}):`, error);
if (retries < 3) {
console.log(`重试上传: ${file.name}`);
this.queue.push({...task, retries: retries + 1});
} else {
this.results.push({ success: false, file: file.name, error });
reject(error);
}
} finally {
this.running--;
this.processNext();
}
}
async uploadFile(file, targetPath, retryCount) {
const sha = await getSha(targetPath);
if (sha && !window.confirm(`已存在该文件: ${targetPath}, 是否覆盖?`)) {
throw new Error('用户取消覆盖');
}
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = async () => {
try {
const arrayBuffer = reader.result;
const blob = new Blob([arrayBuffer], { type: file.type });
const content = await blob.arrayBuffer();
const data = {
message: now() + " update " + targetPath,
content: btoa(chunkChar(new Uint8Array(content))),
sha,
};
await request.put(`/repos/${baseRepo}/contents/${targetPath}`, data, {
headers: { "Content-Type": file.type }
});
resolve();
} catch (err) {
reject(err);
}
};
reader.onerror = (err) => reject(err);
});
}
isComplete() {
return this.queue.length === 0 && this.running === 0;
}
getResults() {
return this.results;
}
}
function handleDrop(e) {
e.preventDefault();
e.stopPropagation();
document.getElementById('drop-zone').classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length === 0) return;
const uploadQueue = new UploadQueue(3); // 最多3个并发上传
showLoading(`准备上传 ${files.length} 个文件...`);
console.log('开始处理拖拽的文件:', files.length, '个文件');
let processed = 0;
const totalFiles = files.length;
const promises = [];
Array.from(files).forEach((file, index) => {
const targetPath = paths.length
? paths[paths.length - 1] + "/" + file.name
: file.name;
promises.push(
uploadQueue.add(file, targetPath)
.then(() => {
processed++;
console.log(`文件 ${file.name} 上传成功,已处理 ${processed}/${totalFiles}`);
showLoading(`正在上传第 ${processed}/${totalFiles} 个文件...`);
})
.catch(err => {
console.error(`文件 ${file.name} 上传失败:`, err);
})
);
});
// 等待所有文件处理完成
Promise.allSettled(promises).then(() => {
const results = uploadQueue.getResults();
const successful = results.filter(r => r.success).length;
const failed = results.filter(r => !r.success).length;
if (failed > 0) {
const failedFiles = results.filter(r => !r.success).map(r => r.file).join(', ');
alert(`上传完成。\n成功: ${successful} 个文件\n失败: ${failed} 个文件\n\n失败的文件: ${failedFiles}`);
} else {
alert(`所有文件上传成功!共 ${successful} 个文件。`);
}
setTimeout(() => {
refresh();
hideLoading();
}, 1000);
});
}
function putFile(path, file) {
const uploadQueue = new UploadQueue(1);
showLoading(`正在上传: ${path}`);
uploadQueue.add(file, path)
.then(() => {
alert("上传成功:" + path + ", 大小:" + getUnit(file.size));
refresh();
})
.catch(err => {
console.error("文件上传失败:", path, err);
alert("上传失败:" + path + ", 请重试");
})
.finally(() => {
hideLoading();
});
}
function chunkChar(arr) {
// content: btoa(String.fromCharCode(...new TextEncoder().encode(content))) 不太行
// String.fromCharCode()方法最多可以接受65535个参数
const chunkSize = 10000;
const chunks = [];
for (let i = 0; i < arr.length; i += chunkSize) {
chunks.push(arr.slice(i, i + chunkSize));
}
const strings = chunks.map((chunk) => String.fromCharCode(...chunk));
return strings.join("");
}
function now() {
return new Date(new Date().getTime() + 8 * 60 * 60 * 1000)
.toISOString()
.replace("T", " ")
.substring(0, 19);
}
function getType(val) {
if (/\.(jpg|jpeg|png|gif)$/i.test(val)) return "img";
if (/\.(mp4|avi|mov|wmv|flv)$/i.test(val)) return "video";
if (/\.(mp3|wav|wma|aac)$/i.test(val)) return "music";
if (/\.(doc|docx|odt)$/i.test(val)) return "doc";
if (/\.(xls|xlsx)$/i.test(val)) return "xls";
if (/\.(ppt|pptx)$/i.test(val)) return "ppt";
if (/\.(pdf)$/i.test(val)) return "pdf";
if (/\.(txt|ini|properties|yml|json|md)$/i.test(val)) return "txt";
if (/\.(java|html|htm|css|js|php|h|go|)$/i.test(val)) return "code";
if (/\.(zip|rar|7z|tar\.gz|tar\.bz2)$/i.test(val)) return "zip";
return "other";
}
function getUnit(bytes, decimals = 2) {