OrbitMC commited on
Commit
36c1a91
·
verified ·
1 Parent(s): 78f182d

Update panel.py

Browse files
Files changed (1) hide show
  1. panel.py +628 -501
panel.py CHANGED
@@ -2,8 +2,8 @@ import os
2
  import asyncio
3
  import collections
4
  import shutil
5
- from fastapi import FastAPI, WebSocket, Request, Response, Form, UploadFile, File, HTTPException
6
- from fastapi.responses import HTMLResponse, FileResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
  import uvicorn
9
 
@@ -15,488 +15,603 @@ output_history = collections.deque(maxlen=300)
15
  connected_clients = set()
16
  BASE_DIR = os.path.abspath("/app")
17
 
18
- HTML_CONTENT = """<!DOCTYPE html>
19
- <html lang="en">
 
 
 
 
20
  <head>
21
- <meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
22
- <title>OrbitMC</title>
23
- <link rel="preconnect" href="https://fonts.googleapis.com">
24
- <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500&family=Geist:wght@300;400;500;600&display=swap" rel="stylesheet">
25
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
26
- <style>
27
- *{box-sizing:border-box;margin:0;padding:0}
28
- :root{
29
- --bg:#0a0a0a;--s1:#111;--s2:#181818;--s3:#222;
30
- --b1:#2a2a2a;--b2:#333;
31
- --t1:#f0f0f0;--t2:#999;--t3:#555;
32
- --accent:#4ade80;--accent2:#22c55e;
33
- --red:#f87171;--blue:#60a5fa;--yellow:#fbbf24;
34
- --r:8px;--font:'Geist',sans-serif;--mono:'JetBrains Mono',monospace;
35
- --trans:all .15s ease;
36
- }
37
- body{background:var(--bg);color:var(--t1);font-family:var(--font);font-size:14px;display:flex;height:100vh;overflow:hidden}
38
-
39
- .sidebar{width:56px;background:var(--s1);border-right:1px solid var(--b1);display:flex;flex-direction:column;align-items:center;padding:16px 0;gap:4px;z-index:10;flex-shrink:0}
40
- .nav-btn{width:40px;height:40px;border:none;background:transparent;color:var(--t3);border-radius:var(--r);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:16px;transition:var(--trans);position:relative}
41
- .nav-btn:hover{background:var(--s3);color:var(--t2)}
42
- .nav-btn.active{background:rgba(74,222,128,.12);color:var(--accent)}
43
- .nav-btn .tooltip{position:absolute;left:52px;background:#1a1a1a;border:1px solid var(--b1);color:var(--t1);padding:4px 10px;border-radius:6px;font-size:12px;white-space:nowrap;pointer-events:none;opacity:0;transition:opacity .15s;z-index:100}
44
- .nav-btn:hover .tooltip{opacity:1}
45
-
46
- .main{flex:1;display:flex;flex-direction:column;overflow:hidden}
47
- .panel{display:none;flex:1;overflow:hidden}
48
- .panel.active{display:flex;flex-direction:column}
49
-
50
- /* CONSOLE */
51
- .console-wrap{flex:1;position:relative;overflow:hidden;background:var(--s1)}
52
- .console-blur{position:absolute;top:0;left:0;right:0;height:60px;background:linear-gradient(to bottom,var(--s1) 0%,transparent 100%);z-index:2;pointer-events:none}
53
- .console-out{position:absolute;inset:0;overflow-y:auto;padding:16px;font-family:var(--mono);font-size:12.5px;line-height:1.7;scrollbar-width:thin;scrollbar-color:var(--b2) transparent}
54
- .console-out::-webkit-scrollbar{width:4px}
55
- .console-out::-webkit-scrollbar-thumb{background:var(--b2);border-radius:2px}
56
- .log-line{animation:fadeUp .25s ease forwards;opacity:0;word-break:break-all}
57
- @keyframes fadeUp{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
58
- .log-line.info{color:#94a3b8}.log-line.warn{color:var(--yellow)}.log-line.error{color:var(--red)}.log-line.ok{color:var(--accent)}.log-line.cmd{color:var(--t3)}
59
- .console-input-bar{padding:12px 16px 20px;background:var(--s1);border-top:1px solid var(--b1);display:flex;gap:8px;align-items:center}
60
- .console-input-bar .prompt{color:var(--accent);font-family:var(--mono);font-size:13px;flex-shrink:0}
61
- .console-input-bar input{flex:1;background:var(--s2);border:1px solid var(--b1);color:var(--t1);font-family:var(--mono);font-size:13px;padding:8px 12px;border-radius:var(--r);outline:none;transition:var(--trans)}
62
- .console-input-bar input:focus{border-color:var(--accent);box-shadow:0 0 0 2px rgba(74,222,128,.1)}
63
- .send-btn{background:var(--accent);color:#000;border:none;padding:8px 16px;border-radius:var(--r);font-family:var(--font);font-weight:600;font-size:13px;cursor:pointer;transition:var(--trans);flex-shrink:0}
64
- .send-btn:hover{background:var(--accent2)}
65
-
66
- /* FILE MANAGER */
67
- .fm-toolbar{padding:12px 16px;background:var(--s1);border-bottom:1px solid var(--b1);display:flex;align-items:center;gap:8px;flex-wrap:wrap}
68
- .fm-breadcrumb{flex:1;display:flex;align-items:center;gap:4px;font-size:13px;color:var(--t2);overflow:hidden;min-width:0}
69
- .fm-breadcrumb span{cursor:pointer;transition:color .15s;white-space:nowrap}
70
- .fm-breadcrumb span:hover{color:var(--accent)}
71
- .fm-breadcrumb .sep{color:var(--t3)}
72
- .tb-btn{height:32px;padding:0 12px;background:var(--s2);border:1px solid var(--b1);color:var(--t2);border-radius:6px;cursor:pointer;font-size:12px;font-family:var(--font);display:flex;align-items:center;gap:6px;transition:var(--trans);white-space:nowrap}
73
- .tb-btn:hover{background:var(--s3);color:var(--t1)}
74
- .fm-list{flex:1;overflow-y:auto;padding:8px;scrollbar-width:thin;scrollbar-color:var(--b2) transparent}
75
- .fm-list::-webkit-scrollbar{width:4px}
76
- .fm-list::-webkit-scrollbar-thumb{background:var(--b2)}
77
- .fm-empty{display:flex;align-items:center;justify-content:center;height:100%;color:var(--t3);font-size:13px}
78
- .fm-item{display:flex;align-items:center;padding:9px 12px;border-radius:6px;cursor:pointer;transition:background .1s;gap:10px;user-select:none}
79
- .fm-item:hover{background:var(--s2)}
80
- .fm-item.selected{background:rgba(74,222,128,.08);outline:1px solid rgba(74,222,128,.2)}
81
- .fm-icon{width:20px;text-align:center;font-size:14px;flex-shrink:0}
82
- .fi-dir{color:var(--blue)}.fi-cfg{color:var(--yellow)}.fi-jar{color:var(--accent)}.fi-log{color:var(--t3)}.fi-other{color:var(--t2)}
83
- .fm-name{flex:1;font-size:13px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
84
- .fm-size{font-size:11px;color:var(--t3);flex-shrink:0}
85
-
86
- .ctx-menu{position:fixed;background:#1a1a1a;border:1px solid var(--b1);border-radius:8px;padding:6px;z-index:1000;min-width:160px;box-shadow:0 8px 32px rgba(0,0,0,.6);animation:ctxIn .12s ease}
87
- @keyframes ctxIn{from{opacity:0;transform:scale(.95)}to{opacity:1;transform:none}}
88
- .ctx-item{padding:7px 12px;border-radius:5px;cursor:pointer;font-size:13px;color:var(--t2);display:flex;align-items:center;gap:8px;transition:var(--trans)}
89
- .ctx-item:hover{background:var(--s3);color:var(--t1)}
90
- .ctx-item.danger{color:var(--red)}.ctx-item.danger:hover{background:rgba(248,113,113,.1)}
91
- .ctx-sep{height:1px;background:var(--b1);margin:4px 0}
92
-
93
- /* CONFIG */
94
- .cfg-wrap{flex:1;overflow-y:auto;padding:16px;scrollbar-width:thin;scrollbar-color:var(--b2) transparent}
95
- .cfg-section{background:var(--s1);border:1px solid var(--b1);border-radius:10px;margin-bottom:16px;overflow:hidden}
96
- .cfg-section-head{padding:12px 16px;border-bottom:1px solid var(--b1);font-size:12px;font-weight:600;color:var(--t3);text-transform:uppercase;letter-spacing:.06em}
97
- .cfg-row{display:flex;align-items:center;padding:10px 16px;border-bottom:1px solid rgba(255,255,255,.03);gap:12px}
98
- .cfg-row:last-child{border-bottom:none}
99
- .cfg-key{flex:1;font-family:var(--mono);font-size:12.5px;color:var(--t2)}
100
- .cfg-val{flex:1;background:var(--s2);border:1px solid var(--b1);color:var(--t1);font-family:var(--mono);font-size:12px;padding:5px 10px;border-radius:6px;outline:none;transition:var(--trans)}
101
- .cfg-val:focus{border-color:var(--accent)}
102
- .cfg-save{margin:0 16px 16px;background:var(--accent);color:#000;border:none;padding:9px 20px;border-radius:var(--r);font-weight:600;font-size:13px;cursor:pointer;transition:var(--trans)}
103
- .cfg-save:hover{background:var(--accent2)}
104
- .coming-soon{display:flex;align-items:center;justify-content:center;height:100%;flex-direction:column;gap:12px;color:var(--t3)}
105
- .coming-soon i{font-size:36px;opacity:.3}
106
-
107
- /* MODALS */
108
- .overlay{position:fixed;inset:0;background:rgba(0,0,0,.7);z-index:500;display:flex;align-items:center;justify-content:center;animation:fadeIn .15s ease;backdrop-filter:blur(4px)}
109
- @keyframes fadeIn{from{opacity:0}to{opacity:1}}
110
- .modal{background:#161616;border:1px solid var(--b1);border-radius:12px;padding:24px;width:90%;max-width:480px;animation:modalIn .2s ease;box-shadow:0 24px 64px rgba(0,0,0,.6)}
111
- .modal.wide{max-width:760px}
112
- @keyframes modalIn{from{opacity:0;transform:translateY(12px) scale(.98)}to{opacity:1;transform:none}}
113
- .modal h3{font-size:15px;font-weight:600;margin-bottom:16px;color:var(--t1)}
114
- .modal input,.modal textarea{width:100%;background:var(--s2);border:1px solid var(--b1);color:var(--t1);font-family:var(--mono);font-size:13px;padding:9px 12px;border-radius:var(--r);outline:none;transition:var(--trans);margin-bottom:12px}
115
- .modal input:focus,.modal textarea:focus{border-color:var(--accent)}
116
- .modal textarea{min-height:320px;resize:vertical;line-height:1.6}
117
- .modal-actions{display:flex;justify-content:flex-end;gap:8px;margin-top:4px}
118
- .btn-ghost{background:transparent;border:1px solid var(--b1);color:var(--t2);padding:7px 16px;border-radius:6px;cursor:pointer;font-family:var(--font);font-size:13px;transition:var(--trans)}
119
- .btn-ghost:hover{border-color:var(--b2);color:var(--t1)}
120
- .btn-primary{background:var(--accent);color:#000;border:none;padding:7px 16px;border-radius:6px;font-family:var(--font);font-weight:600;font-size:13px;cursor:pointer;transition:var(--trans)}
121
- .btn-primary:hover{background:var(--accent2)}
122
- .btn-danger{background:transparent;border:1px solid var(--red);color:var(--red);padding:7px 16px;border-radius:6px;cursor:pointer;font-family:var(--font);font-size:13px;transition:var(--trans)}
123
- .btn-danger:hover{background:rgba(248,113,113,.1)}
124
- .upload-zone{border:2px dashed var(--b2);border-radius:8px;padding:32px;text-align:center;color:var(--t3);cursor:pointer;transition:var(--trans);margin-bottom:12px}
125
- .upload-zone:hover,.upload-zone.drag{border-color:var(--accent);color:var(--accent);background:rgba(74,222,128,.04)}
126
- .upload-zone i{font-size:24px;margin-bottom:8px;display:block}
127
- .upload-zone p{font-size:13px}
128
-
129
- #toast-root{position:fixed;bottom:24px;left:50%;transform:translateX(-50%);z-index:9999;display:flex;flex-direction:column;gap:8px;align-items:center;pointer-events:none}
130
-
131
- @media(max-width:600px){.sidebar{width:48px}.tb-btn span{display:none}.tb-btn{padding:0 10px}.fm-size{display:none}}
132
- </style>
133
  </head>
134
- <body>
135
- <nav class="sidebar">
136
- <button class="nav-btn active" onclick="switchTab('console',this)"><i class="fa-solid fa-terminal"></i><span class="tooltip">Console</span></button>
137
- <button class="nav-btn" onclick="switchTab('files',this)"><i class="fa-solid fa-folder-open"></i><span class="tooltip">Files</span></button>
138
- <button class="nav-btn" onclick="switchTab('config',this)"><i class="fa-solid fa-sliders"></i><span class="tooltip">Config</span></button>
139
- <button class="nav-btn" onclick="switchTab('plugins',this)" style="margin-top:auto"><i class="fa-solid fa-puzzle-piece"></i><span class="tooltip">Plugins</span></button>
140
- </nav>
141
-
142
- <div class="main">
143
- <!-- CONSOLE -->
144
- <div class="panel active" id="tab-console">
145
- <div class="console-wrap">
146
- <div class="console-blur"></div>
147
- <div class="console-out" id="console-out"></div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
148
  </div>
149
- <div class="console-input-bar">
150
- <span class="prompt">$</span>
151
- <input id="cmd-input" type="text" placeholder="Enter command..." autocomplete="off" spellcheck="false" onkeydown="cmdKey(event)">
152
- <button class="send-btn" onclick="sendCmd()"><i class="fa-solid fa-paper-plane"></i></button>
153
- </div>
154
- </div>
155
-
156
- <!-- FILES -->
157
- <div class="panel" id="tab-files">
158
- <div class="fm-toolbar">
159
- <div class="fm-breadcrumb" id="breadcrumb"></div>
160
- <button class="tb-btn" onclick="showMkdir()"><i class="fa-solid fa-folder-plus"></i><span>New Folder</span></button>
161
- <button class="tb-btn" onclick="showUpload()"><i class="fa-solid fa-upload"></i><span>Upload</span></button>
162
- </div>
163
- <div class="fm-list" id="fm-list"></div>
164
- </div>
165
 
166
- <!-- CONFIG -->
167
- <div class="panel" id="tab-config">
168
- <div class="cfg-wrap" id="cfg-wrap">
169
- <div class="fm-empty" style="height:80px"><i class="fa-solid fa-spinner fa-spin"></i>&nbsp;Loading...</div>
170
- </div>
171
- </div>
172
-
173
- <!-- PLUGINS -->
174
- <div class="panel" id="tab-plugins">
175
- <div class="coming-soon">
176
- <i class="fa-solid fa-puzzle-piece"></i>
177
- <p style="font-size:15px;font-weight:600;color:var(--t2)">Plugins</p>
178
- <p style="font-size:13px">Coming soon</p>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
179
  </div>
180
- </div>
181
- </div>
182
-
183
- <!-- MODAL -->
184
- <div id="overlay" class="overlay" style="display:none" onclick="closeModal(event)">
185
- <div class="modal" id="modal" onclick="event.stopPropagation()">
186
- <h3 id="modal-title"></h3>
187
- <div id="modal-body"></div>
188
- <div class="modal-actions" id="modal-actions"></div>
189
- </div>
190
- </div>
191
-
192
- <div id="toast-root"></div>
193
-
194
- <script>
195
- // ── WebSocket ──────────────────────────────────────────────
196
- const wsProto = location.protocol==='https:'?'wss':'ws';
197
- let ws, cmdHistory=[], histIdx=-1;
198
-
199
- function connectWS(){
200
- ws = new WebSocket(`${wsProto}://${location.host}/ws`);
201
- ws.onmessage = e => addLog(e.data);
202
- ws.onclose = () => setTimeout(connectWS, 2000);
203
- }
204
- connectWS();
205
-
206
- // ── Console ────────────────────────────────────────────────
207
- function classify(l){
208
- if(/\[WARN|WARN\]/i.test(l)) return 'warn';
209
- if(/\[ERROR|ERROR\]/i.test(l)||/exception/i.test(l)) return 'error';
210
- if(/Done|started|enabled|loaded/i.test(l)) return 'ok';
211
- return 'info';
212
- }
213
- function addLog(txt){
214
- const out = document.getElementById('console-out');
215
- const atBottom = out.scrollHeight - out.clientHeight - out.scrollTop < 40;
216
- const d = document.createElement('div');
217
- d.className = `log-line ${classify(txt)}`;
218
- d.textContent = txt;
219
- out.appendChild(d);
220
- if(out.children.length > 400) out.removeChild(out.firstChild);
221
- if(atBottom) out.scrollTop = out.scrollHeight;
222
- }
223
- function sendCmd(){
224
- const i = document.getElementById('cmd-input');
225
- const v = i.value.trim();
226
- if(!v || !ws || ws.readyState !== WebSocket.OPEN) return;
227
- ws.send(v);
228
- addLog('> ' + v);
229
- cmdHistory.unshift(v); histIdx = -1; i.value = '';
230
- }
231
- function cmdKey(e){
232
- if(e.key==='Enter') sendCmd();
233
- else if(e.key==='ArrowUp'){ histIdx=Math.min(histIdx+1,cmdHistory.length-1); document.getElementById('cmd-input').value=cmdHistory[histIdx]||''; }
234
- else if(e.key==='ArrowDown'){ histIdx=Math.max(histIdx-1,-1); document.getElementById('cmd-input').value=histIdx>=0?cmdHistory[histIdx]:''; }
235
- }
236
-
237
- // ── Tabs ───────────────────────────────────────────────────
238
- function switchTab(id, btn){
239
- document.querySelectorAll('.panel').forEach(p=>p.classList.remove('active'));
240
- document.querySelectorAll('.nav-btn').forEach(b=>b.classList.remove('active'));
241
- document.getElementById('tab-'+id).classList.add('active');
242
- btn.classList.add('active');
243
- if(id==='files') loadDir(currentPath);
244
- if(id==='config') loadConfig();
245
- }
246
-
247
- // ── File Manager ───────────────────────────────────────────
248
- let currentPath = '';
249
- const apiPost = (url, fd) => fetch(url, {method:'POST', body:fd});
250
-
251
- async function loadDir(path=''){
252
- currentPath = path;
253
- renderBreadcrumb(path);
254
- const list = document.getElementById('fm-list');
255
- list.innerHTML = '<div class="fm-empty"><i class="fa-solid fa-spinner fa-spin"></i>&nbsp;Loading...</div>';
256
- const items = await fetch(`/api/fs/list?path=${encodeURIComponent(path)}`).then(r=>r.json());
257
- list.innerHTML = '';
258
- if(!items.length){ list.innerHTML='<div class="fm-empty">Empty folder</div>'; return; }
259
- items.forEach(item => {
260
- const el = document.createElement('div');
261
- el.className = 'fm-item';
262
- const icon = getIcon(item);
263
- el.innerHTML = `<i class="fm-icon ${icon.cls} ${icon.ic}"></i><span class="fm-name">${item.name}</span><span class="fm-size">${item.is_dir ? '—' : fmtSize(item.size)}</span>`;
264
- el.addEventListener('click', () => { document.querySelectorAll('.fm-item').forEach(e=>e.classList.remove('selected')); el.classList.add('selected'); });
265
- el.addEventListener('dblclick', () => openItem(item));
266
- el.addEventListener('contextmenu', e => { e.preventDefault(); el.click(); showCtx(e, item); });
267
- list.appendChild(el);
268
- });
269
- }
270
- function getIcon(item){
271
- if(item.is_dir) return {cls:'fi-dir', ic:'fa-solid fa-folder'};
272
- const ext = item.name.split('.').pop().toLowerCase();
273
- if(['yml','yaml','json','toml','cfg','conf','properties'].includes(ext)) return {cls:'fi-cfg', ic:'fa-solid fa-file-code'};
274
- if(ext==='jar') return {cls:'fi-jar', ic:'fa-solid fa-cube'};
275
- if(ext==='log') return {cls:'fi-log', ic:'fa-solid fa-file-lines'};
276
- return {cls:'fi-other', ic:'fa-solid fa-file'};
277
- }
278
- function fmtSize(b){ if(b<1024) return b+'B'; if(b<1048576) return (b/1024).toFixed(1)+'KB'; return (b/1048576).toFixed(1)+'MB'; }
279
- function renderBreadcrumb(path){
280
- const bc = document.getElementById('breadcrumb');
281
- const parts = path ? path.split('/').filter(Boolean) : [];
282
- let html = `<span onclick="loadDir('')"><i class="fa-solid fa-server" style="color:var(--accent)"></i></span>`;
283
- let acc = '';
284
- parts.forEach(p => { acc += (acc?'/':'') + p; const cp=acc; html += `<span class="sep">/</span><span onclick="loadDir('${cp}')">${p}</span>`; });
285
- bc.innerHTML = html;
286
- }
287
- function fullPath(name){ return (currentPath ? currentPath+'/' : '') + name; }
288
- function openItem(item){
289
- const fp = fullPath(item.name);
290
- if(item.is_dir){ loadDir(fp); return; }
291
- const ext = item.name.split('.').pop().toLowerCase();
292
- const editable = ['yml','yaml','json','toml','cfg','conf','txt','md','properties','log','sh','py','js'].includes(ext);
293
- if(editable) openEditor(fp, item.name);
294
- else window.location = '/api/fs/download?path=' + encodeURIComponent(fp);
295
- }
296
-
297
- async function openEditor(fp, name){
298
- const res = await fetch(`/api/fs/read?path=${encodeURIComponent(fp)}`);
299
- if(!res.ok){ toast('Cannot read binary file'); return; }
300
- const text = await res.text();
301
- openModal('Edit — ' + name, 'wide');
302
- M.body.innerHTML = `<textarea id="editor-ta" spellcheck="false">${escHtml(text)}</textarea>`;
303
- M.actions.innerHTML = `<button class="btn-ghost" onclick="closeModal()">Cancel</button><button class="btn-primary" onclick="saveFile('${fp}')">Save</button>`;
304
- }
305
- async function saveFile(fp){
306
- const content = document.getElementById('editor-ta').value;
307
- const fd = new FormData(); fd.append('path', fp); fd.append('content', content);
308
- await apiPost('/api/fs/write', fd);
309
- toast('Saved'); closeModal();
310
- }
311
-
312
- function showCtx(e, item){
313
- document.querySelectorAll('.ctx-menu').forEach(c=>c.remove());
314
- const fp = fullPath(item.name);
315
- const m = document.createElement('div'); m.className = 'ctx-menu';
316
- const rows = [
317
- {icon:'fa-solid fa-pen', label:'Rename', fn:()=>showRename(fp, item.name)},
318
- ...(!item.is_dir ? [
319
- {icon:'fa-solid fa-edit', label:'Edit', fn:()=>openEditor(fp, item.name)},
320
- {icon:'fa-solid fa-download', label:'Download', fn:()=>{ window.location='/api/fs/download?path='+encodeURIComponent(fp); }}
321
- ] : []),
322
- {sep:true},
323
- {icon:'fa-solid fa-trash', label:'Delete', fn:()=>showDelete(fp, item.name), danger:true},
324
- ];
325
- rows.forEach(it => {
326
- if(it.sep){ const s=document.createElement('div'); s.className='ctx-sep'; m.appendChild(s); return; }
327
- const d = document.createElement('div'); d.className = 'ctx-item' + (it.danger?' danger':'');
328
- d.innerHTML = `<i class="${it.icon}"></i>${it.label}`;
329
- d.onclick = () => { m.remove(); it.fn(); };
330
- m.appendChild(d);
331
- });
332
- m.style.top = Math.min(e.clientY, window.innerHeight-160) + 'px';
333
- m.style.left = Math.min(e.clientX, window.innerWidth-180) + 'px';
334
- document.body.appendChild(m);
335
- setTimeout(()=>document.addEventListener('click', ()=>m.remove(), {once:true}), 10);
336
- }
337
-
338
- function showRename(fp, name){
339
- openModal('Rename');
340
- M.body.innerHTML = `<input id="rename-in" value="${name}" autocomplete="off">`;
341
- M.actions.innerHTML = `<button class="btn-ghost" onclick="closeModal()">Cancel</button><button class="btn-primary" onclick="doRename('${fp}')">Rename</button>`;
342
- setTimeout(()=>{ const i=document.getElementById('rename-in'); i.focus(); i.select(); }, 50);
343
- }
344
- async function doRename(fp){
345
- const nv = document.getElementById('rename-in').value.trim(); if(!nv) return;
346
- const fd = new FormData(); fd.append('path', fp); fd.append('new_name', nv);
347
- await apiPost('/api/fs/rename', fd); closeModal(); loadDir(currentPath);
348
- }
349
- function showDelete(fp, name){
350
- openModal('Delete');
351
- M.body.innerHTML = `<p style="color:var(--t2);font-size:13px;margin-bottom:16px">Delete <strong style="color:var(--t1)">${name}</strong>? This cannot be undone.</p>`;
352
- M.actions.innerHTML = `<button class="btn-ghost" onclick="closeModal()">Cancel</button><button class="btn-danger" onclick="doDelete('${fp}')">Delete</button>`;
353
- }
354
- async function doDelete(fp){
355
- const fd = new FormData(); fd.append('path', fp);
356
- await apiPost('/api/fs/delete', fd); closeModal(); loadDir(currentPath);
357
- }
358
- function showMkdir(){
359
- openModal('New Folder');
360
- M.body.innerHTML = `<input id="mkdir-in" placeholder="Folder name" autocomplete="off">`;
361
- M.actions.innerHTML = `<button class="btn-ghost" onclick="closeModal()">Cancel</button><button class="btn-primary" onclick="doMkdir()">Create</button>`;
362
- setTimeout(()=>document.getElementById('mkdir-in').focus(), 50);
363
- }
364
- async function doMkdir(){
365
- const n = document.getElementById('mkdir-in').value.trim(); if(!n) return;
366
- const fd = new FormData(); fd.append('path', (currentPath?currentPath+'/':'') + n);
367
- await apiPost('/api/fs/mkdir', fd); closeModal(); loadDir(currentPath);
368
- }
369
- function showUpload(){
370
- openModal('Upload Files');
371
- M.body.innerHTML = `<div class="upload-zone" id="drop-zone" onclick="document.getElementById('file-in').click()">
372
- <i class="fa-solid fa-cloud-arrow-up"></i><p>Click or drag &amp; drop files here</p></div>
373
- <input type="file" id="file-in" multiple style="display:none" onchange="handleUpload(this.files)">
374
- <div id="upload-prog"></div>`;
375
- M.actions.innerHTML = `<button class="btn-ghost" onclick="closeModal()">Close</button>`;
376
- const dz = document.getElementById('drop-zone');
377
- dz.ondragover = e => { e.preventDefault(); dz.classList.add('drag'); };
378
- dz.ondragleave = () => dz.classList.remove('drag');
379
- dz.ondrop = e => { e.preventDefault(); dz.classList.remove('drag'); handleUpload(e.dataTransfer.files); };
380
- }
381
- async function handleUpload(files){
382
- const prog = document.getElementById('upload-prog');
383
- for(const file of files){
384
- prog.innerHTML = `<p style="font-size:12px;color:var(--t2);margin-bottom:4px">Uploading ${file.name}…</p>`;
385
- const fd = new FormData(); fd.append('path', currentPath); fd.append('file', file);
386
- await apiPost('/api/fs/upload', fd);
387
- }
388
- prog.innerHTML = `<p style="font-size:12px;color:var(--accent)">Done!</p>`;
389
- loadDir(currentPath);
390
- }
391
-
392
- // ── Config ─────────────────────────────────────────────────
393
- async function loadConfig(){
394
- const wrap = document.getElementById('cfg-wrap');
395
- wrap.innerHTML = '<div class="fm-empty"><i class="fa-solid fa-spinner fa-spin"></i>&nbsp;Loading...</div>';
396
- const res = await fetch('/api/fs/read?path=server.properties');
397
- if(!res.ok){
398
- wrap.innerHTML = '<div class="fm-empty" style="flex-direction:column;gap:8px"><i class="fa-solid fa-circle-exclamation" style="color:var(--t3)"></i><p style="font-size:13px;color:var(--t3)">server.properties not found</p></div>';
399
- return;
400
- }
401
- const text = await res.text();
402
- const gmap = {motd:'General','max-players':'General','online-mode':'Network','server-ip':'Network','server-port':'Network','enable-rcon':'Network','rcon.port':'Network','rcon.password':'Network','level-name':'World','level-seed':'World','gamemode':'Game','difficulty':'Game','hardcore':'Game','pvp':'Game','spawn-monsters':'Game','spawn-animals':'Game','spawn-npcs':'Game','view-distance':'Performance','simulation-distance':'Performance','max-tick-time':'Performance','network-compression-threshold':'Performance'};
403
- const grouped = {General:[],World:[],Network:[],Game:[],Performance:[],Other:[]};
404
- text.split('\n').filter(l=>l&&!l.startsWith('#')).forEach(l=>{
405
- const eq = l.indexOf('='); if(eq<0) return;
406
- const k = l.slice(0,eq).trim(), v = l.slice(eq+1).trim();
407
- grouped[gmap[k]||'Other'].push({k,v});
408
- });
409
- wrap.innerHTML = '';
410
- Object.entries(grouped).forEach(([g, rows])=>{
411
- if(!rows.length) return;
412
- const sec = document.createElement('div'); sec.className = 'cfg-section';
413
- sec.innerHTML = `<div class="cfg-section-head">${g}</div>`;
414
- rows.forEach(({k,v})=>{
415
- const r = document.createElement('div'); r.className = 'cfg-row';
416
- r.innerHTML = `<span class="cfg-key">${k}</span><input class="cfg-val" data-key="${k}" value="${escHtml(v)}">`;
417
- sec.appendChild(r);
418
- });
419
- wrap.appendChild(sec);
420
- });
421
- const btn = document.createElement('button'); btn.className = 'cfg-save'; btn.textContent = 'Save Changes';
422
- btn.onclick = saveConfig; wrap.appendChild(btn);
423
- }
424
- async function saveConfig(){
425
- const res = await fetch('/api/fs/read?path=server.properties');
426
- let text = await res.text();
427
- document.querySelectorAll('.cfg-val').forEach(inp=>{
428
- text = text.replace(new RegExp(`^(${inp.dataset.key}\\s*=).*$`, 'm'), `$1${inp.value}`);
429
- });
430
- const fd = new FormData(); fd.append('path','server.properties'); fd.append('content',text);
431
- await apiPost('/api/fs/write', fd);
432
- toast('server.properties saved');
433
- }
434
-
435
- // ── Modal ──────────────────────────────────────────────────
436
- const M = {body:null, actions:null};
437
- function openModal(title, cls=''){
438
- const mo = document.getElementById('modal');
439
- mo.className = 'modal' + (cls?' '+cls:'');
440
- document.getElementById('modal-title').textContent = title;
441
- M.body = document.getElementById('modal-body'); M.body.innerHTML = '';
442
- M.actions = document.getElementById('modal-actions'); M.actions.innerHTML = '';
443
- document.getElementById('overlay').style.display = 'flex';
444
- }
445
- function closeModal(e){
446
- if(e && e.target !== document.getElementById('overlay')) return;
447
- document.getElementById('overlay').style.display = 'none';
448
- }
449
- document.addEventListener('keydown', e => { if(e.key==='Escape') document.getElementById('overlay').style.display='none'; });
450
-
451
- // ── Toast ──────────────────────────────────────────────────
452
- function toast(msg){
453
- const t = document.createElement('div');
454
- t.style.cssText = 'background:#1a1a1a;border:1px solid var(--b1);color:var(--t1);padding:8px 18px;border-radius:8px;font-size:13px;white-space:nowrap;box-shadow:0 8px 24px rgba(0,0,0,.5);animation:fadeIn .2s ease;pointer-events:none';
455
- t.textContent = msg;
456
- document.getElementById('toast-root').appendChild(t);
457
- setTimeout(()=>t.remove(), 2400);
458
- }
459
- function escHtml(s){ return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }
460
-
461
- // Init
462
- loadDir('');
463
- </script>
464
- </body>
465
- </html>"""
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
 
468
- # ── Utilities ──────────────────────────────────────────────
 
 
469
  def get_safe_path(subpath: str):
470
  subpath = (subpath or "").strip("/")
471
  target = os.path.abspath(os.path.join(BASE_DIR, subpath))
472
  if not target.startswith(BASE_DIR):
473
- raise HTTPException(status_code=403, detail="Access denied")
474
  return target
475
 
476
-
477
  async def broadcast(message: str):
478
  output_history.append(message)
479
- dead = set()
480
  for client in connected_clients:
481
  try:
482
  await client.send_text(message)
483
- except Exception:
484
- dead.add(client)
485
- connected_clients.difference_update(dead)
486
-
487
-
488
- # ── Minecraft Process ──────────────────────────────────────
489
- async def read_stream(stream):
 
490
  while True:
491
  try:
492
  line = await stream.readline()
493
- if not line:
494
- break
495
- await broadcast(line.decode('utf-8', errors='replace').rstrip('\r\n'))
496
  except Exception:
497
  break
498
 
499
-
500
  async def start_minecraft():
501
  global mc_process
502
  java_args = [
@@ -521,20 +636,20 @@ async def start_minecraft():
521
  )
522
  asyncio.create_task(read_stream(mc_process.stdout))
523
 
524
-
525
  @app.on_event("startup")
526
  async def startup_event():
 
527
  asyncio.create_task(start_minecraft())
528
 
529
-
530
- # ── Routes ─────────────────────────────────────────────────
 
531
  @app.get("/")
532
  def get_panel():
533
  return HTMLResponse(content=HTML_CONTENT)
534
 
535
-
536
  @app.websocket("/ws")
537
- async def ws_endpoint(websocket: WebSocket):
538
  await websocket.accept()
539
  connected_clients.add(websocket)
540
  for line in output_history:
@@ -545,86 +660,98 @@ async def ws_endpoint(websocket: WebSocket):
545
  if mc_process and mc_process.stdin:
546
  mc_process.stdin.write((cmd + "\n").encode('utf-8'))
547
  await mc_process.stdin.drain()
548
- except Exception:
549
- connected_clients.discard(websocket)
550
-
551
 
552
  @app.get("/api/fs/list")
553
  def fs_list(path: str = ""):
554
  target = get_safe_path(path)
555
- if not os.path.exists(target):
556
- return []
557
  items = []
558
  for f in os.listdir(target):
559
  fp = os.path.join(target, f)
560
  items.append({"name": f, "is_dir": os.path.isdir(fp), "size": os.path.getsize(fp) if not os.path.isdir(fp) else 0})
561
  return sorted(items, key=lambda x: (not x["is_dir"], x["name"].lower()))
562
 
563
-
564
  @app.get("/api/fs/read")
565
  def fs_read(path: str):
566
  target = get_safe_path(path)
567
- if not os.path.isfile(target):
568
- raise HTTPException(400, "Not a file")
569
  try:
570
  with open(target, 'r', encoding='utf-8') as f:
571
  return Response(content=f.read(), media_type="text/plain")
572
  except UnicodeDecodeError:
573
  raise HTTPException(400, "File is binary or unsupported encoding")
574
 
575
-
576
  @app.get("/api/fs/download")
577
  def fs_download(path: str):
578
  target = get_safe_path(path)
579
- if not os.path.isfile(target):
580
- raise HTTPException(400, "Not a file")
581
  return FileResponse(target, filename=os.path.basename(target))
582
 
583
-
584
  @app.post("/api/fs/write")
585
  def fs_write(path: str = Form(...), content: str = Form(...)):
586
- with open(get_safe_path(path), 'w', encoding='utf-8') as f:
 
587
  f.write(content)
588
  return {"status": "ok"}
589
 
590
-
591
  @app.post("/api/fs/upload")
592
  async def fs_upload(path: str = Form(""), file: UploadFile = File(...)):
593
  target_dir = get_safe_path(path)
594
- with open(os.path.join(target_dir, file.filename), "wb") as buffer:
 
 
595
  shutil.copyfileobj(file.file, buffer)
596
  return {"status": "ok"}
597
 
598
-
599
  @app.post("/api/fs/delete")
600
  def fs_delete(path: str = Form(...)):
601
- t = get_safe_path(path)
602
- if os.path.isdir(t):
603
- shutil.rmtree(t)
604
- else:
605
- os.remove(t)
606
  return {"status": "ok"}
607
 
 
 
 
 
 
 
 
 
608
 
609
- @app.post("/api/fs/mkdir")
610
- def fs_mkdir(path: str = Form(...)):
611
- os.makedirs(get_safe_path(path), exist_ok=True)
612
- return {"status": "ok"}
613
-
 
 
 
 
614
 
615
  @app.post("/api/fs/rename")
616
- def fs_rename(path: str = Form(...), new_name: str = Form(...)):
617
- src = get_safe_path(path)
618
- dst = os.path.join(os.path.dirname(src), new_name)
619
- os.rename(src, dst)
620
- return {"status": "ok"}
621
-
 
 
 
622
 
623
  @app.post("/api/fs/move")
624
- def fs_move(src_path: str = Form(...), dst_path: str = Form(...)):
625
- shutil.move(get_safe_path(src_path), get_safe_path(dst_path))
626
- return {"status": "ok"}
627
-
 
 
 
 
 
628
 
629
  if __name__ == "__main__":
630
  uvicorn.run(app, host="0.0.0.0", port=7860, log_level="warning")
 
2
  import asyncio
3
  import collections
4
  import shutil
5
+ from fastapi import FastAPI, WebSocket, Form, UploadFile, File, HTTPException
6
+ from fastapi.responses import HTMLResponse, Response, FileResponse
7
  from fastapi.middleware.cors import CORSMiddleware
8
  import uvicorn
9
 
 
15
  connected_clients = set()
16
  BASE_DIR = os.path.abspath("/app")
17
 
18
+ # -----------------
19
+ # HTML FRONTEND (Ultra-Modern Black & Green UI)
20
+ # -----------------
21
+ HTML_CONTENT = """
22
+ <!DOCTYPE html>
23
+ <html lang="en" class="dark">
24
  <head>
25
+ <meta charset="UTF-8">
26
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
27
+ <title>Server Engine</title>
28
+ <script src="https://cdn.tailwindcss.com"></script>
29
+ <script src="https://unpkg.com/lucide@latest"></script>
30
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@400;500;700&family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
31
+ <style>
32
+ :root {
33
+ --bg: #000000; --panel: #0a0a0a; --panel-hover: #111111;
34
+ --border: #1a1a1a; --text: #a1a1aa; --text-light: #e4e4e7;
35
+ --accent: #22c55e; --accent-hover: #16a34a; --accent-glow: rgba(34, 197, 94, 0.15);
36
+ }
37
+ body { background-color: var(--bg); color: var(--text); font-family: 'Inter', sans-serif; overflow: hidden; -webkit-font-smoothing: antialiased; }
38
+ .font-mono { font-family: 'JetBrains Mono', monospace; }
39
+
40
+ /* Custom Scrollbars */
41
+ ::-webkit-scrollbar { width: 4px; height: 4px; }
42
+ ::-webkit-scrollbar-track { background: transparent; }
43
+ ::-webkit-scrollbar-thumb { background: #27272a; border-radius: 4px; }
44
+ ::-webkit-scrollbar-thumb:hover { background: var(--accent); }
45
+
46
+ /* Sidebar & Layout */
47
+ .sidebar { width: 45px; transition: all 0.3s ease; }
48
+ .nav-btn { color: #52525b; transition: all 0.2s; position: relative; }
49
+ .nav-btn:hover, .nav-btn.active { color: var(--accent); }
50
+ .nav-btn.active::before { content: ''; position: absolute; left: -12px; top: 10%; height: 80%; width: 2px; background: var(--accent); border-radius: 4px; box-shadow: 0 0 8px var(--accent); }
51
+
52
+ /* Terminal Mask & Animations */
53
+ .term-mask { mask-image: linear-gradient(to bottom, transparent 0%, black 8%, black 100%); -webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 8%, black 100%); }
54
+ @keyframes fadeUpLine { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: translateY(0); } }
55
+ .log-line { animation: fadeUpLine 0.25s cubic-bezier(0.16, 1, 0.3, 1) forwards; word-break: break-all; padding: 1px 0; }
56
+
57
+ /* File Row */
58
+ .file-row { border-bottom: 1px solid var(--border); transition: background 0.15s; }
59
+ .file-row:hover { background: var(--panel-hover); }
60
+ .file-row:last-child { border-bottom: none; }
61
+
62
+ /* Modals & Inputs */
63
+ input:focus, textarea:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent-glow); }
64
+ .modal-enter { animation: modalIn 0.3s cubic-bezier(0.16, 1, 0.3, 1) forwards; }
65
+ @keyframes modalIn { from { opacity: 0; transform: scale(0.95) translateY(10px); } to { opacity: 1; transform: scale(1) translateY(0); } }
66
+
67
+ /* Loader */
68
+ .loader { animation: spin 1s linear infinite; }
69
+ @keyframes spin { 100% { transform: rotate(360deg); } }
70
+ .hidden-tab { display: none !important; }
71
+ </style>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  </head>
73
+ <body class="flex h-screen w-full select-none">
74
+
75
+ <!-- Super Slim Sidebar (45px) -->
76
+ <aside class="sidebar bg-[#050505] border-r border-[#1a1a1a] flex flex-col items-center py-6 gap-8 z-40 shrink-0">
77
+ <div class="text-green-500 shadow-[0_0_15px_rgba(34,197,94,0.3)] rounded-full"><i data-lucide="server" class="w-5 h-5"></i></div>
78
+ <nav class="flex flex-col gap-6 w-full items-center mt-4">
79
+ <button onclick="switchTab('console')" id="nav-console" class="nav-btn active" title="Console"><i data-lucide="terminal-square" class="w-5 h-5"></i></button>
80
+ <button onclick="switchTab('files')" id="nav-files" class="nav-btn" title="File Manager"><i data-lucide="folder-tree" class="w-5 h-5"></i></button>
81
+ <button onclick="switchTab('config')" id="nav-config" class="nav-btn" title="Server Config"><i data-lucide="settings-2" class="w-5 h-5"></i></button>
82
+ <button onclick="switchTab('plugins')" id="nav-plugins" class="nav-btn" title="Plugins"><i data-lucide="puzzle" class="w-5 h-5"></i></button>
83
+ </nav>
84
+ </aside>
85
+
86
+ <!-- Main Workspace -->
87
+ <main class="flex-1 relative bg-black flex flex-col overflow-hidden">
88
+
89
+ <!-- ================= CONSOLE TAB ================= -->
90
+ <div id="tab-console" class="absolute inset-0 flex flex-col p-3 sm:p-5">
91
+ <div class="flex-1 bg-panel border border-[#1a1a1a] rounded-xl flex flex-col overflow-hidden relative shadow-2xl">
92
+ <!-- Top Status Bar -->
93
+ <div class="h-10 border-b border-[#1a1a1a] bg-[#050505] flex items-center px-4 justify-between">
94
+ <div class="flex items-center gap-2">
95
+ <div class="w-2 h-2 rounded-full bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.8)]"></div>
96
+ <span class="text-xs font-mono text-zinc-400">engine-live-stream</span>
97
+ </div>
98
+ </div>
99
+
100
+ <!-- Terminal Output -->
101
+ <div id="terminal-output" class="flex-1 p-4 overflow-y-auto font-mono text-[13px] text-zinc-300 term-mask select-text">
102
+ <!-- Logs injected here -->
103
+ </div>
104
+
105
+ <!-- Terminal Input -->
106
+ <div class="h-14 border-t border-[#1a1a1a] bg-[#050505] flex items-center px-4 gap-3">
107
+ <i data-lucide="chevron-right" class="w-4 h-4 text-green-500"></i>
108
+ <input type="text" id="cmd-input" class="flex-1 bg-transparent border-none text-green-400 font-mono text-sm placeholder-zinc-700" placeholder="Execute command...">
109
+ </div>
110
+ </div>
111
+ </div>
112
+
113
+ <!-- ================= FILES TAB ================= -->
114
+ <div id="tab-files" class="hidden-tab absolute inset-0 flex flex-col p-3 sm:p-5">
115
+ <div class="flex-1 bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl flex flex-col overflow-hidden shadow-2xl">
116
+ <!-- File Header -->
117
+ <div class="bg-[#050505] border-b border-[#1a1a1a] px-4 py-3 flex flex-col sm:flex-row justify-between items-start sm:items-center gap-3">
118
+ <div class="flex items-center gap-2 text-sm font-mono text-zinc-400 w-full sm:w-auto overflow-x-auto hide-scrollbar" id="breadcrumbs"></div>
119
+
120
+ <div class="flex items-center gap-2 shrink-0">
121
+ <input type="file" id="file-upload" class="hidden" onchange="uploadFile(event)">
122
+ <button onclick="showCreateModal('file')" class="p-1.5 hover:bg-[#1a1a1a] hover:text-green-400 rounded transition-colors text-zinc-400" title="New File"><i data-lucide="file-plus" class="w-4 h-4"></i></button>
123
+ <button onclick="showCreateModal('folder')" class="p-1.5 hover:bg-[#1a1a1a] hover:text-green-400 rounded transition-colors text-zinc-400" title="New Folder"><i data-lucide="folder-plus" class="w-4 h-4"></i></button>
124
+ <button onclick="document.getElementById('file-upload').click()" class="p-1.5 hover:bg-[#1a1a1a] hover:text-green-400 rounded transition-colors text-zinc-400" title="Upload"><i data-lucide="upload" class="w-4 h-4"></i></button>
125
+ <div class="w-px h-4 bg-[#222] mx-1"></div>
126
+ <button onclick="loadFiles(currentPath)" class="p-1.5 hover:bg-[#1a1a1a] text-zinc-400 rounded transition-colors"><i data-lucide="rotate-cw" class="w-4 h-4"></i></button>
127
+ </div>
128
+ </div>
129
+
130
+ <!-- File List Header -->
131
+ <div class="hidden sm:grid grid-cols-12 gap-4 px-4 py-2 border-b border-[#1a1a1a] bg-[#080808] text-[11px] font-semibold text-zinc-600 uppercase tracking-widest">
132
+ <div class="col-span-8">Filename</div>
133
+ <div class="col-span-3 text-right">Size</div>
134
+ <div class="col-span-1 text-right"></div>
135
+ </div>
136
+
137
+ <!-- File List -->
138
+ <div class="flex-1 overflow-y-auto pb-10" id="file-list"></div>
139
+ </div>
140
+ </div>
141
+
142
+ <!-- ================= CONFIG TAB ================= -->
143
+ <div id="tab-config" class="hidden-tab absolute inset-0 flex flex-col p-3 sm:p-5">
144
+ <div class="flex-1 bg-[#0a0a0a] border border-[#1a1a1a] rounded-xl flex flex-col overflow-hidden shadow-2xl relative">
145
+ <div class="h-12 border-b border-[#1a1a1a] bg-[#050505] flex items-center px-4 justify-between">
146
+ <div class="flex items-center gap-2 text-sm font-mono text-zinc-300">
147
+ <i data-lucide="sliders" class="w-4 h-4 text-green-500"></i> server.properties
148
+ </div>
149
+ <button onclick="saveConfig()" class="bg-green-600 hover:bg-green-500 text-black px-4 py-1.5 rounded text-xs font-bold transition-colors flex items-center gap-2">
150
+ <i data-lucide="save" class="w-3.5 h-3.5"></i> Apply Details
151
+ </button>
152
+ </div>
153
+ <textarea id="config-editor" class="flex-1 bg-transparent p-4 text-zinc-300 font-mono text-[13px] resize-none focus:outline-none leading-relaxed select-text w-full h-full" spellcheck="false"></textarea>
154
+ </div>
155
+ </div>
156
+
157
+ <!-- ================= PLUGINS TAB ================= -->
158
+ <div id="tab-plugins" class="hidden-tab absolute inset-0 flex items-center justify-center">
159
+ <div class="text-center flex flex-col items-center gap-4 opacity-50">
160
+ <div class="w-16 h-16 rounded-2xl border border-green-500/30 flex items-center justify-center bg-green-500/5 shadow-[0_0_30px_rgba(34,197,94,0.1)]">
161
+ <i data-lucide="blocks" class="w-8 h-8 text-green-500"></i>
162
+ </div>
163
+ <div>
164
+ <h2 class="text-xl font-bold text-white tracking-tight">Plugin Manager</h2>
165
+ <p class="text-sm text-zinc-500 mt-1 font-mono">system.status = "COMING_SOON"</p>
166
+ </div>
167
+ </div>
168
+ </div>
169
+
170
+ </main>
171
+
172
+ <!-- ================= CONTEXT MENU (•••) ================= -->
173
+ <div id="context-menu" class="hidden absolute z-50 bg-[#0a0a0a] border border-[#222] rounded-md shadow-2xl py-1 w-36 overflow-hidden">
174
+ <!-- Injected via JS -->
175
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
+ <!-- ================= CUSTOM MODALS OVERLAY ================= -->
178
+ <div id="modal-overlay" class="hidden fixed inset-0 z-[100] bg-black/60 backdrop-blur-sm flex items-center justify-center p-4 opacity-0 transition-opacity duration-200">
179
+
180
+ <!-- Input Modal (Create/Rename/Move) -->
181
+ <div id="input-modal" class="hidden bg-[#0a0a0a] border border-[#222] rounded-xl w-full max-w-sm shadow-2xl flex-col overflow-hidden modal-enter">
182
+ <div class="p-5 border-b border-[#1a1a1a]">
183
+ <h3 id="input-modal-title" class="text-white font-medium text-sm">Action</h3>
184
+ <p id="input-modal-desc" class="text-xs text-zinc-500 mt-1"></p>
185
+ </div>
186
+ <div class="p-5">
187
+ <input type="text" id="input-modal-field" class="w-full bg-[#050505] border border-[#222] text-white text-sm rounded-lg px-3 py-2.5 focus:border-green-500 transition-colors font-mono" autocomplete="off">
188
+ </div>
189
+ <div class="px-5 py-3 bg-[#050505] border-t border-[#1a1a1a] flex justify-end gap-2">
190
+ <button onclick="closeModal()" class="px-4 py-1.5 text-xs text-zinc-400 hover:text-white transition-colors">Cancel</button>
191
+ <button id="input-modal-submit" class="px-4 py-1.5 bg-green-600 hover:bg-green-500 text-black text-xs font-bold rounded transition-colors">Confirm</button>
192
+ </div>
193
+ </div>
194
+
195
+ <!-- Confirm Modal (Delete) -->
196
+ <div id="confirm-modal" class="hidden bg-[#0a0a0a] border border-[#222] rounded-xl w-full max-w-sm shadow-2xl flex-col overflow-hidden modal-enter">
197
+ <div class="p-5 border-b border-[#1a1a1a] flex gap-3">
198
+ <i data-lucide="alert-triangle" class="w-5 h-5 text-red-500 shrink-0 mt-0.5"></i>
199
+ <div>
200
+ <h3 id="confirm-modal-title" class="text-white font-medium text-sm">Delete File</h3>
201
+ <p id="confirm-modal-msg" class="text-xs text-zinc-400 mt-1 leading-relaxed"></p>
202
+ </div>
203
+ </div>
204
+ <div class="px-5 py-3 bg-[#050505] flex justify-end gap-2">
205
+ <button onclick="closeModal()" class="px-4 py-1.5 text-xs text-zinc-400 hover:text-white transition-colors">Cancel</button>
206
+ <button id="confirm-modal-submit" class="px-4 py-1.5 bg-red-600 hover:bg-red-500 text-white text-xs font-bold rounded transition-colors">Delete Permanently</button>
207
+ </div>
208
+ </div>
209
+
210
+ <!-- Editor Modal -->
211
+ <div id="editor-modal" class="hidden bg-[#0a0a0a] border border-[#222] rounded-xl w-full max-w-4xl h-[85vh] shadow-2xl flex-col overflow-hidden modal-enter">
212
+ <div class="px-4 py-3 border-b border-[#1a1a1a] bg-[#050505] flex justify-between items-center">
213
+ <span id="editor-modal-title" class="text-sm font-mono text-green-400">editing...</span>
214
+ <div class="flex gap-2">
215
+ <button onclick="closeModal()" class="px-3 py-1.5 text-xs text-zinc-400 hover:text-white transition-colors">Discard</button>
216
+ <button id="editor-modal-submit" class="px-4 py-1.5 bg-green-600 hover:bg-green-500 text-black text-xs font-bold rounded transition-colors flex items-center gap-1.5">
217
+ <i data-lucide="save" class="w-3.5 h-3.5"></i> Save File
218
+ </button>
219
+ </div>
220
+ </div>
221
+ <textarea id="editor-modal-content" class="flex-1 bg-transparent p-4 text-zinc-300 font-mono text-[13px] resize-none focus:outline-none w-full leading-relaxed select-text" spellcheck="false"></textarea>
222
+ </div>
223
  </div>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
224
 
225
+ <!-- Toast Notifications -->
226
+ <div id="toast-container" class="fixed bottom-5 right-5 z-[200] flex flex-col gap-3 pointer-events-none"></div>
227
+
228
+ <script>
229
+ lucide.createIcons();
230
+
231
+ // ----------------- TOAST SYSTEM -----------------
232
+ function showToast(msg, type = 'info') {
233
+ const container = document.getElementById('toast-container');
234
+ const toast = document.createElement('div');
235
+ let color = type === 'error' ? 'text-red-500 border-red-500/20' : (type === 'success' ? 'text-green-500 border-green-500/20' : 'text-blue-400 border-blue-400/20');
236
+ toast.className = `flex items-center gap-3 bg-[#0a0a0a] border ${color} px-4 py-3 rounded-lg shadow-2xl translate-y-4 opacity-0 transition-all duration-300 pointer-events-auto`;
237
+ toast.innerHTML = `<span class="text-xs font-mono text-white">${msg}</span>`;
238
+ container.appendChild(toast);
239
+ requestAnimationFrame(() => toast.classList.remove('translate-y-4', 'opacity-0'));
240
+ setTimeout(() => {
241
+ toast.classList.add('translate-y-4', 'opacity-0');
242
+ setTimeout(() => toast.remove(), 300);
243
+ }, 3000);
244
+ }
245
+
246
+ // ----------------- NAVIGATION -----------------
247
+ function switchTab(tab) {
248
+ document.querySelectorAll('.tab-content, [id^="tab-"]').forEach(el => el.classList.add('hidden-tab'));
249
+ document.querySelectorAll('.nav-btn').forEach(el => el.classList.remove('active'));
250
+
251
+ document.getElementById('tab-' + tab).classList.remove('hidden-tab');
252
+ document.getElementById('nav-' + tab).classList.add('active');
253
+
254
+ if (tab === 'files' && !currentPathLoaded) { loadFiles(''); currentPathLoaded = true; }
255
+ if (tab === 'config') { loadConfig(); }
256
+ if (tab === 'console') { scrollToBottom(); }
257
+ }
258
+
259
+ // ----------------- MODAL SYSTEM -----------------
260
+ const overlay = document.getElementById('modal-overlay');
261
+ let currentModalAction = null;
262
+
263
+ function openModalElement(id) {
264
+ document.getElementById('input-modal').classList.add('hidden');
265
+ document.getElementById('confirm-modal').classList.add('hidden');
266
+ document.getElementById('editor-modal').classList.add('hidden');
267
+
268
+ overlay.classList.remove('hidden');
269
+ document.getElementById(id).classList.remove('hidden');
270
+ requestAnimationFrame(() => overlay.classList.remove('opacity-0'));
271
+ }
272
+
273
+ function closeModal() {
274
+ overlay.classList.add('opacity-0');
275
+ setTimeout(() => overlay.classList.add('hidden'), 200);
276
+ currentModalAction = null;
277
+ }
278
+
279
+ function showPrompt(title, desc, defaultVal, onConfirm) {
280
+ document.getElementById('input-modal-title').innerText = title;
281
+ document.getElementById('input-modal-desc').innerText = desc;
282
+ const input = document.getElementById('input-modal-field');
283
+ input.value = defaultVal;
284
+ openModalElement('input-modal');
285
+ input.focus();
286
+
287
+ const submitBtn = document.getElementById('input-modal-submit');
288
+ submitBtn.onclick = () => { onConfirm(input.value); closeModal(); };
289
+ input.onkeydown = (e) => { if(e.key === 'Enter') submitBtn.click(); };
290
+ }
291
+
292
+ function showConfirm(title, msg, onConfirm) {
293
+ document.getElementById('confirm-modal-title').innerText = title;
294
+ document.getElementById('confirm-modal-msg').innerText = msg;
295
+ openModalElement('confirm-modal');
296
+ document.getElementById('confirm-modal-submit').onclick = () => { onConfirm(); closeModal(); };
297
+ }
298
+
299
+ // ----------------- CUSTOM TERMINAL LOGIC -----------------
300
+ const termOut = document.getElementById('terminal-output');
301
+ const cmdInput = document.getElementById('cmd-input');
302
+
303
+ function parseANSI(str) {
304
+ str = str.replace(/</g, '&lt;').replace(/>/g, '&gt;');
305
+ let res = '', styles = [];
306
+ const chunks = str.split(/\\x1b\\[/);
307
+ res += chunks[0];
308
+
309
+ for (let i = 1; i < chunks.length; i++) {
310
+ const match = chunks[i].match(/^([0-9;]*)m(.*)/s);
311
+ if (match) {
312
+ const codes = match[1].split(';');
313
+ for(let code of codes) {
314
+ if(code === '' || code === '0') styles = [];
315
+ else if(code === '1') styles.push('font-weight:bold');
316
+ else if(code === '31' || code === '91') styles.push('color:#ef4444');
317
+ else if(code === '32' || code === '92') styles.push('color:#22c55e');
318
+ else if(code === '33' || code === '93') styles.push('color:#eab308');
319
+ else if(code === '34' || code === '94') styles.push('color:#3b82f6');
320
+ else if(code === '35' || code === '95') styles.push('color:#d946ef');
321
+ else if(code === '36' || code === '96') styles.push('color:#06b6d4');
322
+ else if(code === '37' || code === '97') styles.push('color:#fafafa');
323
+ else if(code === '90') styles.push('color:#71717a');
324
+ }
325
+ const styleStr = styles.length ? `style="${styles.join(';')}"` : '';
326
+ res += styles.length ? `<span ${styleStr}>${match[2]}</span>` : match[2];
327
+ } else {
328
+ res += '\\x1b[' + chunks[i]; // Unhandled escape
329
+ }
330
+ }
331
+ return res || '&nbsp;';
332
+ }
333
+
334
+ function scrollToBottom() {
335
+ termOut.scrollTop = termOut.scrollHeight;
336
+ }
337
+
338
+ function appendLog(text) {
339
+ const isAtBottom = termOut.scrollHeight - termOut.clientHeight <= termOut.scrollTop + 10;
340
+ const div = document.createElement('div');
341
+ div.className = 'log-line';
342
+ div.innerHTML = parseANSI(text);
343
+ termOut.appendChild(div);
344
+
345
+ // Keep memory bound
346
+ if(termOut.childElementCount > 400) termOut.removeChild(termOut.firstChild);
347
+ if(isAtBottom) scrollToBottom();
348
+ }
349
+
350
+ const wsUrl = (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + '/ws';
351
+ let ws;
352
+ function connectWS() {
353
+ ws = new WebSocket(wsUrl);
354
+ ws.onopen = () => appendLog('\\x1b[32m\\x1b[1m[Panel]\\x1b[0m Stream connected.');
355
+ ws.onmessage = e => appendLog(e.data);
356
+ ws.onclose = () => { appendLog('\\x1b[31m\\x1b[1m[Panel]\\x1b[0m Connection lost. Reconnecting...'); setTimeout(connectWS, 3000); };
357
+ }
358
+ connectWS();
359
+
360
+ cmdInput.addEventListener('keypress', e => {
361
+ if (e.key === 'Enter') {
362
+ const val = cmdInput.value.trim();
363
+ if(val && ws && ws.readyState === WebSocket.OPEN) {
364
+ appendLog(`\\x1b[90m> ${val}\\x1b[0m`);
365
+ ws.send(val);
366
+ cmdInput.value = '';
367
+ }
368
+ }
369
+ });
370
+
371
+ // ----------------- FILE MANAGER LOGIC -----------------
372
+ let currentPath = '';
373
+ let currentPathLoaded = false;
374
+ let menuTarget = null;
375
+
376
+ document.addEventListener('click', () => {
377
+ document.getElementById('context-menu').classList.add('hidden');
378
+ });
379
+
380
+ function openMenu(e, name, isDir) {
381
+ e.stopPropagation();
382
+ menuTarget = { name, isDir, path: (currentPath ? currentPath + '/' + name : name) };
383
+ const menu = document.getElementById('context-menu');
384
+
385
+ let html = '';
386
+ if(!isDir) html += `<button onclick="editFile('${menuTarget.path}')" class="w-full text-left px-4 py-2 hover:bg-[#1a1a1a] hover:text-green-400 text-xs text-zinc-300 transition-colors flex gap-2 items-center"><i data-lucide="edit-3" class="w-3.5 h-3.5"></i> Edit</button>`;
387
+
388
+ html += `<button onclick="initRename()" class="w-full text-left px-4 py-2 hover:bg-[#1a1a1a] hover:text-green-400 text-xs text-zinc-300 transition-colors flex gap-2 items-center"><i data-lucide="type" class="w-3.5 h-3.5"></i> Rename</button>
389
+ <button onclick="initMove()" class="w-full text-left px-4 py-2 hover:bg-[#1a1a1a] hover:text-green-400 text-xs text-zinc-300 transition-colors flex gap-2 items-center"><i data-lucide="move" class="w-3.5 h-3.5"></i> Move</button>`;
390
+
391
+ if(!isDir) html += `<button onclick="window.open('/api/fs/download?path=' + encodeURIComponent('${menuTarget.path}'))" class="w-full text-left px-4 py-2 hover:bg-[#1a1a1a] hover:text-green-400 text-xs text-zinc-300 transition-colors flex gap-2 items-center"><i data-lucide="download" class="w-3.5 h-3.5"></i> Download</button>`;
392
+
393
+ html += `<div class="h-px w-full bg-[#1a1a1a] my-1"></div>
394
+ <button onclick="initDelete()" class="w-full text-left px-4 py-2 hover:bg-red-500/10 hover:text-red-400 text-xs text-red-500 transition-colors flex gap-2 items-center"><i data-lucide="trash-2" class="w-3.5 h-3.5"></i> Delete</button>`;
395
+
396
+ menu.innerHTML = html;
397
+ lucide.createIcons();
398
+
399
+ menu.style.left = Math.min(e.pageX, window.innerWidth - 150) + 'px';
400
+ menu.style.top = Math.min(e.pageY, window.innerHeight - 200) + 'px';
401
+ menu.classList.remove('hidden');
402
+ }
403
+
404
+ async function loadFiles(path) {
405
+ currentPath = path;
406
+ renderBreadcrumbs(path);
407
+ const list = document.getElementById('file-list');
408
+ list.innerHTML = `<div class="flex justify-center py-10"><i data-lucide="loader-2" class="w-6 h-6 text-green-500 loader"></i></div>`;
409
+ lucide.createIcons();
410
+
411
+ try {
412
+ const res = await fetch(`/api/fs/list?path=${encodeURIComponent(path)}`);
413
+ const files = await res.json();
414
+ list.innerHTML = '';
415
+
416
+ if (path !== '') {
417
+ const parent = path.split('/').slice(0, -1).join('/');
418
+ list.innerHTML += `
419
+ <div class="file-row flex items-center px-4 py-3 cursor-pointer group" onclick="loadFiles('${parent}')">
420
+ <i data-lucide="corner-left-up" class="w-4 h-4 text-zinc-600 group-hover:text-green-400 mr-3 transition-colors"></i>
421
+ <span class="text-xs font-mono text-zinc-500 group-hover:text-green-400 transition-colors">..</span>
422
+ </div>`;
423
+ }
424
+
425
+ if(files.length === 0 && path === '') list.innerHTML += `<div class="text-center py-10 text-zinc-600 text-xs font-mono">Directory empty</div>`;
426
+
427
+ files.forEach(f => {
428
+ const icon = f.is_dir ? '<i data-lucide="folder" class="w-4 h-4 text-green-500"></i>' : '<i data-lucide="file" class="w-4 h-4 text-zinc-500"></i>';
429
+ const sizeStr = f.is_dir ? '--' : (f.size > 1024*1024 ? (f.size/(1024*1024)).toFixed(1) + ' MB' : (f.size / 1024).toFixed(1) + ' KB');
430
+ const clickAct = f.is_dir ? `onclick="loadFiles('${currentPath ? currentPath + '/' + f.name : f.name}')"` : '';
431
+
432
+ list.innerHTML += `
433
+ <div class="file-row flex flex-col sm:grid sm:grid-cols-12 items-start sm:items-center px-4 py-2.5 gap-2 group cursor-pointer" ${clickAct}>
434
+ <div class="col-span-8 flex items-center gap-3 w-full truncate">
435
+ ${icon}
436
+ <span class="text-[13px] font-mono text-zinc-300 group-hover:text-white transition-colors truncate">${f.name}</span>
437
+ </div>
438
+ <div class="col-span-3 text-right text-[11px] text-zinc-600 font-mono hidden sm:block">${sizeStr}</div>
439
+ <div class="col-span-1 flex justify-end w-full sm:w-auto mt-1 sm:mt-0">
440
+ <button onclick="openMenu(event, '${f.name}', ${f.is_dir})" class="p-1 hover:bg-[#222] rounded text-zinc-500 hover:text-white transition-colors">
441
+ <i data-lucide="more-horizontal" class="w-4 h-4"></i>
442
+ </button>
443
+ </div>
444
+ </div>`;
445
+ });
446
+ lucide.createIcons();
447
+ } catch { showToast("Error loading files", "error"); }
448
+ }
449
+
450
+ function renderBreadcrumbs(path) {
451
+ const parts = path.split('/').filter(p => p);
452
+ let html = `<button onclick="loadFiles('')" class="hover:text-green-400 transition-colors"><i data-lucide="home" class="w-4 h-4"></i></button>`;
453
+ let build = '';
454
+ parts.forEach((p, i) => {
455
+ build += (build ? '/' : '') + p;
456
+ html += `<span class="opacity-30 mx-1">/</span>`;
457
+ if(i === parts.length - 1) html += `<span class="text-green-500">${p}</span>`;
458
+ else html += `<button onclick="loadFiles('${build}')" class="hover:text-green-400 transition-colors">${p}</button>`;
459
+ });
460
+ document.getElementById('breadcrumbs').innerHTML = html;
461
+ lucide.createIcons();
462
+ }
463
+
464
+ // --- CRUD ACTIONS ---
465
+ function showCreateModal(type) {
466
+ showPrompt(`New ${type === 'folder' ? 'Folder' : 'File'}`, 'Enter name:', '', async (val) => {
467
+ if(!val) return;
468
+ const path = currentPath ? `${currentPath}/${val}` : val;
469
+ const endpoint = type === 'folder' ? '/api/fs/create_dir' : '/api/fs/create_file';
470
+ const fd = new FormData(); fd.append('path', path);
471
+ try {
472
+ const r = await fetch(endpoint, { method: 'POST', body: fd });
473
+ if(r.ok) { showToast('Created successfully', 'success'); loadFiles(currentPath); }
474
+ else showToast('Failed to create', 'error');
475
+ } catch { showToast('Network error', 'error'); }
476
+ });
477
+ }
478
+
479
+ function initRename() {
480
+ const t = menuTarget;
481
+ showPrompt('Rename', `Enter new name for ${t.name}:`, t.name, async (val) => {
482
+ if(!val || val === t.name) return;
483
+ const fd = new FormData(); fd.append('old_path', t.path); fd.append('new_name', val);
484
+ try {
485
+ const r = await fetch('/api/fs/rename', { method: 'POST', body: fd });
486
+ if(r.ok) { showToast('Renamed', 'success'); loadFiles(currentPath); }
487
+ else showToast('Rename failed', 'error');
488
+ } catch { showToast('Network error', 'error'); }
489
+ });
490
+ }
491
+
492
+ function initMove() {
493
+ const t = menuTarget;
494
+ showPrompt('Move', `Enter destination folder path for ${t.name} (relative to root, leave blank for root):`, '', async (val) => {
495
+ const destFolder = val.trim();
496
+ const destPath = destFolder ? `${destFolder}/${t.name}` : t.name;
497
+ if(destPath === t.path) return;
498
+ const fd = new FormData(); fd.append('source', t.path); fd.append('dest', destPath);
499
+ try {
500
+ const r = await fetch('/api/fs/move', { method: 'POST', body: fd });
501
+ if(r.ok) { showToast('Moved', 'success'); loadFiles(currentPath); }
502
+ else showToast('Move failed', 'error');
503
+ } catch { showToast('Network error', 'error'); }
504
+ });
505
+ }
506
+
507
+ function initDelete() {
508
+ const t = menuTarget;
509
+ showConfirm('Delete Permanently', `Are you sure you want to delete ${t.name}? This action cannot be undone.`, async () => {
510
+ const fd = new FormData(); fd.append('path', t.path);
511
+ try {
512
+ const r = await fetch('/api/fs/delete', { method: 'POST', body: fd });
513
+ if(r.ok) { showToast('Deleted', 'success'); loadFiles(currentPath); }
514
+ else showToast('Delete failed', 'error');
515
+ } catch { showToast('Network error', 'error'); }
516
+ });
517
+ }
518
+
519
+ async function uploadFile(e) {
520
+ const file = e.target.files[0];
521
+ if(!file) return;
522
+ showToast(`Uploading ${file.name}...`);
523
+ const fd = new FormData(); fd.append('path', currentPath); fd.append('file', file);
524
+ try {
525
+ const r = await fetch('/api/fs/upload', { method: 'POST', body: fd });
526
+ if(r.ok) { showToast('Upload complete', 'success'); loadFiles(currentPath); }
527
+ else showToast('Upload failed', 'error');
528
+ } catch { showToast('Network error', 'error'); }
529
+ e.target.value = '';
530
+ }
531
+
532
+ // --- EDITOR LOGIC ---
533
+ let currentEditPath = '';
534
+ async function editFile(path) {
535
+ try {
536
+ const r = await fetch(`/api/fs/read?path=${encodeURIComponent(path)}`);
537
+ if(!r.ok) throw new Error();
538
+ const text = await r.text();
539
+ currentEditPath = path;
540
+ document.getElementById('editor-modal-title').innerText = path;
541
+ document.getElementById('editor-modal-content').value = text;
542
+ openModalElement('editor-modal');
543
+
544
+ document.getElementById('editor-modal-submit').onclick = async () => {
545
+ const fd = new FormData(); fd.append('path', currentEditPath);
546
+ fd.append('content', document.getElementById('editor-modal-content').value);
547
+ const res = await fetch('/api/fs/write', { method: 'POST', body: fd });
548
+ if(res.ok) { showToast('File saved', 'success'); closeModal(); }
549
+ else showToast('Save failed', 'error');
550
+ };
551
+ } catch { showToast('Cannot open file (might be binary)', 'error'); }
552
+ }
553
+
554
+ // --- CONFIG TAB LOGIC ---
555
+ async function loadConfig() {
556
+ try {
557
+ const r = await fetch(`/api/fs/read?path=server.properties`);
558
+ if(r.ok) {
559
+ document.getElementById('config-editor').value = await r.text();
560
+ } else {
561
+ document.getElementById('config-editor').value = "# server.properties not found yet.";
562
+ }
563
+ } catch { showToast('Failed to load config', 'error'); }
564
+ }
565
+
566
+ async function saveConfig() {
567
+ const fd = new FormData();
568
+ fd.append('path', 'server.properties');
569
+ fd.append('content', document.getElementById('config-editor').value);
570
+ try {
571
+ const r = await fetch('/api/fs/write', { method: 'POST', body: fd });
572
+ if(r.ok) showToast('Config applied successfully', 'success');
573
+ else showToast('Failed to save', 'error');
574
+ } catch { showToast('Network error', 'error'); }
575
+ }
576
+
577
+ </script>
578
+ </body>
579
+ </html>
580
+ """
581
 
582
+ # -----------------
583
+ # UTILITIES
584
+ # -----------------
585
  def get_safe_path(subpath: str):
586
  subpath = (subpath or "").strip("/")
587
  target = os.path.abspath(os.path.join(BASE_DIR, subpath))
588
  if not target.startswith(BASE_DIR):
589
+ raise HTTPException(status_code=403, detail="Access denied outside /app")
590
  return target
591
 
 
592
  async def broadcast(message: str):
593
  output_history.append(message)
594
+ dead_clients = set()
595
  for client in connected_clients:
596
  try:
597
  await client.send_text(message)
598
+ except:
599
+ dead_clients.add(client)
600
+ connected_clients.difference_update(dead_clients)
601
+
602
+ # -----------------
603
+ # SERVER PROCESSES
604
+ # -----------------
605
+ async def read_stream(stream, prefix=""):
606
  while True:
607
  try:
608
  line = await stream.readline()
609
+ if not line: break
610
+ line_str = line.decode('utf-8', errors='replace').rstrip('\r\n')
611
+ await broadcast(prefix + line_str)
612
  except Exception:
613
  break
614
 
 
615
  async def start_minecraft():
616
  global mc_process
617
  java_args = [
 
636
  )
637
  asyncio.create_task(read_stream(mc_process.stdout))
638
 
 
639
  @app.on_event("startup")
640
  async def startup_event():
641
+ os.makedirs(BASE_DIR, exist_ok=True)
642
  asyncio.create_task(start_minecraft())
643
 
644
+ # -----------------
645
+ # API ROUTING
646
+ # -----------------
647
  @app.get("/")
648
  def get_panel():
649
  return HTMLResponse(content=HTML_CONTENT)
650
 
 
651
  @app.websocket("/ws")
652
+ async def websocket_endpoint(websocket: WebSocket):
653
  await websocket.accept()
654
  connected_clients.add(websocket)
655
  for line in output_history:
 
660
  if mc_process and mc_process.stdin:
661
  mc_process.stdin.write((cmd + "\n").encode('utf-8'))
662
  await mc_process.stdin.drain()
663
+ except:
664
+ connected_clients.remove(websocket)
 
665
 
666
  @app.get("/api/fs/list")
667
  def fs_list(path: str = ""):
668
  target = get_safe_path(path)
669
+ if not os.path.exists(target): return []
 
670
  items = []
671
  for f in os.listdir(target):
672
  fp = os.path.join(target, f)
673
  items.append({"name": f, "is_dir": os.path.isdir(fp), "size": os.path.getsize(fp) if not os.path.isdir(fp) else 0})
674
  return sorted(items, key=lambda x: (not x["is_dir"], x["name"].lower()))
675
 
 
676
  @app.get("/api/fs/read")
677
  def fs_read(path: str):
678
  target = get_safe_path(path)
679
+ if not os.path.isfile(target): raise HTTPException(400, "Not a file")
 
680
  try:
681
  with open(target, 'r', encoding='utf-8') as f:
682
  return Response(content=f.read(), media_type="text/plain")
683
  except UnicodeDecodeError:
684
  raise HTTPException(400, "File is binary or unsupported encoding")
685
 
 
686
  @app.get("/api/fs/download")
687
  def fs_download(path: str):
688
  target = get_safe_path(path)
689
+ if not os.path.isfile(target): raise HTTPException(400, "Not a file")
 
690
  return FileResponse(target, filename=os.path.basename(target))
691
 
 
692
  @app.post("/api/fs/write")
693
  def fs_write(path: str = Form(...), content: str = Form(...)):
694
+ target = get_safe_path(path)
695
+ with open(target, 'w', encoding='utf-8') as f:
696
  f.write(content)
697
  return {"status": "ok"}
698
 
 
699
  @app.post("/api/fs/upload")
700
  async def fs_upload(path: str = Form(""), file: UploadFile = File(...)):
701
  target_dir = get_safe_path(path)
702
+ os.makedirs(target_dir, exist_ok=True)
703
+ target_file = os.path.join(target_dir, file.filename)
704
+ with open(target_file, "wb") as buffer:
705
  shutil.copyfileobj(file.file, buffer)
706
  return {"status": "ok"}
707
 
 
708
  @app.post("/api/fs/delete")
709
  def fs_delete(path: str = Form(...)):
710
+ target = get_safe_path(path)
711
+ if os.path.isdir(target): shutil.rmtree(target)
712
+ else: os.remove(target)
 
 
713
  return {"status": "ok"}
714
 
715
+ @app.post("/api/fs/create_dir")
716
+ def fs_create_dir(path: str = Form(...)):
717
+ target = get_safe_path(path)
718
+ try:
719
+ os.makedirs(target, exist_ok=True)
720
+ return {"status": "ok"}
721
+ except Exception as e:
722
+ raise HTTPException(400, str(e))
723
 
724
+ @app.post("/api/fs/create_file")
725
+ def fs_create_file(path: str = Form(...)):
726
+ target = get_safe_path(path)
727
+ try:
728
+ os.makedirs(os.path.dirname(target), exist_ok=True)
729
+ open(target, 'a').close()
730
+ return {"status": "ok"}
731
+ except Exception as e:
732
+ raise HTTPException(400, str(e))
733
 
734
  @app.post("/api/fs/rename")
735
+ def fs_rename(old_path: str = Form(...), new_name: str = Form(...)):
736
+ src = get_safe_path(old_path)
737
+ base_dir = os.path.dirname(src)
738
+ dst = os.path.join(base_dir, new_name)
739
+ try:
740
+ os.rename(src, dst)
741
+ return {"status": "ok"}
742
+ except Exception as e:
743
+ raise HTTPException(400, str(e))
744
 
745
  @app.post("/api/fs/move")
746
+ def fs_move(source: str = Form(...), dest: str = Form(...)):
747
+ src = get_safe_path(source)
748
+ dst = get_safe_path(dest)
749
+ try:
750
+ os.makedirs(os.path.dirname(dst), exist_ok=True)
751
+ shutil.move(src, dst)
752
+ return {"status": "ok"}
753
+ except Exception as e:
754
+ raise HTTPException(400, str(e))
755
 
756
  if __name__ == "__main__":
757
  uvicorn.run(app, host="0.0.0.0", port=7860, log_level="warning")