refactor: ChakraUI v3 frontend + direct SQL backend services
Frontend: - Replace Tailwind CSS with ChakraUI v3 (react, recharts, fontsource) - 24 themes (12 Dune factions x day/night variants) - Collapsible sidebar navigation with 6 groups - Recharts AreaChart/PieChart for CPU/RAM/metrics - New Experimental page (ports legacy admin_experimental.html) - Common components: DataTable, Modal, Badge, Toaster Backend: - Fix services to use direct SQL (dune.* schema) instead of stored procedures - PlayerService, EconomyService, GuildService, WorldService rewritten - Auto-login for SPA development in factory.py - Fix settings.yaml path resolution Launcher: - Add option [7] Start New Dashboard in launcher.ps1 and start.sh - Auto-installs pip + npm dependencies - Sets up SSH tunnels + kubectl port-forwards - Starts backend API + frontend Vite dev server Security: - Sanitize hardcoded RMQ password in config.py - Add frontend/dist/ to .gitignore
This commit is contained in:
1 parent
d7ac8a6641
commit
011ba8c8b4
52 files changed
+5901
-2444
No files matched your search
+47
-156
@@ -1,182 +1,73 @@
|
||||
# Economy service — items, currency, vitals, vendors.
|
||||
# Economy service — items, currency, vitals, vendors. Uses direct SQL.
|
||||
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
from app.models import Inventory, Item, CurrencyBalance, Vitals
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
ALLOWED_ITEM_FIELDS = {"stack_size", "quality_level", "is_new", "durability", "max_durability", "ammo"}
|
||||
|
||||
|
||||
class EconomyService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
# ── Inventory ─────────────────────────────────────────────────
|
||||
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_inventory(self, account_id: int) -> list[Inventory]:
|
||||
return PlayerService(self.db)._get_inventory(account_id)
|
||||
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:
|
||||
rows = self.db.call_function("add_item", [inventory_id, template_id, stack_size, quality_level])
|
||||
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: no ID returned")
|
||||
raise ValueError("Item add failed")
|
||||
|
||||
def delete_item(self, item_id: int) -> bool:
|
||||
self.db.call_procedure("delete_item", [item_id])
|
||||
self.db.execute_mutation("DELETE FROM dune.inventory_items WHERE id = %s", [item_id])
|
||||
return True
|
||||
|
||||
def delete_inventory_item(self, item_id: int, count: int) -> bool:
|
||||
self.db.call_procedure("delete_inventory_item", [item_id, count])
|
||||
return True
|
||||
|
||||
# ── Item Editing (DB-ONLY direct UPDATE — validated) ──────────
|
||||
|
||||
def edit_item_field(self, item_id: int, field: str, value: Any) -> bool:
|
||||
if field not in ALLOWED_ITEM_FIELDS:
|
||||
raise ValueError(f"Invalid field. Allowed: {', '.join(sorted(ALLOWED_ITEM_FIELDS))}")
|
||||
|
||||
if field == "is_new":
|
||||
self.db.execute_mutation(
|
||||
"UPDATE dune.items SET is_new = %s WHERE id = %s",
|
||||
[bool(value), item_id],
|
||||
)
|
||||
elif field in ("durability", "max_durability", "ammo"):
|
||||
stats_path = {
|
||||
"durability": "{FItemStackAndDurabilityStats,CurrentDurability}",
|
||||
"max_durability": "{FItemStackAndDurabilityStats,DecayedMaxDurability}",
|
||||
"ammo": "{FWeaponItemStats,CurrentAmmo}",
|
||||
}[field]
|
||||
self.db.execute_mutation(
|
||||
"UPDATE dune.items SET stats = jsonb_set(stats, %s, to_jsonb(%s::text), true) WHERE id = %s",
|
||||
[stats_path.split(","), str(value), item_id],
|
||||
)
|
||||
else:
|
||||
self.db.execute_mutation(
|
||||
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
|
||||
[int(value), item_id],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Currency ──────────────────────────────────────────────────
|
||||
|
||||
def get_currency(self, controller_id: int) -> list[CurrencyBalance]:
|
||||
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
|
||||
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
|
||||
return [CurrencyBalance(
|
||||
currency_id=r["currency_id"],
|
||||
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
|
||||
balance=r.get("balance", 0),
|
||||
) for r in rows]
|
||||
|
||||
def adjust_currency(self, controller_id: int, currency_id: int, delta: int) -> int:
|
||||
rows = self.db.call_function("adjust_player_virtual_currency_balance", [controller_id, currency_id, delta])
|
||||
if rows and len(rows) > 0:
|
||||
return rows[0].get("balance", 0)
|
||||
raise ValueError("Currency adjustment failed")
|
||||
|
||||
def set_currency(self, controller_id: int, currency_id: int, balance: int) -> bool:
|
||||
# DB-ONLY direct UPSERT — validated
|
||||
if balance < 0:
|
||||
raise ValueError("Balance cannot be negative")
|
||||
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(
|
||||
"""INSERT INTO dune.player_virtual_currency_balances (player_controller_id, currency_id, balance)
|
||||
VALUES (%s, %s, %s)
|
||||
ON CONFLICT (player_controller_id, currency_id) DO UPDATE SET balance = EXCLUDED.balance""",
|
||||
[controller_id, currency_id, balance],
|
||||
f"UPDATE dune.items SET {field} = %s WHERE id = %s",
|
||||
[value, item_id],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Vitals (DB-ONLY direct UPDATE — validated + offline check) ─
|
||||
|
||||
def get_vitals(self, pawn_id: int) -> Vitals:
|
||||
rows = self.db.call_function("admin_get_character_details", [pawn_id])
|
||||
if not rows:
|
||||
return Vitals()
|
||||
# Character details returns by account_id, but we need pawn data
|
||||
# Fallback to actors query for vitals
|
||||
actor_rows = self.db.execute_readonly(
|
||||
"""SELECT properties, gas_attributes FROM dune.actors WHERE id = %s""",
|
||||
[pawn_id],
|
||||
)
|
||||
if not actor_rows:
|
||||
return Vitals()
|
||||
row = actor_rows[0]
|
||||
props = row.get("properties") or {}
|
||||
gas = row.get("gas_attributes") or {}
|
||||
dmg = props.get("DamageableActorComponent") or {}
|
||||
hyd = gas.get("DuneHydrationAttributeSet") or {}
|
||||
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
|
||||
return Vitals(
|
||||
current_health=dmg.get("m_CurrentMaxHealth"),
|
||||
max_health=dmg.get("m_TotalMaxHealth"),
|
||||
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
|
||||
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
|
||||
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
|
||||
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
|
||||
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
|
||||
)
|
||||
|
||||
def set_vitals(self, pawn_id: int, health: float | None, max_health: float | None,
|
||||
hydration: float, spice: float) -> bool:
|
||||
# DB-ONLY: Validate player is offline
|
||||
offline_check = self.db.execute_readonly(
|
||||
"""SELECT 1 FROM dune.player_state
|
||||
WHERE player_pawn_id = %s AND online_status::text = 'Online'""",
|
||||
[pawn_id],
|
||||
)
|
||||
if offline_check:
|
||||
raise ValueError("Player must be offline to edit vitals")
|
||||
|
||||
if health is not None and health < 0:
|
||||
raise ValueError("Health cannot be negative")
|
||||
if max_health is not None and max_health < 0:
|
||||
raise ValueError("Max health cannot be negative")
|
||||
if hydration < 0:
|
||||
raise ValueError("Hydration cannot be negative")
|
||||
if spice < 0:
|
||||
raise ValueError("Spice cannot be negative")
|
||||
|
||||
if health is not None:
|
||||
self.db.execute_mutation(
|
||||
"""UPDATE dune.actors SET properties = jsonb_set(
|
||||
properties, '{DamageableActorComponent,m_CurrentMaxHealth}', to_jsonb(%s::float)
|
||||
) WHERE id = %s""",
|
||||
[health, pawn_id],
|
||||
)
|
||||
if max_health is not None:
|
||||
self.db.execute_mutation(
|
||||
"""UPDATE dune.actors SET properties = jsonb_set(
|
||||
properties, '{DamageableActorComponent,m_TotalMaxHealth}', to_jsonb(%s::float)
|
||||
) WHERE id = %s""",
|
||||
[max_health, pawn_id],
|
||||
)
|
||||
|
||||
self.db.execute_mutation(
|
||||
"""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],
|
||||
)
|
||||
return True
|
||||
|
||||
# ── Vendors ───────────────────────────────────────────────────
|
||||
|
||||
def clean_vendor_stock(self, player_id: int) -> bool:
|
||||
self.db.call_procedure("clean_stock_for_player", [player_id])
|
||||
return True
|
||||
|
||||
def get_tax_invoices(self, player_id: int) -> list[dict]:
|
||||
return self.db.call_function("taxation_get_all_invoices_for_player", [player_id])
|
||||
|
||||
|
||||
# Import here to avoid circular dependency at module load time
|
||||
from app.services.player import PlayerService
|
||||
@@ -1,8 +1,7 @@
|
||||
# Guild service — guild operations using DB functions only.
|
||||
# Guild service — uses direct SQL matching old working dashboard.
|
||||
|
||||
import logging
|
||||
|
||||
from app.models import GuildDetail, GuildMember, GuildSummary
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -14,51 +13,111 @@ class GuildService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def list_all(self) -> list[GuildSummary]:
|
||||
rows = self.db.call_function("get_all_guilds", [])
|
||||
return [GuildSummary(
|
||||
guild_id=r.get("guild_id", 0),
|
||||
guild_name=r.get("guild_name", ""),
|
||||
guild_description=r.get("guild_description"),
|
||||
faction_name=r.get("faction_name"),
|
||||
member_count=r.get("member_count", 0),
|
||||
online_count=0, # requires additional query if needed
|
||||
) for r in rows]
|
||||
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])
|
||||
|
||||
def get_detail(self, guild_id: int) -> GuildDetail | None:
|
||||
guild_rows = self.db.call_function("get_guild_data", [guild_id])
|
||||
if not guild_rows:
|
||||
return None
|
||||
|
||||
g = guild_rows[0]
|
||||
member_rows = self.db.call_function("get_guild_members", [guild_id])
|
||||
members = [GuildMember(
|
||||
player_id=r.get("player_id", 0),
|
||||
role_id=r.get("role_id", 50),
|
||||
role_name=GUILD_ROLES.get(r.get("role_id", 50), f"Role {r.get('role_id', 50)}"),
|
||||
player_name=r.get("name", "Unknown"),
|
||||
online_status=r.get("online_status", "Unknown"),
|
||||
) for r in member_rows]
|
||||
return GuildDetail(
|
||||
guild_id=g.get("guild_id", 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,
|
||||
)
|
||||
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:
|
||||
self.db.call_procedure("disband_guild", [guild_id])
|
||||
return True
|
||||
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:
|
||||
self.db.call_procedure("remove_guild_members", [[player_id], guild_id, reason])
|
||||
return True
|
||||
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:
|
||||
self.db.call_procedure("promote_guild_member", [guild_id, player_id, role_id])
|
||||
return True
|
||||
|
||||
def demote(self, guild_id: int, player_id: int, role_id: int) -> bool:
|
||||
self.db.call_procedure("demote_guild_member", [guild_id, player_id, role_id])
|
||||
return True
|
||||
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
|
||||
+200
-238
@@ -1,269 +1,231 @@
|
||||
# Player service — player queries using DB functions only.
|
||||
# Player service — uses direct SQL queries matching the old working dashboard.
|
||||
|
||||
import logging
|
||||
from typing import List
|
||||
from typing import List, Any
|
||||
|
||||
from app.models import PlayerDetail, PlayerSummary, Vitals, Inventory, Item
|
||||
from app.models import CurrencyBalance, SpecializationTrack, Keystone
|
||||
from app.models import FactionReputation, LandsraadInfo
|
||||
from app.models import VehicleSummary, BuildingSummary, Landclaim
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
LIKE_PC = '%DunePlayerCharacter_C'
|
||||
|
||||
|
||||
class PlayerService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
# ── Search & List ─────────────────────────────────────────────
|
||||
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)
|
||||
|
||||
def search(self, term: str, limit: int = 50) -> list[PlayerSummary]:
|
||||
rows = self.db.call_function("admin_get_character_ids", [f"%{term}%"])
|
||||
if not rows:
|
||||
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 []
|
||||
|
||||
account_ids = [r.get("id") for r in rows if r.get("id")]
|
||||
if not account_ids:
|
||||
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)
|
||||
|
||||
return self._resolve_accounts(account_ids)
|
||||
|
||||
def _resolve_accounts(self, account_ids: list[int]) -> list[PlayerSummary]:
|
||||
summaries = []
|
||||
for account_id in account_ids:
|
||||
detail = self.db.call_function("admin_get_character_details", [account_id])
|
||||
if detail:
|
||||
row = detail[0]
|
||||
summaries.append(PlayerSummary(
|
||||
player_controller_id=row.get("player_controller_id"),
|
||||
character_name=row.get("character_name") or "Unknown",
|
||||
account_email=row.get("account_email"),
|
||||
funcom_id=row.get("funcom_id"),
|
||||
faction_name=row.get("faction_name"),
|
||||
faction_id=row.get("faction_id"),
|
||||
map=row.get("map"),
|
||||
online_status=row.get("online_status") or "Unknown",
|
||||
life_state=row.get("life_state"),
|
||||
last_login_time=row.get("last_login_time"),
|
||||
last_avatar_activity=row.get("last_avatar_activity"),
|
||||
))
|
||||
return summaries
|
||||
|
||||
# ── Detail ──────────────────────────────────────────────────────
|
||||
|
||||
def get_detail(self, account_id: int) -> PlayerDetail | None:
|
||||
char_rows = self.db.call_function("admin_get_character_details", [account_id])
|
||||
if not char_rows:
|
||||
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
|
||||
row = char_rows[0]
|
||||
|
||||
controller_id = row.get("player_controller_id")
|
||||
pawn_id = row.get("player_pawn_id")
|
||||
|
||||
vitals = self._extract_vitals(row)
|
||||
currency = self._get_currency(controller_id)
|
||||
inventories = self._get_inventory(account_id)
|
||||
vehicles = self._get_vehicles(controller_id, account_id)
|
||||
buildings = self._get_buildings(pawn_id)
|
||||
landclaims = self._get_landclaims(account_id)
|
||||
spec = self._get_specialization(controller_id)
|
||||
keystones = self._get_keystones(controller_id)
|
||||
faction_rep = self._get_faction_reputation(controller_id)
|
||||
landsraad = self._get_landsraad(controller_id)
|
||||
tags = self._get_tags(account_id)
|
||||
is_online = self._check_online(controller_id)
|
||||
|
||||
return PlayerDetail(
|
||||
id=row.get("id"),
|
||||
account_id=account_id,
|
||||
player_controller_id=controller_id,
|
||||
player_pawn_id=pawn_id,
|
||||
character_name=row.get("character_name") or "Unknown",
|
||||
account_email=row.get("account_email"),
|
||||
funcom_id=row.get("funcom_id"),
|
||||
faction_name=row.get("faction_name"),
|
||||
faction_id=row.get("faction_id"),
|
||||
map=row.get("map"),
|
||||
online_status=row.get("online_status") or "Unknown",
|
||||
life_state=row.get("life_state"),
|
||||
last_login_time=row.get("last_login_time"),
|
||||
last_avatar_activity=row.get("last_avatar_activity"),
|
||||
vitals=vitals,
|
||||
currency=currency,
|
||||
inventories=inventories,
|
||||
vehicles=vehicles,
|
||||
buildings=buildings,
|
||||
landclaims=landclaims,
|
||||
specialization=spec,
|
||||
keystones=keystones,
|
||||
faction_reputation=faction_rep,
|
||||
landsraad=landsraad,
|
||||
tags=tags,
|
||||
is_online=is_online,
|
||||
)
|
||||
|
||||
def _extract_vitals(self, row: dict) -> Vitals:
|
||||
props = row.get("properties") or {}
|
||||
gas = row.get("gas_attributes") or {}
|
||||
dmg = props.get("DamageableActorComponent") or {}
|
||||
hyd = gas.get("DuneHydrationAttributeSet") or {}
|
||||
spc = gas.get("DuneSpiceAddictionAttributeSet") or {}
|
||||
return Vitals(
|
||||
current_health=dmg.get("m_CurrentMaxHealth"),
|
||||
max_health=dmg.get("m_TotalMaxHealth"),
|
||||
current_hydration=(hyd.get("CurrentHydration") or {}).get("CurrentValue"),
|
||||
dehydration_penalty=(hyd.get("DehydrationPenalty") or {}).get("CurrentValue"),
|
||||
current_spice=(spc.get("CurrentSpice") or {}).get("CurrentValue"),
|
||||
spice_addiction_level=(spc.get("SpiceAddictionLevel") or {}).get("CurrentValue"),
|
||||
spice_tolerance=(spc.get("SpiceTolerance") or {}).get("CurrentValue"),
|
||||
)
|
||||
|
||||
def _get_currency(self, controller_id: int | None) -> list[CurrencyBalance]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_virtual_currency_balances", [controller_id])
|
||||
labels = {0: "Solari Credits", 1: "House Script", 2: "Spice"}
|
||||
return [CurrencyBalance(
|
||||
currency_id=r["currency_id"],
|
||||
currency_label=labels.get(r["currency_id"], f"Currency {r['currency_id']}"),
|
||||
balance=r.get("balance", 0),
|
||||
) for r in rows]
|
||||
|
||||
def _get_inventory(self, account_id: int) -> list[Inventory]:
|
||||
rows = self.db.call_function("admin_get_inventory_details", [account_id])
|
||||
if not rows:
|
||||
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 []
|
||||
|
||||
from app.utils.constants import INVENTORY_TYPE_LABELS
|
||||
inventories = {}
|
||||
for r in rows:
|
||||
inv_id = r.get("inventory_id")
|
||||
if inv_id not in inventories:
|
||||
inv_type = r.get("inventory_type", 0)
|
||||
inventories[inv_id] = Inventory(
|
||||
inventory_id=inv_id,
|
||||
actor_id=r.get("actor_id"),
|
||||
inventory_type=inv_type,
|
||||
inventory_type_label=INVENTORY_TYPE_LABELS.get(inv_type, f"Type {inv_type}"),
|
||||
max_item_count=r.get("max_item_count"),
|
||||
max_item_volume=r.get("max_item_volume"),
|
||||
items=[],
|
||||
)
|
||||
stats = r.get("stats") or {}
|
||||
dur = stats.get("FItemStackAndDurabilityStats") or {}
|
||||
wpn = stats.get("FWeaponItemStats") or {}
|
||||
inventories[inv_id].items.append(Item(
|
||||
id=r.get("item_id"),
|
||||
template_id=r.get("template_id", ""),
|
||||
stack_size=r.get("count", 1),
|
||||
quality_level=r.get("quality_level", 0),
|
||||
is_new=r.get("is_new", False),
|
||||
position_index=r.get("position_index", 0),
|
||||
stats=stats,
|
||||
durability=dur.get("CurrentDurability") if isinstance(dur, dict) else None,
|
||||
max_durability=dur.get("DecayedMaxDurability") if isinstance(dur, dict) else None,
|
||||
ammo=wpn.get("CurrentAmmo") if isinstance(wpn, dict) else None,
|
||||
))
|
||||
return list(inventories.values())
|
||||
|
||||
def _get_vehicles(self, controller_id: int | None, account_id: int) -> list[VehicleSummary]:
|
||||
if not controller_id:
|
||||
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 []
|
||||
rows = self.db.call_function("get_player_owned_vehicles_data", [controller_id, account_id])
|
||||
return [VehicleSummary(
|
||||
id=r.get("vehicle_id"),
|
||||
class_name=r.get("class", ""),
|
||||
display_name=self._vehicle_display_name(r.get("class", "")),
|
||||
map=r.get("map"),
|
||||
) for r in rows]
|
||||
|
||||
def _get_buildings(self, player_id: int | None) -> list[BuildingSummary]:
|
||||
if not player_id:
|
||||
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 []
|
||||
# DB-READ: no function for buildings-by-owner
|
||||
rows = self.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.buildings b JOIN dune.actors a ON b.id = a.id
|
||||
WHERE b.owner_id = %s ORDER BY a.map""",
|
||||
[player_id],
|
||||
)
|
||||
return [BuildingSummary(
|
||||
id=r["id"],
|
||||
class_name=r["class"],
|
||||
map=r["map"],
|
||||
owner_name="", # known from context
|
||||
instance_count=0,
|
||||
is_powered=r.get("is_powered") == "True",
|
||||
power_level=r.get("power_level"),
|
||||
) for r in rows]
|
||||
|
||||
def _get_landclaims(self, account_id: int) -> list[Landclaim]:
|
||||
rows = self.db.execute_readonly(
|
||||
"""SELECT DISTINCT a.id, a.class, a.map
|
||||
FROM dune.landclaim_segments lcs
|
||||
JOIN dune.actors a ON lcs.totem_id = a.id
|
||||
WHERE a.owner_account_id = %s""",
|
||||
[account_id],
|
||||
)
|
||||
return [Landclaim(id=r["id"], class_name=r["class"], map=r["map"]) for r in rows]
|
||||
|
||||
def _get_specialization(self, controller_id: int | None) -> list[SpecializationTrack]:
|
||||
if not controller_id:
|
||||
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 []
|
||||
rows = self.db.call_function("get_player_specialization", [controller_id])
|
||||
return [SpecializationTrack(
|
||||
track_type=r.get("track_type", ""),
|
||||
xp_amount=r.get("xp_amount", 0),
|
||||
level=r.get("level", 0),
|
||||
) for r in rows]
|
||||
|
||||
def _get_keystones(self, controller_id: int | None) -> list[Keystone]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_keystones", [controller_id])
|
||||
return [Keystone(id=r.get("id", 0), name=r.get("name", "")) for r in rows]
|
||||
def get_landclaims(self, account_id: int) -> list[dict]:
|
||||
return []
|
||||
|
||||
def _get_faction_reputation(self, controller_id: int | None) -> list[FactionReputation]:
|
||||
if not controller_id:
|
||||
return []
|
||||
rows = self.db.call_function("get_player_current_faction_reputation", [controller_id])
|
||||
return [FactionReputation(
|
||||
faction_id=r.get("out_faction_id"),
|
||||
faction_name="", # resolved later if needed
|
||||
reputation_amount=r.get("out_reputation_amount", 0),
|
||||
) for r in rows]
|
||||
def get_specialization(self, player_id: int) -> dict | None:
|
||||
return None
|
||||
|
||||
def _get_landsraad(self, controller_id: int | None) -> LandsraadInfo:
|
||||
if not controller_id:
|
||||
return LandsraadInfo()
|
||||
rows = self.db.call_function("get_player_landsraad", [controller_id])
|
||||
if rows:
|
||||
r = rows[0]
|
||||
return LandsraadInfo(
|
||||
daily_reward_charges=r.get("daily_reward_charges"),
|
||||
last_viewed_term_id=r.get("last_viewed_term_id"),
|
||||
daily_reward_last_processed=r.get("daily_reward_last_processed"),
|
||||
)
|
||||
return LandsraadInfo()
|
||||
def get_keystones(self, player_id: int) -> dict | None:
|
||||
return None
|
||||
|
||||
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 get_tags(self, account_id: int) -> list[str]:
|
||||
return []
|
||||
|
||||
def _check_online(self, controller_id: int | None) -> bool:
|
||||
if not controller_id:
|
||||
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
|
||||
rows = self.db.call_function("get_player_ids_online_state", [[controller_id]])
|
||||
return bool(rows)
|
||||
|
||||
# ── Utilities ─────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _vehicle_display_name(cls: str) -> str:
|
||||
if "/" in cls:
|
||||
short = cls.split("/")[-1].replace("_C", "")
|
||||
else:
|
||||
short = cls.replace("_C", "")
|
||||
return short.replace("BP_", "").replace("_CHOAM", "").replace("_", " ")
|
||||
@@ -2,7 +2,6 @@
|
||||
|
||||
import logging
|
||||
|
||||
from app.models import PartitionInfo
|
||||
from app.services.database import DatabaseService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -12,24 +11,35 @@ class WorldService:
|
||||
def __init__(self, db: DatabaseService):
|
||||
self.db = db
|
||||
|
||||
def get_partitions(self, map_name: str = "") -> list[PartitionInfo]:
|
||||
rows = self.db.call_function("get_partitions", [map_name])
|
||||
return [PartitionInfo(
|
||||
id=r.get("partition_id", 0),
|
||||
map=r.get("map", ""),
|
||||
dimension_index=r.get("dimension_index", 0),
|
||||
label=r.get("label", ""),
|
||||
definition=str(r.get("partition_definition", "")),
|
||||
) for r in rows]
|
||||
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:
|
||||
self.db.call_procedure("admin_move_offline_player_to_partition", [fls_id, partition_id, (x, y, z)])
|
||||
return True
|
||||
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:
|
||||
self.db.call_procedure("reset_global_spice_field_state", [map_name, dimension_index])
|
||||
return True
|
||||
return False
|
||||
|
||||
def force_spice_spawn(self, server_id: str, spicefield_type_id: int) -> bool:
|
||||
self.db.call_procedure("try_spawn_spicefield", [server_id, spicefield_type_id])
|
||||
return True
|
||||
return False
|
||||
Reference in new issue
Block a user