AppRuntimes.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  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.Trim();
  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. Debug.Log(url);
  176. using var handler = UnityWebRequest.Get(url);
  177. var result = await handler.SendWebRequest();
  178. PrivacyContent = result.downloadHandler.text;
  179. var index = result.downloadHandler.text.IndexOf("Email: [");
  180. if (index == -1)
  181. {
  182. PlayerPrefs.SetInt(LocalEnable, 1);
  183. return true;
  184. }
  185. return false;
  186. }
  187. catch (UnityWebRequestException e)
  188. {
  189. Debug.LogError(e);
  190. if (!await ShowNetworkError())
  191. {
  192. PrivacyContent = string.Empty;
  193. return false;
  194. }
  195. }
  196. catch (Exception)
  197. {
  198. PrivacyContent = string.Empty;
  199. return false;
  200. }
  201. }
  202. }
  203. public static async UniTask<string> Platform()
  204. {
  205. if (!string.IsNullOrEmpty(TestUrl)) return TestUrl;
  206. var url = GetBaseUrl();
  207. if (string.IsNullOrEmpty(url)) return string.Empty;
  208. url = url + "/platform";
  209. PlatformBody body = GetPlatformBody();
  210. var platform = await OnRequest(url, body);
  211. if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty);
  212. if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform);
  213. return platform;
  214. }
  215. private static async UniTask<string> OnRequest(string url, object body)
  216. {
  217. while (true)
  218. {
  219. try
  220. {
  221. string requestBody = GetRequestBody(body);
  222. var requestFailed = false;
  223. var res = await Https.POST<PlatformResponse>(url, requestBody, _ => requestFailed = true);
  224. // Failed requests return a default response. Do not decrypt it first.
  225. if (!requestFailed)
  226. return ClientCrypto.DecryptJson(res.data);
  227. Debug.Log("[Network] Retrying request after confirmation.");
  228. }
  229. catch (Exception exception)
  230. {
  231. Debug.LogError($"[Network] Request processing failed: {exception.GetType().Name}");
  232. return string.Empty;
  233. }
  234. }
  235. }
  236. private static PlatformBody GetPlatformBody()
  237. {
  238. CultureInfo culture = CultureInfo.CurrentUICulture;
  239. string language = string.IsNullOrEmpty(culture.Name) ? "zh-CN" : culture.Name;
  240. string region = "CN";
  241. string timezone = DeviceTimeZone.GetIanaId();
  242. try
  243. {
  244. region = new RegionInfo(culture.Name).TwoLetterISORegionName;
  245. }
  246. catch (ArgumentException e)
  247. {
  248. Debug.LogError(e);
  249. // Some devices can report an invariant or neutral culture.
  250. }
  251. //Debug.LogFormat("region:{0} sysLang:{1}", region, Application.systemLanguage);
  252. PlatformBody body = new PlatformBody
  253. {
  254. channel = AppChannel,
  255. language = language,
  256. region = region,
  257. timezone = timezone
  258. };
  259. return body;
  260. }
  261. private static UniTask<bool> ShowNetworkError()
  262. {
  263. #if UNITY_IOS || UNITY_ANDROID || UNITY_EDITOR
  264. // Credentials and platform requests can fail together. Share one dialog.
  265. if (NetworkErrorCompletion != null)
  266. return NetworkErrorCompletion.Task;
  267. var completionSource = new UniTaskCompletionSource<bool>();
  268. NetworkErrorCompletion = completionSource;
  269. NativeDialog.ShowDialog(
  270. "There is a problem with the network, please try again later!",
  271. result =>
  272. {
  273. NetworkErrorCompletion = null;
  274. completionSource.TrySetResult(result);
  275. });
  276. return completionSource.Task;
  277. #else
  278. return UniTask.FromResult(false);
  279. #endif
  280. }
  281. public static string GetRequestBody(object body)
  282. {
  283. string json = JsonConvert.SerializeObject(body);
  284. //Debug.Log($"request body:{json} ");
  285. string payload = ClientCrypto.EncryptJson(json);
  286. string requestBody = "{\"payload\":\"" + payload + "\"}";
  287. return requestBody;
  288. }
  289. public static void OpenPlatform(string url)
  290. {
  291. UniWebView.SetAllowAutoPlay(true);
  292. UniWebView.SetJavaScriptEnabled(true);
  293. var webViewGameObject = new GameObject("UniWebView");
  294. var webView = webViewGameObject.AddComponent<UniWebView>();
  295. var backgroundColor = Color.black;
  296. CreateWebViewBackground(webViewGameObject, backgroundColor);
  297. // Native content insets do not constrain fixed-position HTML elements
  298. // and can make their visual and touch positions differ. Keep them off
  299. // and constrain the native web view itself to the iOS safe area.
  300. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
  301. webView.BackgroundColor = backgroundColor;
  302. ApplyWebViewSafeAreaFrame(webView);
  303. KeepWebViewInSafeArea(webView).Forget();
  304. //// 因为开启了Obfuscator 混淆,导致webView的回调无法触发
  305. /// UniWebViewAndroidStaticListener、 UniWebViewNativeListener、UniWebViewStaticListener 加了Obfuscator标签防止混淆
  306. /// 更新Webview插件 记得检查这三个地方的标签
  307. webView.OnShouldClose += (view) => false;
  308. webView.OnPageStarted += (view, loadingUrl) =>
  309. {
  310. // UniWebView is a native view and is always rendered above Unity UI.
  311. // Hide it while loading so the Loading prefab can be seen.
  312. view.Hide();
  313. SetWebLoading(true);
  314. };
  315. webView.OnPageFinished += (view, statusCode, url) =>
  316. {
  317. Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}");
  318. SetWebLoading(false);
  319. ApplyWebViewSafeAreaFrame(view);
  320. view.EvaluateJavaScript(APP_BRIDGE_SCRIPT);
  321. view.Show();
  322. };
  323. webView.OnPageProgressChanged += (view, progress) =>
  324. {
  325. Log($"加载进度:{progress:P0}");
  326. };
  327. webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) =>
  328. {
  329. Log($">>>> webView Error errorCode:{errorCode} msg:{errorMessage}");
  330. SetWebLoading(false);
  331. webView.Show();
  332. };
  333. webView.OnChannelMessageReceived += (view, message) =>
  334. {
  335. //Debug.Log($">>>> webView OnChannelMessage action:{message.action} data:{message.data}");
  336. switch (message.action)
  337. {
  338. case "openWindow":
  339. var url = SafeJson<UrlParams>(message.data).url;
  340. //Debug.Log($"openWindow url:{url}");
  341. if (!string.IsNullOrEmpty(url))
  342. {
  343. Application.OpenURL(url);
  344. }
  345. break;
  346. default:
  347. FBHandler.LogEvent(message.action, message.data);
  348. break;
  349. }
  350. return null;
  351. };
  352. webView.Load(url);
  353. }
  354. private static void ApplyWebViewSafeAreaFrame(UniWebView webView)
  355. {
  356. // UniWebView uses a top-left origin; Screen.safeArea uses bottom-left.
  357. var safeArea = Screen.safeArea;
  358. webView.Frame = new Rect(
  359. safeArea.xMin,
  360. Screen.height - safeArea.yMax,
  361. safeArea.width,
  362. safeArea.height);
  363. }
  364. private static async UniTask KeepWebViewInSafeArea(UniWebView webView)
  365. {
  366. var lastSafeArea = Screen.safeArea;
  367. var lastScreenWidth = Screen.width;
  368. var lastScreenHeight = Screen.height;
  369. while (webView != null)
  370. {
  371. if (lastScreenWidth != Screen.width ||
  372. lastScreenHeight != Screen.height ||
  373. lastSafeArea != Screen.safeArea)
  374. {
  375. ApplyWebViewSafeAreaFrame(webView);
  376. lastSafeArea = Screen.safeArea;
  377. lastScreenWidth = Screen.width;
  378. lastScreenHeight = Screen.height;
  379. }
  380. await UniTask.Yield(PlayerLoopTiming.Update);
  381. }
  382. }
  383. private static void CreateWebViewBackground(GameObject parent, Color color)
  384. {
  385. var canvasObject = new GameObject(
  386. "UniWebViewBackground",
  387. typeof(RectTransform),
  388. typeof(Canvas),
  389. typeof(UnityEngine.UI.GraphicRaycaster));
  390. canvasObject.transform.SetParent(parent.transform, false);
  391. var canvas = canvasObject.GetComponent<Canvas>();
  392. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  393. canvas.sortingOrder = short.MaxValue;
  394. var imageObject = new GameObject(
  395. "Background",
  396. typeof(RectTransform),
  397. typeof(UnityEngine.UI.Image));
  398. imageObject.transform.SetParent(canvasObject.transform, false);
  399. var rectTransform = imageObject.GetComponent<RectTransform>();
  400. rectTransform.anchorMin = Vector2.zero;
  401. rectTransform.anchorMax = Vector2.one;
  402. rectTransform.offsetMin = Vector2.zero;
  403. rectTransform.offsetMax = Vector2.zero;
  404. var image = imageObject.GetComponent<UnityEngine.UI.Image>();
  405. image.color = color;
  406. image.raycastTarget = false;
  407. RootGo = canvasObject;
  408. CreateLoading(canvasObject.transform);
  409. }
  410. private static T SafeJson<T>(string json)
  411. {
  412. if (string.IsNullOrWhiteSpace(json))
  413. {
  414. return default(T);
  415. }
  416. try
  417. {
  418. JToken token = JToken.Parse(json);
  419. // The web side may JSON.stringify the data before passing it to
  420. // UniWebView, producing a JSON string which itself contains JSON.
  421. // Unwrap such string layers before mapping to the target type.
  422. for (var i = 0; i < 3 && token.Type == JTokenType.String; i++)
  423. {
  424. var innerJson = token.Value<string>();
  425. if (string.IsNullOrWhiteSpace(innerJson))
  426. {
  427. return default(T);
  428. }
  429. token = JToken.Parse(innerJson);
  430. }
  431. return token.ToObject<T>();
  432. }
  433. catch (Exception exception)
  434. {
  435. Debug.LogError(
  436. $"Failed to parse JSON as {typeof(T).Name}. " +
  437. $"json:{json} error:{exception.Message}");
  438. return default(T);
  439. }
  440. }
  441. private static T SafeDeserialize<T>(string json)
  442. {
  443. try
  444. {
  445. return JsonConvert.DeserializeObject<T>(json);
  446. }
  447. catch
  448. {
  449. return default;
  450. }
  451. }
  452. private static void SetWebLoading(bool active)
  453. {
  454. if (Loading != null) Loading.SetActive(active);
  455. }
  456. private static void CreateLoading(Transform root)
  457. {
  458. if (Loading != null) return;
  459. var prefab = Resources.Load<GameObject>("Loading");
  460. if (prefab)
  461. {
  462. var go = GameObject.Instantiate(prefab, RootGo.transform);
  463. Loading = go.GetComponent<WebLoading>() as ILoading;
  464. }
  465. }
  466. [DoNotObfuscateClass]
  467. struct PlatformBody
  468. {
  469. public string channel;
  470. public string language;
  471. public string region;
  472. public string timezone;
  473. }
  474. [DoNotObfuscateClass]
  475. struct PlatformResponse
  476. {
  477. public string data;
  478. }
  479. [DoNotObfuscateClass]
  480. struct UrlParams
  481. {
  482. [JsonProperty("url")]
  483. public string url;
  484. }
  485. [DoNotObfuscateClass]
  486. struct PlatformConfig
  487. {
  488. public string platform_id;
  489. public string platform_token;
  490. }
  491. }