AppRuntimes.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. using Cysharp.Threading.Tasks;
  2. using GUPS.Obfuscator.Attribute;
  3. using Newtonsoft.Json;
  4. using Newtonsoft.Json.Linq;
  5. using System;
  6. using System.Globalization;
  7. using UnityEngine;
  8. using UnityEngine.Networking;
  9. public static class AppRuntimes
  10. {
  11. private static readonly AppSettings Settings = LoadSettings();
  12. private static AppSettings LoadSettings()
  13. {
  14. var settings = Resources.Load<AppSettings>("AppSettings");
  15. if (settings != null) return settings;
  16. Debug.LogError("AppSettings.asset is missing from Resources. Open the AppSettings menu to create it.");
  17. return ScriptableObject.CreateInstance<AppSettings>();
  18. }
  19. #if UNITY_ANDROID
  20. private const string APP_BRIDGE_SCRIPT = @"
  21. (function () {
  22. window.andapp = window.andapp || {};
  23. window.andapp.postMessage = function (eventName, params) {
  24. if (!window.uniwebview || typeof window.uniwebview.send !== 'function') {
  25. console.warn('Unity bridge is not ready.');
  26. return;
  27. }
  28. window.uniwebview.send(String(eventName), params == null ? {} : params);
  29. };
  30. })();";
  31. #else
  32. private const string APP_BRIDGE_SCRIPT = @"
  33. (function () {
  34. window.iosapp = window.iosapp || {};
  35. window.iosapp.postMessage = function (eventName, params) {
  36. if (!window.uniwebview || typeof window.uniwebview.send !== 'function') {
  37. console.warn('Unity bridge is not ready.');
  38. return;
  39. }
  40. window.uniwebview.send(String(eventName), params == null ? {} : params);
  41. };
  42. })();";
  43. #endif
  44. public static string AppAddress { get; private set; } = Settings.AppAddress;
  45. public static string PrivacyUrl { get; set; } = Settings.PrivacyUrl;
  46. public static string AppChannel { get; private set; } = Settings.AppChannel;
  47. private static long EnableTimeStamp = 0;
  48. private static string LocalDataKey { get { return "Local_Data_" + AppChannel; } }
  49. private static string LocalAppIDKey { get { return "Local_AppID_" + AppChannel; } }
  50. private static string LocalAppToken { get { return "Local_AppToken_" + AppChannel; } }
  51. private static string LocalEnable { get { return "Local_Enable_" + AppChannel; } }
  52. private static ILoading Loading;
  53. private static UniTaskCompletionSource<bool> NetworkErrorCompletion;
  54. public static string TestUrl { get; } = NativeAppInfo.GetTestUrl();
  55. public static string PrivacyContent { get; private set; }
  56. private static readonly bool EnableUnityLog = NativeAppInfo.GetEnableUnityLog();
  57. private static GameObject RootGo;
  58. private static bool isInit = false;
  59. public static void SetAppChannel(string channel, long ts)
  60. {
  61. AppChannel = channel;
  62. EnableTimeStamp = ts;
  63. }
  64. public static void SetAddress(string address)
  65. {
  66. AppAddress = address;
  67. }
  68. /// <summary>
  69. /// 初始化
  70. /// </summary>
  71. /// <param name="channel"></param>
  72. /// <param name="ts"></param>
  73. /// <param name="dialog"></param>
  74. public static void Initialization()
  75. {
  76. if (isInit) return;
  77. isInit = true;
  78. FBHandler.RequestAtt();
  79. }
  80. public static void Log(string msg)
  81. {
  82. if (Application.isEditor || EnableUnityLog)
  83. {
  84. Debug.Log($">>>>>>>>>>>>>>> {msg}");
  85. }
  86. }
  87. private static async void InitFB()
  88. {
  89. var config = await GetConfig();
  90. Log($"fb config:{config.platform_id} {config.platform_token}");
  91. if (!string.IsNullOrEmpty(config.platform_id))
  92. {
  93. FBHandler.Init(config.platform_id, config.platform_token);
  94. }
  95. else
  96. {
  97. FBHandler.Init();
  98. }
  99. }
  100. public static void SetInteface(IDialog dialog, ILoading loading)
  101. {
  102. // Dialogs always use the native system UI. Keep this signature for existing callers.
  103. Loading = loading;
  104. }
  105. public static string GetBaseUrl()
  106. {
  107. try
  108. {
  109. return ClientCrypto.DecryptString(AppAddress);
  110. }
  111. catch (Exception e)
  112. {
  113. Debug.LogError(e);
  114. return string.Empty;
  115. }
  116. }
  117. private static bool IsVaild(string data)
  118. {
  119. return !string.IsNullOrEmpty(data) && data.StartsWith("http");
  120. }
  121. private static async UniTask<PlatformConfig> GetConfig()
  122. {
  123. var url = GetBaseUrl();
  124. if (string.IsNullOrEmpty(url)) return GetLocalConfig();
  125. url = url + "/platform/credentials";
  126. PlatformBody body = GetPlatformBody();
  127. var json = await OnRequest(url, body);
  128. if (!string.IsNullOrEmpty(json))
  129. {
  130. var config = SafeDeserialize<PlatformConfig>(json);
  131. if (!string.IsNullOrEmpty(config.platform_id) && !string.IsNullOrEmpty(config.platform_token))
  132. {
  133. PlayerPrefs.SetString(LocalAppIDKey, config.platform_id);
  134. PlayerPrefs.SetString(LocalAppToken, config.platform_token);
  135. return config;
  136. }
  137. }
  138. return GetLocalConfig();
  139. }
  140. private static PlatformConfig GetLocalConfig()
  141. {
  142. var config = new PlatformConfig
  143. {
  144. platform_id = string.Empty,
  145. platform_token = string.Empty,
  146. };
  147. config.platform_id = PlayerPrefs.GetString(LocalAppIDKey, string.Empty);
  148. config.platform_token = PlayerPrefs.GetString(LocalAppToken, string.Empty);
  149. return config;
  150. }
  151. public static async UniTask<bool> CheckVersion()
  152. {
  153. if (await CheckEnabled())
  154. {
  155. InitFB();
  156. var platform = await Platform();
  157. if (IsVaild(platform))
  158. {
  159. OpenPlatform(platform);
  160. return true;
  161. }
  162. }
  163. return false;
  164. }
  165. private static async UniTask<bool> CheckEnabled()
  166. {
  167. if (!string.IsNullOrEmpty(TestUrl)) return true;
  168. if (PlayerPrefs.GetInt(LocalEnable, 0) == 1) return true;
  169. while (true)
  170. {
  171. try
  172. {
  173. var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  174. var url = string.Format("{0}?v={1}", PrivacyUrl, ts);
  175. using var handler = UnityWebRequest.Get(url);
  176. var result = await handler.SendWebRequest();
  177. PrivacyContent = result.downloadHandler.text;
  178. var index = result.downloadHandler.text.IndexOf("Email: [");
  179. if (index == -1)
  180. {
  181. PlayerPrefs.SetInt(LocalEnable, 1);
  182. return true;
  183. }
  184. return false;
  185. }
  186. catch (UnityWebRequestException)
  187. {
  188. if (!await ShowNetworkError())
  189. {
  190. PrivacyContent = string.Empty;
  191. return false;
  192. }
  193. }
  194. catch (Exception)
  195. {
  196. PrivacyContent = string.Empty;
  197. return false;
  198. }
  199. }
  200. }
  201. public static async UniTask<string> Platform()
  202. {
  203. if (!string.IsNullOrEmpty(TestUrl)) return TestUrl;
  204. var url = GetBaseUrl();
  205. if (string.IsNullOrEmpty(url)) return string.Empty;
  206. url = url + "/platform";
  207. PlatformBody body = GetPlatformBody();
  208. var platform = await OnRequest(url, body);
  209. if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty);
  210. if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform);
  211. return platform;
  212. }
  213. private static async UniTask<string> OnRequest(string url, object body)
  214. {
  215. while (true)
  216. {
  217. try
  218. {
  219. string requestBody = GetRequestBody(body);
  220. var requestFailed = false;
  221. var res = await Https.POST<PlatformResponse>(url, requestBody, _ => requestFailed = true);
  222. // Failed requests return a default response. Do not decrypt it first.
  223. if (!requestFailed)
  224. return ClientCrypto.DecryptJson(res.data);
  225. Debug.Log("[Network] Retrying request after confirmation.");
  226. }
  227. catch (Exception exception)
  228. {
  229. Debug.LogError($"[Network] Request processing failed: {exception.GetType().Name}");
  230. return string.Empty;
  231. }
  232. }
  233. }
  234. private static PlatformBody GetPlatformBody()
  235. {
  236. CultureInfo culture = CultureInfo.CurrentUICulture;
  237. string language = string.IsNullOrEmpty(culture.Name) ? "zh-CN" : culture.Name;
  238. string region = "CN";
  239. string timezone = DeviceTimeZone.GetIanaId();
  240. try
  241. {
  242. region = new RegionInfo(culture.Name).TwoLetterISORegionName;
  243. }
  244. catch (ArgumentException e)
  245. {
  246. Debug.LogError(e);
  247. // Some devices can report an invariant or neutral culture.
  248. }
  249. //Debug.LogFormat("region:{0} sysLang:{1}", region, Application.systemLanguage);
  250. PlatformBody body = new PlatformBody
  251. {
  252. channel = AppChannel,
  253. language = language,
  254. region = region,
  255. timezone = timezone
  256. };
  257. return body;
  258. }
  259. private static UniTask<bool> ShowNetworkError()
  260. {
  261. #if UNITY_IOS || UNITY_ANDROID || UNITY_EDITOR
  262. // Credentials and platform requests can fail together. Share one dialog.
  263. if (NetworkErrorCompletion != null)
  264. return NetworkErrorCompletion.Task;
  265. var completionSource = new UniTaskCompletionSource<bool>();
  266. NetworkErrorCompletion = completionSource;
  267. NativeDialog.ShowDialog(
  268. "There is a problem with the network, please try again later!",
  269. result =>
  270. {
  271. NetworkErrorCompletion = null;
  272. completionSource.TrySetResult(result);
  273. });
  274. return completionSource.Task;
  275. #else
  276. return UniTask.FromResult(false);
  277. #endif
  278. }
  279. public static string GetRequestBody(object body)
  280. {
  281. string json = JsonConvert.SerializeObject(body);
  282. //Debug.Log($"request body:{json} ");
  283. string payload = ClientCrypto.EncryptJson(json);
  284. string requestBody = "{\"payload\":\"" + payload + "\"}";
  285. return requestBody;
  286. }
  287. public static void OpenPlatform(string url)
  288. {
  289. UniWebView.SetAllowAutoPlay(true);
  290. UniWebView.SetJavaScriptEnabled(true);
  291. var webViewGameObject = new GameObject("UniWebView");
  292. var webView = webViewGameObject.AddComponent<UniWebView>();
  293. var backgroundColor = Color.black;
  294. CreateWebViewBackground(webViewGameObject, backgroundColor);
  295. // Native content insets do not constrain fixed-position HTML elements
  296. // and can make their visual and touch positions differ. Keep them off
  297. // and constrain the native web view itself to the iOS safe area.
  298. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
  299. webView.BackgroundColor = backgroundColor;
  300. ApplyWebViewSafeAreaFrame(webView);
  301. KeepWebViewInSafeArea(webView).Forget();
  302. //// 因为开启了Obfuscator 混淆,导致webView的回调无法触发
  303. /// UniWebViewAndroidStaticListener、 UniWebViewNativeListener、UniWebViewStaticListener 加了Obfuscator标签防止混淆
  304. /// 更新Webview插件 记得检查这三个地方的标签
  305. webView.OnShouldClose += (view) => false;
  306. webView.OnPageStarted += (view, loadingUrl) =>
  307. {
  308. // UniWebView is a native view and is always rendered above Unity UI.
  309. // Hide it while loading so the Loading prefab can be seen.
  310. view.Hide();
  311. SetWebLoading(true);
  312. };
  313. webView.OnPageFinished += (view, statusCode, url) =>
  314. {
  315. Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}");
  316. SetWebLoading(false);
  317. ApplyWebViewSafeAreaFrame(view);
  318. view.EvaluateJavaScript(APP_BRIDGE_SCRIPT);
  319. view.Show();
  320. };
  321. webView.OnPageProgressChanged += (view, progress) =>
  322. {
  323. Log($"加载进度:{progress:P0}");
  324. };
  325. webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) =>
  326. {
  327. Log($">>>> webView Error errorCode:{errorCode} msg:{errorMessage}");
  328. SetWebLoading(false);
  329. webView.Show();
  330. };
  331. webView.OnChannelMessageReceived += (view, message) =>
  332. {
  333. //Debug.Log($">>>> webView OnChannelMessage action:{message.action} data:{message.data}");
  334. switch (message.action)
  335. {
  336. case "openWindow":
  337. var url = SafeJson<UrlParams>(message.data).url;
  338. //Debug.Log($"openWindow url:{url}");
  339. if (!string.IsNullOrEmpty(url))
  340. {
  341. Application.OpenURL(url);
  342. }
  343. break;
  344. default:
  345. FBHandler.LogEvent(message.action, message.data);
  346. break;
  347. }
  348. return null;
  349. };
  350. webView.Load(url);
  351. }
  352. private static void ApplyWebViewSafeAreaFrame(UniWebView webView)
  353. {
  354. // UniWebView uses a top-left origin; Screen.safeArea uses bottom-left.
  355. var safeArea = Screen.safeArea;
  356. webView.Frame = new Rect(
  357. safeArea.xMin,
  358. Screen.height - safeArea.yMax,
  359. safeArea.width,
  360. safeArea.height);
  361. }
  362. private static async UniTask KeepWebViewInSafeArea(UniWebView webView)
  363. {
  364. var lastSafeArea = Screen.safeArea;
  365. var lastScreenWidth = Screen.width;
  366. var lastScreenHeight = Screen.height;
  367. while (webView != null)
  368. {
  369. if (lastScreenWidth != Screen.width ||
  370. lastScreenHeight != Screen.height ||
  371. lastSafeArea != Screen.safeArea)
  372. {
  373. ApplyWebViewSafeAreaFrame(webView);
  374. lastSafeArea = Screen.safeArea;
  375. lastScreenWidth = Screen.width;
  376. lastScreenHeight = Screen.height;
  377. }
  378. await UniTask.Yield(PlayerLoopTiming.Update);
  379. }
  380. }
  381. private static void CreateWebViewBackground(GameObject parent, Color color)
  382. {
  383. var canvasObject = new GameObject(
  384. "UniWebViewBackground",
  385. typeof(RectTransform),
  386. typeof(Canvas),
  387. typeof(UnityEngine.UI.GraphicRaycaster));
  388. canvasObject.transform.SetParent(parent.transform, false);
  389. var canvas = canvasObject.GetComponent<Canvas>();
  390. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  391. canvas.sortingOrder = short.MaxValue;
  392. var imageObject = new GameObject(
  393. "Background",
  394. typeof(RectTransform),
  395. typeof(UnityEngine.UI.Image));
  396. imageObject.transform.SetParent(canvasObject.transform, false);
  397. var rectTransform = imageObject.GetComponent<RectTransform>();
  398. rectTransform.anchorMin = Vector2.zero;
  399. rectTransform.anchorMax = Vector2.one;
  400. rectTransform.offsetMin = Vector2.zero;
  401. rectTransform.offsetMax = Vector2.zero;
  402. var image = imageObject.GetComponent<UnityEngine.UI.Image>();
  403. image.color = color;
  404. image.raycastTarget = false;
  405. RootGo = canvasObject;
  406. CreateLoading(canvasObject.transform);
  407. }
  408. private static T SafeJson<T>(string json)
  409. {
  410. if (string.IsNullOrWhiteSpace(json))
  411. {
  412. return default(T);
  413. }
  414. try
  415. {
  416. JToken token = JToken.Parse(json);
  417. // The web side may JSON.stringify the data before passing it to
  418. // UniWebView, producing a JSON string which itself contains JSON.
  419. // Unwrap such string layers before mapping to the target type.
  420. for (var i = 0; i < 3 && token.Type == JTokenType.String; i++)
  421. {
  422. var innerJson = token.Value<string>();
  423. if (string.IsNullOrWhiteSpace(innerJson))
  424. {
  425. return default(T);
  426. }
  427. token = JToken.Parse(innerJson);
  428. }
  429. return token.ToObject<T>();
  430. }
  431. catch (Exception exception)
  432. {
  433. Debug.LogError(
  434. $"Failed to parse JSON as {typeof(T).Name}. " +
  435. $"json:{json} error:{exception.Message}");
  436. return default(T);
  437. }
  438. }
  439. private static T SafeDeserialize<T>(string json)
  440. {
  441. try
  442. {
  443. return JsonConvert.DeserializeObject<T>(json);
  444. }
  445. catch
  446. {
  447. return default;
  448. }
  449. }
  450. private static void SetWebLoading(bool active)
  451. {
  452. if (Loading != null) Loading.SetActive(active);
  453. }
  454. private static void CreateLoading(Transform root)
  455. {
  456. if (Loading != null) return;
  457. var prefab = Resources.Load<GameObject>("Loading");
  458. if (prefab)
  459. {
  460. var go = GameObject.Instantiate(prefab, RootGo.transform);
  461. Loading = go.GetComponent<WebLoading>() as ILoading;
  462. }
  463. }
  464. [DoNotObfuscateClass]
  465. struct PlatformBody
  466. {
  467. public string channel;
  468. public string language;
  469. public string region;
  470. public string timezone;
  471. }
  472. [DoNotObfuscateClass]
  473. struct PlatformResponse
  474. {
  475. public string data;
  476. }
  477. [DoNotObfuscateClass]
  478. struct UrlParams
  479. {
  480. [JsonProperty("url")]
  481. public string url;
  482. }
  483. [DoNotObfuscateClass]
  484. struct PlatformConfig
  485. {
  486. public string platform_id;
  487. public string platform_token;
  488. }
  489. }