Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1d1d2ab2ee | ||
|
|
32517999f3 | ||
|
|
5d19f772e5 | ||
|
|
9ea0829789 | ||
|
|
5ecf9f2417 | ||
|
|
18e85592b7 | ||
|
|
c7a0260569 | ||
|
|
17232053ee | ||
|
|
593345fb1f | ||
|
|
79818f6d5d | ||
|
|
f4ee1b85cf | ||
|
|
4a94bf68ce | ||
|
|
0f173dc107 |
No files matched your search
@@ -14,6 +14,10 @@ frontend/.pnpm-store/
|
|||||||
frontend/.vite/
|
frontend/.vite/
|
||||||
frontend/dist/
|
frontend/dist/
|
||||||
|
|
||||||
|
# New dashboard (removed - legacy only)
|
||||||
|
backend/
|
||||||
|
frontend/
|
||||||
|
|
||||||
# Virtual environments
|
# Virtual environments
|
||||||
venv/
|
venv/
|
||||||
env/
|
env/
|
||||||
@@ -38,6 +42,9 @@ internal-scripts/ssh/sshKey
|
|||||||
# SSL Certificates
|
# SSL Certificates
|
||||||
ssl/
|
ssl/
|
||||||
|
|
||||||
|
# Let's Encrypt certbot runtime data
|
||||||
|
certbot/
|
||||||
|
|
||||||
# Temporary settings scripts (generated by launcher)
|
# Temporary settings scripts (generated by launcher)
|
||||||
read_settings*.py
|
read_settings*.py
|
||||||
hash_pw*.py
|
hash_pw*.py
|
||||||
|
|||||||
@@ -1,359 +1,100 @@
|
|||||||
# Dune Awakening Dashboard
|
# Dune Awakening Dashboard
|
||||||
|
|
||||||
A comprehensive web-based management dashboard for Dune: Awakening private servers. Provides real-time monitoring, player management, chat logging, file browsing, and server administration tools.
|
A modern, full‑featured management dashboard for **Dune: Awakening** private servers. Provides real‑time monitoring, player tools, chat logs, file browsing, admin utilities, and secure remote access.
|
||||||
|
|
||||||
## Branching Strategy
|
> “A comprehensive web-based management dashboard for Dune: Awakening private servers.”
|
||||||
|
|
||||||
This repo follows a git-flow inspired strategy. Here's the breakdown:
|
---
|
||||||
|
|
||||||
- **main** - Current beta release. It's stable enough to use, but things still break occasionally. I'm working toward a proper stable release, but we're not there yet. Don't use main as a reference for "production-ready" code - it's more "production-adjacent."
|
|
||||||
|
|
||||||
- **nightly** - The cutting edge. Updated automatically from main with the latest changes. Might have shiny new features, might have shiny new bugs. Generally works but don't be surprised if something catches fire.
|
|
||||||
|
|
||||||
- **experimental** - Where ideas go to become features or crash spectacularly. This is where new features are tested, questionable UI decisions are made, and code is written that might make future-me weep. Expect bugs. Expect weirdness. Expect things to break in creative new ways.
|
|
||||||
|
|
||||||
> "This seemed like a great idea at 3am" - every experimental commit ever
|
|
||||||
|
|
||||||
**Workflow:** Features → experimental → testing → nightly → main (eventually)
|
|
||||||
|
|
||||||
If you're testing this project, grab builds from nightly for the latest features, or main for something more stable. Experimental is where I break things on purpose to see what sticks.
|
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
### Windows
|
### **Windows**
|
||||||
1. Double-click `launcher.bat` (or run `.\launcher.ps1` in PowerShell)
|
1. Run `launcher.bat` or `.\launcher.ps1`
|
||||||
2. Select option **2** to run Setup on first use
|
2. Select **[2] Run Setup** on first launch
|
||||||
3. Select option **1** to Start Dashboard
|
3. Select **[1] Start Dashboard** to open the UI
|
||||||
|
|
||||||
> **Tip**: The launcher automatically finds your SSH key from the Dune Awakening server installation at `%LOCALAPPDATA%\DuneAwakeningServer\sshKey`.
|
> The launcher automatically finds your Dune Awakening SSH key and politely ignores PowerShell’s opinions about execution policies.
|
||||||
>
|
|
||||||
> **Note**: If PowerShell blocks running scripts due to execution policy (`launcher.ps1` won't run), use `launcher.bat` instead — it bypasses the restriction automatically. You can also run `powershell.exe -ExecutionPolicy Bypass -File .\launcher.ps1` directly from Command Prompt.
|
### **Linux / macOS**
|
||||||
|
```bash
|
||||||
|
chmod +x start.sh
|
||||||
|
./start.sh
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Map Features**: Interactive maps with real-world coordinate calibration for Hagga Basin and The Deep Desert. Default view centers on Hagga Basin at 15% zoom. Zoom range: 15%–100%.
|
- **Player Management** (vitals, inventory, vehicles, buildings, guilds, reputation)
|
||||||
- **Player Management**: View, search, and filter players. Track online status, factions, guilds, and locations. Rich detail view with vitals, currency, inventory, vehicles, buildings, landclaims, specialization, keystones, and faction reputation.
|
- **Chat Logs** with channel filtering and auto-refresh
|
||||||
- **Chat Logs**: Parsed from text-router pod logs with channel filtering and auto-refresh.
|
- **Director Tools** (battlegroups, world state, transfers)
|
||||||
- **Director Controls**: Live battlegroup stats, world state management, and server transfer controls.
|
- **SSH File Browser** + **in-browser shell**
|
||||||
- **File Browser**: Secure SSH-based file browser for server configuration and logs.
|
- **Firewall Hardening** via iptables
|
||||||
- **Shell Access**: Interactive VM and Kubernetes pod shells directly in the browser.
|
- **Auto‑Update** with safe file replacement
|
||||||
- **Admin Tools**: Ban management, IP detection, kick/unban functionality, player history, item/currency/vitals editing, and raw SQL query interface.
|
- **HTTPS + Remote Access** (self‑signed or Let’s Encrypt)
|
||||||
- **Firewall Security**: Block unauthenticated game server ports (File Browser, Director) from external internet access. Applied via iptables on the game server VM across INPUT, FORWARD, and mangle PREROUTING chains to cover both host services and Kubernetes NodePort traffic. Configurable per-port during setup or from the Server page.
|
- **Cross‑Platform Launchers**
|
||||||
- **Vehicles & Buildings**: Track owned vehicles, modules, and player structures.
|
- **Organized Logging** with automatic cleanup and redaction
|
||||||
- **Auto-Update**: Background checker polls GitHub for new commits. Safe file replacement preserves your settings, logs, and SSH keys. One-click update from the dashboard.
|
- **Debug Mode** with full SSH/K8s tracing
|
||||||
- **Remote Access**: Built-in support for HTTPS and binding to `0.0.0.0` for secure remote management.
|
- **SSH Key Rotation** — scan all key locations and sync the newest key
|
||||||
- **Let's Encrypt**: Optionally set up publicly trusted SSL certs during setup with automatic renewal via certbot.
|
|
||||||
- **Settings Migration**: Automatically adds new configuration options to `settings.yaml` when updating, so you never miss a feature.
|
|
||||||
- **Cross-Platform**: Works on Windows (`.bat`/`.ps1`) and Linux/macOS (`.sh`).
|
|
||||||
- **Organized Logging**: Launcher logs are automatically categorized by type (SSH, K8s, database, etc.) with sensitive data redacted. Old logs are cleaned up after 30 days, oversized files are truncated at 10 MB.
|
|
||||||
- **Debug Mode**: Enable verbose debug logging via launcher (option 6) or the Server page UI. Logs detailed information about all HTTP requests/responses, SSH commands, database queries, Kubernetes operations, and service health checks. All sensitive data (passwords, tokens, keys) is automatically sanitized before writing to log files. Debug logs are written to `logs/debug.log`.
|
|
||||||
|
|
||||||
## License
|
---
|
||||||
|
|
||||||
This project is **Source Available** under the [Dune Dashboard Source License (DDSL)](LICENSE).
|
|
||||||
- Source code is available for inspection and security auditing.
|
|
||||||
- **No redistribution** (modified or unmodified).
|
|
||||||
- **No claiming of credit** or authorship.
|
|
||||||
- Personal, non-commercial use only.
|
|
||||||
|
|
||||||
## Requirements
|
|
||||||
|
|
||||||
- Python 3.8+
|
|
||||||
- Node.js 18+ (for frontend development/build)
|
|
||||||
- OpenSSH client
|
|
||||||
- `kubectl` access to the Dune: Awakening Kubernetes cluster
|
|
||||||
- SSH access to the game server VM
|
|
||||||
|
|
||||||
## Setup
|
|
||||||
|
|
||||||
### Windows
|
|
||||||
|
|
||||||
1. **Run the Launcher**
|
|
||||||
```powershell
|
|
||||||
.\launcher.ps1
|
|
||||||
```
|
|
||||||
|
|
||||||
2. **Choose an option from the menu:**
|
|
||||||
- **[1] Start Dashboard** — Launch the dashboard web interface
|
|
||||||
- **[2] Run Setup** — Configure the dashboard for the first time (or reconfigure)
|
|
||||||
- **[3] Run Diagnostics** — Check your system for common issues
|
|
||||||
- **[4] Install CA Certificate** — Install the local CA into Windows Trusted Root store (removes browser SSL warnings)
|
|
||||||
- **[5] Clean & Reinstall CA Certificate** — Remove old CA certificates and install a fresh one
|
|
||||||
- **[6] Start Dashboard (Debug Mode)** — Launch with full debug logging enabled
|
|
||||||
- **[7] Start New Dashboard (React + ChakraUI)** — Launch the modern React dashboard with auto-installed dependencies
|
|
||||||
- **[8] Reset to Factory Defaults** — Wipe all data (settings, logs, certs, cache, node_modules) and return to a clean state
|
|
||||||
- **[Q] Quit** — Exit the launcher
|
|
||||||
|
|
||||||
3. **First-time Setup** (option 2)
|
|
||||||
|
|
||||||
The setup script will:
|
|
||||||
- Install Python dependencies
|
|
||||||
- Find your SSH key (automatically detects the Dune Awakening server key)
|
|
||||||
- Auto-detect your VM IP from Hyper-V or SSH history
|
|
||||||
- Generate SSL certificates (local CA or Let's Encrypt)
|
|
||||||
- Configure firewall rules and security hardening
|
|
||||||
|
|
||||||
During setup you'll be prompted for:
|
|
||||||
- **VM External IP** — the IP you SSH into (e.g., `<YOUR_VM_IP>`)
|
|
||||||
- **Host External IP** — the public IP for SSL certificate SANs (e.g., `<YOUR_HOST_IP>`)
|
|
||||||
- **Let's Encrypt** — optionally set up a publicly trusted SSL cert with auto-renewal via certbot
|
|
||||||
- **Firewall rules** — only prompted if no `DuneDashboard` rule exists yet
|
|
||||||
|
|
||||||
> **Note**: Setup will retry SSH up to 12 times (60 seconds) to accommodate fresh VM boot times. If SSH isn't ready yet, you can still continue and enter your Kubernetes namespace manually.
|
|
||||||
|
|
||||||
4. **Start Dashboard** (option 1)
|
|
||||||
|
|
||||||
The launcher will:
|
|
||||||
- Establish an SSH tunnel to your game server
|
|
||||||
- Set up database and Director port-forwards via kubectl
|
|
||||||
- Scale up the BGD deployment if needed
|
|
||||||
- Launch the dashboard web interface
|
|
||||||
|
|
||||||
### Linux / macOS
|
|
||||||
|
|
||||||
1. **Start Dashboard**
|
|
||||||
```bash
|
|
||||||
chmod +x start.sh
|
|
||||||
./start.sh
|
|
||||||
```
|
|
||||||
The launcher will prompt you to run setup if `settings.yaml` is missing.
|
|
||||||
|
|
||||||
## Configuration
|
|
||||||
|
|
||||||
All settings are stored in `settings.yaml`. The setup script generates this automatically. Key settings include:
|
|
||||||
|
|
||||||
- `server.host`: Game server VM IP
|
|
||||||
- `server.ssh_key`: Path to your SSH private key
|
|
||||||
- `kubernetes.namespace`: Auto-detected K8s namespace
|
|
||||||
- `database.port`: Local port for database tunnel
|
|
||||||
- `auth.username` / `auth.password_hash`: Dashboard login credentials (password_hash is Argon2 hash, generated by setup)
|
|
||||||
|
|
||||||
### Remote Access
|
|
||||||
|
|
||||||
During setup, answer **y** to "Enable remote access?" to:
|
|
||||||
- Bind to `0.0.0.0` (accessible from other machines)
|
|
||||||
- Auto-generate SSL certificates for HTTPS
|
|
||||||
- Enable secure remote connections via `https://YOUR_IP:5050`
|
|
||||||
|
|
||||||
**Firewall rules** are created automatically during setup. On subsequent starts, `start.ps1`/`start.sh` will only prompt if the `DuneDashboard` rule is missing.
|
|
||||||
|
|
||||||
You can also manually edit `settings.yaml` later:
|
|
||||||
```yaml
|
|
||||||
dashboard:
|
|
||||||
host: 0.0.0.0
|
|
||||||
ssl_cert: ssl/cert.pem
|
|
||||||
ssl_key: ssl/key.pem
|
|
||||||
```
|
|
||||||
|
|
||||||
### Let's Encrypt (Publicly Trusted Certs)
|
|
||||||
|
|
||||||
During setup, answer **y** when asked to enable Let's Encrypt. The setup script will:
|
|
||||||
1. Install `certbot` (tries `winget`, `pip`, and `python -m` fallbacks on Windows)
|
|
||||||
2. Run `certbot certonly --standalone` to validate your domain
|
|
||||||
3. Configure auto-renewal via Windows Scheduled Task or Linux cron
|
|
||||||
4. Point the dashboard to the Let's Encrypt cert paths
|
|
||||||
|
|
||||||
> **Note**: Port 80 must be free during certbot validation. The dashboard's HTTP redirect server will release port 80 temporarily for this.
|
|
||||||
|
|
||||||
### Local CA Utilities (Windows)
|
|
||||||
|
|
||||||
Available from the launcher menu (`.\launcher.ps1`):
|
|
||||||
- **Option 4: Install CA Certificate** — Installs the local CA (`ssl/ca.pem`) into Windows Trusted Root store. Run as Administrator. Removes browser warnings.
|
|
||||||
- **Option 5: Clean & Reinstall CA Certificate** — Removes all old Dune Dashboard CA certificates from Windows Trusted Root store and installs a fresh one. Use if you have duplicate or expired CA certificates.
|
|
||||||
|
|
||||||
### SSL Configuration
|
|
||||||
|
|
||||||
The dashboard supports both self-signed and CA-signed certificates.
|
|
||||||
|
|
||||||
**Local CA (auto-generated during setup):**
|
|
||||||
- A local Certificate Authority (`ssl/ca.pem`) is created during setup
|
|
||||||
- Server certificates are signed by this CA
|
|
||||||
- Server certs include SAN for the server IP + `127.0.0.1` + `localhost`
|
|
||||||
- Valid for 365 days
|
|
||||||
|
|
||||||
**Remove browser warnings (Windows):**
|
|
||||||
1. Run `.\launcher.ps1` and select option **4** (Install CA Certificate)
|
|
||||||
2. Restart your browser
|
|
||||||
3. Access `https://localhost:5050` — no more warnings
|
|
||||||
|
|
||||||
**Remove browser warnings (Linux):**
|
|
||||||
```bash
|
|
||||||
sudo cp ssl/ca.pem /usr/local/share/ca-certificates/dune-dashboard-ca.crt
|
|
||||||
sudo update-ca-certificates
|
|
||||||
```
|
|
||||||
|
|
||||||
**Let's Encrypt or custom CA:**
|
|
||||||
```yaml
|
|
||||||
dashboard:
|
|
||||||
host: 0.0.0.0
|
|
||||||
ssl_cert: /etc/letsencrypt/live/yourdomain.com/fullchain.pem
|
|
||||||
ssl_key: /etc/letsencrypt/live/yourdomain.com/privkey.pem
|
|
||||||
```
|
|
||||||
|
|
||||||
When SSL is enabled:
|
|
||||||
- Session cookies are marked `Secure` (sent only over HTTPS)
|
|
||||||
- HTTP-to-HTTPS redirect runs on port+1 (e.g., `http://localhost:5051` → `https://localhost:5050`)
|
|
||||||
- Certificate expiry is checked at startup (warning if < 30 days)
|
|
||||||
|
|
||||||
**Regenerate certificates:**
|
|
||||||
Delete `ssl/cert.pem`, `ssl/key.pem`, and `ssl/ca*.pem`, then re-run setup.
|
|
||||||
|
|
||||||
### Auto-Renewal
|
|
||||||
|
|
||||||
SSL certificates are automatically regenerated when they approach expiry:
|
|
||||||
- A background thread checks the certificate every 24 hours (configurable)
|
|
||||||
- If the certificate expires within 30 days (configurable), a new one is generated
|
|
||||||
- The server does **not** need to restart — Flask-SocketIO picks up the new cert on the next connection
|
|
||||||
- Configure thresholds in `settings.yaml` under the `ssl:` section
|
|
||||||
|
|
||||||
## Project Structure
|
## Project Structure
|
||||||
|
|
||||||
```
|
```
|
||||||
DuneDashboard/
|
DuneDashboard/
|
||||||
├── backend/ # New Flask backend (API + services)
|
├── app/ # Flask/Jinja2 dashboard
|
||||||
│ ├── app/
|
├── launcher.ps1 # Windows launcher
|
||||||
│ │ ├── routes/ # HTTP route handlers (API, auth, health, server, files, director, chat)
|
├── start.sh # Linux/macOS launcher
|
||||||
│ │ ├── services/ # Business logic (DB, SSH, K8s, BGD, RMQ, player, economy, guild, world, etc.)
|
└── settings.yaml # Generated config (gitignored)
|
||||||
│ │ ├── models/ # Pydantic v2 models
|
|
||||||
│ │ ├── websocket/ # Socket.IO shell handler
|
|
||||||
│ │ ├── config.py # Settings loader
|
|
||||||
│ │ └── factory.py # App factory (services, blueprints, security)
|
|
||||||
│ ├── run.py # Entry point
|
|
||||||
│ └── requirements.txt # Python dependencies
|
|
||||||
│
|
|
||||||
├── frontend/ # New React SPA (Vite + TypeScript + Tailwind)
|
|
||||||
│ ├── src/
|
|
||||||
│ │ ├── components/ # Pages (overview, players, guilds, vehicles, buildings, map, accounts, server, admin, chat, shell, files, director, settings)
|
|
||||||
│ │ ├── api/ # Axios client
|
|
||||||
│ │ ├── stores/ # React Context (app state, auth, theme)
|
|
||||||
│ │ ├── hooks/ # Custom hooks (realtime, debounce)
|
|
||||||
│ │ └── styles/ # Tailwind + 14 Dune themes
|
|
||||||
│ ├── index.html
|
|
||||||
│ ├── package.json
|
|
||||||
│ ├── vite.config.ts
|
|
||||||
│ └── tsconfig.json
|
|
||||||
│
|
|
||||||
├── app/ # Legacy Flask/Jinja2 dashboard (untouched, still functional)
|
|
||||||
│ ├── routes/
|
|
||||||
│ ├── services/
|
|
||||||
│ ├── utils/
|
|
||||||
│ └── websocket/
|
|
||||||
├── templates/ # Legacy Jinja2 HTML templates
|
|
||||||
├── static/ # Legacy CSS and frontend assets
|
|
||||||
├── scripts/ # Pre-flight utilities (db_check.py)
|
|
||||||
├── launcher.ps1 # Unified launcher (setup, start, diagnostics, CA tools)
|
|
||||||
├── start.sh # Linux/macOS entry point
|
|
||||||
├── settings.yaml # Configuration (gitignored)
|
|
||||||
└── settings.yaml.example # Reference configuration
|
|
||||||
```
|
```
|
||||||
|
|
||||||
> **Note**: The legacy `app/`, `templates/`, and `static/` directories remain untouched and functional. The new system lives in `backend/` and `frontend/`. Both can coexist during migration.
|
---
|
||||||
|
|
||||||
## Architecture
|
## Requirements
|
||||||
|
|
||||||
### Frontend
|
- Python 3.8+
|
||||||
- **React 18** with TypeScript
|
- OpenSSH client
|
||||||
- **Vite** for fast builds and HMR
|
- `kubectl` access to your Dune Awakening cluster
|
||||||
- **Tailwind CSS** for styling with 14 Dune house themes
|
- SSH access to the game server VM
|
||||||
- **SWR** for server state caching and revalidation
|
|
||||||
- **Axios** for HTTP requests with 401 redirect handling
|
|
||||||
- **Socket.IO Client** for the remote terminal
|
|
||||||
- **xterm.js** for the in-browser shell
|
|
||||||
|
|
||||||
### Backend
|
---
|
||||||
- **Flask 3** with Blueprint-based routing
|
|
||||||
- **Pydantic v2** for request/response validation
|
|
||||||
- **psycopg3** with connection pooling for PostgreSQL
|
|
||||||
- **Flask-SocketIO** for the interactive shell
|
|
||||||
- **Flask-Login** for session-based authentication (Argon2 password hashing)
|
|
||||||
- **Flask-Limiter** for rate limiting
|
|
||||||
- **SSE (Server-Sent Events)** for real-time updates (battlegroup, chat, metrics)
|
|
||||||
|
|
||||||
### Services
|
## Security
|
||||||
- `DatabaseService` — psycopg3 pool, stored procedure executor, audit table DDL
|
|
||||||
- `SSHService` — paramiko SSH client for tunneling and remote commands
|
|
||||||
- `K8sService` — kubectl-over-SSH for pod/deployment management
|
|
||||||
- `BgDirectorService` — HTTP client for the Battlegroup Director API
|
|
||||||
- `RmqAdminService` — RabbitMQ Management HTTP API client
|
|
||||||
- `RmqGameService` — RabbitMQ Game HTTP API client (broadcasts, chat intercept)
|
|
||||||
- `RealtimeService` — SSE broadcaster with background polling loops
|
|
||||||
- `PlayerService` / `EconomyService` / `GuildService` / `WorldService` / `ProgressionService` / `CharacterService` — DB-function-only domain services
|
|
||||||
- `AuditService` — persistent PostgreSQL audit logging
|
|
||||||
- `ChatService` — chat history + pod log catch-up
|
|
||||||
|
|
||||||
## Security Notes
|
- `settings.yaml` is never committed
|
||||||
|
- SSH keys stored with restricted permissions
|
||||||
|
- All DB queries parameterized
|
||||||
|
- Raw SQL endpoint is **read‑only SELECT**
|
||||||
|
- All mutations audited
|
||||||
|
- CSP, HSTS, X‑Frame‑Options enforced in production
|
||||||
|
|
||||||
- Never commit `settings.yaml` to version control.
|
> “Raw SQL query endpoint is read‑only SELECT — INSERT/UPDATE/DELETE… are blocked.”
|
||||||
- SSH keys are copied to `%TEMP%` with restricted permissions during startup.
|
> Because letting users run `DROP TABLE` from a web UI is how horror stories begin.
|
||||||
- All database queries use parameterized statements to prevent SQL injection.
|
|
||||||
- Dashboard authentication is required by default.
|
|
||||||
- Raw SQL query endpoint (`/api/query`) is **read-only SELECT** — INSERT/UPDATE/DELETE/DROP/CREATE/ALTER/GRANT/TRUNCATE are blocked.
|
|
||||||
- All mutations are audited to PostgreSQL.
|
|
||||||
- CSP, HSTS, X-Frame-Options, and other security headers are enforced in production mode.
|
|
||||||
|
|
||||||
## Logging
|
---
|
||||||
|
|
||||||
The launcher automatically organizes and sanitizes logs to protect sensitive information.
|
|
||||||
|
|
||||||
### Log Categories
|
|
||||||
|
|
||||||
```
|
|
||||||
logs/
|
|
||||||
├── launcher/
|
|
||||||
│ ├── general/ # General launcher events
|
|
||||||
│ ├── ssh/ # SSH tunnel and connection logs
|
|
||||||
│ ├── k8s/ # Kubernetes operations
|
|
||||||
│ ├── database/ # Database port-forward and connections
|
|
||||||
│ ├── dashboard/ # Dashboard startup and runtime
|
|
||||||
│ ├── setup/ # Setup wizard logs
|
|
||||||
│ └── diagnostics/ # Diagnostic tool output
|
|
||||||
├── app.log # Python application log (rotating, 10 MB max, 5 backups)
|
|
||||||
└── audit.log # Security audit log (rotating, 10 MB max, 5 backups)
|
|
||||||
```
|
|
||||||
|
|
||||||
### Sensitive Data Redaction
|
|
||||||
|
|
||||||
All launcher log files are automatically sanitized before writing. The following are redacted:
|
|
||||||
- IP addresses → `<IP_REDACTED>`
|
|
||||||
- JWT tokens → `<JWT_REDACTED>`
|
|
||||||
- Base64 secrets → `<BASE64_REDACTED>`
|
|
||||||
- SSH key paths → `<SSH_KEY_PATH_REDACTED>`
|
|
||||||
- K8s namespaces → `<NAMESPACE_REDACTED>`
|
|
||||||
- Host IDs → `<HOST_ID_REDACTED>`
|
|
||||||
- Passwords/tokens → `<REDACTED>`
|
|
||||||
- Funcom IDs → `<FUNCOM_ID_REDACTED>`
|
|
||||||
|
|
||||||
Console output is **not** sanitized so you can see full details during operation.
|
|
||||||
|
|
||||||
### Automatic Cleanup
|
|
||||||
|
|
||||||
- Log files older than **30 days** are deleted
|
|
||||||
- Files exceeding **10 MB** are truncated (keeps last 5000 lines)
|
|
||||||
- Empty category directories are removed
|
|
||||||
- Cleanup runs automatically on every launcher start
|
|
||||||
|
|
||||||
## Development
|
## Development
|
||||||
|
|
||||||
### Frontend Development
|
Run `launcher.bat` or `.\launcher.ps1` — the launcher handles dependencies, SSH key configuration, and server setup automatically.
|
||||||
|
|
||||||
```bash
|
---
|
||||||
cd frontend
|
|
||||||
npm install
|
|
||||||
npm run dev # Vite dev server with API proxy to localhost:5050
|
|
||||||
npm run build # Production build to frontend/dist/
|
|
||||||
```
|
|
||||||
|
|
||||||
### Backend Development
|
## Branching Strategy
|
||||||
|
|
||||||
```bash
|
- **main** — stable-ish beta
|
||||||
cd backend
|
- **nightly** — latest features
|
||||||
pip install -r requirements.txt
|
- **experimental** — where chaos becomes innovation
|
||||||
python run.py # Or: flask --app run:app run
|
|
||||||
```
|
|
||||||
|
|
||||||
### Themes
|
> “This seemed like a great idea at 3am.” — every experimental commit ever
|
||||||
|
|
||||||
The dashboard supports 14 Dune house themes. Switch via the theme picker in the top-right nav bar:
|
---
|
||||||
Classic Dune, House Atreides, House Harkonnen, Fremen, Bene Gesserit, Spacing Guild, Emperor, House Corrino, Mentat, Sardaukar, Bene Tleilax, House Ordos, Ix, CHOAM.
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
Source Available under the **Dune Dashboard Source License (DDSL)**
|
||||||
|
- No redistribution
|
||||||
|
- No claiming authorship
|
||||||
|
- Personal, non-commercial use only
|
||||||
|
- Basically: look, learn, enjoy — just don’t repost it as “Dune Dashboard Pro Deluxe Edition”.
|
||||||
|
|
||||||
Themes are implemented via CSS custom properties (`var(--primary)`, `var(--bg)`, etc.) and switched by setting `data-theme` on the `<html>` element.
|
|
||||||
@@ -39,6 +39,7 @@ DEFAULTS = {
|
|||||||
'max_connections': 10,
|
'max_connections': 10,
|
||||||
'owner': 'dune',
|
'owner': 'dune',
|
||||||
'dashboard_schema': 'dashboard',
|
'dashboard_schema': 'dashboard',
|
||||||
|
'dashboard_database_name': 'dashboard',
|
||||||
},
|
},
|
||||||
'kubernetes': {
|
'kubernetes': {
|
||||||
'namespace': '',
|
'namespace': '',
|
||||||
|
|||||||
+37
-23
@@ -15,7 +15,7 @@ from flask_limiter.util import get_remote_address
|
|||||||
|
|
||||||
from app.config import load_settings
|
from app.config import load_settings
|
||||||
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
|
from app.utils.debug_logging import create_debug_log_handler, sanitize_for_log, log_request_details, log_response_details
|
||||||
from app.services.database import DatabaseService
|
from app.services.database import DatabaseService, DashboardDatabaseService
|
||||||
from app.services.ssh import SSHService
|
from app.services.ssh import SSHService
|
||||||
from app.services.k8s import K8sService
|
from app.services.k8s import K8sService
|
||||||
from app.services.player import PlayerService
|
from app.services.player import PlayerService
|
||||||
@@ -24,6 +24,7 @@ from app.services.chat import ChatService
|
|||||||
from app.services.admin import AdminService
|
from app.services.admin import AdminService
|
||||||
from app.services.updater import UpdateService
|
from app.services.updater import UpdateService
|
||||||
from app.services.director import DirectorService
|
from app.services.director import DirectorService
|
||||||
|
from app.services.rmq import RmqService
|
||||||
from app.utils.cache import MultiCache
|
from app.utils.cache import MultiCache
|
||||||
from app.routes.main import register_routes
|
from app.routes.main import register_routes
|
||||||
from app.routes.api import register_api_routes
|
from app.routes.api import register_api_routes
|
||||||
@@ -43,8 +44,10 @@ def create_app(settings_path=None):
|
|||||||
static_url_path='/static'
|
static_url_path='/static'
|
||||||
)
|
)
|
||||||
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
|
app.config['SECRET_KEY'] = settings['dashboard']['secret_key']
|
||||||
|
app.config['TEMPLATES_AUTO_RELOAD'] = True # Pick up template changes without restart
|
||||||
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
app.config['SESSION_COOKIE_HTTPONLY'] = True
|
||||||
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
app.config['SESSION_COOKIE_SAMESITE'] = 'Lax'
|
||||||
|
app.config['PERMANENT_SESSION_LIFETIME'] = 28800 # 8 hours
|
||||||
app.config['WTF_CSRF_ENABLED'] = True
|
app.config['WTF_CSRF_ENABLED'] = True
|
||||||
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
app.config['WTF_CSRF_TIME_LIMIT'] = None
|
||||||
|
|
||||||
@@ -58,7 +61,6 @@ def create_app(settings_path=None):
|
|||||||
and settings['dashboard']['ssl_key'] != 'null'
|
and settings['dashboard']['ssl_key'] != 'null'
|
||||||
)
|
)
|
||||||
|
|
||||||
# Set SESSION_COOKIE_SECURE conditional on SSL being enabled
|
|
||||||
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
|
app.config['SESSION_COOKIE_SECURE'] = ssl_enabled
|
||||||
|
|
||||||
# Add security headers manually (replaces deprecated Flask-Talisman)
|
# Add security headers manually (replaces deprecated Flask-Talisman)
|
||||||
@@ -188,19 +190,32 @@ def create_app(settings_path=None):
|
|||||||
'database': settings['database']['name'],
|
'database': settings['database']['name'],
|
||||||
}
|
}
|
||||||
|
|
||||||
|
dash_db_config = {
|
||||||
|
'host': db_host,
|
||||||
|
'port': settings['database']['port'],
|
||||||
|
'user': settings['database']['user'],
|
||||||
|
'password': settings['database']['password'],
|
||||||
|
'database': settings['database'].get('dashboard_database_name', 'dashboard'),
|
||||||
|
}
|
||||||
|
|
||||||
db_service = DatabaseService(
|
db_service = DatabaseService(
|
||||||
db_config,
|
db_config,
|
||||||
min_conn=settings['database']['min_connections'],
|
min_conn=settings['database']['min_connections'],
|
||||||
max_conn=settings['database']['max_connections'],
|
max_conn=settings['database']['max_connections'],
|
||||||
dashboard_schema=settings['database'].get('dashboard_schema', 'dashboard')
|
|
||||||
)
|
)
|
||||||
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
|
logging.debug(f"DatabaseService initialized: host={db_config['host']}, port={db_config['port']}, user={db_config['user']}")
|
||||||
db_service.ensure_tables()
|
|
||||||
logging.debug("Database tables ensured")
|
dash_db_service = DashboardDatabaseService(
|
||||||
|
dash_db_config,
|
||||||
|
min_conn=settings['database']['min_connections'],
|
||||||
|
max_conn=settings['database']['max_connections'],
|
||||||
|
owner=settings['database'].get('owner', 'dune'),
|
||||||
|
)
|
||||||
|
dash_db_service.ensure_tables(game_db=db_service)
|
||||||
|
|
||||||
# Create performance indexes if they don't exist
|
# Create performance indexes if they don't exist
|
||||||
try:
|
try:
|
||||||
admin_svc_for_indexes = AdminService(db_service, None)
|
admin_svc_for_indexes = AdminService(db_service, None, dash_db=dash_db_service)
|
||||||
success, created, error = admin_svc_for_indexes.create_indexes()
|
success, created, error = admin_svc_for_indexes.create_indexes()
|
||||||
if success and created:
|
if success and created:
|
||||||
logging.info(f"Created {len(created)} database indexes")
|
logging.info(f"Created {len(created)} database indexes")
|
||||||
@@ -223,11 +238,11 @@ def create_app(settings_path=None):
|
|||||||
|
|
||||||
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
static_cache = MultiCache(ttl_seconds=settings['cache']['static_data_ttl'])
|
||||||
|
|
||||||
player_svc = PlayerService(db_service)
|
player_svc = PlayerService(db_service, dash_db=dash_db_service)
|
||||||
vehicle_svc = VehicleService(db_service)
|
vehicle_svc = VehicleService(db_service)
|
||||||
chat_svc = ChatService(db_service, k8s_service, ssh_service, static_cache)
|
chat_svc = ChatService(dash_db_service, k8s_service, ssh_service, static_cache)
|
||||||
logging.debug("ChatService initialized")
|
logging.debug("ChatService initialized")
|
||||||
admin_svc = AdminService(db_service, ssh_service)
|
admin_svc = AdminService(db_service, ssh_service, dash_db=dash_db_service)
|
||||||
logging.debug("AdminService initialized")
|
logging.debug("AdminService initialized")
|
||||||
updater_svc = UpdateService(base_dir)
|
updater_svc = UpdateService(base_dir)
|
||||||
logging.debug("UpdateService initialized")
|
logging.debug("UpdateService initialized")
|
||||||
@@ -239,9 +254,17 @@ def create_app(settings_path=None):
|
|||||||
namespace=settings['kubernetes']['namespace'],
|
namespace=settings['kubernetes']['namespace'],
|
||||||
)
|
)
|
||||||
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
|
logging.debug(f"DirectorService initialized: port={settings.get('director', {}).get('port', 32479)}")
|
||||||
|
rmq_svc = RmqService(
|
||||||
|
admin_port=settings.get('rabbitmq', {}).get('admin_port', 30325),
|
||||||
|
game_port=settings.get('rabbitmq', {}).get('game_port', 32716),
|
||||||
|
username=settings.get('rabbitmq', {}).get('username', 'dashboard_admin'),
|
||||||
|
password=settings.get('rabbitmq', {}).get('password', ''),
|
||||||
|
)
|
||||||
|
logging.debug(f"RmqService initialized: admin=localhost:{settings.get('rabbitmq', {}).get('admin_port', 30325)} game=localhost:{settings.get('rabbitmq', {}).get('game_port', 32716)}")
|
||||||
|
|
||||||
services = {
|
services = {
|
||||||
'db': db_service,
|
'db': db_service,
|
||||||
|
'dash_db': dash_db_service,
|
||||||
'ssh': ssh_service,
|
'ssh': ssh_service,
|
||||||
'k8s': k8s_service,
|
'k8s': k8s_service,
|
||||||
'player': player_svc,
|
'player': player_svc,
|
||||||
@@ -251,6 +274,7 @@ def create_app(settings_path=None):
|
|||||||
'static_cache': static_cache,
|
'static_cache': static_cache,
|
||||||
'updater': updater_svc,
|
'updater': updater_svc,
|
||||||
'director': director_svc,
|
'director': director_svc,
|
||||||
|
'rmq': rmq_svc,
|
||||||
}
|
}
|
||||||
logging.debug(f"All services registered: {list(services.keys())}")
|
logging.debug(f"All services registered: {list(services.keys())}")
|
||||||
|
|
||||||
@@ -266,11 +290,11 @@ def create_app(settings_path=None):
|
|||||||
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
|
cors_origins = "*" if settings['dashboard']['host'] == '0.0.0.0' else []
|
||||||
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading')
|
socketio = SocketIO(app, cors_allowed_origins=cors_origins, async_mode='threading')
|
||||||
|
|
||||||
# Initialize rate limiter (disabled)
|
# Initialize rate limiter (enabled, per-route limits only)
|
||||||
limiter = Limiter(
|
limiter = Limiter(
|
||||||
app=app,
|
app=app,
|
||||||
key_func=get_remote_address,
|
key_func=get_remote_address,
|
||||||
default_limits=[],
|
default_limits=[], # rate limits applied per-route only (login has 10/min)
|
||||||
storage_uri="memory://",
|
storage_uri="memory://",
|
||||||
)
|
)
|
||||||
app.limiter = limiter
|
app.limiter = limiter
|
||||||
@@ -278,22 +302,12 @@ def create_app(settings_path=None):
|
|||||||
if settings['auth']['enabled']:
|
if settings['auth']['enabled']:
|
||||||
init_auth(app, settings, limiter, audit_svc)
|
init_auth(app, settings, limiter, audit_svc)
|
||||||
|
|
||||||
# Auto-login for SPA frontend — bypasses login page
|
|
||||||
from flask_login import login_user
|
|
||||||
from app.routes.auth import AdminUser
|
|
||||||
|
|
||||||
@app.before_request
|
|
||||||
def auto_login_dev():
|
|
||||||
if not current_user.is_authenticated:
|
|
||||||
cfg_user = str(settings.get("auth", {}).get("username", "dune"))
|
|
||||||
login_user(AdminUser(cfg_user))
|
|
||||||
|
|
||||||
register_routes(app, services, settings)
|
register_routes(app, services, settings)
|
||||||
register_api_routes(app, services, settings)
|
register_api_routes(app, services, settings)
|
||||||
register_websocket_handlers(socketio, settings)
|
register_websocket_handlers(socketio, settings)
|
||||||
|
|
||||||
# Start update checker
|
# Start update checker (disabled — being reworked)
|
||||||
updater_svc.start_checker()
|
# updater_svc.start_checker()
|
||||||
|
|
||||||
@app.teardown_appcontext
|
@app.teardown_appcontext
|
||||||
def cleanup_db(exc):
|
def cleanup_db(exc):
|
||||||
|
|||||||
+273
-39
@@ -57,7 +57,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Server actions
|
# Server actions
|
||||||
@app.route('/server/action', methods=['POST'])
|
@app.route('/server/action', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def server_action():
|
def server_action():
|
||||||
deployment = request.form.get('deployment', '')
|
deployment = request.form.get('deployment', '')
|
||||||
action = request.form.get('action', '')
|
action = request.form.get('action', '')
|
||||||
@@ -114,7 +114,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/battlegroup/action', methods=['POST'])
|
@app.route('/server/battlegroup/action', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def battlegroup_action():
|
def battlegroup_action():
|
||||||
action = request.form.get('action', '')
|
action = request.form.get('action', '')
|
||||||
if action not in ('start', 'stop', 'restart'):
|
if action not in ('start', 'stop', 'restart'):
|
||||||
@@ -125,7 +125,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/battlegroup/update', methods=['POST'])
|
@app.route('/server/battlegroup/update', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def battlegroup_update():
|
def battlegroup_update():
|
||||||
bg_script = settings['kubernetes']['battlegroup_script']
|
bg_script = settings['kubernetes']['battlegroup_script']
|
||||||
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
|
out, err, rc = ssh.run(f'{bg_script} update', timeout=600)
|
||||||
@@ -195,7 +195,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/firewall/block', methods=['POST'])
|
@app.route('/server/firewall/block', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def firewall_block():
|
def firewall_block():
|
||||||
port = request.form.get('port', type=int)
|
port = request.form.get('port', type=int)
|
||||||
bgd_port = _get_bgd_nodeport()
|
bgd_port = _get_bgd_nodeport()
|
||||||
@@ -239,7 +239,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/server/firewall/unblock', methods=['POST'])
|
@app.route('/server/firewall/unblock', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def firewall_unblock():
|
def firewall_unblock():
|
||||||
port = request.form.get('port', type=int)
|
port = request.form.get('port', type=int)
|
||||||
bgd_port = _get_bgd_nodeport()
|
bgd_port = _get_bgd_nodeport()
|
||||||
@@ -345,7 +345,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Ban management
|
# Ban management
|
||||||
@app.route('/api/ban_player', methods=['POST'])
|
@app.route('/api/ban_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def api_ban_player():
|
def api_ban_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -408,7 +408,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/unban_player', methods=['POST'])
|
@app.route('/api/unban_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("1000 per hour")
|
|
||||||
def api_unban_player():
|
def api_unban_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -434,7 +434,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/kick_player', methods=['POST'])
|
@app.route('/api/kick_player', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def api_kick_player():
|
def api_kick_player():
|
||||||
try:
|
try:
|
||||||
player_id = request.form.get('player_id', type=int)
|
player_id = request.form.get('player_id', type=int)
|
||||||
@@ -449,7 +449,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# Vitals editing
|
# Vitals editing
|
||||||
@app.route('/api/edit_vitals', methods=['POST'])
|
@app.route('/api/edit_vitals', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("500 per hour")
|
|
||||||
def api_edit_vitals():
|
def api_edit_vitals():
|
||||||
try:
|
try:
|
||||||
pawn_id = request.form.get('pawn_id', type=int)
|
pawn_id = request.form.get('pawn_id', type=int)
|
||||||
@@ -800,35 +800,66 @@ def register_api_routes(app, services, settings):
|
|||||||
FILEBROWSER_BASE_PATH = '/srv'
|
FILEBROWSER_BASE_PATH = '/srv'
|
||||||
|
|
||||||
def _validate_fb_path(path):
|
def _validate_fb_path(path):
|
||||||
"""Validate filebrowser path is within allowed directory."""
|
"""Validate filebrowser path — allow any path, block traversal."""
|
||||||
import posixpath
|
|
||||||
path_str = str(path or "").lstrip("/")
|
path_str = str(path or "").lstrip("/")
|
||||||
if '..' in path_str or '\x00' in path_str:
|
if '..' in path_str or '\x00' in path_str:
|
||||||
return False
|
return False
|
||||||
normalized = posixpath.normpath("/" + path_str)
|
return True
|
||||||
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
|
|
||||||
|
|
||||||
def _get_fb_pod():
|
def _get_fb_pod():
|
||||||
"""Get the FileBrowser pod name dynamically."""
|
"""Get the default FileBrowser pod name dynamically."""
|
||||||
pod = k8s.find_pod_by_pattern('fb-deploy')
|
pod = k8s.find_pod_by_pattern('fb-deploy')
|
||||||
return pod
|
return pod
|
||||||
|
|
||||||
def _fb_exec(command, timeout=10):
|
def _list_pods():
|
||||||
"""Execute kubectl exec in the FileBrowser pod with correct namespace placement."""
|
"""List all running pods available for file browsing, plus VM host."""
|
||||||
pod = _get_fb_pod()
|
available = ['__VM__ (Host OS)']
|
||||||
|
pods = k8s.get_pods()
|
||||||
|
for p in pods:
|
||||||
|
if p.endswith('-sts-0') or '-deploy-' in p:
|
||||||
|
available.append(p)
|
||||||
|
return available
|
||||||
|
|
||||||
|
def _fb_exec(command, pod_name=None, timeout=10):
|
||||||
|
"""Execute a command on the VM host or in a K8s pod."""
|
||||||
|
if pod_name == '__VM__' or (pod_name and pod_name.startswith('__VM__')):
|
||||||
|
return k8s.ssh.run(command, timeout=timeout)
|
||||||
|
pod = pod_name or _get_fb_pod()
|
||||||
if not pod:
|
if not pod:
|
||||||
return '', 'FileBrowser pod not found', 1
|
return '', 'No pod specified or found', 1
|
||||||
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
|
full_cmd = f'sudo kubectl exec {pod} -n {k8s.namespace} -- {command}'
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
return k8s.ssh.run(full_cmd, timeout=timeout)
|
||||||
|
|
||||||
|
def _fb_write_file(content_b64, path, pod_name=None, timeout=30):
|
||||||
|
"""Write a file to the pod filesystem."""
|
||||||
|
import base64
|
||||||
|
cmd = f"echo '{content_b64}' | base64 -d > '{path}'"
|
||||||
|
return _fb_exec(f"sh -c {quote_remote(cmd)}", pod_name, timeout)
|
||||||
|
|
||||||
|
def _get_pod_from_request():
|
||||||
|
pod = request.form.get('pod', '') or request.args.get('pod', '') or request.get_json(silent=True)
|
||||||
|
if isinstance(pod, dict):
|
||||||
|
pod = pod.get('pod', '')
|
||||||
|
return pod or None
|
||||||
|
|
||||||
|
@app.route('/api/files/pods')
|
||||||
|
@auth_req
|
||||||
|
def api_files_pods():
|
||||||
|
try:
|
||||||
|
pods = _list_pods()
|
||||||
|
return jsonify({'success': True, 'pods': pods})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
@app.route('/api/files/list', methods=['POST'])
|
@app.route('/api/files/list', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
def api_files_list():
|
def api_files_list():
|
||||||
path = request.form.get('path', '/srv')
|
path = request.form.get('path', '/srv')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
safe_path = quote_remote(path)
|
safe_path = quote_remote(path)
|
||||||
out, err, rc = _fb_exec(f'ls -la {safe_path}', timeout=10)
|
out, err, rc = _fb_exec(f'ls -la {safe_path}', pod_name, timeout=10)
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
|
return jsonify({'success': False, 'error': err or 'Failed to list directory'})
|
||||||
|
|
||||||
@@ -855,35 +886,90 @@ def register_api_routes(app, services, settings):
|
|||||||
@auth_req
|
@auth_req
|
||||||
def api_files_view():
|
def api_files_view():
|
||||||
path = request.args.get('path', '')
|
path = request.args.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not path:
|
if not path:
|
||||||
return jsonify({'success': False, 'error': 'Missing path'})
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
safe_path = quote_remote(path)
|
safe_path = quote_remote(path)
|
||||||
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', timeout=10)
|
out, err, rc = _fb_exec(f'head -c 100000 {safe_path}', pod_name, timeout=10)
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
||||||
return jsonify({'success': True, 'content': out, 'path': path})
|
return jsonify({'success': True, 'content': out, 'path': path})
|
||||||
|
|
||||||
@app.route('/api/files/save', methods=['POST'])
|
@app.route('/api/files/save', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def api_files_save():
|
def api_files_save():
|
||||||
path = request.form.get('path', '')
|
path = request.form.get('path', '')
|
||||||
content = request.form.get('content', '')
|
content = request.form.get('content', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
if not path:
|
if not path:
|
||||||
return jsonify({'success': False, 'error': 'Missing path'})
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
if not _validate_fb_path(path):
|
if not _validate_fb_path(path):
|
||||||
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
import base64
|
import base64
|
||||||
content_b64 = base64.b64encode(content.encode()).decode()
|
content_b64 = base64.b64encode(content.encode()).decode()
|
||||||
safe_path = quote_remote(path)
|
out, err, rc = _fb_write_file(content_b64, path, pod_name)
|
||||||
save_script = quote_remote(f"base64 -d > {safe_path}")
|
|
||||||
out, err, rc = _fb_exec(f"sh -c {save_script}", timeout=15)
|
|
||||||
if rc != 0:
|
if rc != 0:
|
||||||
return jsonify({'success': False, 'error': err or 'Failed to save file'})
|
return jsonify({'success': False, 'error': err or 'Failed to save file'})
|
||||||
return jsonify({'success': True})
|
return jsonify({'success': True})
|
||||||
|
|
||||||
|
@app.route('/api/files/download', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def api_files_download():
|
||||||
|
path = request.form.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not path:
|
||||||
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
|
if not _validate_fb_path(path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
import base64
|
||||||
|
safe_path = quote_remote(path)
|
||||||
|
out, err, rc = _fb_exec(f'base64 {safe_path}', pod_name, timeout=30)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to read file'})
|
||||||
|
filename = path.rsplit('/', 1)[-1] if '/' in path else path
|
||||||
|
return jsonify({'success': True, 'content': out.strip(), 'filename': filename})
|
||||||
|
|
||||||
|
@app.route('/api/files/upload', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
|
||||||
|
def api_files_upload():
|
||||||
|
target_path = request.form.get('path', '/srv')
|
||||||
|
uploaded = request.files.get('file')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not uploaded:
|
||||||
|
return jsonify({'success': False, 'error': 'No file provided'})
|
||||||
|
if not _validate_fb_path(target_path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
import base64
|
||||||
|
filename = uploaded.filename.rsplit('/', 1)[-1].rsplit('\\', 1)[-1] if uploaded.filename else 'uploaded_file'
|
||||||
|
dest = target_path.rstrip('/') + '/' + filename
|
||||||
|
if not _validate_fb_path(dest):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid destination path'})
|
||||||
|
content = uploaded.read()
|
||||||
|
content_b64 = base64.b64encode(content).decode()
|
||||||
|
out, err, rc = _fb_write_file(content_b64, dest, pod_name)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to upload file'})
|
||||||
|
return jsonify({'success': True, 'filename': filename})
|
||||||
|
|
||||||
|
@app.route('/api/files/delete', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def api_files_delete():
|
||||||
|
path = request.form.get('path', '')
|
||||||
|
pod_name = _get_pod_from_request()
|
||||||
|
if not path:
|
||||||
|
return jsonify({'success': False, 'error': 'Missing path'})
|
||||||
|
if not _validate_fb_path(path):
|
||||||
|
return jsonify({'success': False, 'error': 'Invalid path: access denied'})
|
||||||
|
safe_path = quote_remote(path)
|
||||||
|
out, err, rc = _fb_exec(f'rm -rf {safe_path}', pod_name, timeout=10)
|
||||||
|
if rc != 0:
|
||||||
|
return jsonify({'success': False, 'error': err or 'Failed to delete'})
|
||||||
|
return jsonify({'success': True})
|
||||||
|
|
||||||
director_svc = services.get('director')
|
director_svc = services.get('director')
|
||||||
director_port = settings.get('director', {}).get('port', 32479)
|
director_port = settings.get('director', {}).get('port', 32479)
|
||||||
|
|
||||||
@@ -922,7 +1008,8 @@ def register_api_routes(app, services, settings):
|
|||||||
if map_name:
|
if map_name:
|
||||||
kv = director_svc.extract_server_config_kv(config)
|
kv = director_svc.extract_server_config_kv(config)
|
||||||
if kv:
|
if kv:
|
||||||
director_svc.update_ini_section(map_name, kv)
|
if not director_svc.update_ini_section(map_name, kv):
|
||||||
|
logger.warning("ConfigMap update failed for map %s (director API call succeeded)", map_name)
|
||||||
|
|
||||||
return result, 200, {'Content-Type': 'application/json'}
|
return result, 200, {'Content-Type': 'application/json'}
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
@@ -992,6 +1079,41 @@ def register_api_routes(app, services, settings):
|
|||||||
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
|
return jsonify({'success': False, 'error': 'Director unavailable. The BGD service is not responding.'}), 503
|
||||||
return jsonify({'success': False, 'error': str(e)}), 500
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/director/server_set_scale/<map_name>')
|
||||||
|
@auth_req
|
||||||
|
def director_server_set_scale_get(map_name):
|
||||||
|
try:
|
||||||
|
if not director_svc:
|
||||||
|
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||||
|
scale = director_svc.get_server_set_scale(map_name)
|
||||||
|
if scale is None:
|
||||||
|
return jsonify({'replicas': 0, 'partitions': []})
|
||||||
|
spec = scale.get('spec', {})
|
||||||
|
return jsonify({
|
||||||
|
'replicas': spec.get('replicas', 0),
|
||||||
|
'partitions': [p for p in spec.get('partitions', []) if p is not None],
|
||||||
|
})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
|
@app.route('/api/director/server_set_scale/<map_name>', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def director_server_set_scale_patch(map_name):
|
||||||
|
try:
|
||||||
|
if not director_svc:
|
||||||
|
return jsonify({'success': False, 'error': 'Director service not available'}), 503
|
||||||
|
config = request.get_json()
|
||||||
|
replicas = int(config.get('replicas', 1))
|
||||||
|
partitions_raw = config.get('partitions', [])
|
||||||
|
partitions = [int(p) for p in partitions_raw if p is not None]
|
||||||
|
if replicas > len(partitions):
|
||||||
|
return jsonify({'success': False, 'error': 'replicas cannot exceed partition count'}), 400
|
||||||
|
if not director_svc.patch_server_set_scale(map_name, replicas, partitions):
|
||||||
|
return jsonify({'success': False, 'error': 'Failed to patch ServerSetScale'}), 500
|
||||||
|
return jsonify({'success': True})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)}), 500
|
||||||
|
|
||||||
# Update management
|
# Update management
|
||||||
@app.route('/api/update/status')
|
@app.route('/api/update/status')
|
||||||
@auth_req
|
@auth_req
|
||||||
@@ -1219,7 +1341,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Broadcast ─────────────────────────────────
|
# ── Admin Experimental: Broadcast ─────────────────────────────────
|
||||||
@app.route('/api/admin-experimental/broadcast', methods=['POST'])
|
@app.route('/api/admin-experimental/broadcast', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_broadcast():
|
def admin_broadcast():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
title = (data.get('title') or '').strip()
|
title = (data.get('title') or '').strip()
|
||||||
@@ -1236,7 +1358,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Query Database ────────────────────────────
|
# ── Admin Experimental: Query Database ────────────────────────────
|
||||||
@app.route('/api/admin-experimental/query', methods=['POST'])
|
@app.route('/api/admin-experimental/query', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("300 per hour")
|
|
||||||
def admin_query():
|
def admin_query():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
sql = (data.get('sql') or '').strip()
|
sql = (data.get('sql') or '').strip()
|
||||||
@@ -1275,7 +1397,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Adjust Currency ───────────────────────────
|
# ── Admin Experimental: Adjust Currency ───────────────────────────
|
||||||
@app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
|
@app.route('/api/admin-experimental/adjust-currency', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_adjust_currency():
|
def admin_adjust_currency():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
pid = data.get('player_controller_id')
|
pid = data.get('player_controller_id')
|
||||||
@@ -1289,7 +1411,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Change Faction ────────────────────────────
|
# ── Admin Experimental: Change Faction ────────────────────────────
|
||||||
@app.route('/api/admin-experimental/change-faction', methods=['POST'])
|
@app.route('/api/admin-experimental/change-faction', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_change_faction():
|
def admin_change_faction():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
pid = data.get('player_id')
|
pid = data.get('player_id')
|
||||||
@@ -1329,7 +1451,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Teleport Player ───────────────────────────
|
# ── Admin Experimental: Teleport Player ───────────────────────────
|
||||||
@app.route('/api/admin-experimental/teleport', methods=['POST'])
|
@app.route('/api/admin-experimental/teleport', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_teleport():
|
def admin_teleport():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
fls_id = data.get('fls_id')
|
fls_id = data.get('fls_id')
|
||||||
@@ -1413,7 +1535,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/disband-guild', methods=['POST'])
|
@app.route('/api/admin-experimental/disband-guild', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def admin_disband_guild():
|
def admin_disband_guild():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
guild_id = data.get('guild_id')
|
guild_id = data.get('guild_id')
|
||||||
@@ -1427,7 +1549,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
|
@app.route('/api/admin-experimental/remove-guild-member', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("100 per hour")
|
|
||||||
def admin_remove_guild_member():
|
def admin_remove_guild_member():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
guild_id = data.get('guild_id')
|
guild_id = data.get('guild_id')
|
||||||
@@ -1460,7 +1582,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
|
@app.route('/api/admin-experimental/flag-cheater', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("50 per hour")
|
|
||||||
def admin_flag_cheater():
|
def admin_flag_cheater():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
account_id = data.get('account_id')
|
account_id = data.get('account_id')
|
||||||
@@ -1519,7 +1641,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/delete-character', methods=['POST'])
|
@app.route('/api/admin-experimental/delete-character', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("20 per hour")
|
|
||||||
def admin_delete_character():
|
def admin_delete_character():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
actor_id = data.get('actor_id')
|
actor_id = data.get('actor_id')
|
||||||
@@ -1533,7 +1655,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/delete-account', methods=['POST'])
|
@app.route('/api/admin-experimental/delete-account', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("10 per hour")
|
|
||||||
def admin_delete_account():
|
def admin_delete_account():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
user_id = data.get('user_id')
|
user_id = data.get('user_id')
|
||||||
@@ -1650,7 +1772,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Spice Fields ──────────────────────────────
|
# ── Admin Experimental: Spice Fields ──────────────────────────────
|
||||||
@app.route('/api/admin-experimental/spice', methods=['POST'])
|
@app.route('/api/admin-experimental/spice', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("30 per hour")
|
|
||||||
def admin_spice():
|
def admin_spice():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
try:
|
try:
|
||||||
@@ -1665,7 +1787,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: Server Tools ──────────────────────────────
|
# ── Admin Experimental: Server Tools ──────────────────────────────
|
||||||
@app.route('/api/admin-experimental/server-tools', methods=['POST'])
|
@app.route('/api/admin-experimental/server-tools', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("30 per hour")
|
|
||||||
def admin_server_tools():
|
def admin_server_tools():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
try:
|
try:
|
||||||
@@ -1696,6 +1818,118 @@ def register_api_routes(app, services, settings):
|
|||||||
except Exception as e:
|
except Exception as e:
|
||||||
return jsonify({'success': False, 'error': str(e)})
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
# ── Admin Experimental: RMQ Explorer ─────────────────────────────
|
||||||
|
@app.route('/api/admin-experimental/rmq/overview')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_overview():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_overview()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/queues')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_queues():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_queues()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/exchanges')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_exchanges():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.combined_exchanges()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/bindings')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_bindings():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.bindings()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/consumers')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_consumers():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.consumers()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/peek', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_peek():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
cfg = request.get_json() or {}
|
||||||
|
queue_name = cfg.get('queue', '')
|
||||||
|
count = int(cfg.get('count', 5))
|
||||||
|
if not queue_name:
|
||||||
|
return jsonify({'success': False, 'error': 'queue name required'}), 400
|
||||||
|
data = rmq.peek_messages(queue_name, count=count)
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/publish', methods=['POST'])
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_publish():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
cfg = request.get_json() or {}
|
||||||
|
exchange = cfg.get('exchange', '')
|
||||||
|
routing_key = cfg.get('routing_key', '')
|
||||||
|
message = cfg.get('message', '')
|
||||||
|
side = cfg.get('side', 'admin')
|
||||||
|
if not exchange:
|
||||||
|
return jsonify({'success': False, 'error': 'exchange name required'}), 400
|
||||||
|
if side == 'game':
|
||||||
|
result = rmq.game_publish(exchange, routing_key, message)
|
||||||
|
else:
|
||||||
|
result = rmq.publish(exchange, routing_key, message)
|
||||||
|
return jsonify({'success': True, 'data': result})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
|
@app.route('/api/admin-experimental/rmq/health')
|
||||||
|
@auth_req
|
||||||
|
def admin_rmq_health():
|
||||||
|
try:
|
||||||
|
rmq = services.get('rmq')
|
||||||
|
if not rmq:
|
||||||
|
return jsonify({'success': False, 'error': 'RMQ service not available'}), 503
|
||||||
|
data = rmq.health()
|
||||||
|
return jsonify({'success': True, 'data': data})
|
||||||
|
except Exception as e:
|
||||||
|
return jsonify({'success': False, 'error': str(e)})
|
||||||
|
|
||||||
# ── Admin Experimental: Function Explorer ─────────────────────────
|
# ── Admin Experimental: Function Explorer ─────────────────────────
|
||||||
@app.route('/api/admin-experimental/functions', methods=['GET'])
|
@app.route('/api/admin-experimental/functions', methods=['GET'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@@ -1719,7 +1953,7 @@ def register_api_routes(app, services, settings):
|
|||||||
|
|
||||||
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
|
@app.route('/api/admin-experimental/functions/<name>/execute', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_execute_function(name):
|
def admin_execute_function(name):
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
params = data.get('params', [])
|
params = data.get('params', [])
|
||||||
@@ -1735,7 +1969,7 @@ def register_api_routes(app, services, settings):
|
|||||||
# ── Admin Experimental: SQL Execute (admin functions) ─────────────
|
# ── Admin Experimental: SQL Execute (admin functions) ─────────────
|
||||||
@app.route('/api/admin-experimental/execute', methods=['POST'])
|
@app.route('/api/admin-experimental/execute', methods=['POST'])
|
||||||
@auth_req
|
@auth_req
|
||||||
@limiter.limit("200 per hour")
|
|
||||||
def admin_execute():
|
def admin_execute():
|
||||||
data = request.get_json() or {}
|
data = request.get_json() or {}
|
||||||
sql = (data.get('sql') or '').strip()
|
sql = (data.get('sql') or '').strip()
|
||||||
|
|||||||
+36
-22
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import time
|
import time
|
||||||
import threading
|
import threading
|
||||||
from flask import render_template, request, redirect, url_for, flash
|
from flask import render_template, request, redirect, url_for, flash, session, make_response
|
||||||
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
||||||
from flask_limiter import Limiter
|
from flask_limiter import Limiter
|
||||||
from flask_limiter.util import get_remote_address
|
from flask_limiter.util import get_remote_address
|
||||||
@@ -14,6 +14,15 @@ login_manager.login_message = 'Please log in.'
|
|||||||
# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}}
|
# In-memory failed login tracker: {ip: {"count": int, "first_attempt": float}}
|
||||||
_failed_attempts = {}
|
_failed_attempts = {}
|
||||||
_failed_lock = threading.Lock()
|
_failed_lock = threading.Lock()
|
||||||
|
|
||||||
|
# Reusable Argon2 verifier (created once, not per-request)
|
||||||
|
try:
|
||||||
|
from argon2 import PasswordHasher, exceptions as argon2_exceptions
|
||||||
|
_password_hasher = PasswordHasher(time_cost=3, memory_cost=65536)
|
||||||
|
except ImportError:
|
||||||
|
_password_hasher = None
|
||||||
|
argon2_exceptions = None
|
||||||
|
_failed_lock = threading.Lock()
|
||||||
_MAX_FAILED_ATTEMPTS = 5
|
_MAX_FAILED_ATTEMPTS = 5
|
||||||
_BLOCK_DURATION = 900 # 15 minutes
|
_BLOCK_DURATION = 900 # 15 minutes
|
||||||
|
|
||||||
@@ -82,39 +91,41 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
|
|||||||
u = request.form.get('username', '')
|
u = request.form.get('username', '')
|
||||||
p = request.form.get('password', '')
|
p = request.form.get('password', '')
|
||||||
auth = settings.get('auth', {})
|
auth = settings.get('auth', {})
|
||||||
|
|
||||||
cfg_u = str(auth.get('username', ''))
|
cfg_u = str(auth.get('username', ''))
|
||||||
password_hash = auth.get('password_hash')
|
password_hash = auth.get('password_hash')
|
||||||
|
|
||||||
if u != cfg_u:
|
if not password_hash:
|
||||||
if audit_svc:
|
flash('Authentication not configured. Please run setup.')
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_username'}, user='unknown', severity='warning')
|
|
||||||
_record_failed_attempt(client_ip)
|
|
||||||
flash('Invalid username or password')
|
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
if password_hash:
|
|
||||||
try:
|
try:
|
||||||
from argon2 import PasswordHasher, exceptions
|
# Always run Argon2 verify regardless of username (prevents timing enumeration)
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
from argon2 import exceptions
|
||||||
if ph.verify(password_hash, p):
|
_DUMMY = '$argon2id$v=19$m=65536,t=3,p=4$AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
|
||||||
|
hash_to_verify = password_hash if u == cfg_u else _DUMMY
|
||||||
|
verified = _password_hasher.verify(hash_to_verify, p)
|
||||||
|
|
||||||
|
if verified and u == cfg_u:
|
||||||
_clear_failed_attempts(client_ip)
|
_clear_failed_attempts(client_ip)
|
||||||
login_user(AdminUser(u))
|
login_user(AdminUser(u))
|
||||||
if audit_svc:
|
if audit_svc:
|
||||||
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
|
audit_svc.log('login_success', {'username': u}, user=u, severity='info')
|
||||||
return redirect(url_for('overview'))
|
return redirect(url_for('overview'))
|
||||||
else:
|
else:
|
||||||
if audit_svc:
|
# Dummy always fails; wrong password also fails here
|
||||||
|
_record_failed_attempt(client_ip)
|
||||||
|
if u == cfg_u and audit_svc:
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
||||||
except exceptions.VerifyMismatchError:
|
elif audit_svc:
|
||||||
if audit_svc:
|
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_credentials'}, user='unknown', severity='warning')
|
||||||
audit_svc.log('login_failed', {'username': u, 'reason': 'invalid_password'}, user=u, severity='warning')
|
flash('Invalid username or password')
|
||||||
pass
|
|
||||||
except Exception:
|
|
||||||
flash('Authentication error. Please try again.')
|
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
else:
|
except exceptions.VerifyMismatchError:
|
||||||
flash('Authentication not configured. Please run setup.')
|
_record_failed_attempt(client_ip)
|
||||||
|
flash('Invalid username or password')
|
||||||
|
return render_template('login.html')
|
||||||
|
except Exception as e:
|
||||||
|
flash('Authentication error. Please try again.')
|
||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
_record_failed_attempt(client_ip)
|
_record_failed_attempt(client_ip)
|
||||||
@@ -123,10 +134,13 @@ def init_auth(app, settings, limiter=None, audit_svc=None):
|
|||||||
return render_template('login.html')
|
return render_template('login.html')
|
||||||
|
|
||||||
@app.route('/logout')
|
@app.route('/logout')
|
||||||
@login_required
|
|
||||||
def logout():
|
def logout():
|
||||||
user = current_user.id if current_user.is_authenticated else 'unknown'
|
user = current_user.id if current_user.is_authenticated else 'unknown'
|
||||||
logout_user()
|
logout_user()
|
||||||
|
session.clear()
|
||||||
if audit_svc:
|
if audit_svc:
|
||||||
audit_svc.log('logout', {}, user=user, severity='info')
|
audit_svc.log('logout', {}, user=user, severity='info')
|
||||||
return redirect(url_for('login'))
|
resp = make_response(redirect(url_for('login')))
|
||||||
|
resp.delete_cookie('session')
|
||||||
|
resp.delete_cookie('remember_token')
|
||||||
|
return resp
|
||||||
+77
-18
@@ -6,6 +6,7 @@ from flask import Blueprint, render_template, request, jsonify
|
|||||||
from flask_login import login_required, current_user
|
from flask_login import login_required, current_user
|
||||||
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
from app.utils.constants import NAV_PAGES, GUILD_ROLES
|
||||||
from app.utils.debug_logging import sanitize_for_log
|
from app.utils.debug_logging import sanitize_for_log
|
||||||
|
from app.services.player import LIKE_PC
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
@@ -326,20 +327,32 @@ def register_routes(app, services, settings):
|
|||||||
try:
|
try:
|
||||||
buildings_list = db.query("""
|
buildings_list = db.query("""
|
||||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'ID:' || b.owner_id::text) as owner_name,
|
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name,
|
||||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count,
|
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count,
|
||||||
a.properties->>'m_bIsPowered' as is_powered,
|
a.properties->>'m_bIsPowered' as is_powered,
|
||||||
a.properties->>'m_PowerLevel' as power_level,
|
a.properties->>'m_PowerLevel' as power_level,
|
||||||
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
|
a.properties->'PowerComponent'->>'m_PowerGridID' as power_grid_id
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
JOIN dune.actors a ON b.id = a.id
|
||||||
LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id
|
LEFT JOIN LATERAL (
|
||||||
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
|
FROM dune.building_instances bi
|
||||||
)
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT ps.character_name
|
||||||
|
FROM dune.actors pawn
|
||||||
|
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
ORDER BY owner_name
|
ORDER BY owner_name
|
||||||
LIMIT 200
|
LIMIT 200
|
||||||
""") or []
|
""", [LIKE_PC]) or []
|
||||||
return render_template('buildings.html', buildings=buildings_list)
|
return render_template('buildings.html', buildings=buildings_list)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error in buildings route")
|
logger.exception("Error in buildings route")
|
||||||
@@ -426,7 +439,7 @@ def register_routes(app, services, settings):
|
|||||||
def server_status():
|
def server_status():
|
||||||
logger.debug(f"Page access: /server by user={current_user.id}")
|
logger.debug(f"Page access: /server by user={current_user.id}")
|
||||||
try:
|
try:
|
||||||
active_servers = db.query("""
|
active_servers_raw = db.query("""
|
||||||
SELECT server_id, map
|
SELECT server_id, map
|
||||||
FROM dune.world_partition
|
FROM dune.world_partition
|
||||||
WHERE server_id IS NOT NULL
|
WHERE server_id IS NOT NULL
|
||||||
@@ -448,6 +461,34 @@ def register_routes(app, services, settings):
|
|||||||
deployments = k8s.get_deployments()
|
deployments = k8s.get_deployments()
|
||||||
node_metrics = k8s.get_node_metrics()
|
node_metrics = k8s.get_node_metrics()
|
||||||
|
|
||||||
|
active_servers = []
|
||||||
|
for s in active_servers_raw:
|
||||||
|
sid = (s.get('server_id') or '').lower().replace('_', '-')
|
||||||
|
s['deployment'] = ''
|
||||||
|
mp = (s.get('map') or '').lower().replace('_', '-')
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if sid and sid in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if mp and mp in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if not s['deployment']:
|
||||||
|
mid = '-sg-' + sid
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if mid in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
if not s['deployment'] and mp:
|
||||||
|
for d in deployments:
|
||||||
|
short = d.replace('deployment.apps/', '')
|
||||||
|
if mp in short.lower() and 'pod' in short.lower():
|
||||||
|
s['deployment'] = d
|
||||||
|
break
|
||||||
|
active_servers.append(s)
|
||||||
|
|
||||||
for p in partitions:
|
for p in partitions:
|
||||||
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
sid = (p.get('server_id') or '').lower().replace('_', '-')
|
||||||
p['deployment'] = ''
|
p['deployment'] = ''
|
||||||
@@ -482,7 +523,7 @@ def register_routes(app, services, settings):
|
|||||||
online_players=online_players, partitions=partitions,
|
online_players=online_players, partitions=partitions,
|
||||||
overmap_count=overmap_count.get('c') if overmap_count else 0,
|
overmap_count=overmap_count.get('c') if overmap_count else 0,
|
||||||
online_count=online_count.get('c') if online_count else 0,
|
online_count=online_count.get('c') if online_count else 0,
|
||||||
deployments=deployments, deploys_ok=True, ssh_error='',
|
deployments=deployments, deploys_ok=len(deployments) > 0, ssh_error='',
|
||||||
node_metrics=node_metrics)
|
node_metrics=node_metrics)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.exception("Error in server_status route")
|
logger.exception("Error in server_status route")
|
||||||
@@ -524,7 +565,7 @@ def register_routes(app, services, settings):
|
|||||||
name: cfg for name, cfg in map_config.items()
|
name: cfg for name, cfg in map_config.items()
|
||||||
if isinstance(cfg, dict) and cfg.get('image') and cfg.get('bounds')
|
if isinstance(cfg, dict) and cfg.get('image') and cfg.get('bounds')
|
||||||
}
|
}
|
||||||
default_map = map_config.get('default_map', 'DeepDesert')
|
default_map = map_config.get('default_map', 'HaggaBasin')
|
||||||
|
|
||||||
return map_config, configured_maps, default_map
|
return map_config, configured_maps, default_map
|
||||||
|
|
||||||
@@ -535,6 +576,7 @@ def register_routes(app, services, settings):
|
|||||||
map_options = []
|
map_options = []
|
||||||
for key, cfg in configured_maps.items():
|
for key, cfg in configured_maps.items():
|
||||||
image_size = cfg.get('image_size', {})
|
image_size = cfg.get('image_size', {})
|
||||||
|
bounds = cfg.get('bounds', {})
|
||||||
map_options.append({
|
map_options.append({
|
||||||
'key': key,
|
'key': key,
|
||||||
'label': cfg.get('label') or key,
|
'label': cfg.get('label') or key,
|
||||||
@@ -542,6 +584,7 @@ def register_routes(app, services, settings):
|
|||||||
'width': image_size.get('width', 1000),
|
'width': image_size.get('width', 1000),
|
||||||
'height': image_size.get('height', 1000),
|
'height': image_size.get('height', 1000),
|
||||||
'default_zoom': cfg.get('default_zoom', 0.5),
|
'default_zoom': cfg.get('default_zoom', 0.5),
|
||||||
|
'bounds': bounds,
|
||||||
'counts': {
|
'counts': {
|
||||||
'players': sum(1 for p in player_locations if p.get('map') == key and p.get('in_bounds')),
|
'players': sum(1 for p in player_locations if p.get('map') == key and p.get('in_bounds')),
|
||||||
'vehicles': sum(1 for v in vehicle_locations if v.get('map') == key and v.get('in_bounds')),
|
'vehicles': sum(1 for v in vehicle_locations if v.get('map') == key and v.get('in_bounds')),
|
||||||
@@ -569,27 +612,43 @@ def register_routes(app, services, settings):
|
|||||||
|
|
||||||
# Get vehicles with coordinates for configured map assets
|
# Get vehicles with coordinates for configured map assets
|
||||||
vehicles = db.query("""
|
vehicles = db.query("""
|
||||||
SELECT v.id, a.map, a.transform, a.class
|
SELECT DISTINCT ON (v.id)
|
||||||
|
v.id, a.map, a.transform, a.class,
|
||||||
|
COALESCE(NULLIF(ps.character_name, ''), 'Vehicle ' || v.id::text) as owner_name
|
||||||
FROM dune.vehicles v
|
FROM dune.vehicles v
|
||||||
JOIN dune.actors a ON v.id = a.id
|
JOIN dune.actors a ON v.id = a.id
|
||||||
|
LEFT JOIN dune.permission_actor_rank par ON par.permission_actor_id = v.id
|
||||||
|
LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id
|
||||||
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
||||||
ORDER BY a.map, a.class
|
ORDER BY v.id, par.rank ASC
|
||||||
""", [selected_map_keys]) or []
|
""", [selected_map_keys]) or []
|
||||||
|
|
||||||
# Get bases/buildings with coordinates for configured map assets
|
# Get bases/buildings with coordinates for configured map assets
|
||||||
buildings = db.query("""
|
buildings = db.query("""
|
||||||
SELECT b.id, a.map, a.transform, a.class,
|
SELECT b.id, a.map, a.transform, a.class,
|
||||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(ea.platform_name, ''), 'Base ' || b.id::text) as owner_name
|
COALESCE(NULLIF(owner.character_name, ''), 'Base ' || b.id::text) as owner_name
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
JOIN dune.actors a ON b.id = a.id
|
||||||
LEFT JOIN dune.player_state ps ON b.owner_id = ps.player_pawn_id
|
LEFT JOIN LATERAL (
|
||||||
LEFT JOIN dune.encrypted_accounts ea ON ea.id = (
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
SELECT ps2.account_id FROM dune.player_state ps2 WHERE ps2.player_pawn_id = b.owner_id LIMIT 1
|
FROM dune.building_instances bi
|
||||||
)
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
LEFT JOIN LATERAL (
|
||||||
|
SELECT ps.character_name
|
||||||
|
FROM dune.actors pawn
|
||||||
|
JOIN dune.player_state ps ON pawn.id = ps.player_pawn_id
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
WHERE a.transform IS NOT NULL AND a.map = ANY(%s)
|
||||||
ORDER BY a.map
|
ORDER BY a.map
|
||||||
LIMIT 500
|
LIMIT 500
|
||||||
""", [selected_map_keys]) or []
|
""", [LIKE_PC, selected_map_keys]) or []
|
||||||
|
|
||||||
# Parse coordinates from transform field
|
# Parse coordinates from transform field
|
||||||
def parse_transform(t):
|
def parse_transform(t):
|
||||||
@@ -631,7 +690,7 @@ def register_routes(app, services, settings):
|
|||||||
if coords:
|
if coords:
|
||||||
vehicle_locations.append({
|
vehicle_locations.append({
|
||||||
'id': v['id'],
|
'id': v['id'],
|
||||||
'name': v.get('name', 'Unknown'),
|
'name': v.get('owner_name') or v.get('class', '').split('/')[-1] if v.get('class') else f'Vehicle {v["id"]}',
|
||||||
'map': v['map'],
|
'map': v['map'],
|
||||||
'class': v.get('class', '').split('/')[-1] if v.get('class') else '',
|
'class': v.get('class', '').split('/')[-1] if v.get('class') else '',
|
||||||
'x': coords['x'],
|
'x': coords['x'],
|
||||||
|
|||||||
+76
-86
@@ -26,9 +26,10 @@ def _validate_ip(ip):
|
|||||||
class AdminService:
|
class AdminService:
|
||||||
_iptables_lock = threading.Lock()
|
_iptables_lock = threading.Lock()
|
||||||
|
|
||||||
def __init__(self, db_service, ssh_service):
|
def __init__(self, db_service, ssh_service, dash_db=None):
|
||||||
self.db = db_service
|
self.db = db_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
|
self.dash_db = dash_db or db_service
|
||||||
|
|
||||||
def ban_player(self, player_id, duration=0, reason='', note=''):
|
def ban_player(self, player_id, duration=0, reason='', note=''):
|
||||||
try:
|
try:
|
||||||
@@ -44,17 +45,11 @@ class AdminService:
|
|||||||
account_id = player_row.get('account_id') if player_row else None
|
account_id = player_row.get('account_id') if player_row else None
|
||||||
player_name = player_row.get('character_name', 'Unknown') if player_row else 'Unknown'
|
player_name = player_row.get('character_name', 'Unknown') if player_row else 'Unknown'
|
||||||
|
|
||||||
conn = self.db.get_connection()
|
|
||||||
if not conn:
|
|
||||||
return False, "Database connection failed"
|
|
||||||
cur = None
|
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
if account_id:
|
if account_id:
|
||||||
if duration_int == 0:
|
if duration_int == 0:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
|
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||||
@@ -62,8 +57,8 @@ class AdminService:
|
|||||||
banned_at = NOW(), expires_at = NULL, active = TRUE
|
banned_at = NOW(), expires_at = NULL, active = TRUE
|
||||||
""", [player_id, account_id, reason, note, duration_int])
|
""", [player_id, account_id, reason, note, duration_int])
|
||||||
else:
|
else:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
VALUES (%s, %s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||||
@@ -72,8 +67,8 @@ class AdminService:
|
|||||||
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
||||||
else:
|
else:
|
||||||
if duration_int == 0:
|
if duration_int == 0:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
|
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||||
@@ -81,8 +76,8 @@ class AdminService:
|
|||||||
expires_at = NULL, active = TRUE
|
expires_at = NULL, active = TRUE
|
||||||
""", [player_id, reason, note, duration_int])
|
""", [player_id, reason, note, duration_int])
|
||||||
else:
|
else:
|
||||||
cur.execute("""
|
self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
INSERT INTO bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||||
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
||||||
ON CONFLICT (player_id) DO UPDATE SET
|
ON CONFLICT (player_id) DO UPDATE SET
|
||||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||||
@@ -90,47 +85,47 @@ class AdminService:
|
|||||||
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||||
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
|
audit_logger.info(f"BAN: player_id={player_id} player_name={player_name} duration={duration_int}min reason={reason}")
|
||||||
return True, f"Player {player_name} banned for {duration_int} minutes"
|
return True, f"Player {player_name} banned for {duration_int} minutes"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to ban player {player_id}: {e}")
|
logger.error(f"Failed to ban player {player_id}: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def unban_player(self, player_id):
|
def unban_player(self, player_id):
|
||||||
conn = self.db.get_connection()
|
|
||||||
if not conn:
|
|
||||||
return False, "Database connection failed"
|
|
||||||
cur = None
|
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
# Delete from dashboard bans
|
||||||
cur.execute("DELETE FROM dashboard.bans WHERE player_id = %s", [player_id])
|
self.dash_db.execute("DELETE FROM bans WHERE player_id = %s", [player_id])
|
||||||
conn.commit()
|
|
||||||
|
|
||||||
cur.execute("SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s", [player_id])
|
# Look up account info from game database
|
||||||
account_row = cur.fetchone()
|
account_row = self.db.query(
|
||||||
account_id = account_row[0] if account_row and isinstance(account_row, (tuple, list)) else (account_row.get('account_id') if account_row else None)
|
"SELECT ps.account_id FROM dune.player_state ps WHERE ps.player_controller_id = %s",
|
||||||
|
[player_id], one=True
|
||||||
|
)
|
||||||
|
account_id = account_row.get('account_id') if account_row else None
|
||||||
|
|
||||||
ips_to_unblock = []
|
ips_to_unblock = []
|
||||||
if account_id:
|
if account_id:
|
||||||
all_ips = self.db.query("""
|
game_account_players = self.db.query(
|
||||||
SELECT ip_address FROM dashboard.player_ips
|
"SELECT player_controller_id FROM dune.player_state WHERE account_id = %s",
|
||||||
WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s)
|
[account_id]
|
||||||
""", [account_id]) or []
|
) or []
|
||||||
ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')]
|
account_player_ids = [r['player_controller_id'] for r in game_account_players]
|
||||||
|
if account_player_ids:
|
||||||
|
placeholders = ','.join(['%s'] * len(account_player_ids))
|
||||||
|
ips_rows = self.dash_db.query(
|
||||||
|
f"SELECT ip_address FROM player_ips WHERE player_id IN ({placeholders})",
|
||||||
|
account_player_ids
|
||||||
|
) or []
|
||||||
|
ips_to_unblock = [r.get('ip_address') for r in ips_rows if r.get('ip_address')]
|
||||||
else:
|
else:
|
||||||
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
|
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
|
||||||
if ip_row and ip_row.get('ip_address'):
|
if ip_row and ip_row.get('ip_address'):
|
||||||
ips_to_unblock.append(ip_row.get('ip_address'))
|
ips_to_unblock.append(ip_row.get('ip_address'))
|
||||||
|
|
||||||
cur.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
|
self.dash_db.execute(
|
||||||
conn.commit()
|
"INSERT INTO player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)",
|
||||||
|
[player_id]
|
||||||
|
)
|
||||||
|
|
||||||
with self._iptables_lock:
|
with self._iptables_lock:
|
||||||
for ip in ips_to_unblock:
|
for ip in ips_to_unblock:
|
||||||
@@ -144,13 +139,7 @@ class AdminService:
|
|||||||
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
|
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to unban player {player_id}: {e}")
|
logger.error(f"Failed to unban player {player_id}: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def kick_player(self, player_id):
|
def kick_player(self, player_id):
|
||||||
player = self.db.query("""
|
player = self.db.query("""
|
||||||
@@ -163,7 +152,7 @@ class AdminService:
|
|||||||
return False, "Player not found"
|
return False, "Player not found"
|
||||||
|
|
||||||
player_name = player.get('character_name', 'Unknown')
|
player_name = player.get('character_name', 'Unknown')
|
||||||
ip_row = self.db.query("SELECT ip_address FROM dashboard.player_ips WHERE player_id = %s", [player_id], one=True)
|
ip_row = self.dash_db.query("SELECT ip_address FROM player_ips WHERE player_id = %s", [player_id], one=True)
|
||||||
player_ip = ip_row.get('ip_address') if ip_row else None
|
player_ip = ip_row.get('ip_address') if ip_row else None
|
||||||
|
|
||||||
if not player_ip:
|
if not player_ip:
|
||||||
@@ -184,7 +173,7 @@ class AdminService:
|
|||||||
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
||||||
thread.start()
|
thread.start()
|
||||||
|
|
||||||
self.db.execute("INSERT INTO dashboard.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
self.dash_db.execute("INSERT INTO player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
||||||
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
|
audit_logger.info(f"KICK: player_id={player_id} player_name={player_name} ip={player_ip}")
|
||||||
|
|
||||||
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
||||||
@@ -262,14 +251,8 @@ class AdminService:
|
|||||||
if not game_pods:
|
if not game_pods:
|
||||||
return False, "No game server pods found"
|
return False, "No game server pods found"
|
||||||
|
|
||||||
conn = self.db.get_connection()
|
|
||||||
if not conn:
|
|
||||||
return False, "Database connection failed"
|
|
||||||
cur = None
|
|
||||||
updated = 0
|
updated = 0
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
|
||||||
|
|
||||||
for pod_name, map_name in game_pods:
|
for pod_name, map_name in game_pods:
|
||||||
cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- find /home/dune -name "*.log" -path "*/Logs/*" 2>/dev/null | head -5'
|
cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- find /home/dune -name "*.log" -path "*/Logs/*" 2>/dev/null | head -5'
|
||||||
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
|
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
|
||||||
@@ -302,26 +285,25 @@ class AdminService:
|
|||||||
|
|
||||||
if ip_to_player:
|
if ip_to_player:
|
||||||
for ip, name in ip_to_player.items():
|
for ip, name in ip_to_player.items():
|
||||||
cur.execute("""
|
player_row = self.db.query("""
|
||||||
SELECT ps.player_controller_id, ps.account_id
|
SELECT ps.player_controller_id, ps.account_id
|
||||||
FROM dune.player_state ps
|
FROM dune.player_state ps
|
||||||
JOIN dune.accounts a ON ps.account_id = a.id
|
JOIN dune.accounts a ON ps.account_id = a.id
|
||||||
WHERE a.funcom_id = %s OR ps.character_name = %s
|
WHERE a.funcom_id = %s OR ps.character_name = %s
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""", [name, name])
|
""", [name, name], one=True)
|
||||||
row = cur.fetchone()
|
if player_row:
|
||||||
if row:
|
pid = player_row.get('player_controller_id')
|
||||||
pid = row[0] if isinstance(row, (tuple, list)) else row.get('funcom_id')
|
account_id = player_row.get('account_id')
|
||||||
account_id = row[1] if isinstance(row, (tuple, list)) else row.get('account_id')
|
self.dash_db.execute("""
|
||||||
cur.execute("""
|
INSERT INTO player_ips (player_id, ip_address, updated_at)
|
||||||
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
|
|
||||||
VALUES (%s, %s, NOW())
|
VALUES (%s, %s, NOW())
|
||||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||||
""", [pid, ip])
|
""", [pid, ip])
|
||||||
updated += 1
|
updated += 1
|
||||||
|
|
||||||
ban_check = self.db.query("""
|
ban_check = self.dash_db.query("""
|
||||||
SELECT player_id FROM dashboard.bans
|
SELECT player_id FROM bans
|
||||||
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""", [pid, account_id], one=True)
|
""", [pid, account_id], one=True)
|
||||||
@@ -334,21 +316,14 @@ class AdminService:
|
|||||||
else:
|
else:
|
||||||
logger.warning(f"Skipping invalid IP for ban block: {ip}")
|
logger.warning(f"Skipping invalid IP for ban block: {ip}")
|
||||||
|
|
||||||
conn.commit()
|
|
||||||
return True, f"Updated {updated} player IPs from game logs"
|
return True, f"Updated {updated} player IPs from game logs"
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Failed to detect player IPs: {e}")
|
logger.error(f"Failed to detect player IPs: {e}")
|
||||||
if conn:
|
|
||||||
conn.rollback()
|
|
||||||
return False, str(e)
|
return False, str(e)
|
||||||
finally:
|
|
||||||
if cur:
|
|
||||||
cur.close()
|
|
||||||
self.db.return_connection(conn)
|
|
||||||
|
|
||||||
def set_player_ip(self, player_id, ip_address):
|
def set_player_ip(self, player_id, ip_address):
|
||||||
return self.db.execute("""
|
return self.dash_db.execute("""
|
||||||
INSERT INTO dashboard.player_ips (player_id, ip_address, updated_at)
|
INSERT INTO player_ips (player_id, ip_address, updated_at)
|
||||||
VALUES (%s, %s, NOW())
|
VALUES (%s, %s, NOW())
|
||||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||||
""", [player_id, ip_address])
|
""", [player_id, ip_address])
|
||||||
@@ -363,21 +338,31 @@ class AdminService:
|
|||||||
return True, f"Unblocked {ip}"
|
return True, f"Unblocked {ip}"
|
||||||
|
|
||||||
def get_bans(self, limit=50):
|
def get_bans(self, limit=50):
|
||||||
return self.db.query("""
|
bans = self.dash_db.query("""
|
||||||
SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name
|
SELECT id, player_id, reason, active, banned_at, expires_at
|
||||||
FROM dashboard.bans b
|
FROM bans
|
||||||
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
|
ORDER BY banned_at DESC
|
||||||
ORDER BY b.banned_at DESC
|
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""", [limit]) or []
|
""", [limit]) or []
|
||||||
|
for ban in bans:
|
||||||
|
pid = ban.get('player_id')
|
||||||
|
if pid:
|
||||||
|
player = self.db.query(
|
||||||
|
"SELECT character_name FROM dune.player_state WHERE player_controller_id = %s",
|
||||||
|
[pid], one=True
|
||||||
|
)
|
||||||
|
ban['character_name'] = player.get('character_name', '') if player else ''
|
||||||
|
else:
|
||||||
|
ban['character_name'] = ''
|
||||||
|
return bans
|
||||||
|
|
||||||
def get_player_ban(self, player_id):
|
def get_player_ban(self, player_id):
|
||||||
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dashboard.bans WHERE player_id = %s", [player_id], one=True)
|
return self.dash_db.query("SELECT reason, note, duration, banned_at, expires_at FROM bans WHERE player_id = %s", [player_id], one=True)
|
||||||
|
|
||||||
def get_player_history(self, player_id, limit=20):
|
def get_player_history(self, player_id, limit=20):
|
||||||
return self.db.query("""
|
return self.dash_db.query("""
|
||||||
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
||||||
FROM dashboard.player_actions
|
FROM player_actions
|
||||||
WHERE player_id = %s
|
WHERE player_id = %s
|
||||||
ORDER BY created_at DESC
|
ORDER BY created_at DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
@@ -813,17 +798,22 @@ class AdminService:
|
|||||||
try:
|
try:
|
||||||
import base64
|
import base64
|
||||||
import json as _json
|
import json as _json
|
||||||
title_json = _json.dumps(title)[1:-1]
|
import os
|
||||||
message_json = _json.dumps(message)[1:-1]
|
|
||||||
|
token = os.environ.get('DUNE_BROADCAST_TOKEN',
|
||||||
|
getattr(self, '_broadcast_token', None) or 'Nu6VmPWUMvdPMeB7qErr')
|
||||||
|
title_b64 = base64.b64encode(title.encode('utf-8')).decode()
|
||||||
|
message_b64 = base64.b64encode(message.encode('utf-8')).decode()
|
||||||
|
|
||||||
erl = (
|
erl = (
|
||||||
f'Title = unicode:characters_to_binary(<<"{title_json}">>, utf8), '
|
f'Title = base64:decode(<<"{title_b64}">>), '
|
||||||
f'Body = unicode:characters_to_binary(<<"{message_json}">>, utf8), '
|
f'Body = base64:decode(<<"{message_b64}">>), '
|
||||||
f'Duration = {duration}, '
|
f'Duration = {duration}, '
|
||||||
|
f'Token = <<"{token}">>, '
|
||||||
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEn = #{<<"Key">> => <<"en">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
'EntryEnUs = #{<<"Key">> => <<"en-US">>, <<"Title">> => Title, <<"Body">> => Body}, '
|
||||||
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
'Inner = iolist_to_binary(rabbit_json:encode(#{<<"ServerCommand">> => <<"ServiceBroadcast">>, <<"BroadcastType">> => <<"Generic">>, <<"BroadcastPayload">> => #{<<"BroadcastDuration">> => Duration, <<"LocalizedText">> => [EntryEn, EntryEnUs]}})), '
|
||||||
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => <<"Nu6VmPWUMvdPMeB7qErr">>, <<"MessageContent">> => Inner})), '
|
'Outer = iolist_to_binary(rabbit_json:encode(#{<<"Version">> => 2, <<"AuthToken">> => Token, <<"MessageContent">> => Inner})), '
|
||||||
'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), '
|
'XName = rabbit_misc:r(<<"/">>, exchange, <<"heartbeats">>), '
|
||||||
'X = rabbit_exchange:lookup_or_die(XName), '
|
'X = rabbit_exchange:lookup_or_die(XName), '
|
||||||
'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), '
|
'MsgId = list_to_binary("manual-service-broadcast-" ++ integer_to_list(erlang:system_time(millisecond))), '
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
class ChatService:
|
class ChatService:
|
||||||
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
||||||
self.db = db_service
|
self.db = db_service # DashboardDatabaseService
|
||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.cache = cache
|
self.cache = cache
|
||||||
@@ -20,7 +20,7 @@ class ChatService:
|
|||||||
return True
|
return True
|
||||||
try:
|
try:
|
||||||
self.db.execute("""
|
self.db.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
|
CREATE TABLE IF NOT EXISTS chat_history (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
timestamp TIMESTAMP DEFAULT NOW(),
|
||||||
channel VARCHAR(50),
|
channel VARCHAR(50),
|
||||||
@@ -33,7 +33,7 @@ class ChatService:
|
|||||||
is_admin BOOLEAN DEFAULT FALSE
|
is_admin BOOLEAN DEFAULT FALSE
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)")
|
self.db.execute("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON chat_history (timestamp DESC)")
|
||||||
self.ensured_table = True
|
self.ensured_table = True
|
||||||
logger.info("Chat history table ready")
|
logger.info("Chat history table ready")
|
||||||
return True
|
return True
|
||||||
@@ -46,7 +46,7 @@ class ChatService:
|
|||||||
loc_y = location.get('Y', 0) if location else 0
|
loc_y = location.get('Y', 0) if location else 0
|
||||||
loc_z = location.get('Z', 0) if location else 0
|
loc_z = location.get('Z', 0) if location else 0
|
||||||
return self.db.execute("""
|
return self.db.execute("""
|
||||||
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
|
""", [channel, sender, message, target, loc_x, loc_y, loc_z, is_admin])
|
||||||
|
|
||||||
@@ -61,7 +61,7 @@ class ChatService:
|
|||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
for msg in messages:
|
for msg in messages:
|
||||||
cur.execute("""
|
cur.execute("""
|
||||||
INSERT INTO dashboard.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
INSERT INTO chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||||
""", [
|
""", [
|
||||||
msg['channel'], msg['sender'], msg['message'],
|
msg['channel'], msg['sender'], msg['message'],
|
||||||
@@ -87,7 +87,7 @@ class ChatService:
|
|||||||
return self.db.query("""
|
return self.db.query("""
|
||||||
SELECT id, timestamp, channel, sender, message, target,
|
SELECT id, timestamp, channel, sender, message, target,
|
||||||
location_x, location_y, location_z, is_admin
|
location_x, location_y, location_z, is_admin
|
||||||
FROM dashboard.chat_history
|
FROM chat_history
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT %s
|
LIMIT %s
|
||||||
""", [limit])
|
""", [limit])
|
||||||
|
|||||||
+248
-12
@@ -10,11 +10,10 @@ logger = logging.getLogger(__name__)
|
|||||||
|
|
||||||
|
|
||||||
class DatabaseService:
|
class DatabaseService:
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema='dashboard'):
|
def __init__(self, db_config, min_conn=2, max_conn=10):
|
||||||
self.db_config = db_config
|
self.db_config = db_config
|
||||||
self.min_conn = min_conn
|
self.min_conn = min_conn
|
||||||
self.max_conn = max_conn
|
self.max_conn = max_conn
|
||||||
self.dashboard_schema = dashboard_schema
|
|
||||||
self.pool = None
|
self.pool = None
|
||||||
|
|
||||||
def init_pool(self):
|
def init_pool(self):
|
||||||
@@ -138,23 +137,186 @@ class DatabaseService:
|
|||||||
return False
|
return False
|
||||||
|
|
||||||
def ensure_tables(self):
|
def ensure_tables(self):
|
||||||
|
"""No-op: dashboard tables now live in a separate database."""
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class DashboardDatabaseService:
|
||||||
|
"""Service for the dedicated dashboard database (player_ips, bans, audit_log, etc.)."""
|
||||||
|
|
||||||
|
def __init__(self, db_config, min_conn=2, max_conn=10, owner='dune'):
|
||||||
|
self.db_config = db_config
|
||||||
|
self.min_conn = min_conn
|
||||||
|
self.max_conn = max_conn
|
||||||
|
self.owner = owner
|
||||||
|
self.pool = None
|
||||||
|
self._migrated = False
|
||||||
|
|
||||||
|
def init_pool(self):
|
||||||
|
if self.pool is not None:
|
||||||
|
return self.pool
|
||||||
|
for attempt in range(10):
|
||||||
|
try:
|
||||||
|
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||||
|
minconn=self.min_conn,
|
||||||
|
maxconn=self.max_conn,
|
||||||
|
**self.db_config
|
||||||
|
)
|
||||||
|
logger.info("Dashboard database pool initialized")
|
||||||
|
return self.pool
|
||||||
|
except psycopg2.OperationalError as e:
|
||||||
|
if 'does not exist' in str(e) and attempt == 0:
|
||||||
|
logger.info("Dashboard database does not exist, creating...")
|
||||||
|
self._ensure_database()
|
||||||
|
continue
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
except Exception as e:
|
||||||
|
if attempt < 9:
|
||||||
|
logger.warning(f"Dashboard DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
||||||
|
time.sleep(2)
|
||||||
|
else:
|
||||||
|
logger.error(f"Failed to initialize dashboard pool after 10 attempts: {e}")
|
||||||
|
self.pool = None
|
||||||
|
return self.pool
|
||||||
|
|
||||||
|
def _ensure_database(self):
|
||||||
|
try:
|
||||||
|
admin_config = dict(self.db_config)
|
||||||
|
admin_config['database'] = 'postgres'
|
||||||
|
conn = psycopg2.connect(**admin_config)
|
||||||
|
conn.autocommit = True
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute("SELECT 1 FROM pg_database WHERE datname = %s", [self.db_config['database']])
|
||||||
|
if not cur.fetchone():
|
||||||
|
cur.execute(f"CREATE DATABASE {self.db_config['database']} OWNER {self.db_config['user']}")
|
||||||
|
logger.info("Created dashboard database '%s'", self.db_config['database'])
|
||||||
|
cur.close()
|
||||||
|
conn.close()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to create dashboard database: %s", e)
|
||||||
|
raise
|
||||||
|
|
||||||
|
def _migrate_old_schema(self, game_db):
|
||||||
|
if self._migrated:
|
||||||
|
return
|
||||||
|
tables = ['settings', 'bans', 'player_ips', 'player_actions', 'audit_log', 'chat_history']
|
||||||
|
migrated = False
|
||||||
|
for table in tables:
|
||||||
|
try:
|
||||||
|
rows = game_db.query(f"SELECT count(*) as cnt FROM dashboard.{table}", one=True)
|
||||||
|
if rows and rows.get('cnt', 0) > 0:
|
||||||
|
logger.info("Migrating %d rows from dashboard.%s", rows['cnt'], table)
|
||||||
|
old_rows = game_db.query(f"SELECT * FROM dashboard.{table}")
|
||||||
|
if old_rows:
|
||||||
|
cols = list(old_rows[0].keys())
|
||||||
|
placeholders = ','.join(['%s'] * len(cols))
|
||||||
|
col_names = ','.join(cols)
|
||||||
|
for row in old_rows:
|
||||||
|
vals = [row[c] for c in cols]
|
||||||
|
self.execute(
|
||||||
|
f"INSERT INTO {table} ({col_names}) VALUES ({placeholders}) ON CONFLICT DO NOTHING",
|
||||||
|
vals,
|
||||||
|
)
|
||||||
|
migrated = True
|
||||||
|
logger.info("Migrated dashboard.%s -> %s (%d rows)", table, table, rows['cnt'])
|
||||||
|
except Exception as e:
|
||||||
|
logger.debug("No data to migrate from dashboard.%s: %s", table, e)
|
||||||
|
if migrated:
|
||||||
|
logger.info("Data migration from old dashboard schema complete")
|
||||||
|
self._migrated = True
|
||||||
|
|
||||||
|
def get_connection(self):
|
||||||
|
try:
|
||||||
|
pool = self.init_pool()
|
||||||
|
if pool:
|
||||||
|
return pool.getconn()
|
||||||
|
return psycopg2.connect(**self.db_config)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Failed to get dashboard connection: %s", e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def return_connection(self, conn):
|
||||||
|
if conn and self.pool and hasattr(conn, 'poll'):
|
||||||
|
try:
|
||||||
|
self.pool.putconn(conn)
|
||||||
|
except Exception:
|
||||||
|
try:
|
||||||
|
conn.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
def close_all(self):
|
||||||
|
if self.pool:
|
||||||
|
try:
|
||||||
|
self.pool.closeall()
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Error closing dashboard pool: %s", e)
|
||||||
|
self.pool = None
|
||||||
|
|
||||||
|
def query(self, sql, params=None, one=False):
|
||||||
|
conn = self.get_connection()
|
||||||
|
if not conn:
|
||||||
|
return {} if one else []
|
||||||
|
cur = None
|
||||||
|
try:
|
||||||
|
cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)
|
||||||
|
cur.execute(sql, params)
|
||||||
|
rows = cur.fetchall()
|
||||||
|
if one and rows:
|
||||||
|
return rows[0]
|
||||||
|
if one:
|
||||||
|
return {}
|
||||||
|
return rows
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Dashboard query error: %s", e)
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
if cur:
|
||||||
|
cur.close()
|
||||||
|
self.return_connection(conn)
|
||||||
|
|
||||||
|
def execute(self, sql, params=None, commit=True):
|
||||||
|
conn = self.get_connection()
|
||||||
|
if not conn:
|
||||||
|
return False
|
||||||
|
cur = None
|
||||||
|
try:
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute(sql, params)
|
||||||
|
if commit:
|
||||||
|
conn.commit()
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.error("Dashboard execute error: %s", e)
|
||||||
|
if conn:
|
||||||
|
conn.rollback()
|
||||||
|
return False
|
||||||
|
finally:
|
||||||
|
if cur:
|
||||||
|
cur.close()
|
||||||
|
self.return_connection(conn)
|
||||||
|
|
||||||
|
def ensure_tables(self, game_db=None):
|
||||||
conn = self.get_connection()
|
conn = self.get_connection()
|
||||||
if not conn:
|
if not conn:
|
||||||
return
|
return
|
||||||
cur = None
|
cur = None
|
||||||
schema = self.dashboard_schema
|
|
||||||
try:
|
try:
|
||||||
cur = conn.cursor()
|
cur = conn.cursor()
|
||||||
cur.execute(f"CREATE SCHEMA IF NOT EXISTS {schema}")
|
cur.execute("""
|
||||||
cur.execute(f"""
|
CREATE TABLE IF NOT EXISTS player_ips (
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
|
|
||||||
player_id BIGINT PRIMARY KEY,
|
player_id BIGINT PRIMARY KEY,
|
||||||
ip_address INET NOT NULL,
|
ip_address INET NOT NULL,
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
cur.execute(f"""
|
cur.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.bans (
|
CREATE TABLE IF NOT EXISTS bans (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT UNIQUE,
|
player_id BIGINT UNIQUE,
|
||||||
account_id BIGINT,
|
account_id BIGINT,
|
||||||
@@ -166,8 +328,8 @@ class DatabaseService:
|
|||||||
active BOOLEAN DEFAULT TRUE
|
active BOOLEAN DEFAULT TRUE
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
cur.execute(f"""
|
cur.execute("""
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
|
CREATE TABLE IF NOT EXISTS player_actions (
|
||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
player_id BIGINT NOT NULL,
|
player_id BIGINT NOT NULL,
|
||||||
action_type VARCHAR(50) NOT NULL,
|
action_type VARCHAR(50) NOT NULL,
|
||||||
@@ -178,13 +340,87 @@ class DatabaseService:
|
|||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
)
|
)
|
||||||
""")
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_log (
|
||||||
|
id BIGSERIAL PRIMARY KEY,
|
||||||
|
action_type VARCHAR(50) NOT NULL,
|
||||||
|
user_name VARCHAR(100) NOT NULL,
|
||||||
|
target_player_id BIGINT,
|
||||||
|
details JSONB DEFAULT '{}',
|
||||||
|
source_ip INET,
|
||||||
|
severity VARCHAR(20) DEFAULT 'info',
|
||||||
|
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_history (
|
||||||
|
id SERIAL PRIMARY KEY,
|
||||||
|
timestamp TIMESTAMP DEFAULT NOW(),
|
||||||
|
channel VARCHAR(50),
|
||||||
|
sender VARCHAR(255),
|
||||||
|
message TEXT,
|
||||||
|
target VARCHAR(255),
|
||||||
|
location_x FLOAT,
|
||||||
|
location_y FLOAT,
|
||||||
|
location_z FLOAT,
|
||||||
|
is_admin BOOLEAN DEFAULT FALSE
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
cur.execute("""
|
||||||
|
CREATE TABLE IF NOT EXISTS settings (
|
||||||
|
key VARCHAR(255) PRIMARY KEY,
|
||||||
|
value TEXT DEFAULT '',
|
||||||
|
updated_at TIMESTAMP DEFAULT NOW()
|
||||||
|
)
|
||||||
|
""")
|
||||||
|
|
||||||
|
owner = self.owner
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER TABLE public.' || quote_ident(r.tablename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"""
|
||||||
|
DO $$DECLARE r RECORD;
|
||||||
|
BEGIN
|
||||||
|
FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = 'public'
|
||||||
|
LOOP
|
||||||
|
EXECUTE 'ALTER SEQUENCE public.' || quote_ident(r.sequencename) || ' OWNER TO {owner}';
|
||||||
|
END LOOP;
|
||||||
|
END$$;
|
||||||
|
""")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON TABLES TO {owner}")
|
||||||
|
cur.execute(f"ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT ALL ON SEQUENCES TO {owner}")
|
||||||
|
|
||||||
conn.commit()
|
conn.commit()
|
||||||
logger.info(f"Dashboard tables ensured in schema '{schema}' (player_ips, bans, player_actions)")
|
logger.info("Legacy dashboard tables ensured, owner=%s", owner)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.warning(f"Failed to ensure dashboard tables: {e}")
|
logger.warning("Failed to ensure legacy dashboard tables: %s", e)
|
||||||
if conn:
|
if conn:
|
||||||
conn.rollback()
|
conn.rollback()
|
||||||
finally:
|
finally:
|
||||||
if cur:
|
if cur:
|
||||||
cur.close()
|
cur.close()
|
||||||
self.return_connection(conn)
|
self.return_connection(conn)
|
||||||
|
|
||||||
|
if game_db is not None:
|
||||||
|
self._migrate_old_schema(game_db)
|
||||||
|
|
||||||
|
def check_health(self):
|
||||||
|
try:
|
||||||
|
conn = self.get_connection()
|
||||||
|
if not conn:
|
||||||
|
return False
|
||||||
|
cur = conn.cursor()
|
||||||
|
cur.execute('SELECT 1')
|
||||||
|
cur.fetchone()
|
||||||
|
cur.close()
|
||||||
|
self.return_connection(conn)
|
||||||
|
return True
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("Dashboard health check FAILED: %s", e)
|
||||||
|
return False
|
||||||
@@ -27,7 +27,13 @@ class DirectorService:
|
|||||||
self.k8s = k8s_service
|
self.k8s = k8s_service
|
||||||
self.ssh = ssh_service
|
self.ssh = ssh_service
|
||||||
self.namespace = namespace
|
self.namespace = namespace
|
||||||
self.cm_name = f"{namespace}-bgd-conf-cm"
|
resource_prefix = namespace
|
||||||
|
for prefix in ['funcom-seabass-']:
|
||||||
|
if resource_prefix.startswith(prefix):
|
||||||
|
resource_prefix = resource_prefix[len(prefix):]
|
||||||
|
break
|
||||||
|
self.resource_prefix = resource_prefix
|
||||||
|
self.cm_name = f"{resource_prefix}-bgd-conf-cm"
|
||||||
|
|
||||||
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
def _request(self, path: str, method: str = 'GET', data: Any = None,
|
||||||
timeout: int = 15, raw_data: bool = False) -> str:
|
timeout: int = 15, raw_data: bool = False) -> str:
|
||||||
@@ -141,8 +147,9 @@ class DirectorService:
|
|||||||
Returns:
|
Returns:
|
||||||
True if the update succeeded, False otherwise.
|
True if the update succeeded, False otherwise.
|
||||||
"""
|
"""
|
||||||
cm_out, _, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
cm_out, cm_err, cm_rc = self.k8s.run(f'get configmap {self.cm_name} -o json')
|
||||||
if cm_rc != 0 or not cm_out:
|
if cm_rc != 0 or not cm_out:
|
||||||
|
logger.warning("update_ini_section: could not get ConfigMap %s: %s", self.cm_name, cm_err)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
cm = json.loads(cm_out)
|
cm = json.loads(cm_out)
|
||||||
@@ -165,6 +172,39 @@ class DirectorService:
|
|||||||
cfg.write(buf)
|
cfg.write(buf)
|
||||||
return self.patch_configmap(buf.getvalue())
|
return self.patch_configmap(buf.getvalue())
|
||||||
|
|
||||||
|
# ── ServerSetScale management ────────────────────────────────────
|
||||||
|
|
||||||
|
def _map_to_scale_name(self, map_name: str) -> str:
|
||||||
|
safe = map_name.lower().replace('_', '-')
|
||||||
|
return f"{self.resource_prefix}-{safe}"
|
||||||
|
|
||||||
|
def get_server_set_scale(self, map_name: str) -> Optional[Dict]:
|
||||||
|
name = self._map_to_scale_name(map_name)
|
||||||
|
cm_out, cm_err, cm_rc = self.k8s.run(
|
||||||
|
f'get serversetscale {name} -o json')
|
||||||
|
if cm_rc != 0 or not cm_out:
|
||||||
|
return None
|
||||||
|
return json.loads(cm_out)
|
||||||
|
|
||||||
|
def patch_server_set_scale(self, map_name: str, replicas: int,
|
||||||
|
partitions: list) -> bool:
|
||||||
|
name = self._map_to_scale_name(map_name)
|
||||||
|
patch = json.dumps({
|
||||||
|
'spec': {
|
||||||
|
'partitions': partitions,
|
||||||
|
'replicas': replicas,
|
||||||
|
}
|
||||||
|
})
|
||||||
|
patch_b64 = base64.b64encode(patch.encode()).decode()
|
||||||
|
cmd = (f'echo {patch_b64} | base64 -d | '
|
||||||
|
f'sudo kubectl patch serversetscale {name} -n {self.namespace} '
|
||||||
|
f'--type merge --patch-file /dev/stdin')
|
||||||
|
out, err, rc = self.ssh.run(cmd, timeout=15)
|
||||||
|
if rc != 0:
|
||||||
|
logger.warning("ServerSetScale patch failed for %s: %s", map_name, err)
|
||||||
|
return False
|
||||||
|
return True
|
||||||
|
|
||||||
# ── Helper: extract config values for INI update ─────────────────
|
# ── Helper: extract config values for INI update ─────────────────
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|||||||
+36
-6
@@ -41,8 +41,9 @@ def _build_player_filters(search='', faction_id='', guild_id='', map_filter='',
|
|||||||
|
|
||||||
|
|
||||||
class PlayerService:
|
class PlayerService:
|
||||||
def __init__(self, db_service):
|
def __init__(self, db_service, dash_db=None):
|
||||||
self.db = db_service
|
self.db = db_service
|
||||||
|
self.dash_db = dash_db
|
||||||
|
|
||||||
def is_online(self, player_controller_id):
|
def is_online(self, player_controller_id):
|
||||||
result = self.db.query(
|
result = self.db.query(
|
||||||
@@ -131,8 +132,7 @@ class PlayerService:
|
|||||||
ea.id as account_id, ea.user as account_email,
|
ea.id as account_id, ea.user as account_email,
|
||||||
acc.funcom_id,
|
acc.funcom_id,
|
||||||
ps.player_controller_id,
|
ps.player_controller_id,
|
||||||
f.name as faction_name, g.guild_name,
|
f.name as faction_name, g.guild_name
|
||||||
pi.ip_address
|
|
||||||
FROM dune.actors a
|
FROM dune.actors a
|
||||||
JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id
|
JOIN dune.encrypted_accounts ea ON a.owner_account_id = ea.id
|
||||||
LEFT JOIN dune.accounts acc ON ea.id = acc.id
|
LEFT JOIN dune.accounts acc ON ea.id = acc.id
|
||||||
@@ -141,7 +141,6 @@ class PlayerService:
|
|||||||
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
||||||
LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id
|
LEFT JOIN dune.guild_members gm ON ps.player_controller_id = gm.player_id
|
||||||
LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id
|
LEFT JOIN dune.guilds g ON gm.guild_id = g.guild_id
|
||||||
LEFT JOIN dashboard.player_ips pi ON ps.player_controller_id = pi.player_id
|
|
||||||
WHERE {where_clause}
|
WHERE {where_clause}
|
||||||
ORDER BY player_name
|
ORDER BY player_name
|
||||||
LIMIT %s OFFSET %s
|
LIMIT %s OFFSET %s
|
||||||
@@ -151,6 +150,22 @@ class PlayerService:
|
|||||||
return []
|
return []
|
||||||
|
|
||||||
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
||||||
|
|
||||||
|
# Fetch IPs from the dashboard database separately and merge
|
||||||
|
ip_map = {}
|
||||||
|
if self.dash_db and player_ids:
|
||||||
|
placeholders = ','.join(['%s'] * len(player_ids))
|
||||||
|
ip_rows = self.dash_db.query(
|
||||||
|
f"SELECT player_id, ip_address FROM player_ips WHERE player_id IN ({placeholders})",
|
||||||
|
player_ids
|
||||||
|
) or []
|
||||||
|
ip_map = {r['player_id']: r['ip_address'] for r in ip_rows if r.get('player_id')}
|
||||||
|
for p in players:
|
||||||
|
pid = p.get('player_controller_id')
|
||||||
|
if pid and pid in ip_map:
|
||||||
|
p['ip_address'] = ip_map[pid]
|
||||||
|
else:
|
||||||
|
p['ip_address'] = None
|
||||||
actor_ids = [p.get('id') for p in players if p.get('id')]
|
actor_ids = [p.get('id') for p in players if p.get('id')]
|
||||||
|
|
||||||
vehicle_counts = {}
|
vehicle_counts = {}
|
||||||
@@ -254,9 +269,24 @@ class PlayerService:
|
|||||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
||||||
FROM dune.buildings b
|
FROM dune.buildings b
|
||||||
JOIN dune.actors a ON b.id = a.id
|
JOIN dune.actors a ON b.id = a.id
|
||||||
WHERE b.owner_id = %s
|
JOIN LATERAL (
|
||||||
|
SELECT DISTINCT afe_totem.actor_id as totem_actor_id
|
||||||
|
FROM dune.building_instances bi
|
||||||
|
JOIN dune.actor_fgl_entities afe_totem ON afe_totem.entity_id = bi.owner_entity_id
|
||||||
|
WHERE bi.building_id = b.id
|
||||||
|
LIMIT 1
|
||||||
|
) totem ON true
|
||||||
|
JOIN LATERAL (
|
||||||
|
SELECT pawn.id as pawn_id
|
||||||
|
FROM dune.actors pawn
|
||||||
|
WHERE pawn.id BETWEEN totem.totem_actor_id - 6 AND totem.totem_actor_id - 1
|
||||||
|
AND pawn.class LIKE %s
|
||||||
|
ORDER BY totem.totem_actor_id - pawn.id
|
||||||
|
LIMIT 1
|
||||||
|
) owner ON true
|
||||||
|
WHERE owner.pawn_id = %s
|
||||||
ORDER BY a.map
|
ORDER BY a.map
|
||||||
""", [player_id]) or []
|
""", [LIKE_PC, player_id]) or []
|
||||||
except Exception:
|
except Exception:
|
||||||
return []
|
return []
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,210 @@
|
|||||||
|
"""RMQ service - RabbitMQ Management HTTP API client."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import logging
|
||||||
|
import base64
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
from typing import Any, Dict, List, Optional
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
class RmqService:
|
||||||
|
"""RabbitMQ Management HTTP API client.
|
||||||
|
|
||||||
|
Communicates with RMQ Admin (port 30325) and RMQ Game (port 32716)
|
||||||
|
HTTP API endpoints via SSH tunnel (localhost).
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, admin_port: int = 30325, game_port: int = 32716,
|
||||||
|
username: str = 'dashboard_admin', password: str = ''):
|
||||||
|
self.admin_port = admin_port
|
||||||
|
self.game_port = game_port
|
||||||
|
self.username = username
|
||||||
|
self.password = password
|
||||||
|
self._auth = base64.b64encode(
|
||||||
|
f"{username}:{password}".encode()).decode()
|
||||||
|
logger.info("RmqService initialized: admin=localhost:%s game=localhost:%s",
|
||||||
|
admin_port, game_port)
|
||||||
|
|
||||||
|
def _request(self, port: int, path: str, method: str = 'GET',
|
||||||
|
body: Any = None, timeout: int = 15) -> Optional[Any]:
|
||||||
|
"""Execute an HTTP request against an RMQ API.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
port: Tunnel port (30325 for admin, 32716 for game).
|
||||||
|
path: API path (e.g., '/api/overview').
|
||||||
|
method: HTTP method.
|
||||||
|
body: Optional JSON-serializable request body.
|
||||||
|
timeout: Request timeout in seconds.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
Parsed JSON response, or None on failure.
|
||||||
|
"""
|
||||||
|
url = f"http://127.0.0.1:{port}{path}"
|
||||||
|
headers = {
|
||||||
|
'Authorization': f'Basic {self._auth}',
|
||||||
|
}
|
||||||
|
if body is not None:
|
||||||
|
headers['Content-Type'] = 'application/json'
|
||||||
|
data = json.dumps(body).encode()
|
||||||
|
else:
|
||||||
|
data = None
|
||||||
|
|
||||||
|
req = urllib.request.Request(url, data=data, headers=headers)
|
||||||
|
|
||||||
|
if method != 'GET' and method != 'POST':
|
||||||
|
req.method = method
|
||||||
|
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||||
|
raw = resp.read().decode()
|
||||||
|
return json.loads(raw) if raw.strip() else {}
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
logger.warning("RMQ HTTP %s %s -> %s: %s", method, url, e.code,
|
||||||
|
e.read().decode()[:200] if e.fp else '')
|
||||||
|
return None
|
||||||
|
except Exception as e:
|
||||||
|
logger.warning("RMQ request error %s %s: %s", method, url, e)
|
||||||
|
return None
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _encode_vhost(vhost: str = '/') -> str:
|
||||||
|
return vhost.replace('/', '%2F')
|
||||||
|
|
||||||
|
# ── Admin API (port 30325) ───────────────────────────────────────
|
||||||
|
|
||||||
|
def overview(self) -> Optional[Dict]:
|
||||||
|
"""Cluster overview: node info, message stats, queue totals."""
|
||||||
|
return self._request(self.admin_port, '/api/overview')
|
||||||
|
|
||||||
|
def nodes(self) -> Optional[List]:
|
||||||
|
"""List nodes with memory and disk info."""
|
||||||
|
return self._request(self.admin_port, '/api/nodes')
|
||||||
|
|
||||||
|
def exchanges(self) -> Optional[List]:
|
||||||
|
"""List all exchanges with message stats."""
|
||||||
|
return self._request(self.admin_port, '/api/exchanges')
|
||||||
|
|
||||||
|
def queues(self) -> Optional[List]:
|
||||||
|
"""List all queues with consumer counts and message depths."""
|
||||||
|
return self._request(self.admin_port, '/api/queues')
|
||||||
|
|
||||||
|
def bindings(self) -> Optional[List]:
|
||||||
|
"""List all bindings (source -> destination mappings)."""
|
||||||
|
return self._request(self.admin_port, '/api/bindings')
|
||||||
|
|
||||||
|
def consumers(self) -> Optional[List]:
|
||||||
|
"""List active consumers."""
|
||||||
|
return self._request(self.admin_port, '/api/consumers')
|
||||||
|
|
||||||
|
def connections(self) -> Optional[List]:
|
||||||
|
"""List active AMQP connections."""
|
||||||
|
return self._request(self.admin_port, '/api/connections')
|
||||||
|
|
||||||
|
def channels(self) -> Optional[List]:
|
||||||
|
"""List active channels."""
|
||||||
|
return self._request(self.admin_port, '/api/channels')
|
||||||
|
|
||||||
|
def health(self) -> Optional[Dict]:
|
||||||
|
"""Cluster health and alarm status."""
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
'/api/health/checks/alarms')
|
||||||
|
|
||||||
|
def peek_messages(self, queue_name: str, vhost: str = '/',
|
||||||
|
count: int = 5) -> Optional[List]:
|
||||||
|
"""Peek at messages in a queue without consuming them."""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'count': count,
|
||||||
|
'ackmode': 'ack_requeue_true',
|
||||||
|
'encoding': 'auto',
|
||||||
|
}
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/queues/{vh}/{queue_name}/get',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
def publish(self, exchange: str, routing_key: str, message: Any,
|
||||||
|
vhost: str = '/') -> Optional[Dict]:
|
||||||
|
"""Publish a message to an exchange.
|
||||||
|
|
||||||
|
NOTE: RMQ HTTP API sets user_id to the authenticated username,
|
||||||
|
which the game server may reject. For ServerCommands on the
|
||||||
|
game RPC exchange, use the Erlang eval approach instead.
|
||||||
|
"""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'properties': {},
|
||||||
|
'routing_key': routing_key,
|
||||||
|
'payload': json.dumps(message) if not isinstance(message, str)
|
||||||
|
else message,
|
||||||
|
'payload_encoding': 'string',
|
||||||
|
}
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/publish',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
def get_queue_bindings(self, queue_name: str,
|
||||||
|
vhost: str = '/') -> Optional[List]:
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/queues/{vh}/{queue_name}/bindings')
|
||||||
|
|
||||||
|
def get_exchange_bindings(self, exchange: str,
|
||||||
|
vhost: str = '/') -> Optional[List]:
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
return self._request(self.admin_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/bindings/source')
|
||||||
|
|
||||||
|
# ── Game API (port 32716) ────────────────────────────────────────
|
||||||
|
|
||||||
|
def game_overview(self) -> Optional[Dict]:
|
||||||
|
"""Game RMQ cluster overview."""
|
||||||
|
return self._request(self.game_port, '/api/overview')
|
||||||
|
|
||||||
|
def game_queues(self) -> Optional[List]:
|
||||||
|
"""Game RMQ queues."""
|
||||||
|
return self._request(self.game_port, '/api/queues')
|
||||||
|
|
||||||
|
def game_exchanges(self) -> Optional[List]:
|
||||||
|
"""Game RMQ exchanges."""
|
||||||
|
return self._request(self.game_port, '/api/exchanges')
|
||||||
|
|
||||||
|
def game_publish(self, exchange: str, routing_key: str,
|
||||||
|
message: Any, vhost: str = '/') -> Optional[Dict]:
|
||||||
|
"""Publish a message to the game RMQ."""
|
||||||
|
vh = self._encode_vhost(vhost)
|
||||||
|
body = {
|
||||||
|
'properties': {},
|
||||||
|
'routing_key': routing_key,
|
||||||
|
'payload': json.dumps(message) if not isinstance(message, str)
|
||||||
|
else message,
|
||||||
|
'payload_encoding': 'string',
|
||||||
|
}
|
||||||
|
return self._request(self.game_port,
|
||||||
|
f'/api/exchanges/{vh}/{exchange}/publish',
|
||||||
|
method='POST', body=body)
|
||||||
|
|
||||||
|
# ── Combined / convenience ───────────────────────────────────────
|
||||||
|
|
||||||
|
def combined_overview(self) -> Dict[str, Any]:
|
||||||
|
"""Get overview from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.overview(),
|
||||||
|
'game': self.game_overview(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def combined_queues(self) -> Dict[str, Any]:
|
||||||
|
"""Get queues from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.queues(),
|
||||||
|
'game': self.game_queues(),
|
||||||
|
}
|
||||||
|
|
||||||
|
def combined_exchanges(self) -> Dict[str, Any]:
|
||||||
|
"""Get exchanges from both RMQ instances."""
|
||||||
|
return {
|
||||||
|
'admin': self.exchanges(),
|
||||||
|
'game': self.game_exchanges(),
|
||||||
|
}
|
||||||
@@ -81,5 +81,5 @@ NAV_PAGES = [
|
|||||||
('/guilds', 'Guilds'),
|
('/guilds', 'Guilds'),
|
||||||
('/buildings', 'Buildings'),
|
('/buildings', 'Buildings'),
|
||||||
('/map', 'Map'),
|
('/map', 'Map'),
|
||||||
('/admin-experimental', 'Admin Experimental'),
|
('/admin-experimental', 'Experimental'),
|
||||||
]
|
]
|
||||||
+6
-1
@@ -108,7 +108,12 @@ def generate_cert(cert_path, key_path, ca_cert_path=None, ca_key_path=None,
|
|||||||
])
|
])
|
||||||
|
|
||||||
# Build SAN entries
|
# Build SAN entries
|
||||||
san_entries = [x509.DNSName(common_name)]
|
san_entries = []
|
||||||
|
# Add common_name as the appropriate SAN type
|
||||||
|
try:
|
||||||
|
san_entries.append(x509.IPAddress(ipaddress.ip_address(common_name)))
|
||||||
|
except ValueError:
|
||||||
|
san_entries.append(x509.DNSName(common_name))
|
||||||
if san_ips:
|
if san_ips:
|
||||||
for ip in san_ips:
|
for ip in san_ips:
|
||||||
try:
|
try:
|
||||||
|
|||||||
@@ -1 +0,0 @@
|
|||||||
# Backend package init.
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
"""Settings loader — reads settings.yaml with env var overrides."""
|
|
||||||
|
|
||||||
import os
|
|
||||||
import socket
|
|
||||||
import yaml
|
|
||||||
import logging
|
|
||||||
import copy
|
|
||||||
import secrets
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
DEFAULTS = {
|
|
||||||
"server": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"user": "dune",
|
|
||||||
"ssh_key": None,
|
|
||||||
"local_ip": None,
|
|
||||||
},
|
|
||||||
"dashboard": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 5050,
|
|
||||||
"debug": False,
|
|
||||||
"secret_key": None,
|
|
||||||
"ssl_cert": None,
|
|
||||||
"ssl_key": None,
|
|
||||||
"ssl_domain": None,
|
|
||||||
"ssl_email": None,
|
|
||||||
"http_redirect": False,
|
|
||||||
"http_redirect_port": 80,
|
|
||||||
},
|
|
||||||
"database": {
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
"port": 15433,
|
|
||||||
"user": "postgres",
|
|
||||||
"password": None,
|
|
||||||
"name": "dune",
|
|
||||||
"schema": "dune",
|
|
||||||
"min_connections": 2,
|
|
||||||
"max_connections": 10,
|
|
||||||
"owner": "dune",
|
|
||||||
"dashboard_schema": "dashboard",
|
|
||||||
},
|
|
||||||
"kubernetes": {
|
|
||||||
"namespace": "",
|
|
||||||
"battlegroup_script": "/home/dune/.dune/bin/battlegroup",
|
|
||||||
},
|
|
||||||
"director": {
|
|
||||||
"port": 32479,
|
|
||||||
"host": "127.0.0.1",
|
|
||||||
},
|
|
||||||
"rmq": {
|
|
||||||
"admin_host": "127.0.0.1",
|
|
||||||
"admin_port": 32686,
|
|
||||||
"game_host": "127.0.0.1",
|
|
||||||
"game_port": 32021,
|
|
||||||
"username": "admin",
|
|
||||||
"password": None,
|
|
||||||
"vhost": "%2f",
|
|
||||||
},
|
|
||||||
"filebrowser": {
|
|
||||||
"port": 18888,
|
|
||||||
},
|
|
||||||
"firewall": {
|
|
||||||
"block_filebrowser": True,
|
|
||||||
"block_director": True,
|
|
||||||
},
|
|
||||||
"cache": {
|
|
||||||
"chat_pod_ttl": 60,
|
|
||||||
"chat_messages_ttl": 10,
|
|
||||||
"static_data_ttl": 300,
|
|
||||||
"bgd_ttl": 10,
|
|
||||||
"rmq_ttl": 15,
|
|
||||||
},
|
|
||||||
"auth": {
|
|
||||||
"enabled": True,
|
|
||||||
"username": None,
|
|
||||||
"password_hash": None,
|
|
||||||
"shell_enabled": True,
|
|
||||||
},
|
|
||||||
"logging": {
|
|
||||||
"level": "INFO",
|
|
||||||
"file": "logs/dashboard.log",
|
|
||||||
"debug_file": "logs/debug.log",
|
|
||||||
"debug_enabled": False,
|
|
||||||
"max_bytes": 10485760,
|
|
||||||
"backup_count": 5,
|
|
||||||
},
|
|
||||||
"ssl": {
|
|
||||||
"check_interval_hours": 24,
|
|
||||||
"renewal_days_before_expiry": 30,
|
|
||||||
},
|
|
||||||
"maps": {
|
|
||||||
"default_map": "HaggaBasin",
|
|
||||||
"DeepDesert": {
|
|
||||||
"image": "maps/Deep_Desert.webp",
|
|
||||||
"label": "The Deep Desert",
|
|
||||||
"bounds": {
|
|
||||||
"min_x": -1268624.82,
|
|
||||||
"max_x": 1163312.83,
|
|
||||||
"min_y": -1266548.17,
|
|
||||||
"max_y": 1162416.13,
|
|
||||||
},
|
|
||||||
"flip_y": False,
|
|
||||||
"image_size": {"width": 8000, "height": 8000},
|
|
||||||
"default_zoom": 0.15,
|
|
||||||
},
|
|
||||||
"HaggaBasin": {
|
|
||||||
"image": "maps/HaggaBasin_8k.webp",
|
|
||||||
"label": "Hagga Basin",
|
|
||||||
"bounds": {
|
|
||||||
"min_x": -456752.21,
|
|
||||||
"max_x": 354547.46,
|
|
||||||
"min_y": -450630.14,
|
|
||||||
"max_y": 353821.95,
|
|
||||||
},
|
|
||||||
"flip_y": False,
|
|
||||||
"image_size": {"width": 8000, "height": 8000},
|
|
||||||
"default_zoom": 0.15,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def deep_merge(base, override):
|
|
||||||
"""Deep merge override dict into base dict."""
|
|
||||||
result = base.copy()
|
|
||||||
for key, value in override.items():
|
|
||||||
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
|
|
||||||
result[key] = deep_merge(result[key], value)
|
|
||||||
else:
|
|
||||||
result[key] = value
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _detect_local_ip():
|
|
||||||
"""Detect local IP address for VM connectivity."""
|
|
||||||
try:
|
|
||||||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
|
||||||
s.settimeout(1)
|
|
||||||
s.connect(("8.8.8.8", 80))
|
|
||||||
local_ip = s.getsockname()[0]
|
|
||||||
s.close()
|
|
||||||
if local_ip:
|
|
||||||
logger.debug(f"Detected local IP: {local_ip}")
|
|
||||||
return local_ip
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug(f"Could not detect local IP: {e}")
|
|
||||||
return "127.0.0.1"
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_server_host(settings):
|
|
||||||
"""Validate and fix server.host if invalid or placeholder."""
|
|
||||||
server = settings.setdefault("server", {})
|
|
||||||
host = server.get("host", "")
|
|
||||||
|
|
||||||
local_ip = server.get("local_ip")
|
|
||||||
if local_ip:
|
|
||||||
local_ip_str = str(local_ip).strip()
|
|
||||||
if local_ip_str and local_ip_str not in ("", "null", "None", "YOUR_SERVER_IP", "YOUR_VM_IP"):
|
|
||||||
if local_ip_str.count(".") == 3 and all(part.isdigit() and 0 <= int(part) <= 255 for part in local_ip_str.split(".")):
|
|
||||||
server["host"] = local_ip_str
|
|
||||||
logger.info(f"Using server.local_ip override: {server['host']}")
|
|
||||||
return settings
|
|
||||||
|
|
||||||
host_str = str(host).strip() if host else ""
|
|
||||||
invalid_hosts = ("", "YOUR_SERVER_IP", "YOUR_VM_IP", "null", "None")
|
|
||||||
|
|
||||||
if host_str in invalid_hosts or not host_str:
|
|
||||||
detected_ip = _detect_local_ip()
|
|
||||||
server["host"] = detected_ip
|
|
||||||
logger.warning(f"Invalid server.host detected, using auto-detected IP: {detected_ip}")
|
|
||||||
logger.warning("To fix: Edit settings.yaml and set server.host to your VM's IP address")
|
|
||||||
|
|
||||||
return settings
|
|
||||||
|
|
||||||
|
|
||||||
def _find_missing_keys(defaults, current, path=""):
|
|
||||||
"""Find keys present in defaults but missing in current."""
|
|
||||||
missing = []
|
|
||||||
for key, val in defaults.items():
|
|
||||||
new_path = f"{path}.{key}" if path else key
|
|
||||||
if key not in current:
|
|
||||||
missing.append(new_path)
|
|
||||||
elif isinstance(val, dict) and isinstance(current.get(key), dict):
|
|
||||||
missing.extend(_find_missing_keys(val, current[key], new_path))
|
|
||||||
return missing
|
|
||||||
|
|
||||||
|
|
||||||
def load_settings(settings_path=None):
|
|
||||||
"""Load settings from YAML file with defaults and env var overrides."""
|
|
||||||
if settings_path is None:
|
|
||||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
|
|
||||||
|
|
||||||
settings = copy.deepcopy(DEFAULTS)
|
|
||||||
|
|
||||||
if os.path.exists(settings_path):
|
|
||||||
try:
|
|
||||||
with open(settings_path, "r") as f:
|
|
||||||
file_settings = yaml.safe_load(f) or {}
|
|
||||||
settings = deep_merge(settings, file_settings)
|
|
||||||
logger.info(f"Settings loaded from {settings_path}")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to load settings from {settings_path}: {e}")
|
|
||||||
logger.warning("Using default settings")
|
|
||||||
else:
|
|
||||||
logger.warning(f"Settings file not found at {settings_path}, using defaults")
|
|
||||||
|
|
||||||
env_overrides = {}
|
|
||||||
|
|
||||||
if os.environ.get("DUNE_SERVER_HOST"):
|
|
||||||
env_overrides.setdefault("server", {})["host"] = os.environ["DUNE_SERVER_HOST"]
|
|
||||||
if os.environ.get("DUNE_SERVER_USER"):
|
|
||||||
env_overrides.setdefault("server", {})["user"] = os.environ["DUNE_SERVER_USER"]
|
|
||||||
if os.environ.get("DUNE_DB_PASSWORD"):
|
|
||||||
env_overrides.setdefault("database", {})["password"] = os.environ["DUNE_DB_PASSWORD"]
|
|
||||||
if os.environ.get("DUNE_K8S_NAMESPACE"):
|
|
||||||
env_overrides.setdefault("kubernetes", {})["namespace"] = os.environ["DUNE_K8S_NAMESPACE"]
|
|
||||||
if os.environ.get("DUNE_AUTH_PASSWORD"):
|
|
||||||
env_overrides.setdefault("auth", {})["password"] = os.environ["DUNE_AUTH_PASSWORD"]
|
|
||||||
if os.environ.get("DUNE_DASHBOARD_PORT"):
|
|
||||||
env_overrides.setdefault("dashboard", {})["port"] = int(os.environ["DUNE_DASHBOARD_PORT"])
|
|
||||||
if os.environ.get("DUNE_RMQ_PASSWORD"):
|
|
||||||
env_overrides.setdefault("rmq", {})["password"] = os.environ["DUNE_RMQ_PASSWORD"]
|
|
||||||
|
|
||||||
if env_overrides:
|
|
||||||
settings = deep_merge(settings, env_overrides)
|
|
||||||
logger.info("Environment variable overrides applied")
|
|
||||||
|
|
||||||
if not settings["dashboard"].get("secret_key"):
|
|
||||||
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
|
|
||||||
logger.info("Generated secure SECRET_KEY")
|
|
||||||
|
|
||||||
auth = settings.get("auth", {})
|
|
||||||
password_migrated = False
|
|
||||||
if auth.get("password") and not auth.get("password_hash"):
|
|
||||||
try:
|
|
||||||
from argon2 import PasswordHasher
|
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
|
||||||
settings["auth"]["password_hash"] = ph.hash(str(auth["password"]))
|
|
||||||
del settings["auth"]["password"]
|
|
||||||
password_migrated = True
|
|
||||||
logger.info("Migrated plaintext password to Argon2 hash")
|
|
||||||
except ImportError:
|
|
||||||
logger.error("argon2-cffi not installed. Password hashing unavailable.")
|
|
||||||
settings["auth"]["password_hash"] = None
|
|
||||||
|
|
||||||
if password_migrated:
|
|
||||||
settings["dashboard"]["secret_key"] = secrets.token_hex(32)
|
|
||||||
logger.warning("Rotated secret_key to invalidate sessions after password migration")
|
|
||||||
|
|
||||||
settings = _validate_server_host(settings)
|
|
||||||
|
|
||||||
return settings
|
|
||||||
|
|
||||||
|
|
||||||
_settings_cache = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_settings():
|
|
||||||
"""Get current settings (cached for performance)."""
|
|
||||||
global _settings_cache
|
|
||||||
if _settings_cache is None:
|
|
||||||
_settings_cache = load_settings()
|
|
||||||
return _settings_cache
|
|
||||||
|
|
||||||
|
|
||||||
def save_settings(settings):
|
|
||||||
"""Save settings to YAML file."""
|
|
||||||
global _settings_cache
|
|
||||||
settings_path = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "settings.yaml")
|
|
||||||
try:
|
|
||||||
with open(settings_path, "w") as f:
|
|
||||||
yaml.safe_dump(settings, f, default_flow_style=False, sort_keys=False)
|
|
||||||
_settings_cache = settings
|
|
||||||
logger.info(f"Settings saved to {settings_path}")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to save settings to {settings_path}: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def reload_settings():
|
|
||||||
"""Force reload settings from file."""
|
|
||||||
global _settings_cache
|
|
||||||
_settings_cache = load_settings()
|
|
||||||
return _settings_cache
|
|
||||||
@@ -1,313 +0,0 @@
|
|||||||
# Application factory — creates and configures the Flask app.
|
|
||||||
|
|
||||||
import os
|
|
||||||
import sys
|
|
||||||
import logging
|
|
||||||
import logging.handlers
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from flask import Flask, jsonify, request, g, send_from_directory
|
|
||||||
from flask_cors import CORS
|
|
||||||
from flask_login import current_user
|
|
||||||
from flask_socketio import SocketIO
|
|
||||||
from flask_limiter import Limiter
|
|
||||||
from flask_limiter.util import get_remote_address
|
|
||||||
|
|
||||||
from app.config import load_settings
|
|
||||||
from app.routes.auth import auth_bp, init_auth
|
|
||||||
from app.routes.health import health_bp
|
|
||||||
from app.routes.api import api_bp
|
|
||||||
from app.routes.director import director_bp
|
|
||||||
from app.routes.server import server_bp
|
|
||||||
from app.routes.files import files_bp
|
|
||||||
from app.routes.debug import debug_bp
|
|
||||||
from app.routes.chat import chat_bp
|
|
||||||
from app.websocket.shell import register_websocket_handlers
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
from app.services.ssh import SSHService
|
|
||||||
from app.services.k8s import K8sService
|
|
||||||
from app.services.bg_director import BgDirectorService
|
|
||||||
from app.services.rmq_admin import RmqAdminService
|
|
||||||
from app.services.rmq_game import RmqGameService
|
|
||||||
from app.services.realtime import RealtimeService
|
|
||||||
from app.services.player import PlayerService
|
|
||||||
from app.services.economy import EconomyService
|
|
||||||
from app.services.guild import GuildService
|
|
||||||
from app.services.world import WorldService
|
|
||||||
from app.services.progression import ProgressionService
|
|
||||||
from app.services.character import CharacterService
|
|
||||||
from app.services.audit import AuditService
|
|
||||||
from app.services.chat import ChatService
|
|
||||||
|
|
||||||
_services = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_services():
|
|
||||||
global _services
|
|
||||||
return _services
|
|
||||||
|
|
||||||
|
|
||||||
def create_app(settings_path=None):
|
|
||||||
global _services
|
|
||||||
|
|
||||||
settings = load_settings(settings_path)
|
|
||||||
base_dir = os.path.dirname(os.path.dirname(__file__))
|
|
||||||
|
|
||||||
app = Flask(
|
|
||||||
__name__,
|
|
||||||
template_folder=os.path.join(base_dir, "frontend", "dist"),
|
|
||||||
static_folder=os.path.join(base_dir, "frontend", "dist", "assets"),
|
|
||||||
static_url_path="/assets",
|
|
||||||
)
|
|
||||||
app.config["SECRET_KEY"] = settings["dashboard"]["secret_key"]
|
|
||||||
app.config["SESSION_COOKIE_HTTPONLY"] = True
|
|
||||||
app.config["SESSION_COOKIE_SAMESITE"] = "Lax"
|
|
||||||
app.config["WTF_CSRF_ENABLED"] = True
|
|
||||||
app.config["WTF_CSRF_TIME_LIMIT"] = None
|
|
||||||
|
|
||||||
CORS(app, resources={r"/api/*": {"origins": "*"}})
|
|
||||||
|
|
||||||
ssl_enabled = bool(
|
|
||||||
settings["dashboard"].get("ssl_cert")
|
|
||||||
and settings["dashboard"].get("ssl_key")
|
|
||||||
and settings["dashboard"]["ssl_cert"] != "null"
|
|
||||||
and settings["dashboard"]["ssl_key"] != "null"
|
|
||||||
)
|
|
||||||
app.config["SESSION_COOKIE_SECURE"] = ssl_enabled
|
|
||||||
|
|
||||||
if not settings["dashboard"]["debug"]:
|
|
||||||
@app.after_request
|
|
||||||
def add_security_headers(response):
|
|
||||||
if ssl_enabled:
|
|
||||||
response.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
|
|
||||||
response.headers["X-Frame-Options"] = "SAMEORIGIN"
|
|
||||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
|
||||||
response.headers["X-XSS-Protection"] = "1; mode=block"
|
|
||||||
response.headers["Content-Security-Policy"] = (
|
|
||||||
"default-src 'self'; "
|
|
||||||
"script-src 'self' 'unsafe-inline'; "
|
|
||||||
"style-src 'self' 'unsafe-inline'; "
|
|
||||||
"img-src 'self' data:; "
|
|
||||||
"connect-src 'self' ws: wss:; "
|
|
||||||
"frame-ancestors 'self'; "
|
|
||||||
"base-uri 'self'; "
|
|
||||||
"form-action 'self'"
|
|
||||||
)
|
|
||||||
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
|
|
||||||
return response
|
|
||||||
|
|
||||||
# Error handlers
|
|
||||||
@app.errorhandler(Exception)
|
|
||||||
def handle_exception(e):
|
|
||||||
logging.exception("Unhandled exception: %s", e)
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
if settings["dashboard"].get("debug", False):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InternalError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InternalError", message="An internal error occurred"),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
@app.errorhandler(404)
|
|
||||||
def handle_not_found(e):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Resource not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
|
|
||||||
@app.errorhandler(405)
|
|
||||||
def handle_method_not_allowed(e):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="MethodNotAllowed", message="Method not allowed"),
|
|
||||||
).model_dump()), 405
|
|
||||||
|
|
||||||
# Request logging
|
|
||||||
@app.before_request
|
|
||||||
def before_request_logging():
|
|
||||||
import time as _time
|
|
||||||
g._request_start_time = _time.time()
|
|
||||||
|
|
||||||
@app.after_request
|
|
||||||
def after_request_logging(response):
|
|
||||||
import time as _time
|
|
||||||
duration = _time.time() - g.get("_request_start_time", _time.time())
|
|
||||||
user = current_user.id if current_user.is_authenticated else "anonymous"
|
|
||||||
if request.path.startswith("/api") or request.path.startswith("/server"):
|
|
||||||
logging.info("%s %s %d %.3fs user=%s", request.method, request.path, response.status_code, duration, user)
|
|
||||||
response.headers["X-Response-Time"] = f"{duration:.3f}s"
|
|
||||||
return response
|
|
||||||
|
|
||||||
_setup_logging(settings)
|
|
||||||
|
|
||||||
# ── Services ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
db_config = {
|
|
||||||
"host": settings["database"]["host"],
|
|
||||||
"port": settings["database"]["port"],
|
|
||||||
"user": settings["database"]["user"],
|
|
||||||
"password": settings["database"]["password"],
|
|
||||||
"database": settings["database"]["name"],
|
|
||||||
}
|
|
||||||
|
|
||||||
db_service = DatabaseService(
|
|
||||||
db_config,
|
|
||||||
min_conn=settings["database"]["min_connections"],
|
|
||||||
max_conn=settings["database"]["max_connections"],
|
|
||||||
dashboard_schema=settings["database"].get("dashboard_schema", "dashboard"),
|
|
||||||
)
|
|
||||||
db_service.ensure_tables()
|
|
||||||
|
|
||||||
ssh_service = SSHService(
|
|
||||||
host=settings["server"]["host"],
|
|
||||||
user=settings["server"]["user"],
|
|
||||||
ssh_key=settings["server"].get("ssh_key"),
|
|
||||||
)
|
|
||||||
|
|
||||||
k8s_service = K8sService(
|
|
||||||
ssh_service=ssh_service,
|
|
||||||
namespace=settings["kubernetes"]["namespace"],
|
|
||||||
)
|
|
||||||
|
|
||||||
bg_director = BgDirectorService(
|
|
||||||
host=settings["director"].get("host", "127.0.0.1"),
|
|
||||||
node_port=settings["director"].get("port", 32479),
|
|
||||||
)
|
|
||||||
|
|
||||||
rmq_admin = RmqAdminService(
|
|
||||||
host=settings["rmq"]["admin_host"],
|
|
||||||
port=settings["rmq"]["admin_port"],
|
|
||||||
username=settings["rmq"]["username"],
|
|
||||||
password=settings["rmq"]["password"],
|
|
||||||
)
|
|
||||||
|
|
||||||
rmq_game = RmqGameService(
|
|
||||||
host=settings["rmq"]["game_host"],
|
|
||||||
port=settings["rmq"]["game_port"],
|
|
||||||
username=settings["rmq"]["username"],
|
|
||||||
password=settings["rmq"]["password"],
|
|
||||||
)
|
|
||||||
|
|
||||||
player_svc = PlayerService(db_service)
|
|
||||||
economy_svc = EconomyService(db_service)
|
|
||||||
guild_svc = GuildService(db_service)
|
|
||||||
world_svc = WorldService(db_service)
|
|
||||||
progression_svc = ProgressionService(db_service)
|
|
||||||
character_svc = CharacterService(db_service)
|
|
||||||
audit_svc = AuditService(db_service)
|
|
||||||
chat_svc = ChatService(db_service, k8s_service, ssh_service)
|
|
||||||
|
|
||||||
realtime_svc = RealtimeService(bg_director, rmq_admin, chat_svc)
|
|
||||||
realtime_svc.start()
|
|
||||||
|
|
||||||
_services = {
|
|
||||||
"db": db_service,
|
|
||||||
"ssh": ssh_service,
|
|
||||||
"k8s": k8s_service,
|
|
||||||
"bg_director": bg_director,
|
|
||||||
"rmq_admin": rmq_admin,
|
|
||||||
"rmq_game": rmq_game,
|
|
||||||
"realtime": realtime_svc,
|
|
||||||
"player": player_svc,
|
|
||||||
"economy": economy_svc,
|
|
||||||
"guild": guild_svc,
|
|
||||||
"world": world_svc,
|
|
||||||
"progression": progression_svc,
|
|
||||||
"character": character_svc,
|
|
||||||
"audit": audit_svc,
|
|
||||||
"chat": chat_svc,
|
|
||||||
}
|
|
||||||
|
|
||||||
app.dune_settings = settings
|
|
||||||
app.dune_services = _services
|
|
||||||
|
|
||||||
# ── Blueprints ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
init_auth(app, settings)
|
|
||||||
|
|
||||||
# Auto-login for development — bypasses authentication on all endpoints
|
|
||||||
from flask_login import login_user
|
|
||||||
from app.routes.auth import AdminUser
|
|
||||||
|
|
||||||
@app.before_request
|
|
||||||
def auto_login_dev():
|
|
||||||
if not current_user.is_authenticated:
|
|
||||||
cfg_user = str(settings.get("auth", {}).get("username", "admin"))
|
|
||||||
login_user(AdminUser(cfg_user))
|
|
||||||
|
|
||||||
app.register_blueprint(auth_bp, url_prefix="/api/auth")
|
|
||||||
app.register_blueprint(health_bp, url_prefix="/api")
|
|
||||||
app.register_blueprint(api_bp, url_prefix="/api")
|
|
||||||
app.register_blueprint(director_bp, url_prefix="/api/director")
|
|
||||||
app.register_blueprint(server_bp, url_prefix="/api/server")
|
|
||||||
app.register_blueprint(files_bp, url_prefix="/api/files")
|
|
||||||
app.register_blueprint(chat_bp, url_prefix="/api/chat")
|
|
||||||
app.register_blueprint(debug_bp, url_prefix="/api/debug")
|
|
||||||
|
|
||||||
# ── SocketIO ─────────────────────────────────────────────────
|
|
||||||
socketio = SocketIO(app, cors_allowed_origins="*", async_mode="threading")
|
|
||||||
register_websocket_handlers(socketio, settings)
|
|
||||||
app.socketio = socketio
|
|
||||||
|
|
||||||
# ── Rate Limiter ─────────────────────────────────────────────
|
|
||||||
limiter = Limiter(
|
|
||||||
app=app,
|
|
||||||
key_func=get_remote_address,
|
|
||||||
default_limits=[],
|
|
||||||
storage_uri="memory://",
|
|
||||||
)
|
|
||||||
app.limiter = limiter
|
|
||||||
|
|
||||||
# ── Catch-all for React SPA ─────────────────────────────────
|
|
||||||
@app.route("/", defaults={"path": ""})
|
|
||||||
@app.route("/<path:path>")
|
|
||||||
def serve_react(path):
|
|
||||||
if path.startswith("api/") or path.startswith("server/") or path.startswith("static/") or path.startswith("assets/"):
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Resource not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return send_from_directory(os.path.join(base_dir, "frontend", "dist"), "index.html")
|
|
||||||
|
|
||||||
# ── Auto-detect namespace if empty ───────────────────────────
|
|
||||||
if settings["kubernetes"]["namespace"] == "":
|
|
||||||
try:
|
|
||||||
k8s_service.auto_detect_namespace()
|
|
||||||
if k8s_service.namespace:
|
|
||||||
settings["kubernetes"]["namespace"] = k8s_service.namespace
|
|
||||||
except Exception as e:
|
|
||||||
logging.warning("Could not auto-detect K8s namespace: %s", e)
|
|
||||||
|
|
||||||
return app
|
|
||||||
|
|
||||||
|
|
||||||
def _setup_logging(settings):
|
|
||||||
log_level = getattr(logging, settings["logging"]["level"].upper(), logging.INFO)
|
|
||||||
log_file = settings["logging"]["file"]
|
|
||||||
os.makedirs(os.path.dirname(log_file), exist_ok=True)
|
|
||||||
|
|
||||||
handler = logging.handlers.RotatingFileHandler(
|
|
||||||
log_file,
|
|
||||||
maxBytes=settings["logging"]["max_bytes"],
|
|
||||||
backupCount=settings["logging"]["backup_count"],
|
|
||||||
)
|
|
||||||
handler.setFormatter(logging.Formatter(
|
|
||||||
"%(asctime)s - %(name)s - %(levelname)s - %(message)s"
|
|
||||||
))
|
|
||||||
handler.setLevel(log_level)
|
|
||||||
|
|
||||||
console = logging.StreamHandler(sys.stdout)
|
|
||||||
console.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
|
|
||||||
console.setLevel(log_level)
|
|
||||||
|
|
||||||
root = logging.getLogger()
|
|
||||||
root.setLevel(log_level)
|
|
||||||
root.addHandler(handler)
|
|
||||||
root.addHandler(console)
|
|
||||||
@@ -1,232 +0,0 @@
|
|||||||
# Pydantic models for the Dune Admin Dashboard API.
|
|
||||||
|
|
||||||
from pydantic import BaseModel, Field
|
|
||||||
from typing import Any, List, Optional
|
|
||||||
|
|
||||||
|
|
||||||
class ErrorDetail(BaseModel):
|
|
||||||
code: str
|
|
||||||
message: str
|
|
||||||
details: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class ApiResponse(BaseModel):
|
|
||||||
success: bool
|
|
||||||
data: Optional[Any] = None
|
|
||||||
error: Optional[ErrorDetail] = None
|
|
||||||
|
|
||||||
|
|
||||||
# ── Player Models ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
class Vitals(BaseModel):
|
|
||||||
current_health: Optional[float] = None
|
|
||||||
max_health: Optional[float] = None
|
|
||||||
current_hydration: Optional[float] = None
|
|
||||||
dehydration_penalty: Optional[float] = None
|
|
||||||
current_spice: Optional[float] = None
|
|
||||||
spice_addiction_level: Optional[float] = None
|
|
||||||
spice_tolerance: Optional[float] = None
|
|
||||||
|
|
||||||
|
|
||||||
class CurrencyBalance(BaseModel):
|
|
||||||
currency_id: int
|
|
||||||
currency_label: str
|
|
||||||
balance: float = 0.0
|
|
||||||
|
|
||||||
|
|
||||||
class Item(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
template_id: str = ""
|
|
||||||
stack_size: int = 1
|
|
||||||
quality_level: int = 0
|
|
||||||
is_new: bool = False
|
|
||||||
position_index: int = 0
|
|
||||||
stats: Optional[Any] = None
|
|
||||||
durability: Optional[float] = None
|
|
||||||
max_durability: Optional[float] = None
|
|
||||||
ammo: Optional[int] = None
|
|
||||||
|
|
||||||
|
|
||||||
class Inventory(BaseModel):
|
|
||||||
inventory_id: int
|
|
||||||
actor_id: Optional[int] = None
|
|
||||||
inventory_type: int = 0
|
|
||||||
inventory_type_label: str = ""
|
|
||||||
max_item_count: Optional[int] = None
|
|
||||||
max_item_volume: Optional[float] = None
|
|
||||||
items: List[Item] = []
|
|
||||||
|
|
||||||
|
|
||||||
class VehicleSummary(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
display_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class BuildingSummary(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
owner_name: str = ""
|
|
||||||
instance_count: int = 0
|
|
||||||
is_powered: bool = False
|
|
||||||
power_level: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class Landclaim(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
class_name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class SpecializationTrack(BaseModel):
|
|
||||||
track_type: str = ""
|
|
||||||
xp_amount: int = 0
|
|
||||||
level: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class Keystone(BaseModel):
|
|
||||||
id: int
|
|
||||||
name: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
class FactionReputation(BaseModel):
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
faction_name: str = ""
|
|
||||||
reputation_amount: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class LandsraadInfo(BaseModel):
|
|
||||||
daily_reward_charges: Optional[int] = None
|
|
||||||
last_viewed_term_id: Optional[int] = None
|
|
||||||
daily_reward_last_processed: Optional[Any] = None
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerSummary(BaseModel):
|
|
||||||
player_controller_id: Optional[int] = None
|
|
||||||
character_name: str = "Unknown"
|
|
||||||
account_email: Optional[str] = None
|
|
||||||
funcom_id: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
map: Optional[str] = None
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
life_state: Optional[str] = None
|
|
||||||
last_login_time: Optional[str] = None
|
|
||||||
last_avatar_activity: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerDetail(BaseModel):
|
|
||||||
id: Optional[int] = None
|
|
||||||
account_id: int
|
|
||||||
player_controller_id: Optional[int] = None
|
|
||||||
player_pawn_id: Optional[int] = None
|
|
||||||
character_name: str = "Unknown"
|
|
||||||
account_email: Optional[str] = None
|
|
||||||
funcom_id: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
map: Optional[str] = None
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
life_state: Optional[str] = None
|
|
||||||
last_login_time: Optional[str] = None
|
|
||||||
last_avatar_activity: Optional[str] = None
|
|
||||||
vitals: Optional[Vitals] = None
|
|
||||||
currency: List[CurrencyBalance] = []
|
|
||||||
inventories: List[Inventory] = []
|
|
||||||
vehicles: List[VehicleSummary] = []
|
|
||||||
buildings: List[BuildingSummary] = []
|
|
||||||
landclaims: List[Landclaim] = []
|
|
||||||
specialization: List[SpecializationTrack] = []
|
|
||||||
keystones: List[Keystone] = []
|
|
||||||
faction_reputation: List[FactionReputation] = []
|
|
||||||
landsraad: Optional[LandsraadInfo] = None
|
|
||||||
tags: List[str] = []
|
|
||||||
is_online: bool = False
|
|
||||||
|
|
||||||
|
|
||||||
# ── Guild Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class GuildMember(BaseModel):
|
|
||||||
player_id: int
|
|
||||||
role_id: int = 50
|
|
||||||
role_name: str = "Member"
|
|
||||||
player_name: str = "Unknown"
|
|
||||||
online_status: str = "Unknown"
|
|
||||||
|
|
||||||
|
|
||||||
class GuildSummary(BaseModel):
|
|
||||||
guild_id: int
|
|
||||||
guild_name: str = ""
|
|
||||||
guild_description: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
member_count: int = 0
|
|
||||||
online_count: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
class GuildDetail(BaseModel):
|
|
||||||
guild_id: int
|
|
||||||
guild_name: str = ""
|
|
||||||
guild_description: Optional[str] = None
|
|
||||||
faction_name: Optional[str] = None
|
|
||||||
faction_id: Optional[int] = None
|
|
||||||
members: List[GuildMember] = []
|
|
||||||
|
|
||||||
|
|
||||||
# ── World Models ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
class PartitionInfo(BaseModel):
|
|
||||||
partition_id: int
|
|
||||||
name: str = ""
|
|
||||||
map: Optional[str] = None
|
|
||||||
player_count: int = 0
|
|
||||||
status: str = "unknown"
|
|
||||||
|
|
||||||
|
|
||||||
# ── RMQ Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class RmqQueueInfo(BaseModel):
|
|
||||||
name: str
|
|
||||||
messages: int = 0
|
|
||||||
consumers: int = 0
|
|
||||||
state: str = ""
|
|
||||||
|
|
||||||
|
|
||||||
class RmqOverview(BaseModel):
|
|
||||||
queues: List[RmqQueueInfo] = []
|
|
||||||
total_messages: int = 0
|
|
||||||
total_consumers: int = 0
|
|
||||||
|
|
||||||
|
|
||||||
# ── BGD Models ────────────────────────────────────────────────
|
|
||||||
|
|
||||||
class BattlegroupState(BaseModel):
|
|
||||||
battlegroup_id: Optional[int] = None
|
|
||||||
name: Optional[str] = None
|
|
||||||
status: Optional[str] = None
|
|
||||||
player_count: Optional[int] = None
|
|
||||||
servers: Optional[List[Any]] = None
|
|
||||||
|
|
||||||
|
|
||||||
# ── Request Models ─────────────────────────────────────────────
|
|
||||||
|
|
||||||
class BroadcastRequest(BaseModel):
|
|
||||||
message: str = Field(..., min_length=1, max_length=500)
|
|
||||||
server: Optional[str] = None
|
|
||||||
partition: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
class TeleportRequest(BaseModel):
|
|
||||||
player_id: int
|
|
||||||
destination: str = Field(..., min_length=1)
|
|
||||||
|
|
||||||
|
|
||||||
class FunctionExecuteRequest(BaseModel):
|
|
||||||
schema_name: Optional[str] = Field(default=None, alias="schema")
|
|
||||||
function: str = Field(..., min_length=1)
|
|
||||||
args: dict = {}
|
|
||||||
|
|
||||||
|
|
||||||
class RawQueryRequest(BaseModel):
|
|
||||||
query: str = Field(..., min_length=1)
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Routes package init.
|
|
||||||
@@ -1,971 +0,0 @@
|
|||||||
# Main API routes — players, guilds, economy, world, progression, character, admin.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, request, jsonify
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
from pydantic import ValidationError
|
|
||||||
|
|
||||||
from app.models import (
|
|
||||||
ApiResponse, ErrorDetail, PlayerDetail, BroadcastRequest,
|
|
||||||
TeleportRequest, FunctionExecuteRequest, RawQueryRequest,
|
|
||||||
)
|
|
||||||
|
|
||||||
api_bp = Blueprint("api", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _audit(action: str, details: dict | None = None, target_player_id: int | None = None, severity: str = "info"):
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
audit = services.get("audit")
|
|
||||||
if audit:
|
|
||||||
audit.log(
|
|
||||||
action=action,
|
|
||||||
user=current_user.id if current_user.is_authenticated else "anonymous",
|
|
||||||
details=details,
|
|
||||||
target_player_id=target_player_id,
|
|
||||||
severity=severity,
|
|
||||||
source_ip=request.remote_addr,
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.errorhandler(ValidationError)
|
|
||||||
def handle_validation_error(e):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
|
|
||||||
# ── Player Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/players", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_players():
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 50))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
results = svc.search(term, limit=limit)
|
|
||||||
return jsonify(ApiResponse(success=True, data=results).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/search", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def search_players():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
term = data.get("term", "")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
results = svc.search(term)
|
|
||||||
return jsonify(ApiResponse(success=True, data=results).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["player"]
|
|
||||||
detail = svc.get_detail(account_id)
|
|
||||||
if not detail:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=detail).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/inventory", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_inventory(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
inventories = svc.get_inventory(account_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=inventories).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/currency", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_currency(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
player_svc = get_services()["player"]
|
|
||||||
detail = player_svc.get_detail(account_id)
|
|
||||||
pid = detail.get("player_controller_id") if detail else None
|
|
||||||
if not pid:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player controller not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
econ = get_services()["economy"]
|
|
||||||
currency = econ.get_currency(pid)
|
|
||||||
return jsonify(ApiResponse(success=True, data=currency).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/vitals", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_vitals(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
player_svc = get_services()["player"]
|
|
||||||
detail = player_svc.get_detail(account_id)
|
|
||||||
pawn_id = detail.get("player_pawn_id") if detail else None
|
|
||||||
if not pawn_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Player pawn not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
econ = get_services()["economy"]
|
|
||||||
vitals = econ.get_vitals(pawn_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=vitals).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Economy Mutations ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/items/add", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def add_item():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
inventory_id = data.get("inventory_id")
|
|
||||||
template_id = data.get("template_id")
|
|
||||||
stack_size = data.get("stack_size", 1)
|
|
||||||
quality_level = data.get("quality_level", 0)
|
|
||||||
if not inventory_id or not template_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing inventory_id or template_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
item_id = svc.add_item(inventory_id, template_id, stack_size, quality_level)
|
|
||||||
_audit("item_add", {"inventory_id": inventory_id, "template_id": template_id, "item_id": item_id})
|
|
||||||
return jsonify(ApiResponse(success=True, data={"item_id": item_id}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/items/<int:item_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_item(item_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.delete_item(item_id)
|
|
||||||
_audit("item_delete", {"item_id": item_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/items/<int:item_id>", methods=["PATCH"])
|
|
||||||
@login_required
|
|
||||||
def edit_item(item_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
field = data.get("field")
|
|
||||||
value = data.get("value")
|
|
||||||
if not field or value is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing field or value"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.edit_item_field(item_id, field, value)
|
|
||||||
_audit("item_edit", {"item_id": item_id, "field": field, "value": value})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/currency/adjust", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def adjust_currency():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
controller_id = data.get("controller_id")
|
|
||||||
currency_id = data.get("currency_id")
|
|
||||||
delta = data.get("delta")
|
|
||||||
if controller_id is None or currency_id is None or delta is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
new_balance = svc.adjust_currency(controller_id, currency_id, delta)
|
|
||||||
_audit("currency_adjust", {"controller_id": controller_id, "currency_id": currency_id, "delta": delta, "new_balance": new_balance}, target_player_id=controller_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"new_balance": new_balance}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/currency/set", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_currency():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
controller_id = data.get("controller_id")
|
|
||||||
currency_id = data.get("currency_id")
|
|
||||||
balance = data.get("balance")
|
|
||||||
if controller_id is None or currency_id is None or balance is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.set_currency(controller_id, currency_id, balance)
|
|
||||||
_audit("currency_set", {"controller_id": controller_id, "currency_id": currency_id, "balance": balance}, target_player_id=controller_id)
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/vitals/set", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_vitals():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
pawn_id = data.get("pawn_id")
|
|
||||||
health = data.get("health")
|
|
||||||
max_health = data.get("max_health")
|
|
||||||
hydration = data.get("hydration")
|
|
||||||
spice = data.get("spice")
|
|
||||||
if pawn_id is None or hydration is None or spice is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.set_vitals(pawn_id, health, max_health, hydration, spice)
|
|
||||||
_audit("vitals_edit", {"pawn_id": pawn_id, "health": health, "max_health": max_health, "hydration": hydration, "spice": spice})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Guild Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/guilds", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_guilds():
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 50))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
guilds = svc.list_all()
|
|
||||||
if term:
|
|
||||||
guilds = [g for g in guilds if term.lower() in g.guild_name.lower()]
|
|
||||||
return jsonify(ApiResponse(success=True, data=guilds[:limit]).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_guild(guild_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
guild = svc.get_detail(guild_id)
|
|
||||||
if not guild:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Guild not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=guild).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def disband_guild(guild_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
svc.disband(guild_id)
|
|
||||||
_audit("guild_disband", {"guild_id": guild_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def remove_guild_member(guild_id, player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
svc.remove_member(guild_id, player_id)
|
|
||||||
_audit("guild_kick", {"guild_id": guild_id, "player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/guilds/<int:guild_id>/members/<int:player_id>/role", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def set_guild_role(guild_id, player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
role_id = data.get("role_id")
|
|
||||||
action = data.get("action", "promote")
|
|
||||||
if role_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing role_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["guild"]
|
|
||||||
if action == "promote":
|
|
||||||
svc.promote(guild_id, player_id, role_id)
|
|
||||||
else:
|
|
||||||
svc.demote(guild_id, player_id, role_id)
|
|
||||||
_audit(f"guild_{action}", {"guild_id": guild_id, "player_id": player_id, "role_id": role_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── World Endpoints ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/partitions", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_partitions():
|
|
||||||
map_name = request.args.get("map", "")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
partitions = svc.get_partitions(map_name)
|
|
||||||
return jsonify(ApiResponse(success=True, data=partitions).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/teleport", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def teleport():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
req = TeleportRequest(**data)
|
|
||||||
except ValidationError as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.teleport(req.fls_id, req.partition_id, req.x, req.y, req.z)
|
|
||||||
_audit("player_teleport", {"fls_id": req.fls_id, "partition_id": req.partition_id, "coords": [req.x, req.y, req.z]})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/spice/reset", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def reset_spice():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
map_name = data.get("map_name")
|
|
||||||
dimension_index = data.get("dimension_index", 0)
|
|
||||||
if not map_name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing map_name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.reset_spice(map_name, dimension_index)
|
|
||||||
_audit("spice_reset", {"map": map_name, "dimension": dimension_index})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/spice/spawn", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def force_spice_spawn():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
server_id = data.get("server_id")
|
|
||||||
spicefield_type_id = data.get("spicefield_type_id")
|
|
||||||
if not server_id or spicefield_type_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["world"]
|
|
||||||
svc.force_spice_spawn(server_id, spicefield_type_id)
|
|
||||||
_audit("spice_spawn", {"server_id": server_id, "spicefield_type_id": spicefield_type_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Progression Endpoints ────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/progression/journey", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def journey_action():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
node_ids = data.get("node_ids", [])
|
|
||||||
action = data.get("action", "complete")
|
|
||||||
if not player_id or not node_ids:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id or node_ids"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
if action == "complete":
|
|
||||||
svc.complete_nodes(player_id, node_ids)
|
|
||||||
elif action == "reveal":
|
|
||||||
svc.reveal_nodes(player_id, node_ids)
|
|
||||||
elif action == "reset":
|
|
||||||
svc.reset_nodes(player_id, node_ids)
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Invalid action"),
|
|
||||||
).model_dump()), 400
|
|
||||||
_audit(f"journey_{action}", {"player_id": player_id, "node_ids": node_ids})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/progression/specialization", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def set_specialization():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
track_type = data.get("track_type")
|
|
||||||
xp = data.get("xp")
|
|
||||||
level = data.get("level")
|
|
||||||
if player_id is None or not track_type or xp is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing required parameters"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
svc.set_specialization(player_id, track_type, xp, level or 0)
|
|
||||||
_audit("specialization_set", {"player_id": player_id, "track": track_type, "xp": xp, "level": level})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/progression/specialization/reset", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def reset_specializations():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if player_id is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["progression"]
|
|
||||||
svc.reset_specializations(player_id)
|
|
||||||
_audit("specialization_reset", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Character Management Endpoints ──────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/characters/<int:account_id>/name", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def rename_character(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
name = data.get("name", "").strip()
|
|
||||||
if not name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.rename(account_id, name)
|
|
||||||
_audit("character_rename", {"account_id": account_id, "new_name": name})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/characters/<int:actor_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_character(actor_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.delete_character(actor_id)
|
|
||||||
_audit("character_delete", {"actor_id": actor_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/accounts/<user_id>", methods=["DELETE"])
|
|
||||||
@login_required
|
|
||||||
def delete_account(user_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.delete_account(user_id, reason)
|
|
||||||
_audit("account_delete", {"user_id": user_id, "reason": reason})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/accounts/<user_id>/demo", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def set_demo_state(user_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
state = data.get("demo")
|
|
||||||
if state is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing demo"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.set_demo(user_id, state)
|
|
||||||
_audit("demo_set", {"user_id": user_id, "state": state})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Vehicles ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/vehicles", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_vehicles():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.map
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
|
|
||||||
WHERE a.class ILIKE %s
|
|
||||||
ORDER BY a.id DESC LIMIT %s""",
|
|
||||||
[f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
vehicles = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"class_name": r["class"],
|
|
||||||
"display_name": (r["class"] or "").split("/")[-1].replace("_C", "").replace("BP_", "").replace("_", " "),
|
|
||||||
"map": r["map"],
|
|
||||||
"owner_name": "Unknown",
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=vehicles).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/vehicles/<int:vehicle_id>/<action>", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def vehicle_action(vehicle_id, action):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
if action == "repair":
|
|
||||||
db.call_procedure("repair_vehicle", [vehicle_id])
|
|
||||||
_audit("vehicle_repair", {"vehicle_id": vehicle_id})
|
|
||||||
elif action == "destroy":
|
|
||||||
db.call_procedure("destroy_vehicle", [vehicle_id])
|
|
||||||
_audit("vehicle_destroy", {"vehicle_id": vehicle_id})
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
|
|
||||||
).model_dump()), 400
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Buildings ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/buildings", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_buildings():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.map, a.properties->>'m_bIsPowered' as is_powered,
|
|
||||||
a.properties->>'m_PowerLevel' as power_level
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.buildings b ON a.id = b.id
|
|
||||||
WHERE a.class ILIKE %s
|
|
||||||
ORDER BY a.id DESC LIMIT %s""",
|
|
||||||
[f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
buildings = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"class_name": r["class"],
|
|
||||||
"map": r["map"],
|
|
||||||
"owner_name": "Unknown",
|
|
||||||
"is_powered": r.get("is_powered") == "True",
|
|
||||||
"power_level": r.get("power_level"),
|
|
||||||
"instance_count": 1,
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=buildings).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Accounts ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/accounts", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_accounts():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
term = request.args.get("q", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT a.id, COALESCE(a.email, '') as email, a.funcom_id,
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state ps WHERE ps.account_id = a.id) as character_count,
|
|
||||||
COALESCE(a.is_demo, false) as is_demo, COALESCE(a.is_cheater, false) as is_cheater,
|
|
||||||
NULL as last_login
|
|
||||||
FROM dune.accounts a
|
|
||||||
WHERE a.email ILIKE %s OR a.funcom_id ILIKE %s
|
|
||||||
LIMIT %s""",
|
|
||||||
[f"%{term}%", f"%{term}%", limit],
|
|
||||||
)
|
|
||||||
accounts = [{
|
|
||||||
"id": r["id"],
|
|
||||||
"email": r.get("email") or "",
|
|
||||||
"funcom_id": r["funcom_id"],
|
|
||||||
"character_count": r["character_count"],
|
|
||||||
"is_demo": r["is_demo"],
|
|
||||||
"is_cheater": r["is_cheater"],
|
|
||||||
"last_login": r["last_login"].isoformat() if r["last_login"] else None,
|
|
||||||
} for r in rows]
|
|
||||||
return jsonify(ApiResponse(success=True, data=accounts).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/cheater", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def flag_cheater(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
cheat_type = data.get("cheat_type")
|
|
||||||
if not cheat_type:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing cheat_type"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.flag_cheater(account_id, cheat_type)
|
|
||||||
_audit("cheater_flag", {"account_id": account_id, "cheat_type": cheat_type})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/tags", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_tags(account_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
tags = svc.get_tags(account_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"tags": tags}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:account_id>/tags", methods=["PUT"])
|
|
||||||
@login_required
|
|
||||||
def update_player_tags(account_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
add = data.get("add", [])
|
|
||||||
remove = data.get("remove", [])
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["character"]
|
|
||||||
svc.update_tags(account_id, add, remove)
|
|
||||||
_audit("tags_update", {"account_id": account_id, "add": add, "remove": remove})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Broadcast ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/broadcast", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def send_broadcast():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
req = BroadcastRequest(**data)
|
|
||||||
except ValidationError as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=str(e)),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["rmq_game"]
|
|
||||||
success = svc.send_broadcast(req.message, server=req.server, partition=req.partition)
|
|
||||||
if success:
|
|
||||||
_audit("broadcast_sent", {"message": req.message, "server": req.server, "partition": req.partition})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="BroadcastFailed", message="Failed to send broadcast via RMQ"),
|
|
||||||
).model_dump()), 502
|
|
||||||
|
|
||||||
|
|
||||||
# ── Vendor / Economy ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/vendors/clean", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def clean_vendor_stock():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if not player_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
svc.clean_vendor_stock(player_id)
|
|
||||||
_audit("vendor_clean", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/tax/invoices", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def get_tax_invoices():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
player_id = data.get("player_id")
|
|
||||||
if not player_id:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing player_id"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["economy"]
|
|
||||||
invoices = svc.get_tax_invoices(player_id)
|
|
||||||
return jsonify(ApiResponse(success=True, data=invoices).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Function Explorer ────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/functions", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_functions():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT p.proname as name,
|
|
||||||
pg_get_function_identity_arguments(p.oid) as args,
|
|
||||||
l.lanname as language,
|
|
||||||
p.prokind as kind
|
|
||||||
FROM pg_proc p
|
|
||||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
||||||
JOIN pg_language l ON l.oid = p.prolang
|
|
||||||
WHERE n.nspname = 'dune' AND p.prokind = 'f'
|
|
||||||
ORDER BY p.proname"""
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/<name>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_function_detail(name):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"""SELECT pg_get_functiondef(p.oid) as definition,
|
|
||||||
p.proname as name,
|
|
||||||
pg_get_function_identity_arguments(p.oid) as args
|
|
||||||
FROM pg_proc p
|
|
||||||
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
||||||
WHERE n.nspname = 'dune' AND p.proname = %s AND p.prokind = 'f'""",
|
|
||||||
[name],
|
|
||||||
)
|
|
||||||
if not rows:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Function not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows[0]).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/execute", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def execute_function_v2():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
schema = data.get("schema")
|
|
||||||
func_name = data.get("function", "")
|
|
||||||
args = data.get("args", {})
|
|
||||||
if not func_name:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing function name"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
full_name = f"{schema}.{func_name}" if schema else func_name
|
|
||||||
if isinstance(args, dict):
|
|
||||||
params = list(args.values())
|
|
||||||
elif isinstance(args, list):
|
|
||||||
params = args
|
|
||||||
else:
|
|
||||||
params = [args]
|
|
||||||
result = db.call_function(full_name, params)
|
|
||||||
_audit("function_execute", {"function": full_name, "params": params})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Function execution failed")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ExecutionError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/functions/<name>/execute", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def execute_function(name):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
params = data.get("params", [])
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
result = db.call_function(name, params)
|
|
||||||
_audit("function_execute", {"function": name, "params": params})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Function execution failed")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ExecutionError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
# ── Raw Query (SELECT only) ──────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/query", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def raw_query():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
sql = (data.get("query") or data.get("sql", "")).strip()
|
|
||||||
if not sql:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing SQL"),
|
|
||||||
).model_dump()), 400
|
|
||||||
upper = sql.upper()
|
|
||||||
if any(kw in upper for kw in ("INSERT", "UPDATE", "DELETE", "DROP", "CREATE", "ALTER", "GRANT", "TRUNCATE")):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="Forbidden", message="Only SELECT queries are allowed"),
|
|
||||||
).model_dump()), 403
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
result = db.execute_readonly(sql)
|
|
||||||
_audit("raw_query", {"sql": sql[:200]})
|
|
||||||
return jsonify(ApiResponse(success=True, data=result).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="QueryError", message=str(e)),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
# ── Audit Logs ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/audit/logs", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_audit_logs():
|
|
||||||
action = request.args.get("action")
|
|
||||||
user = request.args.get("user")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
offset = int(request.args.get("offset", 0))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["audit"]
|
|
||||||
logs = svc.get_logs(action=action, user=user, limit=limit, offset=offset)
|
|
||||||
return jsonify(ApiResponse(success=True, data=logs).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/stats", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_stats():
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
try:
|
|
||||||
stats = db.execute_readonly("""
|
|
||||||
SELECT
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state) AS total_players,
|
|
||||||
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') AS online_players,
|
|
||||||
(SELECT COUNT(*) FROM dune.guilds) AS guild_count,
|
|
||||||
(SELECT 0) AS active_guilds,
|
|
||||||
(SELECT COUNT(*) FROM dune.accounts) AS server_count,
|
|
||||||
(SELECT 0) AS partition_count,
|
|
||||||
(SELECT 0) AS total_worth,
|
|
||||||
(SELECT 0) AS total_flavor_text
|
|
||||||
""")
|
|
||||||
return jsonify(ApiResponse(success=True, data=stats[0] if stats else {}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Failed to get stats")
|
|
||||||
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="StatsError", message=str(e))).model_dump()), 500
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/audit/stats", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_audit_stats():
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["audit"]
|
|
||||||
stats = svc.get_stats()
|
|
||||||
return jsonify(ApiResponse(success=True, data=stats).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Settings ────────────────────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/settings", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_settings():
|
|
||||||
from app.factory import get_services
|
|
||||||
settings = get_services()["db"].execute_readonly(
|
|
||||||
"SELECT key, value, updated_at FROM dashboard.settings ORDER BY key"
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data={r["key"]: r["value"] for r in settings}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/settings", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def update_settings():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
if not isinstance(data, dict):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Expected JSON object"),
|
|
||||||
).model_dump()), 400
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
for key, value in data.items():
|
|
||||||
db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.settings (key, value, updated_at)
|
|
||||||
VALUES (%s, %s, NOW())
|
|
||||||
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()""",
|
|
||||||
[key, str(value)],
|
|
||||||
)
|
|
||||||
_audit("settings_update", {"keys": list(data.keys())})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
# ── Moderation (Ban / Kick) ────────────────────────────────────
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/ban", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def ban_player(player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
duration = data.get("duration_hours", 0)
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.bans (player_id, reason, duration, banned_at, expires_at, active)
|
|
||||||
VALUES (%s, %s, %s, NOW(), CASE WHEN %s > 0 THEN NOW() + INTERVAL '%s hours' ELSE NULL END, TRUE)
|
|
||||||
ON CONFLICT (player_id) DO UPDATE SET reason = EXCLUDED.reason, duration = EXCLUDED.duration, banned_at = NOW(), expires_at = EXCLUDED.expires_at, active = TRUE""",
|
|
||||||
[player_id, reason, duration, duration, duration],
|
|
||||||
)
|
|
||||||
_audit("player_ban", {"player_id": player_id, "reason": reason, "duration": duration})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/unban", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def unban_player(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
db.execute_mutation(
|
|
||||||
"UPDATE dashboard.bans SET active = FALSE WHERE player_id = %s",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
_audit("player_unban", {"player_id": player_id})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/ban", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_ban(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"SELECT * FROM dashboard.bans WHERE player_id = %s AND active = TRUE",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows[0] if rows else None).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/kick", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def kick_player(player_id):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
reason = data.get("reason", "admin")
|
|
||||||
_audit("player_kick", {"player_id": player_id, "reason": reason})
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@api_bp.route("/players/<int:player_id>/history", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def get_player_history(player_id):
|
|
||||||
from app.factory import get_services
|
|
||||||
db = get_services()["db"]
|
|
||||||
logs = db.execute_readonly(
|
|
||||||
"""SELECT * FROM dashboard.audit_log
|
|
||||||
WHERE target_player_id = %s OR (details->>'player_id')::bigint = %s
|
|
||||||
ORDER BY created_at DESC LIMIT 100""",
|
|
||||||
[player_id, player_id],
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data=logs).model_dump())
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
# Authentication routes — login, logout.
|
|
||||||
|
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
from functools import wraps
|
|
||||||
|
|
||||||
from flask import Blueprint, request, jsonify, session
|
|
||||||
from flask_login import LoginManager, UserMixin, login_user, logout_user, login_required, current_user
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
auth_bp = Blueprint("auth", __name__)
|
|
||||||
login_manager = LoginManager()
|
|
||||||
|
|
||||||
_failed_attempts = {}
|
|
||||||
_failed_lock = threading.Lock()
|
|
||||||
_MAX_FAILED_ATTEMPTS = 5
|
|
||||||
_BLOCK_DURATION = 900
|
|
||||||
|
|
||||||
|
|
||||||
class AdminUser(UserMixin):
|
|
||||||
def __init__(self, username):
|
|
||||||
self.id = username
|
|
||||||
|
|
||||||
|
|
||||||
def _is_ip_blocked(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
record = _failed_attempts.get(ip)
|
|
||||||
if record and record["count"] >= _MAX_FAILED_ATTEMPTS:
|
|
||||||
elapsed = time.time() - record["first_attempt"]
|
|
||||||
if elapsed < _BLOCK_DURATION:
|
|
||||||
return True
|
|
||||||
del _failed_attempts[ip]
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def _record_failed_attempt(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
now = time.time()
|
|
||||||
record = _failed_attempts.get(ip)
|
|
||||||
if record:
|
|
||||||
record["count"] += 1
|
|
||||||
else:
|
|
||||||
_failed_attempts[ip] = {"count": 1, "first_attempt": now}
|
|
||||||
return _failed_attempts[ip]["count"] >= _MAX_FAILED_ATTEMPTS
|
|
||||||
|
|
||||||
|
|
||||||
def _clear_failed_attempts(ip):
|
|
||||||
with _failed_lock:
|
|
||||||
_failed_attempts.pop(ip, None)
|
|
||||||
|
|
||||||
|
|
||||||
def init_auth(app, settings):
|
|
||||||
login_manager.init_app(app)
|
|
||||||
login_manager.login_view = "auth.login"
|
|
||||||
login_manager.login_message = "Please log in."
|
|
||||||
|
|
||||||
@login_manager.user_loader
|
|
||||||
def load_user(user_id):
|
|
||||||
auth = settings.get("auth", {})
|
|
||||||
if str(auth.get("username")) == str(user_id):
|
|
||||||
return AdminUser(user_id)
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def get_audit_user():
|
|
||||||
return current_user.id if current_user.is_authenticated else "anonymous"
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/login", methods=["POST"])
|
|
||||||
def login():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
username = data.get("username", "").strip()
|
|
||||||
password = data.get("password", "")
|
|
||||||
client_ip = request.remote_addr or "unknown"
|
|
||||||
|
|
||||||
if _is_ip_blocked(client_ip):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="IpBlocked", message="Too many failed attempts. Try again later."),
|
|
||||||
).model_dump()), 429
|
|
||||||
|
|
||||||
auth = request.app.dune_settings.get("auth", {})
|
|
||||||
cfg_u = str(auth.get("username", ""))
|
|
||||||
password_hash = auth.get("password_hash")
|
|
||||||
|
|
||||||
if username != cfg_u:
|
|
||||||
_record_failed_attempt(client_ip)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
|
|
||||||
).model_dump()), 401
|
|
||||||
|
|
||||||
if password_hash:
|
|
||||||
try:
|
|
||||||
from argon2 import PasswordHasher, exceptions
|
|
||||||
ph = PasswordHasher(time_cost=3, memory_cost=65536)
|
|
||||||
ph.verify(password_hash, password)
|
|
||||||
_clear_failed_attempts(client_ip)
|
|
||||||
login_user(AdminUser(username))
|
|
||||||
return jsonify(ApiResponse(success=True, data={"user": username}).model_dump())
|
|
||||||
except exceptions.VerifyMismatchError:
|
|
||||||
_record_failed_attempt(client_ip)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="InvalidCredentials", message="Invalid username or password"),
|
|
||||||
).model_dump()), 401
|
|
||||||
except Exception:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AuthError", message="Authentication error"),
|
|
||||||
).model_dump()), 500
|
|
||||||
else:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotConfigured", message="Authentication not configured"),
|
|
||||||
).model_dump()), 403
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/logout", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def logout():
|
|
||||||
logout_user()
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@auth_bp.route("/me", methods=["GET"])
|
|
||||||
def me():
|
|
||||||
if current_user.is_authenticated:
|
|
||||||
return jsonify(ApiResponse(success=True, data={"user": current_user.id}).model_dump())
|
|
||||||
return jsonify(ApiResponse(success=False, error=ErrorDetail(code="Unauthorized", message="Not authenticated")).model_dump()), 401
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
# Chat routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
chat_bp = Blueprint("chat", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@chat_bp.route("/history", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def chat_history():
|
|
||||||
channel = request.args.get("channel", "")
|
|
||||||
limit = int(request.args.get("limit", 100))
|
|
||||||
from app.factory import get_services
|
|
||||||
svc = get_services()["chat"]
|
|
||||||
rows = svc.get_history(limit=limit)
|
|
||||||
if channel:
|
|
||||||
rows = [r for r in rows if r.get("channel", "").lower() == channel.lower()]
|
|
||||||
return jsonify(ApiResponse(success=True, data=rows).model_dump())
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
# Debug routes — restricted to admin.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
debug_bp = Blueprint("debug", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
@debug_bp.route("/tables", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def list_tables():
|
|
||||||
db = _get_services()["db"]
|
|
||||||
rows = db.execute_readonly(
|
|
||||||
"SELECT table_name FROM information_schema.tables WHERE table_schema = 'dune' ORDER BY table_name"
|
|
||||||
)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"tables": [r["table_name"] for r in rows]}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@debug_bp.route("/vehicle/<int:vehicle_id>", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def debug_vehicle(vehicle_id):
|
|
||||||
db = _get_services()["db"]
|
|
||||||
vehicle = db.execute_readonly(
|
|
||||||
"""SELECT a.id, a.class, a.properties
|
|
||||||
FROM dune.actors a JOIN dune.vehicles v ON a.id = v.id WHERE a.id = %s""",
|
|
||||||
[vehicle_id],
|
|
||||||
)
|
|
||||||
if not vehicle:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="NotFound", message="Vehicle not found"),
|
|
||||||
).model_dump()), 404
|
|
||||||
return jsonify(ApiResponse(success=True, data=vehicle[0]).model_dump())
|
|
||||||
@@ -1,147 +0,0 @@
|
|||||||
# BGD Director proxy routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
director_bp = Blueprint("director", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_service():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()["bg_director"]
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/battlegroup", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_battlegroup():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_battlegroup()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data.model_dump()).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Director battlegroup error: %s", e)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e), hint="Check BGD pod logs"),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/config", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_update_config():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_server_config(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/config/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_clear_config():
|
|
||||||
map_name = request.get_data(as_text=True).strip()
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_map_config(map_name)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_get():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_transfer_rules()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_update():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_transfer_settings(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/transfer/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_transfer_clear():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_transfer_overrides()
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_get():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
data = svc.get_fls_settings()
|
|
||||||
return jsonify(ApiResponse(success=True, data=data).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_update():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.update_fls_settings(data)
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@director_bp.route("/fls/clear", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def director_fls_clear():
|
|
||||||
try:
|
|
||||||
svc = _get_service()
|
|
||||||
result = svc.clear_fls_overrides()
|
|
||||||
return jsonify(ApiResponse(success=True, data={"result": result}).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="DirectorUnavailable", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
# File browser routes.
|
|
||||||
|
|
||||||
import base64
|
|
||||||
import logging
|
|
||||||
import posixpath
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
files_bp = Blueprint("files", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
FILEBROWSER_BASE_PATH = "/srv"
|
|
||||||
|
|
||||||
|
|
||||||
def _validate_fb_path(path: str) -> bool:
|
|
||||||
path_str = str(path or "").lstrip("/")
|
|
||||||
if ".." in path_str or "\x00" in path_str:
|
|
||||||
return False
|
|
||||||
normalized = posixpath.normpath("/" + path_str)
|
|
||||||
return normalized == FILEBROWSER_BASE_PATH or normalized.startswith(FILEBROWSER_BASE_PATH + "/")
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
def _fb_exec(command: str, timeout: int = 10):
|
|
||||||
services = _get_services()
|
|
||||||
k8s = services["k8s"]
|
|
||||||
pod = k8s.get_filebrowser_pod()
|
|
||||||
if not pod:
|
|
||||||
return "", "FileBrowser pod not found", 1
|
|
||||||
full_cmd = f"sudo kubectl exec {pod} -n {k8s.namespace} -- {command}"
|
|
||||||
return k8s.ssh.run(full_cmd, timeout=timeout)
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/list", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def files_list():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
path = data.get("path", "/srv")
|
|
||||||
if not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
out, err, rc = _fb_exec(f"ls -la {safe_path}", timeout=10)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to list directory"),
|
|
||||||
).model_dump()), 500
|
|
||||||
|
|
||||||
files = []
|
|
||||||
for line in out.strip().split("\n")[1:]:
|
|
||||||
parts = line.split(None, 8)
|
|
||||||
if len(parts) >= 9:
|
|
||||||
name = parts[8]
|
|
||||||
if name in (".", ".."):
|
|
||||||
continue
|
|
||||||
files.append({
|
|
||||||
"name": name,
|
|
||||||
"is_dir": parts[0].startswith("d"),
|
|
||||||
"size": parts[4] if not parts[0].startswith("d") else "",
|
|
||||||
"perms": parts[0],
|
|
||||||
"date": " ".join(parts[5:8]),
|
|
||||||
})
|
|
||||||
return jsonify(ApiResponse(success=True, data={"files": files}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/view", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def files_view():
|
|
||||||
path = request.args.get("path", "")
|
|
||||||
if not path or not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
out, err, rc = _fb_exec(f"head -c 100000 {safe_path}", timeout=10)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to read file"),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(success=True, data={"content": out, "path": path}).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@files_bp.route("/save", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def files_save():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
path = data.get("path", "")
|
|
||||||
content = data.get("content", "")
|
|
||||||
if not path or not _validate_fb_path(path):
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="AccessDenied", message="Invalid path"),
|
|
||||||
).model_dump()), 403
|
|
||||||
import shlex
|
|
||||||
import base64
|
|
||||||
content_b64 = base64.b64encode(content.encode()).decode()
|
|
||||||
safe_path = shlex.quote(path)
|
|
||||||
# Write via base64 decode inside pod
|
|
||||||
cmd = f"echo {content_b64} | base64 -d > {safe_path}"
|
|
||||||
out, err, rc = _fb_exec(cmd, timeout=15)
|
|
||||||
if rc != 0:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="CommandError", message=err or "Failed to save file"),
|
|
||||||
).model_dump()), 500
|
|
||||||
return jsonify(ApiResponse(success=True).model_dump())
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
# Health and SSE routes.
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, Response, request, stream_with_context
|
|
||||||
from flask_login import login_required, current_user
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
health_bp = Blueprint("health", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
@health_bp.route("/health", methods=["GET"])
|
|
||||||
def health_check():
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
health = {"status": "healthy", "timestamp": __import__("datetime").datetime.now().isoformat(), "checks": {}}
|
|
||||||
status_code = 200
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["db"].health_check()
|
|
||||||
health["checks"]["database"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["database"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["ssh"].check_connection()
|
|
||||||
health["checks"]["ssh"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["ssh"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["bg_director"].get_battlegroup()
|
|
||||||
health["checks"]["bgd"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["bgd"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
try:
|
|
||||||
services["rmq_admin"].get_overview()
|
|
||||||
health["checks"]["rmq"] = "ok"
|
|
||||||
except Exception as e:
|
|
||||||
health["checks"]["rmq"] = f"error: {e}"
|
|
||||||
health["status"] = "degraded"
|
|
||||||
status_code = 503
|
|
||||||
|
|
||||||
return jsonify(health), status_code
|
|
||||||
|
|
||||||
|
|
||||||
@health_bp.route("/events/stream", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def sse_stream():
|
|
||||||
from app.factory import get_services
|
|
||||||
services = get_services()
|
|
||||||
realtime = services["realtime"]
|
|
||||||
|
|
||||||
queue = asyncio.Queue(maxsize=100)
|
|
||||||
realtime.add_client(queue)
|
|
||||||
|
|
||||||
def event_stream():
|
|
||||||
try:
|
|
||||||
yield "event: connected\ndata: {}\n\n"
|
|
||||||
loop = asyncio.new_event_loop()
|
|
||||||
asyncio.set_event_loop(loop)
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
msg = loop.run_until_complete(asyncio.wait_for(queue.get(), timeout=30))
|
|
||||||
yield msg
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
yield ":ping\n\n"
|
|
||||||
except Exception:
|
|
||||||
break
|
|
||||||
finally:
|
|
||||||
realtime.remove_client(queue)
|
|
||||||
|
|
||||||
return Response(stream_with_context(event_stream()), mimetype="text/event-stream")
|
|
||||||
@@ -1,218 +0,0 @@
|
|||||||
# Server and infrastructure routes.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from flask import Blueprint, jsonify, request
|
|
||||||
from flask_login import login_required
|
|
||||||
|
|
||||||
from app.models import ApiResponse, ErrorDetail
|
|
||||||
|
|
||||||
server_bp = Blueprint("server", __name__)
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
def _get_services():
|
|
||||||
from app.factory import get_services
|
|
||||||
return get_services()
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/pods", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_pods():
|
|
||||||
services = _get_services()
|
|
||||||
pods = services["k8s"].get_pods()
|
|
||||||
return jsonify(ApiResponse(success=True, data=pods).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_deployments():
|
|
||||||
services = _get_services()
|
|
||||||
deployments = services["k8s"].get_deployments()
|
|
||||||
return jsonify(ApiResponse(success=True, data=deployments).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/metrics", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def server_metrics():
|
|
||||||
services = _get_services()
|
|
||||||
raw = services["k8s"].get_node_metrics()
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
metrics = []
|
|
||||||
if raw:
|
|
||||||
cpu_str = raw.get("cpu", "0m").replace("m", "").replace("%", "")
|
|
||||||
mem_str = raw.get("memory", "0Mi").replace("Mi", "").replace("Gi", "000")
|
|
||||||
try:
|
|
||||||
cpu_val = float(cpu_str)
|
|
||||||
mem_val = float(mem_str)
|
|
||||||
metrics.append({
|
|
||||||
"timestamp": datetime.now(timezone.utc).isoformat(),
|
|
||||||
"cpu_percent": min(100, round(cpu_val / 10, 1)), # rough estimate
|
|
||||||
"memory_percent": min(100, round(mem_val / 100, 1)), # rough estimate
|
|
||||||
})
|
|
||||||
except ValueError:
|
|
||||||
pass
|
|
||||||
return jsonify(ApiResponse(success=True, data=metrics).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments/<name>/restart", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def restart_deployment(name: str):
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(f"rollout restart deployment/{name}")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/deployments/<name>/scale", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def scale_deployment(name: str):
|
|
||||||
data = request.get_json() or {}
|
|
||||||
replicas = data.get("replicas")
|
|
||||||
if replicas is None:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing replicas"),
|
|
||||||
).model_dump()), 400
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(f"scale deployment/{name} --replicas={replicas}")
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/action", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def server_action():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
deployment = data.get("deployment", "")
|
|
||||||
action = data.get("action", "")
|
|
||||||
if not deployment or not action:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing deployment or action"),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
actions = {
|
|
||||||
"restart": f"rollout restart deployment/{deployment}",
|
|
||||||
"status": f"rollout status deployment/{deployment}",
|
|
||||||
"scale_0": f"scale deployment/{deployment} --replicas=0",
|
|
||||||
"scale_1": f"scale deployment/{deployment} --replicas=1",
|
|
||||||
"describe": f"describe deployment/{deployment}",
|
|
||||||
}
|
|
||||||
cmd = actions.get(action)
|
|
||||||
if not cmd:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message=f"Unknown action: {action}"),
|
|
||||||
).model_dump()), 400
|
|
||||||
|
|
||||||
services = _get_services()
|
|
||||||
out, err, rc = services["k8s"].run(cmd)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=rc == 0,
|
|
||||||
data={"output": out, "error": err, "rc": rc},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/firewall", methods=["GET"])
|
|
||||||
@server_bp.route("/firewall/status", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def firewall_status():
|
|
||||||
services = _get_services()
|
|
||||||
ssh = services["ssh"]
|
|
||||||
out, _, _ = ssh.run(
|
|
||||||
"sudo iptables -L INPUT -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
|
|
||||||
"sudo iptables -L FORWARD -n 2>/dev/null | grep -E 'dpt:(18888|32479)'; "
|
|
||||||
"sudo iptables -t mangle -L PREROUTING -n 2>/dev/null | grep -E 'dpt:(18888|32479)'",
|
|
||||||
timeout=15,
|
|
||||||
)
|
|
||||||
blocked_ports = set()
|
|
||||||
for line in out.split("\n"):
|
|
||||||
for port in ("18888", "32479"):
|
|
||||||
if f"dpt:{port}" in line and "DROP" in line:
|
|
||||||
blocked_ports.add(port)
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data={
|
|
||||||
"18888_blocked": "18888" in blocked_ports,
|
|
||||||
"32479_blocked": "32479" in blocked_ports,
|
|
||||||
},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/firewall/toggle", methods=["POST"])
|
|
||||||
@login_required
|
|
||||||
def firewall_toggle():
|
|
||||||
data = request.get_json() or {}
|
|
||||||
port = data.get("port")
|
|
||||||
block = data.get("block", True)
|
|
||||||
if not port:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="ValidationError", message="Missing port"),
|
|
||||||
).model_dump()), 400
|
|
||||||
services = _get_services()
|
|
||||||
ssh = services["ssh"]
|
|
||||||
if block:
|
|
||||||
cmd = (
|
|
||||||
f"sudo iptables -I INPUT 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -I INPUT 2 -p tcp --dport {port} -j DROP && "
|
|
||||||
f"sudo iptables -I FORWARD 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -I FORWARD 2 -p tcp --dport {port} -j DROP && "
|
|
||||||
f"sudo iptables -t mangle -I PREROUTING 1 -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT && "
|
|
||||||
f"sudo iptables -t mangle -I PREROUTING 2 -p tcp --dport {port} -j DROP"
|
|
||||||
)
|
|
||||||
else:
|
|
||||||
cmd = (
|
|
||||||
f"sudo iptables -D INPUT -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -D INPUT -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"sudo iptables -D FORWARD -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -D FORWARD -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -j DROP 2>/dev/null; "
|
|
||||||
f"sudo iptables -t mangle -D PREROUTING -p tcp --dport {port} -s 127.0.0.1 -j ACCEPT 2>/dev/null; "
|
|
||||||
f"echo DONE"
|
|
||||||
)
|
|
||||||
out, err, rc = ssh.run(cmd, timeout=20)
|
|
||||||
success = rc == 0 or "DONE" in out
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=success,
|
|
||||||
data={"output": out, "error": err},
|
|
||||||
).model_dump())
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/rmq/queues", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def rmq_queues():
|
|
||||||
services = _get_services()
|
|
||||||
try:
|
|
||||||
queues = services["rmq_admin"].get_queue_depths()
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data=[q.model_dump() for q in queues],
|
|
||||||
).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="RmqError", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
|
|
||||||
|
|
||||||
@server_bp.route("/rmq/overview", methods=["GET"])
|
|
||||||
@login_required
|
|
||||||
def rmq_overview():
|
|
||||||
services = _get_services()
|
|
||||||
try:
|
|
||||||
overview = services["rmq_admin"].get_overview()
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=True,
|
|
||||||
data=overview.model_dump(),
|
|
||||||
).model_dump())
|
|
||||||
except Exception as e:
|
|
||||||
return jsonify(ApiResponse(
|
|
||||||
success=False,
|
|
||||||
error=ErrorDetail(code="RmqError", message=str(e)),
|
|
||||||
).model_dump()), 503
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Services package init.
|
|
||||||
@@ -1,64 +0,0 @@
|
|||||||
# Audit logging service — persistent PostgreSQL storage.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class AuditService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def log(self, action: str, user: str, details: dict | None = None,
|
|
||||||
target_player_id: int | None = None, severity: str = "info",
|
|
||||||
source_ip: str | None = None) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.audit_log
|
|
||||||
(action_type, user_name, target_player_id, details, source_ip, severity, created_at)
|
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, NOW())""",
|
|
||||||
[action, user, target_player_id, details or {}, source_ip, severity],
|
|
||||||
)
|
|
||||||
logger.info("Audit: %s by %s", action, user)
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Audit log failed: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def get_logs(self, action: str | None = None, user: str | None = None,
|
|
||||||
target_player_id: int | None = None, limit: int = 100,
|
|
||||||
offset: int = 0) -> list[dict]:
|
|
||||||
sql = """SELECT id, action_type, user_name, target_player_id, details,
|
|
||||||
source_ip, severity, created_at
|
|
||||||
FROM dashboard.audit_log WHERE 1=1"""
|
|
||||||
params = []
|
|
||||||
if action:
|
|
||||||
sql += " AND action_type = %s"
|
|
||||||
params.append(action)
|
|
||||||
if user:
|
|
||||||
sql += " AND user_name = %s"
|
|
||||||
params.append(user)
|
|
||||||
if target_player_id:
|
|
||||||
sql += " AND target_player_id = %s"
|
|
||||||
params.append(target_player_id)
|
|
||||||
sql += " ORDER BY created_at DESC LIMIT %s OFFSET %s"
|
|
||||||
params.extend([limit, offset])
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
|
|
||||||
def get_stats(self) -> dict:
|
|
||||||
rows = self.db.execute_readonly(
|
|
||||||
"""SELECT action_type, COUNT(*) as cnt FROM dashboard.audit_log
|
|
||||||
GROUP BY action_type"""
|
|
||||||
)
|
|
||||||
return {r["action_type"]: r["cnt"] for r in rows}
|
|
||||||
|
|
||||||
def cleanup_old(self, days: int = 90) -> int:
|
|
||||||
result = self.db.execute_mutation(
|
|
||||||
"DELETE FROM dashboard.audit_log WHERE created_at < NOW() - INTERVAL '%s days'",
|
|
||||||
[days],
|
|
||||||
)
|
|
||||||
logger.info("Audit cleanup: removed %d entries older than %d days", result, days)
|
|
||||||
return result
|
|
||||||
@@ -1,141 +0,0 @@
|
|||||||
"""Battlegroup Director HTTP API client."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from typing import Any, Dict
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from app.models import BattlegroupState, ErrorDetail
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class BgDirectorService:
|
|
||||||
def __init__(self, host: str, node_port: int):
|
|
||||||
self.base_url = f"http://{host}:{node_port}"
|
|
||||||
self.client = httpx.Client(base_url=self.base_url, timeout=15)
|
|
||||||
logger.debug("BgDirectorService initialized: %s", self.base_url)
|
|
||||||
|
|
||||||
def _request(self, method: str, path: str, data: Any = None, timeout: int = 15) -> dict | str:
|
|
||||||
try:
|
|
||||||
if method == "GET":
|
|
||||||
resp = self.client.get(path, timeout=timeout)
|
|
||||||
else:
|
|
||||||
if isinstance(data, str):
|
|
||||||
resp = self.client.request(method, path, content=data, headers={"Content-Type": "application/json"}, timeout=timeout)
|
|
||||||
else:
|
|
||||||
resp = self.client.request(method, path, json=data, timeout=timeout)
|
|
||||||
resp.raise_for_status()
|
|
||||||
if resp.headers.get("content-type", "").startswith("application/json"):
|
|
||||||
return resp.json()
|
|
||||||
return resp.text
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("BGD HTTP error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError(f"BGD returned {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("BGD connection error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError("The Battlegroup Director is not responding. Check BGD pod logs.")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("BGD request error %s %s: %s", method, path, e)
|
|
||||||
raise DirectorUnavailableError(str(e))
|
|
||||||
|
|
||||||
# ── Player Endpoints ──────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_battlegroup(self) -> BattlegroupState:
|
|
||||||
data = self._request("GET", "/v0/battlegroup", timeout=15)
|
|
||||||
if isinstance(data, str):
|
|
||||||
data = json.loads(data)
|
|
||||||
return _parse_battlegroup(data)
|
|
||||||
|
|
||||||
def get_all_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_online_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/online")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_intransit_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/intransit")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_graceperiod_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/graceperiod")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_completion_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/completion")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
def get_queued_players(self) -> list[str]:
|
|
||||||
data = self._request("GET", "/v0/players/queued")
|
|
||||||
return data if isinstance(data, list) else []
|
|
||||||
|
|
||||||
# ── FLS Settings ───────────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_fls_settings(self) -> dict:
|
|
||||||
return self._request("GET", "/v0/BattlegroupFetchFlsReportSettings")
|
|
||||||
|
|
||||||
def update_fls_settings(self, settings: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateFlsReportSettings", data=settings, timeout=30)
|
|
||||||
|
|
||||||
def clear_fls_overrides(self) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearFlsReportOverrides", timeout=30)
|
|
||||||
|
|
||||||
# ── Server Config ──────────────────────────────────────────────
|
|
||||||
|
|
||||||
def update_server_config(self, config: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateServerGroupConfig", data=config, timeout=30)
|
|
||||||
|
|
||||||
def clear_map_config(self, map_name: str) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearMapConfigOverrides", data=map_name, timeout=30)
|
|
||||||
|
|
||||||
# ── Character Transfer ──────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_transfer_rules(self) -> dict:
|
|
||||||
return self._request("GET", "/v0/BattlegroupFetchCharacterTransferRules")
|
|
||||||
|
|
||||||
def update_transfer_settings(self, config: dict) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupUpdateCharacterTransferSettings", data=config, timeout=30)
|
|
||||||
|
|
||||||
def clear_transfer_overrides(self) -> str:
|
|
||||||
return self._request("POST", "/v0/BattlegroupClearCharacterTransferOverrides", timeout=30)
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
self.client.close()
|
|
||||||
|
|
||||||
|
|
||||||
class DirectorUnavailableError(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_battlegroup(data: dict) -> BattlegroupState:
|
|
||||||
"""Parse raw BGD JSON into BattlegroupState model."""
|
|
||||||
state = BattlegroupState()
|
|
||||||
|
|
||||||
for key in ["dimensionMaps", "singleServerMaps", "instancedMaps"]:
|
|
||||||
if key in data:
|
|
||||||
target = "dimension_maps" if key == "dimensionMaps" else "single_server_maps" if key == "singleServerMaps" else "instanced_maps"
|
|
||||||
for mg in data[key]:
|
|
||||||
group = {"name": mg.get("name", ""), "servers": []}
|
|
||||||
for sv in mg.get("servers", []):
|
|
||||||
sst = sv.get("lastServerState", {})
|
|
||||||
sgs = sst.get("serverGameplaySettings", {})
|
|
||||||
server = {
|
|
||||||
"partition": sv.get("partition", ""),
|
|
||||||
"ip": sv.get("ip", ""),
|
|
||||||
"game_port": sv.get("gamePort", 7777),
|
|
||||||
"num_players": sv.get("numPlayers", 0),
|
|
||||||
"status": sv.get("status", "unknown"),
|
|
||||||
"hydration": sgs.get("hydration", 1.0),
|
|
||||||
"sandstorm": sgs.get("sandstorm", False),
|
|
||||||
"sandworm": sgs.get("sandworm", True),
|
|
||||||
"pvp_enabled": sgs.get("pvpEnabled", False),
|
|
||||||
"mining_multiplier": sgs.get("miningMultiplier", 1.0),
|
|
||||||
"durability": sgs.get("durability", 1.0),
|
|
||||||
}
|
|
||||||
group["servers"].append(server)
|
|
||||||
getattr(state, target).append(group)
|
|
||||||
|
|
||||||
return state
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
# Character service — rename, delete, demo, cheater flags using DB functions.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class CharacterService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def rename(self, account_id: int, name: str) -> bool:
|
|
||||||
self.db.call_procedure("set_character_name", [account_id, name])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def delete_character(self, actor_id: int) -> bool:
|
|
||||||
self.db.call_procedure("delete_character", [actor_id])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def delete_account(self, user_id: str, reason: str = "admin") -> bool:
|
|
||||||
self.db.call_procedure("delete_account", [user_id, reason])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def set_demo(self, user_id: str, state: str) -> bool:
|
|
||||||
self.db.call_procedure("set_demo_state", [user_id, state])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def flag_cheater(self, account_id: int, cheat_type: str) -> bool:
|
|
||||||
self.db.call_procedure("flag_player_as_cheater", [account_id, cheat_type])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def get_tags(self, account_id: int) -> list[str]:
|
|
||||||
rows = self.db.call_function("admin_read_player_tags", [account_id])
|
|
||||||
return [r.get("tag", "") for r in rows if r.get("tag")]
|
|
||||||
|
|
||||||
def update_tags(self, account_id: int, add: list[str], remove: list[str]) -> bool:
|
|
||||||
# DB-ONLY direct SQL — no function exists for tag management
|
|
||||||
for tag in add:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"INSERT INTO dune.player_tags (account_id, tag) VALUES (%s, %s) ON CONFLICT DO NOTHING",
|
|
||||||
[account_id, tag],
|
|
||||||
)
|
|
||||||
if remove:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"DELETE FROM dune.player_tags WHERE account_id = %s AND tag = ANY(%s)",
|
|
||||||
[account_id, remove],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
# Chat service — chat history and log parsing.
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from datetime import datetime
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class ChatService:
|
|
||||||
def __init__(self, db: DatabaseService, k8s_service, ssh_service):
|
|
||||||
self.db = db
|
|
||||||
self.k8s = k8s_service
|
|
||||||
self.ssh = ssh_service
|
|
||||||
self.ensured_table = False
|
|
||||||
|
|
||||||
def ensure_history_table(self):
|
|
||||||
if self.ensured_table:
|
|
||||||
return True
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation("""
|
|
||||||
CREATE TABLE IF NOT EXISTS dashboard.chat_history (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
|
||||||
channel VARCHAR(50),
|
|
||||||
sender VARCHAR(255),
|
|
||||||
message TEXT,
|
|
||||||
target VARCHAR(255),
|
|
||||||
location_x FLOAT,
|
|
||||||
location_y FLOAT,
|
|
||||||
location_z FLOAT,
|
|
||||||
is_admin BOOLEAN DEFAULT FALSE
|
|
||||||
)
|
|
||||||
""")
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dashboard.chat_history (timestamp DESC)"
|
|
||||||
)
|
|
||||||
self.ensured_table = True
|
|
||||||
logger.info("Chat history table ready")
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to create chat history table: %s", e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
def save_message(self, channel, sender, message, target="", location=None, is_admin=False):
|
|
||||||
loc_x = location.get("X", 0) if location else 0
|
|
||||||
loc_y = location.get("Y", 0) if location else 0
|
|
||||||
loc_z = location.get("Z", 0) if location else 0
|
|
||||||
return self.db.execute_mutation(
|
|
||||||
"""INSERT INTO dashboard.chat_history
|
|
||||||
(channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
|
||||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)""",
|
|
||||||
[channel, sender, message, target, loc_x, loc_y, loc_z, is_admin],
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_history(self, limit: int = 200) -> list[dict]:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT id, timestamp, channel, sender, message, target,
|
|
||||||
location_x, location_y, location_z, is_admin
|
|
||||||
FROM dashboard.chat_history ORDER BY timestamp DESC LIMIT %s""",
|
|
||||||
[limit],
|
|
||||||
)
|
|
||||||
|
|
||||||
def catch_up(self, namespace: str) -> int:
|
|
||||||
db_messages = self.get_history(1)
|
|
||||||
has_history = db_messages and len(db_messages) >= 10
|
|
||||||
if has_history:
|
|
||||||
return 0
|
|
||||||
|
|
||||||
if not namespace:
|
|
||||||
logger.warning("Cannot catch up — kubernetes namespace not set")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
pod_name = self.k8s.get_text_router_pod()
|
|
||||||
if not pod_name:
|
|
||||||
logger.warning("Cannot catch up — no text-router pod found")
|
|
||||||
return 0
|
|
||||||
|
|
||||||
log_cmd = f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null"
|
|
||||||
out, err, rc = self.ssh.run(log_cmd, timeout=30)
|
|
||||||
if rc != 0 or not out:
|
|
||||||
logger.debug("Cannot catch up — failed to get pod logs (rc=%d)", rc)
|
|
||||||
return 0
|
|
||||||
|
|
||||||
lines = [line for line in out.split("\n") if "CLOG" in line and "TextChat" in line]
|
|
||||||
lines = [line for line in lines if "Starting filtering" not in line]
|
|
||||||
lines = [line for line in lines if "Skipping filtering" not in line]
|
|
||||||
lines = [line for line in lines if "Redirected message" not in line]
|
|
||||||
|
|
||||||
messages = []
|
|
||||||
seen = set()
|
|
||||||
for line in lines:
|
|
||||||
if not line.strip():
|
|
||||||
continue
|
|
||||||
try:
|
|
||||||
idx = line.index("received message from ")
|
|
||||||
rest = line[idx + len("received message from "):]
|
|
||||||
parts = rest.split(" to ", 1)
|
|
||||||
if len(parts) < 2:
|
|
||||||
continue
|
|
||||||
sender_id = parts[0].strip()
|
|
||||||
target_and_json = parts[1]
|
|
||||||
target_idx = target_and_json.index(": ")
|
|
||||||
target = target_and_json[:target_idx].strip()
|
|
||||||
msg_str = target_and_json[target_idx + 2:].strip()
|
|
||||||
|
|
||||||
msg_data = json.loads(msg_str)
|
|
||||||
content = json.loads(msg_data.get("content", "{}"))
|
|
||||||
|
|
||||||
dedup_key = (
|
|
||||||
content.get("m_ChannelType", ""),
|
|
||||||
content.get("m_FuncomIdFrom", ""),
|
|
||||||
content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
|
||||||
)
|
|
||||||
if dedup_key in seen:
|
|
||||||
continue
|
|
||||||
seen.add(dedup_key)
|
|
||||||
|
|
||||||
messages.append({
|
|
||||||
"channel": content.get("m_ChannelType", "Unknown"),
|
|
||||||
"sender": content.get("m_FuncomIdFrom", sender_id),
|
|
||||||
"message": content.get("m_Message", {}).get("m_UnlocalizedMessage", ""),
|
|
||||||
"target": target,
|
|
||||||
"location": content.get("m_OriginLocation", {}),
|
|
||||||
"is_admin": False,
|
|
||||||
})
|
|
||||||
except (ValueError, KeyError, json.JSONDecodeError, IndexError):
|
|
||||||
continue
|
|
||||||
|
|
||||||
if messages:
|
|
||||||
saved = self._save_batch(messages)
|
|
||||||
logger.info("Caught up %d chat messages from pod logs", saved)
|
|
||||||
return saved
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def _save_batch(self, messages: list[dict]) -> int:
|
|
||||||
if not messages:
|
|
||||||
return 0
|
|
||||||
count = 0
|
|
||||||
for msg in messages:
|
|
||||||
if self.save_message(
|
|
||||||
msg["channel"], msg["sender"], msg["message"],
|
|
||||||
msg.get("target", ""), msg.get("location"), msg.get("is_admin", False),
|
|
||||||
):
|
|
||||||
count += 1
|
|
||||||
return count
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
"""Database service — psycopg3 connection pool and stored procedure executor."""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import time
|
|
||||||
from typing import Any, List
|
|
||||||
|
|
||||||
import psycopg
|
|
||||||
from psycopg.rows import dict_row
|
|
||||||
from psycopg_pool import ConnectionPool
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class DatabaseService:
|
|
||||||
def __init__(self, db_config, min_conn=2, max_conn=10, dashboard_schema="dashboard"):
|
|
||||||
self.db_config = db_config
|
|
||||||
self.min_conn = min_conn
|
|
||||||
self.max_conn = max_conn
|
|
||||||
self.dashboard_schema = dashboard_schema
|
|
||||||
self.pool = None
|
|
||||||
|
|
||||||
def init_pool(self):
|
|
||||||
if self.pool is not None:
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
conninfo = (
|
|
||||||
f"host={self.db_config['host']} "
|
|
||||||
f"port={self.db_config['port']} "
|
|
||||||
f"dbname={self.db_config['database']} "
|
|
||||||
f"user={self.db_config['user']} "
|
|
||||||
f"password={self.db_config['password']}"
|
|
||||||
)
|
|
||||||
|
|
||||||
for attempt in range(10):
|
|
||||||
try:
|
|
||||||
self.pool = ConnectionPool(
|
|
||||||
conninfo=conninfo,
|
|
||||||
min_size=self.min_conn,
|
|
||||||
max_size=self.max_conn,
|
|
||||||
open=False,
|
|
||||||
)
|
|
||||||
self.pool.open(wait=True, timeout=20)
|
|
||||||
logger.info("Database connection pool initialized (psycopg3)")
|
|
||||||
return self.pool
|
|
||||||
except Exception as e:
|
|
||||||
if attempt < 9:
|
|
||||||
logger.warning(f"DB pool attempt {attempt + 1}/10 failed, retrying in 2s: {e}")
|
|
||||||
time.sleep(2)
|
|
||||||
else:
|
|
||||||
logger.error(f"Failed to initialize database pool after 10 attempts: {e}")
|
|
||||||
self.pool = None
|
|
||||||
return self.pool
|
|
||||||
|
|
||||||
def call_function(self, name: str, args: List[Any]) -> List[dict]:
|
|
||||||
"""Call a dune schema function and return rows as dicts."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
placeholders = ",".join(["%s"] * len(args))
|
|
||||||
sql = f"SELECT * FROM dune.{name}({placeholders})"
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
|
||||||
cur.execute(sql, args)
|
|
||||||
rows = cur.fetchall()
|
|
||||||
return rows if rows else []
|
|
||||||
|
|
||||||
def call_procedure(self, name: str, args: List[Any]) -> None:
|
|
||||||
"""Call a dune schema procedure (void return)."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
placeholders = ",".join(["%s"] * len(args))
|
|
||||||
sql = f"CALL dune.{name}({placeholders})"
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(sql, args)
|
|
||||||
conn.commit()
|
|
||||||
|
|
||||||
def execute_readonly(self, sql: str, params: List[Any] | None = None) -> List[dict]:
|
|
||||||
"""Execute a read-only SELECT query."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor(row_factory=dict_row) as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
rows = cur.fetchall()
|
|
||||||
return rows if rows else []
|
|
||||||
|
|
||||||
def execute_mutation(self, sql: str, params: List[Any] | None = None) -> int:
|
|
||||||
"""Execute a direct mutation (UPDATE/INSERT/DELETE) with validation."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
raise ConnectionError("Database pool not available")
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(sql, params or [])
|
|
||||||
conn.commit()
|
|
||||||
return cur.rowcount
|
|
||||||
|
|
||||||
def health_check(self) -> bool:
|
|
||||||
try:
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
return False
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute("SELECT 1")
|
|
||||||
cur.fetchone()
|
|
||||||
return True
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Database health check FAILED: {e}")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def ensure_tables(self):
|
|
||||||
"""Ensure dashboard schema tables exist."""
|
|
||||||
pool = self.init_pool()
|
|
||||||
if not pool:
|
|
||||||
return
|
|
||||||
|
|
||||||
schema = self.dashboard_schema
|
|
||||||
ddl = f"""
|
|
||||||
CREATE SCHEMA IF NOT EXISTS {schema};
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.audit_log (
|
|
||||||
id BIGSERIAL PRIMARY KEY,
|
|
||||||
action_type VARCHAR(50) NOT NULL,
|
|
||||||
user_name VARCHAR(100) NOT NULL,
|
|
||||||
target_player_id BIGINT,
|
|
||||||
details JSONB DEFAULT '{{}}',
|
|
||||||
source_ip INET,
|
|
||||||
severity VARCHAR(20) DEFAULT 'info',
|
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_created_at ON {schema}.audit_log (created_at DESC);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_action ON {schema}.audit_log (action_type);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_user ON {schema}.audit_log (user_name);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_ips (
|
|
||||||
player_id BIGINT PRIMARY KEY,
|
|
||||||
ip_address INET NOT NULL,
|
|
||||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.bans (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
player_id BIGINT UNIQUE,
|
|
||||||
account_id BIGINT,
|
|
||||||
reason TEXT DEFAULT '',
|
|
||||||
note TEXT DEFAULT '',
|
|
||||||
duration INT DEFAULT 0,
|
|
||||||
banned_at TIMESTAMP NOT NULL DEFAULT NOW(),
|
|
||||||
expires_at TIMESTAMP,
|
|
||||||
active BOOLEAN DEFAULT TRUE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.player_actions (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
player_id BIGINT NOT NULL,
|
|
||||||
action_type VARCHAR(50) NOT NULL,
|
|
||||||
reason TEXT DEFAULT '',
|
|
||||||
note TEXT DEFAULT '',
|
|
||||||
duration_minutes INT DEFAULT 0,
|
|
||||||
ip_address INET,
|
|
||||||
created_at TIMESTAMP NOT NULL DEFAULT NOW()
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.chat_history (
|
|
||||||
id SERIAL PRIMARY KEY,
|
|
||||||
timestamp TIMESTAMP DEFAULT NOW(),
|
|
||||||
channel VARCHAR(50),
|
|
||||||
sender VARCHAR(255),
|
|
||||||
message TEXT,
|
|
||||||
target VARCHAR(255),
|
|
||||||
location_x FLOAT,
|
|
||||||
location_y FLOAT,
|
|
||||||
location_z FLOAT,
|
|
||||||
is_admin BOOLEAN DEFAULT FALSE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON {schema}.chat_history (timestamp DESC);
|
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS {schema}.settings (
|
|
||||||
key VARCHAR(255) PRIMARY KEY,
|
|
||||||
value TEXT DEFAULT '',
|
|
||||||
updated_at TIMESTAMP DEFAULT NOW()
|
|
||||||
);
|
|
||||||
"""
|
|
||||||
|
|
||||||
with pool.connection() as conn:
|
|
||||||
with conn.cursor() as cur:
|
|
||||||
cur.execute(ddl)
|
|
||||||
conn.commit()
|
|
||||||
logger.info(f"Dashboard tables ensured in schema '{schema}'")
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
if self.pool:
|
|
||||||
try:
|
|
||||||
self.pool.close()
|
|
||||||
logger.info("Database pool closed")
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Error closing pool: {e}")
|
|
||||||
self.pool = None
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
# Economy service — items, currency, vitals, vendors. Uses direct SQL.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import Any
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class EconomyService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def get_inventory(self, account_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT it.id, it.item_name, it.quantity, it.durability
|
|
||||||
FROM dune.inventory_items it
|
|
||||||
WHERE it.account_id = %s
|
|
||||||
ORDER BY it.item_name""",
|
|
||||||
[account_id],
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_currency(self, player_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT currency_id, balance
|
|
||||||
FROM dune.player_currency
|
|
||||||
WHERE player_controller_id = %s""",
|
|
||||||
[player_id],
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_vitals(self, pawn_id: int) -> dict | None:
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(
|
|
||||||
"""SELECT current_health, max_health, current_stamina,
|
|
||||||
max_stamina, current_water, max_water,
|
|
||||||
current_oxygen, max_oxygen
|
|
||||||
FROM dune.player_state
|
|
||||||
WHERE player_pawn_id = %s
|
|
||||||
LIMIT 1""",
|
|
||||||
[pawn_id],
|
|
||||||
)
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def add_item(self, inventory_id: int, template_id: str, stack_size: int = 1, quality_level: int = 0) -> int:
|
|
||||||
sql = """INSERT INTO dune.inventory_items (inventory_id, template_id, quantity, quality_level)
|
|
||||||
VALUES (%s, %s, %s, %s) RETURNING id"""
|
|
||||||
rows = self.db.execute_mutation(sql, [inventory_id, template_id, stack_size, quality_level])
|
|
||||||
if rows and rows[0].get("id"):
|
|
||||||
return rows[0]["id"]
|
|
||||||
raise ValueError("Item add failed")
|
|
||||||
|
|
||||||
def delete_item(self, item_id: int) -> bool:
|
|
||||||
self.db.execute_mutation("DELETE FROM dune.inventory_items WHERE id = %s", [item_id])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def edit_item_field(self, item_id: int, field: str, value: Any) -> bool:
|
|
||||||
allowed = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
|
|
||||||
if field not in allowed:
|
|
||||||
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(allowed))}")
|
|
||||||
self.db.execute_mutation(
|
|
||||||
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
|
|
||||||
[value, item_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
@@ -1,123 +0,0 @@
|
|||||||
# Guild service — uses direct SQL matching old working dashboard.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"}
|
|
||||||
|
|
||||||
|
|
||||||
class GuildService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def list_all(self) -> list[dict]:
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
f.name as faction_name,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
LEFT JOIN dune.factions f ON g.faction_id = f.id
|
|
||||||
ORDER BY g.id
|
|
||||||
""")
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Guild list via faction join failed: {e}, trying fallback")
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
NULL as faction_name,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
ORDER BY g.id
|
|
||||||
""")
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_detail(self, guild_id: int) -> dict | None:
|
|
||||||
try:
|
|
||||||
guild_rows = self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
f.name as faction_name, g.faction_id as guild_faction,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
LEFT JOIN dune.factions f ON g.faction_id = f.id
|
|
||||||
WHERE g.id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
except Exception:
|
|
||||||
guild_rows = self.db.execute_readonly("""
|
|
||||||
SELECT g.id as guild_id, g.name as guild_name,
|
|
||||||
g.description as guild_description,
|
|
||||||
NULL as faction_name, NULL as guild_faction,
|
|
||||||
(SELECT COUNT(*) FROM dune.guild_members gm WHERE gm.guild_id = g.id) as member_count
|
|
||||||
FROM dune.guilds g
|
|
||||||
WHERE g.id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
|
|
||||||
if not guild_rows:
|
|
||||||
return None
|
|
||||||
|
|
||||||
g = guild_rows[0]
|
|
||||||
try:
|
|
||||||
member_rows = self.db.execute_readonly("""
|
|
||||||
SELECT gm.player_id, gm.role_id, ps.character_name as name,
|
|
||||||
ps.online_status::text as online_status
|
|
||||||
FROM dune.guild_members gm
|
|
||||||
LEFT JOIN dune.player_state ps ON gm.player_id = ps.player_controller_id
|
|
||||||
WHERE gm.guild_id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
except Exception:
|
|
||||||
member_rows = self.db.execute_readonly("""
|
|
||||||
SELECT gm.player_id, gm.role_id, NULL as name, NULL as online_status
|
|
||||||
FROM dune.guild_members gm
|
|
||||||
WHERE gm.guild_id = %s
|
|
||||||
""", [guild_id])
|
|
||||||
|
|
||||||
members = [{
|
|
||||||
"player_id": r.get("player_id"),
|
|
||||||
"role_id": r.get("role_id"),
|
|
||||||
"role_name": GUILD_ROLES.get(r.get("role_id", 50), "Member"),
|
|
||||||
"name": r.get("name") or "Unknown",
|
|
||||||
"online_status": r.get("online_status") or "Unknown",
|
|
||||||
} for r in (member_rows or [])]
|
|
||||||
|
|
||||||
return {
|
|
||||||
"guild_id": g.get("guild_id"),
|
|
||||||
"guild_name": g.get("guild_name", ""),
|
|
||||||
"guild_description": g.get("guild_description"),
|
|
||||||
"faction_name": g.get("faction_name"),
|
|
||||||
"faction_id": g.get("guild_faction"),
|
|
||||||
"members": members,
|
|
||||||
}
|
|
||||||
|
|
||||||
def disband(self, guild_id: int) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation("SELECT dune.disband_guild(%s)", [guild_id])
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def remove_member(self, guild_id: int, player_id: int, reason: int = 0) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"DELETE FROM dune.guild_members WHERE guild_id = %s AND player_id = %s",
|
|
||||||
[guild_id, player_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def promote(self, guild_id: int, player_id: int, role_id: int) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"UPDATE dune.guild_members SET role_id = %s WHERE guild_id = %s AND player_id = %s",
|
|
||||||
[role_id, guild_id, player_id],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
@@ -1,142 +0,0 @@
|
|||||||
"""Kubernetes service — kubectl operations via SSH."""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class K8sService:
|
|
||||||
def __init__(self, ssh_service, namespace):
|
|
||||||
self.ssh = ssh_service
|
|
||||||
self.namespace = namespace
|
|
||||||
|
|
||||||
def run(self, kubectl_command, timeout=30):
|
|
||||||
full_cmd = f"sudo kubectl {kubectl_command} -n {self.namespace}"
|
|
||||||
logger.debug("K8s executing: %s", full_cmd)
|
|
||||||
result = self.ssh.run(full_cmd, timeout=timeout)
|
|
||||||
out, err, rc = result
|
|
||||||
if rc != 0:
|
|
||||||
logger.debug("K8s command failed (rc=%d): %s", rc, err[:100] if err else "no error")
|
|
||||||
else:
|
|
||||||
logger.debug("K8s command OK, output lines: %d", len(out.split("\n")) if out else 0)
|
|
||||||
return result
|
|
||||||
|
|
||||||
def get_pods(self):
|
|
||||||
out, err, rc = self.run("get pods -o json")
|
|
||||||
if rc != 0:
|
|
||||||
logger.error("Failed to get pods: %s", err)
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
import json
|
|
||||||
data = json.loads(out or "{}")
|
|
||||||
items = data.get("items", [])
|
|
||||||
pods = []
|
|
||||||
for item in items:
|
|
||||||
metadata = item.get("metadata", {})
|
|
||||||
status = item.get("status", {})
|
|
||||||
container_statuses = status.get("containerStatuses", [])
|
|
||||||
restarts = sum(c.get("restartCount", 0) for c in container_statuses)
|
|
||||||
pods.append({
|
|
||||||
"name": metadata.get("name", ""),
|
|
||||||
"namespace": metadata.get("namespace", self.namespace),
|
|
||||||
"status": status.get("phase", "Unknown"),
|
|
||||||
"restarts": restarts,
|
|
||||||
"age": self._age_from_creation(metadata.get("creationTimestamp")),
|
|
||||||
})
|
|
||||||
logger.debug("Found %d pods in namespace %s", len(pods), self.namespace)
|
|
||||||
return pods
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to parse pods: %s", e)
|
|
||||||
return []
|
|
||||||
|
|
||||||
def find_pod_by_pattern(self, pattern):
|
|
||||||
pods = self.get_pods()
|
|
||||||
for pod in pods:
|
|
||||||
if pattern.lower() in pod.lower():
|
|
||||||
return pod
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_text_router_pod(self):
|
|
||||||
pod = self.find_pod_by_pattern("tr-deploy")
|
|
||||||
if pod:
|
|
||||||
return pod
|
|
||||||
pod = self.find_pod_by_pattern("text")
|
|
||||||
if pod:
|
|
||||||
return pod
|
|
||||||
return self.find_pod_by_pattern("router")
|
|
||||||
|
|
||||||
def get_rabbitmq_pod(self, admin=True):
|
|
||||||
if admin:
|
|
||||||
return self.find_pod_by_pattern("mq-admin")
|
|
||||||
return self.find_pod_by_pattern("mq-game")
|
|
||||||
|
|
||||||
def get_filebrowser_pod(self):
|
|
||||||
return self.find_pod_by_pattern("fb-deploy")
|
|
||||||
|
|
||||||
def get_deployments(self):
|
|
||||||
out, err, rc = self.run("get deployments -o json")
|
|
||||||
if rc != 0:
|
|
||||||
return []
|
|
||||||
try:
|
|
||||||
import json
|
|
||||||
data = json.loads(out or "{}")
|
|
||||||
items = data.get("items", [])
|
|
||||||
deployments = []
|
|
||||||
for item in items:
|
|
||||||
metadata = item.get("metadata", {})
|
|
||||||
spec = item.get("spec", {})
|
|
||||||
status = item.get("status", {})
|
|
||||||
deployments.append({
|
|
||||||
"name": metadata.get("name", ""),
|
|
||||||
"namespace": metadata.get("namespace", self.namespace),
|
|
||||||
"replicas": spec.get("replicas", 0),
|
|
||||||
"available": status.get("availableReplicas", 0),
|
|
||||||
})
|
|
||||||
return deployments
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Failed to parse deployments: %s", e)
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_node_metrics(self):
|
|
||||||
out, err, rc = self.run("top nodes")
|
|
||||||
if rc == 0 and out.strip():
|
|
||||||
lines = out.strip().split("\n")
|
|
||||||
if len(lines) >= 2:
|
|
||||||
parts = lines[1].split()
|
|
||||||
if len(parts) >= 4:
|
|
||||||
return {
|
|
||||||
"cpu": parts[2],
|
|
||||||
"memory": parts[3],
|
|
||||||
"cpu_pct": parts[1],
|
|
||||||
}
|
|
||||||
return {}
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def _age_from_creation(timestamp: str | None) -> str:
|
|
||||||
if not timestamp:
|
|
||||||
return "Unknown"
|
|
||||||
from datetime import datetime, timezone
|
|
||||||
try:
|
|
||||||
created = datetime.fromisoformat(timestamp.replace("Z", "+00:00"))
|
|
||||||
delta = datetime.now(timezone.utc) - created
|
|
||||||
days = delta.days
|
|
||||||
hours = delta.seconds // 3600
|
|
||||||
minutes = (delta.seconds % 3600) // 60
|
|
||||||
if days > 0:
|
|
||||||
return f"{days}d"
|
|
||||||
if hours > 0:
|
|
||||||
return f"{hours}h"
|
|
||||||
return f"{minutes}m"
|
|
||||||
except Exception:
|
|
||||||
return "Unknown"
|
|
||||||
|
|
||||||
def auto_detect_namespace(self):
|
|
||||||
out, err, rc = self.ssh.run("sudo kubectl get namespaces -o name", timeout=10)
|
|
||||||
if rc == 0:
|
|
||||||
for line in (out or "").strip().split("\n"):
|
|
||||||
ns = line.replace("namespace/", "").strip()
|
|
||||||
if ns.startswith("funcom-seabass-"):
|
|
||||||
logger.info("Auto-detected K8s namespace: %s", ns)
|
|
||||||
self.namespace = ns
|
|
||||||
return ns
|
|
||||||
return None
|
|
||||||
@@ -1,231 +0,0 @@
|
|||||||
# Player service — uses direct SQL queries matching the old working dashboard.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
from typing import List, Any
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
LIKE_PC = '%DunePlayerCharacter_C'
|
|
||||||
|
|
||||||
|
|
||||||
class PlayerService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def search(self, term: str, limit: int = 50) -> list[dict]:
|
|
||||||
where = "a.class LIKE %s"
|
|
||||||
params: list[Any] = [LIKE_PC]
|
|
||||||
if term:
|
|
||||||
where += """ AND (
|
|
||||||
ps.character_name ILIKE %s
|
|
||||||
OR acc.funcom_id ILIKE %s
|
|
||||||
OR ea.user ILIKE %s
|
|
||||||
)"""
|
|
||||||
params.extend([f'%{term}%'] * 3)
|
|
||||||
|
|
||||||
sql = f"""
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
|
|
||||||
ps.life_state, acc.funcom_id, ps.account_id,
|
|
||||||
a.map, a.id as actor_id,
|
|
||||||
pf.faction_id, f.name as faction_name,
|
|
||||||
acc.last_login as last_login_time
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.player_state ps ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
|
|
||||||
LEFT JOIN dune.actor_faction af ON a.id = af.actor_id
|
|
||||||
LEFT JOIN dune.factions f ON af.faction_id = f.id
|
|
||||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
|
|
||||||
LEFT JOIN dune.entity_actors ea ON a.owner_id = ea.id
|
|
||||||
LEFT JOIN dune.accounts acc ON ea.id = acc.id
|
|
||||||
WHERE {where}
|
|
||||||
ORDER BY ps.character_name
|
|
||||||
LIMIT %s
|
|
||||||
"""
|
|
||||||
params.append(limit)
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Player search via actor join failed: {e}, trying fallback")
|
|
||||||
return self._search_fallback(term, limit)
|
|
||||||
|
|
||||||
def _search_fallback(self, term: str, limit: int = 50) -> list[dict]:
|
|
||||||
"""Fallback using only player_state and accounts."""
|
|
||||||
where = "1=1"
|
|
||||||
params: list[Any] = []
|
|
||||||
if term:
|
|
||||||
where = """(
|
|
||||||
ps.character_name ILIKE %s
|
|
||||||
OR acc.funcom_id ILIKE %s
|
|
||||||
)"""
|
|
||||||
params = [f'%{term}%', f'%{term}%']
|
|
||||||
sql = f"""
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.character_name, ps.online_status::text as online_status,
|
|
||||||
ps.life_state, acc.funcom_id, ps.account_id,
|
|
||||||
NULL as map, NULL as actor_id,
|
|
||||||
NULL as faction_id, NULL as faction_name,
|
|
||||||
NULL as last_login_time
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
WHERE {where}
|
|
||||||
ORDER BY ps.character_name
|
|
||||||
LIMIT %s
|
|
||||||
"""
|
|
||||||
params.append(limit)
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, params)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("Player search fallback failed")
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_detail(self, account_id: int) -> dict | None:
|
|
||||||
sql = """
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
|
|
||||||
ps.online_status::text as online_status, ps.life_state,
|
|
||||||
ps.account_id, acc.funcom_id, acc.email as account_email,
|
|
||||||
a.map, a.id as actor_id,
|
|
||||||
f.name as faction_name, pf.faction_id,
|
|
||||||
acc.last_login as last_login_time,
|
|
||||||
ps.current_health, ps.max_health,
|
|
||||||
ps.current_stamina, ps.max_stamina,
|
|
||||||
ps.current_water, ps.max_water,
|
|
||||||
ps.current_oxygen, ps.max_oxygen,
|
|
||||||
ps.xp, ps.tech_knowledge
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
LEFT JOIN dune.actors a ON (a.properties->>'m_PlayerControllerId')::bigint = ps.player_controller_id
|
|
||||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.player_controller_id
|
|
||||||
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
|
||||||
WHERE ps.account_id = %s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(sql, [account_id])
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning(f"Player detail via actor failed: {e}, trying fallback")
|
|
||||||
return self._get_detail_fallback(account_id)
|
|
||||||
|
|
||||||
def _get_detail_fallback(self, account_id: int) -> dict | None:
|
|
||||||
sql = """
|
|
||||||
SELECT
|
|
||||||
ps.player_controller_id, ps.player_pawn_id, ps.character_name,
|
|
||||||
ps.online_status::text as online_status, ps.life_state,
|
|
||||||
ps.account_id, acc.funcom_id, acc.email as account_email,
|
|
||||||
NULL as map, NULL as actor_id,
|
|
||||||
NULL as faction_name, NULL as faction_id,
|
|
||||||
NULL as last_login_time,
|
|
||||||
NULL as current_health, NULL as max_health,
|
|
||||||
NULL as current_stamina, NULL as max_stamina,
|
|
||||||
NULL as current_water, NULL as max_water,
|
|
||||||
NULL as current_oxygen, NULL as max_oxygen,
|
|
||||||
NULL as xp, NULL as tech_knowledge
|
|
||||||
FROM dune.player_state ps
|
|
||||||
LEFT JOIN dune.accounts acc ON ps.account_id = acc.id
|
|
||||||
WHERE ps.account_id = %s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(sql, [account_id])
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_inventory(self, account_id: int) -> list[dict]:
|
|
||||||
"""Get player inventory items."""
|
|
||||||
sql = """
|
|
||||||
SELECT it.id, it.item_name, it.quantity, it.durability
|
|
||||||
FROM dune.inventory_items it
|
|
||||||
WHERE it.account_id = %s
|
|
||||||
ORDER BY it.item_name
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, [account_id])
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_currency(self, player_id: int) -> list[dict]:
|
|
||||||
"""Get player currency balances."""
|
|
||||||
sql = """
|
|
||||||
SELECT currency_id, balance
|
|
||||||
FROM dune.player_currency
|
|
||||||
WHERE player_controller_id = %s
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
return self.db.execute_readonly(sql, [player_id])
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_vitals(self, player_id: int) -> dict | None:
|
|
||||||
"""Get player vitals."""
|
|
||||||
sql = """
|
|
||||||
SELECT current_health, max_health, current_stamina, max_stamina,
|
|
||||||
current_water, max_water, current_oxygen, max_oxygen
|
|
||||||
FROM dune.player_state
|
|
||||||
WHERE player_controller_id = %s
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
try:
|
|
||||||
rows = self.db.execute_readonly(sql, [player_id])
|
|
||||||
return rows[0] if rows else None
|
|
||||||
except Exception:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_landsraad(self, player_id: int) -> dict | None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_faction_reputation(self, player_id: int) -> list[dict]:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_vehicles(self, player_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
sql = """
|
|
||||||
SELECT a.id, a.class, a.map
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.vehicle_instances vi ON a.id = vi.actor_id
|
|
||||||
WHERE vi.owner_id = %s
|
|
||||||
"""
|
|
||||||
return self.db.execute_readonly(sql, [player_id])
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_buildings(self, pawn_id: int) -> list[dict]:
|
|
||||||
try:
|
|
||||||
sql = """
|
|
||||||
SELECT a.id, a.class, a.map,
|
|
||||||
a.properties->>'m_bIsPowered' as is_powered,
|
|
||||||
a.properties->>'m_PowerLevel' as power_level
|
|
||||||
FROM dune.actors a
|
|
||||||
JOIN dune.buildings b ON a.id = b.id
|
|
||||||
WHERE b.owner_id = %s
|
|
||||||
"""
|
|
||||||
return self.db.execute_readonly(sql, [pawn_id])
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_landclaims(self, account_id: int) -> list[dict]:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def get_specialization(self, player_id: int) -> dict | None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_keystones(self, player_id: int) -> dict | None:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def get_tags(self, account_id: int) -> list[str]:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def is_online(self, player_id: int) -> bool:
|
|
||||||
try:
|
|
||||||
sql = """
|
|
||||||
SELECT 1 FROM dune.player_state
|
|
||||||
WHERE player_controller_id = %s AND online_status::text = 'Online'
|
|
||||||
LIMIT 1
|
|
||||||
"""
|
|
||||||
rows = self.db.execute_readonly(sql, [player_id])
|
|
||||||
return len(rows) > 0
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
@@ -1,32 +0,0 @@
|
|||||||
# Progression service — journey and specialization using DB functions.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class ProgressionService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def complete_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
|
||||||
self.db.call_procedure("complete_journey_story_nodes_for_player", [player_id, node_ids])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def reveal_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
|
||||||
self.db.call_procedure("reveal_journey_story_nodes_for_player", [player_id, node_ids])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def reset_nodes(self, player_id: str, node_ids: list[str]) -> bool:
|
|
||||||
self.db.call_procedure("delete_journey_story_nodes_for_player", [player_id, node_ids])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def set_specialization(self, player_id: int, track_type: str, xp: int, level: float) -> bool:
|
|
||||||
self.db.call_procedure("set_specialization_xp_and_level", [player_id, track_type, xp, level])
|
|
||||||
return True
|
|
||||||
|
|
||||||
def reset_specializations(self, player_id: int) -> bool:
|
|
||||||
self.db.call_procedure("reset_specialization_tracks", [player_id])
|
|
||||||
return True
|
|
||||||
@@ -1,164 +0,0 @@
|
|||||||
"""Realtime service — SSE broadcaster + BGD/RMQ poller."""
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
import threading
|
|
||||||
import time
|
|
||||||
from typing import Any, Callable, Dict, Set
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class SseClient:
|
|
||||||
"""Simple wrapper for an SSE client connection."""
|
|
||||||
def __init__(self, queue: asyncio.Queue):
|
|
||||||
self.queue = queue
|
|
||||||
self.connected_at = time.time()
|
|
||||||
|
|
||||||
|
|
||||||
class RealtimeService:
|
|
||||||
def __init__(self, bg_director, rmq_admin, chat_service):
|
|
||||||
self.bg_director = bg_director
|
|
||||||
self.rmq_admin = rmq_admin
|
|
||||||
self.chat_service = chat_service
|
|
||||||
self._clients: Set[asyncio.Queue] = set()
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
self._previous_bg: dict | None = None
|
|
||||||
self._running = False
|
|
||||||
self._bgd_task = None
|
|
||||||
self._rmq_task = None
|
|
||||||
|
|
||||||
# ── Client Management ─────────────────────────────────────────
|
|
||||||
|
|
||||||
def add_client(self, queue: asyncio.Queue):
|
|
||||||
with self._lock:
|
|
||||||
self._clients.add(queue)
|
|
||||||
logger.debug("SSE client added. Total: %d", len(self._clients))
|
|
||||||
|
|
||||||
def remove_client(self, queue: asyncio.Queue):
|
|
||||||
with self._lock:
|
|
||||||
self._clients.discard(queue)
|
|
||||||
logger.debug("SSE client removed. Total: %d", len(self._clients))
|
|
||||||
|
|
||||||
async def _broadcast(self, event: str, data: dict):
|
|
||||||
"""Broadcast an event to all connected SSE clients."""
|
|
||||||
payload = f"event: {event}\ndata: {json.dumps(data)}\n\n"
|
|
||||||
with self._lock:
|
|
||||||
dead = set()
|
|
||||||
for queue in self._clients:
|
|
||||||
try:
|
|
||||||
queue.put_nowait(payload)
|
|
||||||
except asyncio.QueueFull:
|
|
||||||
dead.add(queue)
|
|
||||||
except Exception:
|
|
||||||
dead.add(queue)
|
|
||||||
self._clients -= dead
|
|
||||||
|
|
||||||
# ── Background Polling ──────────────────────────────────────
|
|
||||||
|
|
||||||
def start(self):
|
|
||||||
if self._running:
|
|
||||||
return
|
|
||||||
self._running = True
|
|
||||||
self._bgd_task = threading.Thread(target=self._bgd_poll_loop, daemon=True)
|
|
||||||
self._bgd_task.start()
|
|
||||||
self._rmq_task = threading.Thread(target=self._rmq_poll_loop, daemon=True)
|
|
||||||
self._rmq_task.start()
|
|
||||||
logger.info("RealtimeService started")
|
|
||||||
|
|
||||||
def stop(self):
|
|
||||||
self._running = False
|
|
||||||
logger.info("RealtimeService stopped")
|
|
||||||
|
|
||||||
def _bgd_poll_loop(self):
|
|
||||||
"""Poll BGD every 10 seconds and broadcast deltas."""
|
|
||||||
while self._running:
|
|
||||||
try:
|
|
||||||
bg = self.bg_director.get_battlegroup()
|
|
||||||
current = bg.model_dump() if hasattr(bg, "model_dump") else bg.__dict__
|
|
||||||
delta = self._compute_bg_delta(self._previous_bg, current)
|
|
||||||
if delta:
|
|
||||||
asyncio.run(self._broadcast("battlegroup_update", delta))
|
|
||||||
self._previous_bg = current
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("BGD poll failed: %s", e)
|
|
||||||
asyncio.run(self._broadcast("connection_status", {"bgd": False}))
|
|
||||||
time.sleep(10)
|
|
||||||
|
|
||||||
def _rmq_poll_loop(self):
|
|
||||||
"""Poll RMQ every 30 seconds and broadcast health."""
|
|
||||||
while self._running:
|
|
||||||
try:
|
|
||||||
overview = self.rmq_admin.get_overview()
|
|
||||||
data = {
|
|
||||||
"cluster_name": overview.cluster_name,
|
|
||||||
"queue_totals": overview.queue_totals,
|
|
||||||
"message_stats": overview.message_stats,
|
|
||||||
}
|
|
||||||
asyncio.run(self._broadcast("rmq_health", data))
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("RMQ poll failed: %s", e)
|
|
||||||
asyncio.run(self._broadcast("connection_status", {"rmq": False}))
|
|
||||||
time.sleep(30)
|
|
||||||
|
|
||||||
def _compute_bg_delta(self, previous: dict | None, current: dict) -> dict | None:
|
|
||||||
"""Compute meaningful deltas between battlegroup states."""
|
|
||||||
if not previous:
|
|
||||||
return {
|
|
||||||
"online_count": self._count_online(current),
|
|
||||||
"intransit_count": len(current.get("intransit_players", [])),
|
|
||||||
"server_statuses": self._extract_server_statuses(current),
|
|
||||||
"map_counts": self._extract_map_counts(current),
|
|
||||||
}
|
|
||||||
|
|
||||||
prev_online = self._count_online(previous)
|
|
||||||
curr_online = self._count_online(current)
|
|
||||||
prev_statuses = self._extract_server_statuses(previous)
|
|
||||||
curr_statuses = self._extract_server_statuses(current)
|
|
||||||
|
|
||||||
delta = {}
|
|
||||||
if curr_online != prev_online:
|
|
||||||
delta["online_count"] = curr_online
|
|
||||||
if len(current.get("intransit_players", [])) != len(previous.get("intransit_players", [])):
|
|
||||||
delta["intransit_count"] = len(current.get("intransit_players", []))
|
|
||||||
if curr_statuses != prev_statuses:
|
|
||||||
delta["server_statuses"] = curr_statuses
|
|
||||||
|
|
||||||
return delta if delta else None
|
|
||||||
|
|
||||||
def _count_online(self, state: dict) -> int:
|
|
||||||
return len(state.get("online_players", []))
|
|
||||||
|
|
||||||
def _extract_server_statuses(self, state: dict) -> dict:
|
|
||||||
statuses = {}
|
|
||||||
for key in ["dimension_maps", "single_server_maps", "instanced_maps"]:
|
|
||||||
for mg in state.get(key, []):
|
|
||||||
for sv in mg.get("servers", []):
|
|
||||||
partition = sv.get("partition", "")
|
|
||||||
if partition:
|
|
||||||
statuses[partition] = sv.get("status", "unknown")
|
|
||||||
return statuses
|
|
||||||
|
|
||||||
def _extract_map_counts(self, state: dict) -> dict:
|
|
||||||
counts = {}
|
|
||||||
for key in ["dimension_maps", "single_server_maps", "instanced_maps"]:
|
|
||||||
for mg in state.get(key, []):
|
|
||||||
name = mg.get("name", "")
|
|
||||||
if name:
|
|
||||||
counts[name] = sum(sv.get("num_players", 0) for sv in mg.get("servers", []))
|
|
||||||
return counts
|
|
||||||
|
|
||||||
# ── Event Helpers ───────────────────────────────────────────
|
|
||||||
|
|
||||||
async def notify_chat_message(self, msg: dict):
|
|
||||||
await self._broadcast("chat_message", msg)
|
|
||||||
|
|
||||||
async def notify_server_event(self, event: dict):
|
|
||||||
await self._broadcast("server_event", event)
|
|
||||||
|
|
||||||
async def notify_player_event(self, event: dict):
|
|
||||||
await self._broadcast("player_event", event)
|
|
||||||
|
|
||||||
async def notify_connection_status(self, status: dict):
|
|
||||||
await self._broadcast("connection_status", status)
|
|
||||||
@@ -1,146 +0,0 @@
|
|||||||
"""RabbitMQ Admin Management HTTP API client."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
from typing import Any, Dict, List
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
from app.models import RmqOverview, RmqQueueInfo
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class RmqAdminService:
|
|
||||||
def __init__(self, host: str, port: int, username: str, password: str):
|
|
||||||
self.base_url = f"http://{host}:{port}"
|
|
||||||
self.auth = (username, password)
|
|
||||||
self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15)
|
|
||||||
logger.debug("RmqAdminService initialized: %s", self.base_url)
|
|
||||||
|
|
||||||
def _get(self, path: str) -> dict | list:
|
|
||||||
try:
|
|
||||||
resp = self.client.get(path)
|
|
||||||
resp.raise_for_status()
|
|
||||||
return resp.json()
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("RMQ Admin GET %s failed: %s", path, e)
|
|
||||||
raise RmqError(f"RMQ Admin HTTP {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("RMQ Admin connection failed: %s", e)
|
|
||||||
raise RmqError("Cannot connect to RMQ Admin API")
|
|
||||||
|
|
||||||
def _post(self, path: str, data: dict) -> dict:
|
|
||||||
try:
|
|
||||||
resp = self.client.post(path, json=data)
|
|
||||||
resp.raise_for_status()
|
|
||||||
return resp.json()
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("RMQ Admin POST %s failed: %s", path, e)
|
|
||||||
raise RmqError(f"RMQ Admin HTTP {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("RMQ Admin connection failed: %s", e)
|
|
||||||
raise RmqError("Cannot connect to RMQ Admin API")
|
|
||||||
|
|
||||||
# ── Overview & Health ───────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_overview(self) -> RmqOverview:
|
|
||||||
data = self._get("/api/overview")
|
|
||||||
return RmqOverview(
|
|
||||||
cluster_name=data.get("cluster_name", ""),
|
|
||||||
node=data.get("node", ""),
|
|
||||||
message_stats=data.get("message_stats", {}),
|
|
||||||
queue_totals=data.get("queue_totals", {}),
|
|
||||||
object_totals=data.get("object_totals", {}),
|
|
||||||
)
|
|
||||||
|
|
||||||
def get_nodes(self) -> list[dict]:
|
|
||||||
return self._get("/api/nodes")
|
|
||||||
|
|
||||||
def health_check(self) -> dict:
|
|
||||||
return self._get("/api/health/checks/alarms")
|
|
||||||
|
|
||||||
# ── Exchanges & Queues ────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_exchanges(self) -> list[dict]:
|
|
||||||
return self._get("/api/exchanges")
|
|
||||||
|
|
||||||
def get_queues(self) -> list[dict]:
|
|
||||||
return self._get("/api/queues")
|
|
||||||
|
|
||||||
def get_queue_info(self, name: str) -> dict:
|
|
||||||
return self._get(f"/api/queues/%2f/{name}")
|
|
||||||
|
|
||||||
def get_bindings(self) -> list[dict]:
|
|
||||||
return self._get("/api/bindings")
|
|
||||||
|
|
||||||
def get_consumers(self) -> list[dict]:
|
|
||||||
return self._get("/api/consumers")
|
|
||||||
|
|
||||||
def get_connections(self) -> list[dict]:
|
|
||||||
return self._get("/api/connections")
|
|
||||||
|
|
||||||
def get_channels(self) -> list[dict]:
|
|
||||||
return self._get("/api/channels")
|
|
||||||
|
|
||||||
# ── Publish / Consume ─────────────────────────────────────────
|
|
||||||
|
|
||||||
def publish(
|
|
||||||
self,
|
|
||||||
exchange: str,
|
|
||||||
routing_key: str,
|
|
||||||
payload: str | dict,
|
|
||||||
payload_encoding: str = "string",
|
|
||||||
properties: dict | None = None,
|
|
||||||
) -> bool:
|
|
||||||
body_payload = payload if isinstance(payload, str) else json.dumps(payload)
|
|
||||||
body = {
|
|
||||||
"routing_key": routing_key,
|
|
||||||
"payload": body_payload,
|
|
||||||
"payload_encoding": payload_encoding,
|
|
||||||
}
|
|
||||||
if properties:
|
|
||||||
body["properties"] = properties
|
|
||||||
result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body)
|
|
||||||
return result.get("routed", False)
|
|
||||||
|
|
||||||
def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]:
|
|
||||||
body = {"count": count, "ackmode": ackmode, "encoding": "auto"}
|
|
||||||
return self._post(f"/api/queues/%2f/{queue}/get", body)
|
|
||||||
|
|
||||||
def get_exchange_bindings(self, exchange: str) -> list[dict]:
|
|
||||||
return self._get(f"/api/exchanges/%2f/{exchange}/bindings/source")
|
|
||||||
|
|
||||||
def get_queue_bindings(self, queue: str) -> list[dict]:
|
|
||||||
return self._get(f"/api/queues/%2f/{queue}/bindings")
|
|
||||||
|
|
||||||
# ── Helpers ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_queue_depths(self) -> list[RmqQueueInfo]:
|
|
||||||
queues = self.get_queues()
|
|
||||||
return [
|
|
||||||
RmqQueueInfo(
|
|
||||||
name=q.get("name", ""),
|
|
||||||
messages_ready=q.get("messages_ready", 0),
|
|
||||||
messages_unacknowledged=q.get("messages_unacknowledged", 0),
|
|
||||||
consumer_count=q.get("consumers", 0),
|
|
||||||
state=q.get("state", ""),
|
|
||||||
)
|
|
||||||
for q in queues
|
|
||||||
]
|
|
||||||
|
|
||||||
def publish_settings_update(self, payload: dict) -> bool:
|
|
||||||
"""Publish to the settingsUpdate fanout exchange."""
|
|
||||||
return self.publish(
|
|
||||||
exchange="settingsUpdate",
|
|
||||||
routing_key="",
|
|
||||||
payload=json.dumps(payload),
|
|
||||||
properties={"content_type": "application/json"},
|
|
||||||
)
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
self.client.close()
|
|
||||||
|
|
||||||
|
|
||||||
class RmqError(Exception):
|
|
||||||
pass
|
|
||||||
@@ -1,126 +0,0 @@
|
|||||||
"""RabbitMQ Game Management HTTP API client."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
import logging
|
|
||||||
|
|
||||||
import httpx
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class RmqGameService:
|
|
||||||
def __init__(self, host: str, port: int, username: str, password: str):
|
|
||||||
self.base_url = f"http://{host}:{port}"
|
|
||||||
self.auth = (username, password)
|
|
||||||
self.client = httpx.Client(base_url=self.base_url, auth=self.auth, timeout=15)
|
|
||||||
logger.debug("RmqGameService initialized: %s", self.base_url)
|
|
||||||
|
|
||||||
def _get(self, path: str) -> dict | list:
|
|
||||||
try:
|
|
||||||
resp = self.client.get(path)
|
|
||||||
resp.raise_for_status()
|
|
||||||
return resp.json()
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("RMQ Game GET %s failed: %s", path, e)
|
|
||||||
raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("RMQ Game connection failed: %s", e)
|
|
||||||
raise RmqGameError("Cannot connect to RMQ Game API")
|
|
||||||
|
|
||||||
def _post(self, path: str, data: dict) -> dict:
|
|
||||||
try:
|
|
||||||
resp = self.client.post(path, json=data)
|
|
||||||
resp.raise_for_status()
|
|
||||||
return resp.json()
|
|
||||||
except httpx.HTTPStatusError as e:
|
|
||||||
logger.error("RMQ Game POST %s failed: %s", path, e)
|
|
||||||
raise RmqGameError(f"RMQ Game HTTP {e.response.status_code}")
|
|
||||||
except httpx.ConnectError as e:
|
|
||||||
logger.error("RMQ Game connection failed: %s", e)
|
|
||||||
raise RmqGameError("Cannot connect to RMQ Game API")
|
|
||||||
|
|
||||||
# ── Overview ──────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def get_overview(self) -> dict:
|
|
||||||
return self._get("/api/overview")
|
|
||||||
|
|
||||||
def get_exchanges(self) -> list[dict]:
|
|
||||||
return self._get("/api/exchanges")
|
|
||||||
|
|
||||||
def get_queues(self) -> list[dict]:
|
|
||||||
return self._get("/api/queues")
|
|
||||||
|
|
||||||
# ── Publish ───────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def publish(
|
|
||||||
self,
|
|
||||||
exchange: str,
|
|
||||||
routing_key: str,
|
|
||||||
payload: str | dict,
|
|
||||||
payload_encoding: str = "string",
|
|
||||||
properties: dict | None = None,
|
|
||||||
) -> bool:
|
|
||||||
body_payload = payload if isinstance(payload, str) else json.dumps(payload)
|
|
||||||
body = {
|
|
||||||
"routing_key": routing_key,
|
|
||||||
"payload": body_payload,
|
|
||||||
"payload_encoding": payload_encoding,
|
|
||||||
}
|
|
||||||
if properties:
|
|
||||||
body["properties"] = properties
|
|
||||||
result = self._post(f"/api/exchanges/%2f/{exchange}/publish", body)
|
|
||||||
return result.get("routed", False)
|
|
||||||
|
|
||||||
def peek_messages(self, queue: str, count: int = 5, ackmode: str = "ack_requeue_true") -> list[dict]:
|
|
||||||
body = {"count": count, "ackmode": ackmode, "encoding": "auto"}
|
|
||||||
return self._post(f"/api/queues/%2f/{queue}/get", body)
|
|
||||||
|
|
||||||
# ── Broadcast ─────────────────────────────────────────────────
|
|
||||||
|
|
||||||
def send_broadcast(self, message: str, title: str = "", duration: int = 30, server: str | None = None, partition: str | None = None) -> bool:
|
|
||||||
"""Send an in-game broadcast via the heartbeats exchange."""
|
|
||||||
display_title = title or "Admin Broadcast"
|
|
||||||
inner = {
|
|
||||||
"ServerCommand": "ServiceBroadcast",
|
|
||||||
"BroadcastType": "Generic",
|
|
||||||
"BroadcastPayload": {
|
|
||||||
"BroadcastDuration": duration,
|
|
||||||
"LocalizedText": [
|
|
||||||
{"Key": "en", "Title": display_title, "Body": message},
|
|
||||||
{"Key": "en-US", "Title": display_title, "Body": message},
|
|
||||||
],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
body = {
|
|
||||||
"Version": 2,
|
|
||||||
"AuthToken": "Nu6VmPWUMvdPMeB7qErr",
|
|
||||||
"MessageContent": inner,
|
|
||||||
}
|
|
||||||
return self.publish(
|
|
||||||
exchange="heartbeats",
|
|
||||||
routing_key="notifications",
|
|
||||||
payload=json.dumps(body),
|
|
||||||
payload_encoding="string",
|
|
||||||
properties={
|
|
||||||
"content_type": "application/json",
|
|
||||||
"message_id": f"manual-service-broadcast-{int(time.time() * 1000)}",
|
|
||||||
"app_id": "fls",
|
|
||||||
"user_id": "fls_backend",
|
|
||||||
},
|
|
||||||
)
|
|
||||||
|
|
||||||
# ── Chat Intercept ────────────────────────────────────────────
|
|
||||||
|
|
||||||
def peek_chat_intercept(self, count: int = 10) -> list[dict]:
|
|
||||||
"""Peek messages from the chat.intercept queue."""
|
|
||||||
return self.peek_messages("queue.intercept", count=count)
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
self.client.close()
|
|
||||||
|
|
||||||
|
|
||||||
class RmqGameError(Exception):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
import time
|
|
||||||
@@ -1,103 +0,0 @@
|
|||||||
"""SSH service — remote command execution via paramiko."""
|
|
||||||
|
|
||||||
import logging
|
|
||||||
import threading
|
|
||||||
import paramiko
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class SSHService:
|
|
||||||
def __init__(self, host, user, ssh_key=None):
|
|
||||||
self.host = host
|
|
||||||
self.user = user
|
|
||||||
self.ssh_key = ssh_key
|
|
||||||
self._client = None
|
|
||||||
self._lock = threading.Lock()
|
|
||||||
key_status = self.ssh_key if self.ssh_key else "default ssh identity/agent"
|
|
||||||
logger.info("SSHService initialized: %s@%s using %s", user, host, key_status)
|
|
||||||
|
|
||||||
def _get_client(self):
|
|
||||||
with self._lock:
|
|
||||||
if self._client is not None:
|
|
||||||
transport = self._client.get_transport()
|
|
||||||
if transport and transport.is_active():
|
|
||||||
return self._client
|
|
||||||
self._client = None
|
|
||||||
|
|
||||||
client = paramiko.SSHClient()
|
|
||||||
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
|
||||||
|
|
||||||
connect_kwargs = {
|
|
||||||
"hostname": self.host,
|
|
||||||
"username": self.user,
|
|
||||||
"timeout": 15,
|
|
||||||
"allow_agent": True,
|
|
||||||
"look_for_keys": True,
|
|
||||||
}
|
|
||||||
if self.ssh_key:
|
|
||||||
connect_kwargs["key_filename"] = self.ssh_key
|
|
||||||
|
|
||||||
try:
|
|
||||||
client.connect(**connect_kwargs)
|
|
||||||
logger.debug("SSH connection established to %s@%s", self.user, self.host)
|
|
||||||
except paramiko.AuthenticationException:
|
|
||||||
logger.error("SSH authentication failed for %s@%s", self.user, self.host)
|
|
||||||
raise
|
|
||||||
except paramiko.SSHException as e:
|
|
||||||
logger.error("SSH connection error: %s", e)
|
|
||||||
raise
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Unexpected SSH error: %s", e)
|
|
||||||
raise
|
|
||||||
|
|
||||||
self._client = client
|
|
||||||
return self._client
|
|
||||||
|
|
||||||
def run(self, command, timeout=30):
|
|
||||||
cmd_display = command[:150] + "..." if len(command) > 150 else command
|
|
||||||
logger.debug("SSH executing: %s", cmd_display)
|
|
||||||
|
|
||||||
try:
|
|
||||||
client = self._get_client()
|
|
||||||
stdin, stdout, stderr = client.exec_command(command, timeout=timeout)
|
|
||||||
out = stdout.read().decode("utf-8", errors="replace")
|
|
||||||
err = stderr.read().decode("utf-8", errors="replace")
|
|
||||||
rc = stdout.channel.recv_exit_status()
|
|
||||||
|
|
||||||
logger.debug("SSH result: rc=%d, stdout_len=%d, stderr_len=%d", rc, len(out), len(err))
|
|
||||||
if err and rc != 0:
|
|
||||||
logger.warning("SSH stderr (rc=%d): %s", rc, err[:200])
|
|
||||||
if rc != 0:
|
|
||||||
logger.warning("SSH command failed (rc=%d): cmd=%s err=%s", rc, cmd_display, err[:100] if err else "none")
|
|
||||||
return out, err, rc
|
|
||||||
except paramiko.SSHException as e:
|
|
||||||
logger.error("SSH command error (%s): %s", self.host, e)
|
|
||||||
self._client = None
|
|
||||||
return "", str(e), -1
|
|
||||||
except Exception as ex:
|
|
||||||
logger.error("Unexpected SSH command error (%s): %s", self.host, ex)
|
|
||||||
self._client = None
|
|
||||||
return "", str(ex), -1
|
|
||||||
|
|
||||||
def check_connection(self):
|
|
||||||
try:
|
|
||||||
out, err, rc = self.run("echo ok", timeout=10)
|
|
||||||
if rc == 0 and "ok" in out:
|
|
||||||
logger.debug("SSH connection check passed")
|
|
||||||
return True
|
|
||||||
logger.warning("SSH connection check failed: rc=%d, out=%s", rc, out[:50])
|
|
||||||
return False
|
|
||||||
except Exception:
|
|
||||||
logger.warning("SSH connection check failed with exception")
|
|
||||||
return False
|
|
||||||
|
|
||||||
def close(self):
|
|
||||||
with self._lock:
|
|
||||||
if self._client:
|
|
||||||
try:
|
|
||||||
self._client.close()
|
|
||||||
logger.debug("SSH connection closed")
|
|
||||||
except Exception as e:
|
|
||||||
logger.debug("Error closing SSH connection: %s", e)
|
|
||||||
self._client = None
|
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
# World service — partitions, spice, teleport.
|
|
||||||
|
|
||||||
import logging
|
|
||||||
|
|
||||||
from app.services.database import DatabaseService
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
|
|
||||||
class WorldService:
|
|
||||||
def __init__(self, db: DatabaseService):
|
|
||||||
self.db = db
|
|
||||||
|
|
||||||
def get_partitions(self, map_name: str = "") -> list[dict]:
|
|
||||||
try:
|
|
||||||
if map_name:
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT partition_id as id, map, dimension_index,
|
|
||||||
label, partition_definition::text as definition
|
|
||||||
FROM dune.partitions WHERE map = %s ORDER BY partition_id""",
|
|
||||||
[map_name],
|
|
||||||
)
|
|
||||||
return self.db.execute_readonly(
|
|
||||||
"""SELECT partition_id as id, map, dimension_index,
|
|
||||||
label, partition_definition::text as definition
|
|
||||||
FROM dune.partitions ORDER BY partition_id"""
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
return []
|
|
||||||
|
|
||||||
def teleport(self, fls_id: str, partition_id: int, x: float, y: float, z: float) -> bool:
|
|
||||||
try:
|
|
||||||
self.db.execute_mutation(
|
|
||||||
"SELECT dune.admin_move_offline_player_to_partition(%s, %s, (%s, %s, %s))",
|
|
||||||
[fls_id, partition_id, x, y, z],
|
|
||||||
)
|
|
||||||
return True
|
|
||||||
except Exception:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def reset_spice(self, map_name: str, dimension_index: int) -> bool:
|
|
||||||
return False
|
|
||||||
|
|
||||||
def force_spice_spawn(self, server_id: str, spicefield_type_id: int) -> bool:
|
|
||||||
return False
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# Utils package init.
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
# Shared constants and helpers.
|
|
||||||
|
|
||||||
INVENTORY_TYPE_LABELS = {
|
|
||||||
0: "Main Inventory",
|
|
||||||
1: "Equipped Items",
|
|
||||||
5: "Hotbar",
|
|
||||||
12: "Storage",
|
|
||||||
14: "Recipes",
|
|
||||||
15: "Key Items",
|
|
||||||
20: "Crafting Queue",
|
|
||||||
25: "Schematics",
|
|
||||||
27: "Emotes",
|
|
||||||
29: "Quest Items",
|
|
||||||
30: "Bank",
|
|
||||||
31: "Power Pack Slots",
|
|
||||||
32: "Module Slots",
|
|
||||||
33: "Augment Slots",
|
|
||||||
}
|
|
||||||
|
|
||||||
INVENTORY_HIDDEN_TYPES = {14, 27}
|
|
||||||
INVENTORY_UNKNOWN_TYPES = {12, 20, 25, 29, 30, 31, 32, 33}
|
|
||||||
INVENTORY_PRIMARY_TYPES = {0, 1, 5, 15}
|
|
||||||
|
|
||||||
EQUIPPED_SLOT_LABELS = {
|
|
||||||
0: "Head",
|
|
||||||
1: "Chest",
|
|
||||||
2: "Legs",
|
|
||||||
3: "Gloves",
|
|
||||||
4: "Feet",
|
|
||||||
5: "Unknown Spare Slot",
|
|
||||||
6: "Portable Light",
|
|
||||||
7: "Suspensor Belt",
|
|
||||||
8: "Power Pack",
|
|
||||||
9: "Shield",
|
|
||||||
}
|
|
||||||
|
|
||||||
QUALITY_TIERS = {
|
|
||||||
0: {"label": "Common", "color": "#9a8a7a"},
|
|
||||||
1: {"label": "Uncommon", "color": "#27ae60"},
|
|
||||||
2: {"label": "Rare", "color": "#3498db"},
|
|
||||||
3: {"label": "Epic", "color": "#9b59b6"},
|
|
||||||
4: {"label": "Legendary", "color": "#f39c12"},
|
|
||||||
}
|
|
||||||
|
|
||||||
CURRENCY_ID_LABELS = {
|
|
||||||
0: "Solari Credits",
|
|
||||||
1: "House Script",
|
|
||||||
2: "Spice",
|
|
||||||
}
|
|
||||||
|
|
||||||
GUILD_ROLES = {100: "Leader", 90: "Officer", 80: "Officer", 50: "Member", 1: "Member"}
|
|
||||||
|
|
||||||
VEHICLE_TYPE_MAP = {
|
|
||||||
"BP_MediumOrnithopter_CHOAM": "Medium Ornithopter",
|
|
||||||
"BP_TransportOrnithopter_CHOAM": "Transport Ornithopter",
|
|
||||||
"BP_Buggy_CHOAM": "Buggy",
|
|
||||||
"BP_LightOrnithopter_Choam": "Light Ornithopter",
|
|
||||||
"BP_Sandbike_CHOAM": "Sandbike",
|
|
||||||
}
|
|
||||||
|
|
||||||
NAV_PAGES = [
|
|
||||||
("/", "Overview"),
|
|
||||||
("/server", "Server"),
|
|
||||||
("/players", "Players"),
|
|
||||||
("/guilds", "Guilds"),
|
|
||||||
("/vehicles", "Vehicles"),
|
|
||||||
("/map", "Map"),
|
|
||||||
("/chat", "Chat"),
|
|
||||||
("/admin", "Admin"),
|
|
||||||
("/shell", "Shell"),
|
|
||||||
]
|
|
||||||
@@ -1 +0,0 @@
|
|||||||
# WebSocket package init.
|
|
||||||
@@ -1,131 +0,0 @@
|
|||||||
# WebSocket shell handler — interactive terminal via SSH.
|
|
||||||
|
|
||||||
import os
|
|
||||||
import time
|
|
||||||
import threading
|
|
||||||
import logging
|
|
||||||
import re
|
|
||||||
import shlex
|
|
||||||
|
|
||||||
import paramiko
|
|
||||||
from flask import request, session
|
|
||||||
from flask_socketio import emit
|
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
|
||||||
|
|
||||||
shell_processes = {}
|
|
||||||
K8S_NAME_RE = re.compile(r"^[a-z0-9]([-a-z0-9]*[a-z0-9])?$")
|
|
||||||
|
|
||||||
|
|
||||||
def require_k8s_name(value, label):
|
|
||||||
value = str(value or "").strip()
|
|
||||||
if not value or not K8S_NAME_RE.fullmatch(value):
|
|
||||||
raise ValueError(f"Invalid {label}")
|
|
||||||
return value
|
|
||||||
|
|
||||||
|
|
||||||
def quote_remote(value):
|
|
||||||
return shlex.quote(str(value))
|
|
||||||
|
|
||||||
|
|
||||||
def register_websocket_handlers(socketio, settings):
|
|
||||||
@socketio.on("shell_create")
|
|
||||||
def handle_shell_create(data):
|
|
||||||
shell_enabled = settings.get("auth", {}).get("shell_enabled", True)
|
|
||||||
if not shell_enabled:
|
|
||||||
return emit("shell_created", {"success": False, "error": "Shell access is disabled"})
|
|
||||||
|
|
||||||
auth_enabled = settings.get("auth", {}).get("enabled", True)
|
|
||||||
if auth_enabled and not session.get("_user_id"):
|
|
||||||
return emit("shell_created", {"success": False, "error": "Authentication required"})
|
|
||||||
|
|
||||||
shell_type = data.get("type", "vm")
|
|
||||||
shell_id = request.sid
|
|
||||||
|
|
||||||
try:
|
|
||||||
ssh_key = _find_ssh_key(settings)
|
|
||||||
if not ssh_key:
|
|
||||||
return emit("shell_created", {"success": False, "error": "SSH key not found"})
|
|
||||||
|
|
||||||
client = paramiko.SSHClient()
|
|
||||||
client.set_missing_host_key_policy(paramiko.WarningPolicy())
|
|
||||||
server_host = settings["server"]["host"]
|
|
||||||
server_user = settings["server"]["user"]
|
|
||||||
|
|
||||||
if shell_type == "vm":
|
|
||||||
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
|
|
||||||
chan = client.invoke_shell(term="xterm-256color", width=80, height=24)
|
|
||||||
else:
|
|
||||||
namespace = settings["kubernetes"]["namespace"]
|
|
||||||
pod = data.get("pod", "")
|
|
||||||
pod = require_k8s_name(pod, "pod")
|
|
||||||
client.connect(server_host, username=server_user, key_filename=ssh_key, timeout=10)
|
|
||||||
transport = client.get_transport()
|
|
||||||
chan = transport.open_session()
|
|
||||||
chan.get_pty(term="xterm-256color", width=80, height=24)
|
|
||||||
safe_pod = quote_remote(pod)
|
|
||||||
safe_ns = quote_remote(namespace)
|
|
||||||
chan.exec_command(f"sudo kubectl exec -it {safe_pod} -n {safe_ns} -- /bin/bash")
|
|
||||||
|
|
||||||
shell_processes[shell_id] = {"client": client, "channel": chan, "type": shell_type}
|
|
||||||
|
|
||||||
def read_channel():
|
|
||||||
time.sleep(0.5)
|
|
||||||
socketio.emit("shell_output", {"data": "\r\nConnected. Press Enter...\r\n", "type": "stdout", "target": shell_type}, room=shell_id)
|
|
||||||
while shell_id in shell_processes:
|
|
||||||
try:
|
|
||||||
while chan.recv_ready():
|
|
||||||
data = chan.recv(65535).decode("utf-8", errors="replace")
|
|
||||||
if data:
|
|
||||||
socketio.emit("shell_output", {"data": data, "type": "stdout", "target": shell_type}, room=shell_id)
|
|
||||||
while chan.recv_stderr_ready():
|
|
||||||
data = chan.recv_stderr(65535).decode("utf-8", errors="replace")
|
|
||||||
if data:
|
|
||||||
socketio.emit("shell_output", {"data": data, "type": "stderr", "target": shell_type}, room=shell_id)
|
|
||||||
if chan.closed:
|
|
||||||
socketio.emit("shell_output", {"data": "\r\n[Disconnected]\r\n", "type": "stdout", "target": shell_type}, room=shell_id)
|
|
||||||
break
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Shell read error: %s", e)
|
|
||||||
break
|
|
||||||
time.sleep(0.1)
|
|
||||||
|
|
||||||
threading.Thread(target=read_channel, daemon=True).start()
|
|
||||||
socketio.emit("shell_created", {"success": True, "shell_id": shell_id}, room=shell_id)
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Shell creation failed: %s", e)
|
|
||||||
socketio.emit("shell_created", {"success": False, "error": str(e)}, room=shell_id)
|
|
||||||
|
|
||||||
@socketio.on("shell_input")
|
|
||||||
def handle_shell_input(data):
|
|
||||||
shell_id = request.sid
|
|
||||||
if shell_id in shell_processes:
|
|
||||||
try:
|
|
||||||
chan = shell_processes[shell_id]["channel"]
|
|
||||||
if chan and chan.send_ready():
|
|
||||||
chan.send(data.get("data", ""))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Shell input error: %s", e)
|
|
||||||
|
|
||||||
@socketio.on("shell_disconnect")
|
|
||||||
def handle_shell_disconnect(data=None):
|
|
||||||
shell_id = request.sid
|
|
||||||
if shell_id in shell_processes:
|
|
||||||
try:
|
|
||||||
if "client" in shell_processes[shell_id]:
|
|
||||||
shell_processes[shell_id]["client"].close()
|
|
||||||
except Exception as e:
|
|
||||||
logger.error("Shell disconnect error: %s", e)
|
|
||||||
del shell_processes[shell_id]
|
|
||||||
|
|
||||||
|
|
||||||
def _find_ssh_key(settings):
|
|
||||||
ssh_key = settings["server"].get("ssh_key")
|
|
||||||
if ssh_key:
|
|
||||||
return ssh_key
|
|
||||||
local_appdata = os.environ.get("LOCALAPPDATA")
|
|
||||||
if local_appdata:
|
|
||||||
default_key = os.path.join(local_appdata, "DuneAwakeningServer", "sshKey")
|
|
||||||
if os.path.exists(default_key):
|
|
||||||
return default_key
|
|
||||||
return None
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
flask>=3.0.0
|
|
||||||
flask-socketio>=5.3.0
|
|
||||||
flask-login>=0.6.3
|
|
||||||
flask-limiter>=3.5.0
|
|
||||||
flask-cors>=4.0.0
|
|
||||||
flask-wtf>=1.2.0
|
|
||||||
pydantic>=2.5.0
|
|
||||||
httpx>=0.27.0
|
|
||||||
psycopg>=3.1.0
|
|
||||||
psycopg_pool>=3.2.0
|
|
||||||
cachetools>=5.3.0
|
|
||||||
argon2-cffi>=23.1.0
|
|
||||||
pyyaml>=6.0
|
|
||||||
python-socketio>=5.10.0
|
|
||||||
paramiko>=3.4.0
|
|
||||||
Werkzeug>=3.0.0
|
|
||||||
itsdangerous>=2.1.0
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
"""Entry point for the new backend."""
|
|
||||||
|
|
||||||
import sys
|
|
||||||
import os
|
|
||||||
|
|
||||||
# Add backend to path
|
|
||||||
backend_dir = os.path.dirname(os.path.abspath(__file__))
|
|
||||||
if backend_dir not in sys.path:
|
|
||||||
sys.path.insert(0, backend_dir)
|
|
||||||
|
|
||||||
from app.factory import create_app
|
|
||||||
|
|
||||||
app = create_app()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
import logging
|
|
||||||
logging.basicConfig(level=logging.INFO)
|
|
||||||
app.run(
|
|
||||||
host=app.dune_settings["dashboard"]["host"],
|
|
||||||
port=app.dune_settings["dashboard"]["port"],
|
|
||||||
debug=app.dune_settings["dashboard"]["debug"],
|
|
||||||
)
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
<!doctype html>
|
|
||||||
<html lang="en" data-theme="emperor">
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8" />
|
|
||||||
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
|
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
|
||||||
<title>Dune Admin Dashboard</title>
|
|
||||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
|
||||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=Playfair+Display:wght@700&display=swap" rel="stylesheet">
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div id="root"></div>
|
|
||||||
<script type="module" src="/src/main.tsx"></script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
{
|
|
||||||
"name": "dune-dashboard-frontend",
|
|
||||||
"private": true,
|
|
||||||
"version": "1.0.0",
|
|
||||||
"type": "module",
|
|
||||||
"scripts": {
|
|
||||||
"dev": "vite",
|
|
||||||
"build": "tsc && vite build",
|
|
||||||
"preview": "vite preview"
|
|
||||||
},
|
|
||||||
"dependencies": {
|
|
||||||
"@chakra-ui/react": "^3.0.0",
|
|
||||||
"@fontsource/inter": "^5.0.0",
|
|
||||||
"@fontsource/playfair-display": "^5.0.0",
|
|
||||||
"@fontsource/roboto-mono": "^5.0.0",
|
|
||||||
"axios": "^1.6.7",
|
|
||||||
"react": "^18.2.0",
|
|
||||||
"react-dom": "^18.2.0",
|
|
||||||
"react-icons": "^5.6.0",
|
|
||||||
"react-router-dom": "^6.22.0",
|
|
||||||
"recharts": "^2.12.0",
|
|
||||||
"socket.io-client": "^4.7.4",
|
|
||||||
"swr": "^2.2.4",
|
|
||||||
"xterm": "^5.3.0",
|
|
||||||
"xterm-addon-fit": "^0.8.0"
|
|
||||||
},
|
|
||||||
"devDependencies": {
|
|
||||||
"@types/react": "^18.2.55",
|
|
||||||
"@types/react-dom": "^18.2.19",
|
|
||||||
"@vitejs/plugin-react": "^4.2.1",
|
|
||||||
"typescript": "^5.3.3",
|
|
||||||
"vite": "^5.1.0"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,72 +0,0 @@
|
|||||||
import { useEffect } from 'react'
|
|
||||||
import { BrowserRouter, Routes, Route } from 'react-router-dom'
|
|
||||||
import { ChakraProvider, defaultSystem } from '@chakra-ui/react'
|
|
||||||
import { AppProvider, useApp } from './stores/AppContext'
|
|
||||||
import { injectThemeVars } from './themes/inject'
|
|
||||||
import { useRealtime } from './hooks/useRealtime'
|
|
||||||
import AppShell from './components/layout/AppShell'
|
|
||||||
import Overview from './components/overview/Overview'
|
|
||||||
import PlayerExplorer from './components/players/PlayerExplorer'
|
|
||||||
import PlayerDetail from './components/players/PlayerDetail'
|
|
||||||
import GuildManager from './components/guilds/GuildManager'
|
|
||||||
import Vehicles from './components/vehicles/Vehicles'
|
|
||||||
import Buildings from './components/buildings/Buildings'
|
|
||||||
import MapViewer from './components/map/MapViewer'
|
|
||||||
import Accounts from './components/accounts/Accounts'
|
|
||||||
import ServerControl from './components/server/ServerControl'
|
|
||||||
import AdminTools from './components/admin/AdminTools'
|
|
||||||
import ChatMonitor from './components/chat/ChatMonitor'
|
|
||||||
import Terminal from './components/shell/Terminal'
|
|
||||||
import FileBrowser from './components/files/FileBrowser'
|
|
||||||
import Director from './components/director/Director'
|
|
||||||
import Settings from './components/settings/Settings'
|
|
||||||
import Experimental from './components/experimental/Experimental'
|
|
||||||
|
|
||||||
function RealtimeInit() {
|
|
||||||
useRealtime()
|
|
||||||
return null
|
|
||||||
}
|
|
||||||
|
|
||||||
function ThemedApp() {
|
|
||||||
const { state } = useApp()
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
injectThemeVars(state.faction, state.colorMode)
|
|
||||||
}, [state.faction, state.colorMode])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ChakraProvider value={defaultSystem}>
|
|
||||||
<BrowserRouter>
|
|
||||||
<RealtimeInit />
|
|
||||||
<AppShell>
|
|
||||||
<Routes>
|
|
||||||
<Route path="/" element={<Overview />} />
|
|
||||||
<Route path="/players" element={<PlayerExplorer />} />
|
|
||||||
<Route path="/players/:accountId" element={<PlayerDetail />} />
|
|
||||||
<Route path="/guilds" element={<GuildManager />} />
|
|
||||||
<Route path="/vehicles" element={<Vehicles />} />
|
|
||||||
<Route path="/buildings" element={<Buildings />} />
|
|
||||||
<Route path="/map" element={<MapViewer />} />
|
|
||||||
<Route path="/accounts" element={<Accounts />} />
|
|
||||||
<Route path="/server" element={<ServerControl />} />
|
|
||||||
<Route path="/admin" element={<AdminTools />} />
|
|
||||||
<Route path="/chat" element={<ChatMonitor />} />
|
|
||||||
<Route path="/shell" element={<Terminal />} />
|
|
||||||
<Route path="/files" element={<FileBrowser />} />
|
|
||||||
<Route path="/director" element={<Director />} />
|
|
||||||
<Route path="/settings" element={<Settings />} />
|
|
||||||
<Route path="/experimental" element={<Experimental />} />
|
|
||||||
</Routes>
|
|
||||||
</AppShell>
|
|
||||||
</BrowserRouter>
|
|
||||||
</ChakraProvider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function App() {
|
|
||||||
return (
|
|
||||||
<AppProvider>
|
|
||||||
<ThemedApp />
|
|
||||||
</AppProvider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,21 +0,0 @@
|
|||||||
import axios from 'axios'
|
|
||||||
|
|
||||||
const client = axios.create({
|
|
||||||
baseURL: '/api',
|
|
||||||
headers: {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
},
|
|
||||||
timeout: 30000,
|
|
||||||
})
|
|
||||||
|
|
||||||
client.interceptors.response.use(
|
|
||||||
(response) => response,
|
|
||||||
(error) => {
|
|
||||||
if (error.response?.status === 401) {
|
|
||||||
window.location.href = '/login'
|
|
||||||
}
|
|
||||||
return Promise.reject(error)
|
|
||||||
}
|
|
||||||
)
|
|
||||||
|
|
||||||
export default client
|
|
||||||
@@ -1,74 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import { Box, Heading, Input } from '@chakra-ui/react'
|
|
||||||
import { FiSearch } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import DataTable from '../common/DataTable'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Account {
|
|
||||||
id: number
|
|
||||||
email: string
|
|
||||||
funcom_id: string
|
|
||||||
character_count: number
|
|
||||||
is_demo: boolean
|
|
||||||
is_cheater: boolean
|
|
||||||
last_login: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Accounts() {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: accountsData, isLoading } = useSWR(
|
|
||||||
search.length >= 2 ? `/accounts?q=${encodeURIComponent(search)}&limit=50` : '/accounts?limit=100',
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const accountList: Account[] = accountsData?.success ? accountsData.data : []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
|
|
||||||
Accounts
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Box position="relative" maxW="md" mb={6}>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search accounts..."
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
pl={10}
|
|
||||||
fontSize="sm"
|
|
||||||
color="fg"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
|
|
||||||
_focusVisible={{ outline: 'none' }}
|
|
||||||
/>
|
|
||||||
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
|
|
||||||
<FiSearch size={16} />
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={[
|
|
||||||
{ header: 'Email', accessor: 'email' },
|
|
||||||
{ header: 'Funcom ID', accessor: 'funcom_id' },
|
|
||||||
{ header: 'Characters', accessor: 'character_count' },
|
|
||||||
{ header: 'Last Login', accessor: 'last_login' },
|
|
||||||
]}
|
|
||||||
data={accountList}
|
|
||||||
loading={isLoading}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,783 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import {
|
|
||||||
Box, Flex, Heading, Text, Button, Input, Select, Textarea,
|
|
||||||
SimpleGrid, Card, Tabs, Table, VStack, createListCollection,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiAlertTriangle } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
const SCOPE_OPTIONS = ['all', 'server', 'partition']
|
|
||||||
const SERVER_OPTIONS = ['na', 'eu', 'sea', 'sa', 'oc']
|
|
||||||
const PARTITION_OPTIONS = ['parrish', 'sietch', 'bazar']
|
|
||||||
|
|
||||||
const serverCollection = createListCollection({
|
|
||||||
items: SERVER_OPTIONS.map((s) => ({ value: s, label: s.toUpperCase() })),
|
|
||||||
})
|
|
||||||
|
|
||||||
const partitionCollection = createListCollection({
|
|
||||||
items: PARTITION_OPTIONS.map((p) => ({ value: p, label: p })),
|
|
||||||
})
|
|
||||||
|
|
||||||
const itemFieldCollection = createListCollection({
|
|
||||||
items: [
|
|
||||||
{ value: 'stack_size', label: 'stack_size' },
|
|
||||||
{ value: 'quality_level', label: 'quality_level' },
|
|
||||||
{ value: 'durability', label: 'durability' },
|
|
||||||
{ value: 'ammo', label: 'ammo' },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
const demoStateCollection = createListCollection({
|
|
||||||
items: [
|
|
||||||
{ value: 'true', label: 'Demo' },
|
|
||||||
{ value: 'false', label: 'Normal' },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
const limitCollection = createListCollection({
|
|
||||||
items: [10, 25, 50, 100, 250].map((n) => ({ value: String(n), label: `${n} entries` })),
|
|
||||||
})
|
|
||||||
|
|
||||||
export default function AdminTools() {
|
|
||||||
const [tab, setTab] = useState<'broadcast' | 'economy' | 'world' | 'character' | 'functions' | 'raw' | 'audit'>('broadcast')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" fontSize="3xl" color="primary.DEFAULT" mb={6}>
|
|
||||||
Admin Tools
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value as any)} mb={6}>
|
|
||||||
<Tabs.List borderBottomWidth="1px" borderColor="border" overflowX="auto">
|
|
||||||
{([
|
|
||||||
{ key: 'broadcast', label: 'Broadcast' },
|
|
||||||
{ key: 'economy', label: 'Economy' },
|
|
||||||
{ key: 'world', label: 'World' },
|
|
||||||
{ key: 'character', label: 'Character' },
|
|
||||||
{ key: 'functions', label: 'Functions' },
|
|
||||||
{ key: 'raw', label: 'Raw Query' },
|
|
||||||
{ key: 'audit', label: 'Audit Log' },
|
|
||||||
] as const).map((t) => (
|
|
||||||
<Tabs.Trigger
|
|
||||||
key={t.key}
|
|
||||||
value={t.key}
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
whiteSpace="nowrap"
|
|
||||||
_selected={{ color: 'primary.DEFAULT', borderColor: 'primary.DEFAULT' }}
|
|
||||||
color="fg.muted"
|
|
||||||
borderBottomWidth="2px"
|
|
||||||
borderColor="transparent"
|
|
||||||
>
|
|
||||||
{t.label}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
))}
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="broadcast" pt={4}>
|
|
||||||
<BroadcastTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="economy" pt={4}>
|
|
||||||
<EconomyTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="world" pt={4}>
|
|
||||||
<WorldTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="character" pt={4}>
|
|
||||||
<CharacterTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="functions" pt={4}>
|
|
||||||
<FunctionsTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="raw" pt={4}>
|
|
||||||
<RawQueryTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="audit" pt={4}>
|
|
||||||
<AuditLogTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BroadcastTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [message, setMessage] = useState('')
|
|
||||||
const [scope, setScope] = useState('all')
|
|
||||||
const [server, setServer] = useState('na')
|
|
||||||
const [partition, setPartition] = useState('parrish')
|
|
||||||
const [sending, setSending] = useState(false)
|
|
||||||
|
|
||||||
const handleSend = async () => {
|
|
||||||
if (!message.trim()) return
|
|
||||||
setSending(true)
|
|
||||||
try {
|
|
||||||
const payload: any = { message: message.trim() }
|
|
||||||
if (scope === 'server') payload.server = server
|
|
||||||
if (scope === 'partition') {
|
|
||||||
payload.server = server
|
|
||||||
payload.partition = partition
|
|
||||||
}
|
|
||||||
const res = await client.post('/broadcast', payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Broadcast sent', type: 'success' } })
|
|
||||||
setMessage('')
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setSending(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box maxW="xl">
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Scope</Text>
|
|
||||||
<Flex gap={2}>
|
|
||||||
{SCOPE_OPTIONS.map((s) => (
|
|
||||||
<Button
|
|
||||||
key={s}
|
|
||||||
onClick={() => setScope(s)}
|
|
||||||
size="xs"
|
|
||||||
textTransform="capitalize"
|
|
||||||
variant={scope === s ? 'solid' : 'outline'}
|
|
||||||
bg={scope === s ? 'primary.subtle' : 'transparent'}
|
|
||||||
color={scope === s ? 'primary.DEFAULT' : 'fg.muted'}
|
|
||||||
borderColor={scope === s ? 'primary.DEFAULT' : 'border'}
|
|
||||||
borderRadius="md"
|
|
||||||
_hover={{ color: 'fg' }}
|
|
||||||
>
|
|
||||||
{s}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</Flex>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
{scope !== 'all' && (
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Server</Text>
|
|
||||||
<Select.Root collection={serverCollection} value={[server]} onValueChange={(e) => setServer(e.value[0])}>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{serverCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{scope === 'partition' && (
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Partition</Text>
|
|
||||||
<Select.Root collection={partitionCollection} value={[partition]} onValueChange={(e) => setPartition(e.value[0])}>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{partitionCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Message</Text>
|
|
||||||
<Textarea
|
|
||||||
value={message}
|
|
||||||
onChange={(e) => setMessage(e.target.value)}
|
|
||||||
rows={4}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
resize="vertical"
|
|
||||||
placeholder="Enter broadcast message..."
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Button
|
|
||||||
onClick={handleSend}
|
|
||||||
disabled={sending || !message.trim()}
|
|
||||||
colorPalette="primary"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
>
|
|
||||||
{sending ? 'Sending...' : 'Send Broadcast'}
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function EconomyTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [playerId, setPlayerId] = useState('')
|
|
||||||
const [itemForm, setItemForm] = useState({ template_id: '', stack_size: '1', quality: '0', inventory_id: '' })
|
|
||||||
const [editForm, setEditForm] = useState({ item_id: '', field: 'stack_size', value: '' })
|
|
||||||
|
|
||||||
const post = async (endpoint: string, payload: any) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(endpoint, payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Add Item</Text>
|
|
||||||
<Input value={playerId} onChange={(e) => setPlayerId(e.target.value)} placeholder="Player ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={itemForm.template_id} onChange={(e) => setItemForm({ ...itemForm, template_id: e.target.value })} placeholder="Template ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={itemForm.stack_size} onChange={(e) => setItemForm({ ...itemForm, stack_size: e.target.value })} placeholder="Stack Size" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={itemForm.quality} onChange={(e) => setItemForm({ ...itemForm, quality: e.target.value })} placeholder="Quality" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={itemForm.inventory_id} onChange={(e) => setItemForm({ ...itemForm, inventory_id: e.target.value })} placeholder="Inventory ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Button
|
|
||||||
onClick={() => post('/items/add', { player_id: parseInt(playerId), template_id: itemForm.template_id, stack_size: parseInt(itemForm.stack_size), quality_level: parseInt(itemForm.quality), inventory_id: parseInt(itemForm.inventory_id) || undefined })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Add Item
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Edit Item</Text>
|
|
||||||
<Input value={editForm.item_id} onChange={(e) => setEditForm({ ...editForm, item_id: e.target.value })} placeholder="Item ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Select.Root collection={itemFieldCollection} value={[editForm.field]} onValueChange={(e) => setEditForm({ ...editForm, field: e.value[0] })}>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{itemFieldCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
<Input value={editForm.value} onChange={(e) => setEditForm({ ...editForm, value: e.target.value })} placeholder="New value" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => post(`/items/${editForm.item_id}`, { [editForm.field]: editForm.value })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Update
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => post(`/items/${editForm.item_id}`, {})}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Delete
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function WorldTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [tpForm, setTpForm] = useState({ fls_id: '', partition: '', x: '', y: '', z: '' })
|
|
||||||
|
|
||||||
const post = async (endpoint: string, payload: any) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(endpoint, payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Teleport Player</Text>
|
|
||||||
<Input value={tpForm.fls_id} onChange={(e) => setTpForm({ ...tpForm, fls_id: e.target.value })} placeholder="FLS ID / Account ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={tpForm.partition} onChange={(e) => setTpForm({ ...tpForm, partition: e.target.value })} placeholder="Partition ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Input type="number" value={tpForm.x} onChange={(e) => setTpForm({ ...tpForm, x: e.target.value })} placeholder="X" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input type="number" value={tpForm.y} onChange={(e) => setTpForm({ ...tpForm, y: e.target.value })} placeholder="Y" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input type="number" value={tpForm.z} onChange={(e) => setTpForm({ ...tpForm, z: e.target.value })} placeholder="Z" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
</Flex>
|
|
||||||
<Button
|
|
||||||
onClick={() => post('/teleport', { fls_id: parseInt(tpForm.fls_id), partition_id: tpForm.partition, x: parseFloat(tpForm.x) || 0, y: parseFloat(tpForm.y) || 0, z: parseFloat(tpForm.z) || 0 })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Teleport
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Spice Control</Text>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => post('/spice/reset', {})}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Reset Spice Fields
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => post('/spice/spawn', {})}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Force Spawn
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Partitions</Text>
|
|
||||||
<Button
|
|
||||||
onClick={() => client.get('/partitions').then((r) => dispatch({ type: 'ADD_TOAST', payload: { message: 'Partitions loaded', type: 'info' } }))}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
List Partitions
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CharacterTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [charId, setCharId] = useState('')
|
|
||||||
const [newName, setNewName] = useState('')
|
|
||||||
const [demoState, setDemoState] = useState('true')
|
|
||||||
|
|
||||||
const post = async (endpoint: string, payload: any) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(endpoint, payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Rename Character</Text>
|
|
||||||
<Input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID / Character ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Input value={newName} onChange={(e) => setNewName(e.target.value)} placeholder="New Name" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Button
|
|
||||||
onClick={() => post(`/characters/${charId}/name`, { name: newName })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Rename
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Demo State</Text>
|
|
||||||
<Input value={charId} onChange={(e) => setCharId(e.target.value)} placeholder="Account ID" bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm" />
|
|
||||||
<Select.Root collection={demoStateCollection} value={[demoState]} onValueChange={(e) => setDemoState(e.value[0])}>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{demoStateCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
<Button
|
|
||||||
onClick={() => post(`/accounts/${charId}/demo`, { demo: demoState === 'true' })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Set Demo State
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
<Text fontWeight="medium">Danger Zone</Text>
|
|
||||||
<Flex wrap="wrap" gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => { if (confirm('Delete character?')) post(`/characters/${charId}`, {}) }}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Delete Character
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => { if (confirm('Delete account?')) post(`/accounts/${charId}`, {}) }}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Delete Account
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionsTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [schema, setSchema] = useState('')
|
|
||||||
const [funcName, setFuncName] = useState('')
|
|
||||||
const [args, setArgs] = useState('{}')
|
|
||||||
const [result, setResult] = useState('')
|
|
||||||
const [running, setRunning] = useState(false)
|
|
||||||
|
|
||||||
const handleExecute = async () => {
|
|
||||||
setRunning(true)
|
|
||||||
try {
|
|
||||||
const parsedArgs = JSON.parse(args || '{}')
|
|
||||||
const res = await client.post('/functions/execute', { schema: schema || undefined, function: funcName, args: parsedArgs })
|
|
||||||
if (res.data.success) {
|
|
||||||
setResult(JSON.stringify(res.data.data, null, 2))
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Function executed', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.message, type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setRunning(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box maxW="2xl">
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<SimpleGrid columns={2} gap={4}>
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Schema (optional)</Text>
|
|
||||||
<Input
|
|
||||||
value={schema}
|
|
||||||
onChange={(e) => setSchema(e.target.value)}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
placeholder="e.g., public"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Function Name</Text>
|
|
||||||
<Input
|
|
||||||
value={funcName}
|
|
||||||
onChange={(e) => setFuncName(e.target.value)}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
placeholder="e.g., get_player_stats"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
</SimpleGrid>
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={2}>Arguments (JSON)</Text>
|
|
||||||
<Textarea
|
|
||||||
value={args}
|
|
||||||
onChange={(e) => setArgs(e.target.value)}
|
|
||||||
rows={4}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
resize="vertical"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
<Button
|
|
||||||
onClick={handleExecute}
|
|
||||||
disabled={running || !funcName}
|
|
||||||
colorPalette="primary"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
>
|
|
||||||
{running ? 'Running...' : 'Execute'}
|
|
||||||
</Button>
|
|
||||||
{result && (
|
|
||||||
<Box
|
|
||||||
as="pre"
|
|
||||||
mt={4}
|
|
||||||
fontSize="xs"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
bg="code.bg"
|
|
||||||
p={4}
|
|
||||||
borderRadius="md"
|
|
||||||
overflow="auto"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
{result}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function RawQueryTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [query, setQuery] = useState('')
|
|
||||||
const [result, setResult] = useState('')
|
|
||||||
const [running, setRunning] = useState(false)
|
|
||||||
|
|
||||||
const handleRun = async () => {
|
|
||||||
setRunning(true)
|
|
||||||
try {
|
|
||||||
const res = await client.post('/query', { query })
|
|
||||||
if (res.data.success) {
|
|
||||||
setResult(JSON.stringify(res.data.data, null, 2))
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Query executed', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || e.message, type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setRunning(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box maxW="3xl">
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<Flex align="center" justify="space-between">
|
|
||||||
<Text fontSize="sm" color="fg.muted">SQL Query (Read-Only SELECT)</Text>
|
|
||||||
<Text fontSize="10px" color="danger.DEFAULT" textTransform="uppercase" letterSpacing="wider" bg="danger.subtle" px={2} py={0.5} borderRadius="md" borderWidth="1px" borderColor="danger.DEFAULT">
|
|
||||||
<FiAlertTriangle style={{ display: 'inline', marginRight: 4 }} />
|
|
||||||
Read Only
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
<Textarea
|
|
||||||
value={query}
|
|
||||||
onChange={(e) => setQuery(e.target.value)}
|
|
||||||
rows={6}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
resize="vertical"
|
|
||||||
placeholder="SELECT * FROM public.characters LIMIT 10;"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
onClick={handleRun}
|
|
||||||
disabled={running || !query.trim()}
|
|
||||||
colorPalette="primary"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
>
|
|
||||||
{running ? 'Running...' : 'Run Query'}
|
|
||||||
</Button>
|
|
||||||
{result && (
|
|
||||||
<Box
|
|
||||||
as="pre"
|
|
||||||
mt={4}
|
|
||||||
fontSize="xs"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
bg="code.bg"
|
|
||||||
p={4}
|
|
||||||
borderRadius="md"
|
|
||||||
overflow="auto"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
{result}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function AuditLogTab({ dispatch }: { dispatch: any }) {
|
|
||||||
const [limit, setLimit] = useState(50)
|
|
||||||
const [logs, setLogs] = useState<any[]>([])
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
|
|
||||||
const load = async () => {
|
|
||||||
setLoading(true)
|
|
||||||
try {
|
|
||||||
const res = await client.get(`/audit/logs?limit=${limit}`)
|
|
||||||
if (res.data.success) setLogs(res.data.data)
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Flex align="center" gap={4} mb={4}>
|
|
||||||
<Button
|
|
||||||
onClick={load}
|
|
||||||
disabled={loading}
|
|
||||||
colorPalette="primary"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
>
|
|
||||||
{loading ? 'Loading...' : 'Load Logs'}
|
|
||||||
</Button>
|
|
||||||
<Select.Root collection={limitCollection} value={[String(limit)]} onValueChange={(e) => setLimit(Number(e.value[0]))}>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{limitCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>{item.label}</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
</Flex>
|
|
||||||
<Box overflowX="auto" borderRadius="lg" borderWidth="1px" borderColor="border">
|
|
||||||
<Table.Root variant="line" size="sm">
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row borderBottomWidth="1px" borderColor="border">
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Time</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Admin</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Action</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Target</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" fontWeight="semibold" px={4} py={3}>Details</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{logs.map((log, i) => (
|
|
||||||
<Table.Row
|
|
||||||
key={i}
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
_last={{ borderBottomWidth: 0 }}
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
>
|
|
||||||
<Table.Cell px={4} py={3} color="fg.muted" fontSize="xs">{new Date(log.timestamp).toLocaleString()}</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>{log.admin_name}</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>
|
|
||||||
<Text
|
|
||||||
as="span"
|
|
||||||
px={2}
|
|
||||||
py={0.5}
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="11px"
|
|
||||||
fontWeight="semibold"
|
|
||||||
bg="primary.subtle"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
{log.action}
|
|
||||||
</Text>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>{log.target_type}: {log.target_id}</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3} fontSize="xs" color="fg.muted" maxW="md" truncate>{JSON.stringify(log.details)}</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import { Box, Heading, Input, Flex } from '@chakra-ui/react'
|
|
||||||
import { FiSearch } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import DataTable from '../common/DataTable'
|
|
||||||
import Badge from '../common/Badge'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Building {
|
|
||||||
id: number
|
|
||||||
class_name: string
|
|
||||||
map: string
|
|
||||||
owner_name: string
|
|
||||||
is_powered: boolean
|
|
||||||
power_level: number | null
|
|
||||||
instance_count: number
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Buildings() {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: buildingsData, isLoading } = useSWR(
|
|
||||||
search.length >= 2 ? `/buildings?q=${encodeURIComponent(search)}&limit=50` : '/buildings?limit=100',
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const buildingList: Building[] = buildingsData?.success ? buildingsData.data : []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
|
|
||||||
Buildings
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Box position="relative" maxW="md" mb={6}>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search buildings..."
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
pl={10}
|
|
||||||
fontSize="sm"
|
|
||||||
color="fg"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
|
|
||||||
_focusVisible={{ outline: 'none' }}
|
|
||||||
/>
|
|
||||||
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
|
|
||||||
<FiSearch size={16} />
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={[
|
|
||||||
{ header: 'Class', accessor: 'class_name' },
|
|
||||||
{ header: 'Map', accessor: 'map' },
|
|
||||||
{ header: 'Owner', accessor: 'owner_name' },
|
|
||||||
{
|
|
||||||
header: 'Power',
|
|
||||||
accessor: (row) => (
|
|
||||||
<Flex gap={1}>
|
|
||||||
{row.is_powered ? <Badge label="Powered" variant="success" /> : <Badge label="Unpowered" variant="default" />}
|
|
||||||
{row.power_level != null && <Badge label={`Lv ${row.power_level}`} variant="default" />}
|
|
||||||
</Flex>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{ header: 'Instances', accessor: 'instance_count' },
|
|
||||||
]}
|
|
||||||
data={buildingList}
|
|
||||||
loading={isLoading}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,135 +0,0 @@
|
|||||||
import { useState, useEffect, useRef } from 'react'
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Heading,
|
|
||||||
HStack,
|
|
||||||
Flex,
|
|
||||||
Button,
|
|
||||||
Text,
|
|
||||||
VStack,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiMessageSquare } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
|
|
||||||
interface ChatMessage {
|
|
||||||
id: string
|
|
||||||
channel: string
|
|
||||||
sender: string
|
|
||||||
message: string
|
|
||||||
timestamp: string
|
|
||||||
}
|
|
||||||
|
|
||||||
const CHANNELS = ['Global', 'Guild', 'System', 'Combat']
|
|
||||||
|
|
||||||
export default function ChatMonitor() {
|
|
||||||
const [channel, setChannel] = useState('Global')
|
|
||||||
const [messages, setMessages] = useState<ChatMessage[]>([])
|
|
||||||
const bottomRef = useRef<HTMLDivElement>(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
async function load() {
|
|
||||||
try {
|
|
||||||
const res = await client.get(`/chat/history?channel=${channel}&limit=100`)
|
|
||||||
if (res.data.success) {
|
|
||||||
setMessages(res.data.data)
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
load()
|
|
||||||
}, [channel])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const es = new EventSource('/api/events/stream')
|
|
||||||
es.addEventListener('chat_message', (e) => {
|
|
||||||
try {
|
|
||||||
const msg: ChatMessage = JSON.parse(e.data)
|
|
||||||
if (msg.channel === channel || channel === 'Global') {
|
|
||||||
setMessages((prev) => [...prev.slice(-199), msg])
|
|
||||||
}
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
return () => es.close()
|
|
||||||
}, [channel])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
bottomRef.current?.scrollIntoView({ behavior: 'smooth' })
|
|
||||||
}, [messages])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Flex direction="column" h="calc(100vh - 140px)">
|
|
||||||
<Flex align="center" justify="space-between" mb={4}>
|
|
||||||
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT">
|
|
||||||
Chat Monitor
|
|
||||||
</Heading>
|
|
||||||
<HStack gap={2}>
|
|
||||||
{CHANNELS.map((c) => (
|
|
||||||
<Button
|
|
||||||
key={c}
|
|
||||||
onClick={() => setChannel(c)}
|
|
||||||
size="xs"
|
|
||||||
borderRadius="md"
|
|
||||||
fontWeight="medium"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor={channel === c ? 'primary.DEFAULT' : 'border'}
|
|
||||||
bg={channel === c ? 'primary.subtle' : 'card.bg'}
|
|
||||||
color={channel === c ? 'primary.DEFAULT' : 'fg.muted'}
|
|
||||||
_hover={channel === c ? {} : { color: 'fg' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
{c}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
</HStack>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
flex={1}
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
overflow="hidden"
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
flex={1}
|
|
||||||
overflowY="auto"
|
|
||||||
p={4}
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
>
|
|
||||||
{messages.length === 0 ? (
|
|
||||||
<Flex align="center" justify="center" h="full" color="fg.muted">
|
|
||||||
<VStack gap={3}>
|
|
||||||
<FiMessageSquare size={40} />
|
|
||||||
<Text fontSize="sm">Waiting for messages...</Text>
|
|
||||||
</VStack>
|
|
||||||
</Flex>
|
|
||||||
) : (
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
{messages.map((msg) => (
|
|
||||||
<HStack key={msg.id} gap={3} align="baseline">
|
|
||||||
<Text color="fg.muted" fontSize="xs" whiteSpace="nowrap" flexShrink={0}>
|
|
||||||
{new Date(msg.timestamp).toLocaleTimeString()}
|
|
||||||
</Text>
|
|
||||||
<Text color="primary.DEFAULT" fontWeight="semibold" whiteSpace="nowrap" flexShrink={0}>
|
|
||||||
[{msg.channel}]
|
|
||||||
</Text>
|
|
||||||
<Text color="warning.DEFAULT" fontWeight="semibold" whiteSpace="nowrap" flexShrink={0}>
|
|
||||||
{msg.sender}:
|
|
||||||
</Text>
|
|
||||||
<Text color="fg" wordBreak="break-all">
|
|
||||||
{msg.message}
|
|
||||||
</Text>
|
|
||||||
</HStack>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
<Box ref={bottomRef} />
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
import { Badge as ChakraBadge } from '@chakra-ui/react'
|
|
||||||
|
|
||||||
interface BadgeProps {
|
|
||||||
label: string
|
|
||||||
variant?: 'default' | 'success' | 'warning' | 'danger' | 'info'
|
|
||||||
}
|
|
||||||
|
|
||||||
const variantMap: Record<string, { bg: string; color: string }> = {
|
|
||||||
default: { bg: 'primary.subtle', color: 'primary.DEFAULT' },
|
|
||||||
success: { bg: 'success.subtle', color: 'success.DEFAULT' },
|
|
||||||
warning: { bg: 'warning.subtle', color: 'warning.DEFAULT' },
|
|
||||||
danger: { bg: 'danger.subtle', color: 'danger.DEFAULT' },
|
|
||||||
info: { bg: 'info.subtle', color: 'info.DEFAULT' },
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Badge({ label, variant = 'default' }: BadgeProps) {
|
|
||||||
const colors = variantMap[variant] ?? variantMap.default
|
|
||||||
|
|
||||||
return (
|
|
||||||
<ChakraBadge
|
|
||||||
variant="subtle"
|
|
||||||
bg={colors.bg}
|
|
||||||
color={colors.color}
|
|
||||||
borderRadius="full"
|
|
||||||
px={2.5}
|
|
||||||
py={0.5}
|
|
||||||
fontSize="xs"
|
|
||||||
fontWeight="medium"
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</ChakraBadge>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,139 +0,0 @@
|
|||||||
import { ReactNode, useState } from 'react'
|
|
||||||
import { Table, Flex, Text, Spinner } from '@chakra-ui/react'
|
|
||||||
import { FiChevronUp, FiChevronDown } from 'react-icons/fi'
|
|
||||||
|
|
||||||
interface Column<T> {
|
|
||||||
header: string
|
|
||||||
accessor: keyof T | ((row: T) => ReactNode)
|
|
||||||
width?: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface DataTableProps<T> {
|
|
||||||
columns: Column<T>[]
|
|
||||||
data: T[]
|
|
||||||
onRowClick?: (row: T) => void
|
|
||||||
loading?: boolean
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function DataTable<T extends object>({
|
|
||||||
columns,
|
|
||||||
data,
|
|
||||||
onRowClick,
|
|
||||||
loading,
|
|
||||||
}: DataTableProps<T>) {
|
|
||||||
const [sortCol, setSortCol] = useState<string | null>(null)
|
|
||||||
const [sortDir, setSortDir] = useState<'asc' | 'desc'>('asc')
|
|
||||||
|
|
||||||
const handleSort = (header: string) => {
|
|
||||||
if (sortCol === header) {
|
|
||||||
setSortDir(sortDir === 'asc' ? 'desc' : 'asc')
|
|
||||||
} else {
|
|
||||||
setSortCol(header)
|
|
||||||
setSortDir('asc')
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let sorted = [...data]
|
|
||||||
if (sortCol) {
|
|
||||||
const col = columns.find((c) => c.header === sortCol)
|
|
||||||
if (col && typeof col.accessor === 'string') {
|
|
||||||
sorted.sort((a, b) => {
|
|
||||||
const av = (a as any)[col.accessor as string]
|
|
||||||
const bv = (b as any)[col.accessor as string]
|
|
||||||
if (av == null && bv == null) return 0
|
|
||||||
if (av == null) return sortDir === 'asc' ? 1 : -1
|
|
||||||
if (bv == null) return sortDir === 'asc' ? -1 : 1
|
|
||||||
if (typeof av === 'string') {
|
|
||||||
return sortDir === 'asc' ? av.localeCompare(bv) : bv.localeCompare(av)
|
|
||||||
}
|
|
||||||
if (typeof av === 'number') {
|
|
||||||
return sortDir === 'asc' ? av - bv : bv - av
|
|
||||||
}
|
|
||||||
return 0
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const getCellValue = (row: T, col: Column<T>): string => {
|
|
||||||
if (typeof col.accessor === 'function') return ''
|
|
||||||
return String((row as any)[col.accessor] ?? '')
|
|
||||||
}
|
|
||||||
|
|
||||||
const getCellNode = (row: T, col: Column<T>): ReactNode => {
|
|
||||||
if (typeof col.accessor === 'function') return col.accessor(row)
|
|
||||||
return String((row as any)[col.accessor] ?? '')
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
|
|
||||||
<Table.Root variant="line" size="sm" stickyHeader>
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row bg="bg.subtle">
|
|
||||||
{columns.map((col) => (
|
|
||||||
<Table.ColumnHeader
|
|
||||||
key={col.header}
|
|
||||||
onClick={() => handleSort(col.header)}
|
|
||||||
cursor="pointer"
|
|
||||||
userSelect="none"
|
|
||||||
textTransform="uppercase"
|
|
||||||
fontSize="2xs"
|
|
||||||
letterSpacing="wider"
|
|
||||||
fontWeight="semibold"
|
|
||||||
color="fg.muted"
|
|
||||||
py={3}
|
|
||||||
px={4}
|
|
||||||
_hover={{ color: 'fg' }}
|
|
||||||
style={{ width: col.width }}
|
|
||||||
>
|
|
||||||
<Flex align="center" gap={1}>
|
|
||||||
{col.header}
|
|
||||||
{sortCol === col.header && (
|
|
||||||
<Text as="span" color="primary.DEFAULT">
|
|
||||||
{sortDir === 'asc' ? <FiChevronUp size={10} /> : <FiChevronDown size={10} />}
|
|
||||||
</Text>
|
|
||||||
)}
|
|
||||||
</Flex>
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
))}
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{loading ? (
|
|
||||||
<Table.Row>
|
|
||||||
<Table.Cell colSpan={columns.length} textAlign="center" py={8}>
|
|
||||||
<Flex align="center" justify="center" gap={2} color="fg.muted">
|
|
||||||
<Spinner size="sm" />
|
|
||||||
<Text fontSize="sm">Loading...</Text>
|
|
||||||
</Flex>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
) : sorted.length === 0 ? (
|
|
||||||
<Table.Row>
|
|
||||||
<Table.Cell colSpan={columns.length} textAlign="center" py={8} color="fg.muted" fontSize="sm">
|
|
||||||
No results found
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
) : (
|
|
||||||
sorted.map((row, i) => (
|
|
||||||
<Table.Row
|
|
||||||
key={i}
|
|
||||||
onClick={() => onRowClick?.(row)}
|
|
||||||
cursor={onRowClick ? 'pointer' : 'default'}
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
bg={i % 2 === 0 ? 'transparent' : 'bg.subtle'}
|
|
||||||
>
|
|
||||||
{columns.map((col) => (
|
|
||||||
<Table.Cell key={col.header} py={2.5} px={4} fontSize="sm">
|
|
||||||
{getCellNode(row, col)}
|
|
||||||
</Table.Cell>
|
|
||||||
))}
|
|
||||||
</Table.Row>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Table.ScrollArea>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { ReactNode } from 'react'
|
|
||||||
import {
|
|
||||||
Dialog,
|
|
||||||
Portal,
|
|
||||||
IconButton,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiX } from 'react-icons/fi'
|
|
||||||
|
|
||||||
interface ModalProps {
|
|
||||||
open: boolean
|
|
||||||
onClose: () => void
|
|
||||||
title: string
|
|
||||||
children: ReactNode
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Modal({ open, onClose, title, children }: ModalProps) {
|
|
||||||
return (
|
|
||||||
<Dialog.Root open={open} onOpenChange={(e) => { if (!e.open) onClose() }}>
|
|
||||||
<Portal>
|
|
||||||
<Dialog.Backdrop bg="black/60" backdropFilter="blur(4px)" />
|
|
||||||
<Dialog.Positioner>
|
|
||||||
<Dialog.Content
|
|
||||||
bg="card.bg"
|
|
||||||
border="1px solid"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
maxW="600px"
|
|
||||||
w="full"
|
|
||||||
mx={4}
|
|
||||||
>
|
|
||||||
<Dialog.Header
|
|
||||||
display="flex"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="space-between"
|
|
||||||
borderBottom="1px solid"
|
|
||||||
borderColor="border"
|
|
||||||
px={6}
|
|
||||||
py={4}
|
|
||||||
>
|
|
||||||
<Dialog.Title
|
|
||||||
fontSize="lg"
|
|
||||||
fontWeight="semibold"
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
{title}
|
|
||||||
</Dialog.Title>
|
|
||||||
<Dialog.CloseTrigger asChild>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Close"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={onClose}
|
|
||||||
color="fg.muted"
|
|
||||||
_hover={{ color: 'fg' }}
|
|
||||||
>
|
|
||||||
<FiX />
|
|
||||||
</IconButton>
|
|
||||||
</Dialog.CloseTrigger>
|
|
||||||
</Dialog.Header>
|
|
||||||
<Dialog.Body px={6} py={4}>
|
|
||||||
{children}
|
|
||||||
</Dialog.Body>
|
|
||||||
</Dialog.Content>
|
|
||||||
</Dialog.Positioner>
|
|
||||||
</Portal>
|
|
||||||
</Dialog.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Heading,
|
|
||||||
Tabs,
|
|
||||||
Button,
|
|
||||||
Input,
|
|
||||||
Textarea,
|
|
||||||
Field,
|
|
||||||
Text,
|
|
||||||
VStack,
|
|
||||||
HStack,
|
|
||||||
Spinner,
|
|
||||||
Flex,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
export default function Director() {
|
|
||||||
const [tab, setTab] = useState('battlegroup')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: bgData, isLoading: bgLoading } = useSWR('/director/battlegroup', fetcher, {
|
|
||||||
refreshInterval: 15000,
|
|
||||||
})
|
|
||||||
|
|
||||||
const handlePost = async (endpoint: string, payload: any) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(endpoint, payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Success', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
|
|
||||||
Director Control
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value)} variant="line" mb={6}>
|
|
||||||
<Tabs.List borderBottomWidth="1px" borderColor="border">
|
|
||||||
<Tabs.Trigger value="battlegroup" fontWeight="medium">
|
|
||||||
Battlegroup
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="config" fontWeight="medium">
|
|
||||||
Config
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="transfer" fontWeight="medium">
|
|
||||||
Transfer
|
|
||||||
</Tabs.Trigger>
|
|
||||||
<Tabs.Trigger value="fls" fontWeight="medium">
|
|
||||||
FLS
|
|
||||||
</Tabs.Trigger>
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="battlegroup" pt={6}>
|
|
||||||
<Box
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
p={5}
|
|
||||||
>
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted" mb={4}>
|
|
||||||
Battlegroup State
|
|
||||||
</Text>
|
|
||||||
{bgLoading ? (
|
|
||||||
<Flex align="center" gap={2} color="fg.muted">
|
|
||||||
<Spinner size="sm" />
|
|
||||||
<Text fontSize="sm">Loading battlegroup data...</Text>
|
|
||||||
</Flex>
|
|
||||||
) : bgData?.success ? (
|
|
||||||
<Box
|
|
||||||
as="pre"
|
|
||||||
fontSize="xs"
|
|
||||||
color="fg"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
bg="code.bg"
|
|
||||||
p={4}
|
|
||||||
borderRadius="lg"
|
|
||||||
overflow="auto"
|
|
||||||
maxH="60vh"
|
|
||||||
>
|
|
||||||
{JSON.stringify(bgData.data, null, 2)}
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Text color="fg.muted">Loading battlegroup data...</Text>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="config" pt={6}>
|
|
||||||
<Box
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
p={5}
|
|
||||||
maxW="xl"
|
|
||||||
>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
|
|
||||||
Update Config
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm" color="fg.muted">
|
|
||||||
Map Name
|
|
||||||
</Field.Label>
|
|
||||||
<Input
|
|
||||||
id="config-map"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
placeholder="e.g., HaggaBasin"
|
|
||||||
/>
|
|
||||||
</Field.Root>
|
|
||||||
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm" color="fg.muted">
|
|
||||||
Config JSON
|
|
||||||
</Field.Label>
|
|
||||||
<Textarea
|
|
||||||
id="config-json"
|
|
||||||
rows={6}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
placeholder='{"maxPlayers": 100}'
|
|
||||||
/>
|
|
||||||
</Field.Root>
|
|
||||||
|
|
||||||
<HStack gap={2}>
|
|
||||||
<Button
|
|
||||||
variant="solid"
|
|
||||||
size="sm"
|
|
||||||
bg="primary.DEFAULT"
|
|
||||||
borderRadius="lg"
|
|
||||||
_hover={{ bg: 'primary.hover' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => {
|
|
||||||
const map = (document.getElementById('config-map') as HTMLInputElement).value
|
|
||||||
const json = (document.getElementById('config-json') as HTMLTextAreaElement).value
|
|
||||||
handlePost('/director/config', { map, config: JSON.parse(json) })
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
Update Config
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
borderColor="danger.DEFAULT/30"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
bg="danger.subtle"
|
|
||||||
borderRadius="lg"
|
|
||||||
_hover={{ bg: 'danger.subtle/80' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => handlePost('/director/config/clear', {})}
|
|
||||||
>
|
|
||||||
Clear Config
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="transfer" pt={6}>
|
|
||||||
<Box
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
p={5}
|
|
||||||
maxW="xl"
|
|
||||||
>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
|
|
||||||
Transfer Rules
|
|
||||||
</Text>
|
|
||||||
<HStack gap={2}>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
borderColor="danger.DEFAULT/30"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
bg="danger.subtle"
|
|
||||||
borderRadius="lg"
|
|
||||||
_hover={{ bg: 'danger.subtle/80' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => handlePost('/director/transfer/clear', {})}
|
|
||||||
>
|
|
||||||
Clear Overrides
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="fls" pt={6}>
|
|
||||||
<Box
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
p={5}
|
|
||||||
maxW="xl"
|
|
||||||
>
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
|
|
||||||
FLS Settings
|
|
||||||
</Text>
|
|
||||||
<HStack gap={2}>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
borderColor="danger.DEFAULT/30"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
bg="danger.subtle"
|
|
||||||
borderRadius="lg"
|
|
||||||
_hover={{ bg: 'danger.subtle/80' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => handlePost('/director/fls/clear', {})}
|
|
||||||
>
|
|
||||||
Clear FLS Overrides
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@@ -1,733 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import {
|
|
||||||
Box, Flex, Text, Heading, Tabs, Card, Button,
|
|
||||||
Input, Textarea, Select, SimpleGrid, VStack, HStack,
|
|
||||||
Field, Spinner, Badge as ChakraBadge, Switch, Separator,
|
|
||||||
NumberInput, Table, createListCollection,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import {
|
|
||||||
FiSend, FiUsers, FiSearch, FiRefreshCw, FiDollarSign,
|
|
||||||
FiFlag, FiShield, FiBox, FiMap, FiDatabase,
|
|
||||||
FiTerminal, FiPlay, FiAlertTriangle, FiTrash2,
|
|
||||||
FiTag, FiUser, FiGlobe, FiRadio, FiCode,
|
|
||||||
} from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
const apiPost = async (url: string, body?: unknown) => {
|
|
||||||
const res = await client.post(url, body)
|
|
||||||
return res.data
|
|
||||||
}
|
|
||||||
|
|
||||||
const apiGet = async (url: string) => {
|
|
||||||
const res = await client.get(url)
|
|
||||||
return res.data
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Experimental() {
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
const [tab, setTab] = useState('broadcast')
|
|
||||||
const [loading, setLoading] = useState<string | null>(null)
|
|
||||||
|
|
||||||
const doAction = async (url: string, body: unknown, label: string) => {
|
|
||||||
setLoading(label)
|
|
||||||
try {
|
|
||||||
const result = await apiPost(url, body)
|
|
||||||
if (result.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: `${label} succeeded`, type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: result.error || `${label} failed`, type: 'error' } })
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
} catch {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: `${label} failed`, type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setLoading(null)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Flex align="center" gap={3} mb={2}>
|
|
||||||
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT">
|
|
||||||
Experimental
|
|
||||||
</Heading>
|
|
||||||
<ChakraBadge variant="subtle" bg="warning.subtle" color="warning.DEFAULT" borderRadius="full" px={3} py={1}>
|
|
||||||
<FiAlertTriangle size={12} style={{ display: 'inline', marginRight: '4px' }} />
|
|
||||||
Testing Area
|
|
||||||
</ChakraBadge>
|
|
||||||
</Flex>
|
|
||||||
<Text color="fg.muted" fontSize="sm" mb={6}>
|
|
||||||
Experimental tools for RMQ API testing. Features are unstable and subject to change.
|
|
||||||
</Text>
|
|
||||||
|
|
||||||
<Tabs.Root value={tab} onValueChange={(e) => setTab(e.value)} variant="line" mb={6}>
|
|
||||||
<Tabs.List borderBottomWidth="1px" borderColor="border" gap={0} overflowX="auto">
|
|
||||||
{[
|
|
||||||
{ value: 'broadcast', label: 'Broadcast', icon: FiRadio },
|
|
||||||
{ value: 'players', label: 'Players', icon: FiUsers },
|
|
||||||
{ value: 'guilds', label: 'Guilds', icon: FiShield },
|
|
||||||
{ value: 'world', label: 'World', icon: FiGlobe },
|
|
||||||
{ value: 'functions', label: 'Functions', icon: FiCode },
|
|
||||||
{ value: 'query', label: 'Raw Query', icon: FiDatabase },
|
|
||||||
].map(({ value, label, icon: Icon }) => (
|
|
||||||
<Tabs.Trigger
|
|
||||||
key={value}
|
|
||||||
value={value}
|
|
||||||
px={3} py={2.5} fontSize="sm" fontWeight="medium"
|
|
||||||
color="fg.muted"
|
|
||||||
borderBottom="2px solid transparent"
|
|
||||||
_selected={{ color: 'primary.DEFAULT', borderColor: 'primary.DEFAULT' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
gap={1.5}
|
|
||||||
>
|
|
||||||
<Icon size={14} />
|
|
||||||
{label}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
))}
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="broadcast" pt={4}>
|
|
||||||
<BroadcastTab dispatch={dispatch} />
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="players" pt={4}>
|
|
||||||
<PlayersTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="guilds" pt={4}>
|
|
||||||
<GuildsTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="world" pt={4}>
|
|
||||||
<WorldTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="functions" pt={4}>
|
|
||||||
<FunctionsTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="query" pt={4}>
|
|
||||||
<RawQueryTab dispatch={dispatch} loading={loading} setLoading={setLoading} />
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function CardSection({ title, icon: Icon, children }: { title: string; icon: React.ElementType; children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={3}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<Icon size={16} />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
{title}
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
{children}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BroadcastTab({ dispatch }: { dispatch: ReturnType<typeof useApp>['dispatch'] }) {
|
|
||||||
const [title, setTitle] = useState('Server Notice')
|
|
||||||
const [message, setMessage] = useState('')
|
|
||||||
const [duration, setDuration] = useState(30)
|
|
||||||
const [sending, setSending] = useState(false)
|
|
||||||
|
|
||||||
const send = async () => {
|
|
||||||
setSending(true)
|
|
||||||
try {
|
|
||||||
const res = await apiPost('/admin-experimental/broadcast', { title, message, duration })
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Broadcast sent' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
|
|
||||||
} catch {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Broadcast failed', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setSending(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<CardSection title="Send Broadcast" icon={FiRadio}>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={4}>Send a notification to all connected players via RabbitMQ heartbeats exchange.</Text>
|
|
||||||
<VStack align="stretch" gap={4}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm" color="fg">Title</Field.Label>
|
|
||||||
<Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Server Notice" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm" color="fg">Message</Field.Label>
|
|
||||||
<Textarea value={message} onChange={(e) => setMessage(e.target.value)} placeholder="Broadcast message..." rows={3} />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm" color="fg">Duration (seconds)</Field.Label>
|
|
||||||
<NumberInput.Root value={String(duration)} onValueChange={(v) => setDuration(Number(v.value))} min={5} max={300}>
|
|
||||||
<NumberInput.Input />
|
|
||||||
</NumberInput.Root>
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={send} loading={sending}><FiSend size={14} />
|
|
||||||
Send Broadcast
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function PlayersTab({ dispatch, loading, setLoading }: {
|
|
||||||
dispatch: ReturnType<typeof useApp>['dispatch']
|
|
||||||
loading: string | null
|
|
||||||
setLoading: (v: string | null) => void
|
|
||||||
}) {
|
|
||||||
const [searchTerm, setSearchTerm] = useState('')
|
|
||||||
const [searchResults, setSearchResults] = useState<any>(null)
|
|
||||||
const [onlinePlayers, setOnlinePlayers] = useState<any>(null)
|
|
||||||
const [currencyPid, setCurrencyPid] = useState('')
|
|
||||||
const [currencyCid, setCurrencyCid] = useState('0')
|
|
||||||
const [currencyDelta, setCurrencyDelta] = useState('1000')
|
|
||||||
const [currencyResult, setCurrencyResult] = useState<any>(null)
|
|
||||||
const [factionPid, setFactionPid] = useState('')
|
|
||||||
const [factionId, setFactionId] = useState('')
|
|
||||||
const [teleportPid, setTeleportPid] = useState('')
|
|
||||||
const [teleportX, setTeleportX] = useState('')
|
|
||||||
const [teleportY, setTeleportY] = useState('')
|
|
||||||
const [teleportZ, setTeleportZ] = useState('')
|
|
||||||
const [tagPid, setTagPid] = useState('')
|
|
||||||
const [tagKey, setTagKey] = useState('')
|
|
||||||
const [tagValue, setTagValue] = useState('')
|
|
||||||
const [tagResult, setTagResult] = useState<any>(null)
|
|
||||||
const [cheaterPid, setCheaterPid] = useState('')
|
|
||||||
const [cheaterReason, setCheaterReason] = useState('')
|
|
||||||
|
|
||||||
const search = async () => {
|
|
||||||
setLoading('search')
|
|
||||||
try {
|
|
||||||
const res = await apiPost('/admin-experimental/search-players', { term: searchTerm })
|
|
||||||
setSearchResults(res)
|
|
||||||
} finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const loadOnline = async () => {
|
|
||||||
setLoading('online')
|
|
||||||
try {
|
|
||||||
const res = await apiGet('/admin-experimental/online-players')
|
|
||||||
setOnlinePlayers(res)
|
|
||||||
} finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const adjustCurrency = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/adjust-currency', {
|
|
||||||
player_id: Number(currencyPid),
|
|
||||||
currency_id: Number(currencyCid),
|
|
||||||
delta: Number(currencyDelta),
|
|
||||||
})
|
|
||||||
if (res.success) dispatch({ type: 'ADD_TOAST', payload: { message: 'Currency adjusted', type: 'success' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const viewCurrency = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/currency-balances', { player_id: Number(currencyPid) })
|
|
||||||
setCurrencyResult(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
const changeFaction = async () => {
|
|
||||||
await apiPost('/admin-experimental/change-faction', { player_id: Number(factionPid), faction_id: Number(factionId) })
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Faction change requested', type: 'info' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const doTeleport = async () => {
|
|
||||||
await apiPost('/admin-experimental/teleport', {
|
|
||||||
player_id: Number(teleportPid),
|
|
||||||
x: Number(teleportX),
|
|
||||||
y: Number(teleportY),
|
|
||||||
z: Number(teleportZ),
|
|
||||||
})
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Teleport requested', type: 'info' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const getTags = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/player-tags', { player_id: Number(tagPid) })
|
|
||||||
setTagResult(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
const setTag = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/player-tags', {
|
|
||||||
player_id: Number(tagPid),
|
|
||||||
key: tagKey,
|
|
||||||
value: tagValue,
|
|
||||||
action: 'set',
|
|
||||||
})
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Tag set' : 'Failed', type: res.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const flagCheater = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/flag-cheater', {
|
|
||||||
player_id: Number(cheaterPid),
|
|
||||||
reason: cheaterReason,
|
|
||||||
})
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Player flagged' : 'Failed', type: res.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<CardSection title="Search Players" icon={FiSearch}>
|
|
||||||
<Flex gap={2} mb={4}>
|
|
||||||
<Input value={searchTerm} onChange={(e) => setSearchTerm(e.target.value)} placeholder="Character name..." />
|
|
||||||
<Button onClick={search} loading={loading === 'search'}><FiSearch size={14} /> Search</Button>
|
|
||||||
</Flex>
|
|
||||||
{searchResults && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
|
|
||||||
{JSON.stringify(searchResults, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Online Players" icon={FiUsers}>
|
|
||||||
<Button onClick={loadOnline} loading={loading === 'online'} mb={4}><FiRefreshCw size={14} /> Refresh</Button>
|
|
||||||
{onlinePlayers && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
|
|
||||||
{JSON.stringify(onlinePlayers, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Adjust Currency" icon={FiDollarSign}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player Controller ID</Field.Label>
|
|
||||||
<Input value={currencyPid} onChange={(e) => setCurrencyPid(e.target.value)} placeholder="e.g. 81" />
|
|
||||||
</Field.Root>
|
|
||||||
<Flex gap={3}>
|
|
||||||
<Box flex={1}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Currency</Field.Label>
|
|
||||||
<Select.Root
|
|
||||||
value={[currencyCid]}
|
|
||||||
onValueChange={(e) => setCurrencyCid(e.value[0])}
|
|
||||||
collection={createListCollection({ items: [
|
|
||||||
{ value: '0', label: 'Solari Credits' },
|
|
||||||
{ value: '1', label: 'House Script' },
|
|
||||||
{ value: '2', label: 'Spice' },
|
|
||||||
]})}
|
|
||||||
size="sm"
|
|
||||||
>
|
|
||||||
<Select.Trigger>
|
|
||||||
<Select.ValueText placeholder="Select currency" />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{createListCollection({ items: [
|
|
||||||
{ value: '0', label: 'Solari Credits' },
|
|
||||||
{ value: '1', label: 'House Script' },
|
|
||||||
{ value: '2', label: 'Spice' },
|
|
||||||
]}).items.map((item) => (
|
|
||||||
<Select.Item key={item.value} item={item}>
|
|
||||||
{item.label}
|
|
||||||
</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
</Field.Root>
|
|
||||||
</Box>
|
|
||||||
<Box flex={1}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Delta</Field.Label>
|
|
||||||
<Input value={currencyDelta} onChange={(e) => setCurrencyDelta(e.target.value)} type="number" />
|
|
||||||
</Field.Root>
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button onClick={adjustCurrency}><FiDollarSign size={14} /> Apply</Button>
|
|
||||||
<Button variant="outline" onClick={viewCurrency}><FiSearch size={14} /> View Balances</Button>
|
|
||||||
</Flex>
|
|
||||||
{currencyResult && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
|
|
||||||
{JSON.stringify(currencyResult, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Change Faction" icon={FiFlag}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player ID</Field.Label>
|
|
||||||
<Input value={factionPid} onChange={(e) => setFactionPid(e.target.value)} placeholder="e.g. 81" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">New Faction ID</Field.Label>
|
|
||||||
<Input value={factionId} onChange={(e) => setFactionId(e.target.value)} placeholder="Faction ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={changeFaction}><FiFlag size={14} /> Change Faction</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Teleport Player" icon={FiMap}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player ID</Field.Label>
|
|
||||||
<Input value={teleportPid} onChange={(e) => setTeleportPid(e.target.value)} placeholder="Player ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<SimpleGrid columns={3} gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">X</Field.Label>
|
|
||||||
<Input value={teleportX} onChange={(e) => setTeleportX(e.target.value)} placeholder="X" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Y</Field.Label>
|
|
||||||
<Input value={teleportY} onChange={(e) => setTeleportY(e.target.value)} placeholder="Y" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Z</Field.Label>
|
|
||||||
<Input value={teleportZ} onChange={(e) => setTeleportZ(e.target.value)} placeholder="Z" />
|
|
||||||
</Field.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
<Button onClick={doTeleport}><FiMap size={14} /> Teleport</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Player Tags" icon={FiTag}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player ID</Field.Label>
|
|
||||||
<Input value={tagPid} onChange={(e) => setTagPid(e.target.value)} placeholder="Player ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Flex gap={3}>
|
|
||||||
<Box flex={1}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Key</Field.Label>
|
|
||||||
<Input value={tagKey} onChange={(e) => setTagKey(e.target.value)} placeholder="Tag key" />
|
|
||||||
</Field.Root>
|
|
||||||
</Box>
|
|
||||||
<Box flex={1}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Value</Field.Label>
|
|
||||||
<Input value={tagValue} onChange={(e) => setTagValue(e.target.value)} placeholder="Tag value" />
|
|
||||||
</Field.Root>
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button onClick={getTags}><FiSearch size={14} /> Get Tags</Button>
|
|
||||||
<Button onClick={setTag}><FiTag size={14} /> Set Tag</Button>
|
|
||||||
</Flex>
|
|
||||||
{tagResult && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
|
|
||||||
{JSON.stringify(tagResult, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Flag Cheater" icon={FiAlertTriangle}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player ID</Field.Label>
|
|
||||||
<Input value={cheaterPid} onChange={(e) => setCheaterPid(e.target.value)} placeholder="Player ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Reason</Field.Label>
|
|
||||||
<Textarea value={cheaterReason} onChange={(e) => setCheaterReason(e.target.value)} placeholder="Reason for flagging..." rows={2} />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={flagCheater}><FiFlag size={14} /> Flag Cheater</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function GuildsTab({ dispatch, loading, setLoading }: {
|
|
||||||
dispatch: ReturnType<typeof useApp>['dispatch']
|
|
||||||
loading: string | null
|
|
||||||
setLoading: (v: string | null) => void
|
|
||||||
}) {
|
|
||||||
const [guildsData, setGuildsData] = useState<any>(null)
|
|
||||||
const [guildId, setGuildId] = useState('')
|
|
||||||
const [guildInfo, setGuildInfo] = useState<any>(null)
|
|
||||||
const [disbandId, setDisbandId] = useState('')
|
|
||||||
const [removeGuildId, setRemoveGuildId] = useState('')
|
|
||||||
const [removePlayerId, setRemovePlayerId] = useState('')
|
|
||||||
|
|
||||||
const listGuilds = async () => {
|
|
||||||
setLoading('guilds')
|
|
||||||
try {
|
|
||||||
const res = await apiGet('/admin-experimental/guilds')
|
|
||||||
setGuildsData(res)
|
|
||||||
} finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const getGuildData = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/guild-data', { guild_id: Number(guildId) })
|
|
||||||
setGuildInfo(res)
|
|
||||||
}
|
|
||||||
|
|
||||||
const disbandGuild = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/disband-guild', { guild_id: Number(disbandId) })
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Guild disbanded' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const removeMember = async () => {
|
|
||||||
const res = await apiPost('/admin-experimental/remove-guild-member', {
|
|
||||||
guild_id: Number(removeGuildId),
|
|
||||||
player_id: Number(removePlayerId),
|
|
||||||
})
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.success ? 'Member removed' : (res.error || 'Failed'), type: res.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<CardSection title="Guild List" icon={FiShield}>
|
|
||||||
<Button onClick={listGuilds} loading={loading === 'guilds'} mb={4}><FiRefreshCw size={14} /> Load Guilds</Button>
|
|
||||||
{guildsData && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="400px">
|
|
||||||
{JSON.stringify(guildsData, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Guild Info" icon={FiSearch}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Guild ID</Field.Label>
|
|
||||||
<Input value={guildId} onChange={(e) => setGuildId(e.target.value)} placeholder="Guild ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={getGuildData}><FiSearch size={14} /> Get Info</Button>
|
|
||||||
{guildInfo && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
|
|
||||||
{JSON.stringify(guildInfo, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Disband Guild" icon={FiTrash2}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Guild ID</Field.Label>
|
|
||||||
<Input value={disbandId} onChange={(e) => setDisbandId(e.target.value)} placeholder="Guild ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={disbandGuild}><FiTrash2 size={14} /> Disband Guild</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Remove Guild Member" icon={FiUser}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Guild ID</Field.Label>
|
|
||||||
<Input value={removeGuildId} onChange={(e) => setRemoveGuildId(e.target.value)} placeholder="Guild ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Player ID</Field.Label>
|
|
||||||
<Input value={removePlayerId} onChange={(e) => setRemovePlayerId(e.target.value)} placeholder="Player ID" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={removeMember}><FiUser size={14} /> Remove Member</Button>
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function WorldTab({ dispatch, loading, setLoading }: {
|
|
||||||
dispatch: ReturnType<typeof useApp>['dispatch']
|
|
||||||
loading: string | null
|
|
||||||
setLoading: (v: string | null) => void
|
|
||||||
}) {
|
|
||||||
const [partitionsData, setPartitionsData] = useState<any>(null)
|
|
||||||
const [spiceData, setSpiceData] = useState<any>(null)
|
|
||||||
const [vendorResult, setVendorResult] = useState<any>(null)
|
|
||||||
const [taxResult, setTaxResult] = useState<any>(null)
|
|
||||||
|
|
||||||
const loadPartitions = async () => {
|
|
||||||
setLoading('partitions')
|
|
||||||
try { const r = await apiGet('/admin-experimental/partitions'); setPartitionsData(r) } finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const cleanVendor = async () => {
|
|
||||||
const r = await apiPost('/admin-experimental/clean-vendor-stock', {})
|
|
||||||
setVendorResult(r)
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Vendor stock cleaned' : 'Failed', type: r.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
const getTaxInvoices = async () => {
|
|
||||||
const r = await apiPost('/admin-experimental/tax-invoices', {})
|
|
||||||
setTaxResult(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
const controlSpice = async (action: string) => {
|
|
||||||
const r = await apiPost('/admin-experimental/spice', { action })
|
|
||||||
setSpiceData(r)
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Spice action completed' : 'Failed', type: r.success ? 'success' : 'error' } })
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<CardSection title="Partitions" icon={FiMap}>
|
|
||||||
<Button onClick={loadPartitions} loading={loading === 'partitions'} mb={4}><FiRefreshCw size={14} /> Load</Button>
|
|
||||||
{partitionsData && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
|
|
||||||
{JSON.stringify(partitionsData, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Spice Fields" icon={FiBox}>
|
|
||||||
<Flex gap={2} mb={4} wrap="wrap">
|
|
||||||
<Button size="sm" onClick={() => controlSpice('list')}>List</Button>
|
|
||||||
<Button size="sm" onClick={() => controlSpice('reset')}>Reset</Button>
|
|
||||||
<Button size="sm" onClick={() => controlSpice('regenerate')}>Regenerate</Button>
|
|
||||||
</Flex>
|
|
||||||
{spiceData && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px">
|
|
||||||
{JSON.stringify(spiceData, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Vendor Stock" icon={FiBox}>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={4}>Clean all vendor stock entries.</Text>
|
|
||||||
<Button onClick={cleanVendor}><FiRefreshCw size={14} /> Clean Stock</Button>
|
|
||||||
{vendorResult && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="200px" mt={4}>
|
|
||||||
{JSON.stringify(vendorResult, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Tax Invoices" icon={FiDollarSign}>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={4}>View tax invoice data.</Text>
|
|
||||||
<Button onClick={getTaxInvoices} mb={4}><FiSearch size={14} /> Load Invoices</Button>
|
|
||||||
{taxResult && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
|
|
||||||
{JSON.stringify(taxResult, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function FunctionsTab({ dispatch, loading, setLoading }: {
|
|
||||||
dispatch: ReturnType<typeof useApp>['dispatch']
|
|
||||||
loading: string | null
|
|
||||||
setLoading: (v: string | null) => void
|
|
||||||
}) {
|
|
||||||
const [functionsData, setFunctionsData] = useState<any>(null)
|
|
||||||
const [funcName, setFuncName] = useState('')
|
|
||||||
const [funcInfo, setFuncInfo] = useState<any>(null)
|
|
||||||
const [funcArgs, setFuncArgs] = useState('{}')
|
|
||||||
const [execResult, setExecResult] = useState<any>(null)
|
|
||||||
|
|
||||||
const listFunctions = async () => {
|
|
||||||
setLoading('functions')
|
|
||||||
try { const r = await apiGet('/admin-experimental/functions'); setFunctionsData(r) } finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
const getFunctionInfo = async () => {
|
|
||||||
const r = await apiGet(`/admin-experimental/functions/${funcName}`)
|
|
||||||
setFuncInfo(r)
|
|
||||||
}
|
|
||||||
|
|
||||||
const executeFunction = async () => {
|
|
||||||
setLoading('exec')
|
|
||||||
try {
|
|
||||||
const r = await apiPost(`/admin-experimental/functions/${funcName}/execute`, JSON.parse(funcArgs))
|
|
||||||
setExecResult(r)
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: r.success ? 'Executed' : (r.error || 'Failed'), type: r.success ? 'success' : 'error' } })
|
|
||||||
} finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<CardSection title="Stored Procedures" icon={FiCode}>
|
|
||||||
<Button onClick={listFunctions} loading={loading === 'functions'} mb={4}><FiRefreshCw size={14} /> Load Functions</Button>
|
|
||||||
{functionsData && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="400px">
|
|
||||||
{JSON.stringify(functionsData, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</CardSection>
|
|
||||||
|
|
||||||
<CardSection title="Execute Function" icon={FiPlay}>
|
|
||||||
<VStack align="stretch" gap={3}>
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Function Name</Field.Label>
|
|
||||||
<Input value={funcName} onChange={(e) => setFuncName(e.target.value)} placeholder="schema.function_name" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button variant="outline" onClick={getFunctionInfo}><FiSearch size={14} /> Get Info</Button>
|
|
||||||
{funcInfo && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="150px">
|
|
||||||
{JSON.stringify(funcInfo, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
<Field.Root>
|
|
||||||
<Field.Label fontSize="sm">Arguments (JSON array)</Field.Label>
|
|
||||||
<Textarea value={funcArgs} onChange={(e) => setFuncArgs(e.target.value)} rows={3} fontFamily="Roboto Mono, monospace" fontSize="xs" />
|
|
||||||
</Field.Root>
|
|
||||||
<Button onClick={executeFunction} loading={loading === 'exec'}><FiPlay size={14} /> Execute</Button>
|
|
||||||
{execResult && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={3} borderRadius="md" overflow="auto" maxH="300px">
|
|
||||||
{JSON.stringify(execResult, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</CardSection>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function RawQueryTab({ dispatch, loading, setLoading }: {
|
|
||||||
dispatch: ReturnType<typeof useApp>['dispatch']
|
|
||||||
loading: string | null
|
|
||||||
setLoading: (v: string | null) => void
|
|
||||||
}) {
|
|
||||||
const [sql, setSql] = useState('')
|
|
||||||
const [result, setResult] = useState<any>(null)
|
|
||||||
|
|
||||||
const execute = async () => {
|
|
||||||
setLoading('query')
|
|
||||||
try {
|
|
||||||
const r = await apiPost('/admin-experimental/execute', { query: sql })
|
|
||||||
setResult(r)
|
|
||||||
} catch {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Query failed', type: 'error' } })
|
|
||||||
} finally { setLoading(null) }
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={3}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<FiDatabase size={16} />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
Raw SQL Query
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Text fontSize="sm" color="fg.muted" mb={4}>Execute read-only SQL queries against the database.</Text>
|
|
||||||
<VStack align="stretch" gap={4}>
|
|
||||||
<Textarea
|
|
||||||
value={sql}
|
|
||||||
onChange={(e) => setSql(e.target.value)}
|
|
||||||
placeholder="SELECT * FROM ... LIMIT 100;"
|
|
||||||
rows={6}
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
fontSize="sm"
|
|
||||||
bg="code.bg"
|
|
||||||
/>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button onClick={execute} loading={loading === 'query'}><FiPlay size={14} /> Execute</Button>
|
|
||||||
<Button variant="outline" onClick={() => { setSql(''); setResult(null) }}><FiRefreshCw size={14} /> Clear</Button>
|
|
||||||
</Flex>
|
|
||||||
{result && (
|
|
||||||
<Box as="pre" fontSize="xs" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="md" overflow="auto" maxH="500px">
|
|
||||||
{JSON.stringify(result, null, 2)}
|
|
||||||
</Box>
|
|
||||||
)}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,280 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react'
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Heading,
|
|
||||||
Button,
|
|
||||||
Flex,
|
|
||||||
HStack,
|
|
||||||
Table,
|
|
||||||
Text,
|
|
||||||
Spinner,
|
|
||||||
Dialog,
|
|
||||||
Portal,
|
|
||||||
IconButton,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiX, FiFolder, FiFile } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
interface FileEntry {
|
|
||||||
name: string
|
|
||||||
path: string
|
|
||||||
size: number
|
|
||||||
is_dir: boolean
|
|
||||||
mod_time: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function FileBrowser() {
|
|
||||||
const [path, setPath] = useState('/')
|
|
||||||
const [files, setFiles] = useState<FileEntry[]>([])
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
const [viewFile, setViewFile] = useState<{ path: string; content: string } | null>(null)
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const load = async (targetPath: string) => {
|
|
||||||
setLoading(true)
|
|
||||||
try {
|
|
||||||
const res = await client.post('/files/list', { path: targetPath })
|
|
||||||
if (res.data.success) {
|
|
||||||
setFiles(res.data.data)
|
|
||||||
setPath(targetPath)
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
load('/')
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const view = async (filePath: string) => {
|
|
||||||
try {
|
|
||||||
const res = await client.get(`/files/view?path=${encodeURIComponent(filePath)}`)
|
|
||||||
if (res.data.success) {
|
|
||||||
setViewFile({ path: filePath, content: res.data.data })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const breadcrumbs = path.split('/').filter(Boolean)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
|
|
||||||
File Browser
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<HStack gap={1} mb={4} fontSize="sm">
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
fontWeight="normal"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={() => load('/')}
|
|
||||||
>
|
|
||||||
/
|
|
||||||
</Button>
|
|
||||||
{breadcrumbs.map((crumb, i) => {
|
|
||||||
const crumbPath = '/' + breadcrumbs.slice(0, i + 1).join('/')
|
|
||||||
return (
|
|
||||||
<HStack key={i} gap={1}>
|
|
||||||
<Text color="fg.muted">/</Text>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
fontWeight="normal"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={() => load(crumbPath)}
|
|
||||||
>
|
|
||||||
{crumb}
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</HStack>
|
|
||||||
|
|
||||||
<Box bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" overflow="hidden" boxShadow="card">
|
|
||||||
<Table.ScrollArea>
|
|
||||||
<Table.Root variant="line" size="sm">
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row bg="bg.subtle">
|
|
||||||
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
Name
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
Size
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
Modified
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader px={4} py={3} fontSize="2xs" fontWeight="semibold" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
Actions
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{path !== '/' && (
|
|
||||||
<Table.Row
|
|
||||||
cursor="pointer"
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => {
|
|
||||||
const parent = path.substring(0, path.lastIndexOf('/')) || '/'
|
|
||||||
load(parent)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
<Table.Cell px={4} py={3} color="fg">
|
|
||||||
..
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>-</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>-</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>-</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
)}
|
|
||||||
{loading ? (
|
|
||||||
<Table.Row>
|
|
||||||
<Table.Cell colSpan={4} textAlign="center" py={8}>
|
|
||||||
<Flex align="center" justify="center" gap={2} color="fg.muted">
|
|
||||||
<Spinner size="sm" />
|
|
||||||
<Text fontSize="sm">Loading...</Text>
|
|
||||||
</Flex>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
) : files.length === 0 ? (
|
|
||||||
<Table.Row>
|
|
||||||
<Table.Cell colSpan={4} textAlign="center" py={8} color="fg.muted" fontSize="sm">
|
|
||||||
<Flex direction="column" align="center" gap={1}>
|
|
||||||
<FiFolder size={24} />
|
|
||||||
<Text>This directory is empty</Text>
|
|
||||||
</Flex>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
) : (
|
|
||||||
files.map((f, i) => (
|
|
||||||
<Table.Row
|
|
||||||
key={f.path}
|
|
||||||
cursor="pointer"
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
bg={i % 2 === 0 ? 'transparent' : 'bg.subtle'}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={() => f.is_dir && load(f.path)}
|
|
||||||
>
|
|
||||||
<Table.Cell px={4} py={3} color="fg">
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
{f.is_dir ? <FiFolder size={16} /> : <FiFile size={16} />}
|
|
||||||
{f.name}
|
|
||||||
</Flex>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3} color="fg.muted">{f.is_dir ? '-' : formatBytes(f.size)}</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3} color="fg.muted">{new Date(f.mod_time).toLocaleString()}</Table.Cell>
|
|
||||||
<Table.Cell px={4} py={3}>
|
|
||||||
{!f.is_dir && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={(e) => { e.stopPropagation(); view(f.path) }}
|
|
||||||
>
|
|
||||||
View
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Table.ScrollArea>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Dialog.Root open={!!viewFile} onOpenChange={(details) => { if (!details.open) setViewFile(null) }}>
|
|
||||||
<Portal>
|
|
||||||
<Dialog.Backdrop bg="black/60" backdropFilter="blur(4px)" />
|
|
||||||
<Dialog.Positioner>
|
|
||||||
<Dialog.Content
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
maxW="4xl"
|
|
||||||
w="full"
|
|
||||||
mx={4}
|
|
||||||
maxH="80vh"
|
|
||||||
display="flex"
|
|
||||||
flexDirection="column"
|
|
||||||
>
|
|
||||||
<Dialog.Header
|
|
||||||
display="flex"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="space-between"
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
px={5}
|
|
||||||
py={4}
|
|
||||||
>
|
|
||||||
<Dialog.Title
|
|
||||||
fontSize="lg"
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
truncate
|
|
||||||
>
|
|
||||||
{viewFile?.path}
|
|
||||||
</Dialog.Title>
|
|
||||||
<Dialog.CloseTrigger asChild>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Close"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={() => setViewFile(null)}
|
|
||||||
color="fg.muted"
|
|
||||||
_hover={{ color: 'fg' }}
|
|
||||||
>
|
|
||||||
<FiX />
|
|
||||||
</IconButton>
|
|
||||||
</Dialog.CloseTrigger>
|
|
||||||
</Dialog.Header>
|
|
||||||
<Dialog.Body p={5} overflow="auto" flex={1}>
|
|
||||||
<Box
|
|
||||||
as="pre"
|
|
||||||
fontSize="xs"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
color="fg"
|
|
||||||
bg="code.bg"
|
|
||||||
p={4}
|
|
||||||
borderRadius="md"
|
|
||||||
overflow="auto"
|
|
||||||
whiteSpace="pre-wrap"
|
|
||||||
>
|
|
||||||
{viewFile?.content}
|
|
||||||
</Box>
|
|
||||||
</Dialog.Body>
|
|
||||||
</Dialog.Content>
|
|
||||||
</Dialog.Positioner>
|
|
||||||
</Portal>
|
|
||||||
</Dialog.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatBytes(bytes: number): string {
|
|
||||||
if (bytes === 0) return '0 B'
|
|
||||||
const k = 1024
|
|
||||||
const sizes = ['B', 'KB', 'MB', 'GB']
|
|
||||||
const i = Math.floor(Math.log(bytes) / Math.log(k))
|
|
||||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
|
|
||||||
}
|
|
||||||
@@ -1,320 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Heading,
|
|
||||||
Input,
|
|
||||||
HStack,
|
|
||||||
VStack,
|
|
||||||
SimpleGrid,
|
|
||||||
Button,
|
|
||||||
Table,
|
|
||||||
Text,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiSearch, FiTrash2, FiAlertTriangle } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import DataTable from '../common/DataTable'
|
|
||||||
import Modal from '../common/Modal'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Guild {
|
|
||||||
guild_id: number
|
|
||||||
guild_name: string
|
|
||||||
guild_description: string | null
|
|
||||||
faction_name: string | null
|
|
||||||
member_count: number
|
|
||||||
online_count: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface GuildMember {
|
|
||||||
player_id: number
|
|
||||||
role_id: number
|
|
||||||
role_name: string
|
|
||||||
player_name: string
|
|
||||||
online_status: string
|
|
||||||
}
|
|
||||||
|
|
||||||
function InfoRow({ label, value }: { label: string; value: any }) {
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">
|
|
||||||
{label}
|
|
||||||
</Text>
|
|
||||||
<Text fontFamily="Roboto Mono, monospace" color="fg">
|
|
||||||
{value ?? 'N/A'}
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function GuildManager() {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const [selected, setSelected] = useState<Guild | null>(null)
|
|
||||||
const [detail, setDetail] = useState<any>(null)
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: guilds, isLoading } = useSWR(
|
|
||||||
search.length >= 2 ? `/guilds?q=${encodeURIComponent(search)}&limit=25` : null,
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const loadDetail = async (guildId: number) => {
|
|
||||||
try {
|
|
||||||
const res = await client.get(`/guilds/${guildId}`)
|
|
||||||
if (res.data.success) setDetail(res.data.data)
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleDisband = async () => {
|
|
||||||
try {
|
|
||||||
const res = await client.delete(`/guilds/${selected!.guild_id}`)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Guild disbanded', type: 'success' } })
|
|
||||||
setSelected(null)
|
|
||||||
setDetail(null)
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleMemberAction = async (action: string, playerId: number, roleId?: number) => {
|
|
||||||
try {
|
|
||||||
let res
|
|
||||||
if (action === 'remove') {
|
|
||||||
res = await client.delete(`/guilds/${selected!.guild_id}/members/${playerId}`)
|
|
||||||
} else {
|
|
||||||
res = await client.put(`/guilds/${selected!.guild_id}/members/${playerId}/role`, { action, role_id: roleId })
|
|
||||||
}
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Member updated', type: 'success' } })
|
|
||||||
loadDetail(selected!.guild_id)
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const guildList: Guild[] = guilds?.success ? guilds.data : []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
|
|
||||||
Guild Manager
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Box position="relative" maxW="md" mb={6}>
|
|
||||||
<Box
|
|
||||||
position="absolute"
|
|
||||||
left={3}
|
|
||||||
top="50%"
|
|
||||||
transform="translateY(-50%)"
|
|
||||||
color="fg.muted"
|
|
||||||
zIndex={1}
|
|
||||||
pointerEvents="none"
|
|
||||||
>
|
|
||||||
<FiSearch size={16} />
|
|
||||||
</Box>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search guilds..."
|
|
||||||
pl={10}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
color="fg"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
_focus={{ borderColor: 'primary.DEFAULT' }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={[
|
|
||||||
{ header: 'Name', accessor: 'guild_name' },
|
|
||||||
{ header: 'Faction', accessor: 'faction_name' },
|
|
||||||
{ header: 'Members', accessor: 'member_count' },
|
|
||||||
{ header: 'Online', accessor: 'online_count' },
|
|
||||||
]}
|
|
||||||
data={guildList}
|
|
||||||
onRowClick={(row) => {
|
|
||||||
setSelected(row as any)
|
|
||||||
loadDetail((row as any).guild_id)
|
|
||||||
}}
|
|
||||||
loading={isLoading}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<Modal
|
|
||||||
open={!!selected}
|
|
||||||
title={selected?.guild_name || ''}
|
|
||||||
onClose={() => {
|
|
||||||
setSelected(null)
|
|
||||||
setDetail(null)
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{selected && detail && (
|
|
||||||
<VStack gap={4} align="stretch">
|
|
||||||
<SimpleGrid columns={2} gap={4}>
|
|
||||||
<InfoRow label="Guild ID" value={selected.guild_id} />
|
|
||||||
<InfoRow label="Members" value={selected.member_count} />
|
|
||||||
<InfoRow label="Faction" value={selected.faction_name || 'None'} />
|
|
||||||
<InfoRow label="Description" value={selected.guild_description || 'None'} />
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<Box borderTopWidth="1px" borderColor="border" pt={4}>
|
|
||||||
<Text fontSize="xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted" mb={3}>
|
|
||||||
Members
|
|
||||||
</Text>
|
|
||||||
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg" maxH="64">
|
|
||||||
<Table.Root size="sm" variant="line" stickyHeader>
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row bg="bg.subtle">
|
|
||||||
<Table.ColumnHeader
|
|
||||||
fontSize="2xs"
|
|
||||||
textTransform="uppercase"
|
|
||||||
letterSpacing="wider"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
Name
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader
|
|
||||||
fontSize="2xs"
|
|
||||||
textTransform="uppercase"
|
|
||||||
letterSpacing="wider"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
Role
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader
|
|
||||||
fontSize="2xs"
|
|
||||||
textTransform="uppercase"
|
|
||||||
letterSpacing="wider"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
Status
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader
|
|
||||||
fontSize="2xs"
|
|
||||||
textTransform="uppercase"
|
|
||||||
letterSpacing="wider"
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
Actions
|
|
||||||
</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{(detail.members || []).length === 0 ? (
|
|
||||||
<Table.Row>
|
|
||||||
<Table.Cell colSpan={4} textAlign="center" py={8}>
|
|
||||||
<VStack gap={2} color="fg.muted">
|
|
||||||
<FiAlertTriangle size={24} />
|
|
||||||
<Text fontSize="sm">No members found</Text>
|
|
||||||
</VStack>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
) : (
|
|
||||||
(detail.members || []).map((m: GuildMember) => (
|
|
||||||
<Table.Row
|
|
||||||
key={m.player_id}
|
|
||||||
borderBottomWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<Table.Cell py={2} px={3}>
|
|
||||||
{m.player_name}
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell py={2} px={3}>
|
|
||||||
<Text
|
|
||||||
as="span"
|
|
||||||
fontSize="2xs"
|
|
||||||
bg="primary.subtle"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="primary.DEFAULT/20"
|
|
||||||
borderRadius="full"
|
|
||||||
px={2}
|
|
||||||
py={0.5}
|
|
||||||
>
|
|
||||||
{m.role_name}
|
|
||||||
</Text>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell py={2} px={3} fontSize="xs">
|
|
||||||
{m.online_status}
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell py={2} px={3}>
|
|
||||||
<HStack gap={1}>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
fontSize="2xs"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={() => handleMemberAction('promote', m.player_id, 90)}
|
|
||||||
>
|
|
||||||
Promote
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
fontSize="2xs"
|
|
||||||
color="fg.muted"
|
|
||||||
_hover={{ textDecoration: 'underline', color: 'fg' }}
|
|
||||||
onClick={() => handleMemberAction('demote', m.player_id, 50)}
|
|
||||||
>
|
|
||||||
Demote
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
fontSize="2xs"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={() => handleMemberAction('remove', m.player_id)}
|
|
||||||
>
|
|
||||||
Remove
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Table.ScrollArea>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box borderTopWidth="1px" borderColor="border" pt={4}>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="xs"
|
|
||||||
borderColor="danger.DEFAULT/30"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
bg="danger.subtle"
|
|
||||||
borderRadius="lg"
|
|
||||||
_hover={{ bg: 'danger.subtle/80' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
onClick={handleDisband}
|
|
||||||
>
|
|
||||||
<FiTrash2 size={12} style={{ marginRight: 6 }} />
|
|
||||||
Disband Guild
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
</Modal>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,27 +0,0 @@
|
|||||||
import { Box, Flex } from '@chakra-ui/react'
|
|
||||||
import { Toaster, ToastRoot, ToastTitle, ToastDescription } from '@chakra-ui/react'
|
|
||||||
import Sidebar from './Sidebar'
|
|
||||||
import TopBar from './TopBar'
|
|
||||||
import { toaster } from '../../toaster'
|
|
||||||
|
|
||||||
export default function AppShell({ children }: { children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<Flex minH="100vh" bg="bg">
|
|
||||||
<Sidebar />
|
|
||||||
<Box flex={1} ml="260px">
|
|
||||||
<TopBar />
|
|
||||||
<Box as="main" p={6} minH="calc(100vh - 56px)">
|
|
||||||
{children}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
<Toaster toaster={toaster}>
|
|
||||||
{(toast: any) => (
|
|
||||||
<ToastRoot key={toast.id}>
|
|
||||||
{toast.title && <ToastTitle>{toast.title}</ToastTitle>}
|
|
||||||
{toast.description && <ToastDescription>{toast.description}</ToastDescription>}
|
|
||||||
</ToastRoot>
|
|
||||||
)}
|
|
||||||
</Toaster>
|
|
||||||
</Flex>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,70 +0,0 @@
|
|||||||
import { Box, Flex, Text, Tooltip, VStack, Circle } from '@chakra-ui/react'
|
|
||||||
import { FiWifi, FiWifiOff } from 'react-icons/fi'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
const SERVICES = [
|
|
||||||
{ key: 'database' as const, label: 'Database' },
|
|
||||||
{ key: 'ssh' as const, label: 'SSH Tunnel' },
|
|
||||||
{ key: 'bgd' as const, label: 'BG Director' },
|
|
||||||
{ key: 'rmq' as const, label: 'RMQ' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function ConnectionBadge() {
|
|
||||||
const { state } = useApp()
|
|
||||||
const statuses = SERVICES.map((s) => state.connectionStatus[s.key])
|
|
||||||
const upCount = statuses.filter(Boolean).length
|
|
||||||
const allUp = upCount === statuses.length
|
|
||||||
const allDown = upCount === 0
|
|
||||||
|
|
||||||
const dotColor = allUp ? 'success.DEFAULT' : allDown ? 'danger.DEFAULT' : 'warning.DEFAULT'
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<Flex
|
|
||||||
align="center"
|
|
||||||
gap={1.5}
|
|
||||||
px={2.5}
|
|
||||||
py={1}
|
|
||||||
borderRadius="full"
|
|
||||||
bg="bg.subtle"
|
|
||||||
border="1px solid"
|
|
||||||
borderColor="border.subtle"
|
|
||||||
cursor="default"
|
|
||||||
>
|
|
||||||
{allUp ? (
|
|
||||||
<FiWifi size={14} color="currentColor" />
|
|
||||||
) : (
|
|
||||||
<FiWifiOff size={14} color="currentColor" />
|
|
||||||
)}
|
|
||||||
<Circle size="6px" bg={dotColor} />
|
|
||||||
</Flex>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Positioner>
|
|
||||||
<Tooltip.Content bg="card.bg" border="1px solid" borderColor="border" borderRadius="md" p={3}>
|
|
||||||
<VStack align="stretch" gap={2} minW="160px">
|
|
||||||
<Text fontSize="xs" fontWeight="semibold" color="fg" mb={1}>
|
|
||||||
Service Status
|
|
||||||
</Text>
|
|
||||||
{SERVICES.map((s) => (
|
|
||||||
<Flex key={s.key} justify="space-between" align="center" gap={4}>
|
|
||||||
<Text fontSize="xs" color="fg.muted">
|
|
||||||
{s.label}
|
|
||||||
</Text>
|
|
||||||
<Flex align="center" gap={1.5}>
|
|
||||||
<Circle
|
|
||||||
size="6px"
|
|
||||||
bg={state.connectionStatus[s.key] ? 'success.DEFAULT' : 'danger.DEFAULT'}
|
|
||||||
/>
|
|
||||||
<Text fontSize="2xs" color="fg.muted">
|
|
||||||
{state.connectionStatus[s.key] ? 'OK' : 'DOWN'}
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Tooltip.Content>
|
|
||||||
</Tooltip.Positioner>
|
|
||||||
</Tooltip.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,59 +0,0 @@
|
|||||||
import { Link, useLocation } from 'react-router-dom'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import ThemeSwitcher from './ThemeSwitcher'
|
|
||||||
import ConnectionBadge from './ConnectionBadge'
|
|
||||||
|
|
||||||
const NAV_ITEMS = [
|
|
||||||
{ path: '/', label: 'Overview' },
|
|
||||||
{ path: '/players', label: 'Players' },
|
|
||||||
{ path: '/guilds', label: 'Guilds' },
|
|
||||||
{ path: '/vehicles', label: 'Vehicles' },
|
|
||||||
{ path: '/buildings', label: 'Buildings' },
|
|
||||||
{ path: '/map', label: 'Map' },
|
|
||||||
{ path: '/accounts', label: 'Accounts' },
|
|
||||||
{ path: '/server', label: 'Server' },
|
|
||||||
{ path: '/chat', label: 'Chat' },
|
|
||||||
{ path: '/admin', label: 'Admin' },
|
|
||||||
{ path: '/files', label: 'Files' },
|
|
||||||
{ path: '/director', label: 'Director' },
|
|
||||||
{ path: '/settings', label: 'Settings' },
|
|
||||||
{ path: '/shell', label: 'Shell' },
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function NavBar() {
|
|
||||||
const location = useLocation()
|
|
||||||
const { state } = useApp()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<nav className="sticky top-0 z-50 h-[52px] bg-nav-bg flex items-center px-6 shadow-md border-b border-border">
|
|
||||||
<div className="flex items-center gap-2 mr-8">
|
|
||||||
<span className="text-primary font-serif font-bold text-lg tracking-wide">Dune</span>
|
|
||||||
<span className="text-nav-text text-xs uppercase tracking-widest">Admin</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-1 overflow-x-auto no-scrollbar">
|
|
||||||
{NAV_ITEMS.map((item) => (
|
|
||||||
<Link
|
|
||||||
key={item.path}
|
|
||||||
to={item.path}
|
|
||||||
className={`px-4 h-[52px] flex items-center text-[13px] font-medium border-b-2 transition-colors whitespace-nowrap ${
|
|
||||||
location.pathname === item.path || (item.path !== '/' && location.pathname.startsWith(item.path))
|
|
||||||
? 'text-nav-active border-nav-active'
|
|
||||||
: 'text-nav-text border-transparent hover:text-white hover:bg-white/5'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{item.label}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="ml-auto flex items-center gap-4">
|
|
||||||
<ConnectionBadge />
|
|
||||||
<ThemeSwitcher />
|
|
||||||
{state.user && (
|
|
||||||
<span className="text-nav-text text-xs">{state.user}</span>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</nav>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,192 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { Link, useLocation } from 'react-router-dom'
|
|
||||||
import { Box, Flex, VStack, Text, Collapsible, Separator } from '@chakra-ui/react'
|
|
||||||
import { FiHome, FiServer, FiUsers, FiShield, FiMap, FiTruck, FiBox, FiMessageSquare, FiTool, FiSliders, FiUserCheck, FiFolder, FiTerminal, FiSettings, FiZap } from 'react-icons/fi'
|
|
||||||
|
|
||||||
interface NavGroup {
|
|
||||||
label: string
|
|
||||||
icon: React.ElementType
|
|
||||||
items: { path: string; label: string; icon: React.ElementType }[]
|
|
||||||
}
|
|
||||||
|
|
||||||
const NAV_GROUPS: NavGroup[] = [
|
|
||||||
{
|
|
||||||
label: 'Dashboard',
|
|
||||||
icon: FiHome,
|
|
||||||
items: [
|
|
||||||
{ path: '/', label: 'Overview', icon: FiHome },
|
|
||||||
{ path: '/server', label: 'Server', icon: FiServer },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Players & World',
|
|
||||||
icon: FiUsers,
|
|
||||||
items: [
|
|
||||||
{ path: '/players', label: 'Players', icon: FiUsers },
|
|
||||||
{ path: '/guilds', label: 'Guilds', icon: FiShield },
|
|
||||||
{ path: '/map', label: 'Map', icon: FiMap },
|
|
||||||
{ path: '/vehicles', label: 'Vehicles', icon: FiTruck },
|
|
||||||
{ path: '/buildings', label: 'Buildings', icon: FiBox },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Communication',
|
|
||||||
icon: FiMessageSquare,
|
|
||||||
items: [
|
|
||||||
{ path: '/chat', label: 'Chat Monitor', icon: FiMessageSquare },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Administration',
|
|
||||||
icon: FiTool,
|
|
||||||
items: [
|
|
||||||
{ path: '/admin', label: 'Admin Tools', icon: FiTool },
|
|
||||||
{ path: '/director', label: 'Director', icon: FiSliders },
|
|
||||||
{ path: '/accounts', label: 'Accounts', icon: FiUserCheck },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'System',
|
|
||||||
icon: FiFolder,
|
|
||||||
items: [
|
|
||||||
{ path: '/files', label: 'Files', icon: FiFolder },
|
|
||||||
{ path: '/shell', label: 'Shell', icon: FiTerminal },
|
|
||||||
{ path: '/settings', label: 'Settings', icon: FiSettings },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
label: 'Experimental',
|
|
||||||
icon: FiZap,
|
|
||||||
items: [
|
|
||||||
{ path: '/experimental', label: 'Experimental', icon: FiZap },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
]
|
|
||||||
|
|
||||||
export default function Sidebar() {
|
|
||||||
return (
|
|
||||||
<Box
|
|
||||||
as="aside"
|
|
||||||
w="260px"
|
|
||||||
minW="260px"
|
|
||||||
h="100vh"
|
|
||||||
position="fixed"
|
|
||||||
left={0}
|
|
||||||
top={0}
|
|
||||||
bg="nav.bg"
|
|
||||||
color="fg"
|
|
||||||
overflowY="auto"
|
|
||||||
borderRight="1px solid"
|
|
||||||
borderColor="border"
|
|
||||||
zIndex={40}
|
|
||||||
>
|
|
||||||
<Flex align="center" px={5} py={4} borderBottom="1px solid" borderColor="border">
|
|
||||||
<Text
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
fontSize="xl"
|
|
||||||
fontWeight="bold"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
letterSpacing="wider"
|
|
||||||
>
|
|
||||||
Dune
|
|
||||||
</Text>
|
|
||||||
<Text
|
|
||||||
fontSize="2xs"
|
|
||||||
color="fg.muted"
|
|
||||||
ml={2}
|
|
||||||
mt={1}
|
|
||||||
letterSpacing="widest"
|
|
||||||
textTransform="uppercase"
|
|
||||||
>
|
|
||||||
Admin
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<VStack gap={1} px={2} py={3} align="stretch">
|
|
||||||
{NAV_GROUPS.map((group) => (
|
|
||||||
<NavGroupSection key={group.label} group={group} />
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function NavGroupSection({ group }: { group: NavGroup }) {
|
|
||||||
const location = useLocation()
|
|
||||||
const groupActive = group.items.some(
|
|
||||||
(item) =>
|
|
||||||
location.pathname === item.path ||
|
|
||||||
(item.path !== '/' && location.pathname.startsWith(item.path))
|
|
||||||
)
|
|
||||||
const [open, setOpen] = useState(groupActive)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Collapsible.Root open={open} onOpenChange={(e) => setOpen(e.open)}>
|
|
||||||
<Collapsible.Trigger
|
|
||||||
asChild
|
|
||||||
cursor="pointer"
|
|
||||||
display="flex"
|
|
||||||
alignItems="center"
|
|
||||||
gap={2}
|
|
||||||
px={3}
|
|
||||||
py={2}
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="xs"
|
|
||||||
fontWeight="semibold"
|
|
||||||
color="fg.muted"
|
|
||||||
textTransform="uppercase"
|
|
||||||
letterSpacing="wider"
|
|
||||||
_hover={{ bg: 'bg.subtle', color: 'fg' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<Flex align="center" gap={2} w="full">
|
|
||||||
<Box as="span" fontSize="sm">
|
|
||||||
<group.icon />
|
|
||||||
</Box>
|
|
||||||
<Text flex={1}>{group.label}</Text>
|
|
||||||
<Collapsible.Indicator
|
|
||||||
transform={open ? 'rotate(180deg)' : 'rotate(0deg)'}
|
|
||||||
transition="transform 0.15s"
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
</Collapsible.Trigger>
|
|
||||||
<Collapsible.Content>
|
|
||||||
<VStack gap={0} align="stretch" pl={6} mt={1}>
|
|
||||||
{group.items.map((item) => {
|
|
||||||
const active =
|
|
||||||
location.pathname === item.path ||
|
|
||||||
(item.path !== '/' && location.pathname.startsWith(item.path))
|
|
||||||
return (
|
|
||||||
<Link key={item.path} to={item.path}>
|
|
||||||
<Flex
|
|
||||||
align="center"
|
|
||||||
gap={2}
|
|
||||||
px={3}
|
|
||||||
py={2}
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight={active ? 'semibold' : 'normal'}
|
|
||||||
color={active ? 'primary.DEFAULT' : 'fg.muted'}
|
|
||||||
bg={active ? 'primary.subtle' : 'transparent'}
|
|
||||||
borderLeft={active ? '3px solid' : '3px solid transparent'}
|
|
||||||
borderColor={active ? 'primary.DEFAULT' : 'transparent'}
|
|
||||||
_hover={
|
|
||||||
!active
|
|
||||||
? { bg: 'bg.subtle', color: 'fg' }
|
|
||||||
: {}
|
|
||||||
}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<Box as="span" fontSize="xs" opacity={active ? 1 : 0.6}>
|
|
||||||
<item.icon />
|
|
||||||
</Box>
|
|
||||||
<Text>{item.label}</Text>
|
|
||||||
</Flex>
|
|
||||||
</Link>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</VStack>
|
|
||||||
</Collapsible.Content>
|
|
||||||
</Collapsible.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,115 +0,0 @@
|
|||||||
import {
|
|
||||||
Box,
|
|
||||||
Flex,
|
|
||||||
Text,
|
|
||||||
Menu,
|
|
||||||
Button,
|
|
||||||
HStack,
|
|
||||||
IconButton,
|
|
||||||
Tooltip,
|
|
||||||
Portal,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiSun, FiMoon, FiChevronDown } from 'react-icons/fi'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import { FACTION_KEYS, getFactionName } from '../../themes'
|
|
||||||
import type { FactionKey } from '../../themes/palettes'
|
|
||||||
|
|
||||||
export default function ThemeSwitcher() {
|
|
||||||
const { state, dispatch } = useApp()
|
|
||||||
|
|
||||||
const handleFactionChange = (key: FactionKey) => {
|
|
||||||
dispatch({ type: 'SET_FACTION', payload: key })
|
|
||||||
}
|
|
||||||
|
|
||||||
const toggleColorMode = () => {
|
|
||||||
dispatch({
|
|
||||||
type: 'SET_COLOR_MODE',
|
|
||||||
payload: state.colorMode === 'day' ? 'night' : 'day',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<HStack gap={1}>
|
|
||||||
<Tooltip.Root>
|
|
||||||
<Tooltip.Trigger asChild>
|
|
||||||
<IconButton
|
|
||||||
aria-label="Toggle color mode"
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
onClick={toggleColorMode}
|
|
||||||
color="fg.muted"
|
|
||||||
w={8}
|
|
||||||
h={8}
|
|
||||||
>
|
|
||||||
{state.colorMode === 'day' ? <FiSun size={16} /> : <FiMoon size={16} />}
|
|
||||||
</IconButton>
|
|
||||||
</Tooltip.Trigger>
|
|
||||||
<Tooltip.Positioner>
|
|
||||||
<Tooltip.Content bg="card.bg" border="1px solid" borderColor="border" borderRadius="md" px={3} py={1}>
|
|
||||||
{state.colorMode === 'day' ? 'Switch to Night' : 'Switch to Day'}
|
|
||||||
</Tooltip.Content>
|
|
||||||
</Tooltip.Positioner>
|
|
||||||
</Tooltip.Root>
|
|
||||||
|
|
||||||
<Menu.Root>
|
|
||||||
<Menu.Trigger asChild>
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
borderColor="border"
|
|
||||||
color="fg"
|
|
||||||
_hover={{ borderColor: 'primary.DEFAULT', color: 'primary.DEFAULT' }}
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
w={2.5}
|
|
||||||
h={2.5}
|
|
||||||
borderRadius="full"
|
|
||||||
bg="primary.DEFAULT"
|
|
||||||
/>
|
|
||||||
<Text fontSize="xs">{getFactionName(state.faction)}</Text>
|
|
||||||
<FiChevronDown size={12} />
|
|
||||||
</Button>
|
|
||||||
</Menu.Trigger>
|
|
||||||
<Portal>
|
|
||||||
<Menu.Positioner>
|
|
||||||
<Menu.Content
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
boxShadow="card"
|
|
||||||
maxH="400px"
|
|
||||||
overflowY="auto"
|
|
||||||
>
|
|
||||||
<Menu.ItemGroup title="Factions">
|
|
||||||
{FACTION_KEYS.map((key) => (
|
|
||||||
<Menu.Item
|
|
||||||
key={key}
|
|
||||||
value={key}
|
|
||||||
onClick={() => handleFactionChange(key)}
|
|
||||||
bg={state.faction === key ? 'primary.subtle' : 'transparent'}
|
|
||||||
color={state.faction === key ? 'primary.DEFAULT' : 'fg'}
|
|
||||||
fontWeight={state.faction === key ? 'semibold' : 'normal'}
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
cursor="pointer"
|
|
||||||
py={2}
|
|
||||||
>
|
|
||||||
<Flex align="center" gap={3}>
|
|
||||||
<Box
|
|
||||||
w={3}
|
|
||||||
h={3}
|
|
||||||
borderRadius="full"
|
|
||||||
bg="primary.DEFAULT"
|
|
||||||
/>
|
|
||||||
<Text>{getFactionName(key)}</Text>
|
|
||||||
</Flex>
|
|
||||||
</Menu.Item>
|
|
||||||
))}
|
|
||||||
</Menu.ItemGroup>
|
|
||||||
</Menu.Content>
|
|
||||||
</Menu.Positioner>
|
|
||||||
</Portal>
|
|
||||||
</Menu.Root>
|
|
||||||
</HStack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,73 +0,0 @@
|
|||||||
import { Flex, Text, HStack, Box, Input, InputGroup } from '@chakra-ui/react'
|
|
||||||
import { FiSearch, FiUser } from 'react-icons/fi'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import ConnectionBadge from './ConnectionBadge'
|
|
||||||
import ThemeSwitcher from './ThemeSwitcher'
|
|
||||||
|
|
||||||
export default function TopBar() {
|
|
||||||
const { state } = useApp()
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Flex
|
|
||||||
as="header"
|
|
||||||
h="56px"
|
|
||||||
align="center"
|
|
||||||
px={6}
|
|
||||||
gap={4}
|
|
||||||
bg="bg"
|
|
||||||
borderBottom="1px solid"
|
|
||||||
borderColor="border"
|
|
||||||
position="sticky"
|
|
||||||
top={0}
|
|
||||||
zIndex={30}
|
|
||||||
>
|
|
||||||
<Box flex={1} maxW="400px">
|
|
||||||
<InputGroup
|
|
||||||
startElement={
|
|
||||||
<Box pl={3} color="fg.muted">
|
|
||||||
<FiSearch size={14} />
|
|
||||||
</Box>
|
|
||||||
}
|
|
||||||
w="full"
|
|
||||||
>
|
|
||||||
<Input
|
|
||||||
placeholder="Search players, guilds, accounts..."
|
|
||||||
size="sm"
|
|
||||||
borderRadius="lg"
|
|
||||||
bg="bg.subtle"
|
|
||||||
border="1px solid"
|
|
||||||
borderColor="border"
|
|
||||||
color="fg"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
_hover={{ borderColor: 'border' }}
|
|
||||||
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: `0 0 0 1px var(--chakra-colors-primary-DEFAULT)` }}
|
|
||||||
fontSize="xs"
|
|
||||||
pl={8}
|
|
||||||
/>
|
|
||||||
</InputGroup>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<HStack gap={3} ml="auto">
|
|
||||||
<ConnectionBadge />
|
|
||||||
<ThemeSwitcher />
|
|
||||||
{state.user && (
|
|
||||||
<Flex
|
|
||||||
align="center"
|
|
||||||
gap={2}
|
|
||||||
px={3}
|
|
||||||
py={1}
|
|
||||||
borderRadius="full"
|
|
||||||
bg="primary.subtle"
|
|
||||||
border="1px solid"
|
|
||||||
borderColor="primary.subtle"
|
|
||||||
>
|
|
||||||
<FiUser size={12} />
|
|
||||||
<Text fontSize="xs" color="primary.DEFAULT" fontWeight="medium">
|
|
||||||
{state.user}
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
)}
|
|
||||||
</HStack>
|
|
||||||
</Flex>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,204 +0,0 @@
|
|||||||
import { useState, useEffect, useRef } from 'react'
|
|
||||||
import { Box, Flex, Heading, Button, Text } from '@chakra-ui/react'
|
|
||||||
import { FiMap, FiRefreshCw } from 'react-icons/fi'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import client from '../../api/client'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface MapMarker {
|
|
||||||
id: string
|
|
||||||
name: string
|
|
||||||
x: number
|
|
||||||
y: number
|
|
||||||
type: 'player' | 'vehicle' | 'building' | 'landclaim'
|
|
||||||
}
|
|
||||||
|
|
||||||
const FILTERS = ['all', 'player', 'vehicle', 'building'] as const
|
|
||||||
|
|
||||||
export default function MapViewer() {
|
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null)
|
|
||||||
const [markers, setMarkers] = useState<MapMarker[]>([])
|
|
||||||
const [filter, setFilter] = useState<string>('all')
|
|
||||||
const [selected, setSelected] = useState<MapMarker | null>(null)
|
|
||||||
const [scale, setScale] = useState(1)
|
|
||||||
const [offset, setOffset] = useState({ x: 0, y: 0 })
|
|
||||||
const [isDragging, setIsDragging] = useState(false)
|
|
||||||
const dragStart = useRef({ x: 0, y: 0 })
|
|
||||||
|
|
||||||
const { data: mapData } = useSWR('/partitions', fetcher, { refreshInterval: 60000 })
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const allMarkers: MapMarker[] = []
|
|
||||||
if (mapData?.success) {
|
|
||||||
(mapData.data || []).forEach((p: any) => {
|
|
||||||
if (p.center_x != null && p.center_y != null) {
|
|
||||||
allMarkers.push({
|
|
||||||
id: `partition-${p.partition_id}`,
|
|
||||||
name: p.name || `Partition ${p.partition_id}`,
|
|
||||||
x: p.center_x,
|
|
||||||
y: p.center_y,
|
|
||||||
type: 'building',
|
|
||||||
})
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
setMarkers(allMarkers)
|
|
||||||
}, [mapData])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const canvas = canvasRef.current
|
|
||||||
if (!canvas) return
|
|
||||||
const ctx = canvas.getContext('2d')
|
|
||||||
if (!ctx) return
|
|
||||||
|
|
||||||
const dpr = window.devicePixelRatio || 1
|
|
||||||
const rect = canvas.getBoundingClientRect()
|
|
||||||
canvas.width = rect.width * dpr
|
|
||||||
canvas.height = rect.height * dpr
|
|
||||||
ctx.scale(dpr, dpr)
|
|
||||||
|
|
||||||
ctx.fillStyle = '#1a1a1a'
|
|
||||||
ctx.fillRect(0, 0, rect.width, rect.height)
|
|
||||||
|
|
||||||
ctx.strokeStyle = '#333'
|
|
||||||
ctx.lineWidth = 1
|
|
||||||
const gridSize = 50 * scale
|
|
||||||
for (let x = offset.x % gridSize; x < rect.width; x += gridSize) {
|
|
||||||
ctx.beginPath()
|
|
||||||
ctx.moveTo(x, 0)
|
|
||||||
ctx.lineTo(x, rect.height)
|
|
||||||
ctx.stroke()
|
|
||||||
}
|
|
||||||
for (let y = offset.y % gridSize; y < rect.height; y += gridSize) {
|
|
||||||
ctx.beginPath()
|
|
||||||
ctx.moveTo(0, y)
|
|
||||||
ctx.lineTo(rect.width, y)
|
|
||||||
ctx.stroke()
|
|
||||||
}
|
|
||||||
|
|
||||||
const filtered = filter === 'all' ? markers : markers.filter((m) => m.type === filter)
|
|
||||||
|
|
||||||
filtered.forEach((m) => {
|
|
||||||
const sx = rect.width / 2 + (m.x * 0.001 * scale) + offset.x
|
|
||||||
const sy = rect.height / 2 + (m.y * 0.001 * scale) + offset.y
|
|
||||||
|
|
||||||
ctx.beginPath()
|
|
||||||
ctx.arc(sx, sy, 6, 0, Math.PI * 2)
|
|
||||||
ctx.fillStyle = m.type === 'player' ? '#27ae60' : m.type === 'vehicle' ? '#4a90d9' : '#d4af37'
|
|
||||||
ctx.fill()
|
|
||||||
ctx.strokeStyle = '#fff'
|
|
||||||
ctx.lineWidth = 1
|
|
||||||
ctx.stroke()
|
|
||||||
|
|
||||||
ctx.fillStyle = '#c0c0c0'
|
|
||||||
ctx.font = '10px Inter'
|
|
||||||
ctx.fillText(m.name, sx + 10, sy + 3)
|
|
||||||
})
|
|
||||||
}, [markers, filter, scale, offset])
|
|
||||||
|
|
||||||
const handleWheel = (e: React.WheelEvent) => {
|
|
||||||
e.preventDefault()
|
|
||||||
const newScale = Math.max(0.1, Math.min(10, scale + (e.deltaY > 0 ? -0.1 : 0.1)))
|
|
||||||
setScale(newScale)
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleMouseDown = (e: React.MouseEvent) => {
|
|
||||||
setIsDragging(true)
|
|
||||||
dragStart.current = { x: e.clientX - offset.x, y: e.clientY - offset.y }
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleMouseMove = (e: React.MouseEvent) => {
|
|
||||||
if (!isDragging) return
|
|
||||||
setOffset({ x: e.clientX - dragStart.current.x, y: e.clientY - dragStart.current.y })
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleMouseUp = () => setIsDragging(false)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box h="calc(100vh - 140px)" display="flex" flexDirection="column">
|
|
||||||
<Flex align="center" justify="space-between" mb={4}>
|
|
||||||
<Heading
|
|
||||||
as="h1"
|
|
||||||
fontSize="3xl"
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Map Viewer
|
|
||||||
</Heading>
|
|
||||||
<Flex gap={2}>
|
|
||||||
{FILTERS.map((f) => (
|
|
||||||
<Button
|
|
||||||
key={f}
|
|
||||||
onClick={() => setFilter(f)}
|
|
||||||
size="xs"
|
|
||||||
variant={filter === f ? 'solid' : 'outline'}
|
|
||||||
bg={filter === f ? 'primary.DEFAULT' : 'transparent'}
|
|
||||||
color={filter === f ? 'white' : 'fg.muted'}
|
|
||||||
borderColor={filter === f ? 'primary.DEFAULT' : 'border'}
|
|
||||||
_hover={filter === f ? {} : { color: 'fg', borderColor: 'fg.muted' }}
|
|
||||||
textTransform="capitalize"
|
|
||||||
borderRadius="md"
|
|
||||||
>
|
|
||||||
{f}
|
|
||||||
</Button>
|
|
||||||
))}
|
|
||||||
<Button
|
|
||||||
onClick={() => { setScale(1); setOffset({ x: 0, y: 0 }) }}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderColor="border"
|
|
||||||
color="fg.muted"
|
|
||||||
_hover={{ color: 'fg', borderColor: 'fg.muted' }}
|
|
||||||
borderRadius="md"
|
|
||||||
gap={1}
|
|
||||||
>
|
|
||||||
<FiRefreshCw size={12} />
|
|
||||||
Reset View
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<Box
|
|
||||||
flex={1}
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
overflow="hidden"
|
|
||||||
position="relative"
|
|
||||||
>
|
|
||||||
<Box
|
|
||||||
as="canvas"
|
|
||||||
ref={canvasRef}
|
|
||||||
w="full"
|
|
||||||
h="full"
|
|
||||||
cursor="grab"
|
|
||||||
_active={{ cursor: 'grabbing' }}
|
|
||||||
onWheel={handleWheel}
|
|
||||||
onMouseDown={handleMouseDown}
|
|
||||||
onMouseMove={handleMouseMove}
|
|
||||||
onMouseUp={handleMouseUp}
|
|
||||||
onMouseLeave={handleMouseUp}
|
|
||||||
/>
|
|
||||||
<Box
|
|
||||||
position="absolute"
|
|
||||||
bottom={4}
|
|
||||||
left={4}
|
|
||||||
bg="card.bg"
|
|
||||||
opacity={0.9}
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
px={3}
|
|
||||||
py={2}
|
|
||||||
fontSize="xs"
|
|
||||||
color="fg.muted"
|
|
||||||
backdropFilter="blur(8px)"
|
|
||||||
>
|
|
||||||
Zoom: {scale.toFixed(1)}x | Markers: {markers.length}
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,286 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react'
|
|
||||||
import {
|
|
||||||
Box, Flex, Text, Heading, SimpleGrid,
|
|
||||||
Card, Spinner, Progress, Separator, HStack, Circle, VStack
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip as RechartsTooltip } from 'recharts'
|
|
||||||
import { FiUsers, FiActivity, FiShield, FiServer, FiMap, FiDollarSign, FiFileText, FiDatabase, FiTerminal, FiRadio, FiMessageSquare } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
interface Metrics {
|
|
||||||
total_players: number
|
|
||||||
online_players: number
|
|
||||||
guild_count: number
|
|
||||||
active_guilds: number
|
|
||||||
server_count: number
|
|
||||||
partition_count: number
|
|
||||||
total_worth: number
|
|
||||||
total_flavor_text: number
|
|
||||||
}
|
|
||||||
|
|
||||||
const STAT_CARDS = [
|
|
||||||
{ key: 'total_players', label: 'Total Players', icon: FiUsers, color: 'primary' },
|
|
||||||
{ key: 'online_players', label: 'Online', icon: FiActivity, color: 'success' },
|
|
||||||
{ key: 'guild_count', label: 'Guilds', icon: FiShield, color: 'info' },
|
|
||||||
{ key: 'active_guilds', label: 'Active Guilds', icon: FiShield, color: 'warning' },
|
|
||||||
{ key: 'server_count', label: 'Servers', icon: FiServer, color: 'primary' },
|
|
||||||
{ key: 'partition_count', label: 'Partitions', icon: FiMap, color: 'info' },
|
|
||||||
{ key: 'total_worth', label: 'Total Worth', icon: FiDollarSign, color: 'success' },
|
|
||||||
{ key: 'total_flavor_text', label: 'Flavor Text', icon: FiFileText, color: 'warning' },
|
|
||||||
] as const
|
|
||||||
|
|
||||||
function formatValue(key: string, value: number): string {
|
|
||||||
if (key === 'total_worth') return '$' + Math.round(value).toLocaleString()
|
|
||||||
return value.toLocaleString()
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Overview() {
|
|
||||||
const [metrics, setMetrics] = useState<Metrics | null>(null)
|
|
||||||
const [loading, setLoading] = useState(true)
|
|
||||||
const { state } = useApp()
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
async function load() {
|
|
||||||
try {
|
|
||||||
const res = await client.get('/stats')
|
|
||||||
if (res.data.success) {
|
|
||||||
setMetrics(res.data.data)
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
console.error(e)
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
load()
|
|
||||||
|
|
||||||
const es = new EventSource('/api/events/stream')
|
|
||||||
es.addEventListener('metrics', (e) => {
|
|
||||||
try {
|
|
||||||
setMetrics(JSON.parse(e.data))
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
return () => es.close()
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const onlineRatio = metrics
|
|
||||||
? [
|
|
||||||
{ name: 'Online', value: metrics.online_players, color: 'var(--chakra-colors-success-DEFAULT)' },
|
|
||||||
{ name: 'Offline', value: Math.max(0, metrics.total_players - metrics.online_players), color: 'var(--chakra-colors-border-DEFAULT)' },
|
|
||||||
]
|
|
||||||
: []
|
|
||||||
|
|
||||||
const guildRatio = metrics
|
|
||||||
? [
|
|
||||||
{ name: 'Active', value: metrics.active_guilds, color: 'var(--chakra-colors-warning-DEFAULT)' },
|
|
||||||
{ name: 'Inactive', value: Math.max(0, metrics.guild_count - metrics.active_guilds), color: 'var(--chakra-colors-border-DEFAULT)' },
|
|
||||||
]
|
|
||||||
: []
|
|
||||||
|
|
||||||
const healthItems = [
|
|
||||||
{ label: 'Database', key: 'database' as const, icon: FiDatabase },
|
|
||||||
{ label: 'SSH Tunnel', key: 'ssh' as const, icon: FiTerminal },
|
|
||||||
{ label: 'BG Director', key: 'bgd' as const, icon: FiRadio },
|
|
||||||
{ label: 'RMQ Game', key: 'rmq' as const, icon: FiMessageSquare },
|
|
||||||
]
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading
|
|
||||||
as="h1"
|
|
||||||
fontSize="3xl"
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
mb={6}
|
|
||||||
>
|
|
||||||
Dashboard Overview
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
{loading ? (
|
|
||||||
<Flex align="center" justify="center" py={16}>
|
|
||||||
<VStack gap={3}>
|
|
||||||
<Spinner size="lg" color="primary.DEFAULT" />
|
|
||||||
<Text color="fg.muted" fontSize="sm">Loading metrics...</Text>
|
|
||||||
</VStack>
|
|
||||||
</Flex>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<SimpleGrid columns={{ base: 1, sm: 2, lg: 4 }} gap={4}>
|
|
||||||
{STAT_CARDS.map(({ key, label, icon: Icon, color }) => (
|
|
||||||
<Card.Root
|
|
||||||
key={key}
|
|
||||||
bg="card.bg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="xl"
|
|
||||||
boxShadow="card"
|
|
||||||
_hover={{ transform: 'translateY(-2px)', boxShadow: 'lg' }}
|
|
||||||
transition="all 0.2s"
|
|
||||||
>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Flex justify="space-between" align="start" mb={2}>
|
|
||||||
<Box
|
|
||||||
w={10}
|
|
||||||
h={10}
|
|
||||||
borderRadius="lg"
|
|
||||||
bg={`${color}.subtle`}
|
|
||||||
display="flex"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
color={`${color}.DEFAULT`}
|
|
||||||
>
|
|
||||||
<Icon size={20} />
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
<Text
|
|
||||||
fontSize="2xl"
|
|
||||||
fontWeight="bold"
|
|
||||||
color="fg"
|
|
||||||
fontFamily="Roboto Mono, monospace"
|
|
||||||
>
|
|
||||||
{metrics ? formatValue(key, metrics[key as keyof Metrics]) : '-'}
|
|
||||||
</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" mt={1}>
|
|
||||||
{label}
|
|
||||||
</Text>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6} mt={8}>
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
Player Activity
|
|
||||||
</Text>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
{metrics && onlineRatio.length > 0 ? (
|
|
||||||
<Flex align="center" gap={8}>
|
|
||||||
<Box w="160px" h="160px">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<PieChart>
|
|
||||||
<Pie
|
|
||||||
data={onlineRatio}
|
|
||||||
cx="50%"
|
|
||||||
cy="50%"
|
|
||||||
innerRadius={45}
|
|
||||||
outerRadius={70}
|
|
||||||
paddingAngle={4}
|
|
||||||
dataKey="value"
|
|
||||||
stroke="none"
|
|
||||||
>
|
|
||||||
{onlineRatio.map((entry, i) => (
|
|
||||||
<Cell key={i} fill={entry.color} />
|
|
||||||
))}
|
|
||||||
</Pie>
|
|
||||||
<RechartsTooltip />
|
|
||||||
</PieChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</Box>
|
|
||||||
<VStack align="stretch" gap={4} flex={1}>
|
|
||||||
<Box>
|
|
||||||
<Flex justify="space-between" mb={1}>
|
|
||||||
<Text fontSize="sm" color="fg">Online</Text>
|
|
||||||
<Text fontSize="sm" fontWeight="semibold" color="success.DEFAULT">
|
|
||||||
{Math.round((metrics.online_players / Math.max(1, metrics.total_players)) * 100)}%
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
<Progress.Root value={Math.round((metrics.online_players / Math.max(1, metrics.total_players)) * 100)} size="sm" borderRadius="full">
|
|
||||||
<Progress.Track bg="border">
|
|
||||||
<Progress.Range bg="success.DEFAULT" />
|
|
||||||
</Progress.Track>
|
|
||||||
</Progress.Root>
|
|
||||||
</Box>
|
|
||||||
<Box>
|
|
||||||
<Text fontSize="2xs" color="fg.muted" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
{metrics.online_players.toLocaleString()} of {metrics.total_players.toLocaleString()} players online
|
|
||||||
</Text>
|
|
||||||
</Box>
|
|
||||||
</VStack>
|
|
||||||
</Flex>
|
|
||||||
) : (
|
|
||||||
<Text color="fg.muted" fontSize="sm" textAlign="center">No player data</Text>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
System Health
|
|
||||||
</Text>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<VStack align="stretch" gap={4}>
|
|
||||||
{healthItems.map(({ label, icon: Icon }) => (
|
|
||||||
<Flex key={label} align="center" justify="space-between">
|
|
||||||
<Flex align="center" gap={3}>
|
|
||||||
<Box
|
|
||||||
w={8}
|
|
||||||
h={8}
|
|
||||||
borderRadius="md"
|
|
||||||
bg={`${state.connectionStatus[label.toLowerCase().replace(' ', '_') as keyof typeof state.connectionStatus] || state.connectionStatus.database ? 'success' : 'danger'}.subtle`}
|
|
||||||
display="flex"
|
|
||||||
alignItems="center"
|
|
||||||
justifyContent="center"
|
|
||||||
>
|
|
||||||
<Icon size={14} />
|
|
||||||
</Box>
|
|
||||||
<Text fontSize="sm" color="fg">{label}</Text>
|
|
||||||
</Flex>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<Circle
|
|
||||||
size="8px"
|
|
||||||
bg={state.connectionStatus[label.toLowerCase().includes('database') ? 'database' : label.toLowerCase().includes('ssh') ? 'ssh' : label.toLowerCase().includes('bg') ? 'bgd' : 'rmq' as keyof typeof state.connectionStatus] ? 'success.DEFAULT' : 'danger.DEFAULT'}
|
|
||||||
/>
|
|
||||||
<Text fontSize="xs" color="fg.muted">
|
|
||||||
{state.connectionStatus[label.toLowerCase().includes('database') ? 'database' : label.toLowerCase().includes('ssh') ? 'ssh' : label.toLowerCase().includes('bg') ? 'bgd' : 'rmq' as keyof typeof state.connectionStatus] ? 'Connected' : 'Disconnected'}
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card" mt={6}>
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
Quick Actions
|
|
||||||
</Text>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<SimpleGrid columns={{ base: 2, md: 4 }} gap={3}>
|
|
||||||
{['Broadcast Message', 'Player Search', 'Guild Lookup', 'Server Status'].map((label) => (
|
|
||||||
<Box
|
|
||||||
key={label}
|
|
||||||
as="button"
|
|
||||||
px={4}
|
|
||||||
py={3}
|
|
||||||
bg="primary.subtle"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="primary.subtle"
|
|
||||||
borderRadius="lg"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
_hover={{ bg: 'primary.DEFAULT', color: 'white', borderColor: 'primary.DEFAULT' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
textAlign="left"
|
|
||||||
cursor="pointer"
|
|
||||||
>
|
|
||||||
{label}
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,746 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useParams, useNavigate } from 'react-router-dom'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import {
|
|
||||||
Box, Flex, Heading, Text, Button, Input, Select, Textarea,
|
|
||||||
SimpleGrid, VStack, Table, Tabs, Card, createListCollection,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiArrowLeft } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import Badge from '../common/Badge'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
export default function PlayerDetail() {
|
|
||||||
const { accountId } = useParams<{ accountId: string }>()
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
const [activeTab, setActiveTab] = useState('overview')
|
|
||||||
|
|
||||||
const { data: detail } = useSWR(
|
|
||||||
accountId ? `/players/${accountId}` : null,
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const player = detail?.success ? detail.data : null
|
|
||||||
|
|
||||||
const handleAction = async (endpoint: string, payload: any = {}) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(endpoint, payload)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Action failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!player) {
|
|
||||||
return <Text color="fg.muted">Loading player details...</Text>
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Flex mb={6}>
|
|
||||||
<Button
|
|
||||||
onClick={() => navigate('/players')}
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
color="fg.muted"
|
|
||||||
_hover={{ color: 'fg' }}
|
|
||||||
>
|
|
||||||
<FiArrowLeft style={{ marginRight: 6 }} /> Back to Players
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<Flex align="center" justify="space-between" mb={6}>
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" fontSize="3xl" color="primary.DEFAULT">
|
|
||||||
{player.character_name}
|
|
||||||
</Heading>
|
|
||||||
<Flex align="center" gap={2} mt={1}>
|
|
||||||
<Badge
|
|
||||||
label={player.online_status}
|
|
||||||
variant={player.is_online ? 'success' : 'default'}
|
|
||||||
/>
|
|
||||||
{player.faction_name && (
|
|
||||||
<Text fontSize="sm" color="fg.muted">{player.faction_name}</Text>
|
|
||||||
)}
|
|
||||||
{player.tags?.map((tag: string) => (
|
|
||||||
<Badge key={tag} label={tag} variant="warning" />
|
|
||||||
))}
|
|
||||||
</Flex>
|
|
||||||
</Box>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<Tabs.Root value={activeTab} onValueChange={(e) => setActiveTab(e.value)} mb={6}>
|
|
||||||
<Tabs.List borderBottomWidth="1px" borderColor="border">
|
|
||||||
{[
|
|
||||||
{ key: 'overview', label: 'Overview' },
|
|
||||||
{ key: 'inventory', label: 'Inventory' },
|
|
||||||
{ key: 'vehicles', label: 'Vehicles' },
|
|
||||||
{ key: 'buildings', label: 'Buildings' },
|
|
||||||
{ key: 'progression', label: 'Progression' },
|
|
||||||
{ key: 'actions', label: 'Actions' },
|
|
||||||
].map((t) => (
|
|
||||||
<Tabs.Trigger
|
|
||||||
key={t.key}
|
|
||||||
value={t.key}
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
_selected={{ color: 'primary.DEFAULT', borderColor: 'primary.DEFAULT' }}
|
|
||||||
color="fg.muted"
|
|
||||||
borderBottomWidth="2px"
|
|
||||||
borderColor="transparent"
|
|
||||||
>
|
|
||||||
{t.label}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
))}
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="overview" pt={4}>
|
|
||||||
<OverviewTab player={player} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="inventory" pt={4}>
|
|
||||||
<InventoryTab player={player} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="vehicles" pt={4}>
|
|
||||||
<VehiclesTab player={player} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="buildings" pt={4}>
|
|
||||||
<BuildingsTab player={player} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="progression" pt={4}>
|
|
||||||
<ProgressionTab player={player} />
|
|
||||||
</Tabs.Content>
|
|
||||||
<Tabs.Content value="actions" pt={4}>
|
|
||||||
<ActionsTab player={player} onAction={handleAction} />
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function InfoRow({ label, value }: { label: string; value: any }) {
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Text color="fg.muted" fontSize="xs" textTransform="uppercase" letterSpacing="wider">
|
|
||||||
{label}
|
|
||||||
</Text>
|
|
||||||
<Text fontFamily="Roboto Mono, monospace">{value ?? 'N/A'}</Text>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function OverviewTab({ player }: { player: any }) {
|
|
||||||
const vitals = player.vitals || {}
|
|
||||||
const currency = player.currency || []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Character Info
|
|
||||||
</Heading>
|
|
||||||
<SimpleGrid columns={2} gap={4} fontSize="sm">
|
|
||||||
<InfoRow label="Account ID" value={player.account_id} />
|
|
||||||
<InfoRow label="Controller ID" value={player.player_controller_id} />
|
|
||||||
<InfoRow label="Pawn ID" value={player.player_pawn_id} />
|
|
||||||
<InfoRow label="Email" value={player.account_email} />
|
|
||||||
<InfoRow label="Funcom ID" value={player.funcom_id} />
|
|
||||||
<InfoRow label="Map" value={player.map} />
|
|
||||||
<InfoRow label="Life State" value={player.life_state} />
|
|
||||||
<InfoRow label="Last Login" value={player.last_login_time} />
|
|
||||||
</SimpleGrid>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Vitals
|
|
||||||
</Heading>
|
|
||||||
<SimpleGrid columns={2} gap={4} fontSize="sm">
|
|
||||||
<InfoRow label="Health" value={`${vitals.current_health ?? '?'}/${vitals.max_health ?? '?'}`} />
|
|
||||||
<InfoRow label="Hydration" value={vitals.current_hydration ?? '?'} />
|
|
||||||
<InfoRow label="Dehydration" value={vitals.dehydration_penalty ?? '?'} />
|
|
||||||
<InfoRow label="Spice" value={vitals.current_spice ?? '?'} />
|
|
||||||
<InfoRow label="Addiction" value={vitals.spice_addiction_level ?? '?'} />
|
|
||||||
<InfoRow label="Tolerance" value={vitals.spice_tolerance ?? '?'} />
|
|
||||||
</SimpleGrid>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Currency
|
|
||||||
</Heading>
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
{currency.length === 0 && <Text color="fg.muted" fontSize="sm">No currency data</Text>}
|
|
||||||
{currency.map((c: any) => (
|
|
||||||
<Flex key={c.currency_id} justify="space-between" fontSize="sm">
|
|
||||||
<Text color="fg.muted">{c.currency_label}</Text>
|
|
||||||
<Text fontFamily="Roboto Mono, monospace">{c.balance}</Text>
|
|
||||||
</Flex>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Landsraad
|
|
||||||
</Heading>
|
|
||||||
<SimpleGrid columns={2} gap={4} fontSize="sm">
|
|
||||||
{player.landsraad ? (
|
|
||||||
<>
|
|
||||||
<InfoRow label="Daily Charges" value={player.landsraad.daily_reward_charges} />
|
|
||||||
<InfoRow label="Last Term" value={player.landsraad.last_viewed_term_id} />
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<Text color="fg.muted">No landsraad data</Text>
|
|
||||||
)}
|
|
||||||
</SimpleGrid>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Faction Reputation
|
|
||||||
</Heading>
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
{(player.faction_reputation || []).length === 0 && <Text color="fg.muted" fontSize="sm">No reputation data</Text>}
|
|
||||||
{(player.faction_reputation || []).map((r: any) => (
|
|
||||||
<Flex key={r.faction_id} justify="space-between" fontSize="sm">
|
|
||||||
<Text color="fg.muted">{r.faction_name || `Faction ${r.faction_id}`}</Text>
|
|
||||||
<Text fontFamily="Roboto Mono, monospace">{r.reputation_amount}</Text>
|
|
||||||
</Flex>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function InventoryTab({ player }: { player: any }) {
|
|
||||||
const inventories = player.inventories || []
|
|
||||||
const [selectedInv, setSelectedInv] = useState<any>(null)
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="xl" color="primary.DEFAULT" mb={4}>
|
|
||||||
Inventories
|
|
||||||
</Heading>
|
|
||||||
<SimpleGrid columns={{ base: 1, md: 3 }} gap={4} mb={6}>
|
|
||||||
{inventories.map((inv: any) => (
|
|
||||||
<Box
|
|
||||||
key={inv.inventory_id}
|
|
||||||
as="button"
|
|
||||||
onClick={() => setSelectedInv(inv)}
|
|
||||||
textAlign="left"
|
|
||||||
p={4}
|
|
||||||
borderRadius="lg"
|
|
||||||
borderWidth="1px"
|
|
||||||
transition="colors"
|
|
||||||
bg={selectedInv?.inventory_id === inv.inventory_id ? 'primary.subtle' : 'card.bg'}
|
|
||||||
borderColor={selectedInv?.inventory_id === inv.inventory_id ? 'primary.DEFAULT' : 'border'}
|
|
||||||
_hover={{ bg: 'bg.subtle' }}
|
|
||||||
>
|
|
||||||
<Text fontSize="sm" fontWeight="medium">{inv.inventory_type_label}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" mt={1}>ID: {inv.inventory_id}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted">Items: {inv.items?.length || 0}</Text>
|
|
||||||
</Box>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
|
|
||||||
{selectedInv && (
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Text fontWeight="medium" mb={3}>{selectedInv.inventory_type_label} Items</Text>
|
|
||||||
<Box overflowX="auto">
|
|
||||||
<Table.Root variant="line" size="sm">
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row borderBottomWidth="1px" borderColor="border">
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" px={3} py={2}>Item</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" px={3} py={2}>Stack</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" px={3} py={2}>Quality</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader textTransform="uppercase" fontSize="11px" color="fg.muted" px={3} py={2}>Durability</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{(selectedInv.items || []).map((item: any, i: number) => (
|
|
||||||
<Table.Row key={i} borderBottomWidth="1px" borderColor="border" _last={{ borderBottomWidth: 0 }}>
|
|
||||||
<Table.Cell px={3} py={2}>{item.template_id}</Table.Cell>
|
|
||||||
<Table.Cell px={3} py={2} fontFamily="Roboto Mono, monospace">{item.stack_size}</Table.Cell>
|
|
||||||
<Table.Cell px={3} py={2} fontFamily="Roboto Mono, monospace">{item.quality_level}</Table.Cell>
|
|
||||||
<Table.Cell px={3} py={2} fontFamily="Roboto Mono, monospace">
|
|
||||||
{item.durability != null ? `${Math.round(item.durability)}/${Math.round(item.max_durability)}` : 'N/A'}
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Box>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function VehiclesTab({ player }: { player: any }) {
|
|
||||||
const vehicles = player.vehicles || []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="xl" color="primary.DEFAULT" mb={4}>
|
|
||||||
Vehicles
|
|
||||||
</Heading>
|
|
||||||
{vehicles.length === 0 ? (
|
|
||||||
<Text color="fg.muted">No vehicles found.</Text>
|
|
||||||
) : (
|
|
||||||
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={4}>
|
|
||||||
{vehicles.map((v: any) => (
|
|
||||||
<Card.Root key={v.id} borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={4}>
|
|
||||||
<Text fontWeight="medium">{v.display_name || v.class_name}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" mt={1}>Map: {v.map || 'Unknown'}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" fontFamily="Roboto Mono, monospace">ID: {v.id}</Text>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function BuildingsTab({ player }: { player: any }) {
|
|
||||||
const buildings = player.buildings || []
|
|
||||||
const landclaims = player.landclaims || []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<VStack gap={6} align="stretch">
|
|
||||||
<Box>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="xl" color="primary.DEFAULT" mb={4}>
|
|
||||||
Buildings
|
|
||||||
</Heading>
|
|
||||||
{buildings.length === 0 ? (
|
|
||||||
<Text color="fg.muted">No buildings found.</Text>
|
|
||||||
) : (
|
|
||||||
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={4}>
|
|
||||||
{buildings.map((b: any) => (
|
|
||||||
<Card.Root key={b.id} borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={4}>
|
|
||||||
<Text fontWeight="medium">{b.class_name}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" mt={1}>Map: {b.map || 'Unknown'}</Text>
|
|
||||||
<Flex gap={2} mt={2}>
|
|
||||||
{b.is_powered && <Badge label="Powered" variant="success" />}
|
|
||||||
{b.power_level != null && <Badge label={`Power ${b.power_level}`} variant="default" />}
|
|
||||||
</Flex>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<Box>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="xl" color="primary.DEFAULT" mb={4}>
|
|
||||||
Landclaims
|
|
||||||
</Heading>
|
|
||||||
{landclaims.length === 0 ? (
|
|
||||||
<Text color="fg.muted">No landclaims found.</Text>
|
|
||||||
) : (
|
|
||||||
<SimpleGrid columns={{ base: 1, md: 2, lg: 3 }} gap={4}>
|
|
||||||
{landclaims.map((l: any) => (
|
|
||||||
<Card.Root key={l.id} borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={4}>
|
|
||||||
<Text fontWeight="medium">{l.class_name}</Text>
|
|
||||||
<Text fontSize="xs" color="fg.muted" mt={1}>Map: {l.map || 'Unknown'}</Text>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
))}
|
|
||||||
</SimpleGrid>
|
|
||||||
)}
|
|
||||||
</Box>
|
|
||||||
</VStack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ProgressionTab({ player }: { player: any }) {
|
|
||||||
const specs = player.specialization || []
|
|
||||||
const keystones = player.keystones || []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<VStack gap={6} align="stretch">
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Specialization Tracks
|
|
||||||
</Heading>
|
|
||||||
{specs.length === 0 ? (
|
|
||||||
<Text color="fg.muted">No specialization data.</Text>
|
|
||||||
) : (
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
{specs.map((s: any, i: number) => (
|
|
||||||
<Flex key={i} justify="space-between" align="center">
|
|
||||||
<Text fontSize="sm" color="fg.muted">{s.track_type}</Text>
|
|
||||||
<Flex align="center" gap={4}>
|
|
||||||
<Text fontSize="xs" color="fg.muted">XP: {s.xp_amount}</Text>
|
|
||||||
<Badge label={`Lv ${s.level}`} variant="default" />
|
|
||||||
</Flex>
|
|
||||||
</Flex>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Heading as="h3" fontFamily="Playfair Display, serif" fontSize="lg" color="primary.DEFAULT" mb={4}>
|
|
||||||
Keystones
|
|
||||||
</Heading>
|
|
||||||
{keystones.length === 0 ? (
|
|
||||||
<Text color="fg.muted">No keystones.</Text>
|
|
||||||
) : (
|
|
||||||
<Flex wrap="wrap" gap={2}>
|
|
||||||
{keystones.map((k: any) => (
|
|
||||||
<Badge key={k.id} label={k.name} variant="default" />
|
|
||||||
))}
|
|
||||||
</Flex>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</VStack>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
const currencyCollection = createListCollection({
|
|
||||||
items: [
|
|
||||||
{ value: '0', label: 'Solari Credits' },
|
|
||||||
{ value: '1', label: 'House Script' },
|
|
||||||
{ value: '2', label: 'Spice' },
|
|
||||||
],
|
|
||||||
})
|
|
||||||
|
|
||||||
function ActionsTab({ player, onAction }: { player: any; onAction: (endpoint: string, payload?: any) => Promise<void> }) {
|
|
||||||
const accountId = player.account_id
|
|
||||||
const [newName, setNewName] = useState('')
|
|
||||||
const [currencyForm, setCurrencyForm] = useState({ currency_id: '0', amount: '' })
|
|
||||||
const [vitalsForm, setVitalsForm] = useState({ health: '', hydration: '', spice: '' })
|
|
||||||
const [teleportForm, setTeleportForm] = useState({ partition: '', x: '', y: '', z: '' })
|
|
||||||
const [banReason, setBanReason] = useState('')
|
|
||||||
const [banDuration, setBanDuration] = useState('0')
|
|
||||||
|
|
||||||
return (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<ActionCard title="Currency">
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
<Select.Root
|
|
||||||
collection={currencyCollection}
|
|
||||||
value={[currencyForm.currency_id]}
|
|
||||||
onValueChange={(e) => setCurrencyForm({ ...currencyForm, currency_id: e.value[0] })}
|
|
||||||
>
|
|
||||||
<Select.Trigger bg="card.bg" borderColor="border" borderRadius="md" fontSize="sm">
|
|
||||||
<Select.ValueText />
|
|
||||||
</Select.Trigger>
|
|
||||||
<Select.Content>
|
|
||||||
{currencyCollection.items.map((item) => (
|
|
||||||
<Select.Item item={item} key={item.value}>
|
|
||||||
{item.label}
|
|
||||||
</Select.Item>
|
|
||||||
))}
|
|
||||||
</Select.Content>
|
|
||||||
</Select.Root>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={currencyForm.amount}
|
|
||||||
onChange={(e) => setCurrencyForm({ ...currencyForm, amount: e.target.value })}
|
|
||||||
placeholder="Amount"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction('/currency/adjust', { player_id: accountId, currency_id: parseInt(currencyForm.currency_id), amount: parseFloat(currencyForm.amount) })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Adjust
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction('/currency/set', { player_id: accountId, currency_id: parseInt(currencyForm.currency_id), amount: parseFloat(currencyForm.amount) })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Set Exact
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</ActionCard>
|
|
||||||
|
|
||||||
<ActionCard title="Vitals">
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={vitalsForm.health}
|
|
||||||
onChange={(e) => setVitalsForm({ ...vitalsForm, health: e.target.value })}
|
|
||||||
placeholder="Health"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={vitalsForm.hydration}
|
|
||||||
onChange={(e) => setVitalsForm({ ...vitalsForm, hydration: e.target.value })}
|
|
||||||
placeholder="Hydration"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={vitalsForm.spice}
|
|
||||||
onChange={(e) => setVitalsForm({ ...vitalsForm, spice: e.target.value })}
|
|
||||||
placeholder="Spice"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction('/vitals/set', { player_id: accountId, health: parseFloat(vitalsForm.health) || undefined, hydration: parseFloat(vitalsForm.hydration) || undefined, spice: parseFloat(vitalsForm.spice) || undefined })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Set Vitals
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</ActionCard>
|
|
||||||
|
|
||||||
<ActionCard title="Teleport">
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
<Input
|
|
||||||
value={teleportForm.partition}
|
|
||||||
onChange={(e) => setTeleportForm({ ...teleportForm, partition: e.target.value })}
|
|
||||||
placeholder="Partition ID"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Flex gap={2}>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={teleportForm.x}
|
|
||||||
onChange={(e) => setTeleportForm({ ...teleportForm, x: e.target.value })}
|
|
||||||
placeholder="X"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={teleportForm.y}
|
|
||||||
onChange={(e) => setTeleportForm({ ...teleportForm, y: e.target.value })}
|
|
||||||
placeholder="Y"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={teleportForm.z}
|
|
||||||
onChange={(e) => setTeleportForm({ ...teleportForm, z: e.target.value })}
|
|
||||||
placeholder="Z"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
</Flex>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction('/teleport', { fls_id: accountId, partition_id: teleportForm.partition, x: parseFloat(teleportForm.x) || 0, y: parseFloat(teleportForm.y) || 0, z: parseFloat(teleportForm.z) || 0 })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Teleport
|
|
||||||
</Button>
|
|
||||||
</VStack>
|
|
||||||
</ActionCard>
|
|
||||||
|
|
||||||
<ActionCard title="Character">
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
<Input
|
|
||||||
value={newName}
|
|
||||||
onChange={(e) => setNewName(e.target.value)}
|
|
||||||
placeholder="New character name"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Flex wrap="wrap" gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/characters/${accountId}/name`, { name: newName })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
borderColor="primary.DEFAULT"
|
|
||||||
>
|
|
||||||
Rename
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/accounts/${accountId}/demo`, { demo: true })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="warning.DEFAULT"
|
|
||||||
borderColor="warning.DEFAULT"
|
|
||||||
>
|
|
||||||
Set Demo
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/accounts/${accountId}/demo`, { demo: false })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="warning.DEFAULT"
|
|
||||||
borderColor="warning.DEFAULT"
|
|
||||||
>
|
|
||||||
Clear Demo
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
if (confirm('Delete this character? This cannot be undone.')) {
|
|
||||||
onAction(`/characters/${accountId}`, {})
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Delete Character
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => {
|
|
||||||
if (confirm('Delete this entire account? This cannot be undone.')) {
|
|
||||||
onAction(`/accounts/${accountId}`, {})
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Delete Account
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</ActionCard>
|
|
||||||
|
|
||||||
<ActionCard title="Moderation">
|
|
||||||
<VStack gap={2} align="stretch">
|
|
||||||
<Input
|
|
||||||
value={banReason}
|
|
||||||
onChange={(e) => setBanReason(e.target.value)}
|
|
||||||
placeholder="Ban reason"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Input
|
|
||||||
type="number"
|
|
||||||
value={banDuration}
|
|
||||||
onChange={(e) => setBanDuration(e.target.value)}
|
|
||||||
placeholder="Duration (hours, 0 = permanent)"
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
fontSize="sm"
|
|
||||||
/>
|
|
||||||
<Flex wrap="wrap" gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/players/${accountId}/ban`, { reason: banReason, duration_hours: parseInt(banDuration) || 0 })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
borderColor="danger.DEFAULT"
|
|
||||||
>
|
|
||||||
Ban Player
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/players/${accountId}/unban`, {})}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="success.DEFAULT"
|
|
||||||
borderColor="success.DEFAULT"
|
|
||||||
>
|
|
||||||
Unban Player
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={() => onAction(`/players/${accountId}/kick`, { reason: banReason })}
|
|
||||||
size="xs"
|
|
||||||
variant="outline"
|
|
||||||
borderRadius="md"
|
|
||||||
color="warning.DEFAULT"
|
|
||||||
borderColor="warning.DEFAULT"
|
|
||||||
>
|
|
||||||
Kick Player
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</VStack>
|
|
||||||
</ActionCard>
|
|
||||||
</SimpleGrid>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
function ActionCard({ title, children }: { title: string; children: React.ReactNode }) {
|
|
||||||
return (
|
|
||||||
<Card.Root borderRadius="lg" boxShadow="card" bg="card.bg">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
<Text fontWeight="medium" mb={3}>{title}</Text>
|
|
||||||
{children}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,150 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import { useNavigate } from 'react-router-dom'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import { Box, Heading, Input, Button, HStack } from '@chakra-ui/react'
|
|
||||||
import { FiSearch } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import { useDebounce } from '../../hooks/useDebounce'
|
|
||||||
import DataTable from '../common/DataTable'
|
|
||||||
import Badge from '../common/Badge'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Player {
|
|
||||||
player_controller_id: number | null
|
|
||||||
account_id: number | null
|
|
||||||
character_name: string
|
|
||||||
account_email: string | null
|
|
||||||
funcom_id: string | null
|
|
||||||
faction_name: string | null
|
|
||||||
map: string | null
|
|
||||||
online_status: string
|
|
||||||
life_state: string | null
|
|
||||||
last_login_time: string | null
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function PlayerExplorer() {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const debouncedSearch = useDebounce(search, 300)
|
|
||||||
const navigate = useNavigate()
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: players, isLoading } = useSWR(
|
|
||||||
debouncedSearch.length >= 2
|
|
||||||
? `/players?q=${encodeURIComponent(debouncedSearch)}&limit=25`
|
|
||||||
: null,
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const handleAction = async (accountId: number, action: string, payload: Record<string, unknown> = {}) => {
|
|
||||||
try {
|
|
||||||
let res
|
|
||||||
if (action === 'cheater') {
|
|
||||||
res = await client.post(`/players/${accountId}/cheater`, payload)
|
|
||||||
} else if (action === 'tags') {
|
|
||||||
res = await client.put(`/players/${accountId}/tags`, payload)
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: `Action "${action}" not yet implemented`, type: 'warning' } })
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Action failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Action failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const playerList: Player[] = players?.success ? players.data : []
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" fontSize="3xl" color="primary.DEFAULT" mb={6}>
|
|
||||||
Player Explorer
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Box mb={6} maxW="md" position="relative">
|
|
||||||
<Box
|
|
||||||
position="absolute"
|
|
||||||
left={3}
|
|
||||||
top="50%"
|
|
||||||
transform="translateY(-50%)"
|
|
||||||
zIndex={1}
|
|
||||||
color="fg.muted"
|
|
||||||
>
|
|
||||||
<FiSearch size={16} />
|
|
||||||
</Box>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search by name, email, or Funcom ID..."
|
|
||||||
pl={10}
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
fontSize="sm"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={[
|
|
||||||
{ header: 'Name', accessor: 'character_name' },
|
|
||||||
{
|
|
||||||
header: 'Status',
|
|
||||||
accessor: (row) => (
|
|
||||||
<Badge
|
|
||||||
label={(row as any).online_status}
|
|
||||||
variant={(row as any).online_status === 'Online' ? 'success' : 'default'}
|
|
||||||
/>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
{ header: 'Funcom ID', accessor: 'funcom_id' },
|
|
||||||
{ header: 'Faction', accessor: 'faction_name' },
|
|
||||||
{ header: 'Map', accessor: 'map' },
|
|
||||||
{
|
|
||||||
header: 'Quick Actions',
|
|
||||||
accessor: (row) => (
|
|
||||||
<HStack gap={2}>
|
|
||||||
<Button
|
|
||||||
onClick={(e) => { e.stopPropagation(); handleAction((row as any).account_id || (row as any).player_controller_id || 0, 'cheater', { cheat_type: 'exploit' }) }}
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
fontSize="10px"
|
|
||||||
p={0}
|
|
||||||
h="auto"
|
|
||||||
minW="auto"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
>
|
|
||||||
Cheater
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
onClick={(e) => { e.stopPropagation(); handleAction((row as any).account_id || (row as any).player_controller_id || 0, 'tags', { add: ['reviewed'] }) }}
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
fontSize="10px"
|
|
||||||
p={0}
|
|
||||||
h="auto"
|
|
||||||
minW="auto"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
>
|
|
||||||
Tag
|
|
||||||
</Button>
|
|
||||||
</HStack>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
data={playerList}
|
|
||||||
onRowClick={(row) => navigate(`/players/${row.account_id || row.player_controller_id || 0}`)}
|
|
||||||
loading={isLoading}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,333 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import {
|
|
||||||
Box, Flex, Text, Heading, Tabs, Card, Button,
|
|
||||||
Table, Spinner, Badge as ChakraBadge, Separator, SimpleGrid
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import {
|
|
||||||
AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip,
|
|
||||||
ResponsiveContainer, BarChart, Bar, Cell
|
|
||||||
} from 'recharts'
|
|
||||||
import { FiRefreshCw, FiPlus, FiMinus, FiServer, FiCpu, FiHardDrive, FiShield, FiRadio } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import Badge from '../common/Badge'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Pod {
|
|
||||||
name: string
|
|
||||||
namespace: string
|
|
||||||
status: string
|
|
||||||
restarts: number
|
|
||||||
age: string
|
|
||||||
}
|
|
||||||
|
|
||||||
interface Deployment {
|
|
||||||
name: string
|
|
||||||
namespace: string
|
|
||||||
replicas: number
|
|
||||||
available: number
|
|
||||||
}
|
|
||||||
|
|
||||||
interface MetricPoint {
|
|
||||||
timestamp: string
|
|
||||||
cpu_percent: number
|
|
||||||
memory_percent: number
|
|
||||||
}
|
|
||||||
|
|
||||||
const TAB_ICONS: Record<string, React.ElementType> = {
|
|
||||||
pods: FiServer,
|
|
||||||
deployments: FiRefreshCw,
|
|
||||||
metrics: FiCpu,
|
|
||||||
firewall: FiShield,
|
|
||||||
rmq: FiRadio,
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function ServerControl() {
|
|
||||||
const [tab, setTab] = useState<'pods' | 'deployments' | 'metrics' | 'firewall' | 'rmq'>('pods')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: pods, mutate: mutatePods } = useSWR('/server/pods', fetcher, { refreshInterval: 15000 })
|
|
||||||
const { data: deployments } = useSWR('/server/deployments', fetcher, { refreshInterval: 30000 })
|
|
||||||
const { data: metrics } = useSWR('/server/metrics?hours=24', fetcher, { refreshInterval: 60000 })
|
|
||||||
const { data: firewall } = useSWR('/server/firewall/status', fetcher, { refreshInterval: 30000 })
|
|
||||||
const { data: rmq } = useSWR('/server/rmq/overview', fetcher, { refreshInterval: 30000 })
|
|
||||||
|
|
||||||
const podList: Pod[] = pods?.success ? pods.data : []
|
|
||||||
const deploymentList: Deployment[] = deployments?.success ? deployments.data : []
|
|
||||||
const metricList: MetricPoint[] = metrics?.success ? metrics.data : []
|
|
||||||
|
|
||||||
const handleRestart = async (deployment: string) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(`/server/deployments/${deployment}/restart`)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Restart initiated', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { response?: { data?: { error?: string } } }
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: err.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleScale = async (deployment: string, replicas: number) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(`/server/deployments/${deployment}/scale`, { replicas })
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Scaled successfully', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: unknown) {
|
|
||||||
const err = e as { response?: { data?: { error?: string } } }
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: err.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const chartData = metricList.map((m) => ({
|
|
||||||
time: new Date(m.timestamp).toLocaleTimeString(),
|
|
||||||
cpu: m.cpu_percent,
|
|
||||||
memory: m.memory_percent,
|
|
||||||
}))
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontSize="3xl" fontFamily="Playfair Display, serif" color="primary.DEFAULT" mb={6}>
|
|
||||||
Server Control
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Tabs.Root
|
|
||||||
value={tab}
|
|
||||||
onValueChange={(e) => setTab(e.value as typeof tab)}
|
|
||||||
variant="line"
|
|
||||||
mb={6}
|
|
||||||
>
|
|
||||||
<Tabs.List borderBottomWidth="1px" borderColor="border" gap={0}>
|
|
||||||
{(['pods', 'deployments', 'metrics', 'firewall', 'rmq'] as const).map((t) => {
|
|
||||||
const Icon = TAB_ICONS[t]
|
|
||||||
return (
|
|
||||||
<Tabs.Trigger
|
|
||||||
key={t}
|
|
||||||
value={t}
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
fontSize="sm"
|
|
||||||
fontWeight="medium"
|
|
||||||
textTransform="capitalize"
|
|
||||||
color="fg.muted"
|
|
||||||
borderBottom="2px solid transparent"
|
|
||||||
_selected={{
|
|
||||||
color: 'primary.DEFAULT',
|
|
||||||
borderColor: 'primary.DEFAULT',
|
|
||||||
}}
|
|
||||||
transition="all 0.15s"
|
|
||||||
gap={2}
|
|
||||||
>
|
|
||||||
<Icon size={14} />
|
|
||||||
{t}
|
|
||||||
</Tabs.Trigger>
|
|
||||||
)
|
|
||||||
})}
|
|
||||||
</Tabs.List>
|
|
||||||
|
|
||||||
<Tabs.Content value="pods" pt={4}>
|
|
||||||
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
|
|
||||||
<Table.Root variant="line" size="sm" stickyHeader>
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row bg="bg.subtle">
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Name</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Namespace</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Status</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Restarts</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Age</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Actions</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{podList.map((pod) => (
|
|
||||||
<Table.Row key={pod.name} _hover={{ bg: 'bg.subtle' }}>
|
|
||||||
<Table.Cell fontFamily="Roboto Mono, monospace" fontSize="xs">{pod.name}</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{pod.namespace}</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
<Badge
|
|
||||||
label={pod.status}
|
|
||||||
variant={pod.status === 'Running' ? 'success' : pod.status === 'Pending' ? 'warning' : 'danger'}
|
|
||||||
/>
|
|
||||||
</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{pod.restarts}</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{pod.age}</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
<Button variant="ghost" size="xs" color="primary.DEFAULT" onClick={() => handleRestart(pod.name)}>
|
|
||||||
Restart
|
|
||||||
</Button>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Table.ScrollArea>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="deployments" pt={4}>
|
|
||||||
<Table.ScrollArea borderWidth="1px" borderColor="border" borderRadius="lg">
|
|
||||||
<Table.Root variant="line" size="sm" stickyHeader>
|
|
||||||
<Table.Header>
|
|
||||||
<Table.Row bg="bg.subtle">
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Name</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Namespace</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Replicas</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Available</Table.ColumnHeader>
|
|
||||||
<Table.ColumnHeader fontSize="2xs" textTransform="uppercase" letterSpacing="wider" color="fg.muted">Actions</Table.ColumnHeader>
|
|
||||||
</Table.Row>
|
|
||||||
</Table.Header>
|
|
||||||
<Table.Body>
|
|
||||||
{deploymentList.map((dep) => (
|
|
||||||
<Table.Row key={dep.name} _hover={{ bg: 'bg.subtle' }}>
|
|
||||||
<Table.Cell fontFamily="Roboto Mono, monospace" fontSize="xs">{dep.name}</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{dep.namespace}</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{dep.replicas}</Table.Cell>
|
|
||||||
<Table.Cell fontSize="sm">{dep.available}</Table.Cell>
|
|
||||||
<Table.Cell>
|
|
||||||
<Flex gap={1}>
|
|
||||||
<Button variant="outline" size="xs" borderColor="primary.DEFAULT" color="primary.DEFAULT" onClick={() => handleScale(dep.name, dep.replicas + 1)}>
|
|
||||||
<FiPlus size={12} />
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" size="xs" borderColor="border" color="fg.muted" onClick={() => handleScale(dep.name, Math.max(0, dep.replicas - 1))}>
|
|
||||||
<FiMinus size={12} />
|
|
||||||
</Button>
|
|
||||||
<Button variant="outline" size="xs" borderColor="danger.DEFAULT" color="danger.DEFAULT" onClick={() => handleRestart(dep.name)}>
|
|
||||||
Restart
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
</Table.Cell>
|
|
||||||
</Table.Row>
|
|
||||||
))}
|
|
||||||
</Table.Body>
|
|
||||||
</Table.Root>
|
|
||||||
</Table.ScrollArea>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="metrics" pt={4}>
|
|
||||||
{metricList.length === 0 ? (
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl">
|
|
||||||
<Card.Body p={8} textAlign="center">
|
|
||||||
<Flex direction="column" align="center" gap={3}>
|
|
||||||
<FiCpu size={40} style={{ opacity: 0.3 }} />
|
|
||||||
<Text color="fg.muted">No metrics available</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
) : (
|
|
||||||
<SimpleGrid columns={{ base: 1, lg: 2 }} gap={6}>
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<Box w={3} h={3} borderRadius="full" bg="primary.DEFAULT" />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
CPU Usage (24h)
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={4}>
|
|
||||||
<Box w="full" h="280px">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<AreaChart data={chartData}>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="cpuGrad" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="var(--chakra-colors-primary-DEFAULT)" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="var(--chakra-colors-primary-DEFAULT)" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--chakra-colors-border-DEFAULT)" />
|
|
||||||
<XAxis dataKey="time" tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} interval="preserveStartEnd" />
|
|
||||||
<YAxis tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} unit="%" />
|
|
||||||
<Tooltip contentStyle={{ background: 'var(--chakra-colors-card-bg)', border: '1px solid var(--chakra-colors-border-DEFAULT)', borderRadius: '8px', fontSize: '12px' }} />
|
|
||||||
<Area type="monotone" dataKey="cpu" stroke="var(--chakra-colors-primary-DEFAULT)" fill="url(#cpuGrad)" strokeWidth={2} />
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</Box>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<Box w={3} h={3} borderRadius="full" bg="success.DEFAULT" />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
Memory Usage (24h)
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={4}>
|
|
||||||
<Box w="full" h="280px">
|
|
||||||
<ResponsiveContainer width="100%" height="100%">
|
|
||||||
<AreaChart data={chartData}>
|
|
||||||
<defs>
|
|
||||||
<linearGradient id="memGrad" x1="0" y1="0" x2="0" y2="1">
|
|
||||||
<stop offset="5%" stopColor="var(--chakra-colors-success-DEFAULT)" stopOpacity={0.3} />
|
|
||||||
<stop offset="95%" stopColor="var(--chakra-colors-success-DEFAULT)" stopOpacity={0} />
|
|
||||||
</linearGradient>
|
|
||||||
</defs>
|
|
||||||
<CartesianGrid strokeDasharray="3 3" stroke="var(--chakra-colors-border-DEFAULT)" />
|
|
||||||
<XAxis dataKey="time" tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} interval="preserveStartEnd" />
|
|
||||||
<YAxis tick={{ fontSize: 10, fill: 'var(--chakra-colors-fg-muted)' }} unit="%" />
|
|
||||||
<Tooltip contentStyle={{ background: 'var(--chakra-colors-card-bg)', border: '1px solid var(--chakra-colors-border-DEFAULT)', borderRadius: '8px', fontSize: '12px' }} />
|
|
||||||
<Area type="monotone" dataKey="memory" stroke="var(--chakra-colors-success-DEFAULT)" fill="url(#memGrad)" strokeWidth={2} />
|
|
||||||
</AreaChart>
|
|
||||||
</ResponsiveContainer>
|
|
||||||
</Box>
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</SimpleGrid>
|
|
||||||
)}
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="firewall" pt={4}>
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<FiShield size={16} color="currentColor" />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
Firewall Status
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
{firewall?.success ? (
|
|
||||||
<Box as="pre" fontSize="xs" color="fg" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="lg" overflow="auto">
|
|
||||||
{JSON.stringify(firewall.data, null, 2)}
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Text color="fg.muted" fontSize="sm">No firewall data available</Text>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Tabs.Content>
|
|
||||||
|
|
||||||
<Tabs.Content value="rmq" pt={4}>
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card">
|
|
||||||
<Card.Header borderBottomWidth="1px" borderColor="border" px={5} py={4}>
|
|
||||||
<Flex align="center" gap={2}>
|
|
||||||
<FiRadio size={16} color="currentColor" />
|
|
||||||
<Text fontFamily="Playfair Display, serif" fontSize="md" color="primary.DEFAULT" fontWeight="semibold">
|
|
||||||
RMQ Overview
|
|
||||||
</Text>
|
|
||||||
</Flex>
|
|
||||||
</Card.Header>
|
|
||||||
<Card.Body p={5}>
|
|
||||||
{rmq?.success ? (
|
|
||||||
<Box as="pre" fontSize="xs" color="fg" fontFamily="Roboto Mono, monospace" bg="code.bg" p={4} borderRadius="lg" overflow="auto">
|
|
||||||
{JSON.stringify(rmq.data, null, 2)}
|
|
||||||
</Box>
|
|
||||||
) : (
|
|
||||||
<Text color="fg.muted" fontSize="sm">No RMQ data available</Text>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Tabs.Content>
|
|
||||||
</Tabs.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,157 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react'
|
|
||||||
import {
|
|
||||||
Box,
|
|
||||||
Heading,
|
|
||||||
Button,
|
|
||||||
Input,
|
|
||||||
Flex,
|
|
||||||
VStack,
|
|
||||||
Card,
|
|
||||||
Grid,
|
|
||||||
Text,
|
|
||||||
Spinner,
|
|
||||||
} from '@chakra-ui/react'
|
|
||||||
import { FiRefreshCw, FiSave, FiPlus } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
|
|
||||||
export default function Settings() {
|
|
||||||
const [settings, setSettings] = useState<Record<string, string>>({})
|
|
||||||
const [loading, setLoading] = useState(false)
|
|
||||||
const [saving, setSaving] = useState(false)
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const load = async () => {
|
|
||||||
setLoading(true)
|
|
||||||
try {
|
|
||||||
const res = await client.get('/settings')
|
|
||||||
if (res.data.success) {
|
|
||||||
setSettings(res.data.data)
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed to load settings', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setLoading(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
load()
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
const handleSave = async () => {
|
|
||||||
setSaving(true)
|
|
||||||
try {
|
|
||||||
const res = await client.post('/settings', settings)
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Settings saved', type: 'success' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed to save', type: 'error' } })
|
|
||||||
} finally {
|
|
||||||
setSaving(false)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleChange = (key: string, value: string) => {
|
|
||||||
setSettings({ ...settings, [key]: value })
|
|
||||||
}
|
|
||||||
|
|
||||||
const addKey = () => {
|
|
||||||
const key = prompt('Enter new setting key:')
|
|
||||||
if (key) {
|
|
||||||
setSettings({ ...settings, [key]: '' })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
|
|
||||||
Settings
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Flex gap={4} mb={6} wrap="wrap">
|
|
||||||
<Button
|
|
||||||
variant="solid"
|
|
||||||
bg="primary.DEFAULT"
|
|
||||||
color="white"
|
|
||||||
size="sm"
|
|
||||||
borderRadius="lg"
|
|
||||||
onClick={load}
|
|
||||||
disabled={loading}
|
|
||||||
_hover={{ bg: 'primary.hover', transform: 'scale(1.02)' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<FiRefreshCw style={{ marginRight: 6 }} />
|
|
||||||
{loading ? 'Loading...' : 'Reload'}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="solid"
|
|
||||||
bg="success.DEFAULT"
|
|
||||||
color="white"
|
|
||||||
size="sm"
|
|
||||||
borderRadius="lg"
|
|
||||||
onClick={handleSave}
|
|
||||||
disabled={saving}
|
|
||||||
_hover={{ transform: 'scale(1.02)' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<FiSave style={{ marginRight: 6 }} />
|
|
||||||
{saving ? 'Saving...' : 'Save Settings'}
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="solid"
|
|
||||||
bg="card.bg"
|
|
||||||
color="fg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
size="sm"
|
|
||||||
borderRadius="lg"
|
|
||||||
onClick={addKey}
|
|
||||||
_hover={{ bg: 'bg.subtle', transform: 'scale(1.02)' }}
|
|
||||||
transition="all 0.15s"
|
|
||||||
>
|
|
||||||
<FiPlus style={{ marginRight: 6 }} />
|
|
||||||
Add Key
|
|
||||||
</Button>
|
|
||||||
</Flex>
|
|
||||||
|
|
||||||
<Card.Root bg="card.bg" borderWidth="1px" borderColor="border" borderRadius="xl" boxShadow="card" maxW="3xl">
|
|
||||||
<Card.Body p={5}>
|
|
||||||
{loading ? (
|
|
||||||
<Flex align="center" justify="center" py={8} gap={2} color="fg.muted">
|
|
||||||
<Spinner size="sm" />
|
|
||||||
<Text fontSize="sm">Loading settings...</Text>
|
|
||||||
</Flex>
|
|
||||||
) : Object.entries(settings).length === 0 ? (
|
|
||||||
<Flex direction="column" align="center" justify="center" py={8} color="fg.muted">
|
|
||||||
<Text fontSize="sm">No settings found.</Text>
|
|
||||||
<Text fontSize="xs" mt={1}>Click "Add Key" to create one.</Text>
|
|
||||||
</Flex>
|
|
||||||
) : (
|
|
||||||
<VStack gap={3} align="stretch">
|
|
||||||
{Object.entries(settings).map(([key, value]) => (
|
|
||||||
<Grid key={key} templateColumns="200px 1fr" gap={4} alignItems="center">
|
|
||||||
<Text as="label" fontSize="sm" color="fg.muted" truncate title={key}>
|
|
||||||
{key}
|
|
||||||
</Text>
|
|
||||||
<Input
|
|
||||||
value={value}
|
|
||||||
onChange={(e) => handleChange(key, e.target.value)}
|
|
||||||
bg="bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="md"
|
|
||||||
px={3}
|
|
||||||
py={2}
|
|
||||||
fontSize="sm"
|
|
||||||
color="fg"
|
|
||||||
/>
|
|
||||||
</Grid>
|
|
||||||
))}
|
|
||||||
</VStack>
|
|
||||||
)}
|
|
||||||
</Card.Body>
|
|
||||||
</Card.Root>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,120 +0,0 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
|
||||||
import { Box, Heading } from '@chakra-ui/react'
|
|
||||||
import { Terminal as XTerm } from 'xterm'
|
|
||||||
import { FitAddon } from 'xterm-addon-fit'
|
|
||||||
import { io, Socket } from 'socket.io-client'
|
|
||||||
import 'xterm/css/xterm.css'
|
|
||||||
|
|
||||||
export default function Terminal() {
|
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
|
||||||
const termRef = useRef<XTerm | null>(null)
|
|
||||||
const fitAddonRef = useRef<FitAddon | null>(null)
|
|
||||||
const socketRef = useRef<Socket | null>(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (!containerRef.current) return
|
|
||||||
|
|
||||||
const term = new XTerm({
|
|
||||||
cursorBlink: true,
|
|
||||||
fontSize: 14,
|
|
||||||
fontFamily: 'Roboto Mono, monospace',
|
|
||||||
theme: {
|
|
||||||
background: '#1a1a1a',
|
|
||||||
foreground: '#f0f0f0',
|
|
||||||
cursor: '#d4af37',
|
|
||||||
selectionBackground: '#404040',
|
|
||||||
black: '#1a1a1a',
|
|
||||||
red: '#c0392b',
|
|
||||||
green: '#27ae60',
|
|
||||||
yellow: '#f39c12',
|
|
||||||
blue: '#4a90d9',
|
|
||||||
magenta: '#9966cc',
|
|
||||||
cyan: '#20b2aa',
|
|
||||||
white: '#f0f0f0',
|
|
||||||
brightBlack: '#404040',
|
|
||||||
brightRed: '#ff6b6b',
|
|
||||||
brightGreen: '#6abf6a',
|
|
||||||
brightYellow: '#e8c962',
|
|
||||||
brightBlue: '#6baee8',
|
|
||||||
brightMagenta: '#c8a8e8',
|
|
||||||
brightCyan: '#7de8d8',
|
|
||||||
brightWhite: '#ffffff',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const fitAddon = new FitAddon()
|
|
||||||
term.loadAddon(fitAddon)
|
|
||||||
term.open(containerRef.current)
|
|
||||||
fitAddon.fit()
|
|
||||||
|
|
||||||
termRef.current = term
|
|
||||||
fitAddonRef.current = fitAddon
|
|
||||||
|
|
||||||
const socket = io({
|
|
||||||
transports: ['websocket'],
|
|
||||||
})
|
|
||||||
socketRef.current = socket
|
|
||||||
|
|
||||||
socket.on('connect', () => {
|
|
||||||
term.writeln('Connecting to remote shell...')
|
|
||||||
socket.emit('shell_create', { type: 'vm' })
|
|
||||||
})
|
|
||||||
|
|
||||||
socket.on('shell_created', (data: any) => {
|
|
||||||
if (data.success) {
|
|
||||||
term.writeln('\r\nConnected to remote shell.')
|
|
||||||
} else {
|
|
||||||
term.writeln(`\r\nFailed to create shell: ${data.error || 'Unknown error'}`)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
socket.on('shell_output', (data: any) => {
|
|
||||||
if (data.data) {
|
|
||||||
term.write(data.data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
socket.on('disconnect', () => {
|
|
||||||
term.writeln('\r\n[Disconnected]')
|
|
||||||
})
|
|
||||||
|
|
||||||
term.onData((data) => {
|
|
||||||
socket.emit('shell_input', { data })
|
|
||||||
})
|
|
||||||
|
|
||||||
const handleResize = () => {
|
|
||||||
fitAddon.fit()
|
|
||||||
}
|
|
||||||
window.addEventListener('resize', handleResize)
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
window.removeEventListener('resize', handleResize)
|
|
||||||
socket.emit('shell_disconnect')
|
|
||||||
socket.disconnect()
|
|
||||||
term.dispose()
|
|
||||||
}
|
|
||||||
}, [])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box h="calc(100vh - 140px)" display="flex" flexDirection="column">
|
|
||||||
<Heading
|
|
||||||
as="h1"
|
|
||||||
fontSize="3xl"
|
|
||||||
fontFamily="Playfair Display, serif"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
mb={4}
|
|
||||||
>
|
|
||||||
Remote Shell
|
|
||||||
</Heading>
|
|
||||||
<Box
|
|
||||||
ref={containerRef}
|
|
||||||
flex={1}
|
|
||||||
bg="#1a1a1a"
|
|
||||||
borderRadius="lg"
|
|
||||||
borderWidth="1px"
|
|
||||||
borderColor="border"
|
|
||||||
overflow="hidden"
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,111 +0,0 @@
|
|||||||
import { useState } from 'react'
|
|
||||||
import useSWR from 'swr'
|
|
||||||
import { Box, Heading, Input, Button } from '@chakra-ui/react'
|
|
||||||
import { FiSearch } from 'react-icons/fi'
|
|
||||||
import client from '../../api/client'
|
|
||||||
import { useApp } from '../../stores/AppContext'
|
|
||||||
import DataTable from '../common/DataTable'
|
|
||||||
|
|
||||||
const fetcher = (url: string) => client.get(url).then((r) => r.data)
|
|
||||||
|
|
||||||
interface Vehicle {
|
|
||||||
id: number
|
|
||||||
class_name: string
|
|
||||||
display_name: string
|
|
||||||
map: string
|
|
||||||
owner_name: string
|
|
||||||
online_status: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export default function Vehicles() {
|
|
||||||
const [search, setSearch] = useState('')
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
|
|
||||||
const { data: vehiclesData, isLoading } = useSWR(
|
|
||||||
search.length >= 2 ? `/vehicles?q=${encodeURIComponent(search)}&limit=50` : '/vehicles?limit=100',
|
|
||||||
fetcher,
|
|
||||||
{ refreshInterval: 30000 }
|
|
||||||
)
|
|
||||||
|
|
||||||
const vehicleList: Vehicle[] = vehiclesData?.success ? vehiclesData.data : []
|
|
||||||
|
|
||||||
const handleAction = async (id: number, action: string) => {
|
|
||||||
try {
|
|
||||||
const res = await client.post(`/vehicles/${id}/${action}`, {})
|
|
||||||
if (res.data.success) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: 'Action successful', type: 'success' } })
|
|
||||||
} else {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: res.data.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
} catch (e: any) {
|
|
||||||
dispatch({ type: 'ADD_TOAST', payload: { message: e.response?.data?.error || 'Failed', type: 'error' } })
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Box>
|
|
||||||
<Heading as="h1" fontFamily="Playfair Display, serif" color="primary.DEFAULT" fontSize="2xl" mb={6}>
|
|
||||||
Vehicles
|
|
||||||
</Heading>
|
|
||||||
|
|
||||||
<Box position="relative" maxW="md" mb={6}>
|
|
||||||
<Input
|
|
||||||
type="text"
|
|
||||||
value={search}
|
|
||||||
onChange={(e) => setSearch(e.target.value)}
|
|
||||||
placeholder="Search vehicles..."
|
|
||||||
bg="card.bg"
|
|
||||||
borderColor="border"
|
|
||||||
borderRadius="lg"
|
|
||||||
px={4}
|
|
||||||
py={2.5}
|
|
||||||
pl={10}
|
|
||||||
fontSize="sm"
|
|
||||||
color="fg"
|
|
||||||
_placeholder={{ color: 'fg.muted' }}
|
|
||||||
_focus={{ borderColor: 'primary.DEFAULT', boxShadow: '0 0 0 1px var(--chakra-colors-primary-DEFAULT)' }}
|
|
||||||
_focusVisible={{ outline: 'none' }}
|
|
||||||
/>
|
|
||||||
<Box position="absolute" left={3} top="50%" transform="translateY(-50%)" color="fg.muted">
|
|
||||||
<FiSearch size={16} />
|
|
||||||
</Box>
|
|
||||||
</Box>
|
|
||||||
|
|
||||||
<DataTable
|
|
||||||
columns={[
|
|
||||||
{ header: 'Name', accessor: 'display_name' },
|
|
||||||
{ header: 'Class', accessor: 'class_name' },
|
|
||||||
{ header: 'Map', accessor: 'map' },
|
|
||||||
{ header: 'Owner', accessor: 'owner_name' },
|
|
||||||
{
|
|
||||||
header: 'Actions',
|
|
||||||
accessor: (row) => (
|
|
||||||
<Box display="flex" gap={2}>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
color="primary.DEFAULT"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={(e) => { e.stopPropagation(); handleAction((row as any).id, 'repair') }}
|
|
||||||
>
|
|
||||||
Repair
|
|
||||||
</Button>
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="xs"
|
|
||||||
color="danger.DEFAULT"
|
|
||||||
_hover={{ textDecoration: 'underline' }}
|
|
||||||
onClick={(e) => { e.stopPropagation(); handleAction((row as any).id, 'destroy') }}
|
|
||||||
>
|
|
||||||
Destroy
|
|
||||||
</Button>
|
|
||||||
</Box>
|
|
||||||
),
|
|
||||||
},
|
|
||||||
]}
|
|
||||||
data={vehicleList}
|
|
||||||
loading={isLoading}
|
|
||||||
/>
|
|
||||||
</Box>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { useState, useEffect } from 'react'
|
|
||||||
|
|
||||||
export function useDebounce<T>(value: T, delay: number = 300): T {
|
|
||||||
const [debounced, setDebounced] = useState(value)
|
|
||||||
useEffect(() => {
|
|
||||||
const timer = setTimeout(() => setDebounced(value), delay)
|
|
||||||
return () => clearTimeout(timer)
|
|
||||||
}, [value, delay])
|
|
||||||
return debounced
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { useEffect, useRef } from 'react'
|
|
||||||
import { useApp } from '../stores/AppContext'
|
|
||||||
|
|
||||||
export function useRealtime() {
|
|
||||||
const { dispatch } = useApp()
|
|
||||||
const evtSource = useRef<EventSource | null>(null)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
const es = new EventSource('/api/events/stream')
|
|
||||||
evtSource.current = es
|
|
||||||
|
|
||||||
es.onopen = () => {
|
|
||||||
console.log('[SSE] Connected')
|
|
||||||
}
|
|
||||||
|
|
||||||
es.addEventListener('battlegroup_update', (e) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(e.data)
|
|
||||||
console.log('[SSE] battlegroup_update', data)
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
|
|
||||||
es.addEventListener('rmq_health', (e) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(e.data)
|
|
||||||
console.log('[SSE] rmq_health', data)
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
|
|
||||||
es.addEventListener('connection_status', (e) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(e.data)
|
|
||||||
dispatch({ type: 'SET_CONNECTION', payload: data })
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
|
|
||||||
es.addEventListener('chat_message', (e) => {
|
|
||||||
try {
|
|
||||||
const data = JSON.parse(e.data)
|
|
||||||
console.log('[SSE] chat_message', data)
|
|
||||||
} catch {}
|
|
||||||
})
|
|
||||||
|
|
||||||
es.onerror = () => {
|
|
||||||
console.warn('[SSE] Connection error')
|
|
||||||
}
|
|
||||||
|
|
||||||
return () => {
|
|
||||||
es.close()
|
|
||||||
}
|
|
||||||
}, [dispatch])
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import React from 'react'
|
|
||||||
import ReactDOM from 'react-dom/client'
|
|
||||||
import App from './App'
|
|
||||||
import '@fontsource/playfair-display/400.css'
|
|
||||||
import '@fontsource/playfair-display/700.css'
|
|
||||||
import '@fontsource/inter/400.css'
|
|
||||||
import '@fontsource/inter/500.css'
|
|
||||||
import '@fontsource/inter/600.css'
|
|
||||||
import '@fontsource/roboto-mono/400.css'
|
|
||||||
import '@fontsource/roboto-mono/500.css'
|
|
||||||
|
|
||||||
ReactDOM.createRoot(document.getElementById('root')!).render(
|
|
||||||
<React.StrictMode>
|
|
||||||
<App />
|
|
||||||
</React.StrictMode>,
|
|
||||||
)
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
import { createContext, useContext, useReducer, useEffect } from 'react'
|
|
||||||
import type { FactionKey } from '../themes/palettes'
|
|
||||||
import { toaster } from '../toaster'
|
|
||||||
|
|
||||||
interface AppState {
|
|
||||||
user: string | null
|
|
||||||
faction: FactionKey
|
|
||||||
colorMode: 'day' | 'night'
|
|
||||||
connectionStatus: {
|
|
||||||
database: boolean
|
|
||||||
ssh: boolean
|
|
||||||
bgd: boolean
|
|
||||||
rmq: boolean
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type Action =
|
|
||||||
| { type: 'SET_USER'; payload: string | null }
|
|
||||||
| { type: 'SET_FACTION'; payload: FactionKey }
|
|
||||||
| { type: 'SET_COLOR_MODE'; payload: 'day' | 'night' }
|
|
||||||
| { type: 'SET_CONNECTION'; payload: Partial<AppState['connectionStatus']> }
|
|
||||||
| { type: 'ADD_TOAST'; payload: { message: string; type: 'success' | 'error' | 'warning' | 'info' } }
|
|
||||||
|
|
||||||
function loadStoredFaction(): FactionKey {
|
|
||||||
try {
|
|
||||||
const stored = localStorage.getItem('dune-faction')
|
|
||||||
if (stored) return stored as FactionKey
|
|
||||||
} catch {}
|
|
||||||
return 'fremen'
|
|
||||||
}
|
|
||||||
|
|
||||||
function loadStoredColorMode(): 'day' | 'night' {
|
|
||||||
try {
|
|
||||||
const stored = localStorage.getItem('dune-color-mode')
|
|
||||||
if (stored === 'day' || stored === 'night') return stored
|
|
||||||
} catch {}
|
|
||||||
return 'night'
|
|
||||||
}
|
|
||||||
|
|
||||||
const initialState: AppState = {
|
|
||||||
user: null,
|
|
||||||
faction: loadStoredFaction(),
|
|
||||||
colorMode: loadStoredColorMode(),
|
|
||||||
connectionStatus: {
|
|
||||||
database: true,
|
|
||||||
ssh: true,
|
|
||||||
bgd: true,
|
|
||||||
rmq: true,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
function reducer(state: AppState, action: Action): AppState {
|
|
||||||
switch (action.type) {
|
|
||||||
case 'SET_USER':
|
|
||||||
return { ...state, user: action.payload }
|
|
||||||
case 'SET_FACTION':
|
|
||||||
return { ...state, faction: action.payload }
|
|
||||||
case 'SET_COLOR_MODE':
|
|
||||||
return { ...state, colorMode: action.payload }
|
|
||||||
case 'SET_CONNECTION':
|
|
||||||
return { ...state, connectionStatus: { ...state.connectionStatus, ...action.payload } }
|
|
||||||
case 'ADD_TOAST':
|
|
||||||
toaster[action.payload.type]({
|
|
||||||
title: action.payload.message,
|
|
||||||
duration: 4000,
|
|
||||||
})
|
|
||||||
return state
|
|
||||||
default:
|
|
||||||
return state
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const AppContext = createContext<{
|
|
||||||
state: AppState
|
|
||||||
dispatch: React.Dispatch<Action>
|
|
||||||
} | null>(null)
|
|
||||||
|
|
||||||
export function AppProvider({ children }: { children: React.ReactNode }) {
|
|
||||||
const [state, dispatch] = useReducer(reducer, initialState)
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
localStorage.setItem('dune-faction', state.faction)
|
|
||||||
}, [state.faction])
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
localStorage.setItem('dune-color-mode', state.colorMode)
|
|
||||||
}, [state.colorMode])
|
|
||||||
|
|
||||||
return (
|
|
||||||
<AppContext.Provider value={{ state, dispatch }}>
|
|
||||||
{children}
|
|
||||||
</AppContext.Provider>
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function useApp() {
|
|
||||||
const ctx = useContext(AppContext)
|
|
||||||
if (!ctx) throw new Error('useApp must be used within AppProvider')
|
|
||||||
return ctx
|
|
||||||
}
|
|
||||||
@@ -1,100 +0,0 @@
|
|||||||
import { createSystem, defaultConfig } from '@chakra-ui/react'
|
|
||||||
import type { SystemConfig } from '@chakra-ui/react'
|
|
||||||
import { FACTION_PALETTES, type FactionKey, type FactionColors, FACTION_KEYS } from './palettes'
|
|
||||||
|
|
||||||
function semTokensFromPalette(c: FactionColors) {
|
|
||||||
return {
|
|
||||||
colors: {
|
|
||||||
bg: c.bg,
|
|
||||||
'bg.subtle': c.bgSubtle,
|
|
||||||
'fg': c.fg,
|
|
||||||
'fg.muted': c.fgMuted,
|
|
||||||
'border': c.border,
|
|
||||||
'border.subtle': c.borderSubtle,
|
|
||||||
'primary.DEFAULT': c.primary,
|
|
||||||
'primary.hover': c.primaryHover,
|
|
||||||
'primary.subtle': c.primarySubtle,
|
|
||||||
'accent': c.accent,
|
|
||||||
'danger.DEFAULT': c.danger,
|
|
||||||
'danger.subtle': c.dangerSubtle,
|
|
||||||
'success.DEFAULT': c.success,
|
|
||||||
'success.subtle': c.successSubtle,
|
|
||||||
'warning.DEFAULT': c.warning,
|
|
||||||
'warning.subtle': c.warningSubtle,
|
|
||||||
'info.DEFAULT': c.info,
|
|
||||||
'info.subtle': c.infoSubtle,
|
|
||||||
'nav.bg': c.navBg,
|
|
||||||
'card.bg': c.cardBg,
|
|
||||||
'code.bg': c.codeBg,
|
|
||||||
},
|
|
||||||
shadows: {
|
|
||||||
card: c.shadow,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type TokenRecord = Record<string, Record<string, { value: unknown }>>
|
|
||||||
|
|
||||||
function makeSemanticTokens(t: ReturnType<typeof semTokensFromPalette>): TokenRecord {
|
|
||||||
const result: TokenRecord = {}
|
|
||||||
for (const [category, entries] of Object.entries(t)) {
|
|
||||||
result[category] = {}
|
|
||||||
if (category === 'colors') {
|
|
||||||
for (const [key, val] of Object.entries(entries as Record<string, string>)) {
|
|
||||||
result.colors![key] = { value: val }
|
|
||||||
}
|
|
||||||
} else if (category === 'shadows') {
|
|
||||||
for (const [key, val] of Object.entries(entries as Record<string, string>)) {
|
|
||||||
result.shadows![key] = { value: val }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return result
|
|
||||||
}
|
|
||||||
|
|
||||||
function buildSystem(tokens: ReturnType<typeof semTokensFromPalette>) {
|
|
||||||
const systemConfig: SystemConfig = {
|
|
||||||
conditions: defaultConfig.conditions,
|
|
||||||
utilities: defaultConfig.utilities,
|
|
||||||
preflight: defaultConfig.preflight,
|
|
||||||
cssVarsPrefix: defaultConfig.cssVarsPrefix,
|
|
||||||
cssVarsRoot: defaultConfig.cssVarsRoot,
|
|
||||||
globalCss: defaultConfig.globalCss,
|
|
||||||
theme: {
|
|
||||||
breakpoints: defaultConfig.theme?.breakpoints,
|
|
||||||
keyframes: defaultConfig.theme?.keyframes,
|
|
||||||
tokens: defaultConfig.theme?.tokens,
|
|
||||||
semanticTokens: makeSemanticTokens(tokens) as any,
|
|
||||||
recipes: defaultConfig.theme?.recipes,
|
|
||||||
slotRecipes: defaultConfig.theme?.slotRecipes,
|
|
||||||
textStyles: defaultConfig.theme?.textStyles,
|
|
||||||
layerStyles: defaultConfig.theme?.layerStyles,
|
|
||||||
animationStyles: defaultConfig.theme?.animationStyles,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
return createSystem(systemConfig, {})
|
|
||||||
}
|
|
||||||
|
|
||||||
type SystemCache = Record<string, Record<string, ReturnType<typeof createSystem>>>
|
|
||||||
const systemCache: SystemCache = {}
|
|
||||||
|
|
||||||
function getOrCreateSystem(faction: FactionKey, mode: 'day' | 'night') {
|
|
||||||
const key = `${faction}:${mode}`
|
|
||||||
if (!systemCache[faction]) systemCache[faction] = {}
|
|
||||||
if (!systemCache[faction][mode]) {
|
|
||||||
const palette = FACTION_PALETTES[faction][mode]
|
|
||||||
systemCache[faction][mode] = buildSystem(semTokensFromPalette(palette))
|
|
||||||
}
|
|
||||||
return systemCache[faction][mode]
|
|
||||||
}
|
|
||||||
|
|
||||||
export function createDuneSystem(faction: FactionKey, mode: 'day' | 'night') {
|
|
||||||
return getOrCreateSystem(faction, mode)
|
|
||||||
}
|
|
||||||
|
|
||||||
export function getFactionName(key: FactionKey): string {
|
|
||||||
return FACTION_PALETTES[key]?.name ?? key
|
|
||||||
}
|
|
||||||
|
|
||||||
export { FACTION_KEYS, FACTION_PALETTES }
|
|
||||||
export type { FactionKey }
|
|
||||||
@@ -1,49 +0,0 @@
|
|||||||
import { FACTION_PALETTES, type FactionKey, type FactionColors } from './palettes'
|
|
||||||
|
|
||||||
const TOKEN_MAP: [string, keyof FactionColors][] = [
|
|
||||||
['--chakra-colors-bg', 'bg'],
|
|
||||||
['--chakra-colors-bg-subtle', 'bgSubtle'],
|
|
||||||
['--chakra-colors-card-bg', 'cardBg'],
|
|
||||||
['--chakra-colors-nav-bg', 'navBg'],
|
|
||||||
['--chakra-colors-fg', 'fg'],
|
|
||||||
['--chakra-colors-fg-muted', 'fgMuted'],
|
|
||||||
['--chakra-colors-border', 'border'],
|
|
||||||
['--chakra-colors-border-subtle', 'borderSubtle'],
|
|
||||||
['--chakra-colors-primary-DEFAULT', 'primary'],
|
|
||||||
['--chakra-colors-primary-hover', 'primaryHover'],
|
|
||||||
['--chakra-colors-primary-subtle', 'primarySubtle'],
|
|
||||||
['--chakra-colors-accent', 'accent'],
|
|
||||||
['--chakra-colors-danger-DEFAULT', 'danger'],
|
|
||||||
['--chakra-colors-danger-subtle', 'dangerSubtle'],
|
|
||||||
['--chakra-colors-success-DEFAULT', 'success'],
|
|
||||||
['--chakra-colors-success-subtle', 'successSubtle'],
|
|
||||||
['--chakra-colors-warning-DEFAULT', 'warning'],
|
|
||||||
['--chakra-colors-warning-subtle', 'warningSubtle'],
|
|
||||||
['--chakra-colors-info-DEFAULT', 'info'],
|
|
||||||
['--chakra-colors-info-subtle', 'infoSubtle'],
|
|
||||||
['--chakra-colors-code-bg', 'codeBg'],
|
|
||||||
['--chakra-shadows-card', 'shadow'],
|
|
||||||
]
|
|
||||||
|
|
||||||
let injectedStyle: HTMLStyleElement | null = null
|
|
||||||
|
|
||||||
export function injectThemeVars(faction: FactionKey, mode: 'day' | 'night') {
|
|
||||||
const palette = FACTION_PALETTES[faction]?.[mode]
|
|
||||||
if (!palette) return
|
|
||||||
|
|
||||||
const lines = TOKEN_MAP.map(([varName, key]) => {
|
|
||||||
const value = palette[key]
|
|
||||||
if (varName.startsWith('--chakra-shadows-')) {
|
|
||||||
return `${varName}:${value};`
|
|
||||||
}
|
|
||||||
return `${varName}:${value};`
|
|
||||||
})
|
|
||||||
|
|
||||||
if (!injectedStyle) {
|
|
||||||
injectedStyle = document.createElement('style')
|
|
||||||
injectedStyle.id = 'dune-theme-vars'
|
|
||||||
document.head.appendChild(injectedStyle)
|
|
||||||
}
|
|
||||||
|
|
||||||
injectedStyle.textContent = `:where(html, .chakra-theme) {\n ${lines.join('\n ')}\n}`
|
|
||||||
}
|
|
||||||
@@ -1,661 +0,0 @@
|
|||||||
export interface FactionColors {
|
|
||||||
bg: string
|
|
||||||
bgSubtle: string
|
|
||||||
cardBg: string
|
|
||||||
navBg: string
|
|
||||||
fg: string
|
|
||||||
fgMuted: string
|
|
||||||
border: string
|
|
||||||
borderSubtle: string
|
|
||||||
primary: string
|
|
||||||
primaryHover: string
|
|
||||||
primarySubtle: string
|
|
||||||
accent: string
|
|
||||||
danger: string
|
|
||||||
dangerSubtle: string
|
|
||||||
success: string
|
|
||||||
successSubtle: string
|
|
||||||
warning: string
|
|
||||||
warningSubtle: string
|
|
||||||
info: string
|
|
||||||
infoSubtle: string
|
|
||||||
codeBg: string
|
|
||||||
shadow: string
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface FactionPalette {
|
|
||||||
name: string
|
|
||||||
day: FactionColors
|
|
||||||
night: FactionColors
|
|
||||||
}
|
|
||||||
|
|
||||||
export const FACTION_PALETTES: Record<string, FactionPalette> = {
|
|
||||||
atreides: {
|
|
||||||
name: 'House Atreides',
|
|
||||||
day: {
|
|
||||||
bg: '#f4f7f2',
|
|
||||||
bgSubtle: '#edf1ea',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a2e1a',
|
|
||||||
fg: '#1a2e1a',
|
|
||||||
fgMuted: '#6b7c6b',
|
|
||||||
border: '#d4ddd4',
|
|
||||||
borderSubtle: '#e8efe8',
|
|
||||||
primary: '#2d5a27',
|
|
||||||
primaryHover: '#3d7a35',
|
|
||||||
primarySubtle: '#e8f5e8',
|
|
||||||
accent: '#1e3d19',
|
|
||||||
danger: '#8b2500',
|
|
||||||
dangerSubtle: '#fde8e8',
|
|
||||||
success: '#2d5a27',
|
|
||||||
successSubtle: '#e6f4e6',
|
|
||||||
warning: '#b8860b',
|
|
||||||
warningSubtle: '#fef3c7',
|
|
||||||
info: '#4a90d9',
|
|
||||||
infoSubtle: '#e8f0fb',
|
|
||||||
codeBg: '#1e2a1e',
|
|
||||||
shadow: '0 2px 12px rgba(30, 61, 25, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0d1a0d',
|
|
||||||
bgSubtle: '#101e10',
|
|
||||||
cardBg: '#142214',
|
|
||||||
navBg: '#0a120a',
|
|
||||||
fg: '#d4ddd4',
|
|
||||||
fgMuted: '#6b8a6b',
|
|
||||||
border: '#1e3d1e',
|
|
||||||
borderSubtle: '#162d16',
|
|
||||||
primary: '#4aad4a',
|
|
||||||
primaryHover: '#5cc45c',
|
|
||||||
primarySubtle: '#0d2a0d',
|
|
||||||
accent: '#7acc7a',
|
|
||||||
danger: '#ff4444',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#4aad4a',
|
|
||||||
successSubtle: '#0d2a0d',
|
|
||||||
warning: '#d4a853',
|
|
||||||
warningSubtle: '#2a200d',
|
|
||||||
info: '#6495ed',
|
|
||||||
infoSubtle: '#0d1a2a',
|
|
||||||
codeBg: '#0a100a',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
harkonnen: {
|
|
||||||
name: 'House Harkonnen',
|
|
||||||
day: {
|
|
||||||
bg: '#f5f0eb',
|
|
||||||
bgSubtle: '#f0e8e0',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a1208',
|
|
||||||
fg: '#2a1a0a',
|
|
||||||
fgMuted: '#8a6a4a',
|
|
||||||
border: '#e0d5c5',
|
|
||||||
borderSubtle: '#eee5d8',
|
|
||||||
primary: '#e05a00',
|
|
||||||
primaryHover: '#ff6c1a',
|
|
||||||
primarySubtle: '#fff0e6',
|
|
||||||
accent: '#8b4500',
|
|
||||||
danger: '#c0392b',
|
|
||||||
dangerSubtle: '#fde8e8',
|
|
||||||
success: '#27ae60',
|
|
||||||
successSubtle: '#e6f4e6',
|
|
||||||
warning: '#d4a017',
|
|
||||||
warningSubtle: '#fef3c7',
|
|
||||||
info: '#607d8b',
|
|
||||||
infoSubtle: '#e8f0f4',
|
|
||||||
codeBg: '#1e1810',
|
|
||||||
shadow: '0 2px 12px rgba(80, 30, 0, 0.1)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0d0804',
|
|
||||||
bgSubtle: '#100c06',
|
|
||||||
cardBg: '#14100a',
|
|
||||||
navBg: '#080400',
|
|
||||||
fg: '#d4c8b8',
|
|
||||||
fgMuted: '#8a7a60',
|
|
||||||
border: '#2a1a0a',
|
|
||||||
borderSubtle: '#1e1408',
|
|
||||||
primary: '#ff6b00',
|
|
||||||
primaryHover: '#ff8533',
|
|
||||||
primarySubtle: '#2a1000',
|
|
||||||
accent: '#ff8c44',
|
|
||||||
danger: '#ff4444',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#44cc44',
|
|
||||||
successSubtle: '#0d2a0d',
|
|
||||||
warning: '#e8a830',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#78909c',
|
|
||||||
infoSubtle: '#0d1a20',
|
|
||||||
codeBg: '#0a0602',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.6)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
fremen: {
|
|
||||||
name: 'Fremen',
|
|
||||||
day: {
|
|
||||||
bg: '#faf6ed',
|
|
||||||
bgSubtle: '#f5efe0',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#2c2418',
|
|
||||||
fg: '#3d3428',
|
|
||||||
fgMuted: '#8a7d66',
|
|
||||||
border: '#d4cbb8',
|
|
||||||
borderSubtle: '#e8e0d0',
|
|
||||||
primary: '#c49a3c',
|
|
||||||
primaryHover: '#d4a853',
|
|
||||||
primarySubtle: '#fdf5e6',
|
|
||||||
accent: '#8b6914',
|
|
||||||
danger: '#a04000',
|
|
||||||
dangerSubtle: '#fde8e0',
|
|
||||||
success: '#6b8e23',
|
|
||||||
successSubtle: '#e6f0d8',
|
|
||||||
warning: '#d4a017',
|
|
||||||
warningSubtle: '#fef3c7',
|
|
||||||
info: '#5b8fa8',
|
|
||||||
infoSubtle: '#e0eff5',
|
|
||||||
codeBg: '#2a2016',
|
|
||||||
shadow: '0 2px 12px rgba(60, 50, 30, 0.1)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#141008',
|
|
||||||
bgSubtle: '#18140c',
|
|
||||||
cardBg: '#1c1810',
|
|
||||||
navBg: '#0c0804',
|
|
||||||
fg: '#d4cbb8',
|
|
||||||
fgMuted: '#8a7d66',
|
|
||||||
border: '#3a2e1a',
|
|
||||||
borderSubtle: '#2a2010',
|
|
||||||
primary: '#d4a853',
|
|
||||||
primaryHover: '#e0b964',
|
|
||||||
primarySubtle: '#2a1a08',
|
|
||||||
accent: '#e0c060',
|
|
||||||
danger: '#d44530',
|
|
||||||
dangerSubtle: '#2a0d08',
|
|
||||||
success: '#6b8e23',
|
|
||||||
successSubtle: '#0d2a08',
|
|
||||||
warning: '#c8a040',
|
|
||||||
warningSubtle: '#2a1a08',
|
|
||||||
info: '#5b8fa8',
|
|
||||||
infoSubtle: '#0d1a28',
|
|
||||||
codeBg: '#0a0602',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
'bene-gesserit': {
|
|
||||||
name: 'Bene Gesserit',
|
|
||||||
day: {
|
|
||||||
bg: '#f7f6f9',
|
|
||||||
bgSubtle: '#f0eff4',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a1a24',
|
|
||||||
fg: '#2a2a38',
|
|
||||||
fgMuted: '#7878a0',
|
|
||||||
border: '#e0dde8',
|
|
||||||
borderSubtle: '#eeebf4',
|
|
||||||
primary: '#7b6ba8',
|
|
||||||
primaryHover: '#9080c0',
|
|
||||||
primarySubtle: '#f0edf8',
|
|
||||||
accent: '#5a4a88',
|
|
||||||
danger: '#c41e3a',
|
|
||||||
dangerSubtle: '#fde8ec',
|
|
||||||
success: '#2e8b57',
|
|
||||||
successSubtle: '#e6f4ec',
|
|
||||||
warning: '#9b7c28',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#6a8ba8',
|
|
||||||
infoSubtle: '#e8eff5',
|
|
||||||
codeBg: '#1e1e2a',
|
|
||||||
shadow: '0 2px 12px rgba(50, 40, 70, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0e0e18',
|
|
||||||
bgSubtle: '#10101c',
|
|
||||||
cardBg: '#161622',
|
|
||||||
navBg: '#08080e',
|
|
||||||
fg: '#c8c8e0',
|
|
||||||
fgMuted: '#7878a0',
|
|
||||||
border: '#2a2a40',
|
|
||||||
borderSubtle: '#1e1e30',
|
|
||||||
primary: '#a090d0',
|
|
||||||
primaryHover: '#b8a8e0',
|
|
||||||
primarySubtle: '#1a1a30',
|
|
||||||
accent: '#c0b0e8',
|
|
||||||
danger: '#e84858',
|
|
||||||
dangerSubtle: '#2a0d14',
|
|
||||||
success: '#48b868',
|
|
||||||
successSubtle: '#0d2a18',
|
|
||||||
warning: '#c8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#8098c0',
|
|
||||||
infoSubtle: '#0d1a2a',
|
|
||||||
codeBg: '#080810',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
'spacing-guild': {
|
|
||||||
name: 'Spacing Guild',
|
|
||||||
day: {
|
|
||||||
bg: '#f2f5fa',
|
|
||||||
bgSubtle: '#eaf0f8',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#0f1a30',
|
|
||||||
fg: '#1a2a50',
|
|
||||||
fgMuted: '#6a7a9a',
|
|
||||||
border: '#d0d8e8',
|
|
||||||
borderSubtle: '#e4eaf4',
|
|
||||||
primary: '#3a70c0',
|
|
||||||
primaryHover: '#4a80d0',
|
|
||||||
primarySubtle: '#e8f0fb',
|
|
||||||
accent: '#1a5098',
|
|
||||||
danger: '#c44545',
|
|
||||||
dangerSubtle: '#fde8e8',
|
|
||||||
success: '#38a870',
|
|
||||||
successSubtle: '#e6f4ec',
|
|
||||||
warning: '#c89828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#5a90d0',
|
|
||||||
infoSubtle: '#e0ecf8',
|
|
||||||
codeBg: '#101a28',
|
|
||||||
shadow: '0 2px 12px rgba(20, 40, 80, 0.1)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#060d18',
|
|
||||||
bgSubtle: '#08101e',
|
|
||||||
cardBg: '#0c1424',
|
|
||||||
navBg: '#040810',
|
|
||||||
fg: '#b8c8e8',
|
|
||||||
fgMuted: '#6078a0',
|
|
||||||
border: '#1a3058',
|
|
||||||
borderSubtle: '#102040',
|
|
||||||
primary: '#5a90e0',
|
|
||||||
primaryHover: '#6aa0f0',
|
|
||||||
primarySubtle: '#0d1a38',
|
|
||||||
accent: '#7ab0f8',
|
|
||||||
danger: '#e85858',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#48b878',
|
|
||||||
successSubtle: '#0d2a18',
|
|
||||||
warning: '#d8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#6aa0e8',
|
|
||||||
infoSubtle: '#0d1a30',
|
|
||||||
codeBg: '#040a12',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
imperial: {
|
|
||||||
name: 'Imperial House',
|
|
||||||
day: {
|
|
||||||
bg: '#faf5f5',
|
|
||||||
bgSubtle: '#f5eded',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a0a0a',
|
|
||||||
fg: '#2a1515',
|
|
||||||
fgMuted: '#8a5555',
|
|
||||||
border: '#e0d0d0',
|
|
||||||
borderSubtle: '#ece0e0',
|
|
||||||
primary: '#9b1a1a',
|
|
||||||
primaryHover: '#b82020',
|
|
||||||
primarySubtle: '#fde8e8',
|
|
||||||
accent: '#c89828',
|
|
||||||
danger: '#8b0000',
|
|
||||||
dangerSubtle: '#fde0e0',
|
|
||||||
success: '#2d5a27',
|
|
||||||
successSubtle: '#e6f4e6',
|
|
||||||
warning: '#c89828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#6a7a8a',
|
|
||||||
infoSubtle: '#e8eef2',
|
|
||||||
codeBg: '#1e1010',
|
|
||||||
shadow: '0 2px 12px rgba(80, 0, 0, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0d0505',
|
|
||||||
bgSubtle: '#100808',
|
|
||||||
cardBg: '#160c0c',
|
|
||||||
navBg: '#080202',
|
|
||||||
fg: '#d4c0c0',
|
|
||||||
fgMuted: '#8a6060',
|
|
||||||
border: '#2a1010',
|
|
||||||
borderSubtle: '#1e0a0a',
|
|
||||||
primary: '#d43030',
|
|
||||||
primaryHover: '#e04848',
|
|
||||||
primarySubtle: '#2a0808',
|
|
||||||
accent: '#e0b840',
|
|
||||||
danger: '#e84848',
|
|
||||||
dangerSubtle: '#2a0808',
|
|
||||||
success: '#48b848',
|
|
||||||
successSubtle: '#0d2a0d',
|
|
||||||
warning: '#d8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#7a8a9a',
|
|
||||||
infoSubtle: '#0d1a28',
|
|
||||||
codeBg: '#080202',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.6)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
mentat: {
|
|
||||||
name: 'Mentat',
|
|
||||||
day: {
|
|
||||||
bg: '#f4f8f7',
|
|
||||||
bgSubtle: '#edf4f2',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#0a1a18',
|
|
||||||
fg: '#1a2a28',
|
|
||||||
fgMuted: '#6a7a78',
|
|
||||||
border: '#d0e0dc',
|
|
||||||
borderSubtle: '#e4eeea',
|
|
||||||
primary: '#0d7a6e',
|
|
||||||
primaryHover: '#109a8a',
|
|
||||||
primarySubtle: '#e6f5f3',
|
|
||||||
accent: '#086058',
|
|
||||||
danger: '#c44a3a',
|
|
||||||
dangerSubtle: '#fde8e4',
|
|
||||||
success: '#0d7a6e',
|
|
||||||
successSubtle: '#e6f5f3',
|
|
||||||
warning: '#c89828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#5a8aa0',
|
|
||||||
infoSubtle: '#e4f0f5',
|
|
||||||
codeBg: '#101e1c',
|
|
||||||
shadow: '0 2px 12px rgba(10, 60, 50, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#050d0c',
|
|
||||||
bgSubtle: '#081210',
|
|
||||||
cardBg: '#0c1816',
|
|
||||||
navBg: '#020808',
|
|
||||||
fg: '#b8d0cc',
|
|
||||||
fgMuted: '#608a84',
|
|
||||||
border: '#1a3832',
|
|
||||||
borderSubtle: '#102820',
|
|
||||||
primary: '#18c0a8',
|
|
||||||
primaryHover: '#20d8b8',
|
|
||||||
primarySubtle: '#0d2a24',
|
|
||||||
accent: '#28e0c0',
|
|
||||||
danger: '#e85040',
|
|
||||||
dangerSubtle: '#2a0d0a',
|
|
||||||
success: '#18c0a8',
|
|
||||||
successSubtle: '#0d2a24',
|
|
||||||
warning: '#d8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#6a9ab0',
|
|
||||||
infoSubtle: '#0d1a28',
|
|
||||||
codeBg: '#040a08',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
sardaukar: {
|
|
||||||
name: 'Sardaukar',
|
|
||||||
day: {
|
|
||||||
bg: '#f5f2ef',
|
|
||||||
bgSubtle: '#f0ebe6',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a140c',
|
|
||||||
fg: '#2a2018',
|
|
||||||
fgMuted: '#8a7a68',
|
|
||||||
border: '#e0d8cc',
|
|
||||||
borderSubtle: '#ece4d8',
|
|
||||||
primary: '#8b5a30',
|
|
||||||
primaryHover: '#a06e3c',
|
|
||||||
primarySubtle: '#fdf0e6',
|
|
||||||
accent: '#6b4020',
|
|
||||||
danger: '#8b0000',
|
|
||||||
dangerSubtle: '#fde0e0',
|
|
||||||
success: '#5a7a30',
|
|
||||||
successSubtle: '#e8f0dc',
|
|
||||||
warning: '#c08028',
|
|
||||||
warningSubtle: '#fef0d4',
|
|
||||||
info: '#7a8a90',
|
|
||||||
infoSubtle: '#e8eef0',
|
|
||||||
codeBg: '#1e1810',
|
|
||||||
shadow: '0 2px 12px rgba(60, 40, 20, 0.1)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0c0804',
|
|
||||||
bgSubtle: '#100c06',
|
|
||||||
cardBg: '#16100a',
|
|
||||||
navBg: '#060400',
|
|
||||||
fg: '#d4c8b8',
|
|
||||||
fgMuted: '#8a7a60',
|
|
||||||
border: '#2a1e10',
|
|
||||||
borderSubtle: '#1e1408',
|
|
||||||
primary: '#c08040',
|
|
||||||
primaryHover: '#d09050',
|
|
||||||
primarySubtle: '#2a1408',
|
|
||||||
accent: '#d8a060',
|
|
||||||
danger: '#d84040',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#7a9a40',
|
|
||||||
successSubtle: '#1a2a0d',
|
|
||||||
warning: '#d09038',
|
|
||||||
warningSubtle: '#2a180d',
|
|
||||||
info: '#8a9aa0',
|
|
||||||
infoSubtle: '#0d1a20',
|
|
||||||
codeBg: '#060400',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
tleilaxu: {
|
|
||||||
name: 'Tleilaxu',
|
|
||||||
day: {
|
|
||||||
bg: '#f6f4fa',
|
|
||||||
bgSubtle: '#f0edf6',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a1028',
|
|
||||||
fg: '#2a1a40',
|
|
||||||
fgMuted: '#7a68a0',
|
|
||||||
border: '#d8cce8',
|
|
||||||
borderSubtle: '#e8e0f4',
|
|
||||||
primary: '#6a30a0',
|
|
||||||
primaryHover: '#7a40b0',
|
|
||||||
primarySubtle: '#f2e8fc',
|
|
||||||
accent: '#4a2080',
|
|
||||||
danger: '#c43a3a',
|
|
||||||
dangerSubtle: '#fde8e8',
|
|
||||||
success: '#30a060',
|
|
||||||
successSubtle: '#e6f4ec',
|
|
||||||
warning: '#b09030',
|
|
||||||
warningSubtle: '#fef3d4',
|
|
||||||
info: '#7060a8',
|
|
||||||
infoSubtle: '#ece8f8',
|
|
||||||
codeBg: '#1e1828',
|
|
||||||
shadow: '0 2px 12px rgba(40, 20, 70, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#080410',
|
|
||||||
bgSubtle: '#0c0618',
|
|
||||||
cardBg: '#10081e',
|
|
||||||
navBg: '#040208',
|
|
||||||
fg: '#c8b8e0',
|
|
||||||
fgMuted: '#7868a0',
|
|
||||||
border: '#281840',
|
|
||||||
borderSubtle: '#1c1030',
|
|
||||||
primary: '#a060e0',
|
|
||||||
primaryHover: '#b070f0',
|
|
||||||
primarySubtle: '#18082a',
|
|
||||||
accent: '#c080f8',
|
|
||||||
danger: '#d84040',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#40b068',
|
|
||||||
successSubtle: '#0d2a18',
|
|
||||||
warning: '#c0a040',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#8070b8',
|
|
||||||
infoSubtle: '#100d28',
|
|
||||||
codeBg: '#040208',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
ordos: {
|
|
||||||
name: 'House Ordos',
|
|
||||||
day: {
|
|
||||||
bg: '#f2f7f4',
|
|
||||||
bgSubtle: '#ebf2ed',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#0a1a12',
|
|
||||||
fg: '#1a2e22',
|
|
||||||
fgMuted: '#6a8072',
|
|
||||||
border: '#cce0d4',
|
|
||||||
borderSubtle: '#e0eee6',
|
|
||||||
primary: '#1e7a40',
|
|
||||||
primaryHover: '#289a50',
|
|
||||||
primarySubtle: '#e6f5ec',
|
|
||||||
accent: '#146030',
|
|
||||||
danger: '#c44a3a',
|
|
||||||
dangerSubtle: '#fde8e4',
|
|
||||||
success: '#1e7a40',
|
|
||||||
successSubtle: '#e6f5ec',
|
|
||||||
warning: '#b89828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#5a8a90',
|
|
||||||
infoSubtle: '#e4f0f2',
|
|
||||||
codeBg: '#101e16',
|
|
||||||
shadow: '0 2px 12px rgba(20, 60, 40, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#040d08',
|
|
||||||
bgSubtle: '#08120c',
|
|
||||||
cardBg: '#0c1810',
|
|
||||||
navBg: '#020804',
|
|
||||||
fg: '#b8d4c4',
|
|
||||||
fgMuted: '#608a72',
|
|
||||||
border: '#183828',
|
|
||||||
borderSubtle: '#10281c',
|
|
||||||
primary: '#30c060',
|
|
||||||
primaryHover: '#40d070',
|
|
||||||
primarySubtle: '#0d2a14',
|
|
||||||
accent: '#48d878',
|
|
||||||
danger: '#d84848',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#30c060',
|
|
||||||
successSubtle: '#0d2a14',
|
|
||||||
warning: '#c8a838',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#6a9aa0',
|
|
||||||
infoSubtle: '#0d1a20',
|
|
||||||
codeBg: '#020804',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
ixian: {
|
|
||||||
name: 'Ixian',
|
|
||||||
day: {
|
|
||||||
bg: '#f4f6fa',
|
|
||||||
bgSubtle: '#edf0f6',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#0a102a',
|
|
||||||
fg: '#1a2248',
|
|
||||||
fgMuted: '#6a7298',
|
|
||||||
border: '#d0d8e8',
|
|
||||||
borderSubtle: '#e4eaf4',
|
|
||||||
primary: '#3058c8',
|
|
||||||
primaryHover: '#4068d8',
|
|
||||||
primarySubtle: '#e8effb',
|
|
||||||
accent: '#183898',
|
|
||||||
danger: '#c43a50',
|
|
||||||
dangerSubtle: '#fde8ec',
|
|
||||||
success: '#30a860',
|
|
||||||
successSubtle: '#e6f4ec',
|
|
||||||
warning: '#c09828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#4878c0',
|
|
||||||
infoSubtle: '#e0eaf6',
|
|
||||||
codeBg: '#101828',
|
|
||||||
shadow: '0 2px 12px rgba(20, 40, 90, 0.08)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#040810',
|
|
||||||
bgSubtle: '#080c18',
|
|
||||||
cardBg: '#0c1020',
|
|
||||||
navBg: '#020408',
|
|
||||||
fg: '#b8c8e0',
|
|
||||||
fgMuted: '#6078a0',
|
|
||||||
border: '#1a2858',
|
|
||||||
borderSubtle: '#101c40',
|
|
||||||
primary: '#4878e8',
|
|
||||||
primaryHover: '#5888f8',
|
|
||||||
primarySubtle: '#0d1838',
|
|
||||||
accent: '#6098f8',
|
|
||||||
danger: '#d85060',
|
|
||||||
dangerSubtle: '#2a0d10',
|
|
||||||
success: '#40b870',
|
|
||||||
successSubtle: '#0d2a18',
|
|
||||||
warning: '#c8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#5888d8',
|
|
||||||
infoSubtle: '#0d1830',
|
|
||||||
codeBg: '#020408',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
|
|
||||||
choam: {
|
|
||||||
name: 'CHOAM',
|
|
||||||
day: {
|
|
||||||
bg: '#faf9f3',
|
|
||||||
bgSubtle: '#f5f4eb',
|
|
||||||
cardBg: '#ffffff',
|
|
||||||
navBg: '#1a180c',
|
|
||||||
fg: '#2a2820',
|
|
||||||
fgMuted: '#8a8878',
|
|
||||||
border: '#e8e4d8',
|
|
||||||
borderSubtle: '#f0ece0',
|
|
||||||
primary: '#a8860b',
|
|
||||||
primaryHover: '#c09a10',
|
|
||||||
primarySubtle: '#fdf8e6',
|
|
||||||
accent: '#786008',
|
|
||||||
danger: '#b22222',
|
|
||||||
dangerSubtle: '#fde8e8',
|
|
||||||
success: '#228b22',
|
|
||||||
successSubtle: '#e6f4e6',
|
|
||||||
warning: '#c89828',
|
|
||||||
warningSubtle: '#fef3d0',
|
|
||||||
info: '#8a8870',
|
|
||||||
infoSubtle: '#f0efe8',
|
|
||||||
codeBg: '#1e1c14',
|
|
||||||
shadow: '0 2px 12px rgba(60, 50, 20, 0.1)',
|
|
||||||
},
|
|
||||||
night: {
|
|
||||||
bg: '#0c0a04',
|
|
||||||
bgSubtle: '#100e06',
|
|
||||||
cardBg: '#16140a',
|
|
||||||
navBg: '#060400',
|
|
||||||
fg: '#d4d0c0',
|
|
||||||
fgMuted: '#8a8870',
|
|
||||||
border: '#2a2614',
|
|
||||||
borderSubtle: '#1e1a0c',
|
|
||||||
primary: '#c8a018',
|
|
||||||
primaryHover: '#d8b028',
|
|
||||||
primarySubtle: '#2a1c08',
|
|
||||||
accent: '#e0c838',
|
|
||||||
danger: '#d44040',
|
|
||||||
dangerSubtle: '#2a0d0d',
|
|
||||||
success: '#38a838',
|
|
||||||
successSubtle: '#0d2a0d',
|
|
||||||
warning: '#d8a840',
|
|
||||||
warningSubtle: '#2a1a0d',
|
|
||||||
info: '#9a9880',
|
|
||||||
infoSubtle: '#1a180d',
|
|
||||||
codeBg: '#060400',
|
|
||||||
shadow: '0 2px 12px rgba(0, 0, 0, 0.5)',
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
export type FactionKey = keyof typeof FACTION_PALETTES
|
|
||||||
export type ColorMode = 'day' | 'night'
|
|
||||||
|
|
||||||
export const FACTION_KEYS = Object.keys(FACTION_PALETTES) as FactionKey[]
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
import { createToaster } from '@chakra-ui/react'
|
|
||||||
|
|
||||||
export const toaster = createToaster({
|
|
||||||
placement: 'bottom-end',
|
|
||||||
overlap: true,
|
|
||||||
})
|
|
||||||
|
|
||||||
export type ToasterRef = typeof toaster
|
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"target": "ES2020",
|
|
||||||
"useDefineForClassFields": true,
|
|
||||||
"lib": ["ES2020", "DOM", "DOM.Iterable"],
|
|
||||||
"module": "ESNext",
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"allowImportingTsExtensions": true,
|
|
||||||
"resolveJsonModule": true,
|
|
||||||
"isolatedModules": true,
|
|
||||||
"noEmit": true,
|
|
||||||
"jsx": "react-jsx",
|
|
||||||
"strict": true,
|
|
||||||
"noUnusedLocals": false,
|
|
||||||
"noUnusedParameters": false,
|
|
||||||
"noFallthroughCasesInSwitch": true,
|
|
||||||
"baseUrl": ".",
|
|
||||||
"paths": {
|
|
||||||
"@/*": ["src/*"]
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"include": ["src"],
|
|
||||||
"references": [{ "path": "./tsconfig.node.json" }]
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"compilerOptions": {
|
|
||||||
"composite": true,
|
|
||||||
"skipLibCheck": true,
|
|
||||||
"module": "ESNext",
|
|
||||||
"moduleResolution": "bundler",
|
|
||||||
"allowSyntheticDefaultImports": true
|
|
||||||
},
|
|
||||||
"include": ["vite.config.ts"]
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
import { defineConfig } from 'vite'
|
|
||||||
import react from '@vitejs/plugin-react'
|
|
||||||
|
|
||||||
export default defineConfig({
|
|
||||||
plugins: [react()],
|
|
||||||
server: {
|
|
||||||
port: 5173,
|
|
||||||
proxy: {
|
|
||||||
'/api': {
|
|
||||||
target: 'http://localhost:5050',
|
|
||||||
changeOrigin: true,
|
|
||||||
ws: false,
|
|
||||||
},
|
|
||||||
'/socket.io': {
|
|
||||||
target: 'http://localhost:5050',
|
|
||||||
ws: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
build: {
|
|
||||||
outDir: 'dist',
|
|
||||||
emptyOutDir: true,
|
|
||||||
},
|
|
||||||
})
|
|
||||||
+330
-348
@@ -299,13 +299,20 @@ function Show-Menu {
|
|||||||
Write-Host " Launch dashboard with full debug logging enabled." -ForegroundColor DarkGray
|
Write-Host " Launch dashboard with full debug logging enabled." -ForegroundColor DarkGray
|
||||||
Write-Host " Logs written to logs/debug.log - includes SSH, API, DB, K8s details." -ForegroundColor DarkGray
|
Write-Host " Logs written to logs/debug.log - includes SSH, API, DB, K8s details." -ForegroundColor DarkGray
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " [7] Start New Dashboard (React + ChakraUI)" -ForegroundColor Green
|
Write-Host " [7] Reset to Factory Defaults" -ForegroundColor Red
|
||||||
Write-Host " Launch the modern React dashboard with ChakraUI and Recharts." -ForegroundColor DarkGray
|
|
||||||
Write-Host " Auto-installs dependencies. Frontend: http://localhost:5173" -ForegroundColor DarkGray
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " [8] Reset to Factory Defaults" -ForegroundColor Red
|
|
||||||
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
|
Write-Host " Wipe all data and start fresh. Removes settings, logs, certs, and cache." -ForegroundColor DarkGray
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
Write-Host " [8] Repair Game Database" -ForegroundColor Yellow
|
||||||
|
Write-Host " Fixes dashboard schema ownership so game updates won't break." -ForegroundColor DarkGray
|
||||||
|
Write-Host " Run this if game servers fail to start after an update." -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [9] Clean up Old Dashboard Schema" -ForegroundColor Red
|
||||||
|
Write-Host " Drops the old dashboard schema from the game database." -ForegroundColor DarkGray
|
||||||
|
Write-Host " Only run after confirming dashboard migrated successfully." -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " [10] Rotate SSH Key" -ForegroundColor Yellow
|
||||||
|
Write-Host " Scan all SSH key locations and copy the newest key to internal-scripts\ssh\sshKey." -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
Write-Host " [Q] Quit" -ForegroundColor White
|
Write-Host " [Q] Quit" -ForegroundColor White
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
}
|
}
|
||||||
@@ -468,7 +475,7 @@ function Test-SshConnection {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Write-Host " Testing SSH connection to $serverUser@$serverHost..." -ForegroundColor Yellow
|
Write-Host " Testing SSH connection to $serverUser@$serverHost..." -ForegroundColor Yellow
|
||||||
$testOut = ssh -i $sshKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${serverUser}@${serverHost}" "echo ok" 2>$null
|
$testOut = ssh -i $sshKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes "${serverUser}@${serverHost}" "echo ok" 2>$null
|
||||||
if ($testOut -eq "ok") {
|
if ($testOut -eq "ok") {
|
||||||
Write-Host " SSH Connection: OK" -ForegroundColor Green
|
Write-Host " SSH Connection: OK" -ForegroundColor Green
|
||||||
return $true
|
return $true
|
||||||
@@ -967,7 +974,7 @@ function Reset-ToFactoryDefaults {
|
|||||||
if (Test-Path (Join-Path $ProjectRoot "ssl")) { Remove-Item (Join-Path $ProjectRoot "ssl") -Recurse -Force; Write-Host " Deleted ssl/" -ForegroundColor Green; $count++ }
|
if (Test-Path (Join-Path $ProjectRoot "ssl")) { Remove-Item (Join-Path $ProjectRoot "ssl") -Recurse -Force; Write-Host " Deleted ssl/" -ForegroundColor Green; $count++ }
|
||||||
|
|
||||||
# -- Log directories --
|
# -- Log directories --
|
||||||
$logDirs = @("logs", "app\logs", "backend\logs")
|
$logDirs = @("logs", "app\logs")
|
||||||
foreach ($ld in $logDirs) {
|
foreach ($ld in $logDirs) {
|
||||||
$lp = Join-Path $ProjectRoot $ld
|
$lp = Join-Path $ProjectRoot $ld
|
||||||
if (Test-Path $lp) { Remove-Item $lp -Recurse -Force; Write-Host " Deleted $ld/" -ForegroundColor Green; $count++ }
|
if (Test-Path $lp) { Remove-Item $lp -Recurse -Force; Write-Host " Deleted $ld/" -ForegroundColor Green; $count++ }
|
||||||
@@ -1242,13 +1249,18 @@ function Run-Setup {
|
|||||||
|
|
||||||
function Fix-SshKeyPermissions($keyPath) {
|
function Fix-SshKeyPermissions($keyPath) {
|
||||||
if (-not (Test-Path $keyPath)) { return }
|
if (-not (Test-Path $keyPath)) { return }
|
||||||
$acl = Get-Acl $keyPath
|
try {
|
||||||
|
$acl = Get-Acl $keyPath -ErrorAction SilentlyContinue
|
||||||
|
if ($acl) {
|
||||||
$acl.SetAccessRuleProtection($true, $false)
|
$acl.SetAccessRuleProtection($true, $false)
|
||||||
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
|
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
|
||||||
$acl.SetAccessRule($rule)
|
$acl.SetAccessRule($rule)
|
||||||
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule("BUILTIN\Administrators", "FullControl", "Allow")
|
$adminSid = [System.Security.Principal.SecurityIdentifier]::new("S-1-5-32-544")
|
||||||
|
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule($adminSid, "FullControl", "Allow")
|
||||||
$acl.SetAccessRule($adminRule)
|
$acl.SetAccessRule($adminRule)
|
||||||
Set-Acl -Path $keyPath -AclObject $acl
|
Set-Acl -Path $keyPath -AclObject $acl -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (-not $FoundKey) {
|
if (-not $FoundKey) {
|
||||||
@@ -1419,7 +1431,7 @@ function Run-Setup {
|
|||||||
$sshOk = $false
|
$sshOk = $false
|
||||||
for ($i = 0; $i -lt 12; $i++) {
|
for ($i = 0; $i -lt 12; $i++) {
|
||||||
try {
|
try {
|
||||||
$testOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes dune@$VmHost "echo ok" 2>$null
|
$testOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes dune@$VmHost "echo ok" 2>$null
|
||||||
$testExit = $LASTEXITCODE
|
$testExit = $LASTEXITCODE
|
||||||
if ($testOut -match "ok" -and $testExit -eq 0) {
|
if ($testOut -match "ok" -and $testExit -eq 0) {
|
||||||
$sshOk = $true
|
$sshOk = $true
|
||||||
@@ -1433,7 +1445,7 @@ function Run-Setup {
|
|||||||
if ($sshOk) {
|
if ($sshOk) {
|
||||||
Write-Host " SSH connection OK" -ForegroundColor Green
|
Write-Host " SSH connection OK" -ForegroundColor Green
|
||||||
try {
|
try {
|
||||||
$nsOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes dune@$VmHost "sudo kubectl get namespaces -o name" 2>$null
|
$nsOut = ssh -i "$FoundKey" -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes dune@$VmHost "sudo kubectl get namespaces -o name" 2>$null
|
||||||
} catch { $nsOut = $null }
|
} catch { $nsOut = $null }
|
||||||
if ($nsOut) {
|
if ($nsOut) {
|
||||||
foreach ($line in $nsOut -split "`n") {
|
foreach ($line in $nsOut -split "`n") {
|
||||||
@@ -1526,6 +1538,9 @@ function Run-Setup {
|
|||||||
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
|
Write-Host " Configuring SSL certificate..." -ForegroundColor Yellow
|
||||||
$CertDir = Join-Path $ProjectRoot "ssl"
|
$CertDir = Join-Path $ProjectRoot "ssl"
|
||||||
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
|
if (-not (Test-Path $CertDir)) { New-Item -ItemType Directory -Path $CertDir -Force | Out-Null }
|
||||||
|
$LeConfigDir = Join-Path $ProjectRoot "certbot\config"
|
||||||
|
$LeWorkDir = Join-Path $ProjectRoot "certbot\work"
|
||||||
|
$LeLogsDir = Join-Path $ProjectRoot "certbot\logs"
|
||||||
$CaCertPath = Join-Path $CertDir "ca.pem"
|
$CaCertPath = Join-Path $CertDir "ca.pem"
|
||||||
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
|
$CaKeyPath = Join-Path $CertDir "ca-key.pem"
|
||||||
$SslCertPath = Join-Path $CertDir "cert.pem"
|
$SslCertPath = Join-Path $CertDir "cert.pem"
|
||||||
@@ -1572,8 +1587,14 @@ function Run-Setup {
|
|||||||
|
|
||||||
$certbotUseModule = ($certbotCmd.Source -eq "python")
|
$certbotUseModule = ($certbotCmd.Source -eq "python")
|
||||||
|
|
||||||
|
New-Item -ItemType Directory -Path $LeConfigDir -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path $LeWorkDir -Force | Out-Null
|
||||||
|
New-Item -ItemType Directory -Path $LeLogsDir -Force | Out-Null
|
||||||
|
|
||||||
|
$certbotDirArgs = @("--config-dir", $LeConfigDir, "--work-dir", $LeWorkDir, "--logs-dir", $LeLogsDir)
|
||||||
|
|
||||||
if ($certbotUseModule) {
|
if ($certbotUseModule) {
|
||||||
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos")
|
$certbotArgs = @("-m", "certbot", "certonly", "--standalone", "-d", $DomainName, "--non-interactive", "--agree-tos") + $certbotDirArgs
|
||||||
if ($LeEmail) {
|
if ($LeEmail) {
|
||||||
$certbotArgs += "--email"
|
$certbotArgs += "--email"
|
||||||
$certbotArgs += $LeEmail
|
$certbotArgs += $LeEmail
|
||||||
@@ -1587,7 +1608,7 @@ function Run-Setup {
|
|||||||
"-d", $DomainName,
|
"-d", $DomainName,
|
||||||
"--non-interactive",
|
"--non-interactive",
|
||||||
"--agree-tos"
|
"--agree-tos"
|
||||||
)
|
) + $certbotDirArgs
|
||||||
if ($LeEmail) {
|
if ($LeEmail) {
|
||||||
$certbotArgs += "--email"
|
$certbotArgs += "--email"
|
||||||
$certbotArgs += $LeEmail
|
$certbotArgs += $LeEmail
|
||||||
@@ -1600,13 +1621,9 @@ function Run-Setup {
|
|||||||
|
|
||||||
if ($certbotResult.ExitCode -eq 0) {
|
if ($certbotResult.ExitCode -eq 0) {
|
||||||
$UseLetsEncrypt = $true
|
$UseLetsEncrypt = $true
|
||||||
$LeCertPath = "C:\ProgramData\certbot\live\$DomainName\fullchain.pem"
|
$LeLiveDir = Join-Path $LeConfigDir "live\$DomainName"
|
||||||
$LeKeyPath = "C:\ProgramData\certbot\live\$DomainName\privkey.pem"
|
$LeCertPath = Join-Path $LeLiveDir "fullchain.pem"
|
||||||
|
$LeKeyPath = Join-Path $LeLiveDir "privkey.pem"
|
||||||
if (-not (Test-Path $LeCertPath)) {
|
|
||||||
$LeCertPath = "C:\Certbot\live\$DomainName\fullchain.pem"
|
|
||||||
$LeKeyPath = "C:\Certbot\live\$DomainName\privkey.pem"
|
|
||||||
}
|
|
||||||
|
|
||||||
if (Test-Path $LeCertPath) {
|
if (Test-Path $LeCertPath) {
|
||||||
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
|
Write-Host " Let's Encrypt certificate obtained successfully!" -ForegroundColor Green
|
||||||
@@ -1645,8 +1662,11 @@ function Run-Setup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
|
$SanIpsArray = "['" + ($SanIps -join "', '") + "']"
|
||||||
|
$SanDnsArray = "['localhost'"
|
||||||
|
if ($DomainName) { $SanDnsArray += ", '" + $DomainName + "'" }
|
||||||
|
$SanDnsArray += "]"
|
||||||
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
|
if ($VmHost -ne "YOUR_SERVER_IP") { $CommonName = $VmHost } else { $CommonName = "localhost" }
|
||||||
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=['localhost'])"
|
python -c "from app.utils.ssl import generate_cert; generate_cert('$SslCertPathPy', '$SslKeyPathPy', ca_cert_path='$CaCertPathPy', ca_key_path='$CaKeyPathPy', common_name='$CommonName', san_ips=$SanIpsArray, san_dns=$SanDnsArray)"
|
||||||
$SslCert = "'$SslCertPath'"
|
$SslCert = "'$SslCertPath'"
|
||||||
$SslKey = "'$SslKeyPath'"
|
$SslKey = "'$SslKeyPath'"
|
||||||
|
|
||||||
@@ -1778,7 +1798,7 @@ function Run-Setup {
|
|||||||
$certbotPath = "certbot"
|
$certbotPath = "certbot"
|
||||||
}
|
}
|
||||||
|
|
||||||
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet"
|
$renewAction = New-ScheduledTaskAction -Execute $certbotPath -Argument "renew --quiet --config-dir `"$LeConfigDir`" --work-dir `"$LeWorkDir`" --logs-dir `"$LeLogsDir`""
|
||||||
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
|
$renewTrigger = New-ScheduledTaskTrigger -Daily -At 2am
|
||||||
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
$renewSettings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
|
||||||
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
|
$renewPrincipal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest
|
||||||
@@ -1926,7 +1946,7 @@ logging:
|
|||||||
# Check if SSH key is valid for the server
|
# Check if SSH key is valid for the server
|
||||||
$SshValid = $false
|
$SshValid = $false
|
||||||
if ($FoundKey -and (Test-Path $FoundKey) -and $VmHost -ne "YOUR_SERVER_IP") {
|
if ($FoundKey -and (Test-Path $FoundKey) -and $VmHost -ne "YOUR_SERVER_IP") {
|
||||||
$testOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${VmHost}" "echo ok" 2>$null
|
$testOut = ssh -i $FoundKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 -o BatchMode=yes "${ServerUser}@${VmHost}" "echo ok" 2>$null
|
||||||
$SshValid = ($testOut -eq "ok")
|
$SshValid = ($testOut -eq "ok")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1970,7 +1990,7 @@ logging:
|
|||||||
$bytes = [System.IO.File]::ReadAllBytes($tmpFwScript)
|
$bytes = [System.IO.File]::ReadAllBytes($tmpFwScript)
|
||||||
Remove-Item $tmpFwScript -Force -ErrorAction SilentlyContinue
|
Remove-Item $tmpFwScript -Force -ErrorAction SilentlyContinue
|
||||||
$b64 = [Convert]::ToBase64String($bytes)
|
$b64 = [Convert]::ToBase64String($bytes)
|
||||||
$fwOut = ssh -i $FoundKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 "${ServerUser}@${VmHost}" "echo '$b64' | base64 -d > /tmp/fw.sh && sudo bash /tmp/fw.sh && rm /tmp/fw.sh" 2>&1
|
$fwOut = ssh -i $FoundKey -o StrictHostKeyChecking=no -o ConnectTimeout=15 "${ServerUser}@${VmHost}" "echo '$b64' | base64 -d > /tmp/fw.sh && sudo bash /tmp/fw.sh && rm /tmp/fw.sh" 2>&1
|
||||||
if ($fwOut -match "FIREWALL_DONE") {
|
if ($fwOut -match "FIREWALL_DONE") {
|
||||||
Write-Host " Firewall rules applied successfully!" -ForegroundColor Green
|
Write-Host " Firewall rules applied successfully!" -ForegroundColor Green
|
||||||
} else {
|
} else {
|
||||||
@@ -2052,6 +2072,10 @@ function Start-Dashboard {
|
|||||||
$Namespace = $settings.kubernetes.namespace
|
$Namespace = $settings.kubernetes.namespace
|
||||||
$DashboardPort = [int]$settings.dashboard.port
|
$DashboardPort = [int]$settings.dashboard.port
|
||||||
$DirectorPort = [int]$settings.director.port
|
$DirectorPort = [int]$settings.director.port
|
||||||
|
$RmqAdminPort = [int]($settings.rabbitmq | ForEach-Object { $_.admin_port })
|
||||||
|
if (-not $RmqAdminPort) { $RmqAdminPort = 30325 }
|
||||||
|
$RmqGamePort = [int]($settings.rabbitmq | ForEach-Object { $_.game_port })
|
||||||
|
if (-not $RmqGamePort) { $RmqGamePort = 32716 }
|
||||||
|
|
||||||
# Register sensitive values for log sanitization
|
# Register sensitive values for log sanitization
|
||||||
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
||||||
@@ -2066,7 +2090,7 @@ function Start-Dashboard {
|
|||||||
function Test-SshKeyForStart($keyPath, $targetServer) {
|
function Test-SshKeyForStart($keyPath, $targetServer) {
|
||||||
if (-not (Test-Path $keyPath)) { return $false }
|
if (-not (Test-Path $keyPath)) { return $false }
|
||||||
try {
|
try {
|
||||||
$out = ssh -i $keyPath -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
|
$out = ssh -i $keyPath -o StrictHostKeyChecking=no -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
|
||||||
return $out -eq "ok"
|
return $out -eq "ok"
|
||||||
} catch { return $false }
|
} catch { return $false }
|
||||||
}
|
}
|
||||||
@@ -2156,13 +2180,19 @@ function Start-Dashboard {
|
|||||||
Write-Log -Message "Namespace: $Namespace" -Category "k8s"
|
Write-Log -Message "Namespace: $Namespace" -Category "k8s"
|
||||||
|
|
||||||
# Kill existing SSH tunnels on the DB/Director ports
|
# Kill existing SSH tunnels on the DB/Director ports
|
||||||
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort and $DirectorPort" -Category "ssh"
|
Write-Log -Message "Cleaning up existing SSH tunnels on ports $LocalPort, $DirectorPort, $RmqAdminPort, $RmqGamePort" -Category "ssh"
|
||||||
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqAdminPort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
|
Get-NetTCPConnection -LocalPort $RmqGamePort -ErrorAction SilentlyContinue | ForEach-Object {
|
||||||
|
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
||||||
|
}
|
||||||
Start-Sleep 1
|
Start-Sleep 1
|
||||||
|
|
||||||
# [1/4] SSH Tunnel
|
# [1/4] SSH Tunnel
|
||||||
@@ -2171,11 +2201,15 @@ function Start-Dashboard {
|
|||||||
Write-Log -Message "Starting SSH tunnel to ${SSHUser}@${ServerHost}" -Category "ssh"
|
Write-Log -Message "Starting SSH tunnel to ${SSHUser}@${ServerHost}" -Category "ssh"
|
||||||
$sshArgs = @(
|
$sshArgs = @(
|
||||||
"-i", $SSHKey,
|
"-i", $SSHKey,
|
||||||
"-o", "StrictHostKeyChecking=accept-new",
|
"-o", "StrictHostKeyChecking=no",
|
||||||
|
"-o", "BatchMode=yes",
|
||||||
|
"-o", "ConnectTimeout=10",
|
||||||
"-o", "ServerAliveInterval=30",
|
"-o", "ServerAliveInterval=30",
|
||||||
"-o", "ServerAliveCountMax=3",
|
"-o", "ServerAliveCountMax=3",
|
||||||
"-L", "${LocalPort}:localhost:${LocalPort}",
|
"-L", "${LocalPort}:localhost:${LocalPort}",
|
||||||
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
||||||
|
"-L", "${RmqAdminPort}:localhost:${RmqAdminPort}",
|
||||||
|
"-L", "${RmqGamePort}:localhost:${RmqGamePort}",
|
||||||
"-N", "${SSHUser}@${ServerHost}"
|
"-N", "${SSHUser}@${ServerHost}"
|
||||||
)
|
)
|
||||||
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
||||||
@@ -2220,7 +2254,7 @@ function Start-Dashboard {
|
|||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director)" -ForegroundColor Green
|
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort (DB), localhost:$DirectorPort (Director), localhost:$RmqAdminPort (RMQ Admin), localhost:$RmqGamePort (RMQ Game)" -ForegroundColor Green
|
||||||
Write-Log -Message "SSH tunnel connected successfully" -Category "ssh"
|
Write-Log -Message "SSH tunnel connected successfully" -Category "ssh"
|
||||||
|
|
||||||
# [2/4] DB Port-Forward
|
# [2/4] DB Port-Forward
|
||||||
@@ -2245,7 +2279,7 @@ function Start-Dashboard {
|
|||||||
|
|
||||||
$DBService = "${Namespace}-db-dbdepl-svc"
|
$DBService = "${Namespace}-db-dbdepl-svc"
|
||||||
|
|
||||||
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
||||||
if ($pfCheck) {
|
if ($pfCheck) {
|
||||||
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
|
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
|
||||||
if ($dbSvc) {
|
if ($dbSvc) {
|
||||||
@@ -2257,13 +2291,13 @@ function Start-Dashboard {
|
|||||||
|
|
||||||
$RemotePort = 15432
|
$RemotePort = 15432
|
||||||
Write-Log -Message "Starting port-forward: ${LocalPort}:${RemotePort} on service $DBService" -Category "database"
|
Write-Log -Message "Starting port-forward: ${LocalPort}:${RemotePort} on service $DBService" -Category "database"
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
|
ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
|
||||||
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
|
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
|
ssh -i $SSHKey -o StrictHostKeyChecking=no -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
|
||||||
Start-Sleep -Seconds 2
|
Start-Sleep -Seconds 2
|
||||||
|
|
||||||
$bgdSvc = "${Namespace}-bgd-svc"
|
$bgdSvc = "${Namespace}-bgd-svc"
|
||||||
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
||||||
if ($pfCheckBgd) {
|
if ($pfCheckBgd) {
|
||||||
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
|
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
|
||||||
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
|
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
|
||||||
@@ -2272,11 +2306,11 @@ function Start-Dashboard {
|
|||||||
# Check if BGD deployment is running, scale up if needed
|
# Check if BGD deployment is running, scale up if needed
|
||||||
$bgdDeploy = "${Namespace}-bgd-deploy"
|
$bgdDeploy = "${Namespace}-bgd-deploy"
|
||||||
Write-Log -Message "Checking BGD deployment status: $bgdDeploy" -Category "k8s"
|
Write-Log -Message "Checking BGD deployment status: $bgdDeploy" -Category "k8s"
|
||||||
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
|
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
|
||||||
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
|
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
|
||||||
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
|
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
|
||||||
Write-Log -Message "BGD deployment scaled down, scaling to 1 replica" -Category "k8s"
|
Write-Log -Message "BGD deployment scaled down, scaling to 1 replica" -Category "k8s"
|
||||||
$scaleOut = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
|
$scaleOut = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
|
||||||
Write-Host " Waiting for BGD pod to be ready..." -ForegroundColor Yellow
|
Write-Host " Waiting for BGD pod to be ready..." -ForegroundColor Yellow
|
||||||
Start-Sleep -Seconds 15
|
Start-Sleep -Seconds 15
|
||||||
}
|
}
|
||||||
@@ -2284,7 +2318,7 @@ function Start-Dashboard {
|
|||||||
$directorRemotePort = 11717
|
$directorRemotePort = 11717
|
||||||
Write-Log -Message "Starting director port-forward: ${DirectorPort}:${directorRemotePort} on service $bgdSvc" -Category "k8s"
|
Write-Log -Message "Starting director port-forward: ${DirectorPort}:${directorRemotePort} on service $bgdSvc" -Category "k8s"
|
||||||
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
|
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
|
ssh -i $SSHKey -o StrictHostKeyChecking=no -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
|
||||||
|
|
||||||
Start-Sleep -Seconds 3
|
Start-Sleep -Seconds 3
|
||||||
|
|
||||||
@@ -2306,7 +2340,7 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " Troubleshooting:" -ForegroundColor Cyan
|
Write-Host " Troubleshooting:" -ForegroundColor Cyan
|
||||||
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
|
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
|
||||||
$pfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/pf.log" 2>$null
|
$pfLog = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/pf.log" 2>$null
|
||||||
if ($pfLog) { Write-Host " $pfLog" -ForegroundColor Red }
|
if ($pfLog) { Write-Host " $pfLog" -ForegroundColor Red }
|
||||||
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
|
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
@@ -2342,7 +2376,7 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " Troubleshooting:" -ForegroundColor Cyan
|
Write-Host " Troubleshooting:" -ForegroundColor Cyan
|
||||||
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
|
Write-Host " 1. Check the port-forward log on the VM:" -ForegroundColor White
|
||||||
$directorPfLog = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/director_pf.log" 2>$null
|
$directorPfLog = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "cat /tmp/director_pf.log" 2>$null
|
||||||
if ($directorPfLog) { Write-Host " $directorPfLog" -ForegroundColor Red }
|
if ($directorPfLog) { Write-Host " $directorPfLog" -ForegroundColor Red }
|
||||||
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
|
else { Write-Host " Log empty or unreadable." -ForegroundColor Yellow }
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
@@ -2432,7 +2466,7 @@ function Start-Dashboard {
|
|||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
Write-Host "Stopping tunnels..." -ForegroundColor Cyan
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
||||||
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k 15433/tcp 32479/tcp 2>/dev/null"'
|
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=no ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k 15433/tcp 32479/tcp 30325/tcp 32716/tcp 2>/dev/null"'
|
||||||
cmd /c $pkillCmd 2>$null
|
cmd /c $pkillCmd 2>$null
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2526,350 +2560,296 @@ print('ok')
|
|||||||
Start-Dashboard -PreserveDebug
|
Start-Dashboard -PreserveDebug
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── New Dashboard (React + ChakraUI) ─────────────────────────────────────
|
|
||||||
|
|
||||||
function Start-NewDashboard {
|
|
||||||
param(
|
|
||||||
[switch]$PreserveDebug
|
|
||||||
)
|
|
||||||
|
|
||||||
|
function Repair-GameDatabase {
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host " Starting NEW dashboard (React + ChakraUI)..." -ForegroundColor Yellow
|
Write-Host " Game Database Repair" -ForegroundColor Cyan
|
||||||
|
Write-Host " =====================" -ForegroundColor Cyan
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|
||||||
# Check Node.js
|
|
||||||
$nodeVersion = $null
|
|
||||||
try {
|
|
||||||
$nodeVersion = node --version 2>&1
|
|
||||||
Write-Host " Node.js: $nodeVersion" -ForegroundColor Green
|
|
||||||
} catch {
|
|
||||||
Write-Host " Node.js: NOT FOUND" -ForegroundColor Red
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Node.js 18+ is required for the new frontend." -ForegroundColor Yellow
|
|
||||||
Write-Host " Download from https://nodejs.org/" -ForegroundColor Cyan
|
|
||||||
Write-Host ""
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Reuse tunnel/setup logic from Start-Dashboard ──────────────────────
|
|
||||||
# Check Python
|
|
||||||
if (-not (Test-Python)) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
# Check dependencies
|
|
||||||
Test-Dependencies | Out-Null
|
|
||||||
|
|
||||||
# Check settings
|
|
||||||
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
|
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
|
||||||
if (-not (Test-Path $settingsFile)) {
|
if (-not (Test-Path $settingsFile)) {
|
||||||
Write-Host ""
|
Write-Host "[ERROR] settings.yaml not found. Run setup first (option 2)." -ForegroundColor Red
|
||||||
Write-Host " [ERROR] settings.yaml not found. You need to run setup first." -ForegroundColor Red
|
|
||||||
Write-Host ""
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
# Read settings
|
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
|
||||||
$settingsJson = python -c "import yaml, json, sys, os; path = sys.argv[1]; d = yaml.safe_load(open(path, encoding='utf-8-sig')) or {} if os.path.exists(path) else {}; print(json.dumps(d))" $settingsFile 2>$null
|
|
||||||
if (-not $settingsJson) {
|
if (-not $settingsJson) {
|
||||||
Write-Host " [ERROR] Failed to read settings.yaml" -ForegroundColor Red
|
Write-Host "[ERROR] Could not read settings.yaml." -ForegroundColor Red
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
$settings = $settingsJson | ConvertFrom-Json
|
$settings = $settingsJson | ConvertFrom-Json
|
||||||
|
|
||||||
$ServerHost = $settings.server.host
|
$ServerHost = $settings.server.host
|
||||||
$SSHUser = $settings.server.user
|
$SSHUser = $settings.server.user
|
||||||
$LocalPort = [int]$settings.database.port
|
|
||||||
$Namespace = $settings.kubernetes.namespace
|
$Namespace = $settings.kubernetes.namespace
|
||||||
$DashboardPort = [int]$settings.dashboard.port
|
|
||||||
$DirectorPort = [int]$settings.director.port
|
|
||||||
|
|
||||||
Register-SensitiveValue -Key "ServerIP" -Value $ServerHost
|
$SSHKey = $null
|
||||||
Register-SensitiveValue -Key "Namespace" -Value $Namespace
|
if ($settings.server.ssh_key -and $settings.server.ssh_key -ne 'null') {
|
||||||
Register-SensitiveValue -Key "DBPassword" -Value $settings.database.password
|
$SSHKey = $settings.server.ssh_key
|
||||||
Register-SensitiveValue -Key "DBUser" -Value $settings.database.user
|
}
|
||||||
Register-SensitiveValue -Key "DashboardSecret" -Value $settings.dashboard.secret_key
|
if (-not $SSHKey) {
|
||||||
Register-SensitiveValue -Key "DirectorToken" -Value $settings.director.token
|
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
|
||||||
Register-SensitiveValue -Key "AuthSecret" -Value $settings.auth.secret_key
|
|
||||||
|
|
||||||
# Find SSH key (same logic as Start-Dashboard)
|
|
||||||
function Test-SshKeyForNew($keyPath, $targetServer) {
|
|
||||||
if (-not (Test-Path $keyPath)) { return $false }
|
|
||||||
try {
|
|
||||||
$out = ssh -i $keyPath -o StrictHostKeyChecking=accept-new -o ConnectTimeout=5 -o BatchMode=yes $targetServer "echo ok" 2>$null
|
|
||||||
return $out -eq "ok"
|
|
||||||
} catch { return $false }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
$SSHKeySrc = $settings.server.ssh_key
|
if (-not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP') {
|
||||||
$LocalKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
|
Write-Host "[ERROR] Server IP not configured in settings.yaml." -ForegroundColor Red
|
||||||
|
return
|
||||||
if ($SSHKeySrc -and $SSHKeySrc -ne 'null' -and -not [string]::IsNullOrEmpty($SSHKeySrc)) {
|
|
||||||
if (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost)) {
|
|
||||||
Register-SensitiveValue -Key "SSHKeyPath" -Value $SSHKeySrc
|
|
||||||
Write-Host " SSH Key: Using key from settings.yaml" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
$SSHKeySrc = $null
|
|
||||||
}
|
}
|
||||||
|
if (-not $Namespace) {
|
||||||
|
Write-Host "[ERROR] Kubernetes namespace not configured." -ForegroundColor Red
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
if (-not (Test-Path $SSHKey)) {
|
||||||
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc) -or -not (Test-SshKeyForNew $SSHKeySrc ($SSHUser + '@' + $ServerHost))) {
|
Write-Host "[ERROR] SSH key not found at: $SSHKey" -ForegroundColor Red
|
||||||
$keyPaths = @(
|
|
||||||
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
|
|
||||||
$LocalKey,
|
|
||||||
"$env:USERPROFILE\.ssh\id_ed25519",
|
|
||||||
"$env:USERPROFILE\.ssh\id_rsa"
|
|
||||||
)
|
|
||||||
foreach ($kp in $keyPaths) {
|
|
||||||
if ($kp -ne $SSHKeySrc -and (Test-Path $kp)) {
|
|
||||||
if (Test-SshKeyForNew $kp ($SSHUser + '@' + $ServerHost)) {
|
|
||||||
$SSHKeySrc = $kp
|
|
||||||
Register-SensitiveValue -Key "SSHKeyPath" -Value $kp
|
|
||||||
Write-Host " SSH Key: Found working key at $kp" -ForegroundColor Green
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $SSHKeySrc -or -not (Test-Path $SSHKeySrc)) {
|
|
||||||
Write-Host " [ERROR] No working SSH key found." -ForegroundColor Red
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
# Copy key to temp
|
Write-Host " Server: $ServerHost" -ForegroundColor White
|
||||||
$SSHKey = "$env:TEMP\dune-tunnel-key"
|
Write-Host " Namespace: $Namespace" -ForegroundColor White
|
||||||
$ResolvedSrc = [System.IO.Path]::GetFullPath($SSHKeySrc)
|
Write-Host ""
|
||||||
$ResolvedDest = [System.IO.Path]::GetFullPath($SSHKey)
|
|
||||||
if ($ResolvedSrc -ne $ResolvedDest) {
|
$confirm = Read-Host " This will transfer dashboard schema ownership to the dune user. Continue? (y/N)"
|
||||||
Copy-Item $SSHKeySrc $SSHKey -Force
|
if ($confirm -ne 'y' -and $confirm -ne 'Y') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
# 1. Find the database pod
|
||||||
|
Write-Host "[1/4] Finding database pod..." -ForegroundColor Yellow
|
||||||
|
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
|
||||||
|
if (-not $dbPod) {
|
||||||
|
Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
Write-Host " [OK] Database pod: $dbPod" -ForegroundColor Green
|
||||||
|
|
||||||
|
# 2. Run the ownership fix SQL
|
||||||
|
Write-Host "[2/4] Running ownership fix..." -ForegroundColor Yellow
|
||||||
|
|
||||||
|
# Build a temp .ps1 script where each line uses --% with values directly embedded.
|
||||||
|
# After --%, PowerShell passes everything literally to ssh.exe — no parsing issues.
|
||||||
|
$tmpFile = Join-Path $env:TEMP "dune_repair_$([System.IO.Path]::GetRandomFileName()).ps1"
|
||||||
|
$sshBase = "ssh --% -o StrictHostKeyChecking=no -o ConnectTimeout=10 -i `"$SSHKey`" `"$SSHUser@$ServerHost`""
|
||||||
|
|
||||||
|
$scriptLines = @(
|
||||||
|
"$sshBase `"printf 'ALTER SCHEMA dashboard OWNER TO dune;\n' > /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT tablename FROM pg_tables WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER TABLE dashboard.\x27 || quote_ident(r.tablename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'DO \x24\x24DECLARE r RECORD; BEGIN FOR r IN SELECT sequencename FROM pg_sequences WHERE schemaname = \x27dashboard\x27 LOOP EXECUTE \x27ALTER SEQUENCE dashboard.\x27 || quote_ident(r.sequencename) || \x27 OWNER TO dune\x27; END LOOP; END\x24\x24;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON TABLES TO dune;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"printf 'ALTER DEFAULT PRIVILEGES IN SCHEMA dashboard GRANT ALL ON SEQUENCES TO dune;\n' >> /tmp/repair.sql`""
|
||||||
|
"$sshBase `"cat /tmp/repair.sql | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune`""
|
||||||
|
"$sshBase `"printf 'CREATE SCHEMA IF NOT EXISTS dashboard;\nGRANT ALL PRIVILEGES ON SCHEMA dashboard TO dune;\n' | sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d template1`""
|
||||||
|
)
|
||||||
|
|
||||||
|
$scriptLines | Out-File -FilePath $tmpFile -Encoding ASCII
|
||||||
|
|
||||||
|
$sqlResult = powershell -NoProfile -File $tmpFile 2>&1
|
||||||
|
Remove-Item $tmpFile -Force -ErrorAction SilentlyContinue
|
||||||
|
Write-Host " $sqlResult" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Ownership fix applied" -ForegroundColor Green
|
||||||
|
|
||||||
|
# 3. Delete failed util pods
|
||||||
|
Write-Host "[3/4] Cleaning up failed utility pods..." -ForegroundColor Yellow
|
||||||
|
$deleted = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace | grep 'db.*util' | grep -v Running | awk '{print \$1}' | xargs -r sudo kubectl delete pod -n $Namespace --wait=false" 2>$null
|
||||||
|
if ($deleted) {
|
||||||
|
Write-Host " $deleted" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Failed util pods deleted" -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Write-Host " [OK] No failed util pods found" -ForegroundColor Green
|
||||||
|
}
|
||||||
|
|
||||||
|
# 4. Instructions
|
||||||
|
Write-Host "[4/4] Done!" -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host "============================================================" -ForegroundColor Cyan
|
||||||
|
Write-Host " Repair Complete!" -ForegroundColor Green
|
||||||
|
Write-Host "============================================================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " If game servers still show errors, restart the battlegroup:" -ForegroundColor White
|
||||||
|
Write-Host " 1. In the battlegroup management UI, select option 5" -ForegroundColor White
|
||||||
|
Write-Host " (Restart battlegroup)" -ForegroundColor DarkGray
|
||||||
|
Write-Host " 2. Wait for all pods to come back healthy" -ForegroundColor White
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " The dashboard will auto-fix ownership on every startup," -ForegroundColor Green
|
||||||
|
Write-Host " so this should not happen again." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return to the menu..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
}
|
||||||
|
|
||||||
|
function Cleanup-OldDashboardSchema {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Clean Up Old Dashboard Schema" -ForegroundColor Cyan
|
||||||
|
Write-Host " ===============================" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$settingsFile = Join-Path $ProjectRoot "settings.yaml"
|
||||||
|
if ( -not (Test-Path $settingsFile) ) {
|
||||||
|
Write-Host "[ERROR] settings.yaml not found." -ForegroundColor Red
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$settingsJson = python -c "import yaml, json, sys; d = yaml.safe_load(open(sys.argv[1], encoding='utf-8-sig')) or {}; print(json.dumps(d))" $settingsFile 2>$null
|
||||||
|
if ( -not $settingsJson ) { Write-Host "[ERROR] Could not read settings." -ForegroundColor Red; return }
|
||||||
|
$settings = $settingsJson | ConvertFrom-Json
|
||||||
|
$ServerHost = $settings.server.host
|
||||||
|
$SSHUser = $settings.server.user
|
||||||
|
$Namespace = $settings.kubernetes.namespace
|
||||||
|
$SSHKey = $settings.server.ssh_key
|
||||||
|
if ( -not $SSHKey -or $SSHKey -eq 'null' ) {
|
||||||
|
$SSHKey = "$env:LOCALAPPDATA\DuneAwakeningServer\sshKey"
|
||||||
|
}
|
||||||
|
|
||||||
|
if ( -not $ServerHost -or $ServerHost -eq 'YOUR_SERVER_IP' ) { Write-Host "[ERROR] Server IP not configured." -ForegroundColor Red; return }
|
||||||
|
if ( -not $Namespace ) { Write-Host "[ERROR] Namespace not configured." -ForegroundColor Red; return }
|
||||||
|
if ( -not (Test-Path $SSHKey) ) { Write-Host "[ERROR] SSH key not found." -ForegroundColor Red; return }
|
||||||
|
|
||||||
|
$dbPod = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl get pods -n $Namespace -l app=${Namespace}-db-dbdepl-sts -o jsonpath='{.items[0].metadata.name}'" 2>$null
|
||||||
|
if ( -not $dbPod ) { Write-Host "[ERROR] Could not find database pod." -ForegroundColor Red; return }
|
||||||
|
|
||||||
|
$hasOldSchema = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -t -c ""SELECT count(*) FROM information_schema.schemata WHERE schema_name = 'dashboard'"" 2>&1" 2>$null
|
||||||
|
$hasOldSchema = $hasOldSchema.Trim()
|
||||||
|
|
||||||
|
if ( $hasOldSchema -eq '0' ) {
|
||||||
|
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if ( -not $hasOldSchema ) {
|
||||||
|
Write-Host " [OK] No old dashboard schema found - nothing to clean up." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host " [WARN] Old dashboard schema found in the game database." -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " This drops: dashboard.audit_log, dashboard.bans, dashboard.player_ips," -ForegroundColor White
|
||||||
|
Write-Host " dashboard.player_actions, dashboard.chat_history, dashboard.settings" -ForegroundColor White
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Make sure the dashboard has migrated this data to the new database first." -ForegroundColor Yellow
|
||||||
|
Write-Host " (The dashboard does this automatically on next startup.)" -ForegroundColor DarkGray
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$confirm = Read-Host " Type 'yes' to drop the old dashboard schema"
|
||||||
|
if ($confirm -ne 'yes') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$confirm2 = Read-Host " REALLY drop? This cannot be undone. Type 'yes' again"
|
||||||
|
if ($confirm2 -ne 'yes') {
|
||||||
|
Write-Host " Cancelled." -ForegroundColor Yellow
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Dropping old dashboard schema..." -ForegroundColor Yellow
|
||||||
|
$result = ssh -i $SSHKey -o StrictHostKeyChecking=no -o ConnectTimeout=10 "$SSHUser@$ServerHost" "sudo kubectl exec -n $Namespace -i $dbPod -- psql -U postgres -p 15432 -d dune -c ""DROP SCHEMA IF EXISTS dashboard CASCADE"" 2>&1"
|
||||||
|
Write-Host " $result" -ForegroundColor DarkGray
|
||||||
|
Write-Host " [OK] Old dashboard schema dropped." -ForegroundColor Green
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
}
|
||||||
|
|
||||||
|
function Rotate-SSHKey {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Rotate SSH Key" -ForegroundColor Cyan
|
||||||
|
Write-Host " ===============" -ForegroundColor Cyan
|
||||||
|
Write-Host ""
|
||||||
|
|
||||||
|
$TargetKey = Join-Path $ProjectRoot "internal-scripts\ssh\sshKey"
|
||||||
|
$ParentKey = Join-Path (Split-Path $ProjectRoot) "internal-scripts\ssh\sshKey"
|
||||||
|
$UserHome = $env:USERPROFILE
|
||||||
|
$TempDir = $env:TEMP
|
||||||
|
|
||||||
|
$searchPaths = @(
|
||||||
|
"$UserHome\.ssh\dune-dashboard-key",
|
||||||
|
"$TempDir\dune-tunnel-key",
|
||||||
|
"$TempDir\dune-awakening-server-sshKey",
|
||||||
|
$ParentKey,
|
||||||
|
"$env:LOCALAPPDATA\DuneAwakeningServer\sshKey",
|
||||||
|
"$UserHome\.ssh\id_ed25519",
|
||||||
|
"$UserHome\.ssh\id_rsa",
|
||||||
|
"$UserHome\.ssh\id_ecdsa"
|
||||||
|
)
|
||||||
|
|
||||||
|
$foundKeys = @()
|
||||||
|
Write-Host " Scanning for SSH keys..." -ForegroundColor Yellow
|
||||||
|
|
||||||
|
if (Test-Path $TargetKey) {
|
||||||
|
$targetInfo = Get-Item $TargetKey
|
||||||
|
Write-Host " Current: $TargetKey (modified $($targetInfo.LastWriteTime))" -ForegroundColor DarkGray
|
||||||
|
}
|
||||||
|
|
||||||
|
foreach ($path in $searchPaths) {
|
||||||
|
if (Test-Path $path) {
|
||||||
|
$info = Get-Item $path
|
||||||
|
$foundKeys += [PSCustomObject]@{
|
||||||
|
Path = $path
|
||||||
|
LastWriteTime = $info.LastWriteTime
|
||||||
|
Length = $info.Length
|
||||||
|
}
|
||||||
|
Write-Host " Found: $path (modified $($info.LastWriteTime))" -ForegroundColor DarkGray
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($foundKeys.Count -eq 0) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " No SSH keys found in any search location." -ForegroundColor Yellow
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
|
Read-Host
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
$newestKey = $foundKeys | Sort-Object LastWriteTime -Descending | Select-Object -First 1
|
||||||
|
|
||||||
|
$targetDir = Join-Path $ProjectRoot "internal-scripts\ssh"
|
||||||
|
if (-not (Test-Path $targetDir)) {
|
||||||
|
New-Item -ItemType Directory -Path $targetDir -Force | Out-Null
|
||||||
|
}
|
||||||
|
|
||||||
|
if ($newestKey.Path -eq $TargetKey) {
|
||||||
|
Write-Host ""
|
||||||
|
Write-Host " The newest key is already at the target location." -ForegroundColor Green
|
||||||
|
Write-Host " No rotation needed." -ForegroundColor Green
|
||||||
|
} else {
|
||||||
|
Copy-Item $newestKey.Path $TargetKey -Force
|
||||||
|
|
||||||
try {
|
try {
|
||||||
$acl = Get-Acl $SSHKey -ErrorAction SilentlyContinue
|
$acl = Get-Acl $TargetKey -ErrorAction SilentlyContinue
|
||||||
if ($acl) {
|
if ($acl) {
|
||||||
$acl.SetAccessRuleProtection($true, $false)
|
$acl.SetAccessRuleProtection($true, $false)
|
||||||
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
|
$rule = New-Object System.Security.AccessControl.FileSystemAccessRule("$env:USERNAME", "FullControl", "Allow")
|
||||||
$acl.SetAccessRule($rule)
|
$acl.SetAccessRule($rule)
|
||||||
Set-Acl -Path $SSHKey -AclObject $acl -ErrorAction SilentlyContinue
|
$adminSid = [System.Security.Principal.SecurityIdentifier]::new("S-1-5-32-544")
|
||||||
|
$adminRule = New-Object System.Security.AccessControl.FileSystemAccessRule($adminSid, "FullControl", "Allow")
|
||||||
|
$acl.SetAccessRule($adminRule)
|
||||||
|
Set-Acl -Path $TargetKey -AclObject $acl -ErrorAction SilentlyContinue
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "============================================================" -ForegroundColor Cyan
|
Write-Host " Rotated: $($newestKey.Path)" -ForegroundColor Green
|
||||||
Write-Host " Dune Awakening Dashboard (React Edition)" -ForegroundColor Cyan
|
Write-Host " -> $TargetKey" -ForegroundColor Green
|
||||||
Write-Host "============================================================" -ForegroundColor Cyan
|
Write-Host " (modified $($newestKey.LastWriteTime))" -ForegroundColor DarkGray
|
||||||
Write-Host ""
|
|
||||||
|
|
||||||
# ── SSH Tunnel ────────────────────────────────────────────────────────
|
|
||||||
Write-Host "[1/5] Starting SSH tunnel (localhost:$LocalPort -> VM)..." -ForegroundColor Yellow
|
|
||||||
|
|
||||||
Get-NetTCPConnection -LocalPort $LocalPort -ErrorAction SilentlyContinue | ForEach-Object {
|
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
Get-NetTCPConnection -LocalPort $DirectorPort -ErrorAction SilentlyContinue | ForEach-Object {
|
|
||||||
Get-Process -Id $_.OwningProcess -ErrorAction SilentlyContinue | Where-Object { $_.ProcessName -eq 'ssh' } | Stop-Process -Force -ErrorAction SilentlyContinue
|
|
||||||
}
|
|
||||||
Start-Sleep 1
|
|
||||||
|
|
||||||
$sshArgs = @(
|
|
||||||
"-i", $SSHKey,
|
|
||||||
"-o", "StrictHostKeyChecking=accept-new",
|
|
||||||
"-o", "ServerAliveInterval=30",
|
|
||||||
"-o", "ServerAliveCountMax=3",
|
|
||||||
"-L", "${LocalPort}:localhost:${LocalPort}",
|
|
||||||
"-L", "${DirectorPort}:localhost:${DirectorPort}",
|
|
||||||
"-N", "${SSHUser}@${ServerHost}"
|
|
||||||
)
|
|
||||||
$sshTunnel = Start-Process ssh -ArgumentList $sshArgs -PassThru -WindowStyle Hidden
|
|
||||||
|
|
||||||
$connected = $false
|
|
||||||
for ($i = 0; $i -lt 30; $i++) {
|
|
||||||
Start-Sleep -Seconds 1
|
|
||||||
if ($sshTunnel.HasExited) {
|
|
||||||
Write-Host "[ERROR] SSH tunnel exited (code: $($sshTunnel.ExitCode))" -ForegroundColor Red
|
|
||||||
Write-Host " Check server IP and SSH key configuration." -ForegroundColor Yellow
|
|
||||||
return
|
|
||||||
}
|
|
||||||
try {
|
|
||||||
$tcp = New-Object System.Net.Sockets.TcpClient
|
|
||||||
$tcp.Connect("127.0.0.1", $LocalPort)
|
|
||||||
$tcp.Close()
|
|
||||||
$connected = $true
|
|
||||||
break
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
if (-not $connected) {
|
|
||||||
Write-Host "[ERROR] SSH tunnel did not connect within 30 seconds" -ForegroundColor Red
|
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Write-Host "[OK] SSH tunnel up on localhost:$LocalPort" -ForegroundColor Green
|
|
||||||
|
|
||||||
# ── DB Port-Forward ───────────────────────────────────────────────────
|
|
||||||
Write-Host "[2/5] Starting DB port-forward on VM..." -ForegroundColor Yellow
|
|
||||||
|
|
||||||
if (-not $Namespace -or $Namespace -eq '') {
|
|
||||||
Write-Host "[ERROR] Kubernetes namespace is empty." -ForegroundColor Red
|
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
$DBService = "${Namespace}-db-dbdepl-svc"
|
|
||||||
$pfCheck = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
|
||||||
if ($pfCheck) {
|
|
||||||
$dbSvc = ($pfCheck -split "`n") | Where-Object { $_ -match 'db.*svc' -or $_ -match 'postgres' -or $_ -match 'pg' } | Select-Object -First 1
|
|
||||||
if ($dbSvc) { $DBService = $dbSvc -replace 'service/', '' }
|
|
||||||
}
|
|
||||||
|
|
||||||
$RemotePort = 15432
|
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo fuser -k ${LocalPort}/tcp ${DirectorPort}/tcp 2>/dev/null; sleep 1" 2>$null
|
|
||||||
$pfCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$DBService $LocalPort`:$RemotePort > /tmp/pf.log 2>`&1 `"&`""
|
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $pfCmd 2>$null
|
|
||||||
Start-Sleep -Seconds 2
|
|
||||||
|
|
||||||
# BGD Director port-forward
|
|
||||||
$bgdSvc = "${Namespace}-bgd-svc"
|
|
||||||
$pfCheckBgd = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get svc -n ${Namespace} -o name" 2>$null
|
|
||||||
if ($pfCheckBgd) {
|
|
||||||
$bgdMatch = ($pfCheckBgd -split "`n") | Where-Object { $_ -match 'bgd.*svc' } | Select-Object -First 1
|
|
||||||
if ($bgdMatch) { $bgdSvc = $bgdMatch -replace 'service/', '' }
|
|
||||||
}
|
|
||||||
|
|
||||||
# Check BGD deployment
|
|
||||||
$bgdDeploy = "${Namespace}-bgd-deploy"
|
|
||||||
$bgdReady = ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=10 ${SSHUser}@${ServerHost} "sudo kubectl get deployment $bgdDeploy -n $Namespace -o jsonpath='{.status.readyReplicas}'" 2>$null
|
|
||||||
if (-not $bgdReady -or $bgdReady -eq '0' -or $bgdReady -eq '') {
|
|
||||||
Write-Host " BGD deployment is scaled down, starting..." -ForegroundColor Yellow
|
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ConnectTimeout=30 ${SSHUser}@${ServerHost} "sudo kubectl scale deployment $bgdDeploy -n $Namespace --replicas=1" 2>$null
|
|
||||||
Start-Sleep -Seconds 15
|
|
||||||
}
|
|
||||||
|
|
||||||
$directorRemotePort = 11717
|
|
||||||
$directorCmd = "nohup sudo kubectl port-forward -n $Namespace svc/$bgdSvc $DirectorPort`:$directorRemotePort > /tmp/director_pf.log 2>`&1 `"&`""
|
|
||||||
ssh -i $SSHKey -o StrictHostKeyChecking=accept-new -o ServerAliveInterval=30 "${SSHUser}@${ServerHost}" $directorCmd 2>$null
|
|
||||||
Start-Sleep -Seconds 3
|
|
||||||
|
|
||||||
# ── DB Check ──────────────────────────────────────────────────────────
|
|
||||||
Write-Host "[3/5] Checking database..." -ForegroundColor Yellow
|
|
||||||
$dbTest = $false
|
|
||||||
$dbScript = Join-Path $ProjectRoot "scripts\db_check.py"
|
|
||||||
for ($i = 0; $i -lt 15; $i++) {
|
|
||||||
try {
|
|
||||||
$result = python $dbScript $LocalPort 2>$null
|
|
||||||
if ($result -match 'ok') { $dbTest = $true; break }
|
|
||||||
} catch {}
|
|
||||||
Start-Sleep -Seconds 1
|
|
||||||
}
|
|
||||||
if (-not $dbTest) {
|
|
||||||
Write-Host "[ERROR] Database connection failed." -ForegroundColor Red
|
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Write-Host "[OK] Database connected" -ForegroundColor Green
|
|
||||||
|
|
||||||
# ── Install Dependencies ──────────────────────────────────────────────
|
|
||||||
Write-Host "[4/5] Installing dependencies..." -ForegroundColor Yellow
|
|
||||||
|
|
||||||
# Backend Python deps (project root requirements.txt)
|
|
||||||
if (Test-Path (Join-Path $ProjectRoot "requirements.txt")) {
|
|
||||||
Write-Host " Checking backend Python dependencies..." -ForegroundColor DarkGray
|
|
||||||
$pipArgs = @("pip", "install", "-r", (Join-Path $ProjectRoot "requirements.txt"), "--quiet")
|
|
||||||
& python @pipArgs 2>$null
|
|
||||||
$pipArgs2 = @("pip", "install", "psycopg[binary]", "--quiet")
|
|
||||||
& python @pipArgs2 2>$null
|
|
||||||
Write-Host " Backend dependencies OK" -ForegroundColor Green
|
|
||||||
}
|
|
||||||
|
|
||||||
# Frontend npm deps
|
|
||||||
$frontendDir = Join-Path $ProjectRoot "frontend"
|
|
||||||
if (Test-Path (Join-Path $frontendDir "package.json")) {
|
|
||||||
$nodeModulesDir = Join-Path $frontendDir "node_modules"
|
|
||||||
if (-not (Test-Path $nodeModulesDir)) {
|
|
||||||
Write-Host " Installing frontend npm dependencies..." -ForegroundColor DarkGray
|
|
||||||
$prevLoc = Get-Location
|
|
||||||
Set-Location -LiteralPath $frontendDir
|
|
||||||
npm install 2>&1 | Out-Null
|
|
||||||
Set-Location -LiteralPath $prevLoc
|
|
||||||
Write-Host " Frontend dependencies installed" -ForegroundColor Green
|
|
||||||
} else {
|
|
||||||
Write-Host " Frontend dependencies OK" -ForegroundColor Green
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
# ── Start Backend + Frontend ──────────────────────────────────────────
|
|
||||||
Write-Host "[5/5] Starting dashboard..." -ForegroundColor Yellow
|
|
||||||
Write-Host ""
|
|
||||||
|
|
||||||
# Start the new Flask API backend
|
|
||||||
Write-Host " Starting backend API (port $DashboardPort)..." -ForegroundColor Cyan
|
|
||||||
$backendDir = Join-Path $ProjectRoot "backend"
|
|
||||||
$backendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$backendDir`" && python run.py" -PassThru
|
|
||||||
|
|
||||||
# Wait for backend to be ready
|
|
||||||
Write-Host " Waiting for backend to start..." -ForegroundColor DarkGray
|
|
||||||
$backendAlive = $false
|
|
||||||
for ($i = 0; $i -lt 30; $i++) {
|
|
||||||
Start-Sleep -Seconds 1
|
|
||||||
try {
|
|
||||||
$wc = New-Object System.Net.WebClient
|
|
||||||
$result = $wc.DownloadString("http://127.0.0.1:${DashboardPort}/api/stats")
|
|
||||||
if ($result) { $backendAlive = $true; break }
|
|
||||||
} catch {}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (-not $backendAlive) {
|
|
||||||
Write-Host "[ERROR] Backend failed to start within 30 seconds." -ForegroundColor Red
|
|
||||||
Write-Host " Check the backend window for errors." -ForegroundColor Yellow
|
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
return
|
|
||||||
}
|
|
||||||
Write-Host " [OK] Backend API running on port $DashboardPort" -ForegroundColor Green
|
|
||||||
|
|
||||||
# Start frontend in a visible window
|
|
||||||
Write-Host " Starting frontend dev server (port 5173)..." -ForegroundColor Cyan
|
|
||||||
$viteDir = Join-Path $ProjectRoot "frontend"
|
|
||||||
$frontendProcess = Start-Process cmd.exe -ArgumentList "/k", "cd /d `"$viteDir`" && npm run dev -- --host 0.0.0.0" -PassThru
|
|
||||||
|
|
||||||
Start-Sleep -Seconds 6
|
|
||||||
|
|
||||||
# Check if frontend is running by probing the port
|
|
||||||
$frontendAlive = $false
|
|
||||||
try {
|
|
||||||
$wc = New-Object System.Net.WebClient
|
|
||||||
$wc.DownloadString("http://127.0.0.1:5173/") | Out-Null
|
|
||||||
$frontendAlive = $true
|
|
||||||
} catch {}
|
|
||||||
|
|
||||||
if (-not $frontendAlive) {
|
|
||||||
Write-Host "[WARN] Frontend may not have started yet. Check the frontend window." -ForegroundColor Yellow
|
|
||||||
} else {
|
|
||||||
Write-Host " [OK] Frontend running on port 5173" -ForegroundColor Green
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
Write-Host "============================================================" -ForegroundColor Cyan
|
Write-Host " Press Enter to return..." -ForegroundColor DarkGray
|
||||||
Write-Host " New Dashboard Started!" -ForegroundColor Green
|
Read-Host
|
||||||
Write-Host "============================================================" -ForegroundColor Cyan
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Frontend: http://localhost:5173" -ForegroundColor Cyan
|
|
||||||
Write-Host " Backend: http://localhost:${DashboardPort}" -ForegroundColor DarkGray
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Open http://localhost:5173 in your browser" -ForegroundColor Yellow
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Close the backend and frontend windows to stop, or" -ForegroundColor DarkGray
|
|
||||||
Write-Host " press Enter here to kill the SSH tunnel and all processes." -ForegroundColor DarkGray
|
|
||||||
Write-Host ""
|
|
||||||
Read-Host " Press Enter to stop"
|
|
||||||
|
|
||||||
Write-Host ""
|
|
||||||
Write-Host " Stopping services..." -ForegroundColor Cyan
|
|
||||||
Stop-Process -Id $frontendProcess.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
Stop-Process -Id $backendProcess.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
Stop-Process -Id $sshTunnel.Id -Force -ErrorAction SilentlyContinue
|
|
||||||
$pkillCmd = 'ssh -i "' + $SSHKey + '" -o StrictHostKeyChecking=accept-new ' + $SSHUser + '@' + $ServerHost + ' "sudo fuser -k ' + $LocalPort + '/tcp ' + $DirectorPort + '/tcp 2>/dev/null"'
|
|
||||||
cmd /c $pkillCmd 2>$null
|
|
||||||
Write-Host " All services stopped." -ForegroundColor Green
|
|
||||||
Write-Host ""
|
|
||||||
}
|
}
|
||||||
|
|
||||||
# ── Main Loop ───────────────────────────────────────────────────────────
|
# ── Main Loop ───────────────────────────────────────────────────────────
|
||||||
@@ -2887,11 +2867,13 @@ while ($true) {
|
|||||||
"4" { Install-CaCert; break }
|
"4" { Install-CaCert; break }
|
||||||
"5" { Clean-CaCerts; break }
|
"5" { Clean-CaCerts; break }
|
||||||
"6" { Start-DashboardDebug; break }
|
"6" { Start-DashboardDebug; break }
|
||||||
"7" { Start-NewDashboard; break }
|
"7" { Reset-ToFactoryDefaults; break }
|
||||||
"8" { Reset-ToFactoryDefaults; break }
|
"8" { Repair-GameDatabase; break }
|
||||||
|
"9" { Cleanup-OldDashboardSchema; break }
|
||||||
|
"10" { Rotate-SSHKey; break }
|
||||||
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
"Q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
||||||
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
"q" { Write-Host ""; Write-Host " Goodbye!"; Write-Host ""; exit 0 }
|
||||||
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-8, or Q." -ForegroundColor Yellow; Write-Host "" }
|
default { Write-Host ""; Write-Host " Invalid choice. Please enter 1-10, or Q." -ForegroundColor Yellow; Write-Host "" }
|
||||||
}
|
}
|
||||||
|
|
||||||
Write-Host ""
|
Write-Host ""
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ database:
|
|||||||
min_connections: 2
|
min_connections: 2
|
||||||
max_connections: 10
|
max_connections: 10
|
||||||
dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility)
|
dashboard_schema: "dashboard" # Schema for dashboard's own tables (isolated from game DB for backup compatibility)
|
||||||
|
dashboard_database_name: "dashboard" # Dedicated database for dashboard tables (auto-created on startup)
|
||||||
|
|
||||||
# Kubernetes
|
# Kubernetes
|
||||||
kubernetes:
|
kubernetes:
|
||||||
|
|||||||
+2
-1
@@ -224,7 +224,8 @@ table {
|
|||||||
}
|
}
|
||||||
|
|
||||||
thead th {
|
thead th {
|
||||||
background: #f8f6f2;
|
background: var(--table-header);
|
||||||
|
color: var(--text);
|
||||||
padding: 10px 14px;
|
padding: 10px 14px;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
|
|||||||
+88
-27
@@ -322,6 +322,24 @@
|
|||||||
--code-bg: #fafaf5;
|
--code-bg: #fafaf5;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* ===== Dark Variants (for light themes) ===== */
|
||||||
|
[data-theme="default-dark"] { --primary:#c9a24e; --primary-dark:#a8862e; --primary-light:#e0c97a; --bg:#1a1a1e; --card-bg:#252528; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#c9a24e; --danger:#c0392b; --success:#27ae60; --nav-bg:#0d0d12; --nav-text:#c0c0c0; --nav-active:#c9a24e; --hover:#2a2a2e; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2a2e; --code-bg:#1e1e22; }
|
||||||
|
[data-theme="atreides-dark"] { --primary:#2d5a27; --primary-dark:#1e3d19; --primary-light:#4a8c42; --bg:#1a1e1a; --card-bg:#252825; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#3d7a37; --danger:#cc4422; --success:#4a8c42; --nav-bg:#0d120d; --nav-text:#c0c0c0; --nav-active:#6abf6a; --hover:#2a2e2a; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2a; --code-bg:#1e221e; }
|
||||||
|
[data-theme="fremen-dark"] { --primary:#d4a853; --primary-dark:#b8913f; --primary-light:#e8c87a; --bg:#1e1a15; --card-bg:#282420; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#d4a853; --danger:#c45030; --success:#6b8e23; --nav-bg:#100c08; --nav-text:#c0b8a8; --nav-active:#d4a853; --hover:#2a2520; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2520; --code-bg:#1e1c18; }
|
||||||
|
[data-theme="bene-gesserit-dark"] { --primary:#a8a8a8; --primary-dark:#888; --primary-light:#c8c8c8; --bg:#1a1a1c; --card-bg:#252528; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#888; --danger:#c41e3a; --success:#2e8b57; --nav-bg:#0d0d0e; --nav-text:#c0c0c0; --nav-active:#ccc; --hover:#2a2a2c; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2a2c; --code-bg:#1e1e20; }
|
||||||
|
[data-theme="corrino-dark"] { --primary:#b02020; --primary-dark:#8b0000; --primary-light:#d44040; --bg:#1e1a1a; --card-bg:#282525; --text:#e0d8d8; --text-light:#a09090; --text-muted:#705858; --border:#383333; --accent:#c43030; --danger:#c0392b; --success:#27ae60; --nav-bg:#120d0d; --nav-text:#c0b8b8; --nav-active:#ff6b6b; --hover:#2e2a2a; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2e2a2a; --code-bg:#221e1e; }
|
||||||
|
[data-theme="mentat-dark"] { --primary:#008b8b; --primary-dark:#006666; --primary-light:#20b2aa; --bg:#1a1e1e; --card-bg:#252828; --text:#e0e0e0; --text-light:#a0a0a0; --text-muted:#707070; --border:#333; --accent:#008b8b; --danger:#c44569; --success:#20b2aa; --nav-bg:#0d1212; --nav-text:#c0c0c0; --nav-active:#00ced1; --hover:#2a2e2e; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2e; --code-bg:#1e2222; }
|
||||||
|
[data-theme="sardaukar-dark"] { --primary:#cd853f; --primary-dark:#a0522d; --primary-light:#deb887; --bg:#1e1a15; --card-bg:#282420; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#cd853f; --danger:#cc4422; --success:#6b8e23; --nav-bg:#100c08; --nav-text:#c0b8a8; --nav-active:#cd853f; --hover:#2a2520; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2520; --code-bg:#1e1c18; }
|
||||||
|
[data-theme="ordos-dark"] { --primary:#2e8b57; --primary-dark:#1c5c3a; --primary-light:#3cb371; --bg:#1a1e1c; --card-bg:#252825; --text:#e0e0d8; --text-light:#a0a090; --text-muted:#707060; --border:#333a33; --accent:#3cb371; --danger:#cc5c3a; --success:#3cb371; --nav-bg:#0d120d; --nav-text:#c0c8c0; --nav-active:#3cb371; --hover:#2a2e2c; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2e2c; --code-bg:#1e221e; }
|
||||||
|
[data-theme="ix-dark"] { --primary:#4169e1; --primary-dark:#2c4db8; --primary-light:#6495ed; --bg:#1a1c22; --card-bg:#252530; --text:#e0e0e8; --text-light:#a0a0c0; --text-muted:#707090; --border:#333a50; --accent:#6495ed; --danger:#c44569; --success:#32cd32; --nav-bg:#0d0d15; --nav-text:#c0c0d8; --nav-active:#6495ed; --hover:#2a2c38; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2c38; --code-bg:#1e1e28; }
|
||||||
|
[data-theme="choam-dark"] { --primary:#daa520; --primary-dark:#b8860b; --primary-light:#e8c840; --bg:#1e1c15; --card-bg:#282520; --text:#e0d8c8; --text-light:#a09888; --text-muted:#707058; --border:#38332a; --accent:#daa520; --danger:#b22222; --success:#228b22; --nav-bg:#100e08; --nav-text:#c0b8a8; --nav-active:#daa520; --hover:#2a2820; --shadow:0 2px 8px rgba(0,0,0,0.35); --table-header:#2a2820; --code-bg:#1e1c18; }
|
||||||
|
|
||||||
|
/* ===== Light Variants (for dark themes) ===== */
|
||||||
|
[data-theme="harkonnen-light"] { --primary:#ff6b00; --primary-dark:#cc5500; --primary-light:#ff8c33; --bg:#f5f0e8; --card-bg:#ffffff; --text:#1a1a1a; --text-light:#505050; --text-muted:#808080; --border:#e0d8c8; --accent:#ff4500; --danger:#cc0000; --success:#00aa33; --nav-bg:#1a1a1a; --nav-text:#d0d0d0; --nav-active:#ff6b00; --hover:#f0e8d8; --shadow:0 2px 8px rgba(0,0,0,0.08); --table-header:#e8e0d0; --code-bg:#faf8f5; }
|
||||||
|
[data-theme="spacing-guild-light"] { --primary:#4a90d9; --primary-dark:#2e6ab3; --primary-light:#6baee8; --bg:#e8edf5; --card-bg:#ffffff; --text:#1a2230; --text-light:#404860; --text-muted:#687080; --border:#d0d8e8; --accent:#4a90d9; --danger:#d94545; --success:#45d985; --nav-bg:#1a1a2e; --nav-text:#c0c8d0; --nav-active:#4a90d9; --hover:#e0e8f0; --shadow:0 2px 8px rgba(0,0,40,0.1); --table-header:#d8e0ed; --code-bg:#f4f6fa; }
|
||||||
|
[data-theme="emperor-light"] { --primary:#d4af37; --primary-dark:#b8962f; --primary-light:#e8c962; --bg:#faf8f0; --card-bg:#ffffff; --text:#1a1a1a; --text-light:#505050; --text-muted:#808080; --border:#e0d8c0; --accent:#d4af37; --danger:#c0392b; --success:#27ae60; --nav-bg:#1a1a1a; --nav-text:#d0d0d0; --nav-active:#d4af37; --hover:#f0ece0; --shadow:0 2px 8px rgba(0,0,0,0.08); --table-header:#e8e4d8; --code-bg:#fafaf5; }
|
||||||
|
[data-theme="tleilax-light"] { --primary:#6b20b0; --primary-dark:#4a0080; --primary-light:#9966cc; --bg:#f4f0f8; --card-bg:#ffffff; --text:#1a1a24; --text-light:#404060; --text-muted:#686880; --border:#d8d0e8; --accent:#8030cc; --danger:#c41e3a; --success:#00c080; --nav-bg:#1a1a24; --nav-text:#d0d0d8; --nav-active:#9966cc; --hover:#f0e8f8; --shadow:0 2px 8px rgba(40,0,60,0.1); --table-header:#e0d8f0; --code-bg:#f8f4fc; }
|
||||||
|
|
||||||
/* Theme Selector Button */
|
/* Theme Selector Button */
|
||||||
.theme-btn {
|
.theme-btn {
|
||||||
background: none;
|
background: none;
|
||||||
@@ -350,43 +368,70 @@
|
|||||||
position: absolute;
|
position: absolute;
|
||||||
right: 0;
|
right: 0;
|
||||||
background: #252530;
|
background: #252530;
|
||||||
min-width: 180px;
|
min-width: 290px;
|
||||||
|
max-height: 80vh;
|
||||||
|
overflow-y: auto;
|
||||||
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
box-shadow: 0 4px 16px rgba(0,0,0,0.4);
|
||||||
border-radius: 8px;
|
border-radius: 8px;
|
||||||
z-index: 1000;
|
z-index: 1000;
|
||||||
padding: 8px 0;
|
padding: 12px;
|
||||||
border: 1px solid #404050;
|
border: 1px solid #404050;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.theme-grid {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 8px;
|
||||||
|
padding: 4px 4px;
|
||||||
|
border-radius: 6px;
|
||||||
|
transition: background 0.15s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row:hover {
|
||||||
|
background: rgba(255,255,255,0.06);
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row-label {
|
||||||
|
flex: 1;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #d0d0d8;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch {
|
||||||
|
cursor: pointer;
|
||||||
|
transition: transform 0.15s, box-shadow 0.15s;
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
border-radius: 6px;
|
||||||
|
border: 2px solid transparent;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch:hover {
|
||||||
|
transform: scale(1.2);
|
||||||
|
box-shadow: 0 0 8px rgba(255,255,255,0.3);
|
||||||
|
border-color: #fff;
|
||||||
|
}
|
||||||
|
|
||||||
|
.theme-row .theme-swatch.active-theme {
|
||||||
|
border-color: #fff;
|
||||||
|
box-shadow: 0 0 6px rgba(255,255,255,0.4);
|
||||||
|
}
|
||||||
|
|
||||||
.theme-dropdown:hover .theme-dropdown-content {
|
.theme-dropdown:hover .theme-dropdown-content {
|
||||||
display: block;
|
display: block;
|
||||||
}
|
}
|
||||||
|
|
||||||
.theme-option {
|
/* Theme swatches base */
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 10px;
|
|
||||||
padding: 10px 16px;
|
|
||||||
cursor: pointer;
|
|
||||||
color: #d0d0d8;
|
|
||||||
font-size: 13px;
|
|
||||||
transition: background 0.15s;
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option:hover {
|
|
||||||
background: rgba(255,255,255,0.1);
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option.active {
|
|
||||||
background: var(--primary);
|
|
||||||
color: #fff;
|
|
||||||
}
|
|
||||||
|
|
||||||
.theme-option.active:hover {
|
|
||||||
background: var(--primary-dark);
|
|
||||||
}
|
|
||||||
|
|
||||||
/* Theme swatches */
|
|
||||||
.theme-swatch {
|
.theme-swatch {
|
||||||
width: 20px;
|
width: 20px;
|
||||||
height: 20px;
|
height: 20px;
|
||||||
@@ -410,6 +455,22 @@
|
|||||||
.theme-swatch.ix { background: linear-gradient(135deg, #4169e1 50%, #e8edf8 50%); }
|
.theme-swatch.ix { background: linear-gradient(135deg, #4169e1 50%, #e8edf8 50%); }
|
||||||
.theme-swatch.choam { background: linear-gradient(135deg, #b8860b 50%, #faf8f0 50%); }
|
.theme-swatch.choam { background: linear-gradient(135deg, #b8860b 50%, #faf8f0 50%); }
|
||||||
|
|
||||||
|
/* Variant swatches */
|
||||||
|
.theme-swatch.default-dark { background: linear-gradient(135deg, #c9a24e 50%, #1a1a1e 50%); }
|
||||||
|
.theme-swatch.atreides-dark { background: linear-gradient(135deg, #2d5a27 50%, #1a1e1a 50%); }
|
||||||
|
.theme-swatch.harkonnen-light { background: linear-gradient(135deg, #ff6b00 50%, #f5f0e8 50%); }
|
||||||
|
.theme-swatch.fremen-dark { background: linear-gradient(135deg, #d4a853 50%, #1e1a15 50%); }
|
||||||
|
.theme-swatch.bene-gesserit-dark { background: linear-gradient(135deg, #a8a8a8 50%, #1a1a1c 50%); }
|
||||||
|
.theme-swatch.spacing-guild-light { background: linear-gradient(135deg, #4a90d9 50%, #e8edf5 50%); }
|
||||||
|
.theme-swatch.emperor-light { background: linear-gradient(135deg, #d4af37 50%, #faf8f0 50%); }
|
||||||
|
.theme-swatch.corrino-dark { background: linear-gradient(135deg, #b02020 50%, #1e1a1a 50%); }
|
||||||
|
.theme-swatch.mentat-dark { background: linear-gradient(135deg, #008b8b 50%, #1a1e1e 50%); }
|
||||||
|
.theme-swatch.sardaukar-dark { background: linear-gradient(135deg, #cd853f 50%, #1e1a15 50%); }
|
||||||
|
.theme-swatch.tleilax-light { background: linear-gradient(135deg, #6b20b0 50%, #f4f0f8 50%); }
|
||||||
|
.theme-swatch.ordos-dark { background: linear-gradient(135deg, #2e8b57 50%, #1a1e1c 50%); }
|
||||||
|
.theme-swatch.ix-dark { background: linear-gradient(135deg, #4169e1 50%, #1a1c22 50%); }
|
||||||
|
.theme-swatch.choam-dark { background: linear-gradient(135deg, #daa520 50%, #1e1c15 50%); }
|
||||||
|
|
||||||
/* Current theme indicator */
|
/* Current theme indicator */
|
||||||
#current-theme-display {
|
#current-theme-display {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
|
|||||||
@@ -1,12 +1,41 @@
|
|||||||
{% extends "base.html" %}
|
{% extends "base.html" %}
|
||||||
{% block title %}Admin Experimental - Dune Awakening Dashboard{% endblock %}
|
{% block title %}Experimental - Dune Awakening Dashboard{% endblock %}
|
||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
|
<div id="exp-gate" class="exp-gate">
|
||||||
|
<div class="exp-gate-box">
|
||||||
|
<div class="exp-gate-icon">⚠</div>
|
||||||
|
<h2>Experimental Features — Proceed with Caution</h2>
|
||||||
|
<p>This area contains <strong>untested, experimental tools</strong> that interact directly with your game server's internal systems (RabbitMQ, PostgreSQL, Battlegroup Director).</p>
|
||||||
|
<p>These tools <strong>can corrupt data, crash servers, or delete characters</strong>. Do not report bugs about this page. Always snapshot or backup your server first.</p>
|
||||||
|
<div class="exp-gate-actions">
|
||||||
|
<button onclick="denyExperimental()" class="exp-gate-btn deny">Take Me Back to Safety</button>
|
||||||
|
<button onclick="acceptExperimental()" class="exp-gate-btn accept">I Understand the Risks — Proceed</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="exp-content" style="display:none;">
|
||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>Admin Experimental</h1>
|
<h1>Experimental</h1>
|
||||||
<p>Experimental tools discovered through server research</p>
|
<p>Experimental tools discovered through server research</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="experimental-warning">
|
||||||
|
<div class="experimental-warning-title">⚠ DANGER — EXPERIMENTAL FEATURES</div>
|
||||||
|
<div class="experimental-warning-body">
|
||||||
|
<p>This page contains <strong>experimental and potentially destructive</strong> tools that interact directly with your game server's internal systems (RabbitMQ, PostgreSQL, Battlegroup Director).</p>
|
||||||
|
<p><strong>These tools can corrupt your database, crash game servers, delete player data, or render your cluster inoperable.</strong></p>
|
||||||
|
<ul>
|
||||||
|
<li><strong>DO NOT report bugs</strong> found on this page — these features are untested and in active research.</li>
|
||||||
|
<li><strong>USE AT YOUR OWN RISK.</strong> The dashboard authors are not responsible for any damage caused.</li>
|
||||||
|
<li><strong>SNAPSHOT OR BACKUP YOUR SERVER</strong> before using ANY tool on this page.</li>
|
||||||
|
<li>If you don't understand what a button does, <strong>DO NOT CLICK IT.</strong></li>
|
||||||
|
</ul>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">In-Game Broadcast</div>
|
<div class="card-header">In-Game Broadcast</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@@ -406,11 +435,97 @@
|
|||||||
<option value="demo_expired">Demo Expired</option>
|
<option value="demo_expired">Demo Expired</option>
|
||||||
</select>
|
</select>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="margin-top:24px;">
|
||||||
|
<h2 style="margin-bottom:16px;">RabbitMQ Explorer</h2>
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:16px;">
|
||||||
|
Inspect the RMQ clusters. Both Admin (port 30325) and Game (port 32716) instances via SSH tunnel.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Overview</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">Cluster health, node info, message stats.</p>
|
||||||
|
<div id="rmq-overview-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqOverview()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<pre id="rmq-overview-data" style="max-height:300px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
</div>
|
</div>
|
||||||
<button onclick="setDemoState()" style="margin-top:8px;padding:8px 16px;background:var(--bg-hover);color:var(--text);border:1px solid var(--border);border-radius:4px;cursor:pointer;">Set Demo State</button>
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Queues</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">All queues with consumer counts and message depths.</p>
|
||||||
|
<div id="rmq-queues-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqQueues()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<div id="rmq-queues-data" style="max-height:300px;overflow:auto;font-size:11px;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">RMQ Exchanges</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">All exchanges with type, durability, and message stats.</p>
|
||||||
|
<div id="rmq-exchanges-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<button onclick="loadRmqExchanges()"
|
||||||
|
style="padding:8px 16px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;margin-bottom:8px;">Refresh</button>
|
||||||
|
<div id="rmq-exchanges-data" style="max-height:300px;overflow:auto;font-size:11px;"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Message Inspector</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">Peek at messages in any queue without consuming them.</p>
|
||||||
|
<div id="rmq-peek-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<div style="display:flex;gap:8px;margin-bottom:8px;">
|
||||||
|
<input type="text" id="rmq-peek-queue" placeholder="Queue name..."
|
||||||
|
style="flex:1;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<input type="number" id="rmq-peek-count" value="5" min="1" max="20"
|
||||||
|
style="width:60px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<button onclick="peekRmqMessages()"
|
||||||
|
style="padding:6px 14px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Peek</button>
|
||||||
|
</div>
|
||||||
|
<pre id="rmq-peek-data" style="max-height:300px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card" style="grid-column:1 / -1;">
|
||||||
|
<div class="card-header">Publish Test Message</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<p style="color:var(--text-muted);font-size:13px;margin-bottom:8px;">
|
||||||
|
Publish a test message to any exchange. <strong>Note:</strong> HTTP API sets user_id to dashboard_admin, which the game server may reject for RPC commands. Use the Erlang eval broadcast for in-game commands.
|
||||||
|
</p>
|
||||||
|
<div id="rmq-publish-status" class="error-banner" style="display:none;"></div>
|
||||||
|
<div style="display:flex;gap:8px;margin-bottom:8px;flex-wrap:wrap;">
|
||||||
|
<select id="rmq-publish-side" style="padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<option value="admin">Admin (30325)</option>
|
||||||
|
<option value="game">Game (32716)</option>
|
||||||
|
</select>
|
||||||
|
<input type="text" id="rmq-publish-exchange" placeholder="Exchange name..."
|
||||||
|
style="flex:1;min-width:150px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<input type="text" id="rmq-publish-routing" placeholder="Routing key..."
|
||||||
|
style="flex:1;min-width:150px;padding:6px 8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;">
|
||||||
|
<button onclick="publishRmqMessage()"
|
||||||
|
style="padding:6px 14px;background:var(--accent);color:#fff;border:none;border-radius:4px;cursor:pointer;font-size:12px;">Publish</button>
|
||||||
|
</div>
|
||||||
|
<textarea id="rmq-publish-message" rows="4" placeholder='{"key": "value"}'
|
||||||
|
style="width:100%;padding:8px;background:var(--bg-input);border:1px solid var(--border);border-radius:4px;color:var(--text);font-size:12px;font-family:monospace;resize:vertical;"></textarea>
|
||||||
|
<pre id="rmq-publish-data" style="max-height:200px;overflow:auto;font-size:11px;background:var(--bg-hover);padding:10px;border-radius:4px;margin-top:8px;white-space:pre-wrap;word-break:break-all;"></pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="card">
|
||||||
<div class="card-header">Journey & Specialization</div>
|
<div class="card-header">Journey & Specialization</div>
|
||||||
<div class="card-body">
|
<div class="card-body">
|
||||||
@@ -539,10 +654,28 @@
|
|||||||
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.error-banner { padding: 10px 14px; border-radius: 4px; margin-bottom: 12px; font-size: 13px; }
|
.error-banner { padding: 10px 14px; border-radius: 4px; margin-bottom: 12px; font-size: 13px; }
|
||||||
.error-banner.success { background: #1a3a2a; border: 1px solid #2ecc71; color: #2ecc71; display: block; }
|
.error-banner.success { background: #1a3a2a; border: 1px solid #2ecc71; color: #2ecc71; display: block; }
|
||||||
.error-banner.error { background: #3a1a1a; border: 1px solid #e74c3c; color: #e74c3c; display: block; }
|
.error-banner.error { background: #3a1a1a; border: 1px solid #e74c3c; color: #e74c3c; display: block; }
|
||||||
|
.experimental-warning { background: rgba(220,38,38,0.12); border: 2px solid rgba(220,38,38,0.6); border-left: 6px solid #dc2626; border-radius: 8px; padding: 18px 22px; margin-bottom: 24px; }
|
||||||
|
.experimental-warning-title { font-size: 16px; font-weight: 700; color: #ef4444; margin-bottom: 12px; }
|
||||||
|
.experimental-warning-body p { margin: 0 0 10px; font-size: 13px; color: var(--text); line-height: 1.6; }
|
||||||
|
.experimental-warning-body ul { margin: 8px 0 0; padding-left: 20px; font-size: 13px; color: var(--text); line-height: 1.8; }
|
||||||
|
.experimental-warning-body li { margin-bottom: 4px; }
|
||||||
|
.exp-gate { position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 9999; display: flex; align-items: center; justify-content: center; }
|
||||||
|
.exp-gate-box { background: #1a1a1e; border: 2px solid #dc2626; border-radius: 12px; max-width: 560px; width: 90%; padding: 32px; text-align: center; color: #e0e0e0; }
|
||||||
|
.exp-gate-icon { font-size: 48px; color: #ef4444; margin-bottom: 16px; }
|
||||||
|
.exp-gate-box h2 { font-size: 18px; color: #ef4444; margin: 0 0 16px; }
|
||||||
|
.exp-gate-box p { font-size: 13px; line-height: 1.6; margin: 0 0 12px; color: #c0c0c0; }
|
||||||
|
.exp-gate-actions { display: flex; gap: 12px; margin-top: 20px; justify-content: center; flex-wrap: wrap; }
|
||||||
|
.exp-gate-btn { padding: 12px 24px; border: none; border-radius: 6px; font-size: 14px; font-weight: 600; cursor: pointer; }
|
||||||
|
.exp-gate-btn.accept { background: #dc2626; color: #fff; }
|
||||||
|
.exp-gate-btn.accept:hover { background: #b91c1c; }
|
||||||
|
.exp-gate-btn.deny { background: #374151; color: #d0d0d0; }
|
||||||
|
.exp-gate-btn.deny:hover { background: #4b5563; }
|
||||||
code { background: var(--bg-hover); padding: 1px 4px; border-radius: 3px; font-size: 12px; }
|
code { background: var(--bg-hover); padding: 1px 4px; border-radius: 3px; font-size: 12px; }
|
||||||
.result-table { width:100%; border-collapse:collapse; font-size:12px; margin-top:8px; }
|
.result-table { width:100%; border-collapse:collapse; font-size:12px; margin-top:8px; }
|
||||||
.result-table th { text-align:left; padding:6px 8px; background:var(--bg-hover); border-bottom:2px solid var(--border); }
|
.result-table th { text-align:left; padding:6px 8px; background:var(--bg-hover); border-bottom:2px solid var(--border); }
|
||||||
@@ -1272,11 +1405,131 @@ async function executeFunction(name, paramCount) {
|
|||||||
} catch(e) { resultDiv.innerHTML = `<div class="error-banner error" style="display:block;">${esc(e.message)}</div>`; }
|
} catch(e) { resultDiv.innerHTML = `<div class="error-banner error" style="display:block;">${esc(e.message)}</div>`; }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── RMQ Explorer ─────────────────────────────────────────────────
|
||||||
|
async function loadRmqOverview() {
|
||||||
|
const status = document.getElementById('rmq-overview-status');
|
||||||
|
const output = document.getElementById('rmq-overview-data');
|
||||||
|
hideStatus(status); output.textContent = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/overview');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRmqQueues() {
|
||||||
|
const status = document.getElementById('rmq-queues-status');
|
||||||
|
const output = document.getElementById('rmq-queues-data');
|
||||||
|
hideStatus(status); output.innerHTML = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/queues');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.innerHTML = ''; return; }
|
||||||
|
const data = d.data || {};
|
||||||
|
let html = '';
|
||||||
|
for (const [side, queues] of Object.entries(data)) {
|
||||||
|
html += `<h4 style="margin:8px 0 4px;font-size:12px;color:var(--text)">RMQ ${side.toUpperCase()}</h4>`;
|
||||||
|
if (!queues || !queues.length) { html += '<p style="font-size:11px;color:var(--text-muted)">No queues or connection failed</p>'; continue; }
|
||||||
|
html += '<table class="result-table"><tr><th>Name</th><th>State</th><th>Ready</th><th>Consumers</th></tr>';
|
||||||
|
for (const q of queues) {
|
||||||
|
html += `<tr><td style="font-size:10px;word-break:break-all">${esc(q.name||'?')}</td>`;
|
||||||
|
html += `<td>${esc(String(q.state||''))}</td>`;
|
||||||
|
html += `<td>${q.messages_ready||0}</td><td>${q.consumers||0}</td></tr>`;
|
||||||
|
}
|
||||||
|
html += '</table>';
|
||||||
|
}
|
||||||
|
output.innerHTML = html;
|
||||||
|
} catch(e) { showError(status, e.message); output.innerHTML = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadRmqExchanges() {
|
||||||
|
const status = document.getElementById('rmq-exchanges-status');
|
||||||
|
const output = document.getElementById('rmq-exchanges-data');
|
||||||
|
hideStatus(status); output.innerHTML = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/exchanges');
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.innerHTML = ''; return; }
|
||||||
|
const data = d.data || {};
|
||||||
|
let html = '';
|
||||||
|
for (const [side, exchanges] of Object.entries(data)) {
|
||||||
|
html += `<h4 style="margin:8px 0 4px;font-size:12px;color:var(--text)">RMQ ${side.toUpperCase()}</h4>`;
|
||||||
|
if (!exchanges || !exchanges.length) { html += '<p style="font-size:11px;color:var(--text-muted)">No exchanges or connection failed</p>'; continue; }
|
||||||
|
html += '<table class="result-table"><tr><th>Name</th><th>Type</th><th>Durable</th><th>Msgs</th></tr>';
|
||||||
|
for (const x of exchanges) {
|
||||||
|
html += `<tr><td style="font-size:10px;word-break:break-all">${esc(x.name||'?')}</td>`;
|
||||||
|
html += `<td>${esc(x.type||'')}</td><td>${x.durable?'Yes':'No'}</td>`;
|
||||||
|
html += `<td>${x.message_stats?.publish_in||0}</td></tr>`;
|
||||||
|
}
|
||||||
|
html += '</table>';
|
||||||
|
}
|
||||||
|
output.innerHTML = html;
|
||||||
|
} catch(e) { showError(status, e.message); output.innerHTML = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function peekRmqMessages() {
|
||||||
|
const status = document.getElementById('rmq-peek-status');
|
||||||
|
const output = document.getElementById('rmq-peek-data');
|
||||||
|
const queue = document.getElementById('rmq-peek-queue').value.trim();
|
||||||
|
const count = parseInt(document.getElementById('rmq-peek-count').value) || 5;
|
||||||
|
if (!queue) { showError(status, 'Enter a queue name'); return; }
|
||||||
|
hideStatus(status); output.textContent = 'Loading...';
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/peek', {
|
||||||
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({queue, count})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function publishRmqMessage() {
|
||||||
|
const status = document.getElementById('rmq-publish-status');
|
||||||
|
const output = document.getElementById('rmq-publish-data');
|
||||||
|
const side = document.getElementById('rmq-publish-side').value;
|
||||||
|
const exchange = document.getElementById('rmq-publish-exchange').value.trim();
|
||||||
|
const routing_key = document.getElementById('rmq-publish-routing').value.trim();
|
||||||
|
const messageStr = document.getElementById('rmq-publish-message').value.trim();
|
||||||
|
if (!exchange) { showError(status, 'Enter an exchange name'); return; }
|
||||||
|
hideStatus(status); output.textContent = 'Publishing...';
|
||||||
|
let message = messageStr;
|
||||||
|
try { message = JSON.parse(messageStr); } catch(_) {}
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/admin-experimental/rmq/publish', {
|
||||||
|
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||||
|
body: JSON.stringify({exchange, routing_key, message, side})
|
||||||
|
});
|
||||||
|
const d = await r.json();
|
||||||
|
if (!d.success) { showError(status, d.error); output.textContent = ''; return; }
|
||||||
|
output.textContent = JSON.stringify(d.data, null, 2);
|
||||||
|
} catch(e) { showError(status, e.message); output.textContent = ''; }
|
||||||
|
}
|
||||||
|
|
||||||
// ── Helpers ─────────────────────────────────────────────────────────
|
// ── Helpers ─────────────────────────────────────────────────────────
|
||||||
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
function esc(s) { if (!s) return ''; return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
||||||
function showError(el, msg) { el.className = 'error-banner error'; el.textContent = msg; el.style.display = 'block'; }
|
function showError(el, msg) { el.className = 'error-banner error'; el.textContent = msg; el.style.display = 'block'; }
|
||||||
function showSuccess(el, msg) { el.className = 'error-banner success'; el.textContent = msg; el.style.display = 'block'; }
|
function showSuccess(el, msg) { el.className = 'error-banner success'; el.textContent = msg; el.style.display = 'block'; }
|
||||||
function hideStatus(el) { el.style.display = 'none'; }
|
function hideStatus(el) { el.style.display = 'none'; }
|
||||||
|
|
||||||
|
function acceptExperimental() {
|
||||||
|
document.getElementById('exp-gate').style.display = 'none';
|
||||||
|
document.getElementById('exp-content').style.display = 'block';
|
||||||
|
localStorage.setItem('exp-warning-accepted', '1');
|
||||||
|
}
|
||||||
|
|
||||||
|
function denyExperimental() {
|
||||||
|
localStorage.removeItem('exp-warning-accepted');
|
||||||
|
window.location.href = '/';
|
||||||
|
}
|
||||||
|
|
||||||
|
(function() {
|
||||||
|
if (localStorage.getItem('exp-warning-accepted') === '1') {
|
||||||
|
acceptExperimental();
|
||||||
|
}
|
||||||
|
})();
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
+62
-119
@@ -7,15 +7,9 @@
|
|||||||
<meta name="csrf-token" content="{{ csrf_token() }}">
|
<meta name="csrf-token" content="{{ csrf_token() }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
|
||||||
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
<link rel="stylesheet" href="{{ url_for('static', filename='themes.css') }}">
|
||||||
|
{% block head_extra %}{% endblock %}
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="update-banner" class="update-banner" style="display:none;">
|
|
||||||
<span>🔄 Update available for Dune Dashboard</span>
|
|
||||||
<div class="update-actions">
|
|
||||||
<button onclick="applyUpdate()" class="update-btn primary">Update Now</button>
|
|
||||||
<button onclick="dismissUpdate()" class="update-btn">Later</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<nav>
|
<nav>
|
||||||
<div class="brand">DUNE DASHBOARD</div>
|
<div class="brand">DUNE DASHBOARD</div>
|
||||||
{% for href, label in nav_pages %}
|
{% for href, label in nav_pages %}
|
||||||
@@ -25,47 +19,77 @@
|
|||||||
<div class="theme-dropdown">
|
<div class="theme-dropdown">
|
||||||
<button class="theme-btn" title="Theme">🎨</button>
|
<button class="theme-btn" title="Theme">🎨</button>
|
||||||
<div class="theme-dropdown-content">
|
<div class="theme-dropdown-content">
|
||||||
<div class="theme-option active" data-theme="default" onclick="setTheme('default')">
|
<div class="theme-grid">
|
||||||
<span class="theme-swatch default"></span> Classic Dune
|
<div class="theme-row" data-family="default">
|
||||||
|
<span class="theme-row-label">Classic Dune</span>
|
||||||
|
<span class="theme-swatch default" data-theme="default" onclick="setTheme('default')" title="Classic Dune Light"></span>
|
||||||
|
<span class="theme-swatch default-dark active-theme" data-theme="default-dark" onclick="setTheme('default-dark')" title="Classic Dune Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="atreides" onclick="setTheme('atreides')">
|
<div class="theme-row" data-family="atreides">
|
||||||
<span class="theme-swatch atrides"></span> House Atreides
|
<span class="theme-row-label">House Atreides</span>
|
||||||
|
<span class="theme-swatch atreides" data-theme="atreides" onclick="setTheme('atreides')" title="House Atreides Light"></span>
|
||||||
|
<span class="theme-swatch atreides-dark" data-theme="atreides-dark" onclick="setTheme('atreides-dark')" title="House Atreides Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="harkonnen" onclick="setTheme('harkonnen')">
|
<div class="theme-row" data-family="harkonnen">
|
||||||
<span class="theme-swatch harkonnen"></span> House Harkonnen
|
<span class="theme-row-label">House Harkonnen</span>
|
||||||
|
<span class="theme-swatch harkonnen-light" data-theme="harkonnen-light" onclick="setTheme('harkonnen-light')" title="House Harkonnen Light"></span>
|
||||||
|
<span class="theme-swatch harkonnen" data-theme="harkonnen" onclick="setTheme('harkonnen')" title="House Harkonnen Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="fremen" onclick="setTheme('fremen')">
|
<div class="theme-row" data-family="fremen">
|
||||||
<span class="theme-swatch fremen"></span> Fremen
|
<span class="theme-row-label">Fremen</span>
|
||||||
|
<span class="theme-swatch fremen" data-theme="fremen" onclick="setTheme('fremen')" title="Fremen Light"></span>
|
||||||
|
<span class="theme-swatch fremen-dark" data-theme="fremen-dark" onclick="setTheme('fremen-dark')" title="Fremen Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="bene-gesserit" onclick="setTheme('bene-gesserit')">
|
<div class="theme-row" data-family="bene-gesserit">
|
||||||
<span class="theme-swatch bene-gesserit"></span> Bene Gesserit
|
<span class="theme-row-label">Bene Gesserit</span>
|
||||||
|
<span class="theme-swatch bene-gesserit" data-theme="bene-gesserit" onclick="setTheme('bene-gesserit')" title="Bene Gesserit Light"></span>
|
||||||
|
<span class="theme-swatch bene-gesserit-dark" data-theme="bene-gesserit-dark" onclick="setTheme('bene-gesserit-dark')" title="Bene Gesserit Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="spacing-guild" onclick="setTheme('spacing-guild')">
|
<div class="theme-row" data-family="spacing-guild">
|
||||||
<span class="theme-swatch spacing-guild"></span> Spacing Guild
|
<span class="theme-row-label">Spacing Guild</span>
|
||||||
|
<span class="theme-swatch spacing-guild-light" data-theme="spacing-guild-light" onclick="setTheme('spacing-guild-light')" title="Spacing Guild Light"></span>
|
||||||
|
<span class="theme-swatch spacing-guild" data-theme="spacing-guild" onclick="setTheme('spacing-guild')" title="Spacing Guild Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="emperor" onclick="setTheme('emperor')">
|
<div class="theme-row" data-family="emperor">
|
||||||
<span class="theme-swatch emperor"></span> Emperor
|
<span class="theme-row-label">Emperor</span>
|
||||||
|
<span class="theme-swatch emperor-light" data-theme="emperor-light" onclick="setTheme('emperor-light')" title="Emperor Light"></span>
|
||||||
|
<span class="theme-swatch emperor" data-theme="emperor" onclick="setTheme('emperor')" title="Emperor Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="corrino" onclick="setTheme('corrino')">
|
<div class="theme-row" data-family="corrino">
|
||||||
<span class="theme-swatch corrino"></span> House Corrino
|
<span class="theme-row-label">House Corrino</span>
|
||||||
|
<span class="theme-swatch corrino" data-theme="corrino" onclick="setTheme('corrino')" title="House Corrino Light"></span>
|
||||||
|
<span class="theme-swatch corrino-dark" data-theme="corrino-dark" onclick="setTheme('corrino-dark')" title="House Corrino Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="mentat" onclick="setTheme('mentat')">
|
<div class="theme-row" data-family="mentat">
|
||||||
<span class="theme-swatch mentat"></span> Mentat
|
<span class="theme-row-label">Mentat</span>
|
||||||
|
<span class="theme-swatch mentat" data-theme="mentat" onclick="setTheme('mentat')" title="Mentat Light"></span>
|
||||||
|
<span class="theme-swatch mentat-dark" data-theme="mentat-dark" onclick="setTheme('mentat-dark')" title="Mentat Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="sardaukar" onclick="setTheme('sardaukar')">
|
<div class="theme-row" data-family="sardaukar">
|
||||||
<span class="theme-swatch sardaukar"></span> Sardaukar
|
<span class="theme-row-label">Sardaukar</span>
|
||||||
|
<span class="theme-swatch sardaukar" data-theme="sardaukar" onclick="setTheme('sardaukar')" title="Sardaukar Light"></span>
|
||||||
|
<span class="theme-swatch sardaukar-dark" data-theme="sardaukar-dark" onclick="setTheme('sardaukar-dark')" title="Sardaukar Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="tleilax" onclick="setTheme('tleilax')">
|
<div class="theme-row" data-family="tleilax">
|
||||||
<span class="theme-swatch tleilax"></span> Bene Tleilax
|
<span class="theme-row-label">Bene Tleilax</span>
|
||||||
|
<span class="theme-swatch tleilax-light" data-theme="tleilax-light" onclick="setTheme('tleilax-light')" title="Bene Tleilax Light"></span>
|
||||||
|
<span class="theme-swatch tleilax" data-theme="tleilax" onclick="setTheme('tleilax')" title="Bene Tleilax Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="ordos" onclick="setTheme('ordos')">
|
<div class="theme-row" data-family="ordos">
|
||||||
<span class="theme-swatch ordos"></span> House Ordos
|
<span class="theme-row-label">House Ordos</span>
|
||||||
|
<span class="theme-swatch ordos" data-theme="ordos" onclick="setTheme('ordos')" title="House Ordos Light"></span>
|
||||||
|
<span class="theme-swatch ordos-dark" data-theme="ordos-dark" onclick="setTheme('ordos-dark')" title="House Ordos Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="ix" onclick="setTheme('ix')">
|
<div class="theme-row" data-family="ix">
|
||||||
<span class="theme-swatch ix"></span> Ix
|
<span class="theme-row-label">Ix</span>
|
||||||
|
<span class="theme-swatch ix" data-theme="ix" onclick="setTheme('ix')" title="Ix Light"></span>
|
||||||
|
<span class="theme-swatch ix-dark" data-theme="ix-dark" onclick="setTheme('ix-dark')" title="Ix Dark"></span>
|
||||||
|
</div>
|
||||||
|
<div class="theme-row" data-family="choam">
|
||||||
|
<span class="theme-row-label">CHOAM</span>
|
||||||
|
<span class="theme-swatch choam" data-theme="choam" onclick="setTheme('choam')" title="CHOAM Light"></span>
|
||||||
|
<span class="theme-swatch choam-dark" data-theme="choam-dark" onclick="setTheme('choam-dark')" title="CHOAM Dark"></span>
|
||||||
</div>
|
</div>
|
||||||
<div class="theme-option" data-theme="choam" onclick="setTheme('choam')">
|
|
||||||
<span class="theme-swatch choam"></span> CHOAM
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -73,7 +97,6 @@
|
|||||||
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
<span class="conn-dot {% if conn_ok %}online{% else %}offline{% endif %}"></span>
|
||||||
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
{{ 'Connected' if conn_ok else 'Disconnected' }}
|
||||||
</span>
|
</span>
|
||||||
<button id="check-update-btn" onclick="manualCheckUpdate()" style="font-size:12px;color:var(--nav-text);background:none;border:none;cursor:pointer;padding:4px 8px;" title="Check for updates">🔄 Check Updates</button>
|
|
||||||
{% if current_user and current_user.is_authenticated %}
|
{% if current_user and current_user.is_authenticated %}
|
||||||
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
|
<a href="/logout" style="font-size:12px;color:var(--nav-text);">Logout</a>
|
||||||
{% endif %}
|
{% endif %}
|
||||||
@@ -84,13 +107,6 @@
|
|||||||
<footer class="site-footer">
|
<footer class="site-footer">
|
||||||
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
<span>This is a fan-made project and is not affiliated with, endorsed by, or connected to Funcom, Legendary Entertainment, or any official Dune rights holders. All game assets, trademarks, and intellectual property belong to their respective owners.</span>
|
||||||
</footer>
|
</footer>
|
||||||
<div id="update-progress" class="update-progress" style="display:none;">
|
|
||||||
<div class="update-progress-inner">
|
|
||||||
<h3>Updating Dashboard...</h3>
|
|
||||||
<p id="update-status-text">Checking for updates...</p>
|
|
||||||
<div class="update-spinner"></div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<script>
|
<script>
|
||||||
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
const csrfToken = document.querySelector('meta[name="csrf-token"]').getAttribute('content');
|
||||||
|
|
||||||
@@ -100,66 +116,6 @@
|
|||||||
return fetch(url, options);
|
return fetch(url, options);
|
||||||
}
|
}
|
||||||
|
|
||||||
let updateDismissed = false;
|
|
||||||
async function checkForUpdate() {
|
|
||||||
if (updateDismissed) return;
|
|
||||||
try {
|
|
||||||
const resp = await fetch('/api/update/status');
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.available) {
|
|
||||||
document.getElementById('update-banner').style.display = 'flex';
|
|
||||||
}
|
|
||||||
} catch (e) {}
|
|
||||||
}
|
|
||||||
async function manualCheckUpdate() {
|
|
||||||
const btn = document.getElementById('check-update-btn');
|
|
||||||
btn.textContent = 'Checking...';
|
|
||||||
btn.disabled = true;
|
|
||||||
try {
|
|
||||||
const resp = await csrfFetch('/api/update/check', { method: 'POST' });
|
|
||||||
const data = await resp.json();
|
|
||||||
if (data.available) {
|
|
||||||
document.getElementById('update-banner').style.display = 'flex';
|
|
||||||
btn.textContent = 'Update Available!';
|
|
||||||
} else {
|
|
||||||
btn.textContent = 'Up to Date ✓';
|
|
||||||
setTimeout(() => { btn.textContent = '🔄 Check Updates'; }, 3000);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
btn.textContent = 'Check Failed';
|
|
||||||
setTimeout(() => { btn.textContent = '🔄 Check Updates'; }, 3000);
|
|
||||||
}
|
|
||||||
btn.disabled = false;
|
|
||||||
}
|
|
||||||
function dismissUpdate() {
|
|
||||||
updateDismissed = true;
|
|
||||||
document.getElementById('update-banner').style.display = 'none';
|
|
||||||
}
|
|
||||||
async function applyUpdate() {
|
|
||||||
const banner = document.getElementById('update-banner');
|
|
||||||
const progress = document.getElementById('update-progress');
|
|
||||||
const statusText = document.getElementById('update-status-text');
|
|
||||||
banner.style.display = 'none';
|
|
||||||
progress.style.display = 'flex';
|
|
||||||
try {
|
|
||||||
const resp = await csrfFetch('/api/update/apply', { method: 'POST' });
|
|
||||||
const data = await resp.json();
|
|
||||||
statusText.textContent = data.message || 'Applying update...';
|
|
||||||
if (data.success) {
|
|
||||||
statusText.textContent = 'Update complete! Restarting...';
|
|
||||||
setTimeout(() => { location.reload(); }, 5000);
|
|
||||||
} else {
|
|
||||||
statusText.textContent = 'Update failed: ' + (data.message || 'Unknown error');
|
|
||||||
setTimeout(() => { progress.style.display = 'none'; }, 5000);
|
|
||||||
}
|
|
||||||
} catch (e) {
|
|
||||||
statusText.textContent = 'Update failed: ' + e.message;
|
|
||||||
setTimeout(() => { progress.style.display = 'none'; }, 5000);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
setInterval(checkForUpdate, 60000);
|
|
||||||
checkForUpdate();
|
|
||||||
|
|
||||||
// Theme System
|
// Theme System
|
||||||
function setTheme(themeName) {
|
function setTheme(themeName) {
|
||||||
document.documentElement.setAttribute('data-theme', themeName);
|
document.documentElement.setAttribute('data-theme', themeName);
|
||||||
@@ -168,16 +124,13 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function updateThemeUI(themeName) {
|
function updateThemeUI(themeName) {
|
||||||
document.querySelectorAll('.theme-option').forEach(opt => {
|
document.querySelectorAll('.theme-row .theme-swatch').forEach(sw => {
|
||||||
opt.classList.remove('active');
|
sw.classList.toggle('active-theme', sw.getAttribute('data-theme') === themeName);
|
||||||
if (opt.getAttribute('data-theme') === themeName) {
|
|
||||||
opt.classList.add('active');
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function initTheme() {
|
function initTheme() {
|
||||||
const savedTheme = localStorage.getItem('dune-theme') || 'default';
|
const savedTheme = localStorage.getItem('dune-theme') || 'default-dark';
|
||||||
document.documentElement.setAttribute('data-theme', savedTheme);
|
document.documentElement.setAttribute('data-theme', savedTheme);
|
||||||
updateThemeUI(savedTheme);
|
updateThemeUI(savedTheme);
|
||||||
}
|
}
|
||||||
@@ -186,16 +139,6 @@
|
|||||||
</script>
|
</script>
|
||||||
{% block scripts %}{% endblock %}
|
{% block scripts %}{% endblock %}
|
||||||
<style>
|
<style>
|
||||||
.update-banner { background: var(--hover); border-bottom: 2px solid var(--accent); padding: 10px 20px; display: flex; justify-content: space-between; align-items: center; font-size: 13px; color: var(--text); }
|
|
||||||
.update-actions { display: flex; gap: 8px; }
|
|
||||||
.update-btn { padding: 4px 12px; border: 1px solid var(--border); border-radius: 4px; background: var(--bg-card); color: var(--text); cursor: pointer; font-size: 12px; }
|
|
||||||
.update-btn.primary { background: var(--accent); color: #fff; border-color: var(--accent); }
|
|
||||||
.update-progress { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.7); display: flex; align-items: center; justify-content: center; z-index: 9999; }
|
|
||||||
.update-progress-inner { background: var(--bg-card); padding: 30px 40px; border-radius: 8px; text-align: center; color: var(--text); max-width: 400px; }
|
|
||||||
.update-progress-inner h3 { margin: 0 0 10px; }
|
|
||||||
.update-progress-inner p { margin: 0 0 15px; color: var(--text-muted); font-size: 13px; }
|
|
||||||
.update-spinner { width: 30px; height: 30px; border: 3px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 1s linear infinite; margin: 0 auto; }
|
|
||||||
@keyframes spin { to { transform: rotate(360deg); } }
|
|
||||||
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
|
.site-footer { text-align: center; padding: 16px 20px; font-size: 11px; color: var(--text-muted); border-top: 1px solid var(--border); margin-top: 24px; }
|
||||||
</style>
|
</style>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
+109
-18
@@ -185,6 +185,7 @@
|
|||||||
<script>
|
<script>
|
||||||
let bgData = null;
|
let bgData = null;
|
||||||
let charTransferData = null;
|
let charTransferData = null;
|
||||||
|
let scaleData = {};
|
||||||
|
|
||||||
async function loadDirector() {
|
async function loadDirector() {
|
||||||
const banner = document.getElementById('loading-banner');
|
const banner = document.getElementById('loading-banner');
|
||||||
@@ -214,6 +215,7 @@ async function loadDirector() {
|
|||||||
if (ctResp.ok) {
|
if (ctResp.ok) {
|
||||||
charTransferData = await ctResp.json();
|
charTransferData = await ctResp.json();
|
||||||
}
|
}
|
||||||
|
await loadScaleData(bgData);
|
||||||
if (document.getElementById('maps-container').children.length === 0) {
|
if (document.getElementById('maps-container').children.length === 0) {
|
||||||
renderStats();
|
renderStats();
|
||||||
renderMaps();
|
renderMaps();
|
||||||
@@ -238,6 +240,21 @@ document.getElementById('btn-retry-director')?.addEventListener('click', () => {
|
|||||||
loadDirector();
|
loadDirector();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
async function loadScaleData(bg) {
|
||||||
|
const maps = [];
|
||||||
|
const addMaps = (obj) => { if (obj) Object.keys(obj).forEach(k => maps.push(k)); };
|
||||||
|
addMaps(bg.dimensionMaps);
|
||||||
|
addMaps(bg.instancedMaps);
|
||||||
|
addMaps(bg.singleServerMaps);
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
maps.map(m => fetch(`/api/director/server_set_scale/${encodeURIComponent(m)}`).then(r => r.json()))
|
||||||
|
);
|
||||||
|
maps.forEach((m, i) => {
|
||||||
|
const r = results[i];
|
||||||
|
scaleData[m] = (r.status === 'fulfilled') ? r.value : { replicas: 0, partitions: [] };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function updateStats() {
|
function updateStats() {
|
||||||
const t = calcTotals();
|
const t = calcTotals();
|
||||||
document.getElementById('stat-players').textContent = t.total;
|
document.getElementById('stat-players').textContent = t.total;
|
||||||
@@ -301,6 +318,13 @@ function updateMapCards() {
|
|||||||
const nameSpan = summaryParts[i].querySelector('.name');
|
const nameSpan = summaryParts[i].querySelector('.name');
|
||||||
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
|
if (nameSpan) nameSpan.title = s.partition?.label || s.label || '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const repInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||||
|
if (repInput) {
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
|
repInput.value = sc.replicas;
|
||||||
|
repInput.max = sc.partitions.length || 1;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -381,7 +405,7 @@ function renderMaps() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function buildMapCard(mapName, mapData, type) {
|
function buildMapCard(mapName, mapData, type) {
|
||||||
const cfg = mapData.cfg || {};
|
const cfg = { ...(mapData.cfg || {}), ...(mapData.webOverrideCfg || {}) };
|
||||||
let serversHtml = '';
|
let serversHtml = '';
|
||||||
let configHtml = '';
|
let configHtml = '';
|
||||||
let summaryHtml = '';
|
let summaryHtml = '';
|
||||||
@@ -505,6 +529,7 @@ function buildDimensionConfig(mapName, cfg) {
|
|||||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||||
const phCap = cfg.playerHardCap ?? '';
|
const phCap = cfg.playerHardCap ?? '';
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
return `
|
return `
|
||||||
<div class="config-row">
|
<div class="config-row">
|
||||||
<div class="config-field">
|
<div class="config-field">
|
||||||
@@ -527,6 +552,10 @@ function buildDimensionConfig(mapName, cfg) {
|
|||||||
<label>Scale Throttle (s)</label>
|
<label>Scale Throttle (s)</label>
|
||||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="config-field">
|
||||||
|
<label>Replicas</label>
|
||||||
|
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||||
|
</div>
|
||||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
|
<button class="btn-apply-map" onclick="applyConfig('${mapName}','dimension', this)">Apply</button>
|
||||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -539,6 +568,7 @@ function buildInstancedConfig(mapName, cfg) {
|
|||||||
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
const autoScale = cfg.enableAutomaticInstanceScaling ?? false;
|
||||||
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
const throttle = cfg.instanceScalingThrottlingSeconds ?? 30;
|
||||||
const phCap = cfg.playerHardCap ?? '';
|
const phCap = cfg.playerHardCap ?? '';
|
||||||
|
const sc = scaleData[mapName] || { replicas: 1, partitions: [] };
|
||||||
return `
|
return `
|
||||||
<div class="config-row">
|
<div class="config-row">
|
||||||
<div class="config-field">
|
<div class="config-field">
|
||||||
@@ -561,6 +591,10 @@ function buildInstancedConfig(mapName, cfg) {
|
|||||||
<label>Scale Throttle (s)</label>
|
<label>Scale Throttle (s)</label>
|
||||||
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
<input type="number" id="cfg-${mapName}-throttle" value="${throttle}" min="1">
|
||||||
</div>
|
</div>
|
||||||
|
<div class="config-field">
|
||||||
|
<label>Replicas</label>
|
||||||
|
<input type="number" id="cfg-${mapName}-replicas" value="${sc.replicas}" min="0" max="${sc.partitions.length || 1}">
|
||||||
|
</div>
|
||||||
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
|
<button class="btn-apply-map" onclick="applyConfig('${mapName}','instanced', this)">Apply</button>
|
||||||
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
<button class="btn-clear-map" onclick="clearConfig('${mapName}', this)">Clear</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -625,23 +659,45 @@ async function applyConfig(mapName, type, btn) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/update_config', {
|
const resp = await csrfFetch('/api/director/update_config', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
btn.classList.remove('applying');
|
btn.classList.remove('applying');
|
||||||
btn.classList.add('applied');
|
btn.classList.add('applied');
|
||||||
btn.textContent = 'Applied!';
|
btn.textContent = 'Applied!';
|
||||||
setTimeout(() => {
|
|
||||||
btn.classList.remove('applied');
|
|
||||||
btn.textContent = 'Apply';
|
|
||||||
btn.disabled = false;
|
btn.disabled = false;
|
||||||
}, 2000);
|
|
||||||
|
const replicasInput = document.getElementById(`cfg-${mapName}-replicas`);
|
||||||
|
if (replicasInput && type !== 'single') {
|
||||||
|
const sc = scaleData[mapName] || { partitions: [], replicas: 1 };
|
||||||
|
const newReplicas = parseInt(replicasInput.value) || 1;
|
||||||
|
if (newReplicas !== sc.replicas) {
|
||||||
|
const partInput = document.getElementById(`cfg-${mapName}-partitions`);
|
||||||
|
let partitions = sc.partitions;
|
||||||
|
if (partInput) {
|
||||||
|
try { partitions = JSON.parse('[' + partInput.value + ']'); } catch(_){}
|
||||||
|
}
|
||||||
|
csrfFetch(`/api/director/server_set_scale/${encodeURIComponent(mapName)}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ replicas: newReplicas, partitions: partitions })
|
||||||
|
}).catch(() => {});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(() => { btn.textContent = 'Apply'; btn.classList.remove('applied'); loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
btn.classList.remove('applying');
|
btn.classList.remove('applying');
|
||||||
btn.textContent = 'Failed';
|
btn.textContent = 'Failed';
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Config apply error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
|
setTimeout(() => { btn.textContent = 'Apply'; btn.disabled = false; }, 2000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -650,15 +706,23 @@ async function clearConfig(mapName, btn) {
|
|||||||
btn.disabled = true;
|
btn.disabled = true;
|
||||||
btn.textContent = 'Clearing...';
|
btn.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/clear_config', {
|
const resp = await csrfFetch('/api/director/clear_config', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'text/plain' },
|
||||||
body: mapName
|
body: mapName
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
btn.textContent = 'Cleared!';
|
btn.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
btn.disabled = false;
|
||||||
|
setTimeout(() => { btn.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
btn.textContent = 'Failed';
|
btn.textContent = 'Failed';
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Config clear error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
|
setTimeout(() => { btn.textContent = 'Clear'; btn.disabled = false; }, 2000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -671,17 +735,24 @@ document.getElementById('btn-apply-world')?.addEventListener('click', async func
|
|||||||
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
|
ForceIsWorldClosingSoon: document.getElementById('force-world-closing').checked
|
||||||
};
|
};
|
||||||
try {
|
try {
|
||||||
const resp = await fetch('/api/director/character_transfer', {
|
const resp = await csrfFetch('/api/director/character_transfer', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
|
document.getElementById('world-status-msg').textContent = 'World status applied and persisted.';
|
||||||
this.textContent = 'Applied!';
|
this.textContent = 'Applied!';
|
||||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Apply'; }, 2000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Apply'; this.disabled = false;
|
this.textContent = 'Apply'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -691,12 +762,19 @@ document.getElementById('btn-clear-world')?.addEventListener('click', async func
|
|||||||
this.textContent = 'Clearing...';
|
this.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
|
document.getElementById('world-status-msg').textContent = 'World status overrides cleared.';
|
||||||
this.textContent = 'Cleared!';
|
this.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('world-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'World status error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Clear'; this.disabled = false;
|
this.textContent = 'Clear'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -716,12 +794,18 @@ document.getElementById('btn-apply-transfer')?.addEventListener('click', async f
|
|||||||
headers: { 'Content-Type': 'application/json' },
|
headers: { 'Content-Type': 'application/json' },
|
||||||
body: JSON.stringify(config)
|
body: JSON.stringify(config)
|
||||||
});
|
});
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
|
document.getElementById('transfer-status-msg').textContent = 'Transfer settings applied and persisted.';
|
||||||
this.textContent = 'Applied!';
|
this.textContent = 'Applied!';
|
||||||
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
setTimeout(() => { this.textContent = 'Apply'; this.disabled = false; }, 2000);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Apply'; this.disabled = false;
|
this.textContent = 'Apply'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -731,12 +815,19 @@ document.getElementById('btn-clear-transfer')?.addEventListener('click', async f
|
|||||||
this.textContent = 'Clearing...';
|
this.textContent = 'Clearing...';
|
||||||
try {
|
try {
|
||||||
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
const resp = await csrfFetch('/api/director/character_transfer_clear', { method: 'POST' });
|
||||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
if (!resp.ok) {
|
||||||
|
let errMsg = `HTTP ${resp.status}`;
|
||||||
|
try { const errData = await resp.json(); if (errData?.error) errMsg = errData.error; } catch(_) {}
|
||||||
|
throw new Error(errMsg);
|
||||||
|
}
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
|
document.getElementById('transfer-status-msg').textContent = 'Transfer settings cleared.';
|
||||||
this.textContent = 'Cleared!';
|
this.textContent = 'Cleared!';
|
||||||
setTimeout(() => { loadDirector(); }, 1500);
|
this.disabled = false;
|
||||||
|
setTimeout(() => { this.textContent = 'Clear'; loadDirector(); }, 1200);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
document.getElementById('transfer-status-msg').textContent = 'Error: ' + e.message;
|
||||||
|
const errDiv = document.getElementById('error-banner');
|
||||||
|
if (errDiv) { errDiv.textContent = 'Transfer error: ' + e.message; errDiv.style.display = 'block'; }
|
||||||
this.textContent = 'Clear'; this.disabled = false;
|
this.textContent = 'Clear'; this.disabled = false;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -14,7 +14,9 @@
|
|||||||
<span id="view-mode-badge" class="badge">View Mode</span>
|
<span id="view-mode-badge" class="badge">View Mode</span>
|
||||||
</div>
|
</div>
|
||||||
<div class="view-actions">
|
<div class="view-actions">
|
||||||
|
<button id="dl-btn" class="view-btn" onclick="downloadFile()">Download</button>
|
||||||
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
|
<button id="edit-btn" class="view-btn" onclick="toggleEdit()">Edit</button>
|
||||||
|
<button id="delete-btn" class="view-btn danger" onclick="deleteViewFile()">Delete</button>
|
||||||
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button>
|
<button id="save-btn" class="view-btn primary" style="display:none;" onclick="saveFile()">Save</button>
|
||||||
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
|
<button id="cancel-btn" class="view-btn" style="display:none;" onclick="cancelEdit()">Cancel</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -106,6 +108,53 @@ function cancelEdit() {
|
|||||||
badge.classList.remove('edit');
|
badge.classList.remove('edit');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function deleteViewFile() {
|
||||||
|
const name = filePath.split('/').pop();
|
||||||
|
if (!confirm(`Delete "${name}"? This cannot be undone.`)) return;
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('path', filePath);
|
||||||
|
const resp = await csrfFetch('/api/files/delete', { method: 'POST', body: form });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (data.success) {
|
||||||
|
window.close();
|
||||||
|
} else {
|
||||||
|
document.getElementById('view-error').textContent = 'Delete failed: ' + (data.error || 'Unknown');
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('view-error').textContent = 'Delete failed: ' + e.message;
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile() {
|
||||||
|
try {
|
||||||
|
const form = new FormData();
|
||||||
|
form.append('path', filePath);
|
||||||
|
const resp = await csrfFetch('/api/files/download', { method: 'POST', body: form });
|
||||||
|
const data = await resp.json();
|
||||||
|
if (!data.success) {
|
||||||
|
document.getElementById('view-error').textContent = 'Error: ' + (data.error || 'Download failed');
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const byteChars = atob(data.content);
|
||||||
|
const bytes = new Uint8Array(byteChars.length);
|
||||||
|
for (let i = 0; i < byteChars.length; i++) bytes[i] = byteChars.charCodeAt(i);
|
||||||
|
const blob = new Blob([bytes]);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
const a = document.createElement('a');
|
||||||
|
a.href = url; a.download = data.filename;
|
||||||
|
document.body.appendChild(a); a.click();
|
||||||
|
document.body.removeChild(a);
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
} catch (e) {
|
||||||
|
document.getElementById('view-error').textContent = 'Request failed: ' + e.message;
|
||||||
|
document.getElementById('view-error').style.display = 'block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function saveFile() {
|
async function saveFile() {
|
||||||
const saveBtn = document.getElementById('save-btn');
|
const saveBtn = document.getElementById('save-btn');
|
||||||
const success = document.getElementById('view-success');
|
const success = document.getElementById('view-success');
|
||||||
|
|||||||
+266
-128
@@ -3,49 +3,79 @@
|
|||||||
{% block content %}
|
{% block content %}
|
||||||
|
|
||||||
<div class="page-header">
|
<div class="page-header">
|
||||||
<h1>File Browser</h1>
|
<h1>File Manager</h1>
|
||||||
<p>Browse server files via SSH</p>
|
<p>Browse, edit, upload, and download server files</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="card">
|
<div class="fm-layout">
|
||||||
<div class="card-body">
|
<div class="fm-panel">
|
||||||
<div class="fb-toolbar">
|
<div class="fm-toolbar">
|
||||||
<div class="fb-breadcrumb" id="fb-breadcrumb"></div>
|
<select id="fm-pod-select" onchange="selectPod()" style="padding:6px 8px;background:var(--bg-card);color:var(--text);border:1px solid var(--border);border-radius:4px;font-size:12px;max-width:180px;">
|
||||||
<div class="fb-actions">
|
<option value="">Loading...</option>
|
||||||
<button id="fb-refresh-btn" class="fb-btn">Refresh</button>
|
</select>
|
||||||
|
<span style="flex:1;"></span>
|
||||||
|
<input type="file" id="fm-upload-input" style="display:none;" onchange="uploadFile()">
|
||||||
|
<button class="fm-btn" onclick="document.getElementById('fm-upload-input').click()">⇪ Upload</button>
|
||||||
|
<button class="fm-btn" onclick="loadFiles(currentPath)">↻ Refresh</button>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="fm-breadcrumb" id="fm-breadcrumb"></div>
|
||||||
|
<div id="fm-error" class="error-banner danger" style="display:none;"></div>
|
||||||
|
<div id="fm-file-list" class="fm-file-list"></div>
|
||||||
</div>
|
</div>
|
||||||
<div id="fb-error" class="error-banner danger" style="display:none;"></div>
|
<div class="fm-viewer" id="fm-viewer">
|
||||||
<div id="fb-file-list" class="fb-file-list"></div>
|
<div id="fm-viewer-empty" class="fm-viewer-empty">Select a file to view or edit</div>
|
||||||
|
<div id="fm-viewer-toolbar" class="fm-viewer-toolbar" style="display:none;">
|
||||||
|
<span id="fm-viewer-name" style="font-size:13px;color:var(--text);"></span>
|
||||||
|
<span style="flex:1;"></span>
|
||||||
|
<button class="fm-btn" onclick="toggleEdit()" id="fm-edit-btn">✎ Edit</button>
|
||||||
|
<button class="fm-btn" onclick="saveFile()" id="fm-save-btn" style="display:none;">💾 Save</button>
|
||||||
|
<button class="fm-btn" onclick="cancelEdit()" id="fm-cancel-btn" style="display:none;">Cancel</button>
|
||||||
|
<button class="fm-btn" onclick="downloadCurrent()">📥 Download</button>
|
||||||
|
<button class="fm-btn danger" onclick="deleteCurrent()">🗑 Delete</button>
|
||||||
|
</div>
|
||||||
|
<pre id="fm-viewer-content" class="fm-viewer-content" style="display:none;"></pre>
|
||||||
|
<textarea id="fm-editor-content" class="fm-editor-content" style="display:none;" spellcheck="false"></textarea>
|
||||||
|
<div id="fm-viewer-status" class="error-banner success" style="display:none;"></div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.fb-toolbar { display: flex; justify-content: space-between; align-items: center; padding: 12px; background: var(--bg-hover); border-radius: 6px; margin-bottom: 12px; }
|
.fm-layout { display: grid; grid-template-columns: 340px 1fr; gap: 16px; min-height: calc(100vh - 200px); }
|
||||||
.fb-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; }
|
.fm-panel { min-height: 0; display: flex; flex-direction: column; }
|
||||||
.fb-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; font-size: 13px; }
|
.fm-toolbar { display: flex; gap: 8px; margin-bottom: 10px; }
|
||||||
.fb-breadcrumb span:hover { text-decoration: underline; }
|
.fm-btn { padding: 6px 12px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 12px; white-space: nowrap; }
|
||||||
.fb-breadcrumb .sep { color: var(--text-muted); cursor: default; font-size: 11px; }
|
.fm-btn:hover { background: var(--bg-hover); }
|
||||||
.fb-breadcrumb .sep:hover { text-decoration: none; }
|
.fm-btn.danger { color: var(--danger); border-color: var(--danger); }
|
||||||
.fb-breadcrumb .current { color: var(--text); cursor: default; }
|
.fm-breadcrumb { display: flex; gap: 4px; align-items: center; flex-wrap: wrap; font-size: 12px; margin-bottom: 8px; min-height: 20px; }
|
||||||
.fb-breadcrumb .current:hover { text-decoration: none; }
|
.fm-breadcrumb span { cursor: pointer; color: var(--primary); font-family: monospace; }
|
||||||
.fb-actions { display: flex; gap: 8px; }
|
.fm-breadcrumb span:hover { text-decoration: underline; }
|
||||||
.fb-btn { padding: 6px 14px; background: var(--bg-card); color: var(--text); border: 1px solid var(--border); border-radius: 4px; cursor: pointer; font-size: 13px; }
|
.fm-breadcrumb .sep { color: var(--text-muted); cursor: default; }
|
||||||
.fb-btn:hover { background: var(--bg-hover); }
|
.fm-breadcrumb .sep:hover { text-decoration: none; }
|
||||||
.fb-file-list { }
|
.fm-breadcrumb .current { color: var(--text); cursor: default; }
|
||||||
.fb-item { display: flex; align-items: center; padding: 8px 12px; border-bottom: 1px solid var(--border); cursor: pointer; }
|
.fm-breadcrumb .current:hover { text-decoration: none; }
|
||||||
.fb-item:hover { background: var(--bg-hover); }
|
.fm-file-list { flex: 1; overflow-y: auto; border: 1px solid var(--border); border-radius: 6px; }
|
||||||
.fb-item:last-child { border-bottom: none; }
|
.fm-item { display: flex; align-items: center; padding: 6px 10px; border-bottom: 1px solid var(--border); cursor: pointer; font-size: 12px; }
|
||||||
.fb-icon { width: 24px; text-align: center; margin-right: 8px; font-size: 16px; }
|
.fm-item:hover { background: var(--bg-hover); }
|
||||||
.fb-icon.dir { color: var(--accent); }
|
.fm-item.selected { background: var(--bg-hover); border-left: 3px solid var(--primary); }
|
||||||
.fb-name { flex: 1; font-size: 13px; }
|
.fm-item:last-child { border-bottom: none; }
|
||||||
.fb-name.dir { color: var(--accent); font-weight: 500; cursor: pointer; }
|
.fm-icon { width: 20px; text-align: center; margin-right: 6px; font-size: 14px; flex-shrink: 0; }
|
||||||
.fb-name.file { cursor: pointer; }
|
.fm-icon.dir { color: var(--accent); }
|
||||||
.fb-name:hover { text-decoration: underline; }
|
.fm-fname { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||||
.fb-size { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 70px; text-align: right; }
|
.fm-fname.dir { color: var(--accent); font-weight: 500; }
|
||||||
.fb-date { color: var(--text-muted); font-size: 12px; margin-right: 12px; min-width: 130px; }
|
.fm-fsize { color: var(--text-muted); font-size: 11px; margin-left: 8px; flex-shrink: 0; }
|
||||||
.fb-perms { color: var(--text-muted); font-size: 11px; font-family: monospace; margin-right: 12px; min-width: 80px; }
|
.fm-delete-btn { padding: 2px 6px; background: none; border: none; color: var(--danger); cursor: pointer; font-size: 13px; flex-shrink: 0; }
|
||||||
.fb-empty { padding: 20px; text-align: center; color: var(--text-muted); }
|
.fm-delete-btn:hover { background: var(--bg-hover); border-radius: 3px; }
|
||||||
|
.fm-empty { padding: 20px; text-align: center; color: var(--text-muted); font-size: 12px; }
|
||||||
|
.fm-viewer { display: flex; flex-direction: column; border: 1px solid var(--border); border-radius: 6px; min-height: 0; }
|
||||||
|
.fm-viewer-toolbar { display: flex; align-items: center; gap: 6px; padding: 8px 12px; border-bottom: 1px solid var(--border); background: var(--bg-hover); border-radius: 6px 6px 0 0; }
|
||||||
|
.fm-viewer-empty { flex: 1; display: flex; align-items: center; justify-content: center; color: var(--text-muted); font-size: 14px; }
|
||||||
|
.fm-viewer-content { flex: 1; margin: 0; padding: 12px; overflow: auto; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; white-space: pre-wrap; word-break: break-all; background: var(--bg); color: var(--text); border: none; border-radius: 0 0 6px 6px; }
|
||||||
|
.fm-editor-content { flex: 1; padding: 12px; background: var(--bg); color: var(--text); border: none; font-family: 'Consolas','Courier New',monospace; font-size: 12px; line-height: 1.5; resize: none; outline: none; border-radius: 0 0 6px 6px; }
|
||||||
|
|
||||||
|
@media (max-width: 768px) {
|
||||||
|
.fm-layout { grid-template-columns: 1fr; grid-template-rows: auto 1fr; }
|
||||||
|
.fm-viewer { min-height: 300px; }
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
@@ -53,118 +83,226 @@
|
|||||||
{% block scripts %}
|
{% block scripts %}
|
||||||
<script>
|
<script>
|
||||||
let currentPath = '/srv';
|
let currentPath = '/srv';
|
||||||
|
let currentFile = null;
|
||||||
|
let currentPod = '';
|
||||||
|
let originalContent = '';
|
||||||
|
|
||||||
function formatSize(sizeStr) {
|
async function loadPods() {
|
||||||
if (!sizeStr || sizeStr === '-') return '';
|
const sel = document.getElementById('fm-pod-select');
|
||||||
const bytes = parseInt(sizeStr);
|
try {
|
||||||
if (isNaN(bytes)) return sizeStr;
|
const r = await csrfFetch('/api/files/pods');
|
||||||
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
const d = await r.json();
|
||||||
let i = 0;
|
sel.innerHTML = '';
|
||||||
let size = bytes;
|
if (d.success && d.pods) {
|
||||||
while (size >= 1024 && i < units.length - 1) { size /= 1024; i++; }
|
d.pods.forEach(p => { const o = document.createElement('option'); o.value = p; o.textContent = p; sel.appendChild(o); });
|
||||||
return size.toFixed(i === 0 ? 0 : 1) + ' ' + units[i];
|
}
|
||||||
|
// Default to fb-deploy pod if available
|
||||||
|
const fbOpt = Array.from(sel.options).find(o => o.value.includes('fb-deploy'));
|
||||||
|
if (fbOpt) { fbOpt.selected = true; currentPod = fbOpt.value; }
|
||||||
|
else if (sel.options.length) { sel.options[0].selected = true; currentPod = sel.options[0].value; }
|
||||||
|
} catch(e) { sel.innerHTML = '<option>Error loading pods</option>'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectPod() {
|
||||||
|
currentPod = document.getElementById('fm-pod-select').value;
|
||||||
|
currentFile = null;
|
||||||
|
hideViewer();
|
||||||
|
loadFiles(currentPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildForm(path) {
|
||||||
|
const f = new FormData();
|
||||||
|
f.append('path', path);
|
||||||
|
if (currentPod) f.append('pod', currentPod);
|
||||||
|
return f;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(s) {
|
||||||
|
if (!s || s === '-') return '';
|
||||||
|
const b = parseInt(s); if (isNaN(b)) return s;
|
||||||
|
const u = ['B','KB','MB','GB','TB']; let i = 0, sz = b;
|
||||||
|
while (sz >= 1024 && i < u.length-1) { sz /= 1024; i++; }
|
||||||
|
return sz.toFixed(i===0?0:1) + ' ' + u[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
function renderBreadcrumb(path) {
|
function renderBreadcrumb(path) {
|
||||||
const parts = path.split('/').filter(Boolean);
|
const p = path.split('/').filter(Boolean);
|
||||||
let html = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
let h = '<span onclick="loadFiles(\'/\')">📁 /</span>';
|
||||||
let buildPath = '';
|
let b = '';
|
||||||
for (let i = 0; i < parts.length; i++) {
|
for (let i=0;i<p.length;i++) {
|
||||||
buildPath += '/' + parts[i];
|
b += '/'+p[i];
|
||||||
const isLast = i === parts.length - 1;
|
h += i===p.length-1
|
||||||
if (isLast) {
|
? '<span class="sep">/</span><span class="current">'+p[i]+'</span>'
|
||||||
html += `<span class="sep">/</span><span class="current">${parts[i]}</span>`;
|
: '<span class="sep">/</span><span onclick="loadFiles(\''+b.replace(/'/g,"\\'")+'\')">'+p[i]+'</span>';
|
||||||
} else {
|
|
||||||
html += `<span class="sep">/</span><span onclick="loadFiles('${buildPath.replace(/'/g, "\\'")}')">${parts[i]}</span>`;
|
|
||||||
}
|
}
|
||||||
}
|
return h;
|
||||||
return html;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function selectFile(path) { currentFile = path; }
|
||||||
|
|
||||||
async function loadFiles(path) {
|
async function loadFiles(path) {
|
||||||
currentPath = path;
|
currentPath = path; currentFile = null;
|
||||||
const list = document.getElementById('fb-file-list');
|
document.getElementById('fm-error').style.display = 'none';
|
||||||
const error = document.getElementById('fb-error');
|
document.getElementById('fm-breadcrumb').innerHTML = renderBreadcrumb(path);
|
||||||
const breadcrumb = document.getElementById('fb-breadcrumb');
|
const list = document.getElementById('fm-file-list');
|
||||||
error.style.display = 'none';
|
list.innerHTML = '<div class="fm-empty">Loading...</div>';
|
||||||
list.innerHTML = '<div class="fb-empty">Loading...</div>';
|
|
||||||
breadcrumb.innerHTML = renderBreadcrumb(path);
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const form = new FormData();
|
const f = buildForm(path);
|
||||||
form.append('path', path);
|
const r = await csrfFetch('/api/files/list',{method:'POST',body:f});
|
||||||
const resp = await csrfFetch('/api/files/list', { method: 'POST', body: form });
|
const d = await r.json();
|
||||||
const data = await resp.json();
|
if (!d.success) { list.innerHTML = ''; showErr(d.error); return; }
|
||||||
if (!data.success) {
|
const files = (d.files||[]).sort((a,b)=>a.is_dir!==b.is_dir?a.is_dir?-1:1:a.name.localeCompare(b.name));
|
||||||
list.innerHTML = '';
|
if (!files.length) { list.innerHTML = '<div class="fm-empty">Empty directory</div>'; return; }
|
||||||
error.textContent = 'Error: ' + (data.error || 'Failed to list directory');
|
let h = '';
|
||||||
error.style.display = 'block';
|
for (const x of files) {
|
||||||
return;
|
const fp = (path==='/'?'':path)+'/'+x.name;
|
||||||
}
|
const sp = fp.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
const files = data.files || [];
|
const sn = x.name.replace(/\\/g,'\\\\').replace(/'/g,"\\'");
|
||||||
if (files.length === 0) {
|
const icon = x.is_dir ? '📁' : getIcon(x.name);
|
||||||
list.innerHTML = '<div class="fb-empty">Empty directory</div>';
|
const action = x.is_dir ? `loadFiles('${sp}')` : `openFile('${sp}','${sn}')`;
|
||||||
return;
|
h += `<div class="fm-item" onclick="${action}">
|
||||||
}
|
<span class="fm-icon ${x.is_dir?'dir':''}">${icon}</span>
|
||||||
const sorted = files.sort((a, b) => {
|
<span class="fm-fname ${x.is_dir?'dir':''}">${x.name}</span>
|
||||||
if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1;
|
<span class="fm-fsize">${formatSize(x.size)}</span>
|
||||||
return a.name.localeCompare(b.name);
|
<button class="fm-delete-btn" onclick="event.stopPropagation();deleteFile('${sp}','${sn}')" title="Delete">🗑</button>
|
||||||
});
|
|
||||||
let html = '';
|
|
||||||
for (const f of sorted) {
|
|
||||||
const icon = f.is_dir ? '📁' : getFileIcon(f.name);
|
|
||||||
const iconClass = f.is_dir ? 'dir' : '';
|
|
||||||
const nameClass = f.is_dir ? 'dir' : 'file';
|
|
||||||
const fullPath = (path === '/' ? '' : path) + '/' + f.name;
|
|
||||||
const safePath = fullPath.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
||||||
const safeName = f.name.replace(/\\/g, '\\\\').replace(/'/g, "\\'");
|
|
||||||
const clickAction = f.is_dir
|
|
||||||
? `loadFiles('${safePath}')`
|
|
||||||
: `viewFile('${safePath}', '${safeName}')`;
|
|
||||||
html += `<div class="fb-item" onclick="${clickAction}">
|
|
||||||
<span class="fb-icon ${iconClass}">${icon}</span>
|
|
||||||
<span class="fb-name ${nameClass}">${f.name}</span>
|
|
||||||
<span class="fb-perms">${f.perms || ''}</span>
|
|
||||||
<span class="fb-size">${formatSize(f.size)}</span>
|
|
||||||
<span class="fb-date">${f.date || ''}</span>
|
|
||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
list.innerHTML = html;
|
list.innerHTML = h;
|
||||||
} catch (e) {
|
} catch(e) { list.innerHTML = ''; showErr(e.message); }
|
||||||
list.innerHTML = '';
|
|
||||||
error.textContent = 'Request failed: ' + e.message;
|
|
||||||
error.style.display = 'block';
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function getFileIcon(name) {
|
function getIcon(name) {
|
||||||
|
const icons = {log:'📝',txt:'📄',ini:'⚙',cfg:'⚙',json:'𞇤',xml:'📄',yaml:'📄',yml:'📄',sh:'⚙',ps1:'⚙',bat:'⚙',cmd:'⚙',zip:'📦',gz:'📦',tar:'📦',sql:'🗃',db:'🗃',png:'🌄',jpg:'🌄',jpeg:'🌄',gif:'🌄',svg:'🌄',pdf:'📖',md:'📖',html:'🌐',css:'🎨',js:'📜',py:'📜'};
|
||||||
|
return icons[name.split('.').pop().toLowerCase()] || '📄';
|
||||||
|
}
|
||||||
|
|
||||||
|
const textExts = ['log','txt','ini','cfg','json','xml','yaml','yml','sh','ps1','bat','cmd','md','html','css','js','py','conf','env'];
|
||||||
|
|
||||||
|
function openFile(path, name) {
|
||||||
|
currentFile = path;
|
||||||
const ext = name.split('.').pop().toLowerCase();
|
const ext = name.split('.').pop().toLowerCase();
|
||||||
const icons = {
|
if (!textExts.includes(ext)) { downloadFile(path); return; }
|
||||||
log: '📝', txt: '📄', ini: '⚙', cfg: '⚙',
|
|
||||||
json: '𞇤', xml: '📄', yaml: '📄', yml: '📄',
|
document.getElementById('fm-viewer-empty').style.display = 'none';
|
||||||
sh: '⚙', ps1: '⚙', bat: '⚙', cmd: '⚙',
|
document.getElementById('fm-viewer-status').style.display = 'none';
|
||||||
zip: '📦', gz: '📦', tar: '📦',
|
document.getElementById('fm-viewer-content').style.display = 'block';
|
||||||
sql: '🗃', db: '🗃', sqlite: '🗃',
|
document.getElementById('fm-editor-content').style.display = 'none';
|
||||||
png: '🌄', jpg: '🌄', jpeg: '🌄', gif: '🌄', svg: '🌄',
|
document.getElementById('fm-edit-btn').style.display = 'inline-block';
|
||||||
pdf: '📖',
|
document.getElementById('fm-save-btn').style.display = 'none';
|
||||||
md: '📖', html: '🌐', css: '🎨', js: '📜',
|
document.getElementById('fm-cancel-btn').style.display = 'none';
|
||||||
py: '📜',
|
document.getElementById('fm-viewer-toolbar').style.display = 'flex';
|
||||||
};
|
document.getElementById('fm-viewer-name').textContent = name;
|
||||||
return icons[ext] || '📄';
|
|
||||||
|
const content = document.getElementById('fm-viewer-content');
|
||||||
|
content.textContent = 'Loading...';
|
||||||
|
fetch('/api/files/view?path=' + encodeURIComponent(path) + '&pod=' + encodeURIComponent(currentPod))
|
||||||
|
.then(r=>r.json()).then(d=>{
|
||||||
|
if(!d.success){content.textContent='Error: '+(d.error||'Load failed');return;}
|
||||||
|
originalContent = d.content;
|
||||||
|
content.textContent = d.content;
|
||||||
|
}).catch(e=>{content.textContent='Error: '+e.message;});
|
||||||
|
|
||||||
|
// Highlight selected file
|
||||||
|
document.querySelectorAll('.fm-item').forEach(el=>el.classList.remove('selected'));
|
||||||
}
|
}
|
||||||
|
|
||||||
function viewFile(path, name) {
|
function toggleEdit() {
|
||||||
const ext = name.split('.').pop().toLowerCase();
|
document.getElementById('fm-viewer-content').style.display = 'none';
|
||||||
const textExts = ['log', 'txt', 'ini', 'cfg', 'json', 'xml', 'yaml', 'yml', 'sh', 'ps1', 'bat', 'cmd', 'md', 'html', 'css', 'js', 'py', 'conf', 'env'];
|
document.getElementById('fm-editor-content').style.display = 'block';
|
||||||
if (textExts.includes(ext)) {
|
document.getElementById('fm-editor-content').value = originalContent;
|
||||||
window.open(`/files/view?path=${encodeURIComponent(path)}`, '_blank');
|
document.getElementById('fm-editor-content').focus();
|
||||||
} else {
|
document.getElementById('fm-edit-btn').style.display = 'none';
|
||||||
alert('File preview is only available for text files. Download via SSH to view this file.');
|
document.getElementById('fm-save-btn').style.display = 'inline-block';
|
||||||
}
|
document.getElementById('fm-cancel-btn').style.display = 'inline-block';
|
||||||
}
|
}
|
||||||
|
|
||||||
document.getElementById('fb-refresh-btn')?.addEventListener('click', () => loadFiles(currentPath));
|
function cancelEdit() {
|
||||||
|
document.getElementById('fm-editor-content').style.display = 'none';
|
||||||
|
document.getElementById('fm-viewer-content').style.display = 'block';
|
||||||
|
document.getElementById('fm-edit-btn').style.display = 'inline-block';
|
||||||
|
document.getElementById('fm-save-btn').style.display = 'none';
|
||||||
|
document.getElementById('fm-cancel-btn').style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveFile() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
const content = document.getElementById('fm-editor-content').value;
|
||||||
|
const btn = document.getElementById('fm-save-btn');
|
||||||
|
btn.textContent = 'Saving...'; btn.disabled = true;
|
||||||
|
try {
|
||||||
|
const f = buildForm(currentFile); f.append('content', content);
|
||||||
|
const r = await csrfFetch('/api/files/save',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(!d.success){showErr(d.error);return;}
|
||||||
|
originalContent = content;
|
||||||
|
document.getElementById('fm-viewer-content').textContent = content;
|
||||||
|
cancelEdit();
|
||||||
|
document.getElementById('fm-viewer-status').textContent = 'Saved'; document.getElementById('fm-viewer-status').style.display='block';
|
||||||
|
setTimeout(()=>document.getElementById('fm-viewer-status').style.display='none',2000);
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
btn.textContent = '💾 Save'; btn.disabled = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadCurrent() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
downloadFile(currentFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteCurrent() {
|
||||||
|
if (!currentFile) return;
|
||||||
|
const name = currentFile.split('/').pop();
|
||||||
|
if (!confirm('Delete "'+name+'"? This cannot be undone.')) return;
|
||||||
|
try {
|
||||||
|
const f = buildForm(currentFile);
|
||||||
|
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';loadFiles(currentPath);}
|
||||||
|
else showErr(d.error||'Delete failed');
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadFile() {
|
||||||
|
const input = document.getElementById('fm-upload-input');
|
||||||
|
const file = input.files[0]; if(!file)return;
|
||||||
|
const f = buildForm(currentPath); f.append('file',file);
|
||||||
|
try {
|
||||||
|
const r = await csrfFetch('/api/files/upload',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){input.value='';loadFiles(currentPath);}
|
||||||
|
else showErr('Upload: '+(d.error||'Unknown'));
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function downloadFile(path) {
|
||||||
|
try {
|
||||||
|
const f = buildForm(path);
|
||||||
|
const r = await csrfFetch('/api/files/download',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(!d.success){alert('Download failed: '+(d.error||'Unknown'));return;}
|
||||||
|
const chars=atob(d.content); const bytes=new Uint8Array(chars.length);
|
||||||
|
for(let i=0;i<chars.length;i++)bytes[i]=chars.charCodeAt(i);
|
||||||
|
const blob=new Blob([bytes]),url=URL.createObjectURL(blob);
|
||||||
|
const a=document.createElement('a');a.href=url;a.download=d.filename;
|
||||||
|
document.body.appendChild(a);a.click();document.body.removeChild(a);URL.revokeObjectURL(url);
|
||||||
|
} catch(e) { alert('Download failed: '+e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteFile(path,name) {
|
||||||
|
if(!confirm('Delete "'+name+'"? This cannot be undone.'))return;
|
||||||
|
try {
|
||||||
|
const f = buildForm(path);
|
||||||
|
const r = await csrfFetch('/api/files/delete',{method:'POST',body:f});
|
||||||
|
const d = await r.json();
|
||||||
|
if(d.success){ if(currentFile===path){currentFile=null;document.getElementById('fm-viewer-toolbar').style.display='none';document.getElementById('fm-viewer-content').style.display='none';document.getElementById('fm-viewer-empty').style.display='flex';} loadFiles(currentPath); }
|
||||||
|
else showErr(d.error||'Delete failed');
|
||||||
|
} catch(e) { showErr(e.message); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function showErr(msg) { const e=document.getElementById('fm-error');e.textContent='Error: '+msg;e.style.display='block'; }
|
||||||
|
function hideErr() { document.getElementById('fm-error').style.display='none'; }
|
||||||
|
function hideViewer() { document.getElementById('fm-viewer-toolbar').style.display='none'; document.getElementById('fm-viewer-content').style.display='none'; document.getElementById('fm-editor-content').style.display='none'; document.getElementById('fm-viewer-empty').style.display='flex'; }
|
||||||
|
|
||||||
|
loadPods();
|
||||||
loadFiles('/srv');
|
loadFiles('/srv');
|
||||||
</script>
|
</script>
|
||||||
{% endblock %}
|
{% endblock %}
|
||||||
+275
-658
File diff suppressed because it is too large.
Load diff
Loaded 100 of 101 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user