using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using UnityEngine; using UnityEngine.Networking; namespace IDCGames.API { /// /// Friends direct-message chat: REST against /api/v1/chat. /// Real-time: use GET realtime-config + Pusher-compatible client (see docs/CHAT_API.md). /// public class IDCChatManager : MonoBehaviour { [Header("API")] public string apiBaseUrl = "http://localhost:8000"; public event Action OnChatError; private string _accessToken; public void SetAccessToken(string token) => _accessToken = token; public async Task GetRealtimeConfigAsync() { return await GetAsync("/api/v1/chat/realtime-config"); } public async Task OpenConversationAsync(int friendUserId) { var body = JsonConvert.SerializeObject(new { friend_user_id = friendUserId }); return await PostAsync("/api/v1/chat/conversations", body); } public async Task> ListConversationsAsync(int perPage = 20) { return await GetAsync>( $"/api/v1/chat/conversations?per_page={perPage}"); } public async Task> GetMessagesAsync(int conversationId, int perPage = 50, int? beforeId = null) { var url = $"/api/v1/chat/conversations/{conversationId}/messages?per_page={perPage}"; if (beforeId.HasValue) url += $"&before_id={beforeId.Value}"; return await GetAsync>(url); } public async Task SendMessageAsync(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); } public async Task MarkReadAsync(int conversationId, int messageId) { var body = JsonConvert.SerializeObject(new { message_id = messageId }); await PostAsync($"/api/v1/chat/conversations/{conversationId}/read", body); } 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; OnChatError?.Invoke(err); throw new Exception(err); } if (req.responseCode != expectedCode && req.responseCode != 200) { var err = $"HTTP {req.responseCode}: {req.downloadHandler?.text}"; OnChatError?.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 ApiSuccessWrapper { public bool success; public T data; } [Serializable] public class ChatRealtimeConfig { public bool enabled; public string broadcaster; public string auth_endpoint; public string key; public string ws_host; public int ws_port; public string ws_scheme; public bool force_tls; } [Serializable] public class ChatConversationSummary { public int id; public string type; public ChatFriendRef friend; public ChatMessageDto last_message; public int unread_count; public string last_message_at; public string channel; } [Serializable] public class ChatFriendRef { public int id; public string username; } [Serializable] public class ChatMessageDto { public int id; public int conversation_id; public int sender_id; public string sender_username; public string body; public string client_message_id; public string created_at; } [Serializable] public class PaginatedData { public List data; public int current_page; public int last_page; public int per_page; public int total; } }