tim-presence-manager.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  1. /**
  2. * TIM在线状态管理器 + WebSocket聊天管理器
  3. * 统一管理WebSocket连接、心跳、在线状态、聊天消息
  4. */
  5. import timManager from './tim-manager.js';
  6. import TIM from 'tim-wx-sdk';
  7. // WebSocket/TIM 调试日志开关
  8. const DEBUG_WS = false;
  9. class TIMPresenceManager {
  10. constructor() {
  11. this.ws = null;
  12. this.heartbeatTimer = null;
  13. this.reconnectTimer = null;
  14. this.heartbeatInterval = 30000; // 30秒心跳
  15. this.reconnectInterval = 5000; // 5秒重连
  16. this.isConnected = false;
  17. this.userId = null;
  18. this.statusCallbacks = new Map(); // 存储状态变化回调
  19. this.onlineStatusCache = new Map(); // 缓存在线状态
  20. this.wsUrl = 'wss://ws.zhongruanke.cn/ws/chat';
  21. // TIM 状态监听器引用(用于清理)
  22. this.timStatusListener = null;
  23. this.timConnectListener = null;
  24. // 聊天消息相关
  25. this.messageQueue = []; // 消息队列(断线时暂存)
  26. this.maxQueueSize = 100;
  27. this.onMessageCallback = null; // 消息回调
  28. this.onConnectCallback = null; // 连接回调
  29. this.onDisconnectCallback = null; // 断开回调
  30. this.onErrorCallback = null; // 错误回调
  31. this.reconnectCount = 0;
  32. this.maxReconnectCount = 10;
  33. }
  34. /**
  35. * 初始化
  36. */
  37. async init(userId) {
  38. this.userId = userId;
  39. this.connectWebSocket();
  40. }
  41. /**
  42. * 建立 WebSocket 连接
  43. */
  44. connectWebSocket() {
  45. try {
  46. const wsUrl = `${this.wsUrl}?userId=${this.userId}`;
  47. // 先关闭旧连接
  48. if (this.ws) {
  49. try {
  50. uni.closeSocket();
  51. } catch (e) {
  52. console.warn('关闭旧连接失败:', e);
  53. }
  54. }
  55. this.ws = uni.connectSocket({
  56. url: wsUrl,
  57. success: () => {
  58. },
  59. fail: (err) => {
  60. console.error('❌ WebSocket连接请求发送失败:', err);
  61. console.error(' 错误详情:', JSON.stringify(err));
  62. this.scheduleReconnect();
  63. }
  64. });
  65. // 使用 SocketTask 对象的监听器(推荐方式)
  66. this.ws.onOpen((res) => {
  67. this.isConnected = true;
  68. this.reconnectCount = 0; // 重置重连计数
  69. // 启动心跳
  70. this.startHeartbeat();
  71. // 发送队列中的消息
  72. this.flushMessageQueue();
  73. // 连接成功后,立即上报当前 TIM 连接状态
  74. this.reportCurrentTIMStatus();
  75. // 触发连接回调
  76. if (this.onConnectCallback) {
  77. this.onConnectCallback();
  78. }
  79. });
  80. // 监听消息
  81. this.ws.onMessage((res) => {
  82. this.handleMessage(res.data);
  83. });
  84. // 监听错误
  85. this.ws.onError((err) => {
  86. this.isConnected = false;
  87. // 触发错误回调
  88. if (this.onErrorCallback) {
  89. this.onErrorCallback(err);
  90. }
  91. this.scheduleReconnect();
  92. });
  93. // 监听关闭
  94. this.ws.onClose((res) => {
  95. this.isConnected = false;
  96. this.stopHeartbeat();
  97. // 触发断开回调
  98. if (this.onDisconnectCallback) {
  99. this.onDisconnectCallback();
  100. }
  101. this.scheduleReconnect();
  102. });
  103. } catch (error) {
  104. console.error('❌ WebSocket连接异常:', error);
  105. this.scheduleReconnect();
  106. }
  107. }
  108. /**
  109. * 监听 TIM 连接状态变更
  110. */
  111. listenTIMConnectionStatus() {
  112. if (!timManager.tim || !timManager.tim.TIM) {
  113. console.warn('⚠️ TIM 未初始化或 TIM 对象不完整,无法监听连接状态');
  114. return;
  115. }
  116. const TIM = timManager.tim.TIM;
  117. // 监听 IM 连接状态变化
  118. this.timConnectListener = (event) => {
  119. let imStatus = 'offline';
  120. // 映射 TIM 状态到业务状态
  121. switch (event.data.state) {
  122. case TIM.TYPES.NET_STATE_CONNECTED:
  123. imStatus = 'online';
  124. break;
  125. case TIM.TYPES.NET_STATE_DISCONNECTED:
  126. case TIM.TYPES.NET_STATE_CONNECTING:
  127. imStatus = 'offline';
  128. break;
  129. }
  130. // 通过 WebSocket 上报状态给服务端
  131. this.reportIMStatus(imStatus);
  132. };
  133. timManager.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.timConnectListener);
  134. }
  135. /**
  136. * 监听 TIM 用户状态更新(好友状态)
  137. */
  138. listenTIMUserStatus() {
  139. if (!timManager.tim || !timManager.tim.TIM) {
  140. console.warn('⚠️ TIM 未初始化或 TIM 对象不完整,无法监听用户状态');
  141. return;
  142. }
  143. const TIM = timManager.tim.TIM;
  144. // 监听用户状态更新事件
  145. this.timStatusListener = (event) => {
  146. const { userStatusList } = event.data;
  147. if (userStatusList && userStatusList.length > 0) {
  148. userStatusList.forEach(item => {
  149. const userId = item.userID;
  150. const status = item.statusType === TIM.TYPES.USER_STATUS_ONLINE ? 'online' : 'offline';
  151. // 更新本地缓存
  152. this.onlineStatusCache.set(String(userId), status === 'online');
  153. // 通知状态变化
  154. this.notifyStatusChange(String(userId), status);
  155. // 也可以通过 WS 上报给服务端,保证服务端状态一致
  156. this.reportFriendStatus(userId, status);
  157. });
  158. } else {
  159. console.warn(' ⚠️ userStatusList 为空或不存在');
  160. }
  161. };
  162. timManager.tim.on(TIM.EVENT.USER_STATUS_UPDATED, this.timStatusListener);
  163. }
  164. /**
  165. * 上报当前 TIM 连接状态
  166. */
  167. reportCurrentTIMStatus() {
  168. if (!timManager.isLogin) {
  169. this.reportIMStatus('offline');
  170. return;
  171. }
  172. // TIM 已登录,上报在线状态
  173. this.reportIMStatus('online');
  174. }
  175. /**
  176. * 上报 IM 状态给服务端
  177. * @param {String} status 状态:online/offline
  178. */
  179. reportIMStatus(status) {
  180. if (!this.isConnected) {
  181. console.warn('⚠️ WebSocket 未连接,无法上报 IM 状态');
  182. return;
  183. }
  184. this.sendMessage({
  185. type: 'imStatusReport',
  186. userId: this.userId,
  187. status: status,
  188. device: 'mobile', // 设备类型
  189. timestamp: Date.now()
  190. });
  191. }
  192. /**
  193. * 上报好友状态给服务端
  194. * @param {String} friendUserId 好友用户ID
  195. * @param {String} status 状态:online/offline
  196. */
  197. reportFriendStatus(friendUserId, status) {
  198. if (!this.isConnected) {
  199. return;
  200. }
  201. this.sendMessage({
  202. type: 'friendStatusReport',
  203. userId: friendUserId,
  204. status: status,
  205. timestamp: Date.now()
  206. });
  207. }
  208. /**
  209. * 订阅用户状态(使用 TIM 原生能力)
  210. * @param {Array<String>} userIdList 用户ID列表
  211. */
  212. async subscribeUserStatus(userIdList) {
  213. if (!timManager.tim || !timManager.isLogin) {
  214. console.warn('⚠️ TIM 未登录,无法订阅用户状态');
  215. console.warn(' - timManager.tim:', !!timManager.tim);
  216. console.warn(' - timManager.isLogin:', timManager.isLogin);
  217. // 使用 HTTP 轮询作为备用方案
  218. this.startHttpPolling(userIdList);
  219. return;
  220. }
  221. try {
  222. const result = await timManager.tim.subscribeUserStatus({
  223. userIDList: userIdList.map(id => String(id))
  224. });
  225. // 订阅成功后,初始化这些用户的状态
  226. if (result.data && result.data.successUserList) {
  227. result.data.successUserList.forEach(user => {
  228. const status = user.statusType === timManager.tim.TIM.TYPES.USER_STATUS_ONLINE ? 'online' : 'offline';
  229. this.onlineStatusCache.set(String(user.userID), status === 'online');
  230. this.notifyStatusChange(String(user.userID), status);
  231. });
  232. }
  233. // 检查失败列表
  234. if (result.data && result.data.failureUserList && result.data.failureUserList.length > 0) {
  235. console.warn('⚠️ 部分用户订阅失败:', result.data.failureUserList);
  236. }
  237. return result;
  238. } catch (error) {
  239. console.error(' - 错误代码:', error.code);
  240. // 如果订阅失败,启用 HTTP 轮询备用方案
  241. if (error.code === 70402 || error.code === 70403) {
  242. this.startHttpPolling(userIdList);
  243. }
  244. throw error;
  245. }
  246. }
  247. /**
  248. * HTTP 轮询备用方案(当 TIM 订阅失败时使用)
  249. * @param {Array<String>} userIdList 用户ID列表
  250. */
  251. startHttpPolling(userIdList) {
  252. // 立即查询一次
  253. this.pollUserStatus(userIdList);
  254. // 每 30 秒轮询一次
  255. this.pollingTimer = setInterval(() => {
  256. this.pollUserStatus(userIdList);
  257. }, 30000);
  258. }
  259. /**
  260. * 轮询用户状态
  261. */
  262. async pollUserStatus(userIdList) {
  263. for (const userId of userIdList) {
  264. try {
  265. const [err, res] = await uni.request({
  266. url: 'https://api.zhongruanke.cn/api/online/checkStatus',
  267. method: 'GET',
  268. data: { userId }
  269. });
  270. if (!err && res.data && res.data.code === 200) {
  271. const isOnline = res.data.data.online || false;
  272. const oldStatus = this.onlineStatusCache.get(String(userId));
  273. // 只有状态变化时才通知
  274. if (oldStatus !== isOnline) {
  275. this.onlineStatusCache.set(String(userId), isOnline);
  276. this.notifyStatusChange(String(userId), isOnline ? 'online' : 'offline');
  277. }
  278. }
  279. } catch (error) {
  280. console.error(`查询用户 ${userId} 状态失败:`, error);
  281. }
  282. }
  283. }
  284. /**
  285. * 停止 HTTP 轮询
  286. */
  287. stopHttpPolling() {
  288. if (this.pollingTimer) {
  289. clearInterval(this.pollingTimer);
  290. this.pollingTimer = null;
  291. }
  292. }
  293. /**
  294. * 取消订阅用户状态
  295. * @param {Array<String>} userIdList 用户ID列表
  296. */
  297. async unsubscribeUserStatus(userIdList) {
  298. if (!timManager.tim || !timManager.isLogin) {
  299. return;
  300. }
  301. try {
  302. await timManager.tim.unsubscribeUserStatus({
  303. userIDList: userIdList.map(id => String(id))
  304. });
  305. } catch (error) {
  306. console.error('❌ 取消订阅用户状态失败:', error);
  307. }
  308. }
  309. /**
  310. * 处理接收到的消息
  311. */
  312. handleMessage(data) {
  313. try {
  314. const message = typeof data === 'string' ? JSON.parse(data) : data;
  315. switch (message.type) {
  316. case 'pong': // 改为小写,匹配后端
  317. // 心跳响应
  318. break;
  319. case 'ONLINE':
  320. case 'STATUS_UPDATE':
  321. // 用户上线/状态更新通知
  322. if (message.userId || message.fromUserId) {
  323. const userId = String(message.userId || message.fromUserId);
  324. const isOnline = message.online !== undefined ? message.online : (message.type === 'ONLINE');
  325. this.onlineStatusCache.set(userId, isOnline);
  326. this.notifyStatusChange(userId, isOnline ? 'online' : 'offline');
  327. }
  328. break;
  329. case 'OFFLINE':
  330. // 用户离线通知
  331. if (message.userId || message.fromUserId) {
  332. const userId = String(message.userId || message.fromUserId);
  333. this.onlineStatusCache.set(userId, false);
  334. this.notifyStatusChange(userId, 'offline');
  335. }
  336. break;
  337. }
  338. } catch (error) {
  339. console.error('❌ 消息解析失败:', error);
  340. }
  341. }
  342. /**
  343. * 启动心跳
  344. */
  345. startHeartbeat() {
  346. this.stopHeartbeat();
  347. this.heartbeatTimer = setInterval(() => {
  348. if (this.isConnected) {
  349. this.sendMessage({
  350. type: 'ping', // 改为小写,匹配后端
  351. fromUserId: this.userId,
  352. timestamp: Date.now()
  353. });
  354. } else {
  355. console.warn('⚠️ WebSocket未连接,跳过心跳');
  356. }
  357. }, this.heartbeatInterval);
  358. }
  359. /**
  360. * 停止心跳
  361. */
  362. stopHeartbeat() {
  363. if (this.heartbeatTimer) {
  364. clearInterval(this.heartbeatTimer);
  365. this.heartbeatTimer = null;
  366. }
  367. }
  368. /**
  369. * 发送消息
  370. */
  371. sendMessage(data) {
  372. if (!this.isConnected) {
  373. console.warn('⚠️ WebSocket未连接,无法发送消息');
  374. return;
  375. }
  376. try {
  377. uni.sendSocketMessage({
  378. data: JSON.stringify(data),
  379. fail: (err) => {
  380. console.error('❌ 发送消息失败:', err);
  381. }
  382. });
  383. } catch (error) {
  384. console.error('❌ 发送消息异常:', error);
  385. }
  386. }
  387. /**
  388. * 监听用户状态变化
  389. * @param {String} targetUserId 目标用户ID
  390. * @param {Function} callback 回调函数 (status) => {}
  391. */
  392. onStatusChange(targetUserId, callback) {
  393. if (!this.statusCallbacks.has(targetUserId)) {
  394. this.statusCallbacks.set(targetUserId, []);
  395. }
  396. this.statusCallbacks.get(targetUserId).push(callback);
  397. }
  398. /**
  399. * 移除状态监听
  400. * @param {String} targetUserId 目标用户ID
  401. * @param {Function} callback 回调函数
  402. */
  403. offStatusChange(targetUserId, callback) {
  404. if (!this.statusCallbacks.has(targetUserId)) {
  405. return;
  406. }
  407. const callbacks = this.statusCallbacks.get(targetUserId);
  408. const index = callbacks.indexOf(callback);
  409. if (index > -1) {
  410. callbacks.splice(index, 1);
  411. }
  412. if (callbacks.length === 0) {
  413. this.statusCallbacks.delete(targetUserId);
  414. }
  415. }
  416. /**
  417. * 通知状态变化
  418. */
  419. notifyStatusChange(userId, status) {
  420. const callbacks = this.statusCallbacks.get(userId);
  421. if (callbacks && callbacks.length > 0) {
  422. callbacks.forEach(callback => {
  423. try {
  424. callback(status);
  425. } catch (error) {
  426. console.error('❌ 状态回调执行失败:', error);
  427. }
  428. });
  429. }
  430. }
  431. /**
  432. * 获取缓存的在线状态
  433. * @param {String} userId 目标用户ID
  434. * @return {Boolean|null} 在线状态,null表示未知
  435. */
  436. getCachedStatus(userId) {
  437. return this.onlineStatusCache.get(String(userId)) || null;
  438. }
  439. /**
  440. * 计划重连
  441. */
  442. scheduleReconnect() {
  443. if (this.reconnectTimer) {
  444. return;
  445. }
  446. this.reconnectTimer = setTimeout(() => {
  447. this.reconnectTimer = null;
  448. if (!this.isConnected && this.userId) {
  449. this.connectWebSocket();
  450. }
  451. }, this.reconnectInterval);
  452. }
  453. /**
  454. * 发送队列中的消息
  455. */
  456. flushMessageQueue() {
  457. if (this.messageQueue.length === 0) {
  458. return;
  459. }
  460. while (this.messageQueue.length > 0) {
  461. const message = this.messageQueue.shift();
  462. this.sendMessage(message);
  463. }
  464. }
  465. /**
  466. * 断开连接
  467. */
  468. disconnect() {
  469. this.stopHeartbeat();
  470. this.stopHttpPolling(); // 停止 HTTP 轮询
  471. if (this.reconnectTimer) {
  472. clearTimeout(this.reconnectTimer);
  473. this.reconnectTimer = null;
  474. }
  475. // 移除 TIM 事件监听
  476. if (timManager.tim) {
  477. const TIM = timManager.tim.TIM;
  478. if (this.timConnectListener) {
  479. timManager.tim.off(TIM.EVENT.NET_STATE_CHANGE, this.timConnectListener);
  480. }
  481. if (this.timStatusListener) {
  482. timManager.tim.off(TIM.EVENT.USER_STATUS_UPDATED, this.timStatusListener);
  483. }
  484. }
  485. if (this.isConnected) {
  486. uni.closeSocket();
  487. this.isConnected = false;
  488. }
  489. this.statusCallbacks.clear();
  490. this.userId = null;
  491. }
  492. /**
  493. * 获取连接状态
  494. */
  495. getConnectionStatus() {
  496. return this.isConnected;
  497. }
  498. }
  499. // 导出单例
  500. export default new TIMPresenceManager();