tim-manager.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  1. import TIM from 'tim-wx-sdk';
  2. class TIMManager {
  3. constructor() {
  4. this.tim = null;
  5. this.isLogin = false;
  6. this.userId = null;
  7. this.messageCallbacks = [];
  8. }
  9. /**
  10. * 初始化 TIM SDK
  11. */
  12. init(sdkAppID) {
  13. // 创建 SDK 实例
  14. this.tim = TIM.create({
  15. SDKAppID: sdkAppID
  16. });
  17. // 设置日志级别(开发时设为 0,生产设为 1)
  18. this.tim.setLogLevel(0);
  19. // 注册监听事件
  20. this.registerEvents();
  21. console.log('✅ TIM SDK 初始化完成');
  22. }
  23. /**
  24. * 注册事件监听
  25. */
  26. registerEvents() {
  27. // SDK 进入 ready 状态
  28. this.tim.on(TIM.EVENT.SDK_READY, this.onSdkReady.bind(this));
  29. // SDK 未 ready
  30. this.tim.on(TIM.EVENT.SDK_NOT_READY, this.onSdkNotReady.bind(this));
  31. // 收到新消息
  32. this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, this.onMessageReceived.bind(this));
  33. // 会话列表更新
  34. this.tim.on(TIM.EVENT.CONVERSATION_LIST_UPDATED, this.onConversationListUpdated.bind(this));
  35. // 被踢下线
  36. this.tim.on(TIM.EVENT.KICKED_OUT, this.onKickedOut.bind(this));
  37. // 网络状态变化
  38. this.tim.on(TIM.EVENT.NET_STATE_CHANGE, this.onNetStateChange.bind(this));
  39. }
  40. /**
  41. * SDK Ready
  42. */
  43. onSdkReady() {
  44. console.log('✅ TIM SDK Ready');
  45. this.isLogin = true;
  46. }
  47. /**
  48. * SDK Not Ready
  49. */
  50. onSdkNotReady() {
  51. console.log('⚠️ TIM SDK Not Ready');
  52. this.isLogin = false;
  53. }
  54. /**
  55. * 收到新消息
  56. */
  57. onMessageReceived(event) {
  58. const messageList = event.data;
  59. console.log('📥 收到新消息:', messageList.length, '条');
  60. // 同步接收到的消息到MySQL(双重保障)
  61. messageList.forEach(message => {
  62. this.syncReceivedMessageToMySQL(message);
  63. });
  64. // 触发回调
  65. this.messageCallbacks.forEach(callback => {
  66. callback(messageList);
  67. });
  68. }
  69. /**
  70. * 同步接收到的消息到MySQL
  71. */
  72. async syncReceivedMessageToMySQL(timMessage) {
  73. try {
  74. // 获取消息类型
  75. const getMessageType = (msg) => {
  76. const typeMap = {
  77. 'TIMTextElem': 1,
  78. 'TIMImageElem': 2,
  79. 'TIMSoundElem': 3,
  80. 'TIMVideoFileElem': 4,
  81. 'TIMFileElem': 5
  82. };
  83. // 处理自定义消息(我们的语音消息)
  84. if (msg.type === 'TIMCustomElem' && msg.payload) {
  85. try {
  86. const customData = JSON.parse(msg.payload.data);
  87. if (customData.type === 'voice') {
  88. return 3; // 语音消息
  89. }
  90. } catch (e) {
  91. console.error('解析自定义消息类型失败:', e);
  92. }
  93. }
  94. return typeMap[msg.type] || 1;
  95. };
  96. // 获取消息内容
  97. const getMessageContent = (msg) => {
  98. switch (msg.type) {
  99. case 'TIMTextElem':
  100. return msg.payload.text || '';
  101. case 'TIMImageElem':
  102. return '[图片]';
  103. case 'TIMSoundElem':
  104. return '[语音]';
  105. case 'TIMVideoFileElem':
  106. return '[视频]';
  107. case 'TIMFileElem':
  108. return '[文件]';
  109. case 'TIMCustomElem':
  110. // 处理自定义消息
  111. try {
  112. const customData = JSON.parse(msg.payload.data);
  113. if (customData.type === 'voice') {
  114. return '[语音]';
  115. }
  116. } catch (e) {
  117. console.error('解析自定义消息内容失败:', e);
  118. }
  119. return '[自定义消息]';
  120. default:
  121. return '[未知消息]';
  122. }
  123. };
  124. const syncData = {
  125. messageId: timMessage.ID,
  126. fromUserId: timMessage.from,
  127. toUserId: timMessage.to,
  128. messageType: getMessageType(timMessage),
  129. content: getMessageContent(timMessage),
  130. sendTime: timMessage.time
  131. };
  132. // 如果是语音消息,添加语音信息
  133. if (timMessage.type === 'TIMSoundElem' && timMessage.payload) {
  134. syncData.mediaUrl = timMessage.payload.url || timMessage.payload.remoteAudioUrl;
  135. syncData.duration = timMessage.payload.second || 0;
  136. syncData.mediaSize = timMessage.payload.size || 0;
  137. }
  138. // 如果是自定义消息(我们的语音消息)
  139. if (timMessage.type === 'TIMCustomElem' && timMessage.payload) {
  140. try {
  141. const customData = JSON.parse(timMessage.payload.data);
  142. if (customData.type === 'voice') {
  143. syncData.mediaUrl = customData.url;
  144. syncData.duration = customData.duration;
  145. syncData.mediaSize = customData.size || 0;
  146. }
  147. } catch (e) {
  148. console.error('解析自定义消息失败:', e);
  149. }
  150. }
  151. // 如果是图片消息,添加图片信息
  152. if (timMessage.type === 'TIMImageElem' && timMessage.payload.imageInfoArray) {
  153. const imageInfo = timMessage.payload.imageInfoArray[0];
  154. syncData.mediaUrl = imageInfo.imageUrl;
  155. syncData.thumbnailUrl = imageInfo.imageUrl;
  156. }
  157. // 调用后端同步接口
  158. const res = await uni.request({
  159. url: 'http://localhost:8083/api/chat/syncTIMMessage',
  160. method: 'POST',
  161. data: syncData,
  162. header: {
  163. 'Content-Type': 'application/json'
  164. }
  165. });
  166. if (res[1].data.code === 200) {
  167. console.log('✅ 接收消息已同步到MySQL:', timMessage.ID);
  168. }
  169. } catch (error) {
  170. console.error('❌ 同步接收消息失败:', error);
  171. // 同步失败不影响主流程
  172. }
  173. }
  174. /**
  175. * 会话列表更新
  176. */
  177. onConversationListUpdated(event) {
  178. console.log('📋 会话列表更新:', event.data.length, '个');
  179. // 计算总未读数
  180. const conversationList = event.data;
  181. let totalUnread = 0;
  182. conversationList.forEach(conversation => {
  183. totalUnread += conversation.unreadCount || 0;
  184. });
  185. console.log('📊 总未读消息数:', totalUnread);
  186. // 更新到全局状态(Vuex)- 多种方式确保更新成功
  187. try {
  188. // 方式1: 使用 getApp() 获取全局实例
  189. const app = getApp();
  190. if (app && app.$store) {
  191. app.$store.dispatch('updateTotalUnread', totalUnread);
  192. console.log('✅ 已更新全局未读数到 Vuex (getApp):', totalUnread);
  193. } else {
  194. console.warn('⚠️ getApp() 未获取到 $store');
  195. }
  196. // 方式2: 直接导入 store(备用方案)
  197. try {
  198. const store = require('../store/index.js').default;
  199. if (store) {
  200. store.dispatch('updateTotalUnread', totalUnread);
  201. console.log('✅ 已更新全局未读数到 Vuex (require):', totalUnread);
  202. }
  203. } catch (e) {
  204. console.warn('⚠️ require store 失败:', e.message);
  205. }
  206. // 方式3: 触发自定义事件,通知所有页面
  207. uni.$emit('conversationUnreadUpdate', totalUnread);
  208. console.log('✅ 已触发 conversationUnreadUpdate 事件:', totalUnread);
  209. } catch (error) {
  210. console.error('❌ 更新全局未读数失败:', error);
  211. }
  212. }
  213. /**
  214. * 被踢下线
  215. */
  216. onKickedOut(event) {
  217. console.log('❌ 被踢下线:', event.data.type);
  218. uni.showModal({
  219. title: '下线通知',
  220. content: '您的账号在其他设备登录',
  221. showCancel: false
  222. });
  223. }
  224. /**
  225. * 网络状态变化
  226. */
  227. onNetStateChange(event) {
  228. console.log('🌐 网络状态:', event.data.state);
  229. }
  230. /**
  231. * 登录
  232. */
  233. async login(userID, userSig) {
  234. try {
  235. console.log('📱 开始登录 TIM, userID:', userID);
  236. const res = await this.tim.login({
  237. userID: String(userID),
  238. userSig: userSig
  239. });
  240. console.log('✅ TIM 登录成功');
  241. this.userId = userID;
  242. return res;
  243. } catch (error) {
  244. console.error('❌ TIM 登录失败:', error);
  245. throw error;
  246. }
  247. }
  248. /**
  249. * 登出
  250. */
  251. async logout() {
  252. try {
  253. await this.tim.logout();
  254. console.log('✅ TIM 登出成功');
  255. this.isLogin = false;
  256. this.userId = null;
  257. } catch (error) {
  258. console.error('❌ TIM 登出失败:', error);
  259. }
  260. }
  261. /**
  262. * 发送文本消息
  263. */
  264. async sendTextMessage(toUserId, text) {
  265. try {
  266. // 验证参数
  267. if (!toUserId || toUserId === 'undefined' || toUserId === 'null') {
  268. console.error('❌ 接收者ID无效:', toUserId);
  269. throw new Error('接收者ID无效: ' + toUserId);
  270. }
  271. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  272. console.error('❌ 发送者ID无效:', this.userId);
  273. throw new Error('发送者ID未登录或无效');
  274. }
  275. const toUserIdStr = String(toUserId);
  276. console.log('📤 准备发送消息:');
  277. console.log(' - 发送者ID:', this.userId, '(类型:', typeof this.userId, ')');
  278. console.log(' - 接收者ID:', toUserIdStr, '(类型:', typeof toUserIdStr, ')');
  279. console.log(' - 消息内容:', text);
  280. // 创建文本消息
  281. const message = this.tim.createTextMessage({
  282. to: toUserIdStr,
  283. conversationType: TIM.TYPES.CONV_C2C, // 单聊
  284. payload: {
  285. text: text
  286. }
  287. });
  288. console.log('📤 消息已创建,准备发送...');
  289. // 发送消息
  290. const res = await this.tim.sendMessage(message);
  291. console.log('✅ 消息发送成功:', res.data.message);
  292. return res.data.message;
  293. } catch (error) {
  294. console.error('❌ 消息发送失败:', error);
  295. console.error(' - 错误详情:', error.message || error);
  296. console.error(' - 错误代码:', error.code || 'N/A');
  297. throw error;
  298. }
  299. }
  300. /**
  301. * 发送图片消息
  302. */
  303. async sendImageMessage(toUserId, filePath) {
  304. try {
  305. const message = this.tim.createImageMessage({
  306. to: String(toUserId),
  307. conversationType: TIM.TYPES.CONV_C2C,
  308. payload: {
  309. file: filePath
  310. },
  311. onProgress: (percent) => {
  312. console.log('📊 上传进度:', percent);
  313. }
  314. });
  315. const res = await this.tim.sendMessage(message);
  316. console.log('✅ 图片发送成功');
  317. return res.data.message;
  318. } catch (error) {
  319. console.error('❌ 图片发送失败:', error);
  320. throw error;
  321. }
  322. }
  323. /**
  324. * 发送语音消息(通过自定义消息携带MinIO URL)
  325. * @param {String} toUserId 接收者ID
  326. * @param {String} voiceUrl MinIO语音文件URL
  327. * @param {Number} duration 语音时长(秒)
  328. * @param {Number} fileSize 文件大小(字节)
  329. */
  330. async sendVoiceMessage(toUserId, voiceUrl, duration, fileSize) {
  331. try {
  332. console.log('🎤 准备发送语音消息:');
  333. console.log(' - 接收者ID:', toUserId);
  334. console.log(' - 语音URL:', voiceUrl);
  335. console.log(' - 时长:', duration, '秒');
  336. console.log(' - 文件大小:', fileSize, '字节');
  337. // 使用自定义消息发送语音信息
  338. const message = this.tim.createCustomMessage({
  339. to: String(toUserId),
  340. conversationType: TIM.TYPES.CONV_C2C,
  341. payload: {
  342. data: JSON.stringify({
  343. type: 'voice',
  344. url: voiceUrl,
  345. duration: duration,
  346. size: fileSize
  347. }),
  348. description: '[语音]',
  349. extension: voiceUrl
  350. }
  351. });
  352. const res = await this.tim.sendMessage(message);
  353. console.log('✅ 语音发送成功');
  354. return res.data.message;
  355. } catch (error) {
  356. console.error('❌ 语音发送失败:', error);
  357. throw error;
  358. }
  359. }
  360. /**
  361. * 获取会话列表
  362. */
  363. async getConversationList() {
  364. try {
  365. const res = await this.tim.getConversationList();
  366. console.log('📋 会话列表:', res.data.conversationList.length, '个');
  367. return res.data.conversationList;
  368. } catch (error) {
  369. console.error('❌ 获取会话列表失败:', error);
  370. throw error;
  371. }
  372. }
  373. /**
  374. * 获取聊天记录
  375. */
  376. async getMessageList(conversationID, count = 15) {
  377. try {
  378. const res = await this.tim.getMessageList({
  379. conversationID: conversationID,
  380. count: count
  381. });
  382. console.log('💬 聊天记录:', res.data.messageList.length, '条');
  383. return res.data.messageList;
  384. } catch (error) {
  385. console.error('❌ 获取聊天记录失败:', error);
  386. throw error;
  387. }
  388. }
  389. /**
  390. * 将消息设为已读
  391. */
  392. async setMessageRead(conversationID) {
  393. try {
  394. await this.tim.setMessageRead({ conversationID });
  395. console.log('✅ 消息已读');
  396. } catch (error) {
  397. console.error('❌ 设置已读失败:', error);
  398. }
  399. }
  400. /**
  401. * 撤回消息
  402. */
  403. async revokeMessage(message) {
  404. try {
  405. await this.tim.revokeMessage(message);
  406. console.log('✅ 消息已撤回');
  407. } catch (error) {
  408. console.error('❌ 撤回失败:', error);
  409. throw error;
  410. }
  411. }
  412. /**
  413. * 监听消息
  414. */
  415. onMessage(callback) {
  416. this.messageCallbacks.push(callback);
  417. }
  418. /**
  419. * 移除监听
  420. */
  421. offMessage(callback) {
  422. const index = this.messageCallbacks.indexOf(callback);
  423. if (index > -1) {
  424. this.messageCallbacks.splice(index, 1);
  425. }
  426. }
  427. }
  428. // 导出单例
  429. const timManager = new TIMManager();
  430. export default timManager;