using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using UnityEngine; using UnityEngine.Networking; namespace IDCGames.API { /// /// Match session: group chat + voice (LiveKit or Mumble) via /api/v1/matches. /// Text real-time: same Reverb channel as group chat (see IDCChatManager + docs/CHAT_API.md). /// Voice WebRTC: install LiveKit Unity SDK, connect with JoinMatchAsync credentials. /// REQUIRED: enable VAD before publishing mic (GET /api/v1/voice/config → client_requirements.vad). /// public class IDCMatchVoiceManager : MonoBehaviour { [Header("API")] public string apiBaseUrl = "http://localhost:8000"; [Header("Voice")] [Tooltip("livekit or mumble — must match server config")] public string voiceProvider = "livekit"; public event Action OnMatchVoiceError; private string _accessToken; public void SetAccessToken(string token) => _accessToken = token; public async Task GetVoiceConfigAsync() { var data = await GetAsync("/api/v1/voice/config"); return data.client_requirements; } /// Host creates match (same match_key as your game server). public async Task CreateMatchAsync(string matchKey, int[] memberUserIds = null, string label = null) { var payload = new Dictionary { { "match_key", matchKey }, { "member_user_ids", memberUserIds ?? Array.Empty() }, }; if (!string.IsNullOrEmpty(label)) payload["label"] = label; var json = JsonConvert.SerializeObject(payload); return await PostAsync("/api/v1/matches", json, expectCreated: true); } public async Task GetMatchAsync(string matchKey) { return await GetAsync($"/api/v1/matches/{Uri.EscapeDataString(matchKey)}"); } /// Returns all/team chat channels + optional LiveKit token or Mumble credentials (voice requires teamId). public async Task JoinMatchAsync(string matchKey, bool voiceEnabled, string teamId = null) { if (voiceEnabled && string.IsNullOrWhiteSpace(teamId)) throw new ArgumentException("team_id is required when voice is enabled (match voice is team-only)."); var body = JsonConvert.SerializeObject(new { voice_enabled = voiceEnabled, voice_provider = voiceEnabled ? voiceProvider : null, team_id = teamId, }); return await PostAsync( $"/api/v1/matches/{Uri.EscapeDataString(matchKey)}/join", body); } public async Task LeaveMatchAsync(string matchKey) { await PostAsync($"/api/v1/matches/{Uri.EscapeDataString(matchKey)}/leave", "{}"); } public async Task SendMatchChatAsync(int conversationId, string body, string clientMessageId = null) { var payload = new Dictionary { { "body", body } }; if (!string.IsNullOrEmpty(clientMessageId)) payload["client_message_id"] = clientMessageId; var json = JsonConvert.SerializeObject(payload); return await PostAsync( $"/api/v1/chat/conversations/{conversationId}/messages", json, expectCreated: true); } private async Task GetAsync(string path) { using var req = UnityWebRequest.Get(apiBaseUrl.TrimEnd('/') + path); req.SetRequestHeader("Authorization", "Bearer " + _accessToken); req.SetRequestHeader("Accept", "application/json"); await SendAsync(req); return ParseData(req); } private async Task PostAsync(string path, string jsonBody, bool expectCreated = false) { using var req = new UnityWebRequest(apiBaseUrl.TrimEnd('/') + path, "POST"); var bytes = Encoding.UTF8.GetBytes(jsonBody); req.uploadHandler = new UploadHandlerRaw(bytes); req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Authorization", "Bearer " + _accessToken); req.SetRequestHeader("Content-Type", "application/json"); req.SetRequestHeader("Accept", "application/json"); await SendAsync(req, expectCreated ? 201 : 200); return ParseData(req); } private async Task SendAsync(UnityWebRequest req, int expectedCode = 200) { var op = req.SendWebRequest(); while (!op.isDone) await Task.Yield(); if (req.result != UnityWebRequest.Result.Success) { var err = req.error + " " + req.downloadHandler?.text; OnMatchVoiceError?.Invoke(err); throw new Exception(err); } if (req.responseCode != expectedCode && req.responseCode != 200) { var err = $"HTTP {req.responseCode}: {req.downloadHandler?.text}"; OnMatchVoiceError?.Invoke(err); throw new Exception(err); } } private static T ParseData(UnityWebRequest req) { var wrapper = JsonConvert.DeserializeObject>(req.downloadHandler.text); if (wrapper == null || !wrapper.success) throw new Exception("API error: " + req.downloadHandler.text); return wrapper.data; } } [Serializable] public class VoiceConfigData { public VoiceClientRequirements client_requirements; } [Serializable] public class VoiceClientRequirements { public VadRequirement vad; } [Serializable] public class VadRequirement { public bool required; public string policy; public string summary; } [Serializable] public class MatchSessionDto { public string match_key; public int[] presence_user_ids; public MatchChatChannels chat; public MatchVoiceInfo voice; } [Serializable] public class MatchChatChannels { public MatchChatInfo all; public MatchChatInfo team; } [Serializable] public class MatchChatInfo { public int conversation_id; public string type; public string name; public string channel; } [Serializable] public class MatchVoiceInfo { public string scope; public bool team_id_required; public MatchVoiceTeamInfo team; } [Serializable] public class MatchVoiceTeamInfo { public int voice_room_id; public string livekit_room_name; public string mumble_channel; public int max_participants; } [Serializable] public class MatchJoinResult { public string match_key; public string team_id; public int voice_room_id; public MatchJoinText text; public MatchJoinVoice voice; } [Serializable] public class MatchJoinText { public MatchChatInfo all; public MatchChatInfo team; } [Serializable] public class MatchJoinVoice { public bool voice_enabled; public string provider; public string url; public string token; public string room_name; public string host; public int port; public string channel; public string username; public string password; public int expires_in; } }