#!/usr/bin/env python3
"""Look at configurations on this computer with AtomEye in a web browser
somewhere else: on a tablet, say, with this computer behind ssh.

    atomeye-serve [directory or file] [--port 8000]

serves the AtomEye web application and the files under the directory
(default: the current one) from one address on this computer, and prints
the links to open and the ssh command that brings the address to you.
Nothing else needs installing: Python 3.8 or later is enough. The
application is fetched once from https://jameskermode.github.io/AtomEye/app/
and kept in ~/.cache/atomeye-app (--app <directory> uses a copy you have,
--update fetches it again).

The server listens on this computer only (127.0.0.1), and the address
contains a random word, so that other users of this computer cannot read
your files by guessing it (--no-token leaves it out).
"""
import argparse, functools, html, http.server, io, os, posixpath, secrets, socket, sys
import urllib.parse, urllib.request

SITE = "https://jameskermode.github.io/AtomEye/app/"
APP_FILES = ["index.html", "atomeye.js", "atomeye-core.mjs", "sw.js",
             "manifest.webmanifest", "demo.xyz", "icon-192.png",
             "icon-512.png", "icon-maskable-512.png", "apple-touch-icon.png"]
CONFIGURATIONS = (".xyz", ".extxyz", ".cfg", ".pdb")
TYPES = {".html": "text/html; charset=utf-8", ".js": "text/javascript",
         ".mjs": "text/javascript", ".webmanifest": "application/manifest+json",
         ".png": "image/png", ".json": "application/json"}
MAX_LISTED = 2000
MAX_DEPTH = 4


def is_configuration(name):
    name = name.lower()
    if name.endswith(".gz"):
        name = name[:-3]
    return name.endswith(CONFIGURATIONS)


def fetch_app(directory, update=False):
    os.makedirs(directory, exist_ok=True)
    missing = [f for f in APP_FILES
               if update or not os.path.exists(os.path.join(directory, f))]
    if not missing:
        return
    print("Fetching the AtomEye application from %s ..." % SITE, flush=True)
    for name in missing:
        try:
            with urllib.request.urlopen(SITE + name, timeout=60) as response:
                data = response.read()
        except Exception as error:
            sys.exit("Could not fetch %s%s: %s\nIf this computer cannot reach "
                     "the web, copy those files from one that can and pass "
                     "--app <directory>." % (SITE, name, error))
        with open(os.path.join(directory, name + ".part"), "wb") as out:
            out.write(data)
        os.replace(os.path.join(directory, name + ".part"),
                   os.path.join(directory, name))


def listing(root, prefix):
    """A page of links that open each configuration under root."""
    rows, count = [], 0
    for folder, folders, files in os.walk(root):
        depth = 0 if folder == root else os.path.relpath(folder, root).count(os.sep) + 1
        # (not the whole of a home directory: a few levels down)
        folders[:] = sorted(d for d in folders if not d.startswith(".")) if depth < MAX_DEPTH else []
        names = sorted(f for f in files if is_configuration(f))
        if not names:
            continue
        relative = os.path.relpath(folder, root)
        rows.append("<h2>%s</h2><ul>" % html.escape("." if relative == "." else relative))
        for name in names:
            path = name if relative == "." else posixpath.join(relative.replace(os.sep, "/"), name)
            query = urllib.parse.urlencode({"url": "data/" + path})
            try:
                size = os.path.getsize(os.path.join(folder, name))
            except OSError:
                size = 0
            rows.append('<li><a href="%s/?%s">%s</a> <small>%s</small></li>'
                        % (prefix, html.escape(query), html.escape(name), human(size)))
            count += 1
        rows.append("</ul>")
        if count >= MAX_LISTED:
            rows.append("<p>(only the first %d are listed)</p>" % MAX_LISTED)
            break
    if not count:
        rows.append("<p>No .xyz, .extxyz, .cfg or .pdb files here.</p>")
    return ("<!doctype html><html lang=en><meta charset=utf-8>"
            "<meta name=viewport content='width=device-width, initial-scale=1'>"
            "<title>Configurations - AtomEye</title>"
            "<style>body{font:17px/1.5 system-ui,sans-serif;margin:1rem auto;max-width:46rem;padding:0 1rem}"
            "h1{font-size:1.3rem}h2{font-size:1rem;margin:1.2rem 0 .2rem;color:#555}"
            "ul{list-style:none;padding:0;margin:0}li a{display:inline-block;padding:.35rem 0}"
            "small{color:#777}</style>"
            "<h1>Configurations in %s</h1><p><a href='%s/'>The viewer</a></p>%s</html>"
            % (html.escape(root), prefix, "".join(rows)))


def human(size):
    for unit in ("bytes", "kB", "MB", "GB"):
        if size < 1000 or unit == "GB":
            return ("%d %s" if unit == "bytes" else "%.1f %s") % (size, unit)
        size /= 1000.0


class Handler(http.server.SimpleHTTPRequestHandler):
    """<prefix>/ is the application, <prefix>/data/ the files, and
    <prefix>/files a list of them; anything else is not there."""
    protocol_version = "HTTP/1.1"

    def __init__(self, *args, app, root, prefix, quiet, **kwargs):
        self.app, self.root, self.prefix, self.quiet = app, root, prefix, quiet
        super().__init__(*args, **kwargs)

    def log_message(self, fmt, *args):
        if not self.quiet:
            super().log_message(fmt, *args)

    def end_headers(self):
        # what is served changes: a browser should always ask again
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def resolve(self):
        """The file a request is for, "list", or None."""
        path = urllib.parse.unquote(urllib.parse.urlsplit(self.path).path)
        if self.prefix:
            if path == self.prefix:
                return "slash"  # (the page's own files are relative to it)
            if not path.startswith(self.prefix + "/"):
                return None
            path = path[len(self.prefix):]
        if path == "/":
            return os.path.join(self.app, "index.html")
        if path in ("/files", "/files/"):
            return "list"
        parts = [p for p in path.split("/") if p]
        if any(p in (".", "..") or p.startswith(".") for p in parts):
            return None
        if parts[0] == "data":
            base, parts = self.root, parts[1:]
        elif len(parts) == 1 and parts[0] in APP_FILES:
            base = self.app
        else:
            return None
        full = os.path.realpath(os.path.join(base, *parts))
        inside = os.path.realpath(base)
        if full != inside and not full.startswith(inside + os.sep):
            return None
        return full if os.path.isfile(full) else None

    def send_head(self):
        target = self.resolve()
        if target == "list":
            body = listing(self.root, self.prefix).encode()
            self.send_response(200)
            self.send_header("Content-Type", "text/html; charset=utf-8")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            return io.BytesIO(body)
        if target == "slash":
            self.send_response(301)
            self.send_header("Location", self.prefix + "/")
            self.send_header("Content-Length", "0")
            self.end_headers()
            return None
        if target is None:
            self.send_error(404, "Not found")
            return None
        try:
            source = open(target, "rb")
        except OSError:
            self.send_error(404, "Not found")
            return None
        extension = os.path.splitext(target)[1].lower()
        self.send_response(200)
        self.send_header("Content-Type", TYPES.get(extension, "application/octet-stream"))
        self.send_header("Content-Length", str(os.fstat(source.fileno()).st_size))
        self.end_headers()
        return source

    def do_POST(self):
        self.send_error(405, "Not allowed")


def main():
    parser = argparse.ArgumentParser(
        description="Serve the AtomEye web application with the configurations "
                    "under a directory, to look at them from a browser elsewhere.")
    parser.add_argument("path", nargs="?", default=".",
                        help="directory to serve, or one file in it (default: .)")
    parser.add_argument("--port", type=int, default=8000,
                        help="port to listen on; the next free one is used (default 8000)")
    parser.add_argument("--bind", default="127.0.0.1",
                        help="address to listen on (default 127.0.0.1: this computer only)")
    parser.add_argument("--app", help="directory with the application's files, "
                        "instead of fetching them")
    parser.add_argument("--update", action="store_true",
                        help="fetch the application again")
    parser.add_argument("--no-token", action="store_true",
                        help="leave the random word out of the address")
    parser.add_argument("--quiet", action="store_true", help="do not log requests")
    args = parser.parse_args()

    path = os.path.abspath(args.path)
    first = None
    if os.path.isfile(path):
        path, first = os.path.dirname(path), os.path.basename(path)
    if not os.path.isdir(path):
        sys.exit("%s: no such directory or file" % args.path)

    app = args.app or os.path.join(
        os.environ.get("XDG_CACHE_HOME") or os.path.expanduser("~/.cache"), "atomeye-app")
    if args.app:
        absent = [f for f in ("index.html", "atomeye.js", "atomeye-core.mjs")
                  if not os.path.exists(os.path.join(app, f))]
        if absent:
            sys.exit("%s: %s not there" % (app, ", ".join(absent)))
    else:
        fetch_app(app, args.update)

    prefix = "" if args.no_token else "/" + secrets.token_urlsafe(9)
    handler = functools.partial(Handler, app=app, root=path, prefix=prefix,
                                quiet=args.quiet)
    server = None
    for port in range(args.port, args.port + 50):
        try:
            server = http.server.ThreadingHTTPServer((args.bind, port), handler)
            break
        except OSError:
            continue
    if server is None:
        sys.exit("no free port from %d" % args.port)
    server.daemon_threads = True

    host = socket.gethostname()
    local = "http://localhost:%d%s" % (port, prefix)
    print("Serving %s" % path)
    print()
    print("1. Bring port %d to the computer in front of you (add -J <jump host> if you need one):" % port)
    print("       ssh -N -L %d:localhost:%d %s" % (port, port, host))
    print("2. Open in a browser there:")
    print("       %s/files     the configurations here, to choose from" % local)
    if first:
        print("       %s/?%s" % (local, urllib.parse.urlencode({"url": "data/" + first})))
    else:
        print("       %s/?url=data/<file>     one of them" % local)
    print()
    print("From a tablet, run the ssh command on a computer that is always on and")
    print("reachable from the tablet, and publish the port from there: with Tailscale,")
    print("\"tailscale serve --bg %d\", then use https://<that computer>%s/files" % (port, prefix or ""))
    print()
    print("Ctrl-C stops.", flush=True)
    try:
        server.serve_forever()
    except KeyboardInterrupt:
        print()


if __name__ == "__main__":
    main()
