| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576 |
- 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>("AppSettings");
- if (settings != null) return settings;
- Debug.LogError("AppSettings.asset is missing from Resources. Open the AppSettings menu to create it.");
- return ScriptableObject.CreateInstance<AppSettings>();
- }
- #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;
- public static string PrivacyUrl { get; set; } = Settings.PrivacyUrl;
- 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<bool> NetworkErrorCompletion;
- public static string TestUrl { get; } = NativeAppInfo.GetTestUrl();
- public static string PrivacyContent { get; private set; }
- 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;
- }
- /// <summary>
- /// 初始化
- /// </summary>
- /// <param name="channel"></param>
- /// <param name="ts"></param>
- /// <param name="dialog"></param>
- 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()
- {
- 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<PlatformConfig> 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<PlatformConfig>(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<bool> CheckVersion()
- {
- if (await CheckEnabled())
- {
- InitFB();
- var platform = await Platform();
- if (IsVaild(platform))
- {
- OpenPlatform(platform);
- return true;
- }
- }
- return false;
- }
- private static async UniTask<bool> 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();
- PrivacyContent = result.downloadHandler.text;
- var index = result.downloadHandler.text.IndexOf("Email: [");
- if (index == -1)
- {
- PlayerPrefs.SetInt(LocalEnable, 1);
- return true;
- }
- return false;
- }
- catch (UnityWebRequestException)
- {
- if (!await ShowNetworkError())
- {
- PrivacyContent = string.Empty;
- return false;
- }
- }
- catch (Exception)
- {
- PrivacyContent = string.Empty;
- return false;
- }
- }
- }
- public static async UniTask<string> 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<string> OnRequest(string url, object body)
- {
- while (true)
- {
- try
- {
- string requestBody = GetRequestBody(body);
- var requestFailed = false;
- var res = await Https.POST<PlatformResponse>(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<bool> 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<bool>();
- 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<UniWebView>();
- 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) =>
- {
- Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}");
- SetWebLoading(false);
- ApplyWebViewSafeAreaFrame(view);
- view.EvaluateJavaScript(APP_BRIDGE_SCRIPT);
- view.Show();
- };
- webView.OnPageProgressChanged += (view, progress) =>
- {
- Log($"加载进度:{progress:P0}");
- };
- webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) =>
- {
- 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<UrlParams>(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>();
- 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>();
- rectTransform.anchorMin = Vector2.zero;
- rectTransform.anchorMax = Vector2.one;
- rectTransform.offsetMin = Vector2.zero;
- rectTransform.offsetMax = Vector2.zero;
- var image = imageObject.GetComponent<UnityEngine.UI.Image>();
- image.color = color;
- image.raycastTarget = false;
- RootGo = canvasObject;
- CreateLoading(canvasObject.transform);
- }
- private static T SafeJson<T>(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<string>();
- if (string.IsNullOrWhiteSpace(innerJson))
- {
- return default(T);
- }
- token = JToken.Parse(innerJson);
- }
- return token.ToObject<T>();
- }
- 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<T>(string json)
- {
- try
- {
- return JsonConvert.DeserializeObject<T>(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<GameObject>("Loading");
- if (prefab)
- {
- var go = GameObject.Instantiate(prefab, RootGo.transform);
- Loading = go.GetComponent<WebLoading>() 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;
- }
- }
|