Repository navigation
Expand file tree
/
Copy pathsimple_http_file_browser.py
More file actions
1199 lines (1105 loc) · 94.2 KB
/
Copy pathsimple_http_file_browser.py
File metadata and controls
1199 lines (1105 loc) · 94.2 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
#!/usr/bin/env python3
"""A dependency-free, single-file HTTP file browser."""
from __future__ import annotations
import argparse
import base64
import hmac
import ipaddress
import threading
import binascii
import datetime
import json
import mimetypes
import os
import re
import shutil
import stat
import sys
import tempfile
import time
import urllib.parse
import zipfile
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
VERSION = "1.7.1"
ARCHIVE_SUFFIXES = (".zip",)
def is_archive(name):
return str(name).lower().endswith(ARCHIVE_SUFFIXES)
def archive_member_path(name):
"""Keep archive names inside their virtual root; never extract them."""
if not name or name.startswith("/") or "\\" in name or "\0" in name:
return None
parts = [part for part in name.split("/") if part not in ("", ".")]
if not parts or any(part == ".." for part in parts) or ":" in parts[0]:
return None
return "/".join(parts)
def zip_member_name(member):
"""Honor Unicode ZIP names, then recover legacy Korean Windows names."""
if member.flag_bits & 0x800:
return member.filename
raw = member.filename.encode("cp437")
extra = member.extra
while len(extra) >= 4:
tag = int.from_bytes(extra[:2], "little")
size = int.from_bytes(extra[2:4], "little")
value, extra = extra[4:4 + size], extra[4 + size:]
if len(value) != size: break
# Info-ZIP Unicode Path extra field, validated against original bytes.
if tag == 0x7075 and size >= 5 and value[0] == 1 and int.from_bytes(value[1:5], "little") == binascii.crc32(raw):
try: return value[5:].decode("utf-8")
except UnicodeDecodeError: pass
try:
return raw.decode("utf-8")
except UnicodeDecodeError:
try:
decoded = raw.decode("cp949")
if any("\uac00" <= char <= "\ud7a3" for char in decoded):
return decoded
except UnicodeDecodeError:
pass
return member.filename
class ArchiveReader:
"""A bounded, read-only virtual directory backed by ZIP members."""
def __init__(self, target, max_entries=0, *, max_archive_mb=0, max_member_mb=0,
max_expanded_mb=0, max_ratio=0, max_path_length=0, max_path_depth=0):
self.target = target
self.max_entries = max_entries
self.max_archive_bytes = max_archive_mb * 1024 * 1024
self.max_member_bytes = max_member_mb * 1024 * 1024
self.max_expanded_bytes = max_expanded_mb * 1024 * 1024
self.max_ratio = max_ratio
self.max_path_length = max_path_length
self.max_path_depth = max_path_depth
self.archive = None
self.entries = {}
self.slot_acquired = False
def __enter__(self):
try:
if not ARCHIVE_SLOT.acquire(blocking=False):
raise ValueError("Another archive operation is in progress. Try again later.")
self.slot_acquired = True
if self.max_archive_bytes and self.target.stat().st_size > self.max_archive_bytes:
raise ValueError("The archive exceeds the configured ZIP browsing size limit.")
if self.target.suffix.lower() != ".zip":
raise ValueError("TAR browsing is disabled. Download the original instead.")
self.archive = zipfile.ZipFile(self.target)
members = self.archive.infolist()
fallback_time = self.target.stat().st_mtime
total_size = 0
for index, member in enumerate(members):
if self.max_entries and index >= self.max_entries:
raise ValueError("The archive contains too many entries.")
name = archive_member_path(zip_member_name(member))
if name is None: continue
if ((self.max_path_length and len(name) > self.max_path_length)
or (self.max_path_depth and name.count("/") > self.max_path_depth)):
raise ValueError("The archive path is too complex.")
# Avoid CVE-2026-15310 even on an unpatched interpreter.
if member.compress_type not in (zipfile.ZIP_STORED, zipfile.ZIP_DEFLATED):
raise ValueError("Only stored and DEFLATE ZIP members may be browsed.")
if self.max_ratio and member.file_size > max(member.compress_size, 1) * self.max_ratio:
raise ValueError("The archive compression ratio is too high.")
if stat.S_ISLNK(member.external_attr >> 16): continue
is_dir, size = member.is_dir(), member.file_size
try: mtime = datetime.datetime(*member.date_time).timestamp()
except (ValueError, OverflowError, OSError): mtime = fallback_time
total_size += size
if (size < 0 or (self.max_member_bytes and size > self.max_member_bytes)
or (self.max_expanded_bytes and total_size > self.max_expanded_bytes)):
raise ValueError("The archive exceeds the expanded size limits.")
parts = name.split("/")
for depth in range(1, len(parts)):
parent = "/".join(parts[:depth])
self.entries.setdefault(parent, {"dir": True, "size": None, "mtime": fallback_time, "member": None})
if self.max_entries and len(self.entries) > self.max_entries:
raise ValueError("The archive contains too many virtual entries.")
# Ambiguous duplicate paths retain their first visible entry.
self.entries.setdefault(name, {"dir": is_dir, "size": None if is_dir else size, "mtime": mtime, "member": member})
if self.max_entries and len(self.entries) > self.max_entries:
raise ValueError("The archive contains too many virtual entries.")
return self
except Exception:
if self.archive is not None: self.archive.close()
if self.slot_acquired:
ARCHIVE_SLOT.release()
self.slot_acquired = False
raise
def __exit__(self, *_args):
try:
self.archive.close()
finally:
if self.slot_acquired:
ARCHIVE_SLOT.release()
self.slot_acquired = False
def list(self, folder, show_hidden):
if folder:
entry = self.entries.get(folder)
if entry is None: raise FileNotFoundError("The archive folder does not exist.")
if not entry["dir"]: raise ValueError("The requested archive path is not a folder.")
prefix = folder + "/" if folder else ""
items = []
for name, entry in self.entries.items():
if not name.startswith(prefix): continue
child = name[len(prefix):]
if not child or "/" in child or (not show_hidden and child.startswith(".")): continue
items.append({"name": child, "dir": entry["dir"], "size": entry["size"], "mtime": entry["mtime"]})
return items
def open(self, name):
entry = self.entries.get(name)
if entry is None: raise FileNotFoundError("The archive file does not exist.")
if entry["dir"]: raise ValueError("The requested archive path is not a file.")
member = entry["member"]
if member.flag_bits & 1: raise ValueError("Encrypted ZIP members cannot be opened without a password.")
try: return self.archive.open(member)
except (NotImplementedError, RuntimeError) as error:
raise ValueError("This ZIP compression or encryption method is not supported.") from error
class ZipDownloadWriter:
"""An unseekable ZIP output, written directly to the HTTP response."""
def __init__(self, stream):
self.stream = stream
self.position = 0
def write(self, data):
self.stream.write(data)
self.position += len(data)
return len(data)
def tell(self):
return self.position
def flush(self):
self.stream.flush()
PREVIEW_TYPES = {
".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg",
".gif": "image/gif", ".webp": "image/webp", ".svg": "image/svg+xml",
".bmp": "image/bmp", ".avif": "image/avif", ".ico": "image/x-icon",
".apng": "image/apng",
".txt": "text/plain; charset=utf-8", ".text": "text/plain; charset=utf-8",
".md": "text/plain; charset=utf-8", ".markdown": "text/plain; charset=utf-8",
".mp4": "video/mp4", ".m4v": "video/mp4", ".mov": "video/quicktime",
".webm": "video/webm", ".ogv": "video/ogg",
".mp3": "audio/mpeg", ".m4a": "audio/mp4", ".aac": "audio/aac",
".wav": "audio/wav", ".ogg": "audio/ogg", ".oga": "audio/ogg",
".flac": "audio/flac",
}
INDEX_HTML = r'''<!doctype html>
<html lang="en-US"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Simple File Browser</title><style>
.upload-error{color:var(--danger);font-size:12px;white-space:pre-wrap;overflow-wrap:anywhere;margin-top:6px}
.row[draggable="true"]{cursor:grab}.row.moving{opacity:.45}.move-target{background:#eaf3ff!important;outline:2px solid #1677ff;outline-offset:-2px}
:root{--bg:#f3f6fa;--panel:#fff;--line:#dbe3ec;--text:#17212b;--muted:#687787;--blue:#1677ff;--blue2:#eaf3ff;--danger:#d9363e;--shadow:0 7px 28px #24405d18}*{box-sizing:border-box}body{margin:0;background:var(--bg);color:var(--text);font:14px/1.45 system-ui,-apple-system,"Segoe UI",sans-serif}button,input{font:inherit}.app{min-height:100vh}.top{height:58px;background:#172b4d;color:#fff;display:flex;align-items:center;padding:0 22px;gap:12px;box-shadow:0 2px 10px #0003}.logo{width:31px;height:31px;border-radius:8px;background:linear-gradient(145deg,#40a9ff,#096dd9);display:grid;place-items:center;font-size:18px}.top strong{font-size:16px}.top .status{margin-left:auto;color:#cbd7e7;font-size:12px}.layout{display:grid;grid-template-columns:250px minmax(0,1fr);min-height:calc(100vh - 58px)}aside{padding:16px 10px;background:#fff;border-right:1px solid var(--line);overflow:auto;max-height:calc(100vh - 58px)}.tree{min-width:0}.tree-row{display:flex;align-items:center;height:34px;border-radius:7px;white-space:nowrap}.tree-row:hover{background:#f5f9ff}.tree-row.active{background:var(--blue2);color:var(--blue);font-weight:650}.tree-toggle,.tree-name{border:0;background:none;cursor:pointer;color:inherit;padding:0}.tree-toggle{width:22px;min-width:22px;height:30px;color:var(--muted)}.tree-spacer{width:22px;min-width:22px}.tree-name{min-width:0;overflow:hidden;text-overflow:ellipsis;text-align:left;padding:6px 8px 6px 2px;flex:1}.main{padding:22px 26px;min-width:0}.crumbs{display:flex;align-items:center;gap:5px;min-height:33px;overflow:auto;white-space:nowrap}.crumbs button{border:0;background:none;color:var(--blue);cursor:pointer;padding:4px}.bar{display:flex;gap:8px;align-items:center;margin:12px 0}.btn{border:1px solid var(--line);background:#fff;border-radius:7px;padding:8px 12px;cursor:pointer;color:var(--text)}.btn:hover{border-color:#8abfff;color:var(--blue)}.primary{background:var(--blue);border-color:var(--blue);color:white}.primary:hover{color:white;background:#096dd9}.search{margin-left:auto;min-width:220px;border:1px solid var(--line);border-radius:7px;padding:8px 11px;outline:none}.search:focus{border-color:var(--blue)}.panel{background:var(--panel);border:1px solid var(--line);border-radius:10px;box-shadow:var(--shadow);overflow:hidden}.head,.row{display:grid;grid-template-columns:minmax(260px,1fr) 110px 170px 82px;align-items:center}.head{background:#f7f9fc;color:var(--muted);font-size:12px;border-bottom:1px solid var(--line);padding:9px 14px}.head span{cursor:pointer}.row{padding:8px 14px;min-height:49px;border-bottom:1px solid #edf1f5}.row:last-child{border-bottom:0}.row:hover{background:#f5f9ff}.name{display:flex;align-items:center;min-width:0;gap:11px}.name button{border:0;background:none;padding:0;text-align:left;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;cursor:pointer;color:var(--text)}.name button:hover{color:var(--blue)}.icon{font-size:23px;width:26px;text-align:center}.meta{color:var(--muted);font-size:12px}.actions{display:flex;gap:4px;justify-content:flex-end}.iconbtn{border:0;background:none;color:#718096;cursor:pointer;padding:5px}.iconbtn:hover{color:var(--blue)}.empty{padding:70px 20px;text-align:center;color:var(--muted)}.drop{position:fixed;inset:0;background:#1677ff24;z-index:9;display:none;place-items:center;border:4px dashed var(--blue);font-size:24px;color:var(--blue);font-weight:700}.drop.on{display:grid}.upload-panel{position:fixed;right:24px;bottom:24px;width:min(390px,calc(100vw - 32px));z-index:8;background:#fff;border:1px solid var(--line);border-radius:11px;box-shadow:0 14px 45px #172b4d35;padding:16px}.upload-panel[hidden]{display:none}.upload-title{font-weight:700;margin-bottom:10px}.upload-list{max-height:min(55vh,420px);overflow:auto}.upload-item{padding:9px 0;border-top:1px solid var(--line)}.upload-item:first-child{border-top:0}.upload-item-head{display:flex;align-items:center;gap:8px;font-size:12px;margin-bottom:6px}.upload-item-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}.upload-item-status{color:var(--muted);white-space:nowrap}.upload-item-status.complete{color:#17803d;font-weight:650}.upload-item-status.failed{color:var(--danger);font-weight:650}.upload-track{height:8px;background:#e8edf3;border-radius:99px;overflow:hidden}.upload-fill{height:100%;width:0;background:linear-gradient(90deg,#4096ff,var(--blue));border-radius:99px;transition:width .12s linear}.upload-fill.complete{background:#35a866}.upload-stats{margin-top:5px;color:var(--muted);font-size:11px;text-align:right}.toast{position:fixed;right:24px;bottom:24px;max-width:380px;padding:11px 16px;background:#17212beF;color:#fff;border-radius:8px;box-shadow:var(--shadow);opacity:0;transform:translateY(12px);pointer-events:none;transition:.2s}.toast.on{opacity:1;transform:none}.danger{color:var(--danger)}dialog{border:0;border-radius:11px;box-shadow:0 18px 70px #0005;padding:0;min-width:340px}dialog::backdrop{background:#14203377}.modal{padding:20px}.modal h3{margin:0 0 15px}.modal input{width:100%;padding:9px;border:1px solid var(--line);border-radius:7px}.modal .foot{display:flex;justify-content:flex-end;gap:8px;margin-top:18px}@media(max-width:760px){.layout{grid-template-columns:1fr}aside{display:none}.main{padding:14px}.head,.row{grid-template-columns:minmax(130px,1fr) 80px 72px}.date{display:none}.search{min-width:0;width:130px}.bar{flex-wrap:wrap}}
/* Keep application chrome fixed; the file panel and tree scroll independently. */
html,body{height:100%;overflow:hidden}
.app{height:100vh;height:100dvh;min-height:0;display:flex;flex-direction:column;overflow:hidden}
.top{flex:0 0 58px;position:relative;z-index:1}
.layout{flex:1;min-height:0;overflow:hidden}
aside{min-height:0;max-height:none;overflow:auto;overscroll-behavior:contain}
.main{min-height:0;display:flex;flex-direction:column;overflow:hidden}
.crumbs,.bar{flex-shrink:0}
.panel{min-height:0;overflow:auto;overscroll-behavior:contain;scrollbar-gutter:stable}
.head{position:sticky;top:0;z-index:1}
</style></head><body><div class="app"><header class="top"><div class="logo">📁</div><strong id="title">Simple File Browser</strong><span class="status" id="status"></span></header><div class="layout"><aside><div class="tree" id="tree"></div></aside><main class="main"><div class="crumbs" id="crumbs"></div><div class="bar"><button class="btn primary write" data-action="pick" data-i18n="upload">↑ Upload</button><button class="btn write" data-action="mkdir" data-i18n="newFolder">+ New folder</button><button class="btn" data-action="refresh" data-i18n="refresh">↻ Refresh</button><input class="search" id="search" data-i18n-placeholder="search" placeholder="Search this folder" data-search="true"></div><section class="panel"><div class="head"><span data-action="sort" data-value="name" data-i18n="name">Name</span><span data-action="sort" data-value="size" data-i18n="size">Size</span><span class="date" data-action="sort" data-value="mtime" data-i18n="modified">Date modified</span><span></span></div><div id="files"></div></section></main></div></div><input id="picker" type="file" multiple hidden><div class="drop" id="drop" data-i18n="drop">Drop files here to upload</div><div class="upload-panel" id="uploadPanel" hidden><div class="upload-title" id="uploadTitle">Uploading…</div><div id="uploadList"></div></div><div class="toast" id="toast"></div><dialog id="dialog"><div class="modal"><h3 id="dlgTitle"></h3><input id="dlgInput"><div class="foot"><button class="btn" data-action="cancel" data-i18n="cancel">Cancel</button><button class="btn primary" id="dlgOk" data-i18n="confirm">Confirm</button></div></div></dialog>
<dialog id="previewDialog" class="preview-dialog" aria-labelledby="previewTitle"><div class="preview-head"><strong id="previewTitle"></strong><button class="btn" type="button" data-action="close-preview" data-i18n="close">Close</button></div><div class="preview-body"><img id="previewImage" alt="" hidden><video id="previewVideo" controls playsinline preload="metadata" hidden></video><audio id="previewAudio" controls preload="metadata" hidden></audio><pre id="previewText" hidden></pre><div id="previewMarkdown" hidden></div><p id="previewError" hidden></p></div></dialog>
<style>.head,.row{grid-template-columns:minmax(260px,1fr) 110px 170px 132px}.preview-dialog{width:min(1100px,92vw);max-width:92vw;max-height:92vh}.preview-head{display:flex;align-items:center;justify-content:space-between;gap:16px;padding:12px 16px;border-bottom:1px solid var(--line)}.preview-head strong{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.preview-body{display:grid;place-items:center;min-height:160px;padding:16px;overflow:auto}.preview-body img{display:block;max-width:100%;max-height:calc(92vh - 105px);object-fit:contain}.preview-body img[hidden],.preview-body pre[hidden],.preview-body div[hidden]{display:none}.preview-body pre,.preview-body #previewMarkdown{width:100%;max-height:calc(92vh - 105px);overflow:auto;margin:0}.preview-body pre{white-space:pre-wrap;overflow-wrap:anywhere;font:13px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace}.preview-body #previewMarkdown{line-height:1.6;overflow-wrap:anywhere}.preview-body #previewMarkdown h1,.preview-body #previewMarkdown h2{border-bottom:1px solid var(--line);padding-bottom:6px}.preview-body #previewMarkdown pre{background:#f5f7fa;padding:12px;border-radius:7px}.preview-body #previewMarkdown blockquote{border-left:3px solid var(--line);padding-left:12px;color:var(--muted)}.preview-body p{color:var(--danger)}.iconbtn svg{display:block;width:18px;height:18px}@media(max-width:760px){.head,.row{grid-template-columns:minmax(130px,1fr) 80px 120px}}</style>
<style>.preview-body #previewMarkdown p{color:var(--text)}.preview-body #previewError{color:var(--danger)}.preview-body #previewMarkdown a{color:var(--blue);text-decoration:underline}.preview-body #previewMarkdown table{border-collapse:collapse;display:block;max-width:100%;overflow-x:auto;margin:14px 0}.preview-body #previewMarkdown th,.preview-body #previewMarkdown td{border:1px solid var(--line);padding:7px 11px;min-width:70px}.preview-body #previewMarkdown th{background:#f7f9fc;font-weight:650}</style>
<style>.preview-body video{display:block;max-width:100%;max-height:calc(92vh - 105px)}.preview-body audio{display:block;width:min(100%,600px)}.preview-body video[hidden],.preview-body audio[hidden]{display:none}</style>
<script>
const M={
'en-US':{allFiles:'▣ All files',upload:'↑ Upload',newFolder:'+ New folder',refresh:'↻ Refresh',search:'Search this folder',name:'Name',size:'Size',modified:'Date modified',drop:'Drop files here to upload',cancel:'Cancel',confirm:'Confirm',readWrite:'Read / write',readOnly:'Read only',home:'🏠 Home',noResults:'No matching files.',empty:'This folder is empty.',download:'Download',rename:'Rename',delete:'Delete',newFolderName:'New folder name',folderCreated:'Folder created.',renamed:'Name changed.',deleteAsk:n=>`Permanently delete “${n}”? If it is a folder, all files and subfolders inside it will also be deleted.`,deleted:'Deleted.',uploading:'Uploading…',processing:'Processing…',queued:'Queued',uploadingFile:'Uploading…',complete:'✓ Complete',failed:'Failed',uploadSummary:(done,total,failed)=>failed?`${done}/${total} uploaded, ${failed} failed.`:`${done} file(s) uploaded.`,uploaded:n=>`${n} file(s) uploaded.`,requestFailed:'The request could not be completed.'},
'es-ES':{allFiles:'▣ Todos los archivos',upload:'↑ Subir',newFolder:'+ Nueva carpeta',refresh:'↻ Actualizar',search:'Buscar en esta carpeta',name:'Nombre',size:'Tamaño',modified:'Fecha de modificación',drop:'Suelta aquí los archivos para subirlos',cancel:'Cancelar',confirm:'Confirmar',readWrite:'Lectura / escritura',readOnly:'Solo lectura',home:'🏠 Inicio',noResults:'No hay archivos que coincidan.',empty:'Esta carpeta está vacía.',download:'Descargar',rename:'Cambiar nombre',delete:'Eliminar',newFolderName:'Nombre de la nueva carpeta',folderCreated:'Carpeta creada.',renamed:'Nombre cambiado.',deleteAsk:n=>`¿Eliminar “${n}” permanentemente? Si es una carpeta, también se eliminarán todos sus archivos y subcarpetas.`,deleted:'Eliminado.',uploading:'Subiendo…',processing:'Procesando…',queued:'En cola',uploadingFile:'Subiendo…',complete:'✓ Completado',failed:'Fallido',uploadSummary:(done,total,failed)=>failed?`${done}/${total} subidos, ${failed} fallidos.`:`${done} archivo(s) subido(s).`,uploaded:n=>`${n} archivo(s) subido(s).`,requestFailed:'No se pudo completar la solicitud.'},
'ja-JP':{allFiles:'▣ すべてのファイル',upload:'↑ アップロード',newFolder:'+ 新しいフォルダー',refresh:'↻ 更新',search:'このフォルダーを検索',name:'名前',size:'サイズ',modified:'更新日時',drop:'ここにドロップしてアップロード',cancel:'キャンセル',confirm:'確認',readWrite:'読み取り / 書き込み',readOnly:'読み取り専用',home:'🏠 ホーム',noResults:'一致するファイルがありません。',empty:'このフォルダーは空です。',download:'ダウンロード',rename:'名前を変更',delete:'削除',newFolderName:'新しいフォルダー名',folderCreated:'フォルダーを作成しました。',renamed:'名前を変更しました。',deleteAsk:n=>`「${n}」を完全に削除しますか?フォルダーの場合、中のファイルとサブフォルダーもすべて削除されます。`,deleted:'削除しました。',uploading:'アップロード中…',processing:'処理中…',queued:'待機中',uploadingFile:'アップロード中…',complete:'✓ 完了',failed:'失敗',uploadSummary:(done,total,failed)=>failed?`${done}/${total}個をアップロード、${failed}個失敗。`:`${done}個のファイルをアップロードしました。`,uploaded:n=>`${n}個のファイルをアップロードしました。`,requestFailed:'リクエストを完了できませんでした。'},
'ko-KR':{allFiles:'▣ 모든 파일',upload:'↑ 업로드',newFolder:'+ 새 폴더',refresh:'↻ 새로고침',search:'현재 폴더 검색',name:'이름',size:'크기',modified:'수정한 날짜',drop:'여기에 놓아 업로드',cancel:'취소',confirm:'확인',readWrite:'읽기 / 쓰기',readOnly:'읽기 전용',home:'🏠 홈',noResults:'검색 결과가 없습니다.',empty:'이 폴더는 비어 있습니다.',download:'다운로드',rename:'이름 변경',delete:'삭제',newFolderName:'새 폴더 이름',folderCreated:'폴더를 만들었습니다.',renamed:'이름을 변경했습니다.',deleteAsk:n=>`“${n}”을(를) 영구 삭제할까요? 폴더인 경우 내부의 파일과 하위 폴더도 모두 삭제됩니다.`,deleted:'삭제했습니다.',uploading:'업로드 중…',processing:'처리 중…',queued:'대기 중',uploadingFile:'업로드 중…',complete:'✓ 완료',failed:'실패',uploadSummary:(done,total,failed)=>failed?`${done}/${total}개 업로드, ${failed}개 실패.`:`${done}개 파일을 업로드했습니다.`,uploaded:n=>`${n}개 파일을 업로드했습니다.`,requestFailed:'요청을 완료할 수 없습니다.'}
};
Object.assign(M['en-US'],{preview:'Preview',close:'Close',previewFailed:'This file could not be previewed.'});
Object.assign(M['es-ES'],{preview:'Vista previa',close:'Cerrar',previewFailed:'No se pudo mostrar el archivo.'});
Object.assign(M['ja-JP'],{preview:'プレビュー',close:'閉じる',previewFailed:'ファイルをプレビューできませんでした。'});
Object.assign(M['ko-KR'],{preview:'미리보기',close:'닫기',previewFailed:'파일을 미리 볼 수 없습니다.'});
M['en-US'].mediaFailed='This media cannot be played. The codec may be unsupported, or the file may be damaged.';
M['es-ES'].mediaFailed='No se puede reproducir este archivo. Es posible que el códec no sea compatible o que el archivo esté dañado.';
M['ja-JP'].mediaFailed='このメディアを再生できません。コーデックが非対応か、ファイルが破損している可能性があります。';
M['ko-KR'].mediaFailed='이 미디어를 재생할 수 없습니다. 코덱이 지원되지 않거나 파일이 손상되었을 수 있습니다.';
const LANG_MAP={en:'en-US',es:'es-ES',ja:'ja-JP',ko:'ko-KR'};
Object.entries({
'en-US':['Network error or connection reset. Check the server upload log for the rejection reason.','Upload cancelled.'],
'es-ES':['Error de red o conexión restablecida. Consulta el registro de subida del servidor.','Subida cancelada.'],
'ja-JP':['ネットワークエラーまたは接続リセットです。サーバーのアップロードログを確認してください。','アップロードがキャンセルされました。'],
'ko-KR':['네트워크 오류 또는 연결 리셋입니다. 서버 업로드 로그에서 거부 사유를 확인하세요.','업로드가 취소되었습니다.']
}).forEach(([locale,messages])=>Object.assign(M[locale],{uploadNetworkError:messages[0],uploadAborted:messages[1]}));
Object.entries({'en-US':'Moved.','es-ES':'Movido.','ja-JP':'移動しました。','ko-KR':'이동했습니다.'}).forEach(([locale,message])=>M[locale].moved=message);
const LOCALE=(navigator.languages||[navigator.language||'en']).map(x=>LANG_MAP[x.toLowerCase().split('-')[0]]).find(Boolean)||'en-US';
const t=(key,...args)=>typeof M[LOCALE][key]==='function'?M[LOCALE][key](...args):M[LOCALE][key];
document.documentElement.lang=LOCALE;document.querySelectorAll('[data-i18n]').forEach(e=>e.textContent=t(e.dataset.i18n));document.querySelectorAll('[data-i18n-placeholder]').forEach(e=>e.placeholder=t(e.dataset.i18nPlaceholder));
let path='', items=[], writable=false, uploadActive=false, sortKey='name', sortAsc=true, treeCache=new Map(), treeOpen=new Set(['']), treeArchives=new Set();
const $=s=>document.querySelector(s), enc=p=>p.split('/').map(encodeURIComponent).join('/');
function toast(s,bad=false){let e=$('#toast');e.textContent=s;e.style.background=bad?'#b4232b':'#17212b';e.classList.add('on');setTimeout(()=>e.classList.remove('on'),2600)}
let internalDrag=null,dragFromControl=false,externalDrag=0;
function archivePath(p){return [...treeArchives].some(a=>p===a||p.startsWith(a+'/'))}
function moveTarget(e){let target=e.target.closest('[data-folder]');if(!internalDrag||!target)return null;let p=target.dataset.folder;return archivePath(p)||p===internalDrag.path||p===internalDrag.source||p.startsWith(internalDrag.source+'/')?null:target}
function clearDrag(){document.querySelectorAll('.moving,.move-target').forEach(e=>e.classList.remove('moving','move-target'));internalDrag=null;externalDrag=0;$('#drop').classList.remove('on')}
document.addEventListener('pointerdown',e=>{dragFromControl=Boolean(e.target.closest('button,input,a'))});
document.addEventListener('dragstart',e=>{let row=e.target.closest('.row[data-item]');if(!row)return;if(!writable||dragFromControl){e.preventDefault();return}let source=row.dataset.item;internalDrag={path,name:source.split('/').pop(),source};e.dataTransfer.setData('application/x-file-browser-move',source);e.dataTransfer.effectAllowed='move';row.classList.add('moving')});
addEventListener('dragenter',e=>{if(internalDrag)return;if([...e.dataTransfer.types].includes('Files')){e.preventDefault();if(writable){externalDrag++;$('#drop').classList.add('on')}}});
addEventListener('dragleave',e=>{if(internalDrag){let target=e.target.closest('.move-target');if(target&&!target.contains(e.relatedTarget))target.classList.remove('move-target');return}if(--externalDrag<=0){externalDrag=0;$('#drop').classList.remove('on')}});
addEventListener('dragover',e=>{e.preventDefault();if(internalDrag){document.querySelectorAll('.move-target').forEach(x=>x.classList.remove('move-target'));let target=moveTarget(e);e.dataTransfer.dropEffect=target?'move':'none';if(target)target.classList.add('move-target')}});
addEventListener('drop',async e=>{e.preventDefault();if(internalDrag){let target=moveTarget(e),source=internalDrag,destination=target?.dataset.folder;clearDrag();if(!target)return;try{await api('/api/move',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({...source,destination})});treeCache.clear();treeArchives.clear();treeOpen=new Set(['']);await load();toast(t('moved'))}catch(error){toast(error.message,true)}return}clearDrag();if(writable&&e.dataTransfer.files.length)upload(e.dataTransfer.files)});
addEventListener('dragend',clearDrag);
async function api(url,opt={}){if(opt.method==='POST')opt.headers={...opt.headers,'X-File-Browser-Request':'1'};let r=await fetch(url,opt),data;try{data=await r.json()}catch{data={error:r.statusText}}if(!r.ok)throw Error(data.error||r.statusText);return data}
let loadRequest=0;
async function load(p=path,recordHistory=true){let request=++loadRequest;try{let d=await api('/api/list?path='+encodeURIComponent(p)),previous=path;if(request!==loadRequest)return;path=d.path;items=d.items;writable=d.writable;if(recordHistory&&path!==previous)history.pushState({path},'',path?'?path='+encodeURIComponent(path):location.pathname);treeCache.set(path,folderNames(d.items));$('#title').textContent=d.title;$('#status').textContent=writable?t('readWrite'):t('readOnly');document.querySelectorAll('.write').forEach(x=>x.hidden=!writable);crumbs();render();await syncTree(path);return true}catch(e){if(request===loadRequest)toast(e.message,true);return false}}
function folderNames(list,parent=path){for(let item of list){let p=parent+(parent?'/':'')+item.name;if(item.archive)treeArchives.add(p);else treeArchives.delete(p)}return list.filter(x=>x.dir||x.archive).map(x=>x.name).sort((a,b)=>a.localeCompare(b,LOCALE,{numeric:true,sensitivity:'base'}))}
async function ensureTree(p){if(treeCache.has(p))return;let d=await api('/api/list?path='+encodeURIComponent(p));treeCache.set(p,folderNames(d.items,p))}
async function syncTree(p){let cur='';treeOpen.add('');await ensureTree('');for(let part of (p?p.split('/'):[])){cur+=(cur?'/':'')+part;treeOpen.add(cur);await ensureTree(cur)}renderTree()}
async function toggleTree(p,e){if(e)e.stopPropagation();if(treeOpen.has(p)){treeOpen.delete(p);renderTree();return}treeOpen.add(p);try{await ensureTree(p);renderTree()}catch(err){treeOpen.delete(p);toast(err.message,true)}}
function action(name,value=''){return ' data-action="'+name+'" data-value="'+attr(value)+'"'}
function treeToggle(p){if(treeCache.has(p)&&treeCache.get(p).length===0)return '<span class="tree-spacer"></span>';return '<button class="tree-toggle" aria-label="Toggle"'+action('toggle',p)+'>'+(treeOpen.has(p)?'▾':'▸')+'</button>'}
function treeBranch(parent,depth){return (treeCache.get(parent)||[]).map(name=>{let p=parent+(parent?'/':'')+name,open=treeOpen.has(p);return '<div class="tree-row '+(p===path?'active':'')+'" data-folder="'+attr(p)+'" style="padding-left:'+(4+depth*14)+'px">'+treeToggle(p)+'<button class="tree-name" title="'+attr(name)+'"'+action('load',p)+'>'+(treeArchives.has(p)?'📦 ':'📁 ')+esc(name)+'</button></div>'+(open?treeBranch(p,depth+1):'')}).join('')}
function renderTree(){let rootOpen=treeOpen.has('');$('#tree').innerHTML='<div class="tree-row '+(path===''?'active':'')+'" data-folder="" style="padding-left:4px">'+treeToggle('')+'<button class="tree-name"'+action('load')+'>'+t('allFiles')+'</button></div>'+(rootOpen?treeBranch('',1):'')}
function crumbs(){let e=$('#crumbs'),parts=path?path.split('/'):[];e.innerHTML='<button'+action('load')+'>'+t('home')+'</button>';let p='';parts.forEach(x=>{p+=(p?'/':'')+x;e.innerHTML+=' <span>›</span> <button'+action('load',p)+'>'+esc(x)+'</button>'})}
function esc(s){let d=document.createElement('div');d.textContent=s;return d.innerHTML}
function attr(s){return esc(s).replaceAll('"','"')}
function human(n){if(n==null)return '—';let u=['B','KB','MB','GB','TB'],i=0;while(n>=1024&&i<4){n/=1024;i++}return (i?n.toFixed(n<10?1:0):n)+' '+u[i]}
function sortBy(k){sortAsc=sortKey===k?!sortAsc:true;sortKey=k;render()}
const imagePreviewPattern=/\.(?:png|jpe?g|gif|webp|svg|bmp|avif|ico|apng)$/i;
const videoPreviewPattern=/\.(?:mp4|m4v|mov|webm|ogv)$/i;
const audioPreviewPattern=/\.(?:mp3|m4a|aac|wav|ogg|oga|flac)$/i;
const previewPattern=/\.(?:png|jpe?g|gif|webp|svg|bmp|avif|ico|apng|txt|text|md|markdown|mp4|m4v|mov|webm|ogv|mp3|m4a|aac|wav|ogg|oga|flac)$/i;
const eyeIcon='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M2 12s3.6-6 10-6 10 6 10 6-3.6 6-10 6S2 12 2 12Z"/><circle cx="12" cy="12" r="3"/></svg>';
function render(){let q=$('#search').value.toLocaleLowerCase(LOCALE),a=items.filter(x=>x.name.toLocaleLowerCase(LOCALE).includes(q));a.sort((x,y)=>{if(x.dir!==y.dir)return x.dir?-1:1;let v=sortKey==='name'?x.name.localeCompare(y.name,LOCALE,{numeric:true,sensitivity:'base'}):(x[sortKey]||0)-(y[sortKey]||0);return sortAsc?v:-v});let e=$('#files');if(!a.length){e.innerHTML='<div class="empty">'+(q?t('noResults'):t('empty'))+'</div>';return}e.innerHTML=a.map(x=>{let p=path+(path?'/':'')+x.name;return '<div class="row" draggable="'+writable+'" data-item="'+attr(p)+'"'+(x.dir?' data-folder="'+attr(p)+'"':'')+'><div class="name"><span class="icon">'+(x.dir?'📁':x.archive?'📦':'📄')+'</span><button title="'+attr(x.name)+'"'+action(x.dir||x.archive?'load':'download',p)+'>'+esc(x.name)+'</button></div><div class="meta">'+human(x.size)+'</div><div class="meta date">'+new Date(x.mtime*1000).toLocaleString(LOCALE)+'</div><div class="actions">'+(!x.dir&&previewPattern.test(x.name)?'<button class="iconbtn" type="button" title="'+t('preview')+'" aria-label="'+t('preview')+'"'+action('preview',p)+'>'+eyeIcon+'</button>':'')+'<button class="iconbtn" title="'+t('download')+'"'+action('download',p)+'>↓</button>'+(writable?'<button class="iconbtn" title="'+t('rename')+'"'+action('rename',x.name)+'>✎</button><button class="iconbtn danger" title="'+t('delete')+'"'+action('delete',x.name)+'>×</button>':'')+'</div></div>'}).join('')}
document.addEventListener('click',event=>{let button=event.target.closest('[data-action]');if(!button)return;let value=button.dataset.value||'';switch(button.dataset.action){case 'pick':pickFiles();break;case 'mkdir':newFolder();break;case 'refresh':load();break;case 'sort':sortBy(value);break;case 'cancel':$('#dialog').close();break;case 'close-preview':$('#previewDialog').close();break;case 'toggle':toggleTree(value,event);break;case 'load':load(value);break;case 'download':download(value);break;case 'preview':preview(value);break;case 'rename':renameItem(value);break;case 'delete':removeItem(value);break}});
$('#search').addEventListener('input',render);
function markdownInto(source,container,documentPath){
container.replaceChildren();let lines=source.replace(/\r\n?/g,'\n').split('\n'),code=null,list=null,references=new Map();
for(let line of lines){let definition=line.match(/^\s{0,3}\[([^\]]+)\]:\s*(?:<([^>]+)>|(\S+))(?:\s+"[^"]*")?\s*$/);if(definition)references.set(definition[1].trim().toLowerCase(),definition[2]||definition[3])}
const addLink=(node,label,address)=>{let link=document.createElement('a');try{if(/^https?:|^mailto:/i.test(address)){let url=new URL(address);if(!['http:','https:','mailto:'].includes(url.protocol))throw Error();link.href=url.href;link.target='_blank';link.rel='noopener noreferrer'}else{if(/^[a-z][a-z0-9+.-]*:/i.test(address)||address.startsWith('//')||address.startsWith('#'))throw Error();let parent=documentPath.split('/').slice(0,-1).map(encodeURIComponent).join('/'),url=new URL(address,location.origin+'/'+parent+'/');if(url.origin!==location.origin)throw Error();let path=decodeURIComponent(url.pathname.slice(1));link.href=previewPattern.test(path)?viewURL(path,true):'/api/download?path='+encodeURIComponent(path);link.onclick=event=>{if(previewPattern.test(path)&&!event.ctrlKey&&!event.metaKey&&!event.shiftKey&&!event.altKey&&event.button===0){event.preventDefault();preview(path)}}}link.textContent=label;node.append(link)}catch{node.append(document.createTextNode(label))}};
const inline=(node,value)=>{let pattern=/(`[^`]+`|\[([^\]]+)\]\((<[^>]+>|[^)\s]+)(?:\s+"[^"]*")?\)|\[([^\]]+)\]\[([^\]]*)\]|\*\*[^*]+\*\*|\*[^*]+\*)/g,last=0,match;while((match=pattern.exec(value))){node.append(document.createTextNode(value.slice(last,match.index)));let token=match[0];if(match[2])addLink(node,match[2],match[3].replace(/^<|>$/g,''));else if(match[4]){let address=references.get((match[5]||match[4]).trim().toLowerCase());if(address)addLink(node,match[4],address);else node.append(document.createTextNode(token))}else{let tag=token.startsWith('`')?'code':token.startsWith('**')?'strong':'em',part=document.createElement(tag);part.textContent=token.slice(tag==='strong'?2:1,tag==='strong'?-2:-1);node.append(part)}last=pattern.lastIndex}node.append(document.createTextNode(value.slice(last)))};
const cells=line=>{let value=line.trim();if(value.startsWith('|'))value=value.slice(1);if(value.endsWith('|'))value=value.slice(0,-1);let result=[],cell='';for(let i=0;i<value.length;i++){if(value[i]==='\\'&&value[i+1]==='|'){cell+='|';i++}else if(value[i]==='|'){result.push(cell.trim());cell=''}else cell+=value[i]}result.push(cell.trim());return result};
for(let i=0;i<lines.length;i++){let line=lines[i],fence=line.match(/^\s*```/);if(fence){if(code){code=null}else{let pre=document.createElement('pre');code=document.createElement('code');pre.append(code);container.append(pre)}list=null;continue}if(code){code.textContent+=line+'\n';continue}if(/^\s{0,3}\[[^\]]+\]:\s*(?:<[^>]+>|\S+)/.test(line))continue;if(!line.trim()){list=null;continue}
if(i+1<lines.length){let header=cells(line),separator=cells(lines[i+1]);if((line.includes('|')||lines[i+1].includes('|'))&&header.length===separator.length&&separator.every(cell=>/^:?-{3,}:?$/.test(cell))){let table=document.createElement('table'),thead=document.createElement('thead'),headRow=document.createElement('tr'),tbody=document.createElement('tbody'),align=separator.map(cell=>cell.startsWith(':')&&cell.endsWith(':')?'center':cell.endsWith(':')?'right':'left');header.forEach((value,j)=>{let th=document.createElement('th');th.style.textAlign=align[j];inline(th,value);headRow.append(th)});thead.append(headRow);table.append(thead,tbody);i++;while(i+1<lines.length&&lines[i+1].trim()&&lines[i+1].includes('|')){let row=document.createElement('tr'),values=cells(lines[++i]);header.forEach((_,j)=>{let td=document.createElement('td');td.style.textAlign=align[j];inline(td,values[j]||'');row.append(td)});tbody.append(row)}container.append(table);list=null;continue}}
let heading=line.match(/^(#{1,6})\s+(.+)$/),bullet=line.match(/^\s*[-*+]\s+(.+)$/),quote=line.match(/^>\s?(.*)$/),tag,value;if(heading){tag='h'+heading[1].length;value=heading[2];list=null}else if(bullet){if(!list){list=document.createElement('ul');container.append(list)}tag='li';value=bullet[1]}else if(quote){tag='blockquote';value=quote[1];list=null}else{tag='p';value=line;list=null}let element=document.createElement(tag);inline(element,value);(tag==='li'?list:container).append(element)}
}
let previewRequest=0;
function clearPreviewSources(){let img=$('#previewImage');img.onload=img.onerror=null;img.removeAttribute('src');for(let media of [$('#previewVideo'),$('#previewAudio')]){media.pause();media.onerror=null;media.removeAttribute('src');media.load();media.hidden=true}}
async function preview(p,recordHistory=true){let img=$('#previewImage'),textView=$('#previewText'),markdown=$('#previewMarkdown'),error=$('#previewError'),dialog=$('#previewDialog'),request=++previewRequest;if(recordHistory&&(!dialog.open||history.state?.preview!==p)){let previewDepth=dialog.open?(history.state?.previewDepth||1)+1:1;history.pushState({path,preview:p,previewDepth},'',viewURL(p,true))}$('#previewTitle').textContent=p.split('/').pop();clearPreviewSources();img.hidden=textView.hidden=markdown.hidden=error.hidden=true;textView.textContent='';markdown.replaceChildren();if(!dialog.open)dialog.showModal();let url='/api/preview?path='+encodeURIComponent(p);if(imagePreviewPattern.test(p)){img.onload=()=>{if(request===previewRequest)img.hidden=false};img.onerror=()=>{if(request===previewRequest){error.textContent=t('previewFailed');error.hidden=false}};img.src=url;return}if(videoPreviewPattern.test(p)||audioPreviewPattern.test(p)){let media=$(videoPreviewPattern.test(p)?'#previewVideo':'#previewAudio');media.onerror=()=>{if(request===previewRequest){media.hidden=true;error.textContent=t('mediaFailed');error.hidden=false}};media.hidden=false;media.src=url;media.load();return}try{let response=await fetch(url);if(!response.ok)throw Error();let body=await response.text();if(request!==previewRequest)return;if(/\.(?:md|markdown)$/i.test(p)){markdownInto(body,markdown,p);markdown.hidden=false}else{textView.textContent=body;textView.hidden=false}}catch{if(request===previewRequest){error.textContent=t('previewFailed');error.hidden=false}}}
$('#previewDialog').addEventListener('close',()=>{previewRequest++;clearPreviewSources();if(history.state?.preview)history.go(-Math.max(1,history.state.previewDepth||1))});
$('#previewDialog').addEventListener('click',event=>{let dialog=$('#previewDialog'),rect=dialog.getBoundingClientRect();if(event.target===dialog&&(event.clientX<rect.left||event.clientX>rect.right||event.clientY<rect.top||event.clientY>rect.bottom))dialog.close()});
function openItem(p,d){d?load(p):download(p)}function download(p){location.href='/api/download?path='+encodeURIComponent(p)}
$('#dialog').addEventListener('click',event=>{let dialog=$('#dialog'),rect=dialog.getBoundingClientRect();if(event.target===dialog&&(event.clientX<rect.left||event.clientX>rect.right||event.clientY<rect.top||event.clientY>rect.bottom))dialog.close()});
$('#dialog').addEventListener('cancel',event=>{event.preventDefault();$('#dialog').close()});
$('#dlgInput').addEventListener('keydown',event=>{if(event.key==='Enter'&&!event.isComposing&&event.keyCode!==229){event.preventDefault();$('#dlgOk').click()}});
function promptBox(title,value,cb){let dialog=$('#dialog');$('#dlgTitle').textContent=title;$('#dlgInput').value=value||'';$('#dlgOk').onclick=()=>{let v=$('#dlgInput').value.trim();if(v){dialog.close();cb(v)}};dialog.showModal();setTimeout(()=>{$('#dlgInput').focus();$('#dlgInput').select()},30)}
function newFolder(){promptBox(t('newFolderName'),'',async n=>{try{await api('/api/mkdir',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({path,name:n})});toast(t('folderCreated'));load()}catch(e){toast(e.message,true)}})}
function renameItem(old){promptBox(t('rename'),old,async n=>{try{await api('/api/rename',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({path,name:old,new_name:n})});toast(t('renamed'));load()}catch(e){toast(e.message,true)}})}
async function removeItem(name){if(!confirm(t('deleteAsk',name)))return;try{await api('/api/delete',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({path,name})});toast(t('deleted'));load()}catch(e){toast(e.message,true)}}
function pickFiles(){$('#picker').click()}$('#picker').onchange=e=>upload(e.target.files);
function showUpload(files,start=0,append=false){uploadActive=true;let close=$('#uploadClose');if(!close){close=document.createElement('button');close.id='uploadClose';close.className='btn';close.textContent=t('close');close.onclick=hideUpload;$('#uploadPanel').append(close)}close.hidden=true;$('#uploadTitle').textContent=t('uploading');$('#uploadList').className='upload-list';let html=Array.from(files).map((file,offset)=>{let i=start+offset;return '<div class="upload-item" id="upload-item-'+i+'"><div class="upload-item-head"><span class="upload-item-name">'+esc(file.name)+'</span><span class="upload-item-status" id="upload-status-'+i+'">'+t('queued')+'</span></div><div class="upload-track" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0"><div class="upload-fill" id="upload-fill-'+i+'"></div></div><div class="upload-stats" id="upload-stats-'+i+'">0%</div></div>'}).join('');if(append)$('#uploadList').insertAdjacentHTML('beforeend',html);else $('#uploadList').innerHTML=html;$('#uploadPanel').hidden=false}
function updateFileUpload(index,percent,loaded,total){let p=Math.max(0,Math.min(100,percent)),fill=$('#upload-fill-'+index),stats=$('#upload-stats-'+index);fill.style.width=p+'%';stats.textContent=(total?human(loaded)+' / '+human(total)+' · ':'')+Math.round(p)+'%';fill.parentElement.setAttribute('aria-valuenow',Math.round(p))}
function setFileStatus(index,key,complete=false,size=0){let status=$('#upload-status-'+index);status.textContent=t(key);status.className='upload-item-status '+(complete?'complete':key==='failed'?'failed':'');if(complete){$('#upload-fill-'+index).classList.add('complete');updateFileUpload(index,100,size,size)}}
function hideUpload(){if(!uploadActive)$('#uploadPanel').hidden=true}
function sendUpload(file,index,destination=path){return new Promise((resolve,reject)=>{let form=new FormData();form.append('path',destination);form.append('files',file,file.name);let x=new XMLHttpRequest();x.open('POST','/api/upload');x.setRequestHeader('X-File-Browser-Request','1');x.upload.onprogress=e=>{if(e.lengthComputable){updateFileUpload(index,e.loaded/e.total*100,e.loaded,e.total);if(e.loaded>=e.total)setFileStatus(index,'processing')}};x.onload=()=>{let d;try{d=JSON.parse(x.responseText||'{}')}catch{d={error:x.statusText}}if(x.status>=200&&x.status<300)resolve(d);else reject(Error('HTTP '+x.status+': '+(d.error||x.statusText||t('requestFailed'))))};x.onerror=()=>reject(Error(t('uploadNetworkError')));x.onabort=()=>reject(Error(t('uploadAborted')));x.send(form)})}
let uploadBatch=0,uploadQueue=[],uploadIndex=0;
function upload(files){let added=Array.from(files);if(!writable||!added.length)return;let running=uploadActive,destination=path;if(!running){uploadQueue=[];uploadIndex=0;showUpload([])}let start=uploadQueue.length;uploadQueue.push(...added.map(file=>({file,destination})));showUpload(added,start,true);$('#picker').value='';if(!running)return processUploads(++uploadBatch)}
async function processUploads(batch){let done=0,failed=0;while(true){while(uploadIndex<uploadQueue.length){let i=uploadIndex++,{file,destination}=uploadQueue[i];setFileStatus(i,'uploadingFile');try{await sendUpload(file,i,destination);setFileStatus(i,'complete',true,file.size);done++}catch(e){setFileStatus(i,'failed');let detail=document.createElement('div');detail.className='upload-error';detail.textContent=e.message;$('#upload-item-'+i).append(detail);console.error('Upload failed:',file.name,e.message);failed++}}try{await load()}catch(e){toast(e.message,true)}if(uploadIndex>=uploadQueue.length)break}uploadActive=false;if(failed){$('#uploadClose').hidden=false;toast(t('uploadSummary',done,uploadQueue.length,failed),true)}else setTimeout(()=>{if(batch===uploadBatch&&!uploadActive){hideUpload();toast(t('uploadSummary',done,done,0))}},3000)}
function viewURL(p,isPreview=false){return location.pathname+(p?'?path='+encodeURIComponent(p)+(isPreview?'&preview=1':''):'')}
function locationState(){let params=new URLSearchParams(location.search),p=params.get('path')||'';return params.get('preview')==='1'&&p?{path:p.split('/').slice(0,-1).join('/'),preview:p}:{path:p}}
addEventListener('popstate',async event=>{let state=event.state||locationState(),dialog=$('#previewDialog');if(state.preview){if(state.path!==path&&!await load(state.path,false))return;preview(state.preview,false);return}if(dialog.open)dialog.close();if(state.path!==path)load(state.path,false)});
async function openInitialLocation(){let state=locationState();history.replaceState({path:state.path},'',viewURL(state.path));if(await load(state.path,false)&&state.preview)preview(state.preview)}
openInitialLocation();
</script></body></html>'''
# Keep script execution separate from user-controlled HTML attributes.
APP_JS = INDEX_HTML.split('<script>', 1)[1].split('</script>', 1)[0]
INDEX_HTML = INDEX_HTML.split('<script>', 1)[0] + '<script src="/app.js"></script></body></html>'
ARCHIVE_SLOT = threading.BoundedSemaphore(1)
def visible_path(relative, show_hidden=False):
parts = Path(relative).parts
if not show_hidden and any(part.startswith('.') for part in parts):
raise PermissionError("Hidden files are not accessible.")
def upload_name(name, allowed_extensions=None):
name = safe_name(name)
if allowed_extensions and Path(name).suffix.lower() not in allowed_extensions:
raise PermissionError("This upload file type is not allowed.")
return name
class BoundedHTTPServer(ThreadingHTTPServer):
daemon_threads = True
def __init__(self, address, handler, config):
self.config = config
self.slots = threading.BoundedSemaphore(config["max_connections"])
self.upload_lock = threading.Lock()
super().__init__(address, handler)
def process_request(self, request, client_address):
if not self.slots.acquire(blocking=False):
self.shutdown_request(request)
return
try:
super().process_request(request, client_address)
except Exception:
self.slots.release()
raise
def process_request_thread(self, request, client_address):
try:
super().process_request_thread(request, client_address)
finally:
self.slots.release()
class LimitedWriter:
def __init__(self, stream, limit):
self.stream, self.limit, self.size = stream, limit, 0
def write(self, data):
self.size += len(data)
if self.size > self.limit:
raise ValueError("The multipart field is too large.")
return self.stream.write(data)
def safe_name(name: str) -> str:
if not isinstance(name, str) or not name or name in {".", ".."} or "/" in name or "\\" in name or any(ord(char) < 32 or ord(char) == 127 for char in name):
raise ValueError("Invalid file name.")
return name
class LimitedInput:
"""Read at most Content-Length bytes while supporting a pushback buffer."""
def __init__(self, stream, length: int):
self.stream = stream
self.remaining = length
self.buffer = b""
def read(self, size: int = -1) -> bytes:
if size < 0:
size = len(self.buffer) + self.remaining
output = self.buffer[:size]
self.buffer = self.buffer[len(output):]
needed = size - len(output)
if needed > 0 and self.remaining > 0:
chunk = self.stream.read(min(needed, self.remaining))
self.remaining -= len(chunk)
output += chunk
return output
def unread(self, data: bytes):
self.buffer = data + self.buffer
def readline(self, limit: int) -> bytes:
output = bytearray()
while len(output) < limit:
char = self.read(1)
if not char:
return bytes(output)
output += char
if char == b"\n":
return bytes(output)
raise ValueError("A multipart header line is too large.")
def disposition_parameters(value: str):
params = {}
pattern = r";\s*([!#$%&'*+\-.^_`|~0-9A-Za-z]+)\s*=\s*(?:\"((?:\\.|[^\"])*)\"|([^;]*))"
for match in re.finditer(pattern, value):
key = match.group(1).lower()
if match.group(2) is not None:
params[key] = re.sub(r"\\(.)", r"\1", match.group(2))
else:
params[key] = match.group(3).strip()
if "filename" not in params and "filename*" in params:
encoded = params["filename*"]
try:
charset, _language, encoded_name = encoded.split("'", 2)
params["filename"] = urllib.parse.unquote(encoded_name, encoding=charset or "utf-8", errors="strict")
except (LookupError, UnicodeError, ValueError):
raise ValueError("Invalid encoded upload file name.")
return params
class FileBrowserHandler(BaseHTTPRequestHandler):
server_version = f"SimpleFileBrowser/{VERSION}"
def setup(self):
self.request.settimeout(self.server.config["request_timeout"])
super().setup()
@property
def config(self):
return self.server.config # type: ignore[attr-defined]
def log_message(self, fmt, *args):
message = re.sub(r"[\x00-\x1f\x7f-\x9f]", "?", fmt % args)
sys.stderr.write("[%s] %s\n" % (self.log_date_time_string(), message))
def end_headers(self):
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("X-Frame-Options", "DENY")
self.send_header("Referrer-Policy", "no-referrer")
self.send_header("Cache-Control", "no-store")
super().end_headers()
def authorize(self, write=False):
hosts = self.headers.get_all("Host", [])
if len(hosts) != 1 or not valid_host_header(hosts[0]):
self.fail(403, "A single valid Host header is required.")
return False
direct_origin = None
if len(hosts) == 1 and self.config.get("direct_network"):
# Accept the IP actually used to reach this socket, not arbitrary
# attacker-controlled DNS names (DNS rebinding protection).
local_ip, local_port = self.connection.getsockname()[:2]
accepted = {f"{local_ip}:{local_port}"}
if local_port == 80: accepted.add(local_ip)
if ipaddress.ip_address(local_ip).is_loopback:
accepted.add(f"localhost:{local_port}")
if local_port == 80: accepted.add("localhost")
if hosts[0].lower() in accepted:
direct_origin = "http://" + hosts[0].lower()
host_allowed = "*" in self.config["allowed_hosts"] or hosts[0].lower() in self.config["allowed_hosts"]
if not host_allowed and direct_origin is None:
self.fail(403, "This Host is not allowed.")
return False
if host_allowed and self.config.get("dynamic_host_origin"):
direct_origin = "http://" + hosts[0].lower()
expected = self.config.get("authorization")
if expected and not hmac.compare_digest(self.headers.get("Authorization", "").encode(), expected):
self.send_response(401)
self.send_header("WWW-Authenticate", 'Basic realm="File Browser", charset="UTF-8"')
self.send_header("Content-Length", "0")
self.end_headers()
return False
if write:
if self.headers.get("X-File-Browser-Request") != "1":
self.fail(403, "A same-origin write request is required.")
return False
origin = self.headers.get("Origin")
if origin is not None and origin not in self.config["allowed_origins"] and origin != direct_origin:
self.fail(403, "Cross-origin writes are not allowed.")
return False
if self.headers.get("Sec-Fetch-Site") not in (None, "same-origin", "none"):
self.fail(403, "Cross-site writes are not allowed.")
return False
return True
def content_length(self, maximum):
lengths = self.headers.get_all("Content-Length", [])
if self.headers.get("Transfer-Encoding") or len(lengths) != 1 or not re.fullmatch(r"[0-9]+", lengths[0]):
raise ValueError("A single valid Content-Length is required.")
length = int(lengths[0])
if length <= 0 or (maximum and length > maximum):
raise ValueError("The request size is outside the allowed limits.")
return length
def send_json(self, data, status=200):
raw = json.dumps(data, ensure_ascii=False).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.send_header("X-Content-Type-Options", "nosniff")
self.end_headers()
self.wfile.write(raw)
def fail(self, status, message):
if getattr(self, "command", "") == "POST":
self.log_message("Request failed: status=%s path=%s stage=%s reason=%s", status,
urllib.parse.urlsplit(self.path).path, getattr(self, "upload_stage", "validation"), message)
self.send_json({"error": message}, status)
if getattr(self, "command", "") == "POST" and urllib.parse.urlsplit(self.path).path == "/api/upload":
self.drain_rejected_upload()
def drain_rejected_upload(self):
"""Avoid a TCP reset from closing with unread upload bytes.
Send the error first, then discard a bounded amount of in-flight data.
Never store rejected data or wait indefinitely for a stalled client.
"""
self.wfile.flush()
lengths = self.headers.get_all("Content-Length", [])
if self.headers.get("Transfer-Encoding") or len(lengths) != 1 or not re.fullmatch(r"[0-9]+", lengths[0]):
return
reader = getattr(self, "upload_reader", None)
remaining = reader.remaining if reader is not None else int(lengths[0])
remaining = min(remaining, 64 * 1024 * 1024)
deadline = time.monotonic() + 5
original_timeout = self.connection.gettimeout()
try:
while remaining > 0:
timeout = deadline - time.monotonic()
if timeout <= 0: break
self.connection.settimeout(min(timeout, original_timeout) if original_timeout is not None else timeout)
chunk = self.rfile.read1(min(65536, remaining))
if not chunk: break
remaining -= len(chunk)
except OSError:
pass # A client may stop transmitting as soon as it receives the error.
finally:
self.connection.settimeout(original_timeout)
def resolve(self, relative="", must_exist=True):
if not isinstance(relative, str): raise ValueError("The path must be a string.")
relative = relative.replace("\\", "/").lstrip("/")
visible_path(relative, self.config["show_hidden"])
root = self.config["root"]
target = (root / relative).resolve(strict=False)
try:
target.relative_to(root)
except ValueError:
raise PermissionError("Access outside the configured root folder is not allowed.")
visible_path(target.relative_to(root), self.config["show_hidden"])
if must_exist and not target.exists():
raise FileNotFoundError("The file or folder does not exist.")
return target
def send_file(self, target, preview):
with target.open("rb") as source:
self.send_stream(source, target.name, target.stat().st_size, preview)
def send_folder_zip(self, target=None, archive=None, inner=""):
members = []
total_size, file_count = 0, 0
max_files = self.config["max_folder_download_files"]
max_bytes = self.config["max_folder_download_mb"] * 1024 * 1024
def add_member(entry):
nonlocal total_size, file_count
total_size += entry[2]
if entry[1] is not None: file_count += 1
if max_files and file_count > max_files:
raise ValueError(f"The folder exceeds the ZIP download file limit ({max_files}).")
if max_bytes and total_size > max_bytes:
raise ValueError(f"The folder exceeds the ZIP download size limit ({self.config['max_folder_download_mb']} MiB).")
members.append(entry)
if archive is not None:
archive.list(inner, self.config["show_hidden"])
name = inner.rsplit("/", 1)[-1]
prefix = inner + "/"
add_member((name + "/", None, 0, archive.entries[inner]["mtime"]))
for member_name, entry in archive.entries.items():
if not member_name.startswith(prefix): continue
relative = member_name[len(prefix):]
if not self.config["show_hidden"] and any(part.startswith(".") for part in relative.split("/")): continue
zipped_name = name + "/" + relative
if entry["dir"]:
add_member((zipped_name + "/", None, 0, entry["mtime"]))
else:
# Validate encrypted/unsupported members before starting the response.
with archive.open(member_name): pass
add_member((zipped_name, member_name, entry["size"], entry["mtime"]))
else:
name = target.name or "files"
def walk_error(error): raise error
for folder, directories, files in os.walk(target, followlinks=False, onerror=walk_error):
folder = Path(folder)
directories[:] = sorted(directory for directory in directories if not (folder / directory).is_symlink() and (self.config["show_hidden"] or not directory.startswith(".")))
relative = folder.relative_to(target).as_posix()
zipped_folder = name + ("/" + relative if relative != "." else "")
add_member((zipped_folder + "/", None, 0, folder.stat().st_mtime))
for filename in sorted(files):
source = folder / filename
if source.is_symlink() or not source.is_file() or (not self.config["show_hidden"] and filename.startswith(".")): continue
source.resolve().relative_to(target)
info = source.stat()
add_member((zipped_folder + "/" + filename, source, info.st_size, info.st_mtime))
self.send_response(200)
self.send_header("Content-Type", "application/zip")
self.send_header("Content-Disposition", "attachment; filename*=UTF-8''" + urllib.parse.quote(name + ".zip"))
self.send_header("X-Content-Type-Options", "nosniff")
# Generated ZIPs stream without a temporary file or a known final length.
self.send_header("Connection", "close")
self.close_connection = True
self.end_headers()
try:
with zipfile.ZipFile(ZipDownloadWriter(self.wfile), "w", compression=zipfile.ZIP_STORED, allowZip64=True) as output:
for zipped_name, source_name, size, mtime in members:
try: date_time = datetime.datetime.fromtimestamp(mtime).timetuple()[:6]
except (ValueError, OverflowError, OSError): date_time = (1980, 1, 1, 0, 0, 0)
if date_time[0] < 1980: date_time = (1980, 1, 1, 0, 0, 0)
if date_time[0] > 2107: date_time = (2107, 12, 31, 23, 59, 58)
info = zipfile.ZipInfo(zipped_name, date_time)
info.compress_type = zipfile.ZIP_STORED
info.file_size = size
if source_name is None:
info.external_attr = ((stat.S_IFDIR | 0o755) << 16) | 0x10
output.writestr(info, b"")
else:
info.external_attr = (stat.S_IFREG | 0o644) << 16
source = archive.open(source_name) if archive is not None else source_name.open("rb")
with source, output.open(info, "w", force_zip64=True) as destination:
shutil.copyfileobj(source, destination, length=1024 * 1024)
except (BrokenPipeError, ConnectionResetError):
pass
except Exception as error:
self.log_message("Folder ZIP download interrupted: %s", error)
def archive_location(self, relative):
if not isinstance(relative, str): raise ValueError("The path must be a string.")
relative = relative.replace("\\", "/").lstrip("/")
visible_path(relative, self.config["show_hidden"])
parts = relative.split("/")
for depth in range(1, len(parts) + 1):
target = self.resolve("/".join(parts[:depth]), must_exist=False)
if target.is_file() and is_archive(target.name):
inner = "/".join(parts[depth:]).rstrip("/")
if inner and archive_member_path(inner) is None:
raise PermissionError("Access outside the archive root is not allowed.")
return target, archive_member_path(inner) if inner else ""
return None
def send_stream(self, source, name, size, preview):
range_header = None if self.headers.get("If-Range") else self.headers.get("Range")
start, end = 0, size - 1
if range_header:
match = re.fullmatch(r"bytes=(\d*)-(\d*)", range_header.strip())
if match and (match.group(1) or match.group(2)):
if match.group(1):
start = int(match.group(1))
end = min(int(match.group(2)), size - 1) if match.group(2) else size - 1
else:
suffix = int(match.group(2))
start = max(0, size - suffix)
valid = size > 0 and start < size and end >= start
if not match.group(1):
valid = valid and suffix > 0
else:
valid = False
if not valid:
self.send_response(416)
self.send_header("Content-Range", f"bytes */{size}")
self.send_header("Accept-Ranges", "bytes")
self.send_header("Content-Length", "0")
self.end_headers()
return
content_type = PREVIEW_TYPES.get(Path(name).suffix.lower()) if preview else mimetypes.guess_type(name)[0]
self.send_response(206 if range_header else 200)
self.send_header("Content-Type", content_type or "application/octet-stream")
self.send_header("Content-Disposition", ("inline" if preview else "attachment") + "; filename*=UTF-8''" + urllib.parse.quote(name))
self.send_header("Accept-Ranges", "bytes")
if range_header:
self.send_header("Content-Range", f"bytes {start}-{end}/{size}")
if preview:
self.send_header("Content-Security-Policy", "sandbox; default-src 'none'")
self.send_header("X-Content-Type-Options", "nosniff")
self.send_header("Content-Length", str(end - start + 1 if range_header else size))
self.end_headers()
if range_header:
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk: break
self.wfile.write(chunk)
remaining -= len(chunk)
else:
shutil.copyfileobj(source, self.wfile)
def do_GET(self):
if not self.authorize(): return
parsed = urllib.parse.urlsplit(self.path)
query = urllib.parse.parse_qs(parsed.query)
try:
if parsed.path in ("/", "/app.js"):
raw = (INDEX_HTML if parsed.path == "/" else APP_JS).encode()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8" if parsed.path == "/" else "text/javascript; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'unsafe-inline'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'")
self.send_header("X-Frame-Options", "DENY")
self.end_headers(); self.wfile.write(raw)
elif parsed.path == "/api/list":
relative = query.get("path", [""])[0]
location = self.archive_location(relative)
if location:
target, inner = location
with ArchiveReader(target, self.config["max_zip_entries"], **{
"max_" + key.removeprefix("max_zip_"): self.config[key]
for key in ZIP_BROWSING_LIMITS}) as archive:
items = archive.list(inner, self.config["show_hidden"])
rel = target.relative_to(self.config["root"]).as_posix()
self.send_json({"path": rel + ("/" + inner if inner else ""), "items": items, "writable": False, "archive": rel, "title": self.config["title"]})
return
target = self.resolve(relative)
if not target.is_dir(): raise ValueError("The requested path is not a folder.")
items = []
for p in target.iterdir():
if not self.config["show_hidden"] and p.name.startswith("."): continue
try:
st = p.stat(); is_dir = p.is_dir()
items.append({"name": p.name, "dir": is_dir, "archive": not is_dir and is_archive(p.name), "size": None if is_dir else st.st_size, "mtime": st.st_mtime})
except (OSError, PermissionError): pass
rel = target.relative_to(self.config["root"]).as_posix()
self.send_json({"path": "" if rel == "." else rel, "items": items, "writable": self.config["upload"], "title": self.config["title"]})
elif parsed.path in ("/api/download", "/api/preview"):
relative = query.get("path", [""])[0]
preview = parsed.path == "/api/preview"
location = self.archive_location(relative)
if location and location[1]:
target, inner = location
if preview and Path(inner).suffix.lower() not in PREVIEW_TYPES:
raise ValueError("This file cannot be previewed.")
with ArchiveReader(target, self.config["max_zip_entries"], **{
"max_" + key.removeprefix("max_zip_"): self.config[key]
for key in ZIP_BROWSING_LIMITS}) as archive:
if not preview and inner in archive.entries and archive.entries[inner]["dir"]:
self.send_folder_zip(archive=archive, inner=inner)
return
with archive.open(inner) as source:
self.send_stream(source, inner.rsplit("/", 1)[-1], archive.entries[inner]["size"], preview)
return
target = self.resolve(relative)
if target.is_dir() and not preview:
self.send_folder_zip(target=target)
return
if not target.is_file(): raise ValueError("The requested path is not a file.")
if preview and target.suffix.lower() not in PREVIEW_TYPES:
raise ValueError("This file cannot be previewed.")
self.send_file(target, preview)
else: self.fail(404, "Not found.")
except PermissionError as e: self.fail(403, str(e))
except FileNotFoundError as e: self.fail(404, str(e))
except (zipfile.BadZipFile, EOFError): self.fail(400, "The archive is damaged or its format is not supported.")
except (NotImplementedError, RuntimeError): self.fail(400, "The archive compression method is not supported by this Python runtime.")
except (ValueError, OSError) as e: self.fail(400, str(e))
def read_json(self):
if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json":
raise ValueError("An application/json request is required.")
length = self.content_length(1024 * 1024)
body = self.rfile.read(length)
if len(body) != length: raise ValueError("The request was interrupted.")
data = json.loads(body)
if not isinstance(data, dict): raise ValueError("A JSON object is required.")
return data
def require_write(self):
if not self.config["upload"]: raise PermissionError("Write operations are disabled.")
def do_POST(self):
self.close_connection = True
if not self.authorize(write=True): return
parsed = urllib.parse.urlsplit(self.path)
try:
self.require_write()
if parsed.path == "/api/upload": self.handle_upload(); return
data = self.read_json()
if self.archive_location(data.get("path", "")):
raise PermissionError("Archive contents are read-only.")
parent = self.resolve(data.get("path", ""))
if not parent.is_dir(): raise ValueError("The destination folder is invalid.")
if parsed.path == "/api/mkdir":
target = self.resolve((parent.relative_to(self.config["root"]) / safe_name(data.get("name", ""))).as_posix(), must_exist=False)
target.mkdir()
elif parsed.path == "/api/rename":
old = self.resolve((parent.relative_to(self.config["root"]) / safe_name(data.get("name", ""))).as_posix())
new_name = upload_name(data.get("new_name", ""), self.config["allowed_extensions"]) if old.is_file() else safe_name(data.get("new_name", ""))
new = self.resolve((parent.relative_to(self.config["root"]) / new_name).as_posix(), must_exist=False)
if new.exists(): raise FileExistsError("An item with the same name already exists.")
old.rename(new)
elif parsed.path == "/api/move":
destination = data.get("destination", "")
if self.archive_location(destination):
raise PermissionError("Archive contents are read-only.")
destination = self.resolve(destination)
if not destination.is_dir():
raise ValueError("The destination folder is invalid.")
source = parent / safe_name(data.get("name", ""))
visible_path(source.relative_to(self.config["root"]), self.config["show_hidden"])
if not source.exists() and not source.is_symlink():
raise FileNotFoundError("The file or folder does not exist.")
if source.is_dir() and not source.is_symlink() and (destination == source or source in destination.parents):
raise ValueError("A folder cannot be moved into itself or its subfolders.")
target = destination / source.name
if target.exists() or target.is_symlink():
raise FileExistsError("An item with the same name already exists.")
source.rename(target)
elif parsed.path == "/api/delete":
target = parent / safe_name(data.get("name", ""))
visible_path(target.relative_to(self.config["root"]), self.config["show_hidden"])
if target.is_symlink():
target.unlink()
elif target.is_dir():
shutil.rmtree(target)
elif target.exists():
target.unlink()
else:
raise FileNotFoundError("The file or folder does not exist.")
else: self.fail(404, "Not found."); return
self.send_json({"ok": True})
except PermissionError as e: self.fail(403, str(e))
except FileNotFoundError as e: self.fail(404, str(e))
except FileExistsError as e: self.fail(409, str(e))
except (ValueError, OSError, json.JSONDecodeError) as e: self.fail(400, str(e))
def multipart_boundary(self, content_type: str) -> bytes:
if content_type.split(";", 1)[0].strip().lower() != "multipart/form-data":
raise ValueError("A multipart/form-data request is required.")
match = re.search(r'(?:^|;)\s*boundary=(?:"([^"]+)"|([^;]+))', content_type, re.IGNORECASE)
if not match:
raise ValueError("The multipart boundary is missing.")
value = (match.group(1) or match.group(2)).strip()
try:
boundary = value.encode("ascii")
except UnicodeEncodeError:
raise ValueError("The multipart boundary must be ASCII.")
if not boundary or len(boundary) > 200 or b"\r" in boundary or b"\n" in boundary:
raise ValueError("The multipart boundary is invalid.")
return boundary
def multipart_headers(self, reader: LimitedInput):
headers, total = {}, 0
while True:
line = reader.readline(8192)
if not line: raise ValueError("The upload was interrupted while reading multipart headers.")
total += len(line)
if total > 65536: raise ValueError("Multipart headers are too large.")
if line == b"\r\n": return headers
if not line.endswith(b"\r\n") or b":" not in line:
raise ValueError("A multipart header is malformed.")
raw_name, raw_value = line[:-2].split(b":", 1)
try:
name = raw_name.decode("ascii").strip().lower()
value = raw_value.strip().decode("utf-8")
except UnicodeDecodeError:
try:
name = raw_name.decode("ascii").strip().lower()
value = raw_value.strip().decode("latin-1")
except UnicodeDecodeError:
raise ValueError("A multipart header has an invalid encoding.")
headers[name] = value
def stream_multipart_part(self, reader: LimitedInput, boundary: bytes, output):
marker = b"\r\n--" + boundary
buffer = b""
while True:
chunk = reader.read(1024 * 1024)
if not chunk:
raise ValueError("The upload was interrupted before the multipart boundary.")
buffer += chunk
search_from = 0
while True:
index = buffer.find(marker, search_from)
if index < 0:
keep = len(marker) + 2
if len(buffer) > keep:
output.write(buffer[:-keep])
buffer = buffer[-keep:]
break
suffix_at = index + len(marker)
if len(buffer) < suffix_at + 2:
if index:
output.write(buffer[:index])
buffer = buffer[index:]
break
suffix = buffer[suffix_at:suffix_at + 2]
if suffix in (b"\r\n", b"--"):
output.write(buffer[:index])
reader.unread(buffer[suffix_at + 2:])
return suffix == b"--"
search_from = index + 1
def parse_multipart(self, length: int, boundary: bytes):
reader = LimitedInput(self.rfile, length)
self.upload_reader = reader
opening = reader.readline(len(boundary) + 6)
if opening != b"--" + boundary + b"\r\n":
raise ValueError("The multipart request has an invalid opening boundary.")
fields, files = {}, []
try:
final, parts = False, 0
while not final:
parts += 1
if parts > 128: raise ValueError("Too many multipart parts.")
headers = self.multipart_headers(reader)
disposition = headers.get("content-disposition", "")
if disposition.split(";", 1)[0].strip().lower() != "form-data":
raise ValueError("A multipart part is missing form-data disposition.")
params = disposition_parameters(disposition)
field_name = params.get("name")
filename = params.get("filename")
if filename is not None:
if len(files) >= 100: raise ValueError("Too many files in one upload request.")
filename = upload_name(filename.replace("\\", "/").rsplit("/", 1)[-1], self.config["allowed_extensions"])
temporary = tempfile.NamedTemporaryFile(prefix="simple-http-file-browser-", delete=False)
temporary_path = Path(temporary.name)
files.append((filename, temporary_path))
try:
final = self.stream_multipart_part(reader, boundary, temporary)
finally:
temporary.close()
else:
with tempfile.SpooledTemporaryFile(max_size=65536) as field:
final = self.stream_multipart_part(reader, boundary, LimitedWriter(field, 65536))
field.seek(0)
if field_name:
fields[field_name] = field.read().decode("utf-8")
if final:
trailer = reader.read(2)
if trailer not in (b"", b"\r\n"):
raise ValueError("The multipart closing boundary is malformed.")
while reader.read(1024 * 1024): pass
return fields, files
except Exception:
for _name, temporary_path in files:
temporary_path.unlink(missing_ok=True)
raise
def store_uploaded_file(self, source: Path, target: Path, overwrite: bool):
descriptor, temporary_name = tempfile.mkstemp(prefix=f".{target.name}.", suffix=".upload", dir=target.parent)
temporary = Path(temporary_name)
try:
with os.fdopen(descriptor, "wb") as output, source.open("rb") as uploaded:
shutil.copyfileobj(uploaded, output, length=1024 * 1024)
if overwrite:
os.replace(temporary, target)
else:
try:
os.link(temporary, target)
except FileExistsError:
raise FileExistsError(f"{target.name}: an item with the same name already exists.")
temporary.unlink()
finally:
temporary.unlink(missing_ok=True)
def handle_upload(self):
self.upload_stage = "upload lock"
if not self.server.upload_lock.acquire(blocking=False):
raise ValueError("Another upload is in progress. Try again later.")
try:
self.handle_upload_locked()
finally: