UserPlayer.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using JCEngineCore;
  5. using UnityEngine.SceneManagement;
  6. using DG.Tweening;
  7. using JCUnityLib;
  8. using AppUI.Bluetooth;
  9. using UHomeView = AppUI.View.Home.Main.HomeView;
  10. /* Socket组件-玩家业务 */
  11. public class UserPlayer : JCEntity
  12. {
  13. public static UserPlayer ins;
  14. public UserPlayer() {
  15. ins = this;
  16. components.Add("PKComp", PKComp.Instance);
  17. components.Add("UserComp", UserComp.Instance);
  18. GetUserInfo();
  19. }
  20. public static void ConnectServer() {
  21. if (ins != null) return;
  22. if (AuthLoginMask.ins) AuthLoginMask.ins.SetVisiable(true);
  23. if (CommonConfig.businessServerWsURL != null) {
  24. JCEngine.boot(CommonConfig.businessServerWsURL, new UserPlayer());
  25. } else {
  26. LoginByToken();
  27. }
  28. }
  29. private static int _RetryLoginByTokenCount = -1;
  30. public static void LoginByToken()
  31. {
  32. if (++_RetryLoginByTokenCount > 0)
  33. AuthLoginMask.ins?.SetRetryCount(_RetryLoginByTokenCount);
  34. CoroutineStarter.Start(LoginController.Instance.LoginByToken((res) => {
  35. if (res.code == 0) {
  36. _RetryLoginByTokenCount = -1;
  37. string loginToken = (string)res.data;
  38. CommonConfig.businessServerWsURL = loginToken.Split('&')[2];
  39. PlayerPrefs.SetString(LoginMgr.LoginTokenKey, loginToken);
  40. JCEngine.boot(CommonConfig.businessServerWsURL, new UserPlayer());
  41. } else if (res.code == -9999) {
  42. if (_RetryLoginByTokenCount < 3) {
  43. LoginByToken();
  44. } else {
  45. _RetryLoginByTokenCount = -1;
  46. AuthLoginMask.ins?.SetAutoRetryFail();
  47. }
  48. } else {
  49. _RetryLoginByTokenCount = -1;
  50. handleAuthExpire();
  51. }
  52. }));
  53. }
  54. //之所以做成协程延迟触发,是因为用编辑器调试时,停止运行后会触发断线重连,就会造成游戏停止调试了,但socket还连接的现象。
  55. IEnumerator ReconnenctServer() {
  56. yield return new WaitForSecondsRealtime(0.1f);
  57. JCEngine.reboot(this);
  58. }
  59. bool canReconnnect = true;
  60. public override void onLoad() {
  61. Debug.Log("UserPlayer onLoad()");
  62. authToken();
  63. }
  64. public override void onReload() {
  65. Debug.Log("UserPlayer onReload()");
  66. authToken();
  67. }
  68. public override void onDestroy() {
  69. loginAuthed = false;
  70. Debug.Log("UserPlayer onDestroy()");
  71. if (canReconnnect) {
  72. JCUnityLib.CoroutineStarter.Start(ReconnenctServer());
  73. }
  74. }
  75. public override void onMiss() {
  76. Debug.Log("UserPlayer onMiss()");
  77. if (canReconnnect) {
  78. JCUnityLib.CoroutineStarter.Start(ReconnenctServer());
  79. }
  80. }
  81. public void Close() {
  82. LoginMgr.myUserInfo.id = 0;
  83. if (ins == this) ins = null;
  84. this.canReconnnect = false;
  85. this.channel.close();
  86. Debug.Log("user player close");
  87. }
  88. //向服务端发送的请求
  89. public void authToken() {
  90. string p0 = PlayerPrefs.GetString(LoginMgr.LoginTokenKey, "");
  91. string p1 = SceneManager.GetActiveScene().name;
  92. call("authToken2", p0, p1);
  93. }
  94. //被服务端调用的函数
  95. public bool loginAuthed;
  96. public void onAuthRes(bool res) {
  97. Debug.Log("onAuthRes," + res);
  98. loginAuthed = res;
  99. if (!loginAuthed) handleAuthExpire();
  100. else TryHomeAutoConnectBle();
  101. }
  102. /// <summary>Home 延迟自动连蓝牙:仅单机已拉取用户信息,或联机已 auth 且用户信息就绪且 AuthLoginMask 已关闭。</summary>
  103. public static bool IsLoginReadyForHomeBle()
  104. {
  105. if (CommonConfig.bDisableBluetooth) return false;
  106. if (CommonConfig.StandaloneMode)
  107. return ins != null && ins.hasGetUserInfo;
  108. if (ins == null || !ins.loginAuthed || !ins.hasGetUserInfo) return false;
  109. if (AuthLoginMask.ins != null && AuthLoginMask.ins.IsVisiable()) return false;
  110. return true;
  111. }
  112. public static void TryHomeAutoConnectBle()
  113. {
  114. if (!IsLoginReadyForHomeBle()) return;
  115. if (!SceneManager.GetActiveScene().name.Equals("Home")) return;
  116. SmartBowDeviceHub.EnsureReady();
  117. SmartBowDeviceHub.ins?.Ble?.HomeViewConnectBLE();
  118. }
  119. //获取用户信息,失败了就重试
  120. public void GetUserInfo()
  121. {
  122. if (CommonConfig.StandaloneMode)
  123. {
  124. UserInfo userInfo = UserInfo.LoadLocal(0);
  125. if (userInfo == null) userInfo = new();
  126. userInfo.nickname = TextAutoLanguage2.GetTextByKey("Player_Name");
  127. TextAutoLanguage2.OnLanguageChanged += (languageEnum) =>
  128. {
  129. //切换单机的名字
  130. userInfo.nickname = TextAutoLanguage2.GetTextByKey("Player_Name");
  131. UHomeView.ins.RenderNameOrGender();
  132. };
  133. DoAfterGetUserInfo(userInfo);
  134. return;
  135. }
  136. UserPlayer userPlayer = this;
  137. CoroutineStarter.Start(LoginController.Instance.GetUserInfo((res) =>
  138. {
  139. if (ins != userPlayer) return;
  140. if (res.code == 0)
  141. {
  142. UserInfo userInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<UserInfo>(res.data as string);
  143. DoAfterGetUserInfo(userInfo);
  144. }
  145. else if (res.code == -9999)
  146. AuthLoginMask.ins?.SetAutoRetryFail();
  147. else
  148. handleAuthExpire();
  149. }));
  150. }
  151. IEnumerator showTip()
  152. {
  153. yield return new WaitForSeconds(0.3f);
  154. GameObject settingsViewObj = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_HomeViewTip);
  155. settingsViewObj.GetComponent<HomeView_Tip>().setHomeTip(0);
  156. }
  157. public bool hasGetUserInfo;
  158. private void DoAfterGetUserInfo(UserInfo userInfo)
  159. {
  160. if (hasGetUserInfo) return;
  161. hasGetUserInfo = true;
  162. LoginMgr.myUserInfo = userInfo;
  163. if (UHomeView.ins) {
  164. UHomeView.ins.RenderMyAvatarSprite();
  165. UHomeView.ins.RenderNameOrGender();
  166. //UHomeView.ins.RenderDeviceNames();
  167. }
  168. if (AuthLoginMask.ins) AuthLoginMask.ins.SetVisiable(false);
  169. TryHomeAutoConnectBle();
  170. //if (SceneManager.GetActiveScene().name.Equals("Home") && !LoginMgr.myUserInfo.IsGuideFinish(0)) {
  171. // //NewUserGuiderManager.ins?.ReviewNewUserGuide();
  172. // //安装后首次进入APP和首次登录账号进入APP后
  173. // //GameObject settingsViewObj = ViewManager2.getGameObjectAndShowView(ViewManager2.Path_HomeViewTip);
  174. // //settingsViewObj.GetComponent<HomeView_Tip>().setHomeTip(0);
  175. // CoroutineStarter.Start(showTip());
  176. // LoginMgr.myUserInfo.SaveGuideFinish(0);
  177. //}
  178. if (SceneManager.GetActiveScene().name.Equals("Home")) {
  179. if (LoginMgr.myUserInfo.nickname == "test10086") InitLogReporter();
  180. }
  181. if (SceneManager.GetActiveScene().name.Equals("Home") && !CommonConfig.StandaloneMode) {
  182. System.Action eOnAgree = () => {
  183. GPSTool.GetAddress((address) => {
  184. if (address != null) {
  185. if (LoginMgr.myUserInfo.country == address[0]
  186. && LoginMgr.myUserInfo.state == address[1]
  187. && LoginMgr.myUserInfo.city == address[2]
  188. ) return;
  189. LoginMgr.myUserInfo.country = address[0];
  190. LoginMgr.myUserInfo.state = address[1];
  191. LoginMgr.myUserInfo.city = address[2];
  192. LoginMgr.myUserInfo.Save();
  193. }
  194. });
  195. if (!LoginMgr.myUserInfo.IsGuideFinish(0))
  196. {
  197. //新UI不用
  198. //CoroutineStarter.Start(showTip());
  199. LoginMgr.myUserInfo.SaveGuideFinish(0);
  200. }
  201. };
  202. System.Action eOnReject = () => {
  203. if (!LoginMgr.myUserInfo.IsGuideFinish(0))
  204. {
  205. //新UI不用
  206. //CoroutineStarter.Start(showTip());
  207. LoginMgr.myUserInfo.SaveGuideFinish(0);
  208. }
  209. };
  210. //提示Location新UI隐藏
  211. //if (!HomeView.ShowProminentBeforeConnectBLE_Event(eOnAgree,eOnReject)) {
  212. // eOnAgree.Invoke();
  213. //}
  214. ////else
  215. ////{
  216. //// if (!LoginMgr.myUserInfo.IsGuideFinish(0))
  217. //// {
  218. //// CoroutineStarter.Start(showTip());
  219. //// LoginMgr.myUserInfo.SaveGuideFinish(0);
  220. //// }
  221. ////}
  222. }
  223. }
  224. //控制台
  225. private static bool s_LogReporterInited = false;
  226. public static void InitLogReporter()
  227. {
  228. if (s_LogReporterInited) return;
  229. s_LogReporterInited = true;
  230. Object.Instantiate(Resources.Load("Prefabs/LogReporter"));
  231. Debug.LogWarning("在屏幕上画个圈即可打开控制台");
  232. Debug.Log("app-version: " + Resources.Load<TextAsset>("app-version").text);
  233. }
  234. public static Object InitReturnLogReporter()
  235. {
  236. if (s_LogReporterInited) return null;
  237. s_LogReporterInited = true;
  238. Object o = Object.Instantiate(Resources.Load("Prefabs/LogReporter"));
  239. Debug.LogWarning("在屏幕上画个圈即可打开控制台");
  240. Debug.Log("app-version: " + Resources.Load<TextAsset>("app-version").text);
  241. return o;
  242. }
  243. private static void handleAuthExpire()
  244. {
  245. //tip
  246. if (AuthLoginMask.ins && AuthLoginMask.ins.IsVisiable()) {
  247. AuthLoginMask.ins.SetText(TextAutoLanguage2.GetTextByCNKey("登录认证过期"));
  248. } else {
  249. PopupMgr.ins.ShowTip(TextAutoLanguage2.GetTextByCNKey("登录认证过期"));
  250. }
  251. //delay back login
  252. Sequence seq = DOTween.Sequence();
  253. seq.AppendInterval(1.5f);
  254. seq.AppendCallback(() => {
  255. if (SceneManager.GetActiveScene().name.Equals("Home")) {
  256. SceneManager.LoadScene("Login", LoadSceneMode.Single);
  257. } else {
  258. Application.Quit(); //不是Home场景,就关闭游戏
  259. }
  260. });
  261. //close userplayer
  262. PlayerPrefs.DeleteKey(LoginMgr.LoginTokenKey);
  263. CommonConfig.businessServerWsURL = null;
  264. ins?.Close();
  265. }
  266. public void onAnyMessage(string msg)
  267. {
  268. SideTipView.ShowTip(msg, msg.EndsWith("失败") ? Color.yellow : Color.white);
  269. }
  270. public void onRequestAddFriend() {
  271. GameObject tipTopObject = PopupMgr.ins.ShowTipTop(TextAutoLanguage2.GetTextByKey("tip_friend-receive-request"));
  272. tipTopObject.AddComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
  273. if (UnityEngine.SceneManagement.SceneManager.GetActiveScene().name != "Home") return;
  274. //ViewMgr.Instance.ShowView<FriendView>("setFirstBtnTabsIndex", 1);
  275. ViewManager2.ShowView(ViewManager2.Path_SocialView);
  276. GameObject.Destroy(tipTopObject);
  277. });
  278. tempData.hasFriendRequest = true;
  279. }
  280. public void onHasFriendTip() {
  281. tempData.hasFriendRequest = true;
  282. }
  283. public TempData tempData = new TempData();
  284. public class TempData {
  285. public System.Action onUpdate;
  286. private bool _hasFriendRequest;
  287. public bool hasFriendRequest {
  288. get {
  289. return _hasFriendRequest;
  290. }
  291. set {
  292. _hasFriendRequest = value;
  293. onUpdate?.Invoke();
  294. }
  295. }
  296. }
  297. /**
  298. * 获取一个起始和结束的当月时间
  299. */
  300. public string[] getDateArray() {
  301. System.DateTime currentTime = System.DateTime.Now;
  302. System.DateTime firstDayOfMonth = new System.DateTime(currentTime.Year, currentTime.Month, 1);
  303. System.DateTime lastDayOfMonth = firstDayOfMonth.AddMonths(1).AddDays(-1);
  304. //Debug.Log("getDateArray First day of current month: " + firstDayOfMonth.ToString("yyyy-MM-dd"));
  305. //Debug.Log("getDateArray Last day of current month: " + lastDayOfMonth.ToString("yyyy-MM-dd"));
  306. return new string[] { firstDayOfMonth.ToString("yyyy-MM-dd"), lastDayOfMonth.ToString("yyyy-MM-dd") };
  307. }
  308. }