Spaces:
wpms
/
Paused

srinetwork commited on
Commit
b2f3503
·
verified ·
1 Parent(s): 2e5d75b

Update Dockerfile

Browse files
Files changed (1) hide show
  1. Dockerfile +408 -188
Dockerfile CHANGED
@@ -1,11 +1,13 @@
1
  FROM openjdk:21-jdk-slim
2
 
3
- # Install required packages
4
  RUN apt-get update && apt-get install -y \
5
  python3 \
6
  python3-pip \
7
  curl \
8
  git \
 
 
9
  && rm -rf /var/lib/apt/lists/*
10
 
11
  # Install Python WebSocket and Flask
@@ -13,7 +15,7 @@ RUN pip3 install flask flask-sock psutil --break-system-packages
13
 
14
  WORKDIR /app
15
 
16
- # Create startup script with web terminal
17
  RUN cat > start.sh << 'EOF'
18
  #!/bin/bash
19
  set -e
@@ -25,15 +27,20 @@ echo "🚀 Starting Minecraft Server with Web Terminal"
25
  echo "⏰ $(date)"
26
  echo "=========================================="
27
 
 
 
 
 
 
28
  # Clone private repo (requires GITHUB_TOKEN)
29
  if [ -n "$GITHUB_TOKEN" ]; then
30
  echo "📥 Cloning Minecraft server from GitHub..."
 
31
  git clone https://$GITHUB_TOKEN@github.com/Walukapah/bungemcserver.git mcserver
32
  cd mcserver
33
  echo "✅ Repository cloned successfully"
34
  else
35
  echo "❌ ERROR: GITHUB_TOKEN not set!"
36
- echo " Please set your GitHub personal access token"
37
  exit 1
38
  fi
39
 
@@ -43,44 +50,26 @@ if [ ! -f eula.txt ]; then
43
  echo "✅ EULA accepted"
44
  fi
45
 
46
- # Enable RCON for web terminal control
47
- if ! grep -q "enable-rcon=true" server.properties 2>/dev/null; then
48
- echo "" >> server.properties
49
- echo "enable-rcon=true" >> server.properties
50
- echo "rcon.port=25575" >> server.properties
51
- echo "rcon.password=mcadmin123" >> server.properties
52
- echo "broadcast-rcon-to-ops=true" >> server.properties
53
- echo "✅ RCON enabled for web terminal"
54
- fi
55
-
56
  # Create backup script
57
  cat > /app/backup.sh << 'BACKUPSCRIPT'
58
  #!/bin/bash
59
- cd /app/mcserver
60
-
61
- # Configure git
62
  git config user.email "minecraft@huggingface.co"
63
  git config user.name "Minecraft Bot"
64
-
65
- # Add all changes
66
  git add -A
67
-
68
- # Commit with timestamp
69
- git commit -m "Auto backup: $(date '+%Y-%m-%d %H:%M:%S')" || echo "No changes to commit"
70
-
71
- # Push to GitHub
72
- git push origin main || git push origin master || echo "Push failed"
73
  BACKUPSCRIPT
74
 
75
  chmod +x /app/backup.sh
76
 
77
- # Start backup loop in background (every 5 minutes)
78
  (
79
  while true; do
80
  sleep 300
81
  echo ""
82
  echo "💾 [BACKUP] Running auto-backup at $(date)"
83
- /app/backup.sh
84
  echo ""
85
  done
86
  ) &
@@ -89,7 +78,7 @@ echo "✅ Auto-backup enabled (every 5 minutes)"
89
  echo ""
90
 
91
  # ==========================================
92
- # WEB TERMINAL SERVER (Flask + WebSocket)
93
  # ==========================================
94
  cat > /app/web_terminal.py << 'PYTHON_SCRIPT'
95
  import os
@@ -99,6 +88,7 @@ import json
99
  import threading
100
  import time
101
  import queue
 
102
  from flask import Flask, render_template_string
103
  from flask_sock import Sock
104
  import psutil
@@ -106,16 +96,17 @@ import psutil
106
  app = Flask(__name__)
107
  sock = Sock(app)
108
 
109
- # Global variables for process management
110
  mc_process = None
111
  output_queue = queue.Queue()
112
  command_queue = queue.Queue()
 
113
 
114
  def start_minecraft():
115
  global mc_process
116
  mc_dir = "/app/mcserver"
117
-
118
- # Start Minecraft server with stdin/stdout pipes
 
119
  mc_process = subprocess.Popen(
120
  ["java", "-Xms1G", "-Xmx14G", "-XX:+UseG1GC",
121
  "-XX:+ParallelRefProcEnabled", "-XX:MaxGCPauseMillis=200",
@@ -125,32 +116,43 @@ def start_minecraft():
125
  stdout=subprocess.PIPE,
126
  stderr=subprocess.STDOUT,
127
  text=True,
128
- bufsize=1
 
129
  )
130
-
131
- # Read output and put in queue
 
132
  def read_output():
133
- for line in mc_process.stdout:
134
- output_queue.put(line)
135
-
 
 
 
 
 
 
136
  threading.Thread(target=read_output, daemon=True).start()
137
-
138
- # Process commands from queue
139
  def process_commands():
140
  while True:
141
  try:
142
- cmd = command_queue.get(timeout=0.1)
143
  if mc_process and mc_process.poll() is None:
144
- mc_process.stdin.write(cmd + "\n")
145
- mc_process.stdin.flush()
 
 
 
 
146
  except queue.Empty:
147
  continue
148
- except:
 
149
  break
150
-
151
  threading.Thread(target=process_commands, daemon=True).start()
152
 
153
- # HTML Template with xterm.js
154
  HTML_TEMPLATE = '''
155
  <!DOCTYPE html>
156
  <html>
@@ -158,84 +160,181 @@ HTML_TEMPLATE = '''
158
  <title>Minecraft Server - Web Terminal</title>
159
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css" />
160
  <style>
 
161
  body {
162
  margin: 0;
163
  padding: 0;
164
- background: #1e1e1e;
165
- font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 
166
  }
167
  .header {
168
- background: #2d2d2d;
169
- color: #fff;
170
- padding: 15px 20px;
171
  display: flex;
172
  justify-content: space-between;
173
  align-items: center;
174
- border-bottom: 3px solid #4CAF50;
175
  }
176
  .header h1 {
177
  margin: 0;
178
- font-size: 20px;
 
179
  display: flex;
180
  align-items: center;
181
  gap: 10px;
 
182
  }
183
- .status {
184
  display: flex;
185
  align-items: center;
186
- gap: 15px;
 
 
 
 
 
 
 
187
  }
188
  .status-badge {
189
- background: #4CAF50;
190
  color: white;
191
- padding: 5px 15px;
192
  border-radius: 20px;
193
  font-size: 12px;
194
- font-weight: bold;
 
195
  }
196
  .status-badge.offline {
197
- background: #f44336;
198
  }
199
- .terminal-container {
 
 
 
 
 
 
 
200
  padding: 20px;
201
- height: calc(100vh - 80px);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  }
203
  #terminal {
204
  width: 100%;
205
  height: 100%;
206
- background: #000;
207
- border-radius: 8px;
208
  padding: 10px;
209
  }
210
- .quick-cmds {
211
- position: fixed;
212
- bottom: 20px;
213
- right: 20px;
214
  display: flex;
215
  gap: 10px;
216
- flex-wrap: wrap;
217
- max-width: 400px;
218
- justify-content: flex-end;
219
  }
220
- .quick-cmds button {
221
- background: #4CAF50;
222
- color: white;
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  border: none;
224
- padding: 8px 16px;
225
- border-radius: 5px;
 
226
  cursor: pointer;
 
 
 
 
 
 
 
 
 
 
 
 
227
  font-size: 12px;
 
228
  transition: all 0.3s;
229
  }
230
- .quick-cmds button:hover {
231
- background: #45a049;
232
- transform: scale(1.05);
233
- }
234
- .quick-cmds button.danger {
235
- background: #f44336;
236
  }
237
- .quick-cmds button.danger:hover {
238
- background: #da190b;
 
239
  }
240
  </style>
241
  </head>
@@ -245,111 +344,177 @@ HTML_TEMPLATE = '''
245
  <span>⛏️</span>
246
  Minecraft Server Console
247
  </h1>
248
- <div class="status">
249
- <span id="cpu">CPU: --%</span>
250
- <span id="memory">RAM: --%</span>
251
- <span class="status-badge" id="status">ONLINE</span>
252
  </div>
253
  </div>
254
 
255
- <div class="terminal-container">
256
- <div id="terminal"></div>
257
- </div>
258
 
259
- <div class="quick-cmds">
260
- <button onclick="sendCmd('help')">Help</button>
261
- <button onclick="sendCmd('list')">Players</button>
262
- <button onclick="sendCmd('save-all')">Save World</button>
263
- <button onclick="sendCmd('say Server restart in 30s!')">Broadcast</button>
264
- <button class="danger" onclick="sendCmd('stop')">Stop Server</button>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
265
  </div>
266
 
267
  <script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
268
  <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.min.js"></script>
269
  <script>
270
  const term = new Terminal({
271
- fontSize: 14,
272
- fontFamily: 'Consolas, "Courier New", monospace',
273
  cursorBlink: true,
 
274
  theme: {
275
- background: '#000000',
276
- foreground: '#00ff00',
277
- cursor: '#00ff00',
278
- selection: '#4CAF50'
 
 
 
 
 
 
 
 
279
  },
280
- scrollback: 10000,
281
- cols: 120,
282
- rows: 40
283
  });
284
 
285
  const fitAddon = new FitAddon.FitAddon();
286
  term.loadAddon(fitAddon);
287
-
288
  term.open(document.getElementById('terminal'));
289
  fitAddon.fit();
290
 
291
- // Connect to WebSocket
292
- const ws = new WebSocket('ws://' + window.location.host + '/ws');
293
- let inputBuffer = '';
294
-
295
- ws.onopen = () => {
296
- term.writeln('\\r\\n');
297
- term.writeln('\\x1b[32m╔════════════════════════════════════════╗\\x1b[0m');
298
- term.writeln('\\x1b[32m║ Minecraft Server Web Terminal ║\\x1b[0m');
299
- term.writeln('\\x1b[32m╚════════════════════════════════════════╝\\x1b[0m');
300
- term.writeln('');
301
- term.writeln('\\x1b[33mConnected to server console...\\x1b[0m');
302
- term.writeln('');
303
- };
304
 
305
- ws.onmessage = (event) => {
306
- const data = JSON.parse(event.data);
307
- if (data.type === 'output') {
308
- term.write(data.data);
309
- } else if (data.type === 'stats') {
310
- document.getElementById('cpu').textContent = 'CPU: ' + data.cpu + '%';
311
- document.getElementById('memory').textContent = 'RAM: ' + data.memory + '%';
312
- if (!data.running) {
313
- document.getElementById('status').textContent = 'OFFLINE';
314
- document.getElementById('status').classList.add('offline');
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
315
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
316
  }
317
- };
318
 
319
- ws.onclose = () => {
320
- term.writeln('\\r\\n\\x1b[31m[Disconnected from server]\\x1b[0m');
321
- };
322
 
323
- // Handle input
324
- term.onData((data) => {
325
- const code = data.charCodeAt(0);
326
-
327
- if (code === 13) { // Enter
328
- ws.send(JSON.stringify({type: 'command', data: inputBuffer}));
329
- inputBuffer = '';
330
- term.write('\\r\\n');
331
- } else if (code === 127) { // Backspace
332
- if (inputBuffer.length > 0) {
333
- inputBuffer = inputBuffer.slice(0, -1);
334
- term.write('\\b \\b');
335
- }
336
- } else if (code >= 32 && code <= 126) { // Printable chars
337
- inputBuffer += data;
338
- term.write(data);
339
  }
340
- });
341
 
342
- // Quick command sender
343
  function sendCmd(cmd) {
344
- ws.send(JSON.stringify({type: 'command', data: cmd}));
345
- term.writeln('');
346
- term.writeln('\\x1b[36m[Quick Command] ' + cmd + '\\x1b[0m');
 
 
347
  }
348
 
349
- // Resize handling
 
 
 
 
 
350
  window.addEventListener('resize', () => {
351
  fitAddon.fit();
352
  });
 
 
353
  </script>
354
  </body>
355
  </html>
@@ -361,28 +526,43 @@ def index():
361
 
362
  @app.route('/health')
363
  def health():
364
- return {'status': 'running', 'minecraft': mc_process is not None and mc_process.poll() is None}
 
 
 
 
365
 
366
  @sock.route('/ws')
367
  def websocket(ws):
368
- # Send initial output history
369
- buffer = []
370
- while not output_queue.empty() and len(buffer) < 100:
 
 
371
  try:
372
- buffer.append(output_queue.get_nowait())
 
373
  except:
374
  break
375
 
376
- for line in buffer:
377
- ws.send(json.dumps({'type': 'output', 'data': line}))
 
 
 
 
 
 
378
 
379
  def send_output():
380
  while True:
381
  try:
382
- line = output_queue.get(timeout=0.1)
383
- ws.send(json.dumps({'type': 'output', 'data': line}))
 
 
 
384
  except queue.Empty:
385
- # Send stats periodically
386
  try:
387
  cpu = psutil.cpu_percent(interval=0.1)
388
  memory = psutil.virtual_memory().percent
@@ -393,59 +573,99 @@ def websocket(ws):
393
  'memory': memory,
394
  'running': running
395
  }))
396
- except:
397
- pass
398
- time.sleep(1)
399
- except:
 
400
  break
401
 
402
  output_thread = threading.Thread(target=send_output, daemon=True)
403
  output_thread.start()
404
 
405
- # Receive commands
406
  while True:
407
  try:
408
- data = ws.receive()
409
- msg = json.loads(data)
410
- if msg.get('type') == 'command':
411
- command_queue.put(msg.get('data', ''))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
412
  except:
413
- break
 
 
 
 
 
 
 
414
 
415
  if __name__ == '__main__':
416
- # Start Minecraft in background thread
417
  mc_thread = threading.Thread(target=start_minecraft, daemon=True)
418
  mc_thread.start()
419
 
420
- # Wait for Minecraft to start
421
- time.sleep(5)
422
 
423
- # Start Flask server
424
- app.run(host='0.0.0.0', port=7860, threaded=True)
 
425
  PYTHON_SCRIPT
426
 
427
- echo "🌐 Starting Web Terminal Server on port 7860..."
428
- python3 /app/web_terminal.py &
 
 
 
 
 
 
 
 
 
429
 
430
  echo ""
431
- echo "✅ Web Terminal ready at: http://your-domain:7860"
432
- echo "💡 Minecraft logs will stream to the web terminal"
 
433
  echo "=========================================="
434
 
435
- # Keep script running
436
  while true; do
437
- sleep 10
438
- # Check if processes are running
 
 
 
 
439
  if ! pgrep -f "web_terminal.py" > /dev/null; then
440
- echo "❌ Web terminal crashed, restarting..."
441
- python3 /app/web_terminal.py &
 
442
  fi
443
  done
444
  EOF
445
 
446
  RUN chmod +x start.sh
447
 
448
- # HF Spaces required port
449
  EXPOSE 7860 25565 25575
450
 
451
  CMD ["./start.sh"]
 
1
  FROM openjdk:21-jdk-slim
2
 
3
+ # Install required packages (ADDED: procps for pgrep, psmisc for fuser)
4
  RUN apt-get update && apt-get install -y \
5
  python3 \
6
  python3-pip \
7
  curl \
8
  git \
9
+ procps \
10
+ psmisc \
11
  && rm -rf /var/lib/apt/lists/*
12
 
13
  # Install Python WebSocket and Flask
 
15
 
16
  WORKDIR /app
17
 
18
+ # Create startup script with web terminal - FIXED VERSION
19
  RUN cat > start.sh << 'EOF'
20
  #!/bin/bash
21
  set -e
 
27
  echo "⏰ $(date)"
28
  echo "=========================================="
29
 
30
+ # Kill any existing processes on port 7860
31
+ echo "🔧 Cleaning up port 7860..."
32
+ fuser -k 7860/tcp 2>/dev/null || true
33
+ sleep 2
34
+
35
  # Clone private repo (requires GITHUB_TOKEN)
36
  if [ -n "$GITHUB_TOKEN" ]; then
37
  echo "📥 Cloning Minecraft server from GitHub..."
38
+ rm -rf mcserver
39
  git clone https://$GITHUB_TOKEN@github.com/Walukapah/bungemcserver.git mcserver
40
  cd mcserver
41
  echo "✅ Repository cloned successfully"
42
  else
43
  echo "❌ ERROR: GITHUB_TOKEN not set!"
 
44
  exit 1
45
  fi
46
 
 
50
  echo "✅ EULA accepted"
51
  fi
52
 
 
 
 
 
 
 
 
 
 
 
53
  # Create backup script
54
  cat > /app/backup.sh << 'BACKUPSCRIPT'
55
  #!/bin/bash
56
+ cd /app/mcserver 2>/dev/null || exit 0
 
 
57
  git config user.email "minecraft@huggingface.co"
58
  git config user.name "Minecraft Bot"
 
 
59
  git add -A
60
+ git commit -m "Auto backup: $(date '+%Y-%m-%d %H:%M:%S')" || true
61
+ git push origin main 2>/dev/null || git push origin master 2>/dev/null || true
 
 
 
 
62
  BACKUPSCRIPT
63
 
64
  chmod +x /app/backup.sh
65
 
66
+ # Start backup loop in background
67
  (
68
  while true; do
69
  sleep 300
70
  echo ""
71
  echo "💾 [BACKUP] Running auto-backup at $(date)"
72
+ /app/backup.sh 2>/dev/null || true
73
  echo ""
74
  done
75
  ) &
 
78
  echo ""
79
 
80
  # ==========================================
81
+ # WEB TERMINAL SERVER
82
  # ==========================================
83
  cat > /app/web_terminal.py << 'PYTHON_SCRIPT'
84
  import os
 
88
  import threading
89
  import time
90
  import queue
91
+ import signal
92
  from flask import Flask, render_template_string
93
  from flask_sock import Sock
94
  import psutil
 
96
  app = Flask(__name__)
97
  sock = Sock(app)
98
 
 
99
  mc_process = None
100
  output_queue = queue.Queue()
101
  command_queue = queue.Queue()
102
+ server_ready = threading.Event()
103
 
104
  def start_minecraft():
105
  global mc_process
106
  mc_dir = "/app/mcserver"
107
+
108
+ print("[MC] Starting Minecraft server...", flush=True)
109
+
110
  mc_process = subprocess.Popen(
111
  ["java", "-Xms1G", "-Xmx14G", "-XX:+UseG1GC",
112
  "-XX:+ParallelRefProcEnabled", "-XX:MaxGCPauseMillis=200",
 
116
  stdout=subprocess.PIPE,
117
  stderr=subprocess.STDOUT,
118
  text=True,
119
+ bufsize=1,
120
+ preexec_fn=os.setsid
121
  )
122
+
123
+ print(f"[MC] Minecraft PID: {mc_process.pid}", flush=True)
124
+
125
  def read_output():
126
+ try:
127
+ for line in mc_process.stdout:
128
+ output_queue.put(line)
129
+ if "Done" in line and "For help, type" in line:
130
+ server_ready.set()
131
+ print("[MC] Server is ready!", flush=True)
132
+ except Exception as e:
133
+ print(f"[MC] Output error: {e}", flush=True)
134
+
135
  threading.Thread(target=read_output, daemon=True).start()
136
+
 
137
  def process_commands():
138
  while True:
139
  try:
140
+ cmd = command_queue.get(timeout=1)
141
  if mc_process and mc_process.poll() is None:
142
+ try:
143
+ mc_process.stdin.write(cmd + "\n")
144
+ mc_process.stdin.flush()
145
+ print(f"[MC] Command: {cmd}", flush=True)
146
+ except Exception as e:
147
+ print(f"[MC] Command error: {e}", flush=True)
148
  except queue.Empty:
149
  continue
150
+ except Exception as e:
151
+ print(f"[MC] Processor error: {e}", flush=True)
152
  break
153
+
154
  threading.Thread(target=process_commands, daemon=True).start()
155
 
 
156
  HTML_TEMPLATE = '''
157
  <!DOCTYPE html>
158
  <html>
 
160
  <title>Minecraft Server - Web Terminal</title>
161
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/xterm@5.3.0/css/xterm.css" />
162
  <style>
163
+ * { box-sizing: border-box; }
164
  body {
165
  margin: 0;
166
  padding: 0;
167
+ background: #0d1117;
168
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Helvetica, Arial, sans-serif;
169
+ color: #c9d1d9;
170
  }
171
  .header {
172
+ background: #161b22;
173
+ border-bottom: 1px solid #30363d;
174
+ padding: 16px 24px;
175
  display: flex;
176
  justify-content: space-between;
177
  align-items: center;
 
178
  }
179
  .header h1 {
180
  margin: 0;
181
+ font-size: 18px;
182
+ font-weight: 600;
183
  display: flex;
184
  align-items: center;
185
  gap: 10px;
186
+ color: #f0f6fc;
187
  }
188
+ .status-area {
189
  display: flex;
190
  align-items: center;
191
+ gap: 20px;
192
+ font-size: 13px;
193
+ }
194
+ .stat-box {
195
+ background: #21262d;
196
+ padding: 6px 12px;
197
+ border-radius: 6px;
198
+ border: 1px solid #30363d;
199
  }
200
  .status-badge {
201
+ background: #238636;
202
  color: white;
203
+ padding: 6px 14px;
204
  border-radius: 20px;
205
  font-size: 12px;
206
+ font-weight: 600;
207
+ text-transform: uppercase;
208
  }
209
  .status-badge.offline {
210
+ background: #da3633;
211
  }
212
+ .main-container {
213
+ display: flex;
214
+ height: calc(100vh - 70px);
215
+ }
216
+ .sidebar {
217
+ width: 240px;
218
+ background: #161b22;
219
+ border-right: 1px solid #30363d;
220
  padding: 20px;
221
+ display: flex;
222
+ flex-direction: column;
223
+ gap: 12px;
224
+ }
225
+ .sidebar h3 {
226
+ margin: 0 0 10px 0;
227
+ font-size: 12px;
228
+ text-transform: uppercase;
229
+ color: #8b949e;
230
+ letter-spacing: 0.5px;
231
+ }
232
+ .cmd-btn {
233
+ background: #21262d;
234
+ border: 1px solid #30363d;
235
+ color: #c9d1d9;
236
+ padding: 10px 14px;
237
+ border-radius: 6px;
238
+ cursor: pointer;
239
+ font-size: 13px;
240
+ text-align: left;
241
+ transition: all 0.2s;
242
+ display: flex;
243
+ align-items: center;
244
+ gap: 8px;
245
+ }
246
+ .cmd-btn:hover {
247
+ background: #30363d;
248
+ border-color: #8b949e;
249
+ }
250
+ .cmd-btn.danger {
251
+ background: #da3633;
252
+ border-color: #f85149;
253
+ color: white;
254
+ }
255
+ .cmd-btn.danger:hover {
256
+ background: #f85149;
257
+ }
258
+ .terminal-wrapper {
259
+ flex: 1;
260
+ padding: 20px;
261
+ display: flex;
262
+ flex-direction: column;
263
+ }
264
+ .terminal-header {
265
+ background: #21262d;
266
+ padding: 10px 16px;
267
+ border-radius: 8px 8px 0 0;
268
+ border: 1px solid #30363d;
269
+ border-bottom: none;
270
+ font-size: 12px;
271
+ color: #8b949e;
272
+ display: flex;
273
+ align-items: center;
274
+ gap: 8px;
275
+ }
276
+ .terminal-container {
277
+ flex: 1;
278
+ background: #0d1117;
279
+ border-radius: 0 0 8px 8px;
280
+ border: 1px solid #30363d;
281
+ overflow: hidden;
282
+ position: relative;
283
  }
284
  #terminal {
285
  width: 100%;
286
  height: 100%;
 
 
287
  padding: 10px;
288
  }
289
+ .input-area {
 
 
 
290
  display: flex;
291
  gap: 10px;
292
+ margin-top: 15px;
 
 
293
  }
294
+ #cmdInput {
295
+ flex: 1;
296
+ background: #21262d;
297
+ border: 1px solid #30363d;
298
+ color: #f0f6fc;
299
+ padding: 12px 16px;
300
+ border-radius: 6px;
301
+ font-size: 14px;
302
+ font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
303
+ }
304
+ #cmdInput:focus {
305
+ outline: none;
306
+ border-color: #58a6ff;
307
+ }
308
+ .send-btn {
309
+ background: #238636;
310
  border: none;
311
+ color: white;
312
+ padding: 12px 24px;
313
+ border-radius: 6px;
314
  cursor: pointer;
315
+ font-weight: 600;
316
+ font-size: 14px;
317
+ }
318
+ .send-btn:hover {
319
+ background: #2ea043;
320
+ }
321
+ .connection-status {
322
+ position: fixed;
323
+ top: 80px;
324
+ right: 20px;
325
+ padding: 8px 16px;
326
+ border-radius: 6px;
327
  font-size: 12px;
328
+ font-weight: 600;
329
  transition: all 0.3s;
330
  }
331
+ .connection-status.connected {
332
+ background: #238636;
333
+ color: white;
 
 
 
334
  }
335
+ .connection-status.disconnected {
336
+ background: #da3633;
337
+ color: white;
338
  }
339
  </style>
340
  </head>
 
344
  <span>⛏️</span>
345
  Minecraft Server Console
346
  </h1>
347
+ <div class="status-area">
348
+ <div class="stat-box">CPU: <span id="cpu">--</span>%</div>
349
+ <div class="stat-box">RAM: <span id="memory">--</span>%</div>
350
+ <span class="status-badge" id="status">Starting...</span>
351
  </div>
352
  </div>
353
 
354
+ <div class="connection-status disconnected" id="connStatus">Disconnected</div>
 
 
355
 
356
+ <div class="main-container">
357
+ <div class="sidebar">
358
+ <h3>⚡ Quick Commands</h3>
359
+ <button class="cmd-btn" onclick="sendCmd('help')">📖 Help</button>
360
+ <button class="cmd-btn" onclick="sendCmd('list')">👥 Player List</button>
361
+ <button class="cmd-btn" onclick="sendCmd('save-all')">💾 Save World</button>
362
+ <button class="cmd-btn" onclick="sendCmd('say Hello from Web Console!')">💬 Broadcast</button>
363
+ <button class="cmd-btn" onclick="sendCmd('time set day')">☀️ Set Day</button>
364
+ <button class="cmd-btn" onclick="sendCmd('weather clear')">🌤️ Clear Weather</button>
365
+ <div style="flex: 1;"></div>
366
+ <button class="cmd-btn danger" onclick="sendCmd('stop')">🛑 Stop Server</button>
367
+ </div>
368
+
369
+ <div class="terminal-wrapper">
370
+ <div class="terminal-header">
371
+ <span style="color: #f85149;">●</span>
372
+ <span>server.jar</span>
373
+ <span style="margin-left: auto; color: #8b949e;">Live Console</span>
374
+ </div>
375
+ <div class="terminal-container">
376
+ <div id="terminal"></div>
377
+ </div>
378
+ <div class="input-area">
379
+ <input type="text" id="cmdInput" placeholder="Type command here (e.g., 'give @a diamond 64')..." autocomplete="off">
380
+ <button class="send-btn" onclick="sendInput()">Send</button>
381
+ </div>
382
+ </div>
383
  </div>
384
 
385
  <script src="https://cdn.jsdelivr.net/npm/xterm@5.3.0/lib/xterm.min.js"></script>
386
  <script src="https://cdn.jsdelivr.net/npm/xterm-addon-fit@0.8.0/lib/xterm-addon-fit.min.js"></script>
387
  <script>
388
  const term = new Terminal({
389
+ fontSize: 13,
390
+ fontFamily: '"JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace',
391
  cursorBlink: true,
392
+ cursorStyle: 'block',
393
  theme: {
394
+ background: '#0d1117',
395
+ foreground: '#c9d1d9',
396
+ cursor: '#58a6ff',
397
+ selection: '#264f78',
398
+ black: '#484f58',
399
+ red: '#ff7b72',
400
+ green: '#7ee787',
401
+ yellow: '#e3b341',
402
+ blue: '#79c0ff',
403
+ magenta: '#d2a8ff',
404
+ cyan: '#56d4dd',
405
+ white: '#f0f6fc'
406
  },
407
+ scrollback: 50000,
408
+ cols: 100,
409
+ rows: 30
410
  });
411
 
412
  const fitAddon = new FitAddon.FitAddon();
413
  term.loadAddon(fitAddon);
 
414
  term.open(document.getElementById('terminal'));
415
  fitAddon.fit();
416
 
417
+ let ws = null;
418
+ let reconnectAttempts = 0;
419
+ const maxReconnectAttempts = 10;
 
 
 
 
 
 
 
 
 
 
420
 
421
+ function connect() {
422
+ const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
423
+ ws = new WebSocket(protocol + '//' + window.location.host + '/ws');
424
+
425
+ ws.onopen = () => {
426
+ console.log('WebSocket connected');
427
+ reconnectAttempts = 0;
428
+ updateConnectionStatus(true);
429
+ term.writeln('\\r\\n');
430
+ term.writeln('\\x1b[32m╔══════════════════════════════════════════════════════════════╗\\x1b[0m');
431
+ term.writeln('\\x1b[32m║\\x1b[0m \\x1b[1;36mMinecraft Server Web Console\\x1b[0m \\x1b[32m║\\x1b[0m');
432
+ term.writeln('\\x1b[32m╚══════════════════════════════════════════════════════════════╝\\x1b[0m');
433
+ term.writeln('');
434
+ term.writeln('\\x1b[33mType commands below or use quick buttons on the left...\\x1b[0m');
435
+ term.writeln('');
436
+ };
437
+
438
+ ws.onmessage = (event) => {
439
+ const data = JSON.parse(event.data);
440
+ if (data.type === 'output') {
441
+ term.write(data.data);
442
+ } else if (data.type === 'stats') {
443
+ document.getElementById('cpu').textContent = data.cpu.toFixed(1);
444
+ document.getElementById('memory').textContent = data.memory.toFixed(1);
445
+ const statusEl = document.getElementById('status');
446
+ if (data.running) {
447
+ statusEl.textContent = 'Online';
448
+ statusEl.classList.remove('offline');
449
+ } else {
450
+ statusEl.textContent = 'Offline';
451
+ statusEl.classList.add('offline');
452
+ }
453
  }
454
+ };
455
+
456
+ ws.onclose = () => {
457
+ console.log('WebSocket disconnected');
458
+ updateConnectionStatus(false);
459
+ if (reconnectAttempts < maxReconnectAttempts) {
460
+ reconnectAttempts++;
461
+ term.writeln('\\r\\n\\x1b[33m[Connection lost. Reconnecting in 3s... (' + reconnectAttempts + '/' + maxReconnectAttempts + ')]\\x1b[0m');
462
+ setTimeout(connect, 3000);
463
+ } else {
464
+ term.writeln('\\r\\n\\x1b[31m[Connection failed. Please refresh the page.]\\x1b[0m');
465
+ }
466
+ };
467
+
468
+ ws.onerror = (error) => {
469
+ console.error('WebSocket error:', error);
470
+ };
471
+ }
472
+
473
+ function updateConnectionStatus(connected) {
474
+ const statusEl = document.getElementById('connStatus');
475
+ if (connected) {
476
+ statusEl.textContent = 'Connected';
477
+ statusEl.classList.remove('disconnected');
478
+ statusEl.classList.add('connected');
479
+ } else {
480
+ statusEl.textContent = 'Disconnected';
481
+ statusEl.classList.remove('connected');
482
+ statusEl.classList.add('disconnected');
483
  }
484
+ }
485
 
486
+ connect();
 
 
487
 
488
+ function sendInput() {
489
+ const input = document.getElementById('cmdInput');
490
+ const cmd = input.value.trim();
491
+ if (cmd && ws && ws.readyState === WebSocket.OPEN) {
492
+ ws.send(JSON.stringify({type: 'command', data: cmd}));
493
+ term.writeln('');
494
+ term.writeln('\\x1b[36m> ' + cmd + '\\x1b[0m');
495
+ input.value = '';
 
 
 
 
 
 
 
 
496
  }
497
+ }
498
 
 
499
  function sendCmd(cmd) {
500
+ if (ws && ws.readyState === WebSocket.OPEN) {
501
+ ws.send(JSON.stringify({type: 'command', data: cmd}));
502
+ term.writeln('');
503
+ term.writeln('\\x1b[36m[Quick] ' + cmd + '\\x1b[0m');
504
+ }
505
  }
506
 
507
+ document.getElementById('cmdInput').addEventListener('keypress', (e) => {
508
+ if (e.key === 'Enter') {
509
+ sendInput();
510
+ }
511
+ });
512
+
513
  window.addEventListener('resize', () => {
514
  fitAddon.fit();
515
  });
516
+
517
+ document.getElementById('cmdInput').focus();
518
  </script>
519
  </body>
520
  </html>
 
526
 
527
  @app.route('/health')
528
  def health():
529
+ return {
530
+ 'status': 'running',
531
+ 'minecraft': mc_process is not None and mc_process.poll() is None,
532
+ 'timestamp': time.time()
533
+ }
534
 
535
  @sock.route('/ws')
536
  def websocket(ws):
537
+ print("[WS] Client connected", flush=True)
538
+
539
+ # Send recent history
540
+ history = []
541
+ while not output_queue.empty() and len(history) < 50:
542
  try:
543
+ line = output_queue.get_nowait()
544
+ history.append(line)
545
  except:
546
  break
547
 
548
+ for line in history:
549
+ output_queue.put(line)
550
+
551
+ for line in history[-100:]:
552
+ try:
553
+ ws.send(json.dumps({'type': 'output', 'data': line}))
554
+ except:
555
+ break
556
 
557
  def send_output():
558
  while True:
559
  try:
560
+ line = output_queue.get(timeout=1)
561
+ try:
562
+ ws.send(json.dumps({'type': 'output', 'data': line}))
563
+ except:
564
+ break
565
  except queue.Empty:
 
566
  try:
567
  cpu = psutil.cpu_percent(interval=0.1)
568
  memory = psutil.virtual_memory().percent
 
573
  'memory': memory,
574
  'running': running
575
  }))
576
+ except Exception as e:
577
+ print(f"[WS] Stats error: {e}", flush=True)
578
+ break
579
+ except Exception as e:
580
+ print(f"[WS] Output error: {e}", flush=True)
581
  break
582
 
583
  output_thread = threading.Thread(target=send_output, daemon=True)
584
  output_thread.start()
585
 
 
586
  while True:
587
  try:
588
+ data = ws.receive(timeout=1)
589
+ if data:
590
+ msg = json.loads(data)
591
+ if msg.get('type') == 'command':
592
+ cmd = msg.get('data', '').strip()
593
+ if cmd:
594
+ print(f"[WS] Command: {cmd}", flush=True)
595
+ command_queue.put(cmd)
596
+ except Exception as e:
597
+ if "Connection closed" in str(e) or "timed out" in str(e).lower():
598
+ break
599
+ continue
600
+
601
+ print("[WS] Client disconnected", flush=True)
602
+
603
+ def cleanup(signum=None, frame=None):
604
+ print("\n[MAIN] Shutting down...", flush=True)
605
+ if mc_process:
606
+ try:
607
+ mc_process.stdin.write("stop\n")
608
+ mc_process.stdin.flush()
609
+ mc_process.wait(timeout=30)
610
  except:
611
+ try:
612
+ os.killpg(os.getpgid(mc_process.pid), signal.SIGTERM)
613
+ except:
614
+ pass
615
+ sys.exit(0)
616
+
617
+ signal.signal(signal.SIGTERM, cleanup)
618
+ signal.signal(signal.SIGINT, cleanup)
619
 
620
  if __name__ == '__main__':
621
+ print("[MAIN] Starting Minecraft...", flush=True)
622
  mc_thread = threading.Thread(target=start_minecraft, daemon=True)
623
  mc_thread.start()
624
 
625
+ print("[MAIN] Waiting for Minecraft to start...", flush=True)
626
+ server_ready.wait(timeout=60)
627
 
628
+ print("[MAIN] Starting web server on port 7860...", flush=True)
629
+ from werkzeug.serving import run_simple
630
+ run_simple('0.0.0.0', 7860, app, threaded=True, use_reloader=False)
631
  PYTHON_SCRIPT
632
 
633
+ echo "🌐 Starting Web Terminal Server..."
634
+ python3 /app/web_terminal.py 2>&1 &
635
+
636
+ sleep 5
637
+
638
+ if pgrep -f "web_terminal.py" > /dev/null; then
639
+ echo "✅ Web Terminal Server is running on port 7860"
640
+ else
641
+ echo "❌ Web Terminal failed to start"
642
+ exit 1
643
+ fi
644
 
645
  echo ""
646
+ echo "=========================================="
647
+ echo "✅ Minecraft Server with Web Terminal is LIVE!"
648
+ echo "🌐 Access at: https://your-space.hf.space"
649
  echo "=========================================="
650
 
651
+ # Keep container alive and monitor processes
652
  while true; do
653
+ sleep 30
654
+
655
+ if ! pgrep -f "server.jar" > /dev/null; then
656
+ echo "⚠️ Minecraft server not running!"
657
+ fi
658
+
659
  if ! pgrep -f "web_terminal.py" > /dev/null; then
660
+ echo "❌ Web Terminal crashed! Restarting..."
661
+ python3 /app/web_terminal.py 2>&1 &
662
+ sleep 5
663
  fi
664
  done
665
  EOF
666
 
667
  RUN chmod +x start.sh
668
 
 
669
  EXPOSE 7860 25565 25575
670
 
671
  CMD ["./start.sh"]