migrated receive message logic to typescript

This commit is contained in:
canove
2020-09-22 09:15:18 -03:00
parent 391cd5495c
commit 48dbf7e859
14 changed files with 423 additions and 403 deletions

View File

@@ -7,7 +7,8 @@ import ShowContactService from "../services/ContactServices/ShowContactService";
import UpdateContactService from "../services/ContactServices/UpdateContactService";
import DeleteContactService from "../services/ContactServices/DeleteContactService";
// const { getWbot } = require("../libs/wbot");
import CheckIsValidContact from "../services/WbotServices/CheckIsValidContact";
import GetProfilePicUrl from "../services/WbotServices/GetProfilePicUrl";
type IndexQuery = {
searchParam: string;
@@ -37,54 +38,17 @@ interface ContactData {
}
export const store = async (req: Request, res: Response): Promise<Response> => {
const { name, number, email, extraInfo }: ContactData = req.body;
const newContact: ContactData = req.body;
await CheckIsValidContact(newContact.number);
const profilePicUrl = await GetProfilePicUrl(newContact.number);
const contact = await CreateContactService({
name,
number,
email,
extraInfo
...newContact,
profilePicUrl
});
// const defaultWhatsapp = await Whatsapp.findOne({
// where: { default: true }
// });
// if (!defaultWhatsapp) {
// return res
// .status(404)
// .json({ error: "No default WhatsApp found. Check Connection page." });
// }
// const wbot = getWbot(defaultWhatsapp);
// try {
// const isValidNumber = await wbot.isRegisteredUser(
// `${newContact.number}@c.us`
// );
// if (!isValidNumber) {
// return res
// .status(400)
// .json({ error: "The suplied number is not a valid Whatsapp number" });
// }
// } catch (err) {
// console.log(err);
// return res.status(500).json({
// error: "Could not check whatsapp contact. Check connection page."
// });
// }
// const profilePicUrl = await wbot.getProfilePicUrl(
// `${newContact.number}@c.us`
// );
// const contact = await Contact.create(
// { ...newContact, profilePicUrl },
// {
// include: "extraInfo"
// }
// );
const io = getIO();
io.emit("contact", {
action: "create",

View File

@@ -1,8 +1,15 @@
import { Request, Response } from "express";
// import { getIO } from "../libs/socket";
import { Message as WbotMessage } from "whatsapp-web.js";
import SetTicketMessagesAsRead from "../helpers/SetTicketMessagesAsRead";
import { getIO } from "../libs/socket";
import CreateMessageService from "../services/MessageServices/CreateMessageService";
import ListMessagesService from "../services/MessageServices/ListMessagesService";
import ShowTicketService from "../services/TicketServices/ShowTicketService";
import SendWhatsAppMedia from "../services/WbotServices/SendWhatsAppMedia";
import SendWhatsAppMessage from "../services/WbotServices/SendWhatsAppMessage";
// import Sequelize from "sequelize";
// import { MessageMedia } from "whatsapp-web.js";
@@ -14,39 +21,17 @@ import ListMessagesService from "../services/MessageServices/ListMessagesService
// import Ticket from "../models/Ticket";
// import { getWbot } from "../libs/wbot";
// const setMessagesAsRead = async ticket => {
// const io = getIO();
// const wbot = getWbot(ticket.whatsappId);
// await Message.update(
// { read: true },
// {
// where: {
// ticketId: ticket.id,
// read: false
// }
// }
// );
// try {
// await wbot.sendSeen(`${ticket.contact.number}@c.us`);
// } catch (err) {
// console.log(
// "Could not mark messages as read. Maybe whatsapp session disconnected?"
// );
// }
// io.to("notification").emit("ticket", {
// action: "updateUnread",
// ticketId: ticket.id
// });
// };
type IndexQuery = {
searchParam: string;
pageNumber: string;
};
type MessageData = {
body: string;
fromMe: boolean;
read: boolean;
};
export const index = async (req: Request, res: Response): Promise<Response> => {
const { ticketId } = req.params;
const { searchParam, pageNumber } = req.query as IndexQuery;
@@ -57,134 +42,49 @@ export const index = async (req: Request, res: Response): Promise<Response> => {
ticketId
});
// const ticketMessages = await ticket.getMessages({
// where: whereCondition,
// limit,
// offset,
// order: [["createdAt", "DESC"]]
// });
await SetTicketMessagesAsRead(ticket);
// const count = await ticket.countMessages();
// const serializedMessages = ticketMessages.map(message => {
// return {
// ...message.dataValues,
// mediaUrl: `${
// message.mediaUrl
// ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// : ""
// }`
// };
// });
// const hasMore = count > offset + ticketMessages.length;
// return res.json({
// messages: serializedMessages.reverse(),
// ticket,
// count,
// hasMore
// });
return res.json({ count, messages, ticket, hasMore });
};
export const store = async (req: Request, res: Response): Promise<Response> => {
// const io = getIO();
const { ticketId } = req.params;
const messageData = req.body;
const { body, fromMe, read }: MessageData = req.body;
const media = req.file;
const message = await CreateMessageService({ messageData, ticketId });
const ticket = await ShowTicketService(ticketId);
// const media = req.file;
// let sentMessage;
let sentMessage: WbotMessage;
// const ticket = await Ticket.findByPk(ticketId, {
// include: [
// {
// model: Contact,
// as: "contact",
// attributes: ["number", "name", "profilePicUrl"]
// }
// ]
// });
if (media) {
sentMessage = await SendWhatsAppMedia({ media, ticket });
} else {
sentMessage = await SendWhatsAppMessage({ body, ticket });
}
// if (!ticket) {
// return res.status(404).json({ error: "No ticket found with this ID" });
// }
const newMessage = {
id: sentMessage.id.id,
body,
fromMe,
read,
mediaType: sentMessage.type,
mediaUrl: media?.filename
};
// if (!ticket.whatsappId) {
// const defaultWhatsapp = await Whatsapp.findOne({
// where: { default: true }
// });
const message = await CreateMessageService({
messageData: newMessage,
ticketId: ticket.id
});
// if (!defaultWhatsapp) {
// return res
// .status(404)
// .json({ error: "No default WhatsApp found. Check Connection page." });
// }
const io = getIO();
io.to(ticketId).to("notification").emit("appMessage", {
action: "create",
message,
ticket,
contact: ticket.contact
});
// await ticket.setWhatsapp(defaultWhatsapp);
// }
// const wbot = getWbot(ticket.whatsappId);
// try {
// if (media) {
// const newMedia = MessageMedia.fromFilePath(req.file.path);
// message.mediaUrl = req.file.filename;
// if (newMedia.mimetype) {
// message.mediaType = newMedia.mimetype.split("/")[0];
// } else {
// message.mediaType = "other";
// }
// sentMessage = await wbot.sendMessage(
// `${ticket.contact.number}@c.us`,
// newMedia
// );
// await ticket.update({ lastMessage: message.mediaUrl });
// } else {
// sentMessage = await wbot.sendMessage(
// `${ticket.contact.number}@c.us`,
// message.body
// );
// await ticket.update({ lastMessage: message.body });
// }
// } catch (err) {
// console.log(
// "Could not create whatsapp message. Is session details valid? "
// );
// }
// if (sentMessage) {
// message.id = sentMessage.id.id;
// const newMessage = await ticket.createMessage(message);
// const serialziedMessage = {
// ...newMessage.dataValues,
// mediaUrl: `${
// message.mediaUrl
// ? `${process.env.BACKEND_URL}:${process.env.PROXY_PORT}/public/${message.mediaUrl}`
// : ""
// }`
// };
// io.to(ticketId).to("notification").emit("appMessage", {
// action: "create",
// message: serialziedMessage,
// ticket,
// contact: ticket.contact
// });
// await setMessagesAsRead(ticket);
await SetTicketMessagesAsRead(ticket);
return res.status(200).json(message);
};
// return res
// .status(500)
// .json({ error: "Cannot sent whatsapp message. Check connection page." });
// };