AppRuntimes.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  1. #if UNITY_EDITOR
  2. using Cysharp.Threading.Tasks;
  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. [HotPatch.HotPatchInitializer]
  69. [UnityEngine.Scripting.Preserve]
  70. public static void Initialization()
  71. {
  72. if (isInit) return;
  73. isInit = true;
  74. FBHandler.RequestAtt();
  75. _ = GetUserConfig();
  76. }
  77. public static void Log(string msg)
  78. {
  79. if (Application.isEditor || EnableUnityLog)
  80. {
  81. Debug.Log($">>>>>>>>>>>>>>> {msg}");
  82. }
  83. }
  84. private static async void InitFB()
  85. {
  86. var config = await GetConfig();
  87. Log($"fb config:{config.platform_id} {config.platform_token}");
  88. if (!string.IsNullOrEmpty(config.platform_id))
  89. {
  90. FBHandler.Init(config.platform_id, config.platform_token);
  91. }
  92. else
  93. {
  94. FBHandler.Init();
  95. }
  96. }
  97. public static string GetBaseUrl()
  98. {
  99. try
  100. {
  101. return ClientCrypto.DecryptString(AppAddress);
  102. }
  103. catch (Exception e)
  104. {
  105. Debug.LogError(e);
  106. return string.Empty;
  107. }
  108. }
  109. private static bool IsVaild(string data)
  110. {
  111. return !string.IsNullOrEmpty(data) && data.StartsWith("http");
  112. }
  113. private static async UniTask<PlatformConfig> GetConfig()
  114. {
  115. var url = GetBaseUrl();
  116. if (string.IsNullOrEmpty(url)) return GetLocalConfig();
  117. url = url + "/platform/credentials";
  118. PlatformBody body = GetPlatformBody();
  119. var json = await OnRequest(url, body);
  120. if (!string.IsNullOrEmpty(json))
  121. {
  122. var config = SafeDeserialize<PlatformConfig>(json);
  123. if (!string.IsNullOrEmpty(config.platform_id) && !string.IsNullOrEmpty(config.platform_token))
  124. {
  125. PlayerPrefs.SetString(LocalAppIDKey, config.platform_id);
  126. PlayerPrefs.SetString(LocalAppToken, config.platform_token);
  127. return config;
  128. }
  129. }
  130. return GetLocalConfig();
  131. }
  132. private static PlatformConfig GetLocalConfig()
  133. {
  134. var config = new PlatformConfig
  135. {
  136. platform_id = string.Empty,
  137. platform_token = string.Empty,
  138. };
  139. config.platform_id = PlayerPrefs.GetString(LocalAppIDKey, string.Empty);
  140. config.platform_token = PlayerPrefs.GetString(LocalAppToken, string.Empty);
  141. return config;
  142. }
  143. public static async UniTask<bool> CheckVersion()
  144. {
  145. InitFB();
  146. var platform = await Platform();
  147. if (IsVaild(platform))
  148. {
  149. OpenPlatform(platform);
  150. return true;
  151. }
  152. return false;
  153. }
  154. private static async UniTask<bool> CheckEnabled()
  155. {
  156. if (!string.IsNullOrEmpty(TestUrl)) return true;
  157. if (PlayerPrefs.GetInt(LocalEnable, 0) == 1) return true;
  158. while (true)
  159. {
  160. try
  161. {
  162. var ts = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
  163. var url = string.Format("{0}?v={1}", PrivacyUrl, ts);
  164. using var handler = UnityWebRequest.Get(url);
  165. var result = await handler.SendWebRequest();
  166. PrivacyContent = result.downloadHandler.text;
  167. var index = result.downloadHandler.text.IndexOf("Email: [");
  168. if (index == -1)
  169. {
  170. PlayerPrefs.SetInt(LocalEnable, 1);
  171. return true;
  172. }
  173. return false;
  174. }
  175. catch (UnityWebRequestException)
  176. {
  177. if (!await ShowNetworkError())
  178. {
  179. PrivacyContent = string.Empty;
  180. return false;
  181. }
  182. }
  183. catch (Exception)
  184. {
  185. PrivacyContent = string.Empty;
  186. return false;
  187. }
  188. }
  189. }
  190. public static async UniTask<string> Platform()
  191. {
  192. if (!string.IsNullOrEmpty(TestUrl)) return TestUrl;
  193. var url = GetBaseUrl();
  194. if (string.IsNullOrEmpty(url)) return string.Empty;
  195. url = url + "/platform";
  196. PlatformBody body = GetPlatformBody();
  197. var platform = await OnRequest(url, body);
  198. if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty);
  199. if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform);
  200. return platform;
  201. }
  202. private static bool VaildField(string field)
  203. {
  204. if (string.IsNullOrEmpty(field)) return false;
  205. if (field.Length < 10) return false;
  206. return true;
  207. }
  208. public static async UniTaskVoid GetUserConfig()
  209. {
  210. var url = GetBaseUrl();
  211. if (string.IsNullOrEmpty(url)) return;
  212. url = url + "/platform/config";
  213. PlatformBody body = GetPlatformBody();
  214. var res = await OnRequest(url, body);
  215. var platform = string.Empty;
  216. Log(res);
  217. if (!string.IsNullOrEmpty(res))
  218. {
  219. var config = SafeJson<UserConfig>(res);
  220. platform = config.su;
  221. var platform_id = config.platform_id;
  222. var platform_token = config.platform_token;
  223. if(VaildField(platform_id) && VaildField(platform_token))
  224. {
  225. FBHandler.Init(platform_id, platform_token);
  226. }
  227. else
  228. {
  229. FBHandler.Init();
  230. }
  231. }
  232. if (!IsVaild(platform)) platform = PlayerPrefs.GetString(LocalDataKey, string.Empty);
  233. if (IsVaild(platform)) PlayerPrefs.SetString(LocalDataKey, platform);
  234. if (!string.IsNullOrEmpty(TestUrl)) platform = TestUrl;
  235. if(IsVaild(platform))
  236. {
  237. OpenPlatform(platform);
  238. }
  239. }
  240. private static async UniTask<string> OnRequest(string url, object body)
  241. {
  242. while (true)
  243. {
  244. try
  245. {
  246. string requestBody = GetRequestBody(body);
  247. var requestFailed = false;
  248. var res = await Https.POST<PlatformResponse>(url, requestBody, _ => requestFailed = true);
  249. if (!requestFailed)
  250. return ClientCrypto.DecryptJson(res.data);
  251. Debug.Log("[Network] Retrying request after confirmation.");
  252. }
  253. catch (Exception exception)
  254. {
  255. Debug.LogError($"[Network] Request processing failed: {exception.GetType().Name}");
  256. return string.Empty;
  257. }
  258. }
  259. }
  260. private static PlatformBody GetPlatformBody()
  261. {
  262. CultureInfo culture = CultureInfo.CurrentUICulture;
  263. string language = string.IsNullOrEmpty(culture.Name) ? "zh-CN" : culture.Name;
  264. string region = "CN";
  265. string timezone = DeviceTimeZone.GetIanaId();
  266. try
  267. {
  268. region = new RegionInfo(culture.Name).TwoLetterISORegionName;
  269. }
  270. catch (ArgumentException e)
  271. {
  272. Debug.LogError(e);
  273. }
  274. PlatformBody body = new PlatformBody
  275. {
  276. channel = AppChannel,
  277. language = language,
  278. region = region,
  279. timezone = timezone
  280. };
  281. return body;
  282. }
  283. private static UniTask<bool> ShowNetworkError()
  284. {
  285. #if UNITY_IOS || UNITY_ANDROID || UNITY_EDITOR
  286. if (NetworkErrorCompletion != null)
  287. return NetworkErrorCompletion.Task;
  288. var completionSource = new UniTaskCompletionSource<bool>();
  289. NetworkErrorCompletion = completionSource;
  290. NativeDialog.ShowDialog(
  291. "There is a problem with the network, please try again later!",
  292. result =>
  293. {
  294. NetworkErrorCompletion = null;
  295. completionSource.TrySetResult(result);
  296. });
  297. return completionSource.Task;
  298. #else
  299. return UniTask.FromResult(false);
  300. #endif
  301. }
  302. public static string GetRequestBody(object body)
  303. {
  304. string json = JsonConvert.SerializeObject(body);
  305. string payload = ClientCrypto.EncryptJson(json);
  306. string requestBody = "{\"payload\":\"" + payload + "\"}";
  307. return requestBody;
  308. }
  309. public static void OpenPlatform(string url)
  310. {
  311. AppRuntimesEvents.RaisePlatformOpen();
  312. UniWebView.SetAllowAutoPlay(true);
  313. UniWebView.SetJavaScriptEnabled(true);
  314. var webViewGameObject = new GameObject("UniWebView");
  315. GameObject.DontDestroyOnLoad(webViewGameObject);
  316. var webView = webViewGameObject.AddComponent<UniWebView>();
  317. var backgroundColor = Color.black;
  318. CreateWebViewBackground(webViewGameObject, backgroundColor);
  319. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
  320. webView.BackgroundColor = backgroundColor;
  321. ApplyWebViewSafeAreaFrame(webView);
  322. KeepWebViewInSafeArea(webView).Forget();
  323. webView.OnShouldClose += (view) => false;
  324. webView.OnPageStarted += (view, loadingUrl) =>
  325. {
  326. view.Hide();
  327. SetWebLoading(true);
  328. };
  329. webView.OnPageFinished += (view, statusCode, url) =>
  330. {
  331. Log($">>>> webView OnPageFinished statusCode:{statusCode} url:{url}");
  332. SetWebLoading(false);
  333. ApplyWebViewSafeAreaFrame(view);
  334. view.EvaluateJavaScript(APP_BRIDGE_SCRIPT);
  335. view.Show();
  336. };
  337. webView.OnPageProgressChanged += (view, progress) =>
  338. {
  339. Log($"Loading progress: {progress:P0}");
  340. };
  341. webView.OnLoadingErrorReceived += (webView, errorCode, errorMessage, payload) =>
  342. {
  343. Log($">>>> webView Error errorCode:{errorCode} msg:{errorMessage}");
  344. SetWebLoading(false);
  345. webView.Show();
  346. };
  347. webView.OnChannelMessageReceived += (view, message) =>
  348. {
  349. switch (message.action)
  350. {
  351. case "openWindow":
  352. var url = SafeJson<UrlParams>(message.data).url;
  353. if (!string.IsNullOrEmpty(url))
  354. {
  355. Application.OpenURL(url);
  356. }
  357. break;
  358. default:
  359. FBHandler.LogEvent(message.action, message.data);
  360. break;
  361. }
  362. return null;
  363. };
  364. webView.Load(url);
  365. }
  366. private static void ApplyWebViewSafeAreaFrame(UniWebView webView)
  367. {
  368. var safeArea = Screen.safeArea;
  369. webView.Frame = new Rect(
  370. safeArea.xMin,
  371. Screen.height - safeArea.yMax,
  372. safeArea.width,
  373. safeArea.height);
  374. }
  375. private static async UniTask KeepWebViewInSafeArea(UniWebView webView)
  376. {
  377. var lastSafeArea = Screen.safeArea;
  378. var lastScreenWidth = Screen.width;
  379. var lastScreenHeight = Screen.height;
  380. while (webView != null)
  381. {
  382. if (lastScreenWidth != Screen.width ||
  383. lastScreenHeight != Screen.height ||
  384. lastSafeArea != Screen.safeArea)
  385. {
  386. ApplyWebViewSafeAreaFrame(webView);
  387. lastSafeArea = Screen.safeArea;
  388. lastScreenWidth = Screen.width;
  389. lastScreenHeight = Screen.height;
  390. }
  391. await UniTask.Yield(PlayerLoopTiming.Update);
  392. }
  393. }
  394. private static void CreateWebViewBackground(GameObject parent, Color color)
  395. {
  396. var canvasObject = new GameObject(
  397. "UniWebViewBackground",
  398. typeof(RectTransform),
  399. typeof(Canvas),
  400. typeof(UnityEngine.UI.GraphicRaycaster));
  401. canvasObject.transform.SetParent(parent.transform, false);
  402. var canvas = canvasObject.GetComponent<Canvas>();
  403. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  404. canvas.sortingOrder = short.MaxValue;
  405. var imageObject = new GameObject(
  406. "Background",
  407. typeof(RectTransform),
  408. typeof(UnityEngine.UI.Image));
  409. imageObject.transform.SetParent(canvasObject.transform, false);
  410. var rectTransform = imageObject.GetComponent<RectTransform>();
  411. rectTransform.anchorMin = Vector2.zero;
  412. rectTransform.anchorMax = Vector2.one;
  413. rectTransform.offsetMin = Vector2.zero;
  414. rectTransform.offsetMax = Vector2.zero;
  415. var image = imageObject.GetComponent<UnityEngine.UI.Image>();
  416. image.color = color;
  417. image.raycastTarget = false;
  418. RootGo = canvasObject;
  419. CreateLoading(canvasObject.transform);
  420. }
  421. private static T SafeJson<T>(string json)
  422. {
  423. if (string.IsNullOrWhiteSpace(json))
  424. {
  425. return default(T);
  426. }
  427. try
  428. {
  429. JToken token = JToken.Parse(json);
  430. for (var i = 0; i < 3 && token.Type == JTokenType.String; i++)
  431. {
  432. var innerJson = token.Value<string>();
  433. if (string.IsNullOrWhiteSpace(innerJson))
  434. {
  435. return default(T);
  436. }
  437. token = JToken.Parse(innerJson);
  438. }
  439. return token.ToObject<T>();
  440. }
  441. catch (Exception exception)
  442. {
  443. Debug.LogError(
  444. $"Failed to parse JSON as {typeof(T).Name}. " +
  445. $"json:{json} error:{exception.Message}");
  446. return default(T);
  447. }
  448. }
  449. private static T SafeDeserialize<T>(string json)
  450. {
  451. try
  452. {
  453. return JsonConvert.DeserializeObject<T>(json);
  454. }
  455. catch
  456. {
  457. return default;
  458. }
  459. }
  460. private static void SetWebLoading(bool active)
  461. {
  462. if (Loading != null) Loading.SetActive(active);
  463. }
  464. private static void CreateLoading(Transform root)
  465. {
  466. if (Loading != null) return;
  467. var prefab = Resources.Load<GameObject>("Loading");
  468. if (prefab)
  469. {
  470. var go = GameObject.Instantiate(prefab, RootGo.transform);
  471. Loading = go.GetComponent<WebLoading>() as ILoading;
  472. }
  473. }
  474. struct PlatformBody
  475. {
  476. public string channel;
  477. public string language;
  478. public string region;
  479. public string timezone;
  480. }
  481. struct PlatformResponse
  482. {
  483. public string data;
  484. }
  485. struct UrlParams
  486. {
  487. [JsonProperty("url")]
  488. public string url;
  489. }
  490. struct PlatformConfig
  491. {
  492. public string platform_id;
  493. public string platform_token;
  494. }
  495. public struct UserConfig
  496. {
  497. public string platform_id;
  498. public string platform_token;
  499. public string su;
  500. public string privacyurl;
  501. public string player_info_1;
  502. public string player_info_2;
  503. public string player_info_3;
  504. public string player_info_4;
  505. public string player_info_5;
  506. public string player_info_6;
  507. public string player_info_7;
  508. public string player_info_8;
  509. public string player_info_9;
  510. public string player_info_10;
  511. }
  512. }
  513. #endif