AppRuntimes.cs 18 KB

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