#!/usr/bin/env python3
"""简易网页文件浏览器 - 给不懂终端的同事用"""
import http.server
import os
import urllib.parse

ROOT = "/root/.hermes"
PORT = 8088
USER = "admin"
PASS = "hermes123"

class FileBrowser(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        import base64
        auth = self.headers.get("Authorization", "")
        expected = f"Basic {base64.b64encode(f'{USER}:{PASS}'.encode()).decode()}"
        if auth != expected:
            self.send_response(401)
            self.send_header("WWW-Authenticate", 'Basic realm="FileBrowser"')
            self.end_headers()
            self.wfile.write(b"Auth required")
            return

        path = urllib.parse.unquote(self.path).split("?")[0]
        full = os.path.join(ROOT, path.lstrip("/"))

        if os.path.isdir(full):
            self._list_dir(full, path)
        else:
            super().do_GET()

    def _list_dir(self, full_dir, rel_path):
        self.send_response(200)
        self.send_header("Content-type", "text/html; charset=utf-8")
        self.end_headers()

        items = sorted(os.listdir(full_dir), key=lambda x: (not os.path.isdir(os.path.join(full_dir, x)), x.lower()))

        html = """<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>文件管理</title>
<style>
body{font-family:-apple-system,sans-serif;max-width:900px;margin:40px auto;padding:0 20px;background:#f5f5f5}
h2{color:#333;border-bottom:2px solid #4A90D9;padding-bottom:10px}
.breadcrumb a{color:#4A90D9;text-decoration:none}
.breadcrumb a:hover{text-decoration:underline}
table{width:100%;border-collapse:collapse;background:#fff;border-radius:8px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.1)}
th{background:#4A90D9;color:#fff;padding:12px;text-align:left}
td{padding:10px 12px;border-bottom:1px solid #eee}
tr:hover{background:#f0f7ff}
a{color:#333;text-decoration:none}
a:hover{color:#4A90D9}
.size{color:#999;font-size:13px}
.dir a{font-weight:600}
.back{display:inline-block;margin-bottom:15px;padding:6px 14px;background:#4A90D9;color:#fff!important;border-radius:4px;font-size:14px}
</style></head><body>
<h2>📁 文件管理</h2>
<div class="breadcrumb"><a href="/">🏠 根目录</a>"""

        parts = [p for p in rel_path.split("/") if p]
        acc = ""
        for p in parts:
            acc += f"/{p}"
            html += f' / <a href="{acc}">{p}</a>'
        html += "</div>"

        if rel_path != "/" and rel_path != "":
            parent = "/".join(rel_path.split("/")[:-1]) or "/"
            html += f'<a class="back" href="{parent}">⬅ 返回上级</a>'

        html += "<table><tr><th>名称</th><th style='width:120px'>大小</th></tr>"

        for name in items:
            item_path = os.path.join(full_dir, name)
            item_rel = f"{rel_path.rstrip('/')}/{name}" if rel_path != "/" else f"/{name}"
            item_rel = item_rel.replace("//", "/")

            if os.path.isdir(item_path):
                html += f"<tr class='dir'><td><a href='{item_rel}'>📁 {name}/</a></td><td>-</td></tr>"
            else:
                size = os.path.getsize(item_path)
                if size < 1024: s = f"{size} B"
                elif size < 1024*1024: s = f"{size/1024:.1f} KB"
                else: s = f"{size/(1024*1024):.1f} MB"
                ext = name.rsplit(".", 1)[-1].lower() if "." in name else ""
                icon = "📄"
                if ext == "pdf": icon = "📕"
                elif ext in ("xlsx", "xls", "csv"): icon = "📊"
                elif ext in ("md", "txt"): icon = "📝"
                html += f"<tr><td><a href='{item_rel}'>{icon} {name}</a></td><td class='size'>{s}</td></tr>"

        html += "</table></body></html>"
        self.wfile.write(html.encode())

    def log_message(self, format, *args):
        pass

class Handler(FileBrowser):
    def translate_path(self, path):
        p = urllib.parse.unquote(path).split("?")[0]
        return os.path.join(ROOT, p.lstrip("/"))

if __name__ == "__main__":
    os.chdir(ROOT)
    server = http.server.HTTPServer(("0.0.0.0", PORT), Handler)
    print(f"文件浏览器已启动: http://0.0.0.0:{PORT}")
    print(f"账号: {USER} / 密码: {PASS}")
    server.serve_forever()
