Initial release - Dune Awakening Dashboard beta
This commit is contained in:
commit
59cc98133c
51 files changed
+8428
No files matched your search
@@ -0,0 +1 @@
|
||||
"""Services package"""
|
||||
@@ -0,0 +1,393 @@
|
||||
"""Admin service - ban, kick, unban, vitals, IP detection"""
|
||||
|
||||
import re
|
||||
import time
|
||||
import threading
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class AdminService:
|
||||
def __init__(self, db_service, ssh_service):
|
||||
self.db = db_service
|
||||
self.ssh = ssh_service
|
||||
|
||||
def ban_player(self, player_id, duration=0, reason='', note=''):
|
||||
try:
|
||||
duration_int = int(duration) if duration else 0
|
||||
except (ValueError, TypeError):
|
||||
duration_int = 0
|
||||
|
||||
player_row = self.db.query(
|
||||
"SELECT ps.account_id, ps.character_name FROM dune.player_state ps WHERE ps.player_controller_id = %s",
|
||||
[player_id], one=True
|
||||
)
|
||||
|
||||
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'
|
||||
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
|
||||
if account_id:
|
||||
if duration_int == 0:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.bans (player_id, account_id, reason, note, duration, banned_at, expires_at, active)
|
||||
VALUES (%s, %s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||
ON CONFLICT (player_id) DO UPDATE SET
|
||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||
note = EXCLUDED.note, duration = EXCLUDED.duration,
|
||||
banned_at = NOW(), expires_at = NULL, active = TRUE
|
||||
""", [player_id, account_id, reason, note, duration_int])
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.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)
|
||||
ON CONFLICT (player_id) DO UPDATE SET
|
||||
account_id = EXCLUDED.account_id, reason = EXCLUDED.reason,
|
||||
note = EXCLUDED.note, duration = EXCLUDED.duration,
|
||||
banned_at = NOW(), expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||
""", [player_id, account_id, reason, note, duration_int, duration_int, duration_int])
|
||||
else:
|
||||
if duration_int == 0:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||
VALUES (%s, %s, %s, %s, NOW(), NULL, TRUE)
|
||||
ON CONFLICT (player_id) DO UPDATE SET
|
||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||
duration = EXCLUDED.duration, banned_at = NOW(),
|
||||
expires_at = NULL, active = TRUE
|
||||
""", [player_id, reason, note, duration_int])
|
||||
else:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.bans (player_id, reason, note, duration, banned_at, expires_at, active)
|
||||
VALUES (%s, %s, %s, %s, NOW(), NOW() + INTERVAL '1 minute' * %s, TRUE)
|
||||
ON CONFLICT (player_id) DO UPDATE SET
|
||||
reason = EXCLUDED.reason, note = EXCLUDED.note,
|
||||
duration = EXCLUDED.duration, banned_at = NOW(),
|
||||
expires_at = NOW() + INTERVAL '1 minute' * %s, active = TRUE
|
||||
""", [player_id, reason, note, duration_int, duration_int, duration_int])
|
||||
|
||||
conn.commit()
|
||||
return True, f"Player {player_name} banned for {duration_int} minutes"
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to ban player {player_id}: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def unban_player(self, player_id):
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("DELETE FROM dune.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])
|
||||
account_row = cur.fetchone()
|
||||
account_id = account_row[0] if account_row else None
|
||||
|
||||
ips_to_unblock = []
|
||||
if account_id:
|
||||
all_ips = self.db.query("""
|
||||
SELECT ip_address FROM dune.player_ips
|
||||
WHERE player_id IN (SELECT player_controller_id FROM dune.player_state WHERE account_id = %s)
|
||||
""", [account_id]) or []
|
||||
ips_to_unblock = [r.get('ip_address') for r in all_ips if r.get('ip_address')]
|
||||
else:
|
||||
ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True)
|
||||
if ip_row and ip_row.get('ip_address'):
|
||||
ips_to_unblock.append(ip_row.get('ip_address'))
|
||||
|
||||
cur.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes) VALUES (%s, 'unban', 'Manual unban', 0)", [player_id])
|
||||
conn.commit()
|
||||
|
||||
for ip in ips_to_unblock:
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null')
|
||||
|
||||
return True, f"Player unbanned. Cleared {len(ips_to_unblock)} IP block(s)."
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to unban player {player_id}: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def kick_player(self, player_id):
|
||||
player = self.db.query("""
|
||||
SELECT ps.character_name, a.map FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE ps.player_controller_id = %s
|
||||
""", [player_id], one=True)
|
||||
|
||||
if not player:
|
||||
return False, "Player not found"
|
||||
|
||||
player_name = player.get('character_name', 'Unknown')
|
||||
ip_row = self.db.query("SELECT ip_address FROM dune.player_ips WHERE player_id = %s", [player_id], one=True)
|
||||
player_ip = ip_row.get('ip_address') if ip_row else None
|
||||
|
||||
if not player_ip:
|
||||
return False, "Player IP not known. Detect IPs first."
|
||||
|
||||
def temporary_block(ip):
|
||||
self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP')
|
||||
time.sleep(60)
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP')
|
||||
|
||||
thread = threading.Thread(target=temporary_block, args=(player_ip,), daemon=True)
|
||||
thread.start()
|
||||
|
||||
self.db.execute("INSERT INTO dune.player_actions (player_id, action_type, reason, duration_minutes, ip_address) VALUES (%s, 'kick', 'Temporary kick', 1, %s)", [player_id, player_ip])
|
||||
|
||||
return True, f"Player {player_name} kicked (IP {player_ip} blocked for 60 seconds)"
|
||||
|
||||
def edit_vitals(self, pawn_id, current_health=None, max_health=None, current_hydration=None, current_spice=None):
|
||||
if pawn_id is None or current_hydration is None or current_spice is None:
|
||||
return False, "Missing parameters"
|
||||
|
||||
controller_row = self.db.query(
|
||||
"SELECT player_controller_id FROM dune.player_state WHERE player_pawn_id = %s LIMIT 1",
|
||||
[pawn_id], one=True
|
||||
)
|
||||
if controller_row:
|
||||
from app.services.player import PlayerService
|
||||
ps = PlayerService(self.db)
|
||||
if ps.is_online(controller_row['player_controller_id']):
|
||||
return False, "Player must be offline to edit vitals. Log out first."
|
||||
|
||||
health = max(0.0, float(current_health)) if current_health is not None else None
|
||||
max_h = max(0.0, float(max_health)) if max_health is not None else None
|
||||
hydration = max(0.0, float(current_hydration))
|
||||
spice = max(0.0, float(current_spice))
|
||||
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
if health is not None:
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)) WHERE id = %s",
|
||||
[health, pawn_id]
|
||||
)
|
||||
if max_h is not None:
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET properties = jsonb_set(properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)) WHERE id = %s",
|
||||
[max_h, pawn_id]
|
||||
)
|
||||
cur.execute(
|
||||
"UPDATE dune.actors SET gas_attributes = jsonb_set("
|
||||
" jsonb_set(jsonb_set(jsonb_set(gas_attributes, "
|
||||
" '{DuneHydrationAttributeSet,CurrentHydration,CurrentValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneHydrationAttributeSet,CurrentHydration,BaseValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneSpiceAddictionAttributeSet,CurrentSpice,CurrentValue}', to_jsonb(%s::float)), "
|
||||
" '{DuneSpiceAddictionAttributeSet,CurrentSpice,BaseValue}', to_jsonb(%s::float)) "
|
||||
"WHERE id = %s",
|
||||
[hydration, hydration, spice, spice, pawn_id]
|
||||
)
|
||||
conn.commit()
|
||||
return True, {"health": health, "max_health": max_h, "hydration": hydration, "spice": spice}
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to edit vitals for pawn {pawn_id}: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def detect_player_ips(self, namespace):
|
||||
out, err, rc = self.ssh.run(f'sudo kubectl get pods -n {namespace} -o name 2>/dev/null')
|
||||
if rc != 0 or not out:
|
||||
return False, "Failed to list pods"
|
||||
|
||||
game_pods = []
|
||||
for line in out.strip().split('\n'):
|
||||
pod = line.replace('pod/', '').strip()
|
||||
if '-sg-' in pod and '-pod-' in pod:
|
||||
map_name = pod.split('-sg-')[-1].split('-pod-')[0] if '-sg-' in pod else 'Unknown'
|
||||
game_pods.append((pod, map_name))
|
||||
|
||||
if not game_pods:
|
||||
return False, "No game server pods found"
|
||||
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
updated = 0
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
|
||||
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'
|
||||
out_logs, err_logs, rc_logs = self.ssh.run(cmd)
|
||||
if not out_logs:
|
||||
continue
|
||||
|
||||
log_files = [l.strip() for l in out_logs.strip().split('\n') if l.strip()]
|
||||
for log_file in log_files:
|
||||
cat_cmd = f'sudo kubectl exec -n {namespace} {pod_name} -- cat "{log_file}" 2>/dev/null'
|
||||
out, err, rc = self.ssh.run(cat_cmd)
|
||||
if not out:
|
||||
continue
|
||||
|
||||
ip_to_player = {}
|
||||
current_ip = None
|
||||
|
||||
for line in out.split('\n'):
|
||||
ip_match = re.search(r'RemoteAddr:\s*([0-9.]+):(\d+)', line)
|
||||
if ip_match:
|
||||
current_ip = ip_match.group(1)
|
||||
continue
|
||||
|
||||
if 'Login request:' in line and current_ip:
|
||||
name_match = re.search(r'Name=([^?#]+)', line)
|
||||
if name_match:
|
||||
current_player = name_match.group(1).split('#')[0]
|
||||
if current_player and current_ip and current_ip != '65.21.198.100':
|
||||
ip_to_player[current_ip] = current_player
|
||||
current_ip = None
|
||||
|
||||
if ip_to_player:
|
||||
for ip, name in ip_to_player.items():
|
||||
cur.execute("""
|
||||
SELECT ps.player_controller_id, ps.account_id
|
||||
FROM dune.player_state ps
|
||||
JOIN dune.accounts a ON ps.account_id = a.id
|
||||
WHERE a.funcom_id = %s OR ps.character_name = %s
|
||||
LIMIT 1
|
||||
""", [name, name])
|
||||
row = cur.fetchone()
|
||||
if row:
|
||||
pid = row[0]
|
||||
account_id = row[1]
|
||||
cur.execute("""
|
||||
INSERT INTO dune.player_ips (player_id, ip_address, updated_at)
|
||||
VALUES (%s, %s, NOW())
|
||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||
""", [pid, ip])
|
||||
updated += 1
|
||||
|
||||
ban_check = self.db.query("""
|
||||
SELECT player_id FROM dune.bans
|
||||
WHERE (player_id = %s OR account_id = %s) AND (active = TRUE OR active IS NULL)
|
||||
LIMIT 1
|
||||
""", [pid, account_id], one=True)
|
||||
|
||||
if ban_check:
|
||||
self.ssh.run(f'sudo iptables -I INPUT -s {ip} -j DROP')
|
||||
self.ssh.run(f'sudo iptables -I OUTPUT -d {ip} -j DROP')
|
||||
|
||||
conn.commit()
|
||||
return True, f"Updated {updated} player IPs from game logs"
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to detect player IPs: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def set_player_ip(self, player_id, ip_address):
|
||||
return self.db.execute("""
|
||||
INSERT INTO dune.player_ips (player_id, ip_address, updated_at)
|
||||
VALUES (%s, %s, NOW())
|
||||
ON CONFLICT (player_id) DO UPDATE SET ip_address = EXCLUDED.ip_address, updated_at = NOW()
|
||||
""", [player_id, ip_address])
|
||||
|
||||
def emergency_unban(self, ip):
|
||||
self.ssh.run(f'sudo iptables -D INPUT -s {ip} -j DROP 2>/dev/null')
|
||||
self.ssh.run(f'sudo iptables -D OUTPUT -d {ip} -j DROP 2>/dev/null')
|
||||
return True, f"Unblocked {ip}"
|
||||
|
||||
def get_bans(self, limit=50):
|
||||
return self.db.query("""
|
||||
SELECT b.id, b.player_id, b.reason, b.active, b.banned_at, b.expires_at, ps.character_name
|
||||
FROM dune.bans b
|
||||
LEFT JOIN dune.player_state ps ON b.player_id = ps.player_controller_id
|
||||
ORDER BY b.banned_at DESC
|
||||
LIMIT %s
|
||||
""", [limit]) or []
|
||||
|
||||
def get_player_ban(self, player_id):
|
||||
return self.db.query("SELECT reason, note, duration, banned_at, expires_at FROM dune.bans WHERE player_id = %s", [player_id], one=True)
|
||||
|
||||
def get_player_history(self, player_id, limit=20):
|
||||
return self.db.query("""
|
||||
SELECT action_type, reason, note, duration_minutes, created_at, ip_address
|
||||
FROM dune.player_actions
|
||||
WHERE player_id = %s
|
||||
ORDER BY created_at DESC
|
||||
LIMIT %s
|
||||
""", [player_id, limit]) or []
|
||||
|
||||
def create_indexes(self):
|
||||
indexes = [
|
||||
("idx_actors_class", "CREATE INDEX IF NOT EXISTS idx_actors_class ON dune.actors (class)"),
|
||||
("idx_actors_map", "CREATE INDEX IF NOT EXISTS idx_actors_map ON dune.actors (map)"),
|
||||
("idx_actors_owner_account", "CREATE INDEX IF NOT EXISTS idx_actors_owner_account ON dune.actors (owner_account_id)"),
|
||||
("idx_player_state_controller", "CREATE INDEX IF NOT EXISTS idx_player_state_controller ON dune.player_state (player_controller_id)"),
|
||||
("idx_player_state_pawn", "CREATE INDEX IF NOT EXISTS idx_player_state_pawn ON dune.player_state (player_pawn_id)"),
|
||||
("idx_player_state_account", "CREATE INDEX IF NOT EXISTS idx_player_state_account ON dune.player_state (account_id)"),
|
||||
("idx_player_state_online", "CREATE INDEX IF NOT EXISTS idx_player_state_online ON dune.player_state (online_status)"),
|
||||
("idx_guild_members_player", "CREATE INDEX IF NOT EXISTS idx_guild_members_player ON dune.guild_members (player_id)"),
|
||||
("idx_guild_members_guild", "CREATE INDEX IF NOT EXISTS idx_guild_members_guild ON dune.guild_members (guild_id)"),
|
||||
("idx_player_faction_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_actor ON dune.player_faction (actor_id)"),
|
||||
("idx_permission_actor_rank_player", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_player ON dune.permission_actor_rank (player_id)"),
|
||||
("idx_permission_actor_rank_actor", "CREATE INDEX IF NOT EXISTS idx_permission_actor_rank_actor ON dune.permission_actor_rank (permission_actor_id)"),
|
||||
("idx_buildings_owner", "CREATE INDEX IF NOT EXISTS idx_buildings_owner ON dune.buildings (owner_id)"),
|
||||
("idx_inventories_actor", "CREATE INDEX IF NOT EXISTS idx_inventories_actor ON dune.inventories (actor_id)"),
|
||||
("idx_items_inventory", "CREATE INDEX IF NOT EXISTS idx_items_inventory ON dune.items (inventory_id)"),
|
||||
("idx_specialization_tracks_player", "CREATE INDEX IF NOT EXISTS idx_specialization_tracks_player ON dune.specialization_tracks (player_id)"),
|
||||
("idx_player_faction_reputation_actor", "CREATE INDEX IF NOT EXISTS idx_player_faction_reputation_actor ON dune.player_faction_reputation (actor_id)"),
|
||||
("idx_player_virtual_currency_controller", "CREATE INDEX IF NOT EXISTS idx_player_virtual_currency_controller ON dune.player_virtual_currency_balances (player_controller_id)"),
|
||||
]
|
||||
|
||||
created = []
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, [], "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for name, sql in indexes:
|
||||
try:
|
||||
cur.execute(sql)
|
||||
created.append(name)
|
||||
except Exception as e:
|
||||
logger.warning(f"Index {name} failed: {e}")
|
||||
conn.commit()
|
||||
return True, created, None
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create indexes: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False, [], str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
@@ -0,0 +1,156 @@
|
||||
"""Chat service - chat history and log parsing"""
|
||||
|
||||
import json
|
||||
import datetime
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ChatService:
|
||||
def __init__(self, db_service, k8s_service, ssh_service, cache):
|
||||
self.db = db_service
|
||||
self.k8s = k8s_service
|
||||
self.ssh = ssh_service
|
||||
self.cache = cache
|
||||
self.ensured_table = False
|
||||
|
||||
def ensure_history_table(self):
|
||||
if self.ensured_table:
|
||||
return True
|
||||
try:
|
||||
self.db.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.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("CREATE INDEX IF NOT EXISTS idx_chat_history_timestamp ON dune.chat_history (timestamp DESC)")
|
||||
self.ensured_table = True
|
||||
logger.info("Chat history table ready")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create chat history table: {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("""
|
||||
INSERT INTO dune.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 save_messages_batch(self, messages):
|
||||
if not messages:
|
||||
return 0
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return 0
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
for msg in messages:
|
||||
cur.execute("""
|
||||
INSERT INTO dune.chat_history (channel, sender, message, target, location_x, location_y, location_z, is_admin)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", [
|
||||
msg['channel'], msg['sender'], msg['message'],
|
||||
msg.get('target', ''),
|
||||
msg.get('location', {}).get('X', 0),
|
||||
msg.get('location', {}).get('Y', 0),
|
||||
msg.get('location', {}).get('Z', 0),
|
||||
msg.get('is_admin', False)
|
||||
])
|
||||
conn.commit()
|
||||
return len(messages)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to save chat messages batch: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return 0
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
|
||||
def get_history(self, limit=200):
|
||||
return self.db.query("""
|
||||
SELECT id, timestamp, channel, sender, message, target,
|
||||
location_x, location_y, location_z, is_admin
|
||||
FROM dune.chat_history
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT %s
|
||||
""", [limit])
|
||||
|
||||
def catch_up(self, namespace):
|
||||
db_messages = self.get_history(1)
|
||||
has_history = db_messages and len(db_messages) >= 10
|
||||
if has_history:
|
||||
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
|
||||
|
||||
out, err, rc = self.ssh.run(
|
||||
f"sudo kubectl logs -n {namespace} {pod_name} --tail=2000 2>/dev/null | "
|
||||
"grep 'CLOG.*TextChat' | grep -v 'Starting filtering' | grep -v 'Skipping filtering' | grep -v 'Redirected message'",
|
||||
timeout=30
|
||||
)
|
||||
|
||||
messages = []
|
||||
seen = set()
|
||||
for line in (out or '').strip().split('\n'):
|
||||
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_messages_batch(messages)
|
||||
logger.info(f"Caught up {saved} chat messages from pod logs")
|
||||
return saved
|
||||
return 0
|
||||
@@ -0,0 +1,174 @@
|
||||
"""Database service - connection pool and query helpers"""
|
||||
|
||||
import logging
|
||||
import psycopg2
|
||||
import psycopg2.extras
|
||||
import psycopg2.pool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseService:
|
||||
def __init__(self, db_config, min_conn=2, max_conn=10):
|
||||
self.db_config = db_config
|
||||
self.min_conn = min_conn
|
||||
self.max_conn = max_conn
|
||||
self.pool = None
|
||||
|
||||
def init_pool(self):
|
||||
if self.pool is None:
|
||||
try:
|
||||
self.pool = psycopg2.pool.ThreadedConnectionPool(
|
||||
minconn=self.min_conn,
|
||||
maxconn=self.max_conn,
|
||||
**self.db_config
|
||||
)
|
||||
logger.info("Database connection pool initialized")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to initialize database pool: {e}")
|
||||
self.pool = None
|
||||
return self.pool
|
||||
|
||||
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(f"Failed to get database connection: {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(f"Error closing pool: {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(f"Database query error: {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(f"Database execute error: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
return False
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.return_connection(conn)
|
||||
|
||||
def execute_with_conn(self, conn, sql, params=None):
|
||||
cur = conn.cursor()
|
||||
try:
|
||||
cur.execute(sql, params)
|
||||
return cur
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
|
||||
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:
|
||||
return False
|
||||
|
||||
def ensure_tables(self):
|
||||
conn = self.get_connection()
|
||||
if not conn:
|
||||
return
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.player_ips (
|
||||
player_id BIGINT PRIMARY KEY,
|
||||
ip_address INET NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL DEFAULT NOW()
|
||||
)
|
||||
""")
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.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
|
||||
)
|
||||
""")
|
||||
cur.execute("""
|
||||
CREATE TABLE IF NOT EXISTS dune.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()
|
||||
)
|
||||
""")
|
||||
conn.commit()
|
||||
logger.info("Dashboard tables ensured (player_ips, bans, player_actions)")
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to ensure dashboard tables: {e}")
|
||||
if conn:
|
||||
conn.rollback()
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.return_connection(conn)
|
||||
@@ -0,0 +1,77 @@
|
||||
"""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}'
|
||||
return self.ssh.run(full_cmd, timeout=timeout)
|
||||
|
||||
def get_pods(self):
|
||||
out, err, rc = self.run('get pods -o name')
|
||||
if rc != 0:
|
||||
logger.error(f"Failed to get pods: {err}")
|
||||
return []
|
||||
return [line.replace('pod/', '').strip() for line in (out or '').strip().split('\n') if line.strip()]
|
||||
|
||||
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
|
||||
pod = self.find_pod_by_pattern('router')
|
||||
return pod
|
||||
|
||||
def get_rabbitmq_pod(self):
|
||||
pod = self.find_pod_by_pattern('mq-admin')
|
||||
if pod:
|
||||
return pod
|
||||
pod = self.find_pod_by_pattern('mq-game')
|
||||
return pod
|
||||
|
||||
def get_deployments(self):
|
||||
out, err, rc = self.run('get deployments -o name')
|
||||
if rc != 0:
|
||||
return []
|
||||
return [d.strip() for d in (out or '').strip().split('\n') if d.strip()]
|
||||
|
||||
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 {}
|
||||
|
||||
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(f"Auto-detected K8s namespace: {ns}")
|
||||
self.namespace = ns
|
||||
return ns
|
||||
return None
|
||||
@@ -0,0 +1,339 @@
|
||||
"""Player service - player queries and operations"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LIKE_PC = '%DunePlayerCharacter_C'
|
||||
|
||||
|
||||
class PlayerService:
|
||||
def __init__(self, db_service):
|
||||
self.db = db_service
|
||||
|
||||
def is_online(self, player_controller_id):
|
||||
result = self.db.query(
|
||||
"SELECT 1 FROM dune.player_state WHERE player_controller_id = %s AND online_status::text = 'Online' LIMIT 1",
|
||||
[player_controller_id],
|
||||
one=True
|
||||
)
|
||||
return bool(result)
|
||||
|
||||
def get_overview_counts(self):
|
||||
return self.db.query("""
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM dune.accounts) as account_count,
|
||||
(SELECT COUNT(*) FROM dune.player_state) as player_count,
|
||||
(SELECT COUNT(*) FROM dune.vehicles) as vehicle_count,
|
||||
(SELECT COUNT(*) FROM dune.buildings) as building_count,
|
||||
(SELECT COUNT(*) FROM dune.guilds) as guild_count,
|
||||
(SELECT COUNT(*) FROM dune.actors) as actor_count,
|
||||
(SELECT COUNT(*) FROM dune.player_state WHERE online_status::text = 'Online') as online_count
|
||||
""", one=True)
|
||||
|
||||
def get_faction_distribution(self):
|
||||
return self.db.query("""
|
||||
SELECT f.name, COUNT(pf.actor_id)::int count
|
||||
FROM dune.player_faction pf
|
||||
JOIN dune.factions f ON pf.faction_id = f.id
|
||||
GROUP BY f.name
|
||||
ORDER BY count DESC
|
||||
""")
|
||||
|
||||
def get_players_per_map(self):
|
||||
return self.db.query("""
|
||||
SELECT a.map, COUNT(*)::int as count
|
||||
FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE a.class LIKE %s AND a.map IS NOT NULL
|
||||
GROUP BY a.map
|
||||
ORDER BY count DESC
|
||||
""", [LIKE_PC])
|
||||
|
||||
def get_players_online(self):
|
||||
return self.db.query("""
|
||||
SELECT ps.character_name, ps.player_pawn_id as pawn_id, a.map,
|
||||
ps.online_status::text as online_status
|
||||
FROM dune.player_state ps
|
||||
JOIN dune.actors a ON ps.player_pawn_id = a.id
|
||||
WHERE ps.online_status::text = 'Online'
|
||||
ORDER BY ps.character_name
|
||||
""")
|
||||
|
||||
def get_players_list(self, search='', faction_id='', guild_id='', map_filter='', online_filter='', limit=200):
|
||||
where = ["a.class LIKE %s"]
|
||||
params = [LIKE_PC]
|
||||
|
||||
if search:
|
||||
where.append("""(
|
||||
ps.character_name ILIKE %s
|
||||
OR acc.funcom_id ILIKE %s
|
||||
OR ea.user ILIKE %s
|
||||
OR a.properties::text ILIKE %s
|
||||
)""")
|
||||
params.extend([f'%{search}%'] * 4)
|
||||
if faction_id:
|
||||
where.append("pf.faction_id = %s")
|
||||
params.append(faction_id)
|
||||
if guild_id:
|
||||
where.append("gm.guild_id = %s")
|
||||
params.append(guild_id)
|
||||
if map_filter:
|
||||
where.append("a.map = %s")
|
||||
params.append(map_filter)
|
||||
if online_filter == 'online':
|
||||
where.append("ps.online_status::text = 'Online'")
|
||||
elif online_filter == 'offline':
|
||||
where.append("ps.online_status::text = 'Offline'")
|
||||
|
||||
where_clause = ' AND '.join(where)
|
||||
players = self.db.query(f"""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
ps.life_state::text as life_state,
|
||||
ps.last_login_time,
|
||||
ps.last_avatar_activity,
|
||||
ea.id as account_id, ea.user as account_email,
|
||||
acc.funcom_id,
|
||||
ps.player_controller_id,
|
||||
f.name as faction_name, g.guild_name,
|
||||
pi.ip_address
|
||||
FROM dune.actors a
|
||||
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.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id
|
||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_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.guilds g ON gm.guild_id = g.guild_id
|
||||
LEFT JOIN dune.player_ips pi ON ps.player_controller_id = pi.player_id
|
||||
WHERE {where_clause}
|
||||
ORDER BY player_name
|
||||
LIMIT %s
|
||||
""", params + [limit])
|
||||
|
||||
if not players:
|
||||
return []
|
||||
|
||||
player_ids = [p.get('player_controller_id') for p in players if p.get('player_controller_id')]
|
||||
actor_ids = [p.get('id') for p in players if p.get('id')]
|
||||
|
||||
vehicle_counts = {}
|
||||
if player_ids:
|
||||
vc = self.db.query("""
|
||||
SELECT par.player_id, COUNT(DISTINCT par.permission_actor_id)::int as cnt
|
||||
FROM dune.permission_actor_rank par
|
||||
JOIN dune.vehicles v ON par.permission_actor_id = v.id
|
||||
WHERE par.rank = 1 AND par.player_id = ANY(%s)
|
||||
GROUP BY par.player_id
|
||||
""", [player_ids])
|
||||
vehicle_counts = {r['player_id']: r['cnt'] for r in (vc or []) if r.get('player_id')}
|
||||
|
||||
building_counts = {}
|
||||
if actor_ids:
|
||||
bc = self.db.query("""
|
||||
SELECT owner_id, COUNT(*)::int as cnt
|
||||
FROM dune.buildings
|
||||
WHERE owner_id = ANY(%s)
|
||||
GROUP BY owner_id
|
||||
""", [actor_ids])
|
||||
building_counts = {r['owner_id']: r['cnt'] for r in (bc or []) if r.get('owner_id')}
|
||||
|
||||
for p in players:
|
||||
pid = p.get('player_controller_id') or p.get('id')
|
||||
p['vehicle_count'] = vehicle_counts.get(pid, 0)
|
||||
p['building_count'] = building_counts.get(p.get('id'), 0)
|
||||
|
||||
return players
|
||||
|
||||
def get_player_detail(self, player_id):
|
||||
player = self.db.query("""
|
||||
SELECT a.*, a.transform::text as transform_text,
|
||||
ea.id as account_id, ea.user as account_email, ea.platform_id,
|
||||
acc.funcom_id,
|
||||
COALESCE(NULLIF(ps.character_name, ''), NULLIF(acc.funcom_id, ''), 'Character ' || a.id::text) as player_name,
|
||||
ps.online_status::text as online_status,
|
||||
ps.life_state::text as life_state,
|
||||
ps.last_login_time,
|
||||
ps.last_avatar_activity,
|
||||
ps.player_controller_id,
|
||||
ps.player_pawn_id as state_pawn_id,
|
||||
f.name as faction_name, pf.faction_id, pf.utc_time_faction_change
|
||||
FROM dune.actors a
|
||||
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.player_state ps ON a.owner_account_id = ps.account_id AND a.id = ps.player_pawn_id
|
||||
LEFT JOIN dune.player_faction pf ON ps.player_controller_id = pf.actor_id
|
||||
LEFT JOIN dune.factions f ON pf.faction_id = f.id
|
||||
WHERE a.id = %s AND a.class LIKE %s
|
||||
""", [player_id, LIKE_PC], one=True)
|
||||
return player
|
||||
|
||||
def get_player_vitals(self, state_pawn_id):
|
||||
if not state_pawn_id:
|
||||
return {}
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT
|
||||
(properties->'DamageableActorComponent'->>'m_CurrentMaxHealth')::float as current_health,
|
||||
(properties->'DamageableActorComponent'->>'m_TotalMaxHealth')::float as max_health,
|
||||
(gas_attributes->'DuneHydrationAttributeSet'->'CurrentHydration'->>'CurrentValue')::float as current_hydration,
|
||||
(gas_attributes->'DuneHydrationAttributeSet'->'DehydrationPenalty'->>'CurrentValue')::float as dehydration_penalty,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'CurrentSpice'->>'CurrentValue')::float as current_spice,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceAddictionLevel'->'CurrentValue'->>'Value')::float as spice_addiction_level,
|
||||
(gas_attributes->'DuneSpiceAddictionAttributeSet'->'SpiceTolerance'->'CurrentValue'->>'Value')::float as spice_tolerance
|
||||
FROM dune.actors WHERE id = %s
|
||||
""", [state_pawn_id], one=True) or {}
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get vitals: {e}")
|
||||
return {}
|
||||
|
||||
def get_player_guild(self, player_controller_id):
|
||||
return self.db.query("""
|
||||
SELECT g.guild_id, g.guild_name, g.guild_description, f.name as faction_name, gm.role_id
|
||||
FROM dune.guild_members gm
|
||||
JOIN dune.guilds g ON gm.guild_id = g.guild_id
|
||||
LEFT JOIN dune.factions f ON g.guild_faction = f.id
|
||||
WHERE gm.player_id = %s
|
||||
""", [player_controller_id], one=True)
|
||||
|
||||
def get_player_vehicles(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
return self.db.query("""
|
||||
SELECT v_a.id, v_a.class, v_a.map, v_a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
par.rank as ownership_rank
|
||||
FROM dune.permission_actor_rank par
|
||||
JOIN dune.vehicles v ON par.permission_actor_id = v.id
|
||||
JOIN dune.actors v_a ON v.id = v_a.id
|
||||
LEFT JOIN dune.permission_actor pa ON v.id = pa.actor_id AND pa.is_child = FALSE
|
||||
WHERE par.player_id = %s
|
||||
ORDER BY v_a.class
|
||||
""", [player_controller_id]) or []
|
||||
|
||||
def get_player_buildings(self, player_id):
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
(SELECT COUNT(*)::int FROM dune.building_instances bi WHERE bi.building_id = b.id) as instance_count
|
||||
FROM dune.buildings b
|
||||
JOIN dune.actors a ON b.id = a.id
|
||||
WHERE b.owner_id = %s
|
||||
ORDER BY a.map
|
||||
""", [player_id]) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_currency(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT pvcb.currency_id, pvcb.balance FROM dune.player_virtual_currency_balances pvcb WHERE pvcb.player_controller_id = %s",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_inventories(self, player_id):
|
||||
try:
|
||||
inventories = self.db.query("""
|
||||
SELECT i.id, i.actor_id, i.inventory_type,
|
||||
COALESCE(json_agg(
|
||||
json_build_object(
|
||||
'id', items.id,
|
||||
'template_id', items.template_id,
|
||||
'stack_size', items.stack_size,
|
||||
'quality_level', items.quality_level,
|
||||
'is_new', items.is_new,
|
||||
'stats_text', items.stats::text
|
||||
) ORDER BY items.position_index
|
||||
) FILTER (WHERE items.id IS NOT NULL), '[]') as item_list
|
||||
FROM dune.inventories i
|
||||
LEFT JOIN dune.items ON i.id = items.inventory_id
|
||||
WHERE i.actor_id = %s
|
||||
GROUP BY i.id, i.actor_id, i.inventory_type
|
||||
ORDER BY i.inventory_type
|
||||
""", [player_id]) or []
|
||||
for inv in inventories:
|
||||
inv['item_list'] = inv.get('item_list', []) or []
|
||||
return inventories
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to get inventories: {e}")
|
||||
inventories = self.db.query(
|
||||
"SELECT i.* FROM dune.inventories i WHERE i.actor_id = %s ORDER BY i.inventory_type",
|
||||
[player_id]
|
||||
) or []
|
||||
for inv in inventories:
|
||||
inv['item_list'] = []
|
||||
return inventories
|
||||
|
||||
def get_player_landclaims(self, owner_account_id):
|
||||
try:
|
||||
return self.db.query("""
|
||||
SELECT DISTINCT a.id, a.class, a.map, a.transform::text as transform_text
|
||||
FROM dune.landclaim_segments lcs
|
||||
JOIN dune.actors a ON lcs.totem_id = a.id
|
||||
WHERE a.owner_account_id = %s
|
||||
""", [owner_account_id]) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_specialization(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT track_type, xp_amount, level FROM dune.specialization_tracks WHERE player_id = %s",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_tech_knowledge(self, player_id):
|
||||
try:
|
||||
tech_row = self.db.query(
|
||||
"SELECT (properties->'TechKnowledgePlayerComponent'->>'m_TechKnowledgePoints')::int as xp_points FROM dune.actors WHERE id = %s",
|
||||
[player_id], one=True
|
||||
)
|
||||
return tech_row['xp_points'] if tech_row else None
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def get_player_keystones(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT ks.id, ks.name FROM dune.purchased_specialization_keystones psk JOIN dune.specialization_keystones_map ks ON psk.keystone_id = ks.id WHERE psk.player_id = %s ORDER BY ks.id",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_faction_reputation(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return []
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT pfr.faction_id, f.name as faction_name, pfr.reputation_amount FROM dune.player_faction_reputation pfr JOIN dune.factions f ON pfr.faction_id = f.id WHERE pfr.actor_id = %s ORDER BY pfr.faction_id",
|
||||
[player_controller_id]
|
||||
) or []
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
def get_player_landsraad(self, player_controller_id):
|
||||
if not player_controller_id:
|
||||
return {}
|
||||
try:
|
||||
return self.db.query(
|
||||
"SELECT (properties->'LandsraadCharacterComponent'->>'m_DailyRewardCharges')::int as daily_reward_charges, "
|
||||
"(properties->'LandsraadCharacterComponent'->>'m_LastViewedLandsraadTermId')::int as last_viewed_term_id, "
|
||||
"(properties->'LandsraadCharacterComponent'->>'m_DailyRewardLastProcessedTimestamp')::bigint as daily_reward_last_processed "
|
||||
"FROM dune.actors WHERE id = %s",
|
||||
[player_controller_id], one=True
|
||||
) or {}
|
||||
except Exception:
|
||||
return {}
|
||||
@@ -0,0 +1,43 @@
|
||||
"""SSH service - remote command execution"""
|
||||
|
||||
import subprocess
|
||||
import logging
|
||||
import os
|
||||
|
||||
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
|
||||
|
||||
def run(self, command, timeout=30):
|
||||
args = [
|
||||
'ssh',
|
||||
'-i', self.ssh_key,
|
||||
'-o', 'StrictHostKeyChecking=accept-new',
|
||||
'-o', 'ConnectTimeout=10',
|
||||
'-o', 'BatchMode=yes',
|
||||
f'{self.user}@{self.host}',
|
||||
command
|
||||
]
|
||||
try:
|
||||
result = subprocess.run(
|
||||
args,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout
|
||||
)
|
||||
return result.stdout, result.stderr, result.returncode
|
||||
except FileNotFoundError:
|
||||
return '', 'ssh command not found', -1
|
||||
except subprocess.TimeoutExpired:
|
||||
return '', 'SSH command timed out', -1
|
||||
except Exception as ex:
|
||||
return '', str(ex), -1
|
||||
|
||||
def check_connection(self):
|
||||
out, err, rc = self.run('echo ok', timeout=5)
|
||||
return rc == 0 and 'ok' in out
|
||||
@@ -0,0 +1,158 @@
|
||||
"""Vehicle service - vehicle queries and operations"""
|
||||
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
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',
|
||||
}
|
||||
|
||||
TYPE_CONFIGS = {
|
||||
'Ornithopter': {
|
||||
'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000, 'Boost': 2000, 'Launcher': 2000},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Cockpit', 'HullBack': 'Tail', 'Locomotion': 'Wing', 'Boost': 'Boost', 'Launcher': 'Launcher'}
|
||||
},
|
||||
'Transport': {
|
||||
'base': {'Chassis': 2200, 'Engine': 2000, 'Generator': 2000, 'Hull': 1650, 'HullFront': 1650, 'HullBack': 1650, 'Locomotion': 2000},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'HullFront': 'Main Hull', 'HullBack': 'Tail Hull', 'Locomotion': 'Wing'}
|
||||
},
|
||||
'Buggy': {
|
||||
'base': {'Chassis': 3500, 'Engine': 1750, 'Generator': 1750, 'Hull': 2625, 'HullFront': 2625, 'HullBack': 2625, 'Locomotion': 1750},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'PSU', 'Hull': 'Hull', 'HullFront': 'Front', 'HullBack': 'Rear', 'Locomotion': 'Tread'}
|
||||
},
|
||||
'Sandcrawler': {
|
||||
'base': {'Chassis': 4250, 'Hull': 3187, 'Locomotion': 2500, 'SpiceHeader': 2500, 'Generator': 2500, 'Engine': 2500, 'SpiceContainer': 3200},
|
||||
'names': {'Chassis': 'Chassis', 'Hull': 'Hull', 'Locomotion': 'Tread', 'SpiceHeader': 'Spice Header', 'Generator': 'PSU', 'Engine': 'Engine', 'SpiceContainer': 'Spice Container'}
|
||||
},
|
||||
'Sandbike': {
|
||||
'base': {'Chassis': 1500, 'Engine': 1200, 'Generator': 1200, 'Hull': 1000, 'Locomotion': 1200},
|
||||
'names': {'Chassis': 'Chassis', 'Engine': 'Engine', 'Generator': 'Generator', 'Hull': 'Hull', 'Locomotion': 'Wheel'}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def vehicle_type_name(cls):
|
||||
if '/' in cls:
|
||||
short = cls.split('/')[-1].replace('_C', '')
|
||||
for key, name in VEHICLE_TYPE_MAP.items():
|
||||
if key in short:
|
||||
return name
|
||||
return short.replace('BP_', '').replace('_CHOAM', '').replace('_Choam', '').replace('_', ' ')
|
||||
return cls
|
||||
|
||||
|
||||
def get_vehicle_type_config(vehicle_class):
|
||||
type_order = ['Sandcrawler', 'Sandbike', 'Buggy', 'Transport', 'Ornithopter', 'Light', 'Medium']
|
||||
for t in type_order:
|
||||
if t in vehicle_class:
|
||||
return TYPE_CONFIGS.get(t, TYPE_CONFIGS['Buggy'])
|
||||
return TYPE_CONFIGS['Buggy']
|
||||
|
||||
|
||||
def parse_vehicle_modules(modules, vehicle_class):
|
||||
config = get_vehicle_type_config(vehicle_class)
|
||||
parsed = []
|
||||
for m in modules:
|
||||
stats = m.get('stats', {})
|
||||
durability = stats.get('FVehicleModuleDurabilityStats', [{}])[1] if stats.get('FVehicleModuleDurabilityStats') else {}
|
||||
current = durability.get('CurrentDurability', 0)
|
||||
max_durability = durability.get('MaxDurability') or durability.get('DecayedMaxDurability') or current
|
||||
|
||||
template = m.get('template_id', '')
|
||||
mod_clean = template.replace('Ornithopter', '').replace('Buggy', '').replace('Sandcrawler', '').replace('Sandbike', '').replace('_6', '').replace('_0', '')
|
||||
mod_type = mod_clean.replace('Medium', '').replace('Transport', '').replace('Light', '').replace('Heavy', '').replace('Front', '').replace('Back', '').replace('Left', '').replace('Right', '').replace('Center', '').replace('1', '').replace('2', '')
|
||||
name = config['names'].get(mod_type, mod_clean)
|
||||
|
||||
parsed.append({
|
||||
'id': m['id'],
|
||||
'name': name,
|
||||
'template': template,
|
||||
'current': round(current, 1),
|
||||
'max': round(max_durability, 1),
|
||||
'damage_cause': durability.get('LastDeteriorationCause', '')
|
||||
})
|
||||
return parsed
|
||||
|
||||
|
||||
class VehicleService:
|
||||
def __init__(self, db_service):
|
||||
self.db = db_service
|
||||
|
||||
def get_all_vehicles(self, limit=200):
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
pilot_ps.character_name as pilot_name,
|
||||
pilot_a.id as pilot_pawn_id,
|
||||
ps_owner.character_name as owner_name,
|
||||
ps_owner.player_pawn_id as owner_pawn_id,
|
||||
par.rank as owner_rank
|
||||
FROM dune.actors a
|
||||
JOIN dune.vehicles v ON a.id = v.id
|
||||
LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE
|
||||
LEFT JOIN dune.actors pilot_a ON pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_CurrentVehicleId' = CONCAT('!!act#', a.id::text)
|
||||
AND (pilot_a.properties->'BP_DunePlayerCharacter_C'->>'m_bIsDriving')::boolean = TRUE
|
||||
LEFT JOIN dune.player_state pilot_ps ON pilot_a.owner_account_id = pilot_ps.account_id AND pilot_a.id = pilot_ps.player_pawn_id
|
||||
LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1
|
||||
LEFT JOIN dune.player_state ps_owner ON par.player_id = ps_owner.player_controller_id
|
||||
ORDER BY a.class
|
||||
LIMIT %s
|
||||
""", [limit]) or []
|
||||
|
||||
def get_vehicle(self, vehicle_id):
|
||||
return self.db.query("""
|
||||
SELECT a.id, a.class, a.map, a.transform::text as transform_text,
|
||||
pa.actor_name,
|
||||
ps.character_name as owner_name,
|
||||
ps.player_pawn_id as owner_pawn_id
|
||||
FROM dune.actors a
|
||||
JOIN dune.vehicles v ON a.id = v.id
|
||||
LEFT JOIN dune.permission_actor pa ON a.id = pa.actor_id AND pa.is_child = FALSE
|
||||
LEFT JOIN dune.permission_actor_rank par ON a.id = par.permission_actor_id AND par.rank = 1
|
||||
LEFT JOIN dune.player_state ps ON par.player_id = ps.player_controller_id
|
||||
WHERE a.id = %s
|
||||
""", [vehicle_id], one=True)
|
||||
|
||||
def get_vehicle_modules(self, vehicle_id):
|
||||
return self.db.query("""
|
||||
SELECT id, template_id, stats
|
||||
FROM dune.vehicle_modules
|
||||
WHERE vehicle_id = %s
|
||||
ORDER BY id
|
||||
""", [vehicle_id]) or []
|
||||
|
||||
def delete_vehicle(self, vehicle_id):
|
||||
conn = self.db.get_connection()
|
||||
if not conn:
|
||||
return False, "Database connection failed"
|
||||
cur = None
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SET session_replication_role = replica")
|
||||
cur.execute("DELETE FROM dune.vehicles WHERE id = %s RETURNING id", [vehicle_id])
|
||||
deleted = cur.fetchone()
|
||||
if deleted:
|
||||
cur.execute("DELETE FROM dune.actors WHERE id = %s RETURNING id", [vehicle_id])
|
||||
conn.commit()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return True, f"Vehicle {vehicle_id} deleted"
|
||||
else:
|
||||
conn.rollback()
|
||||
cur.execute("SET session_replication_role = default")
|
||||
return False, "Vehicle not found"
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to delete vehicle {vehicle_id}: {e}")
|
||||
try:
|
||||
cur.execute("SET session_replication_role = default")
|
||||
except Exception:
|
||||
pass
|
||||
return False, str(e)
|
||||
finally:
|
||||
if cur:
|
||||
cur.close()
|
||||
self.db.return_connection(conn)
|
||||
Reference in new issue
Block a user