perf(前端): wai 发消息

dev/supplier-email-drawer
Lei OT 9 months ago
parent 2d2eee7704
commit b802532c50

@ -1,26 +1,24 @@
import { fetchJSON, postForm, postJSON } from '@/utils/request';
import { API_HOST, WAI_HOST } from '@/config';
import { usingStorage } from '@/utils/usingStorage';
import { fetchJSON, postForm, postJSON } from '@/utils/request'
import { API_HOST, WAI_HOST } from '@/config'
import { usingStorage } from '@/utils/usingStorage'
const WAI_SERVER_KEY = 'G-STR:WAI_SERVER'
export const postSendMsg = async (body) => {
const { waiServer } = usingStorage(WAI_SERVER_KEY)
const { attaList=[], atta, content, ...bodyData } = body;
const formData = new FormData();
const { attaList = [], atta, content, ...bodyData } = body
const formData = new FormData()
Object.keys(bodyData).forEach(function (key) {
formData.append(key, bodyData[key]);
});
formData.append(key, bodyData[key])
})
attaList.forEach(function (item) {
formData.append('attachment', item);
});
const { result } = await postJSON(`${waiServer}/messages/text`, body);
return result;
};
formData.append('attachment', item)
})
const { result } = await postJSON(`${waiServer}/messages/send`, body)
return result
}
export const fetchQRCode = (phone) => {
const { waiServer } = usingStorage(WAI_SERVER_KEY)
return fetchJSON(
`${waiServer}/channels/qrcode`,
{ phone })
return fetchJSON(`${waiServer}/channels/qrcode`, { phone })
}

@ -107,14 +107,20 @@ const InputComposer = ({ channel, currentActive }) => {
id: `${currentConversation.sn}.${uuid()}`,
msg_source: channel,
wabaName: channel === 'waba' ? WABAccountsMapped[fromIM]?.verifiedName : '',
externalId: currentConversation.sn || ''
};
// olog('sendMessage------------------', msgObjMerge)
const contentToSend = sentMsgTypeMapped[msgObjMerge.type].contentToSend(msgObjMerge);
// console.log('content to send-------------------------------------', contentToSend);
if (channel === 'wai') {
// const waObj = { from: fromIM.replace('+', ''), to: toIM.replace('+', ''), content: msgObj.text, };
await postSendMsg({...contentToSend, externalId: currentConversation.sn || ''});
try {
await postSendMsg({...contentToSend, });
} catch (error) {
appNotification.error({ message: error.message || '发送失败', placement: 'bottom', duration: 6, });
// appMessage.error(error.message || '');
return false;
}
} else if (channel === 'waba') {
websocket.sendMessage({ ...contentToSend, opi_sn: userId, coli_sn: currentConversation.coli_sn || '', conversationid: currentConversation.sn, });
}

@ -10,6 +10,9 @@ function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
* @deprecated 即将废弃
*/
exports.sendText = async ctx => {
const { from, to, msgcontent, content: _content, actionId } = ctx.request.body;
const content = _content || msgcontent.body || '';
@ -40,8 +43,48 @@ exports.sendText = async ctx => {
await createOutboundMessage({ ...toUpsert });
// return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
// });
//wsToSend.sendTextMessage(to, content, actionId);
waEmitter.emit('request.' + from + '.send.text', {to, content, externalId: actionId});
// wsToSend.sendTextMessage(to, content, actionId);
waEmitter.emit('request.' + from + '.send.text', { to, content, externalId: actionId });
return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
} catch (error) {
console.error('Error sending message:', error);
ctx.assert(null, 500, 'Failed to send message');
}
};
exports.send = async ctx => {
const { msgtype, from, to, msgcontent, content: _content, actionId } = ctx.request.body;
const content = _content || msgcontent.body || '';
if (!from || !content) {
ctx.assert(from, 400, 'From and message are required');
return;
}
const wsToSend = sessionStore.getSession(from);
// console.log('find wsToSend', wsToSend)
if (!wsToSend) {
ctx.assert(wsToSend, 400, '未登录WhatsApp, 请到个人资料页扫码登录'); // 404
return;
}
try {
// wsToSend.sendTextMessage(to, content, actionId).then(({ messageId }) => {
// const messageId = generateId();
const _data = ctx.request.body;
const defaultR = { direction: 'outbound' };
const r1 = pick(_data, ['actionId', 'msgtype', 'externalId']);
r1.id = actionId; // id not null
// r1.wamid = messageId;
r1.msg_status = 'ready';
r1.createTime = Date.now();
const record = objectMapper(_data, { from: 'from', to: 'to' }, false);
const byType = _data.msgtype === 'text' ? { text_body: _data.msgcontent.body, text_preview_url: _data.msgcontent.preview_url } : {};
const toUpsert = { ...defaultR, ...r1, ...record, ...byType, message_origin: JSON.stringify(_data) };
await createOutboundMessage({ ...toUpsert });
// return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
// });
// wsToSend.sendTextMessage(to, content, actionId);
// todo: build msgtype content to wa
waEmitter.emit('request.' + from + '.send.' + msgtype, { to, content, externalId: actionId });
return 'Message sent successfully'; // { wsToSend, ret: 'Message sent successfully' };
} catch (error) {
console.error('Error sending message:', error);

@ -7,7 +7,9 @@ module.exports = Router => {
prefix: `/messages`,
});
router.post('/:type', controller.sendText);
router
.post('/send', controller.send)
.post('/:type', controller.sendText);
return router;
};

@ -41,7 +41,7 @@ const webhookBodyBuilder = (messageData, messageType) => {
...messageData,
...(messageData.updateTime ? { [timeField[messageData.status]]: messageData.updateTime } : {}),
id: messageData.id && messageData.direction ? `${directionPrefix[messageData.direction]}${messageData.id}` : (messageData.id || generateId()),
wamid: messageData.id || null,
wamid: messageData.id || '',
// direction: directionField[messageType],
status: statusMapped?.[messageData.status] || messageData.status || '',
externalId: messageData?.externalId || '',

Loading…
Cancel
Save