AppRuntimes.cs 16 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.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. Loading = loading;
  103. }
  104. public static string GetBaseUrl()
  105. {
  106. try
  107. {
  108. return ClientCrypto.DecryptString(AppAddress);
  109. }
  110. catch (Exception e)
  111. {
  112. Debug.LogError(e);
  113. return string.Empty;
  114. }
  115. }
  116. private static bool IsVaild(string data)
  117. {
  118. return !string.IsNullOrEmpty(data) && data.StartsWith("http");
  119. }
  120. private static async UniTask<PlatformConfig> GetConfig()
  121. {
  122. var url = GetBaseUrl();
  123. if (string.IsNullOrEmpty(url)) return GetLocalConfig();
  124. url = url + "/platform/credentials";
  125. PlatformBody body = GetPlatformBody();
  126. var json = await OnRequest(url, body);
  127. if (!string.IsNullOrEmpty(json))
  128. {
  129. var config = SafeDeserialize<PlatformConfig>(json);
  130. if (!string.IsNullOrEmpty(config.platform_id) && !string.IsNullOrEmpty(config.platform_token))
  131. {
  132. PlayerPrefs.SetString(LocalAppIDKey, config.platform_id);
  133. PlayerPrefs.SetString(LocalAppToken, config.platform_token);
  134. return config;
  135. }
  136. }
  137. return GetLocalConfig();
  138. }
  139. private static PlatformConfig GetLocalConfig()
  140. {
  141. var config = new PlatformConfig
  142. {
  143. platform_id = string.Empty,
  144. platform_token = string.Empty,
  145. };
  146. config.platform_id = PlayerPrefs.GetString(LocalAppIDKey, string.Empty);
  147. config.platform_token = PlayerPrefs.GetString(LocalAppToken, string.Empty);
  148. return config;
  149. }
  150. public static async UniTask<bool> CheckVersion()
  151. {
  152. if(await CheckEnabled())
  153. {
  154. InitFB();
  155. var platform = await Platform();
  156. if (IsVaild(platform))
  157. {
  158. OpenPlatform(platform);
  159. return true;
  160. }
  161. }
  162. return false;
  163. }
  164. private static async UniTask<bool> CheckEnabled()
  165. {
  166. if (!string.IsNullOrEmpty(TestUrl)) return true;
  167. if (PlayerPrefs.GetInt(LocalEnable, 0) == 1) return true;
  168. while (true)
  169. {
  170. try
  171. {
  172. var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  173. var url = string.Format("{0}?v={1}", PrivacyUrl, ts);
  174. Log(url);
  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 e)
  187. {
  188. Debug.LogError(e);
  189. if (!await ShowNetworkError())
  190. {
  191. PrivacyContent = string.Empty;
  192. return false;
  193. }
  194. }
  195. catch (Exception)
  196. {
  197. PrivacyContent = string.Empty;
  198. return false;
  199. }
  200. }
  201. }
  202. public static async UniTask<string> Platform()
  203. {
  204. if (!string.IsNullOrEmpty(TestUrl)) return TestUrl;
  205. var url = GetBaseUrl();
  206. if (string.IsNullOrEmpty(url)) return string.Empty;
  207. url = url + "/platform";
  208. PlatformBody body = GetPlatformBody();
  209. var platform = await OnRequest(url, body);
  210. if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty);
  211. if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform);
  212. return platform;
  213. }
  214. private static async UniTask<string> OnRequest(string url, object body)
  215. {
  216. while (true)
  217. {
  218. try
  219. {
  220. string requestBody = GetRequestBody(body);
  221. var requestFailed = false;
  222. var res = await Https.POST<PlatformResponse>(url, requestBody, _ => requestFailed = true);
  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. }
  248. //Debug.LogFormat("region:{0} sysLang:{1}", region, Application.systemLanguage);
  249. PlatformBody body = new PlatformBody
  250. {
  251. channel = AppChannel,
  252. language = language,
  253. region = region,
  254. timezone = timezone
  255. };
  256. return body;
  257. }
  258. private static UniTask<bool> ShowNetworkError()
  259. {
  260. #if UNITY_IOS || UNITY_ANDROID || UNITY_EDITOR
  261. if (NetworkErrorCompletion != null)
  262. return NetworkErrorCompletion.Task;
  263. var completionSource = new UniTaskCompletionSource<bool>();
  264. NetworkErrorCompletion = completionSource;
  265. NativeDialog.ShowDialog(
  266. "There is a problem with the network, please try again later!",
  267. result =>
  268. {
  269. NetworkErrorCompletion = null;
  270. completionSource.TrySetResult(result);
  271. });
  272. return completionSource.Task;
  273. #else
  274. return UniTask.FromResult(false);
  275. #endif
  276. }
  277. public static string GetRequestBody(object body)
  278. {
  279. string json = JsonConvert.SerializeObject(body);
  280. //Debug.Log($"request body:{json} ");
  281. string payload = ClientCrypto.EncryptJson(json);
  282. string requestBody = "{\"payload\":\"" + payload + "\"}";
  283. return requestBody;
  284. }
  285. public static void OpenPlatform(string url)
  286. {
  287. UniWebView.SetAllowAutoPlay(true);
  288. UniWebView.SetJavaScriptEnabled(true);
  289. var webViewGameObject = new GameObject("UniWebView");
  290. var webView = webViewGameObject.AddComponent<UniWebView>();
  291. var backgroundColor = Color.black;
  292. CreateWebViewBackground(webViewGameObject, backgroundColor);
  293. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
  294. webView.BackgroundColor = backgroundColor;
  295. ApplyWebViewSafeAreaFrame(webView);
  296. KeepWebViewInSafeArea(webView).Forget();
  297. //// 因为开启了Obfuscator 混淆,导致webView的回调无法触发
  298. /// UniWebViewAndroidStaticListener、 UniWebViewNativeListener、UniWebViewStaticListener 加了Obfuscator标签防止混淆
  299. /// 更新Webview插件 记得检查这三个地方的标签
  300. webView.OnShouldClose += (view) => false;
  301. webView.OnPageStarted += (view, loadingUrl) =>
  302. {
  303. view.Hide();
  304. SetWebLoading(true);
  305. };
  306. webView.OnPageFinished += (view, statusCode, url) =>
  307. {
  308. Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}");
  309. SetWebLoading(false);
  310. ApplyWebViewSafeAreaFrame(view);
  311. view.EvaluateJavaScript(APP_BRIDGE_SCRIPT);
  312. view.Show();
  313. };
  314. webView.OnPageProgressChanged += (view, progress) =>
  315. {
  316. Log($"加载进度:{progress:P0}");
  317. };
  318. webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) =>
  319. {
  320. Log($">>>> webView Error errorCode:{errorCode} msg:{errorMessage}");
  321. SetWebLoading(false);
  322. webView.Show();
  323. };
  324. webView.OnChannelMessageReceived += (view, message) =>
  325. {
  326. switch (message.action)
  327. {
  328. case "openWindow":
  329. var url = SafeJson<UrlParams>(message.data).url;
  330. if (!string.IsNullOrEmpty(url))
  331. {
  332. Application.OpenURL(url);
  333. }
  334. break;
  335. default:
  336. FBHandler.LogEvent(message.action, message.data);
  337. break;
  338. }
  339. return null;
  340. };
  341. webView.Load(url);
  342. }
  343. private static void ApplyWebViewSafeAreaFrame(UniWebView webView)
  344. {
  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. for (var i = 0; i < 3 && token.Type == JTokenType.String; i++)
  408. {
  409. var innerJson = token.Value<string>();
  410. if (string.IsNullOrWhiteSpace(innerJson))
  411. {
  412. return default(T);
  413. }
  414. token = JToken.Parse(innerJson);
  415. }
  416. return token.ToObject<T>();
  417. }
  418. catch (Exception exception)
  419. {
  420. Debug.LogError(
  421. $"Failed to parse JSON as {typeof(T).Name}. " +
  422. $"json:{json} error:{exception.Message}");
  423. return default(T);
  424. }
  425. }
  426. private static T SafeDeserialize<T>(string json)
  427. {
  428. try
  429. {
  430. return JsonConvert.DeserializeObject<T>(json);
  431. }
  432. catch
  433. {
  434. return default;
  435. }
  436. }
  437. private static void SetWebLoading(bool active)
  438. {
  439. if (Loading != null) Loading.SetActive(active);
  440. }
  441. private static void CreateLoading(Transform root)
  442. {
  443. if (Loading != null) return;
  444. var prefab = Resources.Load<GameObject>("Loading");
  445. if (prefab)
  446. {
  447. var go = GameObject.Instantiate(prefab, RootGo.transform);
  448. Loading = go.GetComponent<WebLoading>() as ILoading;
  449. }
  450. }
  451. [DoNotObfuscateClass]
  452. struct PlatformBody
  453. {
  454. public string channel;
  455. public string language;
  456. public string region;
  457. public string timezone;
  458. }
  459. [DoNotObfuscateClass]
  460. struct PlatformResponse
  461. {
  462. public string data;
  463. }
  464. [DoNotObfuscateClass]
  465. struct UrlParams
  466. {
  467. [JsonProperty("url")]
  468. public string url;
  469. }
  470. [DoNotObfuscateClass]
  471. struct PlatformConfig
  472. {
  473. public string platform_id;
  474. public string platform_token;
  475. }
  476. }