AppRuntimes.cs 17 KB

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