tim-manager.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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. /**
  181. * 被踢下线
  182. */
  183. onKickedOut(event) {
  184. console.log('❌ 被踢下线:', event.data.type);
  185. uni.showModal({
  186. title: '下线通知',
  187. content: '您的账号在其他设备登录',
  188. showCancel: false
  189. });
  190. }
  191. /**
  192. * 网络状态变化
  193. */
  194. onNetStateChange(event) {
  195. console.log('🌐 网络状态:', event.data.state);
  196. }
  197. /**
  198. * 登录
  199. */
  200. async login(userID, userSig) {
  201. try {
  202. console.log('📱 开始登录 TIM, userID:', userID);
  203. const res = await this.tim.login({
  204. userID: String(userID),
  205. userSig: userSig
  206. });
  207. console.log('✅ TIM 登录成功');
  208. this.userId = userID;
  209. return res;
  210. } catch (error) {
  211. console.error('❌ TIM 登录失败:', error);
  212. throw error;
  213. }
  214. }
  215. /**
  216. * 登出
  217. */
  218. async logout() {
  219. try {
  220. await this.tim.logout();
  221. console.log('✅ TIM 登出成功');
  222. this.isLogin = false;
  223. this.userId = null;
  224. } catch (error) {
  225. console.error('❌ TIM 登出失败:', error);
  226. }
  227. }
  228. /**
  229. * 发送文本消息
  230. */
  231. async sendTextMessage(toUserId, text) {
  232. try {
  233. // 验证参数
  234. if (!toUserId || toUserId === 'undefined' || toUserId === 'null') {
  235. console.error('❌ 接收者ID无效:', toUserId);
  236. throw new Error('接收者ID无效: ' + toUserId);
  237. }
  238. if (!this.userId || this.userId === 'undefined' || this.userId === 'null') {
  239. console.error('❌ 发送者ID无效:', this.userId);
  240. throw new Error('发送者ID未登录或无效');
  241. }
  242. const toUserIdStr = String(toUserId);
  243. console.log('📤 准备发送消息:');
  244. console.log(' - 发送者ID:', this.userId, '(类型:', typeof this.userId, ')');
  245. console.log(' - 接收者ID:', toUserIdStr, '(类型:', typeof toUserIdStr, ')');
  246. console.log(' - 消息内容:', text);
  247. // 创建文本消息
  248. const message = this.tim.createTextMessage({
  249. to: toUserIdStr,
  250. conversationType: TIM.TYPES.CONV_C2C, // 单聊
  251. payload: {
  252. text: text
  253. }
  254. });
  255. console.log('📤 消息已创建,准备发送...');
  256. // 发送消息
  257. const res = await this.tim.sendMessage(message);
  258. console.log('✅ 消息发送成功:', res.data.message);
  259. return res.data.message;
  260. } catch (error) {
  261. console.error('❌ 消息发送失败:', error);
  262. console.error(' - 错误详情:', error.message || error);
  263. console.error(' - 错误代码:', error.code || 'N/A');
  264. throw error;
  265. }
  266. }
  267. /**
  268. * 发送图片消息
  269. */
  270. async sendImageMessage(toUserId, filePath) {
  271. try {
  272. const message = this.tim.createImageMessage({
  273. to: String(toUserId),
  274. conversationType: TIM.TYPES.CONV_C2C,
  275. payload: {
  276. file: filePath
  277. },
  278. onProgress: (percent) => {
  279. console.log('📊 上传进度:', percent);
  280. }
  281. });
  282. const res = await this.tim.sendMessage(message);
  283. console.log('✅ 图片发送成功');
  284. return res.data.message;
  285. } catch (error) {
  286. console.error('❌ 图片发送失败:', error);
  287. throw error;
  288. }
  289. }
  290. /**
  291. * 发送语音消息(通过自定义消息携带MinIO URL)
  292. * @param {String} toUserId 接收者ID
  293. * @param {String} voiceUrl MinIO语音文件URL
  294. * @param {Number} duration 语音时长(秒)
  295. * @param {Number} fileSize 文件大小(字节)
  296. */
  297. async sendVoiceMessage(toUserId, voiceUrl, duration, fileSize) {
  298. try {
  299. console.log('🎤 准备发送语音消息:');
  300. console.log(' - 接收者ID:', toUserId);
  301. console.log(' - 语音URL:', voiceUrl);
  302. console.log(' - 时长:', duration, '秒');
  303. console.log(' - 文件大小:', fileSize, '字节');
  304. // 使用自定义消息发送语音信息
  305. const message = this.tim.createCustomMessage({
  306. to: String(toUserId),
  307. conversationType: TIM.TYPES.CONV_C2C,
  308. payload: {
  309. data: JSON.stringify({
  310. type: 'voice',
  311. url: voiceUrl,
  312. duration: duration,
  313. size: fileSize
  314. }),
  315. description: '[语音]',
  316. extension: voiceUrl
  317. }
  318. });
  319. const res = await this.tim.sendMessage(message);
  320. console.log('✅ 语音发送成功');
  321. return res.data.message;
  322. } catch (error) {
  323. console.error('❌ 语音发送失败:', error);
  324. throw error;
  325. }
  326. }
  327. /**
  328. * 获取会话列表
  329. */
  330. async getConversationList() {
  331. try {
  332. const res = await this.tim.getConversationList();
  333. console.log('📋 会话列表:', res.data.conversationList.length, '个');
  334. return res.data.conversationList;
  335. } catch (error) {
  336. console.error('❌ 获取会话列表失败:', error);
  337. throw error;
  338. }
  339. }
  340. /**
  341. * 获取聊天记录
  342. */
  343. async getMessageList(conversationID, count = 15) {
  344. try {
  345. const res = await this.tim.getMessageList({
  346. conversationID: conversationID,
  347. count: count
  348. });
  349. console.log('💬 聊天记录:', res.data.messageList.length, '条');
  350. return res.data.messageList;
  351. } catch (error) {
  352. console.error('❌ 获取聊天记录失败:', error);
  353. throw error;
  354. }
  355. }
  356. /**
  357. * 将消息设为已读
  358. */
  359. async setMessageRead(conversationID) {
  360. try {
  361. await this.tim.setMessageRead({ conversationID });
  362. console.log('✅ 消息已读');
  363. } catch (error) {
  364. console.error('❌ 设置已读失败:', error);
  365. }
  366. }
  367. /**
  368. * 撤回消息
  369. */
  370. async revokeMessage(message) {
  371. try {
  372. await this.tim.revokeMessage(message);
  373. console.log('✅ 消息已撤回');
  374. } catch (error) {
  375. console.error('❌ 撤回失败:', error);
  376. throw error;
  377. }
  378. }
  379. /**
  380. * 监听消息
  381. */
  382. onMessage(callback) {
  383. this.messageCallbacks.push(callback);
  384. }
  385. /**
  386. * 移除监听
  387. */
  388. offMessage(callback) {
  389. const index = this.messageCallbacks.indexOf(callback);
  390. if (index > -1) {
  391. this.messageCallbacks.splice(index, 1);
  392. }
  393. }
  394. }
  395. // 导出单例
  396. const timManager = new TIMManager();
  397. export default timManager;