using System; using System.Text; using BrewMonster; using Cysharp.Threading.Tasks; using UnityEngine; using UnityEngine.Networking; namespace BrewMonster.Scripts { /// /// Kết quả lấy contentVersion / assetsBaseUrl (từ server hoặc hardcode). /// Result of fetching contentVersion / assetsBaseUrl (from server or hardcoded). /// public readonly struct GameContentVersionFetchResult { public GameContentVersionFetchResult(bool ok, string contentVersion, string assetsBaseUrl, string error) { Ok = ok; ContentVersion = contentVersion; AssetsBaseUrl = assetsBaseUrl; Error = error; } public bool Ok { get; } public string ContentVersion { get; } public string AssetsBaseUrl { get; } public string Error { get; } } /// /// Gửi GET hoặc POST (JSON body) lên server, parse JSON phẳng (JsonUtility). /// Sends GET or POST (JSON body) to server and parses flat JSON (JsonUtility). /// public static class GameContentVersionServerClient { /// /// GET hoặc POST JSON; response: { "contentVersion": "12", "assetsBaseUrl": "https://..." }. /// GET or POST JSON; response shape: { "contentVersion": "12", "assetsBaseUrl": "https://..." }. /// /// false = GET; true = POST với (rỗng → "{}"). / false = GET; true = POST with body (empty → "{}"). public static async UniTask FetchAsync( string url, int timeoutSeconds, bool usePost = false, string postJsonBody = null) { if (string.IsNullOrWhiteSpace(url)) return new GameContentVersionFetchResult(false, null, null, "version URL is empty"); try { UnityWebRequest req; if (usePost) { string body = string.IsNullOrWhiteSpace(postJsonBody) ? "{}" : postJsonBody.Trim(); byte[] raw = Encoding.UTF8.GetBytes(body); req = new UnityWebRequest(url, UnityWebRequest.kHttpVerbPOST); req.uploadHandler = new UploadHandlerRaw(raw) { contentType = "application/json" }; req.downloadHandler = new DownloadHandlerBuffer(); req.SetRequestHeader("Content-Type", "application/json"); } else { req = UnityWebRequest.Get(url); } using (req) { req.timeout = Mathf.Max(5, timeoutSeconds); await req.SendWebRequest().ToUniTask(); if (req.result != UnityWebRequest.Result.Success) return new GameContentVersionFetchResult(false, null, null, req.error); string json = req.downloadHandler?.text; if (string.IsNullOrWhiteSpace(json)) return new GameContentVersionFetchResult(false, null, null, "Empty response body"); var parsed = JsonUtility.FromJson(json); if (parsed == null || string.IsNullOrWhiteSpace(parsed.contentVersion)) return new GameContentVersionFetchResult(false, null, null, "JSON missing contentVersion"); return new GameContentVersionFetchResult( true, parsed.contentVersion.Trim(), string.IsNullOrWhiteSpace(parsed.assetsBaseUrl) ? null : parsed.assetsBaseUrl.Trim(), null); } } catch (Exception e) { BMLogger.LogError($"[Cuong] GameContentVersionServerClient: {e.Message}"); return new GameContentVersionFetchResult(false, null, null, e.Message); } } [Serializable] class VersionResponseJson { public string contentVersion; public string assetsBaseUrl; } } }