You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
292 lines
12 KiB
JavaScript
292 lines
12 KiB
JavaScript
import React, { useState, useRef, useEffect } from 'react';
|
|
import { App, Input, Flex, Button, Image, } from 'antd';
|
|
// import { Input } from 'react-chat-elements';
|
|
import useAuthStore from '@/stores/AuthStore';
|
|
import useConversationStore from '@/stores/ConversationStore';
|
|
import {
|
|
SendOutlined,
|
|
MessageOutlined,
|
|
SmileOutlined,
|
|
PictureOutlined,
|
|
CommentOutlined,
|
|
UploadOutlined,
|
|
CloudUploadOutlined,
|
|
FolderAddOutlined,
|
|
FilePdfOutlined,
|
|
CloseCircleOutlined,
|
|
YoutubeOutlined,
|
|
AudioOutlined, PlayCircleOutlined, LoadingOutlined, CheckCircleOutlined, FileOutlined
|
|
} from '@ant-design/icons';
|
|
import { isEmpty, olog } from '@/utils/utils';
|
|
import { v4 as uuid } from 'uuid';
|
|
import { sentMsgTypeMapped } from '@/lib/msgUtils';
|
|
import InputTemplate from './Input/Template';
|
|
import InputEmoji from './Input/Emoji';
|
|
import InputMediaUpload from './Input/MediaUpload';
|
|
import { postUploadFileItem } from '@/actions/CommonActions';
|
|
import ExpireTimeClock from './ExpireTimeClock';
|
|
import dayjs from 'dayjs';
|
|
|
|
const aliOSSHost = `https://haina-sale-system.oss-cn-shenzhen.aliyuncs.com/WAMedia/`;
|
|
/**
|
|
* image
|
|
* ext: ani;bmp;gif;ico;jpe;jpeg;jpg;pcx;png;psd;tga;tif;tiff;wmf
|
|
*
|
|
* audio
|
|
* ext: aac;ac3;aif;aifc;aiff;au;cda;dts;fla;flac;it;m1a;m2a;m3u;m4a;mid;midi;mka;mod;mp2;mp3;mpa;ogg;ra;rmi;spc;rmi;snd;umx;voc;wav;wma;xm
|
|
*
|
|
* video
|
|
* ext: 3g2;3gp;3gp2;3gpp;amr;amv;asf;avi;bdmv;bik;d2v;divx;drc;dsa;dsm;dss;dsv;evo;f4v;flc;fli;flic;flv;hdmov;ifo;ivf;m1v;m2p;m2t;m2ts;m2v;m4b;m4p;m4v;mkv;mp2v;mp4;mp4v;mpe;mpeg;mpg;mpls;mpv2;mpv4;mov;mts;ogm;ogv;pss;pva;qt;ram;ratdvd;rm;rmm;rmvb;roq;rpm;smil;smk;swf;tp;tpr;ts;vob;vp6;webm;wm;wmp;wmv
|
|
*
|
|
*/
|
|
const fileTypesExt = {
|
|
sticker: ['webp'],
|
|
photo: ['jpeg', 'jpg', 'png'],
|
|
video: ['gif', 'mp4', '3gp'],
|
|
document: ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'csv'],
|
|
audio: ['aac', 'mp4', 'm4a', 'mp3', 'amr', 'ogg'],
|
|
};
|
|
|
|
const InputComposer = ({ mobile }) => {
|
|
const userId = useAuthStore((state) => state.loginUser.userId);
|
|
const websocket = useConversationStore((state) => state.websocket);
|
|
const websocketOpened = useConversationStore((state) => state.websocketOpened);
|
|
const currentConversation = useConversationStore((state) => state.currentConversation);
|
|
const [referenceMsg, setReferenceMsg] = useConversationStore((state) => [state.referenceMsg, state.setReferenceMsg]);
|
|
const [complexMsg, setComplexMsg] = useConversationStore((state) => [state.complexMsg, state.setComplexMsg]);
|
|
const sentOrReceivedNewMessage = useConversationStore((state) => state.sentOrReceivedNewMessage);
|
|
|
|
const talkabled = !isEmpty(currentConversation.sn) && websocketOpened;
|
|
const gt24h = currentConversation.last_received_time ? dayjs().diff(dayjs(currentConversation.last_received_time), 'hour') > 24 : true;
|
|
const textabled = talkabled && !gt24h;
|
|
|
|
const textInputRef = useRef(null);
|
|
const [textContent, setTextContent] = useState('');
|
|
|
|
const invokeSendMessage = (msgObj) => {
|
|
const msgObjMerge = {
|
|
sender: 'me',
|
|
senderName: 'me',
|
|
to: currentConversation.whatsapp_phone_number,
|
|
date: new Date(),
|
|
status: 'waiting',
|
|
...(referenceMsg.id ? { context: { message_id: referenceMsg.id }, message_origin: referenceMsg } : {}),
|
|
...msgObj,
|
|
id: `${currentConversation.sn}.${uuid()}`,
|
|
};
|
|
// olog('sendMessage------------------', msgObjMerge)
|
|
const contentToSend = sentMsgTypeMapped[msgObjMerge.type].contentToSend(msgObjMerge);
|
|
// console.log('content to send-------------------------------------', contentToSend);
|
|
websocket.sendMessage({ ...contentToSend, opi_sn: userId, coli_sn: currentConversation.coli_sn });
|
|
const contentToRender = sentMsgTypeMapped[msgObjMerge.type].contentToRender(msgObjMerge);
|
|
// console.log(contentToRender, 'contentToRender sendMessage------------------');
|
|
sentOrReceivedNewMessage(contentToRender.conversationid, contentToRender);
|
|
|
|
setTextContent('');
|
|
setReferenceMsg({});
|
|
setComplexMsg({});
|
|
};
|
|
|
|
/**
|
|
* 先推到消息记录上面, 再发送
|
|
*/
|
|
const invokeUploadFileMessage = (msgObj) => {
|
|
const msgObjMerge = {
|
|
sender: 'me',
|
|
senderName: 'me',
|
|
to: currentConversation.whatsapp_phone_number,
|
|
date: new Date(),
|
|
status: 'waiting',
|
|
...(referenceMsg.id ? { context: { message_id: referenceMsg.id }, message_origin: referenceMsg } : {}),
|
|
...msgObj,
|
|
id: `${currentConversation.sn}.${msgObj.id}`,
|
|
};
|
|
// olog('invoke upload', msgObjMerge)
|
|
const contentToRender = sentMsgTypeMapped[msgObjMerge.type].contentToRender(msgObjMerge);
|
|
// console.log(contentToRender, 'contentToRender sendMessage------------------');
|
|
sentOrReceivedNewMessage(contentToRender.conversationid, contentToRender);
|
|
};
|
|
|
|
const invokeSendUploadMessage = (msgObj) => {
|
|
const msgObjMerge = {
|
|
sender: 'me',
|
|
senderName: 'me',
|
|
to: currentConversation.whatsapp_phone_number,
|
|
date: new Date(),
|
|
status: 'waiting',
|
|
...(referenceMsg.id ? { context: { message_id: referenceMsg.id }, message_origin: referenceMsg } : {}),
|
|
...msgObj,
|
|
id: `${currentConversation.sn}.${msgObj.id}`,
|
|
};
|
|
const contentToSend = sentMsgTypeMapped[msgObjMerge.type].contentToSend(msgObjMerge);
|
|
// olog('invoke upload send +++ ', contentToSend)
|
|
websocket.sendMessage({ ...contentToSend, opi_sn: userId, coli_sn: currentConversation.coli_sn });
|
|
};
|
|
|
|
const { message } = App.useApp();
|
|
const [pastedUploading, setPastedUploading] = useState(false);
|
|
const readPasted = async (file, rename = false) => {
|
|
// 使用 FileReader 读取文件对象
|
|
const reader = new FileReader();
|
|
const suffix = file.name.slice(file.name.lastIndexOf('.') + 1);
|
|
const newName = `${uuid()}.${suffix}`; // rename ? `${uuid()}.${suffix}` : file.name;
|
|
const type = Object.keys(fileTypesExt).find((type) => fileTypesExt[type].includes(suffix));
|
|
const dataUri = aliOSSHost + newName;
|
|
const msgObj = {
|
|
type: type,
|
|
name: file.name,
|
|
uploadStatus: 'loading',
|
|
data: { dataUri: dataUri, link: dataUri, width: '100%', height: 150, loading: 0.01 },
|
|
id: uuid(),
|
|
};
|
|
// 读取完毕后获取结果
|
|
reader.onload = (event) => {
|
|
const previewSrc = event.target.result;
|
|
msgObj.data.uri = previewSrc;
|
|
};
|
|
file.newName = newName;
|
|
file.msgData = msgObj;
|
|
// 把文件对象作为一个 dataURL 读入
|
|
reader.readAsDataURL(file);
|
|
return file;
|
|
};
|
|
const handlePaste = async (event) => {
|
|
const items = (event.clipboardData || window.clipboardData).items;
|
|
let tmpfile = null;
|
|
if (!items || items.length === 0) {
|
|
// 当前浏览器不支持本地
|
|
message.warning('当前浏览器不支持本地');
|
|
return;
|
|
}
|
|
let isNotFile = true;
|
|
for (let i = 0; i < items.length; i++) {
|
|
// if (items[i].type.indexOf("image") !== -1) {
|
|
if (items[i].kind.indexOf('file') !== -1) {
|
|
isNotFile = false;
|
|
tmpfile = items[i].getAsFile();
|
|
break;
|
|
}
|
|
}
|
|
if (isNotFile) {
|
|
// 普通的粘贴
|
|
return;
|
|
}
|
|
if (!tmpfile) {
|
|
message.warning('没有读取到粘贴内容');
|
|
return;
|
|
}
|
|
const shouldRename = tmpfile.type.indexOf('image') !== -1;
|
|
const _tmpFile = await readPasted(tmpfile, shouldRename);
|
|
setComplexMsg(_tmpFile.msgData);
|
|
setPastedUploading(true);
|
|
const { file_url } = await postUploadFileItem(tmpfile, _tmpFile.newName);
|
|
setPastedUploading(false); // todo: 更新data uri
|
|
setComplexMsg({ ..._tmpFile.msgData, uploadStatus: file_url ? 'done' : 'error' });
|
|
return;
|
|
};
|
|
|
|
const focusInput = () => {
|
|
textInputRef.current.focus({ cursor: 'end', preventScroll: true });
|
|
window.dispatchEvent(new Event('resize'));
|
|
};
|
|
|
|
const addEmoji = (emoji) => {
|
|
setTextContent((prevValue) => {
|
|
return prevValue + emoji;
|
|
});
|
|
};
|
|
|
|
const handleSendText = () => {
|
|
if (textContent.trim() !== '' || !isEmpty(complexMsg)) {
|
|
const msgObj = {
|
|
type: 'text',
|
|
text: textContent,
|
|
...complexMsg,
|
|
};
|
|
invokeSendMessage(msgObj);
|
|
}
|
|
};
|
|
|
|
useEffect(() => {
|
|
focusInput();
|
|
return () => {};
|
|
}, [referenceMsg, complexMsg]);
|
|
|
|
return (
|
|
<div>
|
|
{referenceMsg.id && (
|
|
<Flex justify='space-between' className='reply-to bg-gray-100 p-1 rounded-none text-slate-500'>
|
|
<div className='flex flex-col referrer-msg border-l-3 border-y-0 border-r-0 border-slate-300 border-solid pl-2 pr-1 py-1'>
|
|
<span className=' text-primary pr-1 italic align-top'>{referenceMsg.senderName}</span>
|
|
{referenceMsg.type === 'photo' && <Image width={100} src={referenceMsg.data.uri} />}
|
|
<span className='px-1 whitespace-pre-wrap'>{referenceMsg.originText}</span>
|
|
</div>
|
|
<Button type='text' title='取消引用' className=' rounded-none text-slate-500' icon={<CloseCircleOutlined />} size={'middle'} onClick={() => setReferenceMsg({})} />
|
|
</Flex>
|
|
)}
|
|
{complexMsg.id && (
|
|
<Flex justify='space-between' className='reply-to bg-gray-100 p-1 rounded-none text-slate-500'>
|
|
<div className='pl-2 pr-1 py-1'>
|
|
{['photo', 'sticker'].includes(complexMsg.type) && complexMsg.data.uri ? (
|
|
<Image width={100} src={complexMsg.data.uri} />
|
|
) : (
|
|
<>
|
|
<FileOutlined className=' text-red-400' />
|
|
<span className='px-1'>{complexMsg.name}</span>
|
|
</>
|
|
)}
|
|
{complexMsg.uploadStatus === 'loading' && <LoadingOutlined className='px-1' />}
|
|
{/* {complexMsg.uploadStatus === 'done' && <CheckCircleOutlined className='px-1 text-primary' />} */}
|
|
{complexMsg.uploadStatus === 'error' && (
|
|
<>
|
|
<CloseCircleOutlined className='px-1 text-red-400' /> <span>添加失败</span>{' '}
|
|
</>
|
|
)}
|
|
</div>
|
|
<Button type='text' title='删除' className=' rounded-none text-slate-500' icon={<CloseCircleOutlined />} size={'middle'} onClick={() => setComplexMsg({})} />
|
|
</Flex>
|
|
)}
|
|
<Input.TextArea
|
|
onPaste={handlePaste}
|
|
ref={textInputRef}
|
|
size='large'
|
|
maxLength={2000}
|
|
showCount={textabled}
|
|
placeholder={gt24h ? 'This session has expired. Please send a template message to activate the session' : 'Enter 发送, Shift+Enter 换行\n支持复制粘贴 [截图/文件] 以备发送'}
|
|
rows={2}
|
|
disabled={!textabled}
|
|
value={textContent}
|
|
onChange={(e) => setTextContent(e.target.value)}
|
|
className='rounded-b-none emoji'
|
|
onPressEnter={(e) => {
|
|
if (!e.shiftKey) {
|
|
e.preventDefault();
|
|
handleSendText();
|
|
}
|
|
}}
|
|
autoSize={{ minRows: 2, maxRows: 6 }}
|
|
/>
|
|
<Flex justify={'space-between'} className=' bg-gray-200 p-1 rounded-b'>
|
|
<Flex gap={4} className='*:text-primary *:rounded-none'>
|
|
<InputTemplate key='templates' disabled={!talkabled} invokeSendMessage={invokeSendMessage} {...{ mobile }} />
|
|
<InputEmoji key='emoji' disabled={!textabled} inputEmoji={addEmoji} {...{ mobile }} />
|
|
<InputMediaUpload key={'addNewMedia'} disabled={!textabled} {...{ invokeUploadFileMessage, invokeSendUploadMessage }} />
|
|
{/* <Button type='text' className='' icon={<YoutubeOutlined />} size={'middle'} />
|
|
<Button type='text' className='' icon={<AudioOutlined />} size={'middle'} />
|
|
<Button type='text' className='' icon={<FolderAddOutlined />} size={'middle'} />
|
|
<Button type='text' className='' icon={<CloudUploadOutlined />} size={'middle'} />
|
|
<Button type='text' className='' icon={<FilePdfOutlined />} size={'middle'} /> */}
|
|
</Flex>
|
|
<Flex gap={4} align={'center'}>
|
|
<ExpireTimeClock expireTime={currentConversation.conversation_expiretime} />
|
|
<Button key={'send-btn'} onClick={handleSendText} type='primary' size='middle' icon={<SendOutlined />} disabled={!textabled || pastedUploading}>
|
|
Send
|
|
</Button>
|
|
</Flex>
|
|
</Flex>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default InputComposer;
|