summaryrefslogtreecommitdiff
path: root/main.py
blob: dae6661f6d9bd245886f4e70531e4b2cce0bbac3 (plain)
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
import fastapi
from fastapi.middleware.cors import CORSMiddleware
import fastapi.staticfiles
import fastapi.responses
from pydantic import BaseModel
from pathlib import Path
import os
import html

print("Hello, world!")

FOLDER_PATH = Path("/Users/altaf/").resolve()
# FOLDER_PATH = "/var/files"

app = fastapi.FastAPI(title="altaf-files", decscription="altaf-files backend", version="1.0")

origins = [
    "http://localhost",
    "http://localhost:9092",
    "https://files.altafcreator.com",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/{path:path}")
def folder(path: str):
    target_path = (FOLDER_PATH / path).resolve()

    if FOLDER_PATH not in target_path.parents and target_path != FOLDER_PATH:
        return fastapi.responses.Response(status_code=403, content="Access denied.")

    is_file = False

    if target_path.is_file():
        is_file = True
        return fastapi.responses.FileResponse(target_path)
    elif not target_path.is_dir():
        return fastapi.responses.Response(status_code=404)

    content = f"<p>/{path}</p><a href='..'>../</a><br>"

    for item in sorted(target_path.iterdir()):
        safe_child_path = html.escape(item.name)

        href_path = ""
        if path == "":
            href_path = f"/{safe_child_path}"
        else:
            href_path = f"/{path.rstrip('/')}/{safe_child_path}"

        filetype_string = "📂"
        if (target_path / safe_child_path).resolve().is_file():
            filetype_string = "📄"

        content += f"<a href='{href_path}'>{filetype_string} {safe_child_path}</a><br>"

    return fastapi.responses.Response(content=content, media_type="text/html", status_code=200)