Owner-reported on live: adding a radio channel for a server + voice channel that already had one (different label, system, even bot) overwrote the existing stream and made its bot leave, because stream_id was guild:channel. - New streams get guild:channel:<12 hex> ids (leases.new_stream_id); old guild:channel docs keep working for read/stop/remove/node reports. Route validators accept both (leases.STREAM_ID_PATTERN). - start_stream: no stream_id = ADD. Same system already on in that channel is idempotent (already_on, label/mode untouched); a stopped one of that system is restarted; anything else is a new doc. stream_id = explicit restart/edit (admin Start button, reconciler), incl. moving to another bot. - preferred_token_id is strict: bot already in this server -> 409 preferred_busy naming the stream; on another node -> preferred_other_node; unusable -> preferred_unavailable. No silent swap. pool_exhausted now says one-bot-per-server and to add + invite another bot. - One-token-per-guild was already enforced inside the lease transaction; now covered by race tests. Per-guild asyncio lock serialises the already-on / server-cap check with the create (guild half of #223). - Stop by stream_id (POST /discord/guilds/{id}/stop {stream_id}); admin UI Stop/Start/Remove act on the row's stream; node picker lists every stream in a channel and adds beside other systems. - Bot: /leave stream: (autocomplete) stops one; /leave channel: with several streams asks which unless all:True; bare /leave still stops the server. /status and /join name each stream's bot. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
292 lines
13 KiB
Python
292 lines
13 KiB
Python
import httpx
|
|
from typing import Optional
|
|
from app.config import settings
|
|
from app.internal.logger import logger
|
|
|
|
|
|
class C2Client:
|
|
def __init__(self):
|
|
self.base = settings.c2_url.rstrip("/")
|
|
|
|
def _headers(self) -> dict:
|
|
if settings.c2_service_key:
|
|
return {"Authorization": f"Bearer {settings.c2_service_key}"}
|
|
return {}
|
|
|
|
# ------------------------------------------------------------------
|
|
# Discord radio channels — every call is scoped to one guild
|
|
# (server-26#203). C2 resolves the guild's org; nothing here sees another
|
|
# org's nodes, systems or bots.
|
|
# ------------------------------------------------------------------
|
|
|
|
async def guild_overview(self, guild_id: int | str) -> dict:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(f"{self.base}/discord/guilds/{guild_id}/overview", headers=self._headers())
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 guild_overview failed: {e}")
|
|
return {"guild_id": str(guild_id), "org_id": None, "systems": [], "nodes": [],
|
|
"streams": [], "bots": [], "error": True}
|
|
|
|
async def put_guild_directory(self, guild_id: int | str, payload: dict) -> bool:
|
|
"""This server's name + voice channels, for the web node-page picker
|
|
(server-26#213). Names only — no members, no messages, no tokens."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.put(f"{self.base}/discord/guilds/{guild_id}/directory",
|
|
json=payload, headers=self._headers())
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 put_guild_directory({guild_id}) failed: {e}")
|
|
return False
|
|
|
|
async def start_stream(self, payload: dict) -> tuple[bool, dict]:
|
|
"""Returns (ok, body). On a refusal body carries detail/code/invite."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=30) as client:
|
|
r = await client.post(f"{self.base}/discord/streams", json=payload, headers=self._headers())
|
|
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
|
if r.status_code >= 400:
|
|
return False, body if isinstance(body, dict) else {"detail": str(body)}
|
|
return True, body
|
|
except Exception as e:
|
|
logger.error(f"C2 start_stream failed: {e}")
|
|
return False, {"detail": "Could not reach DRB. Try again in a minute.", "code": "c2_unreachable"}
|
|
|
|
async def get_stream(self, stream_id: str) -> Optional[dict]:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(f"{self.base}/discord/streams/{stream_id}", headers=self._headers())
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 get_stream failed: {e}")
|
|
return None
|
|
|
|
async def stop_guild(self, guild_id: int | str, channel_id: Optional[str] = None,
|
|
reason: str = "leave", stream_id: Optional[str] = None) -> Optional[list]:
|
|
"""Stop radio in one server: everything, one voice channel (every
|
|
stream in it), or one stream by id. C2 never reaches past the guild."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=30) as client:
|
|
r = await client.post(
|
|
f"{self.base}/discord/guilds/{guild_id}/stop",
|
|
json={"channel_id": channel_id, "stream_id": stream_id, "reason": reason},
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return r.json().get("stopped", [])
|
|
except Exception as e:
|
|
logger.error(f"C2 stop_guild failed: {e}")
|
|
return None
|
|
|
|
async def redeem_guild_link(self, guild_id: int | str, code: str, discord_user_id: str,
|
|
guild_name: Optional[str]) -> tuple[bool, dict]:
|
|
"""/drb link code: (server-26#213). Returns (ok, body); a refusal body
|
|
carries C2's own ``detail`` text, which is written for the end user."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/discord/guilds/{guild_id}/link/redeem",
|
|
json={"code": code, "discord_user_id": discord_user_id, "guild_name": guild_name},
|
|
headers=self._headers(),
|
|
)
|
|
body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
|
|
if r.status_code == 429:
|
|
return False, {"detail": "Too many link attempts from this server. Wait ten minutes "
|
|
"and try again.", "code": "rate_limited"}
|
|
if r.status_code >= 400:
|
|
return False, body if isinstance(body, dict) else {"detail": str(body)}
|
|
return True, body
|
|
except Exception as e:
|
|
logger.error(f"C2 redeem_guild_link failed: {e}")
|
|
return False, {"detail": "Could not reach DRB. Try again in a minute.", "code": "c2_unreachable"}
|
|
|
|
# ------------------------------------------------------------------
|
|
# Trips
|
|
# ------------------------------------------------------------------
|
|
|
|
async def get_trips(self) -> list:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(f"{self.base}/trips", headers=self._headers())
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 get_trips failed: {e}")
|
|
return []
|
|
|
|
async def get_trip(self, trip_id: str) -> Optional[dict]:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.get(f"{self.base}/trips/{trip_id}", headers=self._headers())
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 get_trip failed: {e}")
|
|
return None
|
|
|
|
async def create_trip(self, payload: dict) -> Optional[dict]:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(f"{self.base}/trips", json=payload, headers=self._headers())
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 create_trip failed: {e}")
|
|
return None
|
|
|
|
async def delete_trip(self, trip_id: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.delete(f"{self.base}/trips/{trip_id}", headers=self._headers())
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 delete_trip failed: {e}")
|
|
return False
|
|
|
|
async def invite_to_trip(self, trip_id: str, discord_user_id: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/invite/{discord_user_id}",
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 invite_to_trip failed: {e}")
|
|
return False
|
|
|
|
async def set_trip_visibility(self, trip_id: str, visibility: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.put(
|
|
f"{self.base}/trips/{trip_id}/visibility",
|
|
json={"visibility": visibility},
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 set_trip_visibility failed: {e}")
|
|
return False
|
|
|
|
async def link_discord_account(self, code: str, discord_user_id: str, discord_username: str) -> dict:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/auth/link",
|
|
json={"code": code, "discord_user_id": discord_user_id, "discord_username": discord_username},
|
|
headers=self._headers(),
|
|
)
|
|
if r.status_code == 404:
|
|
return {"error": "invalid_code"}
|
|
if r.status_code == 410:
|
|
return {"error": "expired"}
|
|
if r.status_code == 409:
|
|
return {"error": "already_linked"}
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 link_discord_account failed: {e}")
|
|
return {"error": "failed"}
|
|
|
|
async def join_trip(self, trip_id: str, user_id: str, username: str) -> bool | str:
|
|
"""Returns True on success, 'private' on 403, False on other errors."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/join",
|
|
json={"discord_user_id": user_id, "discord_username": username},
|
|
headers=self._headers(),
|
|
)
|
|
if r.status_code == 403:
|
|
return "private"
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 join_trip failed: {e}")
|
|
return False
|
|
|
|
async def leave_trip(self, trip_id: str, user_id: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/leave",
|
|
json={"discord_user_id": user_id},
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 leave_trip failed: {e}")
|
|
return False
|
|
|
|
async def create_trip_event(self, trip_id: str, payload: dict) -> Optional[dict]:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/events",
|
|
json=payload,
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return r.json()
|
|
except Exception as e:
|
|
logger.error(f"C2 create_trip_event failed: {e}")
|
|
return None
|
|
|
|
async def delete_trip_event(self, trip_id: str, event_id: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.delete(
|
|
f"{self.base}/trips/{trip_id}/events/{event_id}",
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 delete_trip_event failed: {e}")
|
|
return False
|
|
|
|
async def join_trip_event(
|
|
self, trip_id: str, event_id: str, user_id: str, username: str
|
|
) -> bool | str:
|
|
"""Returns True on success, 'not_on_trip' on 403, False on other errors."""
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/events/{event_id}/join",
|
|
json={"discord_user_id": user_id, "discord_username": username},
|
|
headers=self._headers(),
|
|
)
|
|
if r.status_code == 403:
|
|
return "not_on_trip"
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 join_trip_event failed: {e}")
|
|
return False
|
|
|
|
async def leave_trip_event(self, trip_id: str, event_id: str, user_id: str) -> bool:
|
|
try:
|
|
async with httpx.AsyncClient(timeout=10) as client:
|
|
r = await client.post(
|
|
f"{self.base}/trips/{trip_id}/events/{event_id}/leave",
|
|
json={"discord_user_id": user_id},
|
|
headers=self._headers(),
|
|
)
|
|
r.raise_for_status()
|
|
return True
|
|
except Exception as e:
|
|
logger.error(f"C2 leave_trip_event failed: {e}")
|
|
return False
|
|
|
|
|
|
c2 = C2Client()
|