bruschetta

A simple golang web based file browser
Log | Files | Refs | LICENSE

main.go (20682B)


      1 package main
      2 
      3 import (
      4 	"bytes"
      5 	"encoding/json"
      6 	"flag"
      7 	"fmt"
      8 	"html/template"
      9 	"image"
     10 	"image/color"
     11 	"image/draw"
     12 	"image/jpeg"
     13 	_ "image/gif"
     14 	_ "image/png"
     15 	"log"
     16 	"net/http"
     17 	"net/url"
     18 	"os"
     19 	"os/exec"
     20 	"path/filepath"
     21 	"sort"
     22 	"strings"
     23 	"time"
     24 )
     25 
     26 var rootDir string
     27 
     28 type FileEntry struct {
     29 	Name    string
     30 	Path    string
     31 	IsDir   bool
     32 	Size    int64
     33 	ModTime time.Time
     34 	Ext     string
     35 }
     36 
     37 type TreeNode struct {
     38 	Name     string      `json:"name"`
     39 	Path     string      `json:"path"`
     40 	Children []*TreeNode `json:"children,omitempty"`
     41 }
     42 
     43 type Breadcrumb struct {
     44 	Name string
     45 	Path string
     46 }
     47 
     48 type PageData struct {
     49 	CurrentPath string
     50 	Breadcrumbs []Breadcrumb
     51 	Files       []FileEntry
     52 	TreeJSON    template.JS
     53 	View        string
     54 }
     55 
     56 const tmpl = `<!DOCTYPE html>
     57 <html lang="en">
     58 <head>
     59 <meta charset="UTF-8">
     60 <meta name="viewport" content="width=device-width, initial-scale=1.0">
     61 <title>{{ .CurrentPath }}</title>
     62 <style>
     63 *,::after,::before{box-sizing:border-box;margin:0;padding:0;list-style:none}
     64 a:hover{text-decoration:underline}
     65 body,html{height:100%;overflow:hidden}
     66 body{background:#1a1a1a;color:#d4d4d4;font-family:Consolas,Menlo,'DejaVu Sans Mono',monospace;font-size:13px;display:flex;flex-direction:column}
     67 footer{padding:6px 16px;color:#777}
     68 header{border-bottom:1px solid #333;padding:10px 16px;display:flex;align-items:center;gap:12px}
     69 main{flex:1;overflow-y:auto}
     70 @media (max-width: 640px) { .sidebar { display: none; } .file-table td.date { display: none; } .file-table td.size { min-width: 50px; } .thumb-grid { grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; padding: 8px; } }
     71 .breadcrumb .current{color:#777}
     72 .breadcrumb .sep{color:#777;margin:0 2px}
     73 .breadcrumb a,.file-table thead th:hover,.thumb-label a{color:#d4d4d4}
     74 .breadcrumb a:hover,.thumb-label a:hover,a{color:#5b9bd5;text-decoration:none}
     75 .breadcrumb,.tree-item,.view-toggle{display:flex;gap:4px}
     76 .breadcrumb{align-items:center;flex-wrap:wrap;flex:1}
     77 .empty{padding:48px;text-align:center;color:#777}
     78 .file-icon.dir,.thumb-preview .dir-icon{color:#c8a94e}
     79 .file-icon.img{color:#7cbf7c}
     80 .file-icon{margin-right:6px;color:#777}
     81 .file-table tbody tr,.file-table thead th{border-bottom:1px solid #333}
     82 .file-table tbody tr:hover,.tree-item.active,.tree-item:hover{background:#2e2e2e}
     83 .file-table td.date{color:#777;min-width:130px}
     84 .file-table td.name{width:100%;white-space:normal;word-break:break-all}
     85 .file-table td.size{color:#777;text-align:right;min-width:70px}
     86 .file-table td{padding:7px 12px;white-space:nowrap}
     87 .file-table thead th,.tree-item{cursor:pointer;user-select:none;white-space:nowrap}
     88 .file-table thead th.sort-asc::after{content:' ↑';color:#5b9bd5}
     89 .file-table thead th.sort-desc::after{content:' ↓';color:#5b9bd5}
     90 .file-table thead th{background:#222;padding:8px 12px;text-align:left;font-weight:400;color:#777;font-size:11px;letter-spacing:.08em;text-transform:uppercase}
     91 .file-table thead{position:sticky;top:0}
     92 .file-table{width:100%;border-collapse:collapse}
     93 .layout{display:flex;flex:1;overflow:hidden}
     94 .sidebar,.thumb-item,footer,header{background:#222}
     95 .sidebar{width:220px;min-width:220px;border-right:1px solid #333;overflow-y:auto;overflow-x:hidden;padding:8px 0;flex-shrink:0}
     96 .sidebar-title{font-size:10px;letter-spacing:.1em;color:#777;padding:4px 12px 8px;text-transform:uppercase}
     97 .thumb-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:12px;padding:16px}
     98 .thumb-item:hover{border-color:#5b9bd5}
     99 .thumb-item{border:1px solid #333;overflow:hidden}
    100 .thumb-item a,.thumb-item a:hover{text-decoration:none}
    101 .thumb-label,footer{border-top:1px solid #333;font-size:11px}
    102 .thumb-label{padding:6px 8px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
    103 .thumb-meta{font-size:10px;color:#777;padding:0 8px 6px}
    104 .thumb-preview .big-icon{font-size:36px;color:#777}
    105 .thumb-preview img{width:100%;height:100%;object-fit:cover}
    106 .thumb-preview{width:100%;height:110px;display:flex;align-items:center;justify-content:center;background:#2a2a2a;overflow:hidden}
    107 .tree-children.open{display:block}
    108 .tree-children{display:none;padding-left:12px}
    109 .tree-icon{color:#777;flex-shrink:0}
    110 .tree-item.active{color:#5b9bd5}
    111 .tree-item{align-items:center;padding:3px 8px;overflow:hidden;color:#d4d4d4;font-size:12px}
    112 .tree-label{overflow:hidden;text-overflow:ellipsis}
    113 .tree-toggle{width:12px;text-align:center;color:#777;flex-shrink:0;font-size:10px}
    114 .view-toggle button.active{background:#1a1a1a;color:#5b9bd5;border-color:#5b9bd5}
    115 .view-toggle button:hover{background:#2e2e2e;color:#d4d4d4}
    116 .view-toggle button{background:#2a2a2a;border:1px solid #333;color:#777;padding:4px 10px;cursor:pointer;font-size:12px;font-family:inherit}
    117 .view-toggle{margin-left:auto}
    118 .filter-box{display:flex;align-items:center;gap:6px;margin-left:auto}
    119 .filter-box input{background:#2a2a2a;border:1px solid #333;color:#d4d4d4;font-family:inherit;font-size:12px;padding:4px 10px;width:180px;outline:none}
    120 .filter-box input::placeholder{color:#555}
    121 .filter-box input:focus{border-color:#5b9bd5}
    122 .filter-clear{background:none;border:none;color:#555;cursor:pointer;font-size:14px;padding:0 2px;line-height:1}
    123 .filter-clear:hover{color:#d4d4d4}
    124 </style>
    125 </head>
    126 <body>
    127 
    128 <header>
    129   <span>&#128193;</span>
    130   <div class="breadcrumb">
    131     {{ range $i, $crumb := .Breadcrumbs }}
    132       {{ if gt $i 0 }}<span class="sep">/</span>{{ end }}
    133       {{ if eq $i (sub1 (len $.Breadcrumbs)) }}
    134         <span class="current">{{ $crumb.Name }}</span>
    135       {{ else }}
    136         <a href="{{ viewSuffix $.View $crumb.Path }}">{{ $crumb.Name }}</a>
    137       {{ end }}
    138     {{ end }}
    139   </div>
    140   <div class="filter-box">
    141     <input type="text" id="filter-input" placeholder="Filter..." oninput="filterView(this.value)" autocomplete="off" spellcheck="false">
    142     <button class="filter-clear" id="filter-clear" onclick="clearFilter()" title="Clear filter" style="display:none">&#10005;</button>
    143   </div>
    144   <div class="view-toggle">
    145     <button id="btn-list" class="{{ if eq .View "list" }}active{{ end }}" onclick="setView('list')">&#9776; List</button>
    146     <button id="btn-thumb" class="{{ if eq .View "thumb" }}active{{ end }}" onclick="setView('thumb')">&#9638; Thumbs</button>
    147   </div>
    148 </header>
    149 
    150 <div class="layout">
    151   <nav class="sidebar">
    152     <div class="sidebar-title">Folders</div>
    153     <ul id="tree-root"></ul>
    154   </nav>
    155 
    156   <main>
    157     <div id="view-list"{{ if eq .View "thumb" }} style="display:none"{{ end }}>
    158       {{ if .Files }}
    159       <table class="file-table" id="file-table">
    160         <thead>
    161           <tr>
    162             <th class="name" onclick="sortTable(0)">Name</th>
    163             <th class="size" onclick="sortTable(1)">Size</th>
    164             <th class="date" onclick="sortTable(2)">Modified</th>
    165           </tr>
    166         </thead>
    167         <tbody>
    168           {{ if ne .CurrentPath "/" }}
    169           <tr>
    170             <td class="name"><span class="file-icon dir">&#128193;</span><a href="{{ viewSuffix $.View "../" }}">../</a></td>
    171             <td class="size">—</td>
    172             <td class="date">—</td>
    173           </tr>
    174           {{ end }}
    175           {{ range .Files }}
    176           <tr data-name="{{ .Name }}" data-size="{{ .Size }}" data-date="{{ .ModTime.Unix }}">
    177             <td class="name">
    178               {{ if .IsDir }}
    179                 <span class="file-icon dir">&#128193;</span><a href="{{ viewSuffix $.View .Path }}">{{ .Name }}/</a>
    180               {{ else if isImage .Ext }}
    181                 <span class="file-icon img">&#128247;</span><a href="{{ urlPath .Path }}">{{ .Name }}</a>
    182               {{ else }}
    183                 <span class="file-icon">&#128196;</span><a href="{{ urlPath .Path }}">{{ .Name }}</a>
    184               {{ end }}
    185             </td>
    186             <td class="size">{{ if .IsDir }}—{{ else }}{{ formatSize .Size }}{{ end }}</td>
    187             <td class="date">{{ formatTime .ModTime }}</td>
    188           </tr>
    189           {{ end }}
    190         </tbody>
    191       </table>
    192       {{ else }}
    193       <div class="empty">Empty directory</div>
    194       {{ end }}
    195     </div>
    196 
    197     <div id="view-thumb"{{ if eq .View "list" }} style="display:none"{{ end }}>
    198       {{ if .Files }}
    199       <div class="thumb-grid">
    200         {{ if ne .CurrentPath "/" }}
    201         <div class="thumb-item">
    202           <a href="{{ viewSuffix $.View "../" }}" style="display:block">
    203             <div class="thumb-preview"><span class="big-icon dir-icon">&#8593;</span></div>
    204             <div class="thumb-label">../</div>
    205           </a>
    206         </div>
    207         {{ end }}
    208         {{ range .Files }}
    209         <div class="thumb-item">
    210           <a href="{{ if .IsDir }}{{ viewSuffix $.View .Path }}{{ else }}{{ urlPath .Path }}{{ end }}" style="display:block">
    211             <div class="thumb-preview">
    212               {{ if .IsDir }}
    213                 <span class="big-icon dir-icon">&#128193;</span>
    214                 {{ else if eq .Ext "svg" }}
    215                   <img src="{{ urlPath .Path }}" alt="{{ .Name }}" loading="lazy">
    216                 {{ else if isImage .Ext }}
    217                   <img src="/__thumb{{ urlPath .Path }}" alt="{{ .Name }}" loading="lazy">
    218               {{ else }}
    219                 <span class="big-icon">&#128196;</span>
    220               {{ end }}
    221             </div>
    222             <div class="thumb-label" title="{{ .Name }}">{{ .Name }}{{ if .IsDir }}/{{ end }}</div>
    223             <div class="thumb-meta">{{ if .IsDir }}folder{{ else }}{{ formatSize .Size }}{{ end }}</div>
    224           </a>
    225         </div>
    226         {{ end }}
    227       </div>
    228       {{ else }}
    229       <div class="empty">Empty directory</div>
    230       {{ end }}
    231     </div>
    232   </main>
    233 </div>
    234 
    235 <footer>{{ len .Files }} item(s) &nbsp;·&nbsp; {{ .CurrentPath }}</footer>
    236 
    237 <script>
    238 const TREE_DATA = {{ .TreeJSON }};
    239 const CURRENT_PATH = '{{ .CurrentPath }}';
    240 const VIEW = '{{ .View }}';
    241 
    242 function setView(v) {
    243   if (v === VIEW) return;
    244   window.location.href = v === 'thumb' ? window.location.pathname + '?v=thumb' : window.location.pathname;
    245 }
    246 
    247 function filterView(query) {
    248   const q = query.trim().toLowerCase();
    249   document.getElementById('filter-clear').style.display = q ? '' : 'none';
    250 
    251   // Filter rows, skipping parent
    252   document.querySelectorAll('#file-table tbody tr').forEach(row => {
    253     const name = (row.dataset.name || '').toLowerCase();
    254     if (!name) { row.style.display = ''; return; }
    255     row.style.display = (!q || name.includes(q)) ? '' : 'none';
    256   });
    257 
    258   document.querySelectorAll('#view-thumb .thumb-item').forEach(item => {
    259     const label = item.querySelector('.thumb-label');
    260     if (!label) { item.style.display = ''; return; }
    261     const name = label.textContent.trim().toLowerCase();
    262     // The ../ item text is "../" — keep it always visible
    263     if (name === '../') { item.style.display = ''; return; }
    264     item.style.display = (!q || name.includes(q)) ? '' : 'none';
    265   });
    266 }
    267 
    268 function clearFilter() {
    269   const input = document.getElementById('filter-input');
    270   input.value = '';
    271   filterView('');
    272   input.focus();
    273 }
    274 
    275 function viewHref(path) {
    276   const encoded = path.split('/').map(encodeURIComponent).join('/');
    277   return VIEW === 'thumb' ? encoded + '?v=thumb' : encoded;
    278 }
    279 
    280 let sortCol = -1, sortDir = 1;
    281 function sortTable(col) {
    282   const tbody = document.querySelector('#file-table tbody');
    283   const rows = Array.from(tbody.querySelectorAll('tr'));
    284   const parentRow = rows.find(r => r.querySelector('a[href="../"]'));
    285   const dataRows = rows.filter(r => r !== parentRow);
    286 
    287   if (sortCol === col) sortDir *= -1;
    288   else { sortCol = col; sortDir = 1; }
    289 
    290   dataRows.sort((a, b) => {
    291     let av, bv;
    292     if (col === 0) { av = (a.dataset.name||'').toLowerCase(); bv = (b.dataset.name||'').toLowerCase(); }
    293     else if (col === 1) { av = parseInt(a.dataset.size||0); bv = parseInt(b.dataset.size||0); }
    294     else { av = parseInt(a.dataset.date||0); bv = parseInt(b.dataset.date||0); }
    295     return av < bv ? -sortDir : av > bv ? sortDir : 0;
    296   });
    297 
    298   document.querySelectorAll('#file-table thead th').forEach((th, i) => {
    299     th.className = th.className.replace(/ ?sort-(asc|desc)/g, '');
    300     if (i === col) th.className += sortDir > 0 ? ' sort-asc' : ' sort-desc';
    301   });
    302 
    303   tbody.innerHTML = '';
    304   if (parentRow) tbody.appendChild(parentRow);
    305   dataRows.forEach(r => tbody.appendChild(r));
    306 }
    307 
    308 function buildTree(nodes, container, depth) {
    309   if (!nodes || !nodes.length) return;
    310   nodes.forEach(node => {
    311     const li = document.createElement('li');
    312     const item = document.createElement('div');
    313     item.className = 'tree-item' + (node.path === CURRENT_PATH ? ' active' : '');
    314     item.style.paddingLeft = (8 + depth * 12) + 'px';
    315 
    316     const toggle = document.createElement('span');
    317     toggle.className = 'tree-toggle';
    318     toggle.textContent = (node.children && node.children.length) ? '▶' : ' ';
    319 
    320     const icon = document.createElement('span');
    321     icon.className = 'tree-icon';
    322     icon.textContent = '📁';
    323 
    324     const label = document.createElement('span');
    325     label.className = 'tree-label';
    326     label.textContent = node.name;
    327 
    328     item.append(toggle, icon, label);
    329     li.appendChild(item);
    330 
    331     let childUl = null;
    332     if (node.children && node.children.length) {
    333       childUl = document.createElement('ul');
    334       childUl.className = 'tree-children';
    335       buildTree(node.children, childUl, depth + 1);
    336       li.appendChild(childUl);
    337       toggle.addEventListener('click', e => {
    338         e.stopPropagation();
    339         toggle.textContent = childUl.classList.toggle('open') ? '▼' : '▶';
    340       });
    341     }
    342 
    343     item.addEventListener('click', () => { window.location.href = viewHref(node.path); });
    344 
    345     if (CURRENT_PATH.startsWith(node.path) && childUl) {
    346       childUl.classList.add('open');
    347       toggle.textContent = '▼';
    348     }
    349 
    350     container.appendChild(li);
    351   });
    352 }
    353 
    354 buildTree(TREE_DATA, document.getElementById('tree-root'), 0);
    355 </script>
    356 </body>
    357 </html>`
    358 
    359 func main() {
    360 	var dir string
    361 	var port int
    362 	flag.StringVar(&dir, "d", ".", "Directory to serve")
    363 	flag.IntVar(&port, "p", 8080, "Port to listen on")
    364 	flag.Parse()
    365 
    366 	absDir, err := filepath.Abs(dir)
    367 	if err != nil {
    368 		log.Fatalf("Invalid directory: %v", err)
    369 	}
    370 	if _, err := os.Stat(absDir); os.IsNotExist(err) {
    371 		log.Fatalf("Directory does not exist: %s", absDir)
    372 	}
    373 
    374 	rootDir = absDir
    375 	log.Printf("Serving %s on :%d", rootDir, port)
    376 
    377 	http.HandleFunc("/__thumb/", thumbHandler)
    378 	http.HandleFunc("/", listingHandler)
    379 
    380 	log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", port), nil))
    381 }
    382 
    383 func safeFS(urlPath string) (string, bool) {
    384 	fsPath := filepath.Join(rootDir, filepath.FromSlash(urlPath))
    385 	clean := filepath.Clean(fsPath)
    386 	rootClean := filepath.Clean(rootDir)
    387 	return clean, strings.HasPrefix(clean, rootClean+string(os.PathSeparator)) || clean == rootClean
    388 }
    389 
    390 func listingHandler(w http.ResponseWriter, r *http.Request) {
    391 	urlPath := r.URL.Path
    392 	if urlPath == "" {
    393 		urlPath = "/"
    394 	}
    395 
    396 	fsPath, ok := safeFS(urlPath)
    397 	if !ok {
    398 		http.Error(w, "Forbidden", http.StatusForbidden)
    399 		return
    400 	}
    401 
    402 	info, err := os.Stat(fsPath)
    403 	if err != nil {
    404 		http.NotFound(w, r)
    405 		return
    406 	}
    407 
    408 	if !info.IsDir() {
    409 		http.ServeFile(w, r, fsPath)
    410 		return
    411 	}
    412 
    413 	if !strings.HasSuffix(r.URL.Path, "/") {
    414 		redir := escapePath(r.URL.Path + "/")
    415 		if v := r.URL.Query().Get("v"); v == "thumb" {
    416 			redir += "?v=thumb"
    417 		}
    418 		http.Redirect(w, r, redir, http.StatusMovedPermanently)
    419 		return
    420 	}
    421 
    422 	for _, indexName := range []string{"index.html", "index.htm"} {
    423 		indexPath := filepath.Join(fsPath, indexName)
    424 		if fi, err := os.Stat(indexPath); err == nil && !fi.IsDir() {
    425 			http.ServeFile(w, r, indexPath)
    426 			return
    427 		}
    428 	}
    429 
    430 	entries, err := os.ReadDir(fsPath)
    431 	if err != nil {
    432 		http.Error(w, "Cannot read directory", http.StatusInternalServerError)
    433 		return
    434 	}
    435 
    436 	var files []FileEntry
    437 	for _, e := range entries {
    438 		name := e.Name()
    439 		if strings.HasPrefix(name, ".") {
    440 			continue
    441 		}
    442 		fi, err := e.Info()
    443 		if err != nil {
    444 			continue
    445 		}
    446 		entryPath := urlPath + name
    447 		if e.IsDir() {
    448 			entryPath += "/"
    449 		}
    450 		ext := ""
    451 		if !e.IsDir() {
    452 			ext = strings.ToLower(strings.TrimPrefix(filepath.Ext(name), "."))
    453 		}
    454 		files = append(files, FileEntry{
    455 			Name:    name,
    456 			Path:    entryPath,
    457 			IsDir:   e.IsDir(),
    458 			Size:    fi.Size(),
    459 			ModTime: fi.ModTime(),
    460 			Ext:     ext,
    461 		})
    462 	}
    463 
    464 	sort.Slice(files, func(i, j int) bool {
    465 		if files[i].IsDir != files[j].IsDir {
    466 			return files[i].IsDir
    467 		}
    468 		return strings.ToLower(files[i].Name) < strings.ToLower(files[j].Name)
    469 	})
    470 
    471 	tree := buildTree(rootDir, "/")
    472 	treeBytes, _ := json.Marshal(tree)
    473 
    474 	view := r.URL.Query().Get("v")
    475 	if view != "thumb" {
    476 		view = "list"
    477 	}
    478 
    479 	data := PageData{
    480 		CurrentPath: urlPath,
    481 		Breadcrumbs: buildBreadcrumbs(urlPath),
    482 		Files:       files,
    483 		TreeJSON:    template.JS(treeBytes),
    484 		View:        view,
    485 	}
    486 
    487 	funcMap := template.FuncMap{
    488 		"formatSize": formatSize,
    489 		"formatTime": func(t time.Time) string { return t.Format("2006-01-02 15:04") },
    490 		"isImage":    isImageExt,
    491 		"urlPath":    escapePath,
    492 		"sub1":       func(n int) int { return n - 1 },
    493 		"viewSuffix": func(view, path string) string {
    494 			path = escapePath(path)
    495 			if view == "thumb" {
    496 				return path + "?v=thumb"
    497 			}
    498 			return path
    499 		},
    500 	}
    501 
    502 	t, err := template.New("page").Funcs(funcMap).Parse(tmpl)
    503 	if err != nil {
    504 		http.Error(w, "Template error: "+err.Error(), http.StatusInternalServerError)
    505 		return
    506 	}
    507 
    508 	w.Header().Set("Content-Type", "text/html; charset=utf-8")
    509 	if err := t.Execute(w, data); err != nil {
    510 		log.Printf("Template error: %v", err)
    511 	}
    512 }
    513 
    514 func thumbHandler(w http.ResponseWriter, r *http.Request) {
    515 	urlPath := strings.TrimPrefix(r.URL.Path, "/__thumb")
    516 	fsPath, ok := safeFS(urlPath)
    517 	if !ok {
    518 		http.Error(w, "Forbidden", http.StatusForbidden)
    519 		return
    520 	}
    521 
    522 	f, err := os.Open(fsPath)
    523 	if err != nil {
    524 		servePlaceholder(w)
    525 		return
    526 	}
    527 	defer f.Close()
    528 
    529 	var img image.Image
    530 
    531 	if isVideoExt(strings.ToLower(strings.TrimPrefix(filepath.Ext(fsPath), "."))) {
    532 		f.Close()
    533 
    534 		cmd := exec.Command(
    535 			"ffmpeg",
    536 			"-v", "error",
    537 			"-i", fsPath,
    538 			"-frames:v", "1",
    539 			"-f", "image2pipe",
    540 			"-vcodec", "mjpeg",
    541 			"pipe:1",
    542 		)
    543 
    544 		var out bytes.Buffer
    545 		cmd.Stdout = &out
    546 
    547 		if err := cmd.Run(); err != nil {
    548 			servePlaceholder(w)
    549 			return
    550 		}
    551 
    552 		img, _, err = image.Decode(&out)
    553 	} else {
    554 		img, _, err = image.Decode(f)
    555 	}
    556 
    557 	if err != nil {
    558 		servePlaceholder(w)
    559 		return
    560 	}
    561 
    562 	thumb := resizeNN(img, 200, 150)
    563 	w.Header().Set("Content-Type", "image/jpeg")
    564 	w.Header().Set("Cache-Control", "max-age=3600")
    565 	_ = jpeg.Encode(w, thumb, &jpeg.Options{Quality: 75})
    566 
    567 }
    568 
    569 func resizeNN(src image.Image, maxW, maxH int) image.Image {
    570 	b := src.Bounds()
    571 	srcW, srcH := b.Dx(), b.Dy()
    572 	scale := float64(maxW) / float64(srcW)
    573 	if s := float64(maxH) / float64(srcH); s < scale {
    574 		scale = s
    575 	}
    576 	newW := int(float64(srcW)*scale + 0.5)
    577 	newH := int(float64(srcH)*scale + 0.5)
    578 	if newW < 1 { newW = 1 }
    579 	if newH < 1 { newH = 1 }
    580 	dst := image.NewRGBA(image.Rect(0, 0, newW, newH))
    581 	for y := 0; y < newH; y++ {
    582 		for x := 0; x < newW; x++ {
    583 			dst.Set(x, y, src.At(b.Min.X+int(float64(x)/scale), b.Min.Y+int(float64(y)/scale)))
    584 		}
    585 	}
    586 	return dst
    587 }
    588 
    589 func servePlaceholder(w http.ResponseWriter) {
    590 	img := image.NewRGBA(image.Rect(0, 0, 200, 150))
    591 	draw.Draw(img, img.Bounds(), &image.Uniform{color.RGBA{40, 40, 40, 255}}, image.Point{}, draw.Src)
    592 	w.Header().Set("Content-Type", "image/jpeg")
    593 	jpeg.Encode(w, img, &jpeg.Options{Quality: 60})
    594 }
    595 
    596 func buildBreadcrumbs(urlPath string) []Breadcrumb {
    597 	crumbs := []Breadcrumb{{Name: "root", Path: "/"}}
    598 	cur := "/"
    599 	for _, p := range strings.Split(strings.Trim(urlPath, "/"), "/") {
    600 		if p == "" { continue }
    601 		cur = cur + p + "/"
    602 		crumbs = append(crumbs, Breadcrumb{Name: p, Path: cur})
    603 	}
    604 	return crumbs
    605 }
    606 
    607 func buildTree(basePath, urlBase string) []*TreeNode {
    608 	entries, err := os.ReadDir(basePath)
    609 	if err != nil { return nil }
    610 	var nodes []*TreeNode
    611 	for _, e := range entries {
    612 		if !e.IsDir() { continue }
    613 		name := e.Name()
    614 		if strings.HasPrefix(name, ".") { continue }
    615 		nodePath := urlBase + name + "/"
    616 		node := &TreeNode{Name: name, Path: nodePath}
    617 		node.Children = buildTree(filepath.Join(basePath, name), nodePath)
    618 		nodes = append(nodes, node)
    619 	}
    620 	return nodes
    621 }
    622 
    623 func isImageExt(ext string) bool {
    624 	switch ext {
    625 	case "jpg", "jpeg", "png", "gif", "webp", "bmp", "avif":
    626 		return true
    627 	}
    628 	return isVideoExt(ext)
    629 }
    630 
    631 func isVideoExt(ext string) bool {
    632 	switch ext {
    633 	case "webm", "mp4", "m4v", "mkv", "mov", "avi", "wmv", "flv", "mpg", "mpeg", "3gp", "ogv", "mts", "m2ts":
    634 		return true
    635 	}
    636 	return false
    637 }
    638 
    639 func escapePath(p string) string {
    640 	return (&url.URL{Path: p}).EscapedPath()
    641 }
    642 
    643 func formatSize(n int64) string {
    644 	if n < 1024 { return fmt.Sprintf("%d B", n) }
    645 	div, exp := int64(1024), 0
    646 	for v := n / 1024; v >= 1024; v /= 1024 { div *= 1024; exp++ }
    647 	return fmt.Sprintf("%.1f %cB", float64(n)/float64(div), "KMGTPE"[exp])
    648 }