import { TypeSaveMsg, AccInfoTypes } from '../types/types' import commonData from '../store/data' import CONST_MSG_TYPE from '../const/CONST_MSG_TYPE' import hookRequest from '../api/hookRequest' import envConfig from '../config/envConfig' import { cdnDownloadImg3, delay } from '../utils/index' import serverRequest from '../api/scrm/serverRequest' const formatAndSaveMsg = async (msgData): Promise => { try { const _isBein = commonData.get('isBein') // 判断消息是不是自己发送的 const _accInfo: AccInfoTypes = commonData.get('accInfo') const selfwxid: string = commonData.get('selfwxid') let _content = msgData.msgtype == 0 ? msgData.content : '[' + CONST_MSG_TYPE[msgData.msgtype] + ']' // 语音消息处理(语音转文字) if (msgData.msgtype == 13) { // 语音转文字重试机制 let resData: { text: string } | null = null for (let i = 0; i < 3; i++) { await delay(2000) try { resData = await hookRequest.fetchVoiceToText(msgData.hook_wx_msg_id) if (resData && resData.text) break } catch (error) { console.log(`语音转文字第${i + 1}次失败`) } } _content = resData && resData.text ? `[语音] ${resData.text}` : _content } // 图片消息处理(将图片信息保存,供后续下载使用) let _contentImageInfo = '' if (msgData.msgtype == 9 || msgData.msgtype == 10) { _contentImageInfo = JSON.stringify(msgData.content) } const _data: TypeSaveMsg = { contentType: msgData.msgtype, content: _content, publishTime: msgData.send_time, publisher: msgData.sender_name, publisherId: msgData.sender, wxMsgId: msgData.msg_id, hookWxMsgId: msgData.hook_wx_msg_id, wxRoomId: msgData.room_conversation_id, type: _isBein ? 'bein' : 'normal', // 是否坐班时间 // normal bein submitWxId: selfwxid, submitWxName: _accInfo.nick_name, rereceiverName: _accInfo.nick_name, rereceiver: msgData.rereceiver, contentAtList: msgData.at_list && msgData.at_list.length ? JSON.stringify(msgData.at_list) : '', contentImageInfo: _contentImageInfo // 图片信息 } serverRequest.saveMsg(_data).then((res) => { if (res) { const { contentImageInfo, contentType } = res if ((contentType == 9 || contentType == 10) && contentImageInfo) updateImageMsg(res) } }) } catch (error) { console.error('ERROR: 提交消息失败') } } const updateImageMsg = async (msgData): Promise => { const imgData = JSON.parse(msgData.contentImageInfo) // 下载图片 const img_path = await cdnDownloadImg3(imgData) await delay(1000) // 上传图片至服务器 const ossPath = await serverRequest.uploadImg(img_path) if (ossPath) { const imgUrl = envConfig.urlENV.OSS_BASE + ossPath // 更新消息 serverRequest.updateMsg({ id: msgData.id, wxMsgId: msgData.wxMsgId, content: imgUrl }) } } export default { formatAndSaveMsg }