-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
1677 lines (1493 loc) · 75 KB
/
server.py
File metadata and controls
1677 lines (1493 loc) · 75 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
"""
Local Network File Sharing Server
- No authentication; all actions audited by client IP.
- Run: python server.py
- Access: http://<your-ip>:5000
"""
import os
import re
import io
import shutil
import zipfile
import mimetypes
import logging
import platform
import configparser
from pathlib import Path
IMAGE_EXTS = frozenset({'.jpg', '.jpeg', '.png', '.gif', '.webp', '.bmp', '.svg'})
VIDEO_EXTS = frozenset({'.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm', '.m4v', '.mpg', '.mpeg'})
def _find_ffmpeg():
"""Return path to ffmpeg: project folder / ffmpeg subfolder first, then system PATH."""
for candidate in [_HERE / "ffmpeg" / "ffmpeg.exe", _HERE / "ffmpeg.exe"]:
if candidate.exists():
return str(candidate)
import shutil
return shutil.which("ffmpeg") or shutil.which("ffmpeg.exe")
from flask import Flask, request, send_file, jsonify, abort, Response
from werkzeug.utils import secure_filename
# ── Configuration ──────────────────────────────────────────────────────────────
_HERE = Path(__file__).parent
_cfg = configparser.ConfigParser()
_cfg.read(_HERE / "config.ini", encoding="utf-8")
_base_path = _cfg.get("server", "base_path", fallback="").strip()
BASE_DIR = (
Path(_base_path).resolve()
if _base_path
else (_HERE / _cfg.get("server", "shared_dir", fallback="./shared")).resolve()
)
AUDIT_LOG = (_HERE / _cfg.get("audit", "log_file", fallback="./audit.log")).resolve()
_HOST = _cfg.get("server", "host", fallback="0.0.0.0")
_PORT = _cfg.getint("server", "port", fallback=80)
_MAX_GB = _cfg.getfloat("server", "max_upload_gb", fallback=10)
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = int(_MAX_GB * 1024 ** 3)
# ── Audit logging ──────────────────────────────────────────────────────────────
audit_logger = logging.getLogger("audit")
audit_logger.setLevel(logging.INFO)
_fh = logging.FileHandler(AUDIT_LOG, encoding="utf-8")
_fh.setFormatter(logging.Formatter("%(asctime)s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S"))
audit_logger.addHandler(_fh)
def audit(action: str, path: str = "", extra: str = ""):
ip = request.environ.get("HTTP_X_FORWARDED_FOR", request.remote_addr)
parts = [ip, action]
if path:
parts.append(path)
if extra:
parts.append(extra)
audit_logger.info(" | ".join(parts))
# ── Path security ──────────────────────────────────────────────────────────────
def safe_path(rel: str) -> Path:
"""Resolve rel within BASE_DIR. Abort 400 on traversal attempts."""
try:
p = (BASE_DIR / rel.lstrip("/\\")).resolve()
except Exception:
abort(400, "Bad path")
base = str(BASE_DIR)
s = str(p)
# Drive roots already end with os.sep (e.g. "C:\"); don't double it.
base_prefix = base if base.endswith(os.sep) else base + os.sep
if s != base and not s.startswith(base_prefix):
abort(400, "Path outside shared directory")
return p
def to_rel(p: Path) -> str:
return str(p.relative_to(BASE_DIR)).replace("\\", "/")
def safe_filename(name: str) -> str:
"""Sanitize filename, preserving unicode but removing dangerous chars."""
name = Path(name).name # strip any directory components
name = re.sub(r'[\x00-\x1f\x7f<>:"/\\|?*]', "_", name)
name = name.lstrip(". ")
return name[:255] if name else "file"
# ── API ────────────────────────────────────────────────────────────────────────
@app.route("/api/list")
def api_list():
path = request.args.get("path", "")
d = safe_path(path)
if not d.exists() or not d.is_dir():
abort(404, "Directory not found")
def _sort_key(p):
try:
return (not p.is_dir(), p.name.lower())
except OSError:
return (True, p.name.lower())
entries = []
try:
items = sorted(d.iterdir(), key=_sort_key)
except PermissionError:
abort(403, "Permission denied reading directory")
for item in items:
try:
st = item.stat()
entries.append({
"name": item.name,
"path": to_rel(item),
"is_dir": item.is_dir(),
"size": st.st_size if item.is_file() else None,
"modified": st.st_mtime,
"is_image": item.is_file() and item.suffix.lower() in IMAGE_EXTS,
"is_video": item.is_file() and item.suffix.lower() in VIDEO_EXTS,
"has_thumb": item.is_file() and item.suffix.lower() in (IMAGE_EXTS | VIDEO_EXTS),
})
except OSError:
pass
return jsonify(path=path or "", entries=entries)
@app.route("/api/download")
def api_download():
path = request.args.get("path", "")
f = safe_path(path)
if not f.is_file():
abort(404, "File not found")
audit("DOWNLOAD", path)
mime, _ = mimetypes.guess_type(f.name)
return send_file(f, mimetype=mime or "application/octet-stream",
as_attachment=True, download_name=f.name)
@app.route("/api/upload", methods=["POST"])
def api_upload():
path = request.args.get("path", "")
d = safe_path(path)
if not d.is_dir():
abort(400, "Target is not a directory")
files = request.files.getlist("files")
if not files:
abort(400, "No files provided")
uploaded = []
for file in files:
name = safe_filename(file.filename or "")
if not name:
continue
dest = d / name
file.save(dest)
audit("UPLOAD", f"{path}/{name}".lstrip("/"))
uploaded.append(name)
return jsonify(uploaded=uploaded)
@app.route("/api/mkdir", methods=["POST"])
def api_mkdir():
data = request.get_json(silent=True) or {}
path = data.get("path", "")
if not path:
abort(400, "Path required")
d = safe_path(path)
if d.exists():
abort(400, "Already exists")
d.mkdir(parents=True)
audit("MKDIR", path)
return jsonify(ok=True)
@app.route("/api/rename", methods=["POST"])
def api_rename():
data = request.get_json(silent=True) or {}
old = data.get("old", "")
new = data.get("new", "")
if not old or not new:
abort(400, "old and new required")
src = safe_path(old)
dst = safe_path(new)
if not src.exists():
abort(404, "Source not found")
if dst.exists():
abort(400, "Destination already exists")
src.rename(dst)
audit("RENAME", old, f"-> {new}")
return jsonify(ok=True)
@app.route("/api/delete", methods=["POST"])
def api_delete():
data = request.get_json(silent=True) or {}
path = data.get("path", "")
if not path:
abort(400, "Path required")
p = safe_path(path)
if not p.exists():
abort(404, "Not found")
if p.is_dir():
def _on_error(func, fpath, _):
os.chmod(fpath, 0o777)
func(fpath)
shutil.rmtree(p, onerror=_on_error)
audit("DELETE_DIR", path)
else:
p.unlink()
audit("DELETE", path)
return jsonify(ok=True)
@app.route("/api/bulk_delete", methods=["POST"])
def api_bulk_delete():
data = request.get_json(silent=True) or {}
paths = data.get("paths", [])
if not paths:
abort(400, "Paths required")
errors = []
for path in paths:
try:
p = safe_path(path)
if not p.exists():
continue
if p.is_dir():
def _onerr(func, fpath, _):
os.chmod(fpath, 0o777); func(fpath)
shutil.rmtree(p, onerror=_onerr)
audit("BULK_DELETE_DIR", path)
else:
p.unlink()
audit("BULK_DELETE", path)
except Exception as e:
errors.append(f"{path}: {e}")
return jsonify(ok=not errors, errors=errors), (207 if errors else 200)
@app.route("/api/zip")
def api_zip():
path = request.args.get("path", "")
d = safe_path(path)
if not d.is_dir():
abort(400, "Not a directory")
audit("ZIP_DOWNLOAD", path)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
for f in d.rglob("*"):
try:
if f.is_file():
z.write(f, f.relative_to(d))
except (PermissionError, OSError):
pass
buf.seek(0)
zip_name = (d.name or "download") + ".zip"
return Response(
buf.read(), mimetype="application/zip",
headers={"Content-Disposition": f'attachment; filename="{zip_name}"'}
)
@app.route("/api/thumb")
def api_thumb():
path = request.args.get("path", "")
f = safe_path(path)
if not f.is_file():
abort(404, "File not found")
ext = f.suffix.lower()
if ext not in IMAGE_EXTS and ext not in VIDEO_EXTS:
abort(400, "Not a supported image or video")
# ── Video thumbnail via ffmpeg ──────────────────────────────────────────
if ext in VIDEO_EXTS:
ffmpeg = _find_ffmpeg()
if not ffmpeg:
abort(501, "ffmpeg not found. Place ffmpeg.exe in the server folder.")
import subprocess
try:
result = subprocess.run(
[ffmpeg, "-ss", "00:00:01", "-i", str(f),
"-vframes", "1", "-vf", "scale=256:-1",
"-f", "image2", "-vcodec", "mjpeg", "pipe:1"],
capture_output=True, timeout=15
)
if result.returncode != 0 or not result.stdout:
abort(500, "ffmpeg failed to extract frame")
resp = Response(result.stdout, mimetype="image/jpeg")
resp.headers["Cache-Control"] = "max-age=3600"
return resp
except subprocess.TimeoutExpired:
abort(500, "ffmpeg timed out")
except Exception as e:
abort(500, f"Video thumbnail error: {e}")
# SVG: serve directly, browsers render natively
if ext == ".svg":
resp = send_file(f, mimetype="image/svg+xml")
resp.headers["Cache-Control"] = "max-age=3600"
return resp
try:
from PIL import Image
with Image.open(f) as img:
img.thumbnail((256, 256), Image.LANCZOS)
buf = io.BytesIO()
if img.mode in ("RGBA", "P", "LA"):
img = img.convert("RGBA")
img.save(buf, format="PNG")
mime = "image/png"
else:
img = img.convert("RGB")
img.save(buf, format="JPEG", quality=82)
mime = "image/jpeg"
buf.seek(0)
resp = Response(buf.read(), mimetype=mime)
resp.headers["Cache-Control"] = "max-age=3600"
return resp
except ImportError:
abort(501, "Pillow not installed. Run: pip install Pillow")
except Exception as e:
abort(500, f"Thumbnail error: {e}")
@app.route("/api/default_pins")
def api_default_pins():
if platform.system() != "Windows":
return jsonify(pins=[])
profile = os.environ.get("USERPROFILE", "")
candidates = [
("Desktop", "🖥️", os.path.join(profile, "Desktop")),
("Downloads", "⬇️", os.path.join(profile, "Downloads")),
("Documents", "📋", os.path.join(profile, "Documents")),
("Pictures", "🖼️", os.path.join(profile, "Pictures")),
("Music", "🎵", os.path.join(profile, "Music")),
("Videos", "🎬", os.path.join(profile, "Videos")),
]
pins = []
for name, icon, abs_path in candidates:
p = Path(abs_path)
if p.exists() and p.is_dir():
try:
rel = p.relative_to(BASE_DIR)
pins.append({"name": name, "icon": icon, "path": str(rel).replace("\\", "/")})
except ValueError:
pass # folder exists but is not under BASE_DIR
return jsonify(pins=pins)
@app.route("/api/ping")
def api_ping():
import socket
try:
ip = socket.gethostbyname(socket.gethostname())
except Exception:
ip = "127.0.0.1"
return jsonify(ok=True, app="LocalWorkStorage", ip=ip, port=_PORT)
@app.route("/api/stats")
def api_stats():
import shutil
result = {}
try:
du = shutil.disk_usage(BASE_DIR)
result["disk"] = {
"total": du.total, "used": du.used, "free": du.free,
"percent": round(du.used / du.total * 100, 1) if du.total else 0,
}
except Exception:
result["disk"] = None
try:
import psutil
result["cpu"] = {"percent": psutil.cpu_percent(interval=0.2)}
vm = psutil.virtual_memory()
result["ram"] = {"total": vm.total, "used": vm.used, "percent": round(vm.percent, 1)}
except ImportError:
result["cpu"] = None
result["ram"] = None
return jsonify(**result)
@app.route("/api/raw")
def api_raw():
"""Serve file inline (no attachment header) so browsers can render images, video, PDF."""
path = request.args.get("path", "")
f = safe_path(path)
if not f.is_file():
abort(404, "File not found")
audit("VIEW", path)
mime, _ = mimetypes.guess_type(f.name)
return send_file(f, mimetype=mime or "application/octet-stream")
@app.route("/api/preview")
def api_preview():
"""Return text file content (≤2 MB) as JSON for inline code/text preview."""
path = request.args.get("path", "")
f = safe_path(path)
if not f.is_file():
abort(404, "File not found")
if f.stat().st_size > 2 * 1024 * 1024:
abort(413, "File too large to preview (max 2 MB)")
audit("PREVIEW", path)
try:
text = f.read_text(encoding="utf-8", errors="replace")
except Exception as e:
abort(500, f"Could not read file: {e}")
return jsonify(content=text, ext=f.suffix.lstrip(".").lower())
@app.route("/api/audit")
def api_audit():
n = min(int(request.args.get("n", 500)), 2000)
if not AUDIT_LOG.exists():
return jsonify(lines=[])
with open(AUDIT_LOG, encoding="utf-8") as f:
lines = f.readlines()
return jsonify(lines=[ln.rstrip() for ln in lines[-n:]])
# ── UI ─────────────────────────────────────────────────────────────────────────
HTML = """<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>File Share</title>
<style>
@font-face { font-family: "Outfit"; src: url("/fonts/Outfit-VariableFont_wght.ttf") format("truetype"); font-weight: 100 900; }
@font-face { font-family: "StackSans"; src: url("/fonts/stacksans.ttf") format("truetype"); font-weight: 100 900; }
@font-face { font-family: "EBGaramond"; src: url("/fonts/EBGaramond.ttf") format("truetype"); font-weight: 400 800; }
@font-face { font-family: "Playwrite"; src: url("/fonts/playwrite.ttf") format("truetype"); font-weight: 400; }
* { box-sizing: border-box; margin: 0; padding: 0; }
body { font-family: "Outfit", sans-serif; background: #f5f5f5; color: #000; min-height: 100vh; }
/* ── Top nav (perekaperabot style) ── */
.topnav { background: #000; border-bottom: 1px solid #1a1a1a; position: sticky; top: 0; z-index: 50; transition: box-shadow .3s ease; }
.topnav.nav-scrolled { box-shadow: 0 2px 24px rgba(0,0,0,.45); }
.topnav-inner { max-width: 1280px; margin: 0 auto; padding: 0 32px; height: 68px; display: flex; align-items: center; justify-content: space-between; gap: 24px; }
.nav-brand { display: flex; align-items: center; gap: 14px; cursor: default; flex-shrink: 0; }
.nav-brand-text { display: flex; flex-direction: column; justify-content: center; line-height: 1; }
.nav-brand-name { font-family: "Outfit", sans-serif; font-size: 19px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; color: #fff; }
.nav-brand-sub { font-family: "Outfit", sans-serif; font-size: 8.5px; color: #a3a3a3; letter-spacing: .18em; text-transform: uppercase; margin-top: 4px; }
.nav-actions { display: flex; align-items: center; gap: 10px; }
.view-toggle { border-color: #333; }
.view-btn { color: #666; }
.view-btn:hover { background: #1a1a1a; color: #fff; }
.view-btn.active { background: #FFCE1B; color: #000; }
.btn-log { color: #666; border-color: #333; }
.btn-log:hover { background: #1a1a1a; color: #fff; }
.toolbar { display: flex; align-items: center; gap: 10px; margin-bottom: 14px; flex-wrap: wrap; }
.breadcrumb { display: flex; align-items: center; gap: 4px; flex-wrap: wrap; font-size: 14px; flex: 1; min-width: 0; }
.breadcrumb a { color: #000; text-decoration: none; font-weight: 500; cursor: pointer; }
.breadcrumb a:hover { text-decoration: underline; color: #525252; }
.breadcrumb .sep { color: #a3a3a3; }
.breadcrumb .cur { color: #000; font-weight: 600; }
.btn { display: inline-flex; align-items: center; gap: 5px; padding: 7px 14px; border: none; border-radius: 6px; font-size: 13px; font-weight: 500; cursor: pointer; transition: background .15s, opacity .15s; text-decoration: none; white-space: nowrap; }
.btn:disabled { opacity: .5; cursor: not-allowed; }
.btn-primary { background: #FFCE1B; color: #000; }
.btn-primary:hover:not(:disabled) { background: #e6b800; }
.btn-secondary { background: #000; color: #fff; }
.btn-secondary:hover:not(:disabled) { background: #222; }
.btn-danger { background: #ef4444; color: #fff; border: 1px solid #ef4444; }
.btn-danger:hover:not(:disabled) { background: #dc2626; border-color: #dc2626; }
.btn-ghost { background: transparent; color: #525252; border: 1px solid #e5e5e5; }
.btn-ghost:hover:not(:disabled) { background: #f5f5f5; }
.btn-sm { padding: 4px 10px; font-size: 12px; }
.btn-log { background: transparent; color: #a3a3a3; border: 1px solid #525252; }
.btn-log:hover { background: #222; color: #fff; }
.btn-back { background: #000; color: #fff; border: 1px solid #000; }
.btn-back:hover:not(:disabled) { background: #333; border-color: #333; }
.view-toggle { display: flex; border: 1px solid #525252; border-radius: 6px; overflow: hidden; }
.view-btn { padding: 6px 12px; background: transparent; border: none; color: #a3a3a3; cursor: pointer; font-size: 13px; font-weight: 500; transition: background .12s, color .12s; }
.view-btn:hover { background: #222; color: #fff; }
.view-btn.active { background: #FFCE1B; color: #000; }
.page-layout { display: flex; min-height: calc(100vh - 68px); }
.sidebar { width: 220px; flex-shrink: 0; background: #fff; border-right: 1px solid #e5e5e5; position: sticky; top: 68px; height: calc(100vh - 68px); overflow-y: auto; display: flex; flex-direction: column; }
.sidebar-header { padding: 18px 16px 8px; font-size: 10px; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; color: #a3a3a3; flex-shrink: 0; }
.pin-item { display: flex; align-items: center; gap: 8px; padding: 9px 14px; font-size: 13px; cursor: pointer; color: #000; transition: background .1s; overflow: hidden; user-select: none; }
.pin-item:hover { background: #f5f5f5; }
.pin-item.pin-active { background: #FFCE1B; font-weight: 600; }
.pin-item.pin-active:hover { background: #e6b800; }
.pin-item-icon { flex-shrink: 0; font-size: 15px; line-height: 1; }
.pin-item-name { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.pin-remove { opacity: 0; flex-shrink: 0; font-size: 16px; line-height: 1; color: #a3a3a3; cursor: pointer; padding: 0 2px; transition: opacity .12s, color .12s; }
.pin-item:hover .pin-remove { opacity: 1; }
.pin-remove:hover { color: #ef4444; }
.pin-empty { padding: 14px 16px; font-size: 12px; color: #a3a3a3; line-height: 1.6; }
.pin-home { font-weight: 600; margin-top: 4px; }
.pin-home.pin-active { background: #FFCE1B; }
.sidebar-sep { height: 1px; background: #e5e5e5; margin: 6px 0; }
.main { flex: 1; min-width: 0; padding: 24px; }
/* ── Search ── */
.search-wrap { position: relative; }
.search-wrap input { padding: 7px 28px 7px 12px; border: 1px solid #e5e5e5; border-radius: 6px; font-size: 13px; font-family: inherit; outline: none; width: 190px; transition: border-color .15s, width .2s; }
.search-wrap input:focus { border-color: #FFCE1B; width: 240px; }
.search-clear { position: absolute; right: 7px; top: 50%; transform: translateY(-50%); background: none; border: none; cursor: pointer; color: #a3a3a3; font-size: 15px; display: none; padding: 0; }
.search-clear.vis { display: block; }
/* ── Bulk action bar ── */
.bulk-bar { display: none; align-items: center; gap: 10px; background: #FFCE1B; padding: 9px 14px; border-radius: 8px; margin-bottom: 12px; font-size: 13px; font-weight: 600; animation: fadeIn .15s ease; }
.bulk-bar.active { display: flex; }
.bulk-spacer { flex: 1; }
/* ── Sortable table headers ── */
thead th.sortable { cursor: pointer; user-select: none; }
thead th.sortable:hover { background: #ececec; }
.sort-ic { margin-left: 3px; opacity: .3; font-size: 10px; }
.sort-ic.on { opacity: 1; }
.th-cb { width: 36px; padding: 11px 8px !important; }
/* ── Selection ── */
.sel-cb, .card-cb { width: 15px; height: 15px; cursor: pointer; accent-color: #000; }
.sel-row { background: #fffde7 !important; }
.file-card.selected { outline: 2px solid #FFCE1B; outline-offset: -2px; }
.card-cb-wrap { position: absolute; top: 6px; left: 6px; z-index: 2; opacity: 0; transition: opacity .15s; pointer-events: none; background: rgba(255,255,255,.85); border-radius: 4px; padding: 2px; }
.file-card:hover .card-cb-wrap, .file-card.selected .card-cb-wrap { opacity: 1; pointer-events: auto; }
.drop-zone { border: 2px dashed #FFCE1B; border-radius: 10px; padding: 24px; text-align: center; color: #000; margin-bottom: 16px; font-size: 14px; background: #fffde7; transition: background .15s; display: none; }
.drop-zone.drag-over { background: #fff3b0; border-color: #e6b800; }
.drop-zone label { cursor: pointer; text-decoration: underline; }
.upload-progress { margin-bottom: 16px; }
.progress-item { background: #fff; border-radius: 8px; padding: 10px 14px; margin-bottom: 6px; box-shadow: 0 1px 3px rgba(0,0,0,.06); font-size: 13px; }
.progress-item .row { display: flex; justify-content: space-between; margin-bottom: 5px; }
.progress-bar-wrap { background: #e5e5e5; border-radius: 99px; height: 5px; overflow: hidden; }
.progress-bar { background: #FFCE1B; height: 100%; border-radius: 99px; transition: width .15s; }
.progress-item.done .progress-bar { background: #10b981; }
.progress-item.error .progress-bar { background: #ef4444; }
/* ── File container card ── */
.card { background: #fff; border-radius: 10px; box-shadow: 0 1px 4px rgba(0,0,0,.06); overflow: hidden; }
/* ── List view ── */
.table-wrap { overflow-x: auto; }
table { width: 100%; border-collapse: collapse; font-size: 14px; }
thead th { background: #f5f5f5; font-weight: 600; color: #525252; padding: 11px 16px; text-align: left; border-bottom: 1px solid #e5e5e5; white-space: nowrap; }
tbody tr { border-bottom: 1px solid #f5f5f5; transition: background .08s; }
tbody tr:last-child { border-bottom: none; }
tbody tr:hover { background: #f5f5f5; }
td { padding: 9px 16px; vertical-align: middle; }
.td-name { display: flex; align-items: center; gap: 10px; }
.td-name a { color: #000; text-decoration: none; font-weight: 500; cursor: pointer; }
.td-name a:hover { text-decoration: underline; color: #525252; }
.td-actions { display: flex; gap: 5px; justify-content: flex-end; white-space: nowrap; }
.list-icon { width: 22px; height: 22px; flex-shrink: 0; display: flex; align-items: center; justify-content: center; font-size: 18px; line-height: 1; }
.list-icon img { width: 20px; height: 20px; display: block; }
.text-muted { color: #a3a3a3; font-size: 13px; }
.empty-state { text-align: center; padding: 56px; color: #a3a3a3; }
.empty-state .big { font-size: 40px; margin-bottom: 10px; }
/* ── Grid / Thumb view ── */
.grid-wrap { padding: 16px; }
.grid-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(148px, 1fr)); gap: 12px; }
.file-card { position: relative; background: #fff; border-radius: 10px; border: 1px solid #e5e5e5; cursor: pointer; transition: box-shadow .15s, transform .12s; display: flex; flex-direction: column; overflow: hidden; user-select: none; }
.file-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.1); transform: translateY(-2px); }
.card-preview { display: flex; align-items: center; justify-content: center; height: 110px; background: #f5f5f5; font-size: 52px; line-height: 1; overflow: hidden; flex-shrink: 0; }
.card-preview.folder-bg { background: #fffde7; }
.card-preview img { width: 100%; height: 100%; object-fit: cover; display: block; }
.card-body { padding: 8px 10px 10px; }
.card-name { font-size: 12.5px; font-weight: 500; color: #000; word-break: break-all; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; line-height: 1.35; }
.card-meta { font-size: 11px; color: #a3a3a3; margin-top: 4px; }
.card-actions { position: absolute; top: 6px; right: 6px; display: flex; gap: 3px; opacity: 0; transition: opacity .15s; pointer-events: none; }
.file-card:hover .card-actions { opacity: 1; pointer-events: auto; }
.cab { background: rgba(0,0,0,.72); backdrop-filter: blur(4px); color: #fff; border: none; border-radius: 5px; padding: 4px 8px; font-size: 12px; cursor: pointer; }
.cab:hover { background: rgba(0,0,0,.95); }
.cab.danger { background: rgba(220,38,38,.8); }
.cab.danger:hover { background: rgba(185,28,28,.95); }
/* ── Modals ── */
.modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.5); z-index: 100; display: flex; align-items: center; justify-content: center; padding: 16px; }
.modal { background: #fff; border-radius: 12px; padding: 24px; width: 100%; max-width: 440px; box-shadow: 0 20px 60px rgba(0,0,0,.2); }
.modal h2 { font-size: 16px; font-weight: 600; margin-bottom: 16px; }
.modal p { font-size: 14px; color: #525252; line-height: 1.5; }
.modal input { width: 100%; padding: 9px 12px; border: 1px solid #e5e5e5; border-radius: 6px; font-size: 14px; outline: none; margin-top: 2px; }
.modal input:focus { border-color: #FFCE1B; box-shadow: 0 0 0 3px rgba(255,206,27,.2); }
.modal-actions { display: flex; gap: 8px; justify-content: flex-end; margin-top: 18px; }
.audit-modal { max-width: 760px; }
.audit-toolbar { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; }
.audit-body { font-family: "Consolas", "Courier New", monospace; font-size: 12px; background: #000; color: #a3a3a3; padding: 12px 14px; border-radius: 8px; height: 420px; overflow-y: auto; white-space: pre; line-height: 1.6; }
.toast-container { position: fixed; bottom: 24px; right: 24px; z-index: 200; display: flex; flex-direction: column; gap: 8px; }
.toast { padding: 11px 18px; border-radius: 8px; font-size: 14px; font-weight: 500; box-shadow: 0 4px 16px rgba(0,0,0,.15); animation: slideIn .2s ease; color: #fff; max-width: 320px; }
.toast.success { background: #10b981; }
.toast.error { background: #ef4444; }
@keyframes slideIn { from { transform: translateX(120%); opacity: 0; } to { transform: none; opacity: 1; } }
/* ── Tooltip button ── */
.tip-btn { position: relative; }
.tip-btn::after { content: attr(data-tip); position: absolute; top: calc(100% + 7px); left: 50%; transform: translateX(-50%); background: #000; color: #fff; font-size: 11px; white-space: nowrap; padding: 5px 10px; border-radius: 5px; pointer-events: none; opacity: 0; transition: opacity .15s; z-index: 10; }
.tip-btn:hover::after { opacity: 1; }
/* ── Context menu ── */
#ctx-menu { position: fixed; background: #fff; border: 1px solid #e5e5e5; border-radius: 8px; box-shadow: 0 8px 32px rgba(0,0,0,.12); z-index: 400; min-width: 168px; padding: 4px 0; display: none; animation: fadeUp .14s cubic-bezier(.22,1,.36,1); }
#ctx-menu li { list-style: none; padding: 9px 16px; font-size: 13px; cursor: pointer; display: flex; align-items: center; gap: 10px; color: #000; transition: background .1s; user-select: none; }
#ctx-menu li:hover { background: #f5f5f5; }
#ctx-menu li.ctx-danger { color: #ef4444; }
#ctx-menu li.ctx-danger:hover { background: #fff5f5; }
#ctx-menu .ctx-sep { height: 1px; background: #e5e5e5; margin: 4px 8px; }
@keyframes fadeUp { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
@keyframes modalIn { from { opacity: 0; transform: scale(.96) translateY(8px); } to { opacity: 1; transform: none; } }
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
.main { animation: fadeIn .25s ease; overflow-x: hidden; }
.anim { opacity: 0; animation: fadeUp .3s cubic-bezier(.22,1,.36,1) forwards; }
.modal { animation: modalIn .2s cubic-bezier(.22,1,.36,1); }
.btn { transition: background .15s, opacity .15s, transform .1s, box-shadow .15s; }
.btn:hover:not(:disabled) { transform: translateY(-1px); }
.btn:active:not(:disabled) { transform: translateY(0); }
/* ── Home stats dashboard ── */
.home-stats { margin-bottom: 20px; }
.home-section-label { font-size: 10px; font-weight: 700; letter-spacing: .14em; text-transform: uppercase; color: #a3a3a3; margin-bottom: 10px; }
.stats-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; margin-bottom: 20px; }
.stat-card { background: #fff; border-radius: 10px; box-shadow: 0 1px 4px rgba(0,0,0,.06); padding: 18px 20px; }
.stat-label { font-size: 10px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; color: #a3a3a3; margin-bottom: 8px; }
.stat-value { font-size: 26px; font-weight: 700; color: #000; line-height: 1.1; }
.stat-sub { font-size: 12px; color: #a3a3a3; margin-top: 4px; }
.stat-bar-wrap { background: #e5e5e5; border-radius: 99px; height: 5px; margin-top: 12px; overflow: hidden; }
.stat-bar { height: 100%; border-radius: 99px; background: #FFCE1B; transition: width .5s ease; }
.stat-bar.warn { background: #f97316; }
.stat-bar.crit { background: #ef4444; }
.pins-home-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(130px, 1fr)); gap: 10px; }
.pin-home-card { background: #fff; border-radius: 10px; border: 1px solid #e5e5e5; padding: 16px 12px; cursor: pointer; transition: box-shadow .15s, transform .12s; display: flex; flex-direction: column; align-items: center; gap: 6px; text-align: center; }
.pin-home-card:hover { box-shadow: 0 6px 20px rgba(0,0,0,.1); transform: translateY(-2px); }
.pin-home-icon { font-size: 30px; line-height: 1; }
.pin-home-name { font-size: 12.5px; font-weight: 500; color: #000; word-break: break-word; }
/* ── Preview modal ── */
.prev-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.88); z-index: 300; display: flex; flex-direction: column; }
.prev-header { display: flex; align-items: center; gap: 12px; padding: 10px 16px; background: #111; color: #fff; flex-shrink: 0; border-bottom: 1px solid #222; }
.prev-title { flex: 1; font-size: 14px; font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.prev-close { background: none; border: none; color: #aaa; font-size: 26px; cursor: pointer; padding: 0 4px; line-height: 1; }
.prev-close:hover { color: #FFCE1B; }
.prev-body { flex: 1; overflow: hidden; display: flex; align-items: center; justify-content: center; position: relative; min-height: 0; background: #0d0d0d; }
.prev-content { width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; overflow: auto; }
.prev-nav { position: absolute; top: 50%; transform: translateY(-50%); background: rgba(0,0,0,.55); color: #fff; border: none; border-radius: 50%; width: 44px; height: 44px; font-size: 20px; cursor: pointer; z-index: 1; transition: background .15s; display: flex; align-items: center; justify-content: center; }
.prev-nav:hover { background: rgba(0,0,0,.9); }
.prev-nav-prev { left: 14px; }
.prev-nav-next { right: 14px; }
.prev-img { max-width: 100%; max-height: 100%; object-fit: contain; display: block; }
.prev-video { max-width: 100%; max-height: 100%; display: block; outline: none; }
.prev-pdf { width: 100%; height: 100%; border: none; display: block; }
.prev-code { margin: 0; padding: 24px 28px; background: #1e1e1e; color: #d4d4d4; font-family: "Consolas","Courier New",monospace; font-size: 13px; line-height: 1.65; overflow: auto; width: 100%; height: 100%; white-space: pre; tab-size: 4; box-sizing: border-box; }
.prev-footer { display: flex; align-items: center; justify-content: center; padding: 8px; background: #111; color: #555; font-size: 12px; flex-shrink: 0; border-top: 1px solid #222; }
</style>
</head>
<body>
<nav class="topnav" id="topnav">
<div class="topnav-inner">
<div class="nav-brand">
<div class="nav-brand-text">
<span class="nav-brand-name">LocalWorkStorage</span>
<span class="nav-brand-sub">A tool to manage shared files on local network</span>
</div>
</div>
<div class="nav-actions">
<div class="view-toggle">
<button class="view-btn" data-view="list" onclick="setView('list')" title="List view">List</button>
<button class="view-btn" data-view="grid" onclick="setView('grid')" title="Grid view">Grid</button>
<button class="view-btn" data-view="thumb" onclick="setView('thumb')" title="Thumbnail view">Thumb</button>
</div>
<button class="btn btn-log" onclick="openAudit()">Audit Log</button>
</div>
</div>
</nav>
<div id="ctx-menu"></div>
<div class="page-layout">
<aside class="sidebar" id="sidebar">
<div class="pin-item pin-home" id="sidebar-home" onclick="navigate('')">
<span class="pin-item-icon">🏠</span>
<span class="pin-item-name">Home</span>
</div>
<div class="sidebar-sep"></div>
<div class="sidebar-header">Pinned Folders</div>
<div id="pin-list"><p class="pin-empty">No pins yet.<br>Right-click a folder to pin it.</p></div>
</aside>
<div class="main">
<div class="toolbar">
<button class="btn btn-ghost btn-back" id="btn-back" onclick="goBack()" style="display:none">← Back</button>
<nav class="breadcrumb" id="breadcrumb"></nav>
<div class="search-wrap">
<input id="search-input" type="search" placeholder="Search..." oninput="onSearch(this.value)" autocomplete="off">
<button class="search-clear" id="search-clear" onclick="clearSearch()">×</button>
</div>
<button class="btn btn-primary tip-btn" data-tip="Upload files" onclick="openUpload()">⇧ Upload</button>
<button class="btn btn-secondary tip-btn" data-tip="New folder" onclick="openMkdir()">+ New Folder</button>
</div>
<div id="bulk-bar" class="bulk-bar">
<span id="bulk-count">0 selected</span>
<span class="bulk-spacer"></span>
<button class="btn btn-secondary btn-sm" onclick="clearSel()">× Clear</button>
<button class="btn btn-danger btn-sm" onclick="bulkDelete()">🗑 Delete selected</button>
</div>
<div id="upload-progress" class="upload-progress"></div>
<div id="drop-zone" class="drop-zone">
<div style="font-size:32px;margin-bottom:8px">⇧</div>
Drop files here to upload, or <label for="file-input">browse</label>
<input type="file" id="file-input" multiple style="display:none" onchange="handleFileInput(this)">
</div>
<div id="home-stats" class="home-stats" style="display:none">
<p class="home-section-label">System</p>
<div id="stats-grid" class="stats-grid"></div>
<div id="home-pins-section" style="display:none">
<p class="home-section-label">Pinned Folders</p>
<div id="home-pins-grid" class="pins-home-grid"></div>
</div>
</div>
<div id="file-container" class="card"></div>
</div><!-- .main -->
</div><!-- .page-layout -->
<!-- Rename modal -->
<div id="modal-rename" class="modal-backdrop" style="display:none" onclick="closeModal('modal-rename')">
<div class="modal" onclick="event.stopPropagation()">
<h2>Rename</h2>
<input type="text" id="rename-input" placeholder="New name"
onkeydown="if(event.key==='Enter')doRename(); if(event.key==='Escape')closeModal('modal-rename')">
<div class="modal-actions">
<button class="btn btn-ghost" onclick="closeModal('modal-rename')">Cancel</button>
<button class="btn btn-primary" onclick="doRename()">Rename</button>
</div>
</div>
</div>
<!-- New folder modal -->
<div id="modal-mkdir" class="modal-backdrop" style="display:none" onclick="closeModal('modal-mkdir')">
<div class="modal" onclick="event.stopPropagation()">
<h2>New Folder</h2>
<input type="text" id="mkdir-input" placeholder="Folder name"
onkeydown="if(event.key==='Enter')doMkdir(); if(event.key==='Escape')closeModal('modal-mkdir')">
<div class="modal-actions">
<button class="btn btn-ghost" onclick="closeModal('modal-mkdir')">Cancel</button>
<button class="btn btn-primary" onclick="doMkdir()">Create</button>
</div>
</div>
</div>
<!-- Delete confirm modal -->
<div id="modal-delete" class="modal-backdrop" style="display:none" onclick="closeModal('modal-delete')">
<div class="modal" onclick="event.stopPropagation()">
<h2>Confirm Delete</h2>
<p id="delete-msg"></p>
<div class="modal-actions">
<button class="btn btn-ghost" onclick="closeModal('modal-delete')">Cancel</button>
<button class="btn btn-danger" onclick="doDelete()">Delete</button>
</div>
</div>
</div>
<!-- Audit log modal -->
<div id="modal-audit" class="modal-backdrop" style="display:none" onclick="closeModal('modal-audit')">
<div class="modal audit-modal" onclick="event.stopPropagation()">
<div class="audit-toolbar">
<h2>Audit Log</h2>
<button class="btn btn-ghost btn-sm" onclick="loadAudit()">Refresh</button>
</div>
<div class="audit-body" id="audit-body">Loading...</div>
<div class="modal-actions">
<button class="btn btn-ghost" onclick="closeModal('modal-audit')">Close</button>
</div>
</div>
</div>
<!-- Preview modal -->
<div id="modal-preview" class="prev-backdrop" style="display:none">
<div class="prev-header">
<button class="prev-close" onclick="closePreview()" title="Close (Esc)">×</button>
<span class="prev-title" id="prev-title"></span>
<a id="prev-dl" class="btn btn-ghost btn-sm" href="#" title="Download" style="border-color:#444;color:#aaa">⇩ Download</a>
</div>
<div class="prev-body">
<button class="prev-nav prev-nav-prev" id="prev-btn-prev" onclick="prevPreview()" title="Previous (←)">←</button>
<div id="prev-content" class="prev-content"></div>
<button class="prev-nav prev-nav-next" id="prev-btn-next" onclick="nextPreview()" title="Next (→)">→</button>
</div>
<div class="prev-footer"><span id="prev-counter"></span></div>
</div>
<div class="toast-container" id="toasts"></div>
<script>
let currentPath = '';
let pendingRename = null;
let pendingDelete = null;
let lastEntries = [];
let currentView = localStorage.getItem('fs_view') || 'list';
// ── View toggle ────────────────────────────────────────────────────────────
function setView(v) {
currentView = v;
localStorage.setItem('fs_view', v);
document.querySelectorAll('.view-btn').forEach(b =>
b.classList.toggle('active', b.dataset.view === v));
renderFiles(lastEntries);
}
function initViewToggle() {
document.querySelectorAll('.view-btn').forEach(b =>
b.classList.toggle('active', b.dataset.view === currentView));
}
// ── Navigation ─────────────────────────────────────────────────────────────
function navigate(path) {
currentPath = path;
_sel.clear(); updateBulkBar();
_search = ''; document.getElementById('search-input').value = ''; document.getElementById('search-clear').classList.remove('vis');
loadDir(path);
updateBreadcrumb(path);
document.getElementById('btn-back').style.display = path ? '' : 'none';
renderPins();
if (path === '') { loadHomeStats(); }
else {
document.getElementById('home-stats').style.display = 'none';
if (_statsTimer) { clearInterval(_statsTimer); _statsTimer = null; }
}
}
function goBack() {
var parts = currentPath ? currentPath.split('/') : [];
parts.pop();
navigate(parts.join('/'));
}
function updateBreadcrumb(path) {
const bc = document.getElementById('breadcrumb');
const parts = path ? path.split('/') : [];
let html = '<a onclick="navigate(\\'\\')">Home</a>';
let acc = '';
parts.forEach((p, i) => {
acc += (acc ? '/' : '') + p;
const cap = acc;
html += '<span class="sep"> / </span>';
if (i === parts.length - 1) {
html += '<span class="cur">' + esc(p) + '</span>';
} else {
html += '<a data-path="' + esc(cap) + '" onclick="navigate(this.dataset.path)">' + esc(p) + '</a>';
}
});
bc.innerHTML = html;
}
async function loadDir(path) {
const res = await fetch('/api/list?path=' + encodeURIComponent(path));
if (!res.ok) { toast('Failed to load directory', 'error'); return; }
const data = await res.json();
lastEntries = data.entries;
renderFiles(lastEntries);
}
// ── Sort ───────────────────────────────────────────────────────────────────
var _sort = { field: 'name', dir: 'asc' };
function setSort(field) {
_sort.dir = (_sort.field === field && _sort.dir === 'asc') ? 'desc' : 'asc';
_sort.field = field;
renderFiles(lastEntries);
}
function sortEntries(entries) {
return entries.slice().sort(function(a, b) {
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
var av, bv;
if (_sort.field === 'size') { av = a.size || 0; bv = b.size || 0; }
else if (_sort.field === 'modified') { av = a.modified || 0; bv = b.modified || 0; }
else { av = a.name.toLowerCase(); bv = b.name.toLowerCase(); }
var cmp = av < bv ? -1 : av > bv ? 1 : 0;
return _sort.dir === 'asc' ? cmp : -cmp;
});
}
// ── Search / filter ────────────────────────────────────────────────────────
var _search = '';
function onSearch(val) {
_search = val.trim();
document.getElementById('search-clear').classList.toggle('vis', !!_search);
renderFiles(lastEntries);
}
function clearSearch() {
_search = '';
document.getElementById('search-input').value = '';
document.getElementById('search-clear').classList.remove('vis');
renderFiles(lastEntries);
}
function filterEntries(entries) {
if (!_search) return entries;
var q = _search.toLowerCase();
return entries.filter(function(e) { return e.name.toLowerCase().indexOf(q) !== -1; });
}
// ── Bulk selection ─────────────────────────────────────────────────────────
var _sel = new Set();
function toggleSel(path, checked) {
checked ? _sel.add(path) : _sel.delete(path);
updateBulkBar();
}
function toggleCardSel(el, path) {
el.closest('.file-card').classList.toggle('selected', el.checked);
toggleSel(path, el.checked);
}
function toggleSelAll(checked) {
document.querySelectorAll('.sel-cb[data-path]').forEach(function(cb) {
cb.checked = checked;
checked ? _sel.add(cb.dataset.path) : _sel.delete(cb.dataset.path);
});
document.querySelectorAll('.file-card[data-path]').forEach(function(c) {
c.classList.toggle('selected', checked);
var cb = c.querySelector('.card-cb');
if (cb) cb.checked = checked;
checked ? _sel.add(c.dataset.path) : _sel.delete(c.dataset.path);
});
updateBulkBar();
}
function clearSel() {
_sel.clear();
document.querySelectorAll('.sel-cb, .card-cb').forEach(function(cb) { cb.checked = false; });
document.querySelectorAll('.file-card.selected').forEach(function(c) { c.classList.remove('selected'); });
updateBulkBar();
}
function updateBulkBar() {
var n = _sel.size;
document.getElementById('bulk-bar').classList.toggle('active', n > 0);
document.getElementById('bulk-count').textContent = n + ' selected';
}
async function bulkDelete() {
var n = _sel.size;
if (!n) return;
if (!confirm('Delete ' + n + ' item' + (n > 1 ? 's' : '') + '? This cannot be undone.')) return;
const res = await fetch('/api/bulk_delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ paths: Array.from(_sel) })
});
if (res.ok || res.status === 207) {
toast('Deleted ' + n + ' item' + (n > 1 ? 's' : ''), 'success');
_sel.clear(); updateBulkBar(); loadDir(currentPath);
} else { toast('Delete failed', 'error'); }
}
function zipFolder(path) {
location.href = '/api/zip?path=' + encodeURIComponent(path);
}
function renderFiles(entries) {
lastEntries = entries;
var processed = sortEntries(filterEntries(entries));
if (currentView === 'list') renderList(processed);
else renderGrid(processed, currentView === 'thumb');
}
// ── List view ──────────────────────────────────────────────────────────────
function renderList(entries) {
const c = document.getElementById('file-container');
const empty = _search
? '<div class="empty-state"><div class="big">🔍</div>No results for “' + esc(_search) + '”</div>'
: '<div class="empty-state"><div class="big">📂</div>This folder is empty</div>';
if (!entries.length) { c.innerHTML = empty; return; }
function si(field) {
if (_sort.field !== field) return '<span class="sort-ic">↕</span>';
return '<span class="sort-ic on">' + (_sort.dir === 'asc' ? '↑' : '↓') + '</span>';
}
c.innerHTML =
'<div class="table-wrap"><table>' +
'<thead><tr>' +
'<th class="th-cb"><input type="checkbox" class="sel-cb" id="sel-all" onchange="toggleSelAll(this.checked)"></th>' +
'<th class="sortable" data-sort="name" onclick="setSort(this.dataset.sort)" style="width:99%">Name ' + si('name') + '</th>' +
'<th class="sortable" data-sort="size" onclick="setSort(this.dataset.sort)" style="min-width:90px">Size ' + si('size') + '</th>' +
'<th class="sortable" data-sort="modified" onclick="setSort(this.dataset.sort)" style="min-width:160px">Modified ' + si('modified') + '</th>' +
'<th style="min-width:150px;text-align:right">Actions</th>' +
'</tr></thead><tbody>' +