ActivityWebViewController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. [DisallowMultipleComponent]
  5. public sealed class ActivityWebViewController : MonoBehaviour
  6. {
  7. const float RestoredBackdropAlpha = 0.68f;
  8. const float MaximizedBackdropAlpha = 1.0f;
  9. static ActivityWebViewController instance;
  10. static bool shownDuringLoadingThisSession;
  11. static bool shownThisSession;
  12. UniWebView webView;
  13. Image backdrop;
  14. float initialScale = 0.8f;
  15. bool maximized;
  16. bool closing;
  17. bool pageLoaded;
  18. Rect lastSafeArea;
  19. int lastScreenWidth;
  20. int lastScreenHeight;
  21. [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
  22. static void ResetStatics()
  23. {
  24. instance = null;
  25. shownDuringLoadingThisSession = false;
  26. shownThisSession = false;
  27. }
  28. public static void ShowDuringLoading()
  29. {
  30. if (shownDuringLoadingThisSession)
  31. return;
  32. ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
  33. if (settings == null)
  34. {
  35. Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources.");
  36. return;
  37. }
  38. if (!settings.showOnLaunch)
  39. return;
  40. if (EnsureInstance())
  41. {
  42. shownDuringLoadingThisSession = true;
  43. Debug.Log("[Activity] Activity page opened during loading.");
  44. }
  45. }
  46. public static void ShowOnLaunch()
  47. {
  48. if (shownThisSession)
  49. return;
  50. ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
  51. if (settings == null)
  52. {
  53. Debug.LogWarning("[Activity] ActivityWebViewSettings.asset was not found in Resources.");
  54. return;
  55. }
  56. if (!settings.showOnLaunch)
  57. return;
  58. if (Show())
  59. shownThisSession = true;
  60. }
  61. public static bool Show()
  62. {
  63. return EnsureInstance();
  64. }
  65. static bool EnsureInstance()
  66. {
  67. if (instance != null)
  68. {
  69. instance.ApplyCurrentFrame();
  70. if (instance.webView != null && instance.pageLoaded)
  71. instance.webView.Show();
  72. return true;
  73. }
  74. ActivityWebViewSettings settings = ActivityWebViewSettings.Instance;
  75. string url = settings != null ? settings.activityUrl : ActivityWebViewSettings.DefaultActivityUrl;
  76. url = string.IsNullOrWhiteSpace(url) ? ActivityWebViewSettings.DefaultActivityUrl : url.Trim();
  77. if (!Uri.TryCreate(url, UriKind.Absolute, out Uri uri) ||
  78. (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
  79. {
  80. Debug.LogWarning("[Activity] Activity URL must be an absolute HTTP(S) URL: " + url);
  81. return false;
  82. }
  83. if (!UniWebView.IsWebViewSupported)
  84. {
  85. Debug.LogWarning("[Activity] UniWebView is not supported on this platform.");
  86. return false;
  87. }
  88. var root = new GameObject("ActivityWebView");
  89. DontDestroyOnLoad(root);
  90. var controller = root.AddComponent<ActivityWebViewController>();
  91. controller.Initialize(url, settings != null ? settings.initialScale : 0.8f);
  92. return true;
  93. }
  94. public static void CloseCurrent()
  95. {
  96. if (instance != null)
  97. instance.Close();
  98. }
  99. void Initialize(string url, float scale)
  100. {
  101. instance = this;
  102. initialScale = Mathf.Clamp(scale, 0.1f, 1f);
  103. CreateBackdrop();
  104. CreateWebView();
  105. lastSafeArea = Screen.safeArea;
  106. lastScreenWidth = Screen.width;
  107. lastScreenHeight = Screen.height;
  108. ApplyCurrentFrame();
  109. webView.Load(url);
  110. }
  111. void Update()
  112. {
  113. if (webView == null)
  114. return;
  115. Rect safeArea = Screen.safeArea;
  116. if (safeArea != lastSafeArea ||
  117. lastScreenWidth != Screen.width ||
  118. lastScreenHeight != Screen.height)
  119. {
  120. lastSafeArea = safeArea;
  121. lastScreenWidth = Screen.width;
  122. lastScreenHeight = Screen.height;
  123. ApplyCurrentFrame();
  124. }
  125. }
  126. void OnDestroy()
  127. {
  128. if (webView != null)
  129. {
  130. webView.OnShouldClose -= HandleShouldClose;
  131. webView.OnPageFinished -= HandlePageFinished;
  132. webView.OnLoadingErrorReceived -= HandleLoadingError;
  133. webView.OnChannelMessageReceived -= HandleChannelMessage;
  134. webView.OnMessageReceived -= HandleUrlMessage;
  135. }
  136. if (instance == this)
  137. instance = null;
  138. }
  139. void CreateBackdrop()
  140. {
  141. var canvasObject = new GameObject(
  142. "Backdrop",
  143. typeof(RectTransform),
  144. typeof(Canvas),
  145. typeof(GraphicRaycaster));
  146. canvasObject.transform.SetParent(transform, false);
  147. var canvas = canvasObject.GetComponent<Canvas>();
  148. canvas.renderMode = RenderMode.ScreenSpaceOverlay;
  149. canvas.sortingOrder = short.MaxValue;
  150. var imageObject = new GameObject("Dim", typeof(RectTransform), typeof(Image));
  151. imageObject.transform.SetParent(canvasObject.transform, false);
  152. var rect = imageObject.GetComponent<RectTransform>();
  153. rect.anchorMin = Vector2.zero;
  154. rect.anchorMax = Vector2.one;
  155. rect.offsetMin = Vector2.zero;
  156. rect.offsetMax = Vector2.zero;
  157. backdrop = imageObject.GetComponent<Image>();
  158. backdrop.color = new Color(0f, 0f, 0f, RestoredBackdropAlpha);
  159. backdrop.raycastTarget = true;
  160. }
  161. void CreateWebView()
  162. {
  163. UniWebView.SetAllowAutoPlay(true);
  164. UniWebView.SetJavaScriptEnabled(true);
  165. webView = gameObject.AddComponent<UniWebView>();
  166. webView.SetContentInsetAdjustmentBehavior(UniWebViewContentInsetAdjustmentBehavior.Never);
  167. webView.BackgroundColor = Color.black;
  168. webView.SetBackButtonEnabled(true);
  169. webView.OnShouldClose += HandleShouldClose;
  170. webView.OnPageFinished += HandlePageFinished;
  171. webView.OnLoadingErrorReceived += HandleLoadingError;
  172. webView.OnChannelMessageReceived += HandleChannelMessage;
  173. webView.OnMessageReceived += HandleUrlMessage;
  174. }
  175. bool HandleShouldClose(UniWebView view)
  176. {
  177. Close();
  178. return false;
  179. }
  180. void HandlePageFinished(UniWebView view, int statusCode, string url)
  181. {
  182. pageLoaded = true;
  183. Debug.Log("[Activity] Activity page loaded: " + url);
  184. ApplyCurrentFrame();
  185. view.Show();
  186. }
  187. void HandleLoadingError(UniWebView view, int errorCode, string errorMessage, UniWebViewNativeResultPayload payload)
  188. {
  189. if (pageLoaded)
  190. {
  191. Debug.LogWarning($"[Activity] Resource loading error {errorCode}: {errorMessage}");
  192. return;
  193. }
  194. Debug.LogWarning($"[Activity] Failed to load the activity page {errorCode}: {errorMessage}");
  195. Close();
  196. }
  197. UniWebViewChannelMessageResponse HandleChannelMessage(UniWebView view, UniWebViewChannelMessage message)
  198. {
  199. HandleAction(message.action, message.data);
  200. return null;
  201. }
  202. void HandleUrlMessage(UniWebView view, UniWebViewMessage message)
  203. {
  204. if (!string.Equals(message.Scheme, "uniwebview", StringComparison.OrdinalIgnoreCase))
  205. return;
  206. string payload = null;
  207. if (message.Args != null)
  208. message.Args.TryGetValue("payload", out payload);
  209. HandleAction(message.Path, payload);
  210. }
  211. void HandleAction(string action, string data)
  212. {
  213. if (string.IsNullOrWhiteSpace(action))
  214. return;
  215. switch (action.Trim().ToLowerInvariant())
  216. {
  217. case "close":
  218. Close();
  219. break;
  220. case "maximize":
  221. SetMaximized(true);
  222. break;
  223. case "restore":
  224. SetMaximized(false);
  225. break;
  226. case "facebook_config":
  227. ActivityFacebookService.ApplyConfig(ParseFacebookConfig(data));
  228. break;
  229. case "openwindow":
  230. OpenWindow(data);
  231. break;
  232. default:
  233. ActivityFacebookService.LogEvent(action, data);
  234. break;
  235. }
  236. }
  237. void SetMaximized(bool value)
  238. {
  239. maximized = value;
  240. ApplyCurrentFrame();
  241. }
  242. void ApplyCurrentFrame()
  243. {
  244. if (webView != null)
  245. webView.Frame = CalculateFrame();
  246. if (backdrop != null)
  247. backdrop.color = new Color(0f, 0f, 0f, maximized ? MaximizedBackdropAlpha : RestoredBackdropAlpha);
  248. }
  249. Rect CalculateFrame()
  250. {
  251. Rect safeArea = Screen.safeArea;
  252. float safeTop = Screen.height - safeArea.yMax;
  253. if (maximized)
  254. return new Rect(safeArea.xMin, safeTop, safeArea.width, safeArea.height);
  255. float width = safeArea.width * initialScale;
  256. float height = safeArea.height * initialScale;
  257. float x = safeArea.xMin + (safeArea.width - width) * 0.5f;
  258. float y = safeTop + (safeArea.height - height) * 0.5f;
  259. return new Rect(x, y, width, height);
  260. }
  261. void OpenWindow(string data)
  262. {
  263. if (string.IsNullOrWhiteSpace(data))
  264. return;
  265. try
  266. {
  267. var payload = JsonUtility.FromJson<ActivityOpenWindowPayload>(data);
  268. if (payload != null && !string.IsNullOrWhiteSpace(payload.url))
  269. Application.OpenURL(payload.url);
  270. }
  271. catch (Exception exception)
  272. {
  273. Debug.LogWarning("[Activity] Invalid openWindow payload: " + exception.Message);
  274. }
  275. }
  276. static ActivityFacebookConfig ParseFacebookConfig(string data)
  277. {
  278. if (string.IsNullOrWhiteSpace(data))
  279. return null;
  280. try
  281. {
  282. return JsonUtility.FromJson<ActivityFacebookConfig>(data);
  283. }
  284. catch (Exception exception)
  285. {
  286. Debug.LogWarning("[Activity] Invalid Facebook config: " + exception.Message);
  287. return null;
  288. }
  289. }
  290. void Close()
  291. {
  292. if (closing)
  293. return;
  294. closing = true;
  295. if (instance == this)
  296. instance = null;
  297. Destroy(gameObject);
  298. }
  299. #pragma warning disable 0649
  300. [Serializable]
  301. sealed class ActivityOpenWindowPayload
  302. {
  303. public string url;
  304. }
  305. #pragma warning restore 0649
  306. }