vortexa64 commited on
Commit
dfa7514
·
verified ·
1 Parent(s): 5192f30

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -116
app.py CHANGED
@@ -1,132 +1,92 @@
1
- from fastapi import FastAPI, Request, UploadFile, File
2
  from fastapi.responses import HTMLResponse, JSONResponse
3
  from fastapi.staticfiles import StaticFiles
4
- from pydantic import BaseModel
5
- import os, subprocess, shutil
6
 
7
  app = FastAPI()
8
 
9
- # Global storage
10
- CONFIG = {
11
- "username": "",
12
- "password": "",
13
- "startcmd": "",
14
- "running": False,
15
- "process": None
16
- }
17
 
18
- # Base dir
19
- USER_DIR = "/tmp/user"
20
- os.makedirs(USER_DIR, exist_ok=True)
21
-
22
- # Mount static
23
- app.mount("/static", StaticFiles(directory="static"), name="static")
24
 
 
25
  @app.get("/", response_class=HTMLResponse)
26
- def index():
27
- with open("index.html", "r", encoding="utf-8") as f:
28
  return f.read()
29
 
30
- # ================= SETUP ====================
31
-
32
- class SetupData(BaseModel):
33
- username: str
34
- password: str
35
- startcmd: str
36
-
37
- @app.post("/setup")
38
- def save_setup(data: SetupData):
39
- CONFIG.update({
40
- "username": data.username,
41
- "password": data.password,
42
- "startcmd": data.startcmd
43
- })
44
- return {"status": "ok"}
45
-
46
- # ================= CONSOLE ====================
47
-
48
- @app.post("/console/start")
49
- def start_console():
50
- if CONFIG["running"]:
51
- return {"status": "already running"}
52
- with open(f"{USER_DIR}/main.py", "w") as f:
53
- f.write("")
54
- CONFIG["process"] = subprocess.Popen(["python3", "-i", f"{USER_DIR}/main.py"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
55
- CONFIG["running"] = True
56
- return {"status": "started"}
57
-
58
- @app.post("/console/stop")
59
- def stop_console():
60
- if CONFIG["process"]:
61
- CONFIG["process"].terminate()
62
- CONFIG["running"] = False
63
- return {"status": "stopped"}
64
-
65
- class InputData(BaseModel):
66
- input: str
67
-
68
- @app.post("/console/input")
69
- def console_input(data: InputData):
70
- if not CONFIG["running"] or not CONFIG["process"]:
71
- return {"output": "Console not running"}
72
- try:
73
- CONFIG["process"].stdin.write(data.input + "\n")
74
- CONFIG["process"].stdin.flush()
75
- output = CONFIG["process"].stdout.readline()
76
- return {"output": output}
77
- except Exception as e:
78
- return {"output": str(e)}
79
-
80
- # ================= FILE MANAGER ====================
81
 
 
82
  @app.get("/files")
83
- def list_files():
84
- result = []
85
- for root, dirs, files in os.walk(USER_DIR):
86
- for name in dirs + files:
87
- full = os.path.join(root, name)
88
- rel = os.path.relpath(full, USER_DIR)
89
- result.append(rel)
90
- return result
91
-
92
- class FileData(BaseModel):
93
- name: str
94
-
95
- @app.post("/file/create")
96
- def create_file(data: FileData):
97
- full = os.path.join(USER_DIR, data.name)
98
- open(full, "w").close()
99
- return {"status": "file created"}
100
-
101
- @app.post("/folder/create")
102
- def create_folder(data: FileData):
103
- full = os.path.join(USER_DIR, data.name)
104
- os.makedirs(full, exist_ok=True)
105
- return {"status": "folder created"}
106
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  @app.post("/delete")
108
- def delete_item(data: FileData):
109
- full = os.path.join(USER_DIR, data.name)
110
- if os.path.isdir(full):
111
- shutil.rmtree(full)
112
- elif os.path.isfile(full):
113
- os.remove(full)
114
- return {"status": "deleted"}
115
-
116
- class RenameData(BaseModel):
117
- old_name: str
118
- new_name: str
 
 
 
 
 
 
 
 
119
 
120
- @app.post("/rename")
121
- def rename_item(data: RenameData):
122
- src = os.path.join(USER_DIR, data.old_name)
123
- dst = os.path.join(USER_DIR, data.new_name)
124
- os.rename(src, dst)
125
- return {"status": "renamed"}
 
126
 
127
- @app.post("/upload")
128
- async def upload(file: UploadFile = File(...)):
129
- dest = os.path.join(USER_DIR, file.filename)
130
- with open(dest, "wb") as f:
131
- f.write(await file.read())
132
- return {"status": "uploaded"}
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Request
2
  from fastapi.responses import HTMLResponse, JSONResponse
3
  from fastapi.staticfiles import StaticFiles
4
+ import shutil, os, json
 
5
 
6
  app = FastAPI()
7
 
8
+ # Buat direktori yang dibutuhkan
9
+ UPLOAD_DIR = "uploads"
10
+ STATIC_DIR = "static"
11
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
12
+ os.makedirs(STATIC_DIR, exist_ok=True)
 
 
 
13
 
14
+ # Serve static files
15
+ app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
16
+ app.mount("/uploads", StaticFiles(directory=UPLOAD_DIR), name="uploads")
 
 
 
17
 
18
+ # Serve halaman utama
19
  @app.get("/", response_class=HTMLResponse)
20
+ async def root():
21
+ with open("index.html", encoding="utf-8") as f:
22
  return f.read()
23
 
24
+ # Upload file
25
+ @app.post("/upload")
26
+ async def upload(file: UploadFile = File(...)):
27
+ dest = os.path.join(UPLOAD_DIR, file.filename)
28
+ with open(dest, "wb") as f:
29
+ shutil.copyfileobj(file.file, f)
30
+ return {"filename": file.filename}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
+ # Ambil list file/folder dari uploads
33
  @app.get("/files")
34
+ async def files():
35
+ return os.listdir(UPLOAD_DIR)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
36
 
37
+ # Rename file
38
+ @app.post("/rename")
39
+ async def rename_file(request: Request):
40
+ data = await request.json()
41
+ src = os.path.join(UPLOAD_DIR, data["old"])
42
+ dst = os.path.join(UPLOAD_DIR, data["new"])
43
+ if os.path.exists(src):
44
+ os.rename(src, dst)
45
+ return {"status": "renamed"}
46
+ return {"status": "error", "detail": "file not found"}
47
+
48
+ # Delete file
49
  @app.post("/delete")
50
+ async def delete_file(request: Request):
51
+ data = await request.json()
52
+ path = os.path.join(UPLOAD_DIR, data["filename"])
53
+ if os.path.exists(path):
54
+ if os.path.isfile(path):
55
+ os.remove(path)
56
+ elif os.path.isdir(path):
57
+ shutil.rmtree(path)
58
+ return {"status": "deleted"}
59
+ return {"status": "error", "detail": "file not found"}
60
+
61
+ # Buat file kosong
62
+ @app.post("/create_file")
63
+ async def create_file(request: Request):
64
+ data = await request.json()
65
+ path = os.path.join(UPLOAD_DIR, data["filename"])
66
+ with open(path, "w") as f:
67
+ f.write("")
68
+ return {"status": "created"}
69
 
70
+ # Buat folder
71
+ @app.post("/create_folder")
72
+ async def create_folder(request: Request):
73
+ data = await request.json()
74
+ path = os.path.join(UPLOAD_DIR, data["foldername"])
75
+ os.makedirs(path, exist_ok=True)
76
+ return {"status": "created"}
77
 
78
+ # Simpan setup
79
+ @app.post("/setup")
80
+ async def setup_config(request: Request):
81
+ data = await request.json()
82
+ with open("setup.json", "w") as f:
83
+ json.dump(data, f, indent=2)
84
+ return {"status": "ok", "received": data}
85
+
86
+ # Ambil setup
87
+ @app.get("/setup")
88
+ async def get_setup():
89
+ if os.path.exists("setup.json"):
90
+ with open("setup.json", "r") as f:
91
+ return json.load(f)
92
+ return {"username": "", "password": "", "start_cmd": ""}