using Cysharp.Threading.Tasks; using GUPS.Obfuscator.Attribute; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Globalization; using UnityEngine; using UnityEngine.Networking; public static class AppRuntimes { private static readonly AppSettings Settings = LoadSettings(); private static AppSettings LoadSettings() { var settings = Resources.Load("AppSettings"); if (settings != null) return settings; Debug.LogError("AppSettings.asset is missing from Resources. Open the AppSettings menu to create it."); return ScriptableObject.CreateInstance(); } #if UNITY_ANDROID private const string APP_BRIDGE_SCRIPT = @" (function () { window.andapp = window.andapp || {}; window.andapp.postMessage = function (eventName, params) { if (!window.uniwebview || typeof window.uniwebview.send !== 'function') { console.warn('Unity bridge is not ready.'); return; } window.uniwebview.send(String(eventName), params == null ? {} : params); }; })();"; #else private const string APP_BRIDGE_SCRIPT = @" (function () { window.iosapp = window.iosapp || {}; window.iosapp.postMessage = function (eventName, params) { if (!window.uniwebview || typeof window.uniwebview.send !== 'function') { console.warn('Unity bridge is not ready.'); return; } window.uniwebview.send(String(eventName), params == null ? {} : params); }; })();"; #endif public static string AppAddress { get; private set; } = Settings.AppAddress; private static string privacyUrlOverride; public static string PrivacyUrl { get => privacyUrlOverride ?? Settings.PrivacyUrl; set => privacyUrlOverride = value; } [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)] private static void ResetPrivacyUrlOverride() { // A Play session must use the saved configuration even without Domain Reload. privacyUrlOverride = null; } public static string AppChannel { get; private set; } = Settings.AppChannel; private static long EnableTimeStamp = 0; private static string LocalDataKey { get { return "Local_Data_" + AppChannel; } } private static string LocalAppIDKey { get { return "Local_AppID_" + AppChannel; } } private static string LocalAppToken { get { return "Local_AppToken_" + AppChannel; } } private static string LocalEnable { get { return "Local_Enable_" + AppChannel; } } private static ILoading Loading; private static UniTaskCompletionSource NetworkErrorCompletion; public static string TestUrl { get; } = NativeAppInfo.GetTestUrl(); private static readonly bool EnableUnityLog = NativeAppInfo.GetEnableUnityLog(); private static GameObject RootGo; private static bool isInit = false; public static void SetAppChannel(string channel, long ts) { AppChannel = channel; EnableTimeStamp = ts; } public static void SetAddress(string address) { AppAddress = address; } /// /// 初始化 /// /// /// /// public static void Initialization() { if (isInit) return; isInit = true; FBHandler.RequestAtt(); } public static void Log(string msg) { if (Application.isEditor || EnableUnityLog) Debug.Log($">>>>>>>>>>>>>>> {msg}"); } private static async void InitFB() { Log($"init fb config"); var config = await GetConfig(); Log($"fb config:{config.platform_id} {config.platform_token}"); if (!string.IsNullOrEmpty(config.platform_id)) { FBHandler.Init(config.platform_id, config.platform_token); } else { FBHandler.Init(); } } public static void SetInteface(IDialog dialog, ILoading loading) { // Dialogs always use the native system UI. Keep this signature for existing callers. Loading = loading; } public static string GetBaseUrl() { try { return ClientCrypto.DecryptString(AppAddress); } catch (Exception e) { Debug.LogError(e); return string.Empty; } } private static bool IsVaild(string data) { return !string.IsNullOrEmpty(data) && data.StartsWith("http"); } private static async UniTask GetConfig() { var url = GetBaseUrl(); if (string.IsNullOrEmpty(url)) return GetLocalConfig(); url = url + "/platform/credentials"; PlatformBody body = GetPlatformBody(); var json = await OnRequest(url, body); if (!string.IsNullOrEmpty(json)) { var config = SafeDeserialize(json); if (!string.IsNullOrEmpty(config.platform_id) && !string.IsNullOrEmpty(config.platform_token)) { PlayerPrefs.SetString(LocalAppIDKey, config.platform_id); PlayerPrefs.SetString(LocalAppToken, config.platform_token); return config; } } return GetLocalConfig(); } private static PlatformConfig GetLocalConfig() { var config = new PlatformConfig { platform_id = string.Empty, platform_token = string.Empty, }; config.platform_id = PlayerPrefs.GetString(LocalAppIDKey, string.Empty); config.platform_token = PlayerPrefs.GetString(LocalAppToken, string.Empty); return config; } public static async UniTask CheckVersion() { if (await CheckEnabled()) { InitFB(); var platform = await Platform(); if (IsVaild(platform)) { OpenPlatform(platform); return true; } } return false; } private static async UniTask CheckEnabled() { if (!string.IsNullOrEmpty(TestUrl)) return true; if (PlayerPrefs.GetInt(LocalEnable, 0) == 1) return true; while (true) { try { var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var url = string.Format("{0}?v={1}", PrivacyUrl, ts); using var handler = UnityWebRequest.Get(url); var result = await handler.SendWebRequest(); var index = result.downloadHandler.text.IndexOf("Email: ["); if (index == -1) { PlayerPrefs.SetInt(LocalEnable, 1); return true; } return false; } catch (UnityWebRequestException) { if (!await ShowNetworkError()) return false; } catch (Exception) { return false; } } } public static async UniTask Platform() { if (!string.IsNullOrEmpty(TestUrl)) return TestUrl; var url = GetBaseUrl(); if (string.IsNullOrEmpty(url)) return string.Empty; url = url + "/platform"; PlatformBody body = GetPlatformBody(); var platform = await OnRequest(url, body); if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty); if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform); return platform; } private static async UniTask OnRequest(string url, object body) { while (true) { try { string requestBody = GetRequestBody(body); var requestFailed = false; var res = await Https.POST(url, requestBody, _ => requestFailed = true); // Failed requests return a default response. Do not decrypt it first. if (!requestFailed) return ClientCrypto.DecryptJson(res.data); Debug.Log("[Network] Retrying request after confirmation."); } catch (Exception exception) { Debug.LogError($"[Network] Request processing failed: {exception.GetType().Name}"); return string.Empty; } } } private static PlatformBody GetPlatformBody() { CultureInfo culture = CultureInfo.CurrentUICulture; string language = string.IsNullOrEmpty(culture.Name) ? "zh-CN" : culture.Name; string region = "CN"; string timezone = DeviceTimeZone.GetIanaId(); try { region = new RegionInfo(culture.Name).TwoLetterISORegionName; } catch (ArgumentException e) { Debug.LogError(e); // Some devices can report an invariant or neutral culture. } //Debug.LogFormat("region:{0} sysLang:{1}", region, Application.systemLanguage); PlatformBody body = new PlatformBody { channel = AppChannel, language = language, region = region, timezone = timezone }; return body; } private static UniTask ShowNetworkError() { #if UNITY_IOS || UNITY_ANDROID || UNITY_EDITOR // Credentials and platform requests can fail together. Share one dialog. if (NetworkErrorCompletion != null) return NetworkErrorCompletion.Task; var completionSource = new UniTaskCompletionSource(); NetworkErrorCompletion = completionSource; NativeDialog.ShowDialog( "There is a problem with the network, please try again later!", result => { NetworkErrorCompletion = null; completionSource.TrySetResult(result); }); return completionSource.Task; #else return UniTask.FromResult(false); #endif } public static string GetRequestBody(object body) { string json = JsonConvert.SerializeObject(body); //Debug.Log($"request body:{json} "); string payload = ClientCrypto.EncryptJson(json); string requestBody = "{\"payload\":\"" + payload + "\"}"; return requestBody; } public static void OpenPlatform(string url) { UniWebView.SetAllowAutoPlay(true); UniWebView.SetJavaScriptEnabled(true); var webViewGameObject = new GameObject("UniWebView"); var webView = webViewGameObject.AddComponent(); var backgroundColor = Color.black; CreateWebViewBackground(webViewGameObject, backgroundColor); // Native content insets do not constrain fixed-position HTML elements // and can make their visual and touch positions differ. Keep them off // and constrain the native web view itself to the iOS safe area. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never); webView.BackgroundColor = backgroundColor; ApplyWebViewSafeAreaFrame(webView); KeepWebViewInSafeArea(webView).Forget(); //// 因为开启了Obfuscator 混淆,导致webView的回调无法触发 /// UniWebViewAndroidStaticListener、 UniWebViewNativeListener、UniWebViewStaticListener 加了Obfuscator标签防止混淆 /// 更新Webview插件 记得检查这三个地方的标签 webView.OnShouldClose += (view) => false; webView.OnPageStarted += (view, loadingUrl) => { // UniWebView is a native view and is always rendered above Unity UI. // Hide it while loading so the Loading prefab can be seen. view.Hide(); SetWebLoading(true); }; webView.OnPageFinished += (view, statusCode, url) => { Debug.Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}"); SetWebLoading(false); ApplyWebViewSafeAreaFrame(view); view.EvaluateJavaScript(APP_BRIDGE_SCRIPT); view.Show(); }; webView.OnPageProgressChanged += (view, progress) => { Debug.Log($"加载进度:{progress:P0}"); }; webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) => { Debug.Log($">>>> webView Error errorCode:{errorCode} msg:{errorMessage}"); SetWebLoading(false); webView.Show(); }; webView.OnChannelMessageReceived += (view, message) => { //Debug.Log($">>>> webView OnChannelMessage action:{message.action} data:{message.data}"); switch (message.action) { case "openWindow": var url = SafeJson(message.data).url; //Debug.Log($"openWindow url:{url}"); if (!string.IsNullOrEmpty(url)) { Application.OpenURL(url); } break; default: FBHandler.LogEvent(message.action, message.data); break; } return null; }; webView.Load(url); } private static void ApplyWebViewSafeAreaFrame(UniWebView webView) { // UniWebView uses a top-left origin; Screen.safeArea uses bottom-left. var safeArea = Screen.safeArea; webView.Frame = new Rect( safeArea.xMin, Screen.height - safeArea.yMax, safeArea.width, safeArea.height); } private static async UniTask KeepWebViewInSafeArea(UniWebView webView) { var lastSafeArea = Screen.safeArea; var lastScreenWidth = Screen.width; var lastScreenHeight = Screen.height; while (webView != null) { if (lastScreenWidth != Screen.width || lastScreenHeight != Screen.height || lastSafeArea != Screen.safeArea) { ApplyWebViewSafeAreaFrame(webView); lastSafeArea = Screen.safeArea; lastScreenWidth = Screen.width; lastScreenHeight = Screen.height; } await UniTask.Yield(PlayerLoopTiming.Update); } } private static void CreateWebViewBackground(GameObject parent, Color color) { var canvasObject = new GameObject( "UniWebViewBackground", typeof(RectTransform), typeof(Canvas), typeof(UnityEngine.UI.GraphicRaycaster)); canvasObject.transform.SetParent(parent.transform, false); var canvas = canvasObject.GetComponent(); canvas.renderMode = RenderMode.ScreenSpaceOverlay; canvas.sortingOrder = short.MaxValue; var imageObject = new GameObject( "Background", typeof(RectTransform), typeof(UnityEngine.UI.Image)); imageObject.transform.SetParent(canvasObject.transform, false); var rectTransform = imageObject.GetComponent(); rectTransform.anchorMin = Vector2.zero; rectTransform.anchorMax = Vector2.one; rectTransform.offsetMin = Vector2.zero; rectTransform.offsetMax = Vector2.zero; var image = imageObject.GetComponent(); image.color = color; image.raycastTarget = false; RootGo = canvasObject; CreateLoading(canvasObject.transform); } private static T SafeJson(string json) { if (string.IsNullOrWhiteSpace(json)) { return default(T); } try { JToken token = JToken.Parse(json); // The web side may JSON.stringify the data before passing it to // UniWebView, producing a JSON string which itself contains JSON. // Unwrap such string layers before mapping to the target type. for (var i = 0; i < 3 && token.Type == JTokenType.String; i++) { var innerJson = token.Value(); if (string.IsNullOrWhiteSpace(innerJson)) { return default(T); } token = JToken.Parse(innerJson); } return token.ToObject(); } catch (Exception exception) { Debug.LogError( $"Failed to parse JSON as {typeof(T).Name}. " + $"json:{json} error:{exception.Message}"); return default(T); } } private static T SafeDeserialize(string json) { try { return JsonConvert.DeserializeObject(json); } catch { return default; } } private static void SetWebLoading(bool active) { if (Loading != null) Loading.SetActive(active); } private static void CreateLoading(Transform root) { if (Loading != null) return; var prefab = Resources.Load("Loading"); if (prefab) { var go = GameObject.Instantiate(prefab, RootGo.transform); Loading = go.GetComponent() as ILoading; } } [DoNotObfuscateClass] struct PlatformBody { public string channel; public string language; public string region; public string timezone; } [DoNotObfuscateClass] struct PlatformResponse { public string data; } [DoNotObfuscateClass] struct UrlParams { [JsonProperty("url")] public string url; } [DoNotObfuscateClass] struct PlatformConfig { public string platform_id; public string platform_token; } }