Corrigido problema ao renderizar VCards

Resolvido problema ao renderizar VCards.

Não consegui realizar a renderização de Multi_VCards mas deixei comentado a rotina quando for resolvido o problema de retornar body vazio ao enviar ou receber Multi_VCards
This commit is contained in:
Danilo Alves
2022-01-07 16:19:58 -03:00
parent d6efb23136
commit fec4f82957
9 changed files with 285 additions and 39 deletions

View File

@@ -12,12 +12,18 @@ import CheckContactNumber from "../services/WbotServices/CheckNumber"
import CheckIsValidContact from "../services/WbotServices/CheckIsValidContact";
import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl";
import AppError from "../errors/AppError";
import GetContactService from "../services/ContactServices/GetContactService";
type IndexQuery = {
searchParam: string;
pageNumber: string;
};
type IndexGetContactQuery = {
name: string;
number: string;
};
interface ExtraInfo {
name: string;
value: string;
@@ -40,6 +46,17 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
return res.json({ contacts, count, hasMore });
};
export const getContact = async (req: Request, res: Response): Promise<Response> => {
const { name, number } = req.body as IndexGetContactQuery;
const contact = await GetContactService({
name,
number
});
return res.status(200).json(contact);
};
export const store = async (req: Request, res: Response): Promise<Response> => {
const newContact: ContactData = req.body;
newContact.number = newContact.number.replace("-", "").replace(" ", "");

View File

@@ -18,6 +18,8 @@ contactRoutes.get("/contacts/:contactId", isAuth, ContactController.show);
contactRoutes.post("/contacts", isAuth, ContactController.store);
contactRoutes.post("/contact", isAuth, ContactController.getContact);
contactRoutes.put("/contacts/:contactId", isAuth, ContactController.update);
contactRoutes.delete("/contacts/:contactId", isAuth, ContactController.remove);

View File

@@ -0,0 +1,29 @@
import AppError from "../../errors/AppError";
import Contact from "../../models/Contact";
interface ExtraInfo {
name: string;
value: string;
}
interface Request {
name: string;
number: string;
email?: string;
profilePicUrl?: string;
extraInfo?: ExtraInfo[];
}
const GetContactService = async ({ name, number }: Request): Promise<Contact> => {
const numberExists = await Contact.findOne({
where: { number }
});
if (!numberExists) {
throw new AppError("CONTACT_NOT_FIND");
}
return numberExists;
};
export default GetContactService;

View File

@@ -22,6 +22,8 @@ import FindOrCreateTicketService from "../TicketServices/FindOrCreateTicketServi
import ShowWhatsAppService from "../WhatsappService/ShowWhatsAppService";
import { debounce } from "../../helpers/Debounce";
import UpdateTicketService from "../TicketServices/UpdateTicketService";
import CreateContactService from "../ContactServices/CreateContactService";
import GetContactService from "../ContactServices/GetContactService";
interface Session extends Client {
id?: number;
@@ -196,6 +198,7 @@ const isValidMsg = (msg: WbotMessage): boolean => {
msg.type === "image" ||
msg.type === "document" ||
msg.type === "vcard" ||
//msg.type === "multi_vcard" ||
msg.type === "sticker"
)
return true;
@@ -222,7 +225,9 @@ const handleMessage = async (
// media messages sent from me from cell phone, first comes with "hasMedia = false" and type = "image/ptt/etc"
// in this case, return and let this message be handled by "media_uploaded" event, when it will have "hasMedia = true"
if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard") return;
if (!msg.hasMedia && msg.type !== "chat" && msg.type !== "vcard"
//&& msg.type !== "multi_vcard"
) return;
msgContact = await wbot.getContactById(msg.to);
} else {
@@ -249,32 +254,93 @@ const handleMessage = async (
const contact = await verifyContact(msgContact);
if ( unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
if (unreadMessages === 0 && whatsapp.farewellMessage && whatsapp.farewellMessage === msg.body) return;
const ticket = await FindOrCreateTicketService(
contact,
wbot.id!,
unreadMessages,
groupContact
);
const ticket = await FindOrCreateTicketService(
contact,
wbot.id!,
unreadMessages,
groupContact
);
if (msg.hasMedia) {
await verifyMediaMessage(msg, ticket, contact);
} else {
await verifyMessage(msg, ticket, contact);
if (msg.hasMedia) {
await verifyMediaMessage(msg, ticket, contact);
} else {
await verifyMessage(msg, ticket, contact);
}
if (
!ticket.queue &&
!chat.isGroup &&
!msg.fromMe &&
!ticket.userId &&
whatsapp.queues.length >= 1
) {
await verifyQueue(wbot, msg, ticket, contact);
}
if (msg.type === "vcard") { try { const array = msg.body.split("\n"); const obj = []; let contact = ""; for (let index = 0; index < array.length; index++) { const v = array[index]; const values = v.split(":"); for (let ind = 0; ind < values.length; ind++) { if (values[ind].indexOf("+") !== -1) { obj.push({ number: values[ind] }); } if (values[ind].indexOf("FN") !== -1) { contact = values[ind + 1]; } } } for await (const ob of obj) { const cont = await CreateContactService({ name: contact, number: ob.number.replace(/\D/g, "") }); } } catch (error) { console.log(error); } }
/*if (msg.type === "multi_vcard") {
try {
const array = msg.vCards.toString().split("\n");
let name = "";
let number = "";
const obj = [];
const conts = [];
for (let index = 0; index < array.length; index++) {
const v = array[index];
const values = v.split(":");
for (let ind = 0; ind < values.length; ind++) {
if (values[ind].indexOf("+") !== -1) {
number = values[ind];
}
if (values[ind].indexOf("FN") !== -1) {
name = values[ind + 1];
}
if (name !== "" && number !== "") {
obj.push({
name,
number
});
name = "";
number = "";
}
}
}
// eslint-disable-next-line no-restricted-syntax
for await (const ob of obj) {
try {
const cont = await CreateContactService({
name: ob.name,
number: ob.number.replace(/\D/g, "")
});
conts.push({
id: cont.id,
name: cont.name,
number: cont.number
});
} catch (error) {
if (error.message === "ERR_DUPLICATED_CONTACT") {
const cont = await GetContactService({
name: ob.name,
number: ob.number.replace(/\D/g, ""),
email: ""
});
conts.push({
id: cont.id,
name: cont.name,
number: cont.number
});
}
}
}
msg.body = JSON.stringify(conts);
} catch (error) {
console.log(error);
}
if (
!ticket.queue &&
!chat.isGroup &&
!msg.fromMe &&
!ticket.userId &&
whatsapp.queues.length >= 1
) {
await verifyQueue(wbot, msg, ticket, contact);
}
}*/
} catch (err) {
Sentry.captureException(err);

View File

@@ -152,7 +152,11 @@ const CustomLink = ({ children, ...props }) => (
const MarkdownWrapper = ({ children }) => {
const boldRegex = /\*(.*?)\*/g;
const tildaRegex = /~(.*?)~/g;
if(children.includes('BEGIN:VCARD'))
//children = "Diga olá ao seu novo contato clicando em *conversar*!";
children = null;
if (children && boldRegex.test(children)) {
children = children.replace(boldRegex, "**$1**");
}
@@ -179,8 +183,8 @@ const MarkdownWrapper = ({ children }) => {
}, []);
if (!children) return null;
return <Markdown options={options}>{children}</Markdown>;
};
export default MarkdownWrapper;
export default MarkdownWrapper;

View File

@@ -584,7 +584,7 @@ const MessageInput = ({ ticketStatus }) => {
: i18n.t("messagesInput.placeholderClosed")
}
multiline
rowsMax={5}
maxRows={5}
value={inputMessage}
onChange={handleChangeInput}
disabled={recording || loading || ticketStatus !== "open"}

View File

@@ -22,6 +22,7 @@ import {
} from "@material-ui/icons";
import MarkdownWrapper from "../MarkdownWrapper";
import VcardPreview from "../VcardPreview";
import ModalImageCors from "../ModalImageCors";
import MessageOptionsMenu from "../MessageOptionsMenu";
import whatsBackground from "../../assets/wa-background.png";
@@ -413,18 +414,52 @@ const MessagesList = ({ ticketId, isGroup }) => {
};
const checkMessageMedia = (message) => {
if (message.mediaType === "image") {
if (message.mediaType === "vcard") {
//console.log("vcard")
//console.log(message)
let array = message.body.split("\n");
let obj = [];
let contact = "";
for (let index = 0; index < array.length; index++) {
const v = array[index];
let values = v.split(":");
for (let ind = 0; ind < values.length; ind++) {
if (values[ind].indexOf("+") !== -1) {
obj.push({ number: values[ind] });
}
if (values[ind].indexOf("FN") !== -1) {
contact = values[ind + 1];
}
}
}
return <VcardPreview contact={contact} numbers={obj[0].number} />
}
/*else if (message.mediaType === "multi_vcard") {
console.log("multi_vcard")
console.log(message)
if(message.body !== null && message.body !== "") {
let newBody = JSON.parse(message.body)
return (
<>
{
newBody.map(v => (
<VcardPreview contact={v.name} numbers={v.number} />
))
}
</>
)
} else return (<></>)
}*/
else if (message.mediaType === "image") {
return <ModalImageCors imageUrl={message.mediaUrl} />;
}
if (message.mediaType === "audio") {
} else if (message.mediaType === "audio") {
return (
<audio controls>
<source src={message.mediaUrl} type="audio/ogg"></source>
</audio>
);
}
if (message.mediaType === "video") {
} else if (message.mediaType === "video") {
return (
<video
className={classes.messageMedia}
@@ -569,7 +604,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
{message.contact?.name}
</span>
)}
{message.mediaUrl && checkMessageMedia(message)}
{(message.mediaUrl || message.mediaType === "vcard"
//|| message.mediaType === "multi_vcard"
) && checkMessageMedia(message)}
<div className={classes.textContentItem}>
{message.quotedMsg && renderQuotedMessage(message)}
<MarkdownWrapper>{message.body}</MarkdownWrapper>
@@ -596,7 +633,9 @@ const MessagesList = ({ ticketId, isGroup }) => {
>
<ExpandMore />
</IconButton>
{message.mediaUrl && checkMessageMedia(message)}
{(message.mediaUrl || message.mediaType === "vcard"
//|| message.mediaType === "multi_vcard"
) && checkMessageMedia(message)}
<div
className={clsx(classes.textContentItem, {
[classes.textContentItemDeleted]: message.isDeleted,
@@ -651,4 +690,4 @@ const MessagesList = ({ ticketId, isGroup }) => {
);
};
export default MessagesList;
export default MessagesList;

View File

@@ -190,7 +190,7 @@ const NotificationsPopOver = () => {
<>
<IconButton
onClick={handleClick}
buttonRef={anchorEl}
ref={anchorEl}
aria-label="Open Notifications"
color="inherit"
>
@@ -231,4 +231,4 @@ const NotificationsPopOver = () => {
);
};
export default NotificationsPopOver;
export default NotificationsPopOver;

View File

@@ -0,0 +1,89 @@
import React, { useEffect, useState, useContext } from 'react';
import { useHistory } from "react-router-dom";
import toastError from "../../errors/toastError";
import api from "../../services/api";
import Avatar from "@material-ui/core/Avatar";
import Typography from "@material-ui/core/Typography";
import Grid from "@material-ui/core/Grid";
import { AuthContext } from "../../context/Auth/AuthContext";
import { Button, Divider, } from "@material-ui/core";
const VcardPreview = ({ contact, numbers }) => {
const history = useHistory();
const { user } = useContext(AuthContext);
const [selectedContact, setContact] = useState({
name: "",
number: 0,
profilePicUrl: ""
});
useEffect(() => {
const delayDebounceFn = setTimeout(() => {
const fetchContacts = async() => {
try {
let contactObj = {
name: contact,
number: numbers.replace(/\D/g, ""),
email: ""
}
const { data } = await api.post("/contact", contactObj);
setContact(data)
} catch (err) {
console.log(err)
toastError(err);
}
};
fetchContacts();
}, 500);
return () => clearTimeout(delayDebounceFn);
}, [contact, numbers]);
const handleNewChat = async() => {
try {
const { data: ticket } = await api.post("/tickets", {
contactId: selectedContact.id,
userId: user.id,
status: "open",
});
history.push(`/tickets/${ticket.id}`);
} catch (err) {
toastError(err);
}
}
return (
<>
<div style={{
minWidth: "250px",
}}>
<Grid container spacing={1}>
<Grid item xs={2}>
<Avatar src={selectedContact.profilePicUrl} />
</Grid>
<Grid item xs={9}>
<Typography style={{ marginTop: "12px", marginLeft: "10px" }} variant="subtitle1" color="primary" gutterBottom>
{selectedContact.name}
</Typography>
</Grid>
<Grid item xs={12}>
<Divider />
<Button
fullWidth
color="primary"
onClick={handleNewChat}
disabled={!selectedContact.number}
>Conversar</Button>
</Grid>
</Grid>
</div>
</>
);
};
export default VcardPreview;