App.vue 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  1. <script>
  2. import timPresenceManager from '@/utils/tim-presence-manager.js';
  3. import timManager from '@/utils/tim-manager.js';
  4. export default {
  5. data() {
  6. return {
  7. _timInitializing: false
  8. }
  9. },
  10. onLaunch: function () {
  11. console.log('=== App启动 ===');
  12. // 初始化TIM(全局)
  13. this.initGlobalTIM();
  14. // 延迟挂载全局方法(等待 App 实例创建完成)
  15. setTimeout(() => {
  16. const app = getApp();
  17. if (app) {
  18. app.globalData.initGlobalTIM = this.initGlobalTIM.bind(this);
  19. app.globalData.initPresenceManager = this.initPresenceManager.bind(this);
  20. console.log('✅ 全局方法挂载成功');
  21. }
  22. }, 100);
  23. },
  24. onShow: function () {
  25. console.log('=== App显示 ===');
  26. console.log(' 当前时间:', new Date().toLocaleTimeString());
  27. // 延迟检查TIM连接状态,避免在登录过程中重复调用
  28. setTimeout(() => {
  29. console.log('⏰ 开始执行 checkTIMConnection...');
  30. this.checkTIMConnection();
  31. }, 500); // 缩短延迟时间到 500ms
  32. },
  33. onHide: function () {
  34. console.log('=== App隐藏 ===');
  35. // App切换到后台时,不断开连接,保持在线状态
  36. },
  37. methods: {
  38. /**
  39. * 初始化全局TIM
  40. */
  41. async initGlobalTIM() {
  42. // 避免在登录过程中被重复触发
  43. if (this._timInitializing) {
  44. return
  45. }
  46. this._timInitializing = true
  47. try {
  48. // 获取当前登录用户ID
  49. const userInfo = uni.getStorageSync('userInfo');
  50. const userId = uni.getStorageSync('userId') || userInfo?.userId || userInfo?.id;
  51. if (!userId) {
  52. console.log('⚠️ 未登录,跳过TIM初始化');
  53. return;
  54. }
  55. // 如果TIM已经登录且用户ID匹配,跳过
  56. if (timManager.isLogin && String(timManager.userId) === String(userId)) {
  57. console.log('✅ TIM已登录,用户ID:', userId);
  58. return;
  59. }
  60. console.log('🚀 开始初始化全局TIM,用户ID:', userId);
  61. // 初始化TIM SDK(只在首次初始化)
  62. const SDKAppID = 1600109674;
  63. if (!timManager.tim) {
  64. timManager.init(SDKAppID);
  65. console.log('✅ TIM SDK 初始化完成');
  66. }
  67. // 如果用户ID不匹配,先登出旧用户
  68. if (timManager.isLogin && timManager.userId && String(timManager.userId) !== String(userId)) {
  69. console.log('⚠️ 检测到用户切换,先登出旧用户...');
  70. try {
  71. await timManager.logout();
  72. console.log('✅ 旧用户已登出');
  73. } catch (e) {
  74. console.warn('⚠️ 登出失败,继续登录新用户:', e.message);
  75. }
  76. }
  77. // 获取UserSig
  78. const res = await uni.request({
  79. url: `http://localhost:8083/api/im/getUserSig?userId=${userId}`,
  80. method: 'GET'
  81. });
  82. if (res[1].data.code === 200) {
  83. const userSig = res[1].data.data.userSig;
  84. // 登录TIM
  85. await timManager.login(String(userId), userSig);
  86. console.log('✅ 全局TIM登录成功');
  87. // TIM 登录成功后,初始化在线状态管理器
  88. await this.initPresenceManager(userId);
  89. } else {
  90. throw new Error('获取UserSig失败');
  91. }
  92. } catch (error) {
  93. console.error('❌ 初始化全局TIM失败:', error);
  94. } finally {
  95. this._timInitializing = false
  96. }
  97. },
  98. /**
  99. * 初始化在线状态管理器
  100. */
  101. async initPresenceManager(userId) {
  102. try {
  103. console.log('🌐 初始化在线状态管理器,用户ID:', userId);
  104. // 初始化 TIM + WebSocket 混合状态管理器
  105. await timPresenceManager.init(String(userId));
  106. console.log('✅ 在线状态管理器初始化成功');
  107. } catch (error) {
  108. console.error('❌ 初始化在线状态管理器失败:', error);
  109. }
  110. },
  111. /**
  112. * 检查TIM连接状态和WebSocket连接状态
  113. */
  114. checkTIMConnection() {
  115. console.log('🔍 ========== 开始检查连接状态 ==========');
  116. // 获取当前登录用户ID
  117. const userId = uni.getStorageSync('userId');
  118. console.log(' 当前用户ID:', userId);
  119. if (!userId) {
  120. console.log('⚠️ 未登录,跳过连接检查');
  121. console.log('=========================================');
  122. return;
  123. }
  124. // 检查 TIM 是否登录
  125. console.log(' TIM 登录状态:', timManager.isLogin);
  126. console.log(' TIM 用户ID:', timManager.userId);
  127. if (!timManager.isLogin) {
  128. console.log('⚠️ TIM未登录,尝试重新初始化');
  129. console.log('=========================================');
  130. this.initGlobalTIM();
  131. return;
  132. }
  133. // 检查 WebSocket 是否连接
  134. console.log(' WebSocket 连接状态:', timPresenceManager.isConnected);
  135. if (!timPresenceManager.isConnected) {
  136. console.log('⚠️ WebSocket未连接,尝试重新初始化在线状态管理器');
  137. console.log('=========================================');
  138. this.initPresenceManager(userId);
  139. } else {
  140. console.log('✅ TIM和WebSocket连接正常');
  141. console.log('=========================================');
  142. }
  143. }
  144. },
  145. globalData: {
  146. }
  147. }
  148. </script>
  149. <style lang="scss">
  150. /*每个页面公共css */
  151. page {
  152. min-height: 100vh;
  153. width: 750rpx;
  154. background-color: #fff;
  155. padding-bottom: constant(safe-area-inset-bottom);
  156. padding-bottom: env(safe-area-inset-bottom);
  157. }
  158. .content {
  159. display: flex;
  160. flex-direction: column;
  161. }
  162. </style>