using System; using System.Net.Http; using System.Threading.Tasks; using asap.core; using GameCore; using UnityEngine; public struct RequestSvrTimeEvent { public bool Status; } public class ZZTimeHelper { public static TimeSpan timeDiff = TimeSpan.Zero; public static bool isAttachedToFChange = false; static bool isRequesting = false; public static int LocalTimeOffsetInSec = 0; public static DateTime UtcNow() { return DateTime.UtcNow.AddSeconds(LocalTimeOffsetInSec) + timeDiff; } public static void AdjustTime(DateTime svrTime) { var diff = svrTime - DateTime.UtcNow; if(Mathf.Abs((float)diff.TotalSeconds) < 60) { timeDiff = TimeSpan.Zero; } else { timeDiff = diff; } //UnityEngine.Debug.Log("[ZZTimeHelper] AdjustTime:" + timeDiff); } public static void WathForcusChange() { if (!isAttachedToFChange) { UnityEngine.Application.focusChanged += focused => { if (focused) { UnityEngine.Debug.Log("[ZZTimeHelper] RequestSvrTime"); _ = RequestSvrTime(); } }; isAttachedToFChange = true; } } /// /// Request ServerTime, but also sync data. /// /// True if needing to sync data. public static async Task RequestSvrTime() { if (isRequesting) { return; } GameCore.UIManager.ShowWaitingBlock("RequestSvrTime"); isRequesting = true; var SvrTime = await GetSvrTime(); isRequesting = false; GameCore.UIManager.HideWaitingBlock("RequestSvrTime"); if(SvrTime != null) { AdjustTime(SvrTime.Value); GContext.Publish(new RequestSvrTimeEvent() { Status = true }); } else { GContext.Publish(new RequestSvrTimeEvent() { Status = false }); GameObject go = await UIManager.Instance.ShowUI(UITypes.NoticeConfirmPopupPanel); var NoticeConfirmPopupPanel = go.GetComponent(); string info = LocalizationMgr.GetText("UI_FishingReconnectPanel_101003"); string label = LocalizationMgr.GetText("UI_FishingRewardPanel_101022"); string title = LocalizationMgr.GetText("UI_FishingReconnectPanel_101002"); NoticeConfirmPopupPanel.Init(1, title, info, onClickLeft: async () => {await RequestSvrTime();}, onClose: async () =>{ await RequestSvrTime();}, btn_left_text: label); } } //private const string timeUrl = "http://time.bamboogames.cc"; private static async Task GetSvrTime() { try { HttpClient client = new HttpClient(); client.Timeout = TimeSpan.FromSeconds(5); IConfig config = GContext.container.Resolve(); string apiUrl = config.Get(GConstant.K_Event_API_URL, "http://192.168.9.101:5292/"); string url = $"{apiUrl}account/svrtime"; var svrTimeStr = await client.GetStringAsync(url); // var svrTimeStr = await client.GetStringAsync(timeUrl); if (!string.IsNullOrEmpty(svrTimeStr)) { if(DateTime.TryParse(svrTimeStr, out DateTime SvrTime)) { if(SvrTime.Kind == DateTimeKind.Local) SvrTime = SvrTime.ToUniversalTime(); return SvrTime; } } return null; } catch(System.Exception) { UnityEngine.Debug.LogWarning("[ZZTimeHelper] RequestSvrTime error"); return null; } } }