Spaces:
Paused
Paused
Remove playit tunnel client and config elements from dashboard
Browse filesFiles changed (2)
- Dockerfile+1-1
- app.py+4-277
25 unmodified lines2627282930313225 unmodified linesRUN pip3 install --no-cache-dir -r /app/requirements.txt# Create directories and assign ownership to user 1000RUN mkdir -p /app/minecraft /app/playit /data && \chown -R 1000:1000 /app /data# Switch to the non-root user25 unmodified lines2627282930313225 unmodified linesRUN pip3 install --no-cache-dir -r /app/requirements.txt# Create directories and assign ownership to user 1000RUN mkdir -p /app/minecraft /data && \chown -R 1000:1000 /app /data# Switch to the non-root user
37 unmodified lines383940414243447 unmodified lines525354555657585960616263646566676869707172737475767778798081828384858662 unmodified lines149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188443 unmodified lines632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795115 unmodified lines9119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469474 unmodified lines952953954955956957958959960961257 unmodified lines121912201221122212231224122512261227122812291230123112321233123425 unmodified lines126012611262126312641265126612671268126912701271127212731274127512761277127812791280128129 unmodified lines1311131213131314131513161317200 unmodified lines151815191520152115221523152415251526152715281529153015311532153315341535153615371538153991 unmodified lines16311632163316341635163616371 unmodified line163916401641164216431644164537 unmodified linesMAX_RAM = os.getenv("MAX_RAM", "4G")HF_TOKEN = os.getenv("HF_TOKEN", "")HF_DATASET = os.getenv("HF_DATASET", "")PLAYIT_SECRET = os.getenv("SECRET_KEY", "") # playit agent secret keyDASHBOARD_PASSWORD = os.getenv("DASHBOARD_PASSWORD", "") # Panel PasswordENABLE_BEDROCK = os.getenv("ENABLE_BEDROCK", "true").lower() == "true"CUSTOM_DOMAIN = os.getenv("CUSTOM_DOMAIN", "")7 unmodified lines# Determine server working directories (Checking for persistent storage volume at /data)if os.path.exists("/data") and os.access("/data", os.W_OK):SERVER_DIR = "/data/minecraft"PLAYIT_DIR = "/data/playit"BIN_DIR = "/data/bin"BACKUPS_DIR = "/data/backups"else:# Local fallback for free Hugging Face tierSERVER_DIR = os.path.abspath("./minecraft")PLAYIT_DIR = os.path.abspath("./playit")BIN_DIR = os.path.abspath("./bin")BACKUPS_DIR = os.path.abspath("./backups")os.makedirs(SERVER_DIR, exist_ok=True)os.makedirs(PLAYIT_DIR, exist_ok=True)os.makedirs(BIN_DIR, exist_ok=True)os.makedirs(BACKUPS_DIR, exist_ok=True)# Global variables to track processes and statesmc_process = Nonemc_logs = collections.deque(maxlen=500)playit_process = Noneplayit_claim_link = ""playit_status = "Offline"cf_process = Nonecf_status = "Offline"# Dynamic connection URLs parsed from playit logsplayit_java_url = ""playit_bedrock_address = ""playit_bedrock_port = ""backup_status = "Idle"last_backup_time = "Never"62 unmodified linesreturn full_pathreturn Nonedef check_and_download_playit():IS_WINDOWS = sys.platform.startswith("win")playit_name = "playit.exe" if IS_WINDOWS else "playit"playit_bin = os.path.join(BIN_DIR, playit_name)if os.path.exists(playit_bin):logger.info(f"Playit agent binary found: {playit_bin}")if not IS_WINDOWS:try:os.chmod(playit_bin, 0o755)except Exception:passreturn playit_binlogger.info("Playit agent not found. Downloading standalone binary...")if IS_WINDOWS:url = "https://github.com/playit-cloud/playit-agent/releases/download/v0.15.26/playit-windows-x86_64.exe"else:url = "https://github.com/playit-cloud/playit-agent/releases/download/v0.15.26/playit-linux-amd64"try:r = requests.get(url, stream=True, timeout=30)r.raise_for_status()with open(playit_bin, "wb") as f:for chunk in r.iter_content(chunk_size=8192):f.write(chunk)if not IS_WINDOWS:os.chmod(playit_bin, 0o755)logger.info(f"Playit agent downloaded successfully to {playit_bin}")return playit_binexcept Exception as e:logger.error(f"Error downloading playit agent: {e}")return Nonedef check_and_download_cloudflared():IS_WINDOWS = sys.platform.startswith("win")cf_name = "cloudflared.exe" if IS_WINDOWS else "cloudflared"443 unmodified linesbackup_server()return "Server stopped."# Playit.gg managementdef read_playit_output(log_path):global playit_process, playit_claim_link, playit_status, playit_java_url, playit_bedrock_address, playit_bedrock_port# Wait for the log file to be createdfor _ in range(30):if os.path.exists(log_path):breaktime.sleep(0.5)if not os.path.exists(log_path):logger.error(f"Playit log file {log_path} not found.")returntry:# Open in read mode, and continuously check for new lineswith open(log_path, "r", encoding="utf-8", errors="ignore") as f:while playit_process and playit_process.poll() is None:line = f.readline()if not line:time.sleep(0.5)continueline = line.strip()logger.info(f"[Playit] {line}")# Look for Claim linkif "https://playit.gg/claim/" in line:parts = line.split()for p in parts:if p.startswith("https://playit.gg/claim/"):playit_claim_link = pplayit_status = "Needs Claiming"# Parse connection detailsif "ply.gg" in line.lower() or "joinmc.link" in line.lower() or "playit.gg" in line.lower():matches = re.findall(r'([a-zA-Z0-9\.\-_]+\.(?:ply\.gg|joinmc\.link|playit\.gg)(?::\d+)?)', line)for addr in matches:if "udp" in line.lower() or "bedrock" in line.lower() or ":19132" in addr:if ":" in addr:host, port = addr.split(":")playit_bedrock_address = hostplayit_bedrock_port = portelse:playit_bedrock_address = addrplayit_bedrock_port = "19132"playit_status = "Online"logger.info("==================================================")logger.info(f"MC BEDROCK ADDRESS DETECTED: {playit_bedrock_address}:{playit_bedrock_port}")logger.info("==================================================")else:playit_java_url = addrplayit_status = "Online"logger.info("==================================================")logger.info(f"MC JAVA CONNECTION ADDRESS DETECTED: {playit_java_url}")logger.info("==================================================")if "authenticated" in line.lower() or "agent running" in line.lower() or "tunnel running" in line.lower():if playit_status == "Offline" or playit_status == "Needs Claiming":playit_status = "Online"except Exception as e:logger.error(f"Error reading playit log file: {e}")playit_status = "Offline"def start_playit_agent():global playit_process, playit_status, PLAYIT_SECRET# Terminate any dangling local playit process to prevent config file locking conflictstry:for proc in psutil.process_iter(['pid', 'name']):if proc.info['name'] in ['playit', 'playit.exe']:try:logger.info(f"Terminating dangling playit process (PID: {proc.info['pid']})")proc.terminate()proc.wait(timeout=2)except Exception:passexcept Exception:passif playit_process and playit_process.poll() is None:returnplayit_bin = check_and_download_playit()if not playit_bin:logger.error("Failed to download Playit binary.")playit_status = "Error starting"returntoml_path = os.path.join(PLAYIT_DIR, "playit.toml")log_file_path = os.path.join(PLAYIT_DIR, "playit.log")# Clean previous log fileif os.path.exists(log_file_path):try:os.remove(log_file_path)except Exception:passif PLAYIT_SECRET:try:os.makedirs(PLAYIT_DIR, exist_ok=True)with open(toml_path, "w") as f:f.write(f'[agent]\nsecret_key = "{PLAYIT_SECRET.strip()}"\n')logger.info("SECRET_KEY environment variable written to playit.toml")except Exception as e:logger.error(f"Failed to write SECRET_KEY to playit.toml: {e}")env = os.environ.copy()if shutil.which("stdbuf"):cmd = ["stdbuf", "-oL", "-eL", playit_bin, "--secret_path", toml_path, "--log_path", log_file_path, "start"]else:cmd = [playit_bin, "--secret_path", toml_path, "--log_path", log_file_path, "start"]playit_status = "Starting..."try:# Run process detached, log_path handles buffering nativelyplayit_process = subprocess.Popen(cmd,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL,cwd=PLAYIT_DIR,env=env)t = threading.Thread(target=read_playit_output, args=(log_file_path,), daemon=True)t.start()except Exception as e:logger.error(f"Failed to start playit agent: {e}")playit_status = "Error starting"def apply_playit_secret(secret_key):global playit_process, playit_status, PLAYIT_SECRETif not secret_key.strip():return "Secret key cannot be empty."# Write to playit.tomltoml_path = os.path.join(PLAYIT_DIR, "playit.toml")try:os.makedirs(PLAYIT_DIR, exist_ok=True)with open(toml_path, "w") as f:f.write(f'[agent]\nsecret_key = "{secret_key.strip()}"\n')logger.info(f"Successfully saved playit secret key to {toml_path}")PLAYIT_SECRET = secret_key.strip()# Stop playit process if runningif playit_process and playit_process.poll() is None:playit_process.terminate()playit_process.wait()# Start playit process again (it will load the new playit.toml secret!)start_playit_agent()return "Secret key applied! Restarting playit tunnel..."except Exception as e:logger.error(f"Error saving playit secret: {e}")return f"Failed to save secret key: {e}"def start_cloudflare_tunnel():global cf_process, cf_status, CLOUDFLARE_TOKENif not CLOUDFLARE_TOKEN:115 unmodified linespassbackup_server()# Secret key detector to print to logsdef log_secret_key_detector():logged = Falsewhile True:time.sleep(10)if logged:continuetoml_files = glob.glob(os.path.join(PLAYIT_DIR, "**", "*.toml"), recursive=True)toml_files += glob.glob(os.path.join(os.path.abspath("."), "**", "*.toml"), recursive=True)for toml_path in toml_files:if "playit" in toml_path:try:with open(toml_path, "r") as f:content = f.read()match = re.search(r'secret_key\s*=\s*["\']([^"\']+)["\']', content)if match:secret = match.group(1)logger.info("==================================================")logger.info(f"PLAYIT AGENT SECRET KEY DETECTED: {secret}")logger.info("PLEASE COPY AND SAVE THIS KEY TO YOUR SPACE SECRETS")logger.info("AS 'SECRET_KEY' SO IT PERSISTS ON REBOOTS!")logger.info("==================================================")logged = Truebreakexcept Exception:pass# ----------------- INITIALIZATION ON IMPORT -----------------restore_server()start_playit_agent()start_cloudflare_tunnel()# Auto start server on start if eula is true or we auto-write it4 unmodified linesbt = threading.Thread(target=backup_scheduler, daemon=True)bt.start()# Start secret key logger threadskt = threading.Thread(target=log_secret_key_detector, daemon=True)skt.start()# ----------------- GRADIO DASHBOARD INTERFACE -----------------# Functions interfacing with Gradio layout257 unmodified lines</div>"""# Claim link blockclaim_html = ""if playit_claim_link:claim_html = f"""<div style='background-color: rgba(88, 101, 242, 0.15); border: 1px solid #5865f2; border-radius: 8px; padding: 12px; margin-bottom: 15px; font-size: 0.85rem;'><strong>Action Required:</strong> Agent unclaimed.<a href='{playit_claim_link}' target='_blank' style='color: #00b0f4; font-weight: bold; text-decoration: underline; margin-left: 5px;'>Click here to Claim Agent</a></div>"""custom_domain_html = ""if CUSTOM_DOMAIN:custom_domain_html = f"""25 unmodified linestunnel_html = f"""<div style='background-color: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 15px; display: flex; flex-direction: column; gap: 8px;'><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Tunnel Status</span><span style='font-weight: bold;'>{playit_status.upper()}</span></div>{custom_domain_html}<div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Java Connection</span><span style='font-family: monospace; color: #00b0f4;'>{playit_java_url or 'Waiting for tunnel...'}</span></div><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Bedrock IP</span><span style='font-family: monospace; color: #00b0f4;'>{playit_bedrock_address or 'Waiting for tunnel...'}</span></div><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Bedrock Port</span><span style='font-family: monospace; color: #00b0f4;'>{playit_bedrock_port or 'Waiting...'}</span></div><div style='border-top: 1px solid rgba(255,255,255,0.06); margin-top: 5px; padding-top: 5px;'><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Local IP</span>29 unmodified lines"""dropdown_choices = ["@a", "@p", "@r"] + list(online_players_set)return metrics_html, claim_html, tunnel_html, backup_html, gr.Dropdown(choices=dropdown_choices), gr.Dropdown(choices=dropdown_choices), gr.Dropdown(choices=dropdown_choices)def trigger_action(action):if action == "start":200 unmodified linesbtn_tp_coords = gr.Button("📍 Teleport to Coords", size="sm", scale=2)with gr.Column(scale=1):# Claiming bannerclaim_panel = gr.HTML()# Connection Details Cardgr.HTML("<div style='font-size: 0.9rem; font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 5px; margin-bottom: 10px;'>Connection Portal</div>")tunnel_panel = gr.HTML()# Custom Secret Key Input Accordionwith gr.Accordion("⚙️ Link Existing Playit Agent", open=False):secret_input = gr.Textbox(label="Playit Secret Key",placeholder="Paste your secret key here...",type="password")apply_secret_btn = gr.Button("Save & Apply Secret Key", size="sm", variant="secondary")secret_output = gr.Textbox(label="Result Output", interactive=False)with gr.Accordion("⚙️ Link Cloudflare Tunnel", open=False):cf_secret_input = gr.Textbox(91 unmodified linesrestart_btn.click(lambda: trigger_action("restart"), outputs=[action_msg])backup_btn.click(lambda: trigger_action("backup"), outputs=[action_msg])apply_secret_btn.click(apply_playit_secret, inputs=[secret_input], outputs=[secret_output])apply_cf_btn.click(apply_cloudflare_secret, inputs=[cf_secret_input], outputs=[cf_secret_output])refresh_backups_btn.click(lambda: gr.Dropdown(choices=list_local_backups(), value=list_local_backups()[0] if list_local_backups() else None), outputs=[local_backups_dropdown])1 unmodified line# Automatic status refresh (Every 3 seconds)timer = gr.Timer(3)timer.tick(get_server_status, outputs=[metrics_panel, claim_panel, tunnel_panel, backup_panel, target_player, tp_from, tp_to_player])timer.tick(get_console_logs, outputs=[console_output])# TAB 2: DUNGEONS37 unmodified lines3839404142437 unmodified lines51525354555657585960616263646566676869707172737462 unmodified lines137138139140141142443 unmodified lines586587588589590591115 unmodified lines7077087097107117127137144 unmodified lines719720721722723724257 unmodified lines98298398498598698725 unmodified lines101310141015101610171018101910201021102229 unmodified lines1052105310541055105610571058200 unmodified lines12591260126112621263126412651266126791 unmodified lines1359136013611362136313641 unmodified line136613671368136913701371137237 unmodified linesMAX_RAM = os.getenv("MAX_RAM", "4G")HF_TOKEN = os.getenv("HF_TOKEN", "")HF_DATASET = os.getenv("HF_DATASET", "")DASHBOARD_PASSWORD = os.getenv("DASHBOARD_PASSWORD", "") # Panel PasswordENABLE_BEDROCK = os.getenv("ENABLE_BEDROCK", "true").lower() == "true"CUSTOM_DOMAIN = os.getenv("CUSTOM_DOMAIN", "")7 unmodified lines# Determine server working directories (Checking for persistent storage volume at /data)if os.path.exists("/data") and os.access("/data", os.W_OK):SERVER_DIR = "/data/minecraft"BIN_DIR = "/data/bin"BACKUPS_DIR = "/data/backups"else:# Local fallback for free Hugging Face tierSERVER_DIR = os.path.abspath("./minecraft")BIN_DIR = os.path.abspath("./bin")BACKUPS_DIR = os.path.abspath("./backups")os.makedirs(SERVER_DIR, exist_ok=True)os.makedirs(BIN_DIR, exist_ok=True)os.makedirs(BACKUPS_DIR, exist_ok=True)# Global variables to track processes and statesmc_process = Nonemc_logs = collections.deque(maxlen=500)cf_process = Nonecf_status = "Offline"backup_status = "Idle"last_backup_time = "Never"62 unmodified linesreturn full_pathreturn Nonedef check_and_download_cloudflared():IS_WINDOWS = sys.platform.startswith("win")cf_name = "cloudflared.exe" if IS_WINDOWS else "cloudflared"443 unmodified linesbackup_server()return "Server stopped."def start_cloudflare_tunnel():global cf_process, cf_status, CLOUDFLARE_TOKENif not CLOUDFLARE_TOKEN:115 unmodified linespassbackup_server()# ----------------- INITIALIZATION ON IMPORT -----------------restore_server()start_cloudflare_tunnel()# Auto start server on start if eula is true or we auto-write it4 unmodified linesbt = threading.Thread(target=backup_scheduler, daemon=True)bt.start()# ----------------- GRADIO DASHBOARD INTERFACE -----------------# Functions interfacing with Gradio layout257 unmodified lines</div>"""custom_domain_html = ""if CUSTOM_DOMAIN:custom_domain_html = f"""25 unmodified linestunnel_html = f"""<div style='background-color: rgba(255,255,255,0.03); border: 1px solid rgba(255,255,255,0.08); border-radius: 8px; padding: 15px; display: flex; flex-direction: column; gap: 8px;'><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Cloudflare Tunnel</span><span style='font-weight: bold; color: {"#10b981" if cf_status == "Online" else "#f59e0b" if cf_status.startswith("Start") else "#ef4444"};'>{cf_status.upper()}</span></div>{custom_domain_html}<div style='border-top: 1px solid rgba(255,255,255,0.06); margin-top: 5px; padding-top: 5px;'><div style='display: flex; justify-content: space-between; font-size: 0.85rem;'><span style='color: #888;'>Local IP</span>29 unmodified lines"""dropdown_choices = ["@a", "@p", "@r"] + list(online_players_set)return metrics_html, tunnel_html, backup_html, gr.Dropdown(choices=dropdown_choices), gr.Dropdown(choices=dropdown_choices), gr.Dropdown(choices=dropdown_choices)def trigger_action(action):if action == "start":200 unmodified linesbtn_tp_coords = gr.Button("📍 Teleport to Coords", size="sm", scale=2)with gr.Column(scale=1):# Connection Details Cardgr.HTML("<div style='font-size: 0.9rem; font-weight: bold; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 5px; margin-bottom: 10px;'>Connection Portal</div>")tunnel_panel = gr.HTML()with gr.Accordion("⚙️ Link Cloudflare Tunnel", open=False):cf_secret_input = gr.Textbox(91 unmodified linesrestart_btn.click(lambda: trigger_action("restart"), outputs=[action_msg])backup_btn.click(lambda: trigger_action("backup"), outputs=[action_msg])apply_cf_btn.click(apply_cloudflare_secret, inputs=[cf_secret_input], outputs=[cf_secret_output])refresh_backups_btn.click(lambda: gr.Dropdown(choices=list_local_backups(), value=list_local_backups()[0] if list_local_backups() else None), outputs=[local_backups_dropdown])1 unmodified line# Automatic status refresh (Every 3 seconds)timer = gr.Timer(3)timer.tick(get_server_status, outputs=[metrics_panel, tunnel_panel, backup_panel, target_player, tp_from, tp_to_player])timer.tick(get_console_logs, outputs=[console_output])# TAB 2: DUNGEONS
Dockerfile+1-1
app.py+4-277