File size: 3,062 Bytes
e6e948c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import os
import re
import json
import asyncio
from pathlib import Path
from fastapi import FastAPI, HTTPException, Header

RCLONE_CONFIG = os.getenv("RCLONE_CONFIG", "https://gist.githubusercontent.com/genstava789/e7fa4e34e126bfc257b21db4f8c0f3ba/raw/rclone.conf")
HOST = os.getenv("HOST", "0.0.0.0")
PORT = int(os.getenv("PORT", "8080"))
API_TOKEN = os.getenv("API_TOKEN", "admin")

app = FastAPI(title="rclone index backend")


def check_auth(token: str | None):
    if API_TOKEN and token != API_TOKEN:
        raise HTTPException(status_code=401, detail="unauthorized")


def parse_remotes(conf_path: str) -> list[str]:
    path = Path(conf_path)
    if not path.exists():
        return []

    text = path.read_text(encoding="utf-8", errors="ignore")
    out = []

    for line in text.splitlines():
        line = line.strip()
        if line.startswith("[") and line.endswith("]"):
            name = line[1:-1].strip()
            if name:
                out.append(name if name.endswith(":") else name + ":")

    return out


def safe_remote(fs: str) -> bool:
    return bool(re.fullmatch(r"[A-Za-z0-9_.\-]+:", fs))


def safe_dir(remote: str) -> bool:
    if ".." in remote or "\x00" in remote:
        return False
    return True


async def run_rclone(*args: str):
    cmd = ["rclone", *args, "--config", RCLONE_CONFIG, "--use-json-log=false"]
    proc = await asyncio.create_subprocess_exec(
        *cmd,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE
    )
    stdout, stderr = await proc.communicate()

    out = stdout.decode("utf-8", errors="ignore").strip()
    err = stderr.decode("utf-8", errors="ignore").strip()

    if proc.returncode != 0:
        raise HTTPException(status_code=500, detail=err or "rclone error")

    return out


@app.get("/health")
async def health():
    return {"ok": True}


@app.get("/api/remotes")
async def api_remotes(x_api_token: str | None = Header(default=None)):
    check_auth(x_api_token)
    return {"ok": True, "remotes": parse_remotes(RCLONE_CONFIG)}


@app.get("/api/list")
async def api_list(

    fs: str,

    dir: str = "",

    x_api_token: str | None = Header(default=None)

):
    check_auth(x_api_token)

    if not safe_remote(fs):
        raise HTTPException(status_code=400, detail="invalid fs")

    if not safe_dir(dir):
        raise HTTPException(status_code=400, detail="invalid dir")

    target = fs + dir
    out = await run_rclone("lsjson", target)

    try:
        data = json.loads(out)
    except Exception:
        raise HTTPException(status_code=500, detail="invalid rclone response")

    items = []
    for item in data:
        items.append({
            "name": item.get("Name", ""),
            "path": item.get("Path", ""),
            "size": item.get("Size", 0),
            "isDir": item.get("IsDir", False)
        })

    return {
        "ok": True,
        "fs": fs,
        "dir": dir,
        "list": items
    }