File size: 1,708 Bytes
9dc6849
 
8083ca2
9dc6849
 
 
5ac84de
86614b9
2d82f50
9dc6849
a91e922
9dc6849
 
 
 
 
 
2d82f50
a91e922
2d82f50
9dc6849
 
 
 
 
 
2d82f50
9dc6849
 
 
 
 
 
 
 
bb403b8
9dc6849
 
 
 
bb403b8
9dc6849
 
a91e922
9dc6849
 
2d82f50
bb403b8
 
 
 
 
 
 
 
 
2d82f50
9dc6849
bb403b8
9dc6849
bb403b8
9dc6849
2d82f50
 
 
 
 
 
 
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
from fastapi import FastAPI, Request
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
from itables import to_html_datatable
from pathlib import Path
import pandas as pd


ROOT = Path("/home/user")
app = FastAPI()
app.mount(path="/files", app=StaticFiles(directory=ROOT), name="HOME")


@app.middleware("http")
async def file_system(request: Request, call_next):
    url = request.url
    if url.path.endswith("/"):
        return HTMLResponse(
            content=files_in_folder(url.path.lstrip("/files"))
        )
    response = await call_next(request)
    return response


def files_in_folder(path: str):
    """List files to render as file index."""

    folder = ROOT / path
    path_glob = folder.glob("*")
    res = pd.DataFrame(
        [
            (
                f.name,
                f.stat().st_size,
                pd.Timestamp(int(f.stat().st_mtime), unit="s"),
                f.is_dir(),
            )
            for f in path_glob
        ],
        columns=["path", "size", "mtime", "folder"],
    ).sort_values(["folder", "path"], ascending=[False, True])

    res["path"] = res.apply(
        lambda x: f"<a href=/files/{path}{x.path}{'/' if x.folder else ''}>{x.path}</a>",
        axis=1,
    )

    res.loc[-1] = [
        (
            f"<a href=/files/{path.parent}/>..</a>",
            "",
            "",
            True,
        )
    ]

    table = to_html_datatable(
        df=res.drop(columns="folder"),
        classes="display nowrap compact",
        showIndex=False,
        paging=False
    )

    return f"""
    <div style="width:50%; margin: 0 auto;">
        <h1>{folder}</h1><br>
        {table}
    </div>
    """