mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-18 11:49:19 +00:00
Migrate from moment to date-fns and some changes
This commit is contained in:
46
backend/src/controllers/auth.js
Normal file
46
backend/src/controllers/auth.js
Normal file
@@ -0,0 +1,46 @@
|
||||
const { validationResult } = require("express-validator");
|
||||
const bcrypt = require("bcryptjs");
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const User = require("../models/User");
|
||||
|
||||
exports.signup = async (req, res, next) => {
|
||||
const errors = validationResult(req);
|
||||
|
||||
if (!errors.isEmpty()) {
|
||||
return res.status(400).json({ error: "Validation failed" });
|
||||
}
|
||||
|
||||
const { name, password, email } = req.body;
|
||||
|
||||
const hashedPw = await bcrypt.hash(password, 12);
|
||||
const user = User.build({
|
||||
email: email,
|
||||
password: hashedPw,
|
||||
name: name,
|
||||
});
|
||||
const result = await user.save();
|
||||
res.status(201).json({ message: "User created!", userId: result.id });
|
||||
};
|
||||
|
||||
exports.login = async (req, res, next) => {
|
||||
const { email, password } = req.body;
|
||||
|
||||
const user = await User.findOne({ where: { email: email } });
|
||||
if (!user) {
|
||||
return res.status(400).json({ error: "No user found with this email" });
|
||||
}
|
||||
|
||||
const isEqual = await bcrypt.compare(password, user.password);
|
||||
if (!isEqual) {
|
||||
return res.status(401).json({ error: "Password does not match" });
|
||||
}
|
||||
|
||||
const token = jwt.sign({ email: user.email, userId: user.id }, "mysecret", {
|
||||
expiresIn: "24h",
|
||||
});
|
||||
|
||||
return res
|
||||
.status(200)
|
||||
.json({ token: token, username: user.name, userId: user.id });
|
||||
};
|
||||
67
backend/src/controllers/contact.js
Normal file
67
backend/src/controllers/contact.js
Normal file
@@ -0,0 +1,67 @@
|
||||
const Contact = require("../models/Contact");
|
||||
const Message = require("../models/Message");
|
||||
const Sequelize = require("sequelize");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot } = require("./wbot");
|
||||
|
||||
exports.getContacts = async (req, res) => {
|
||||
const { searchParam = "" } = req.query;
|
||||
|
||||
const lowerSerachParam = searchParam.toLowerCase();
|
||||
|
||||
const whereCondition = {
|
||||
name: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("name")),
|
||||
"LIKE",
|
||||
"%" + lowerSerachParam + "%"
|
||||
),
|
||||
};
|
||||
|
||||
//todo >> add contact number to search where condition
|
||||
|
||||
const contacts = await Contact.findAll({
|
||||
where: whereCondition,
|
||||
attributes: {
|
||||
include: [
|
||||
[
|
||||
Sequelize.literal(`(
|
||||
SELECT COUNT(*)
|
||||
FROM messages AS message
|
||||
WHERE
|
||||
message.contactId = contact.id
|
||||
AND
|
||||
message.read = 0
|
||||
|
||||
)`),
|
||||
"unreadMessages",
|
||||
],
|
||||
],
|
||||
},
|
||||
order: [["updatedAt", "DESC"]],
|
||||
});
|
||||
|
||||
return res.json(contacts);
|
||||
};
|
||||
|
||||
exports.createContact = async (req, res) => {
|
||||
const wbot = getWbot();
|
||||
const io = getIO();
|
||||
const { number, name } = req.body;
|
||||
|
||||
const result = await wbot.isRegisteredUser(`55${number}@c.us`);
|
||||
|
||||
if (!result) {
|
||||
return res
|
||||
.status(400)
|
||||
.json({ error: "The suplied number is not a valid Whatsapp number" });
|
||||
}
|
||||
const profilePicUrl = await wbot.getProfilePicUrl(`55${number}@c.us`);
|
||||
|
||||
const contact = await Contact.create({
|
||||
name,
|
||||
number: `55${number}`,
|
||||
profilePicUrl,
|
||||
});
|
||||
|
||||
res.status(200).json(contact);
|
||||
};
|
||||
126
backend/src/controllers/message.js
Normal file
126
backend/src/controllers/message.js
Normal file
@@ -0,0 +1,126 @@
|
||||
const fs = require("fs");
|
||||
const Message = require("../models/Message");
|
||||
const Contact = require("../models/Contact");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot } = require("./wbot");
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const { MessageMedia } = require("whatsapp-web.js");
|
||||
|
||||
const setMessagesAsRead = async contactId => {
|
||||
const io = getIO();
|
||||
await Message.update(
|
||||
{ read: true },
|
||||
{
|
||||
where: {
|
||||
contactId: contactId,
|
||||
read: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
io.to("notification").emit("contact", {
|
||||
action: "updateUnread",
|
||||
contactId: contactId,
|
||||
});
|
||||
};
|
||||
|
||||
exports.getContactMessages = async (req, res, next) => {
|
||||
const wbot = getWbot();
|
||||
const io = getIO();
|
||||
|
||||
const { contactId } = req.params;
|
||||
const { searchParam = "", pageNumber = 1 } = req.query;
|
||||
|
||||
const lowerSerachParam = searchParam.toLowerCase();
|
||||
|
||||
const whereCondition = {
|
||||
messageBody: Sequelize.where(
|
||||
Sequelize.fn("LOWER", Sequelize.col("messageBody")),
|
||||
"LIKE",
|
||||
"%" + lowerSerachParam + "%"
|
||||
),
|
||||
};
|
||||
|
||||
let limit = 20;
|
||||
let offset = limit * (pageNumber - 1);
|
||||
|
||||
const contact = await Contact.findByPk(contactId);
|
||||
if (!contact) {
|
||||
return res.status(400).json({ error: "No contact found with this ID" });
|
||||
}
|
||||
|
||||
await setMessagesAsRead(contactId);
|
||||
|
||||
const contactMessages = await contact.getMessages({
|
||||
where: whereCondition,
|
||||
limit,
|
||||
offset,
|
||||
order: [["createdAt", "DESC"]],
|
||||
});
|
||||
|
||||
const serializedMessages = contactMessages.map(message => {
|
||||
return {
|
||||
...message.dataValues,
|
||||
mediaUrl: `${
|
||||
message.mediaUrl
|
||||
? `http://${process.env.HOST}:${process.env.PORT}/public/${message.mediaUrl}`
|
||||
: ""
|
||||
}`,
|
||||
};
|
||||
});
|
||||
|
||||
return res.json({
|
||||
messages: serializedMessages.reverse(),
|
||||
contact: contact,
|
||||
});
|
||||
};
|
||||
|
||||
exports.postCreateContactMessage = async (req, res, next) => {
|
||||
const wbot = getWbot();
|
||||
const io = getIO();
|
||||
|
||||
const { contactId } = req.params;
|
||||
const message = req.body;
|
||||
const media = req.file;
|
||||
let sentMessage;
|
||||
|
||||
const contact = await Contact.findByPk(contactId);
|
||||
if (media) {
|
||||
const newMedia = MessageMedia.fromFilePath(req.file.path);
|
||||
message.mediaUrl = req.file.filename.replace(/\s/g, "");
|
||||
if (newMedia.mimetype) {
|
||||
message.mediaType = newMedia.mimetype.split("/")[0];
|
||||
} else {
|
||||
message.mediaType = "other";
|
||||
}
|
||||
|
||||
sentMessage = await wbot.sendMessage(`${contact.number}@c.us`, newMedia);
|
||||
} else {
|
||||
sentMessage = await wbot.sendMessage(
|
||||
`${contact.number}@c.us`,
|
||||
message.messageBody
|
||||
);
|
||||
}
|
||||
|
||||
message.id = sentMessage.id.id;
|
||||
|
||||
const newMessage = await contact.createMessage(message);
|
||||
|
||||
const serialziedMessage = {
|
||||
...newMessage.dataValues,
|
||||
mediaUrl: `${
|
||||
message.mediaUrl
|
||||
? `http://${process.env.HOST}:${process.env.PORT}/public/${message.mediaUrl}`
|
||||
: ""
|
||||
}`,
|
||||
};
|
||||
|
||||
io.to(contactId).emit("appMessage", {
|
||||
action: "create",
|
||||
message: serialziedMessage,
|
||||
});
|
||||
await setMessagesAsRead(contactId);
|
||||
|
||||
return res.json({ message: "Mensagem enviada" });
|
||||
};
|
||||
74
backend/src/controllers/wbot.js
Normal file
74
backend/src/controllers/wbot.js
Normal file
@@ -0,0 +1,74 @@
|
||||
const qrCode = require("qrcode-terminal");
|
||||
const { Client } = require("whatsapp-web.js");
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const { getIO } = require("../libs/socket");
|
||||
|
||||
let wbot;
|
||||
|
||||
module.exports = {
|
||||
init: async () => {
|
||||
let sessionCfg;
|
||||
|
||||
const dbSession = await Whatsapp.findOne({ where: { id: 1 } });
|
||||
if (dbSession && dbSession.session) {
|
||||
sessionCfg = JSON.parse(dbSession.session);
|
||||
}
|
||||
|
||||
wbot = new Client({
|
||||
session: sessionCfg,
|
||||
restartOnAuthFail: true,
|
||||
});
|
||||
wbot.initialize();
|
||||
wbot.on("qr", async qr => {
|
||||
qrCode.generate(qr, { small: true });
|
||||
await Whatsapp.upsert({ id: 1, qrcode: qr, status: "pending" });
|
||||
getIO().emit("qrcode", {
|
||||
action: "update",
|
||||
qr: qr,
|
||||
});
|
||||
});
|
||||
wbot.on("authenticated", async session => {
|
||||
console.log("AUTHENTICATED");
|
||||
await Whatsapp.upsert({
|
||||
id: 1,
|
||||
session: JSON.stringify(session),
|
||||
status: "authenticated",
|
||||
});
|
||||
getIO().emit("whats_auth", {
|
||||
action: "authentication",
|
||||
session: dbSession,
|
||||
});
|
||||
});
|
||||
wbot.on("auth_failure", async msg => {
|
||||
console.error("AUTHENTICATION FAILURE", msg);
|
||||
await Whatsapp.update({ session: "" }, { where: { id: 1 } });
|
||||
});
|
||||
wbot.on("ready", async () => {
|
||||
console.log("READY");
|
||||
await Whatsapp.update(
|
||||
{ status: "online", qrcode: "" },
|
||||
{ where: { id: 1 } }
|
||||
);
|
||||
// const chats = await wbot.getChats(); // pega as mensagens nao lidas (recebidas quando o bot estava offline)
|
||||
// let unreadMessages; // todo > salvar isso no DB pra mostrar no frontend
|
||||
// for (let chat of chats) {
|
||||
// if (chat.unreadCount > 0) {
|
||||
// unreadMessages = await chat.fetchMessages({
|
||||
// limit: chat.unreadCount,
|
||||
// });
|
||||
// }
|
||||
// }
|
||||
|
||||
// console.log(unreadMessages);
|
||||
wbot.sendPresenceAvailable();
|
||||
});
|
||||
return wbot;
|
||||
},
|
||||
|
||||
getWbot: () => {
|
||||
if (!wbot) {
|
||||
throw new Error("Wbot not initialized");
|
||||
}
|
||||
return wbot;
|
||||
},
|
||||
};
|
||||
138
backend/src/controllers/wbotMessageListener.js
Normal file
138
backend/src/controllers/wbotMessageListener.js
Normal file
@@ -0,0 +1,138 @@
|
||||
const Contact = require("../models/Contact");
|
||||
const Message = require("../models/Message");
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot, init } = require("./wbot");
|
||||
|
||||
const wbotMessageListener = () => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot();
|
||||
|
||||
wbot.on("message", async msg => {
|
||||
console.log(msg);
|
||||
let newMessage;
|
||||
// console.log(msg);
|
||||
if (msg.from === "status@broadcast") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const msgContact = await msg.getContact();
|
||||
const profilePicUrl = await msgContact.getProfilePicUrl();
|
||||
try {
|
||||
let contact = await Contact.findOne({
|
||||
where: { number: msgContact.number },
|
||||
});
|
||||
|
||||
if (contact) {
|
||||
await contact.update({ profilePicUrl: profilePicUrl });
|
||||
}
|
||||
|
||||
if (!contact) {
|
||||
try {
|
||||
contact = await Contact.create({
|
||||
name: msgContact.pushname || msgContact.number.toString(),
|
||||
number: msgContact.number,
|
||||
profilePicUrl: profilePicUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
|
||||
if (msg.hasQuotedMsg) {
|
||||
const quotedMessage = await msg.getQuotedMessage();
|
||||
console.log("quoted", quotedMessage);
|
||||
}
|
||||
|
||||
if (msg.hasMedia) {
|
||||
const media = await msg.downloadMedia();
|
||||
|
||||
if (media) {
|
||||
if (!media.filename) {
|
||||
let ext = media.mimetype.split("/")[1].split(";")[0];
|
||||
media.filename = `${new Date().getTime()}.${ext}`;
|
||||
}
|
||||
|
||||
fs.writeFile(
|
||||
path.join(__dirname, "..", "public", media.filename),
|
||||
media.data,
|
||||
"base64",
|
||||
err => {
|
||||
console.log(err);
|
||||
}
|
||||
);
|
||||
|
||||
newMessage = await contact.createMessage({
|
||||
id: msg.id.id,
|
||||
messageBody: msg.body || media.filename,
|
||||
mediaUrl: media.filename,
|
||||
mediaType: media.mimetype.split("/")[0],
|
||||
});
|
||||
await contact.update({ lastMessage: msg.body || media.filename });
|
||||
}
|
||||
} else {
|
||||
newMessage = await contact.createMessage({
|
||||
id: msg.id.id,
|
||||
messageBody: msg.body,
|
||||
});
|
||||
await contact.update({ lastMessage: msg.body });
|
||||
}
|
||||
|
||||
io.to(contact.id)
|
||||
.to("notification")
|
||||
.emit("appMessage", {
|
||||
action: "create",
|
||||
message: {
|
||||
...newMessage.dataValues,
|
||||
mediaUrl: `${
|
||||
newMessage.mediaUrl
|
||||
? `http://${process.env.HOST}:${process.env.PORT}/public/${newMessage.mediaUrl}`
|
||||
: ""
|
||||
}`,
|
||||
},
|
||||
contact: {
|
||||
...contact.dataValues,
|
||||
unreadMessages: 1,
|
||||
lastMessage: newMessage.messageBody,
|
||||
},
|
||||
});
|
||||
|
||||
let chat = await msg.getChat();
|
||||
chat.sendSeen();
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
|
||||
wbot.on("message_ack", async (msg, ack) => {
|
||||
try {
|
||||
const messageToUpdate = await Message.findOne({
|
||||
where: { id: msg.id.id },
|
||||
});
|
||||
if (!messageToUpdate) {
|
||||
// will throw an error is msg wasn't sent from app
|
||||
const error = new Error(
|
||||
"Erro ao alterar o ack da mensagem no banco de dados"
|
||||
);
|
||||
error.statusCode = 501;
|
||||
throw error;
|
||||
}
|
||||
await messageToUpdate.update({ ack: ack });
|
||||
|
||||
io.to(messageToUpdate.contactId).emit("appMessage", {
|
||||
action: "update",
|
||||
message: messageToUpdate,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = wbotMessageListener;
|
||||
50
backend/src/controllers/wbotMonitor.js
Normal file
50
backend/src/controllers/wbotMonitor.js
Normal file
@@ -0,0 +1,50 @@
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const wbotMessageListener = require("./wbotMessageListener");
|
||||
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot, init } = require("./wbot");
|
||||
|
||||
const wbotMonitor = () => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot();
|
||||
|
||||
try {
|
||||
wbot.on("change_state", newState => {
|
||||
console.log("monitor", newState);
|
||||
});
|
||||
|
||||
wbot.on("change_battery", async batteryInfo => {
|
||||
// Battery percentage for attached device has changed
|
||||
const { battery, plugged } = batteryInfo;
|
||||
try {
|
||||
await Whatsapp.update({ battery, plugged }, { where: { id: 1 } });
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
console.log(`Battery: ${battery}% - Charging? ${plugged}`); //todo> save batery state to db
|
||||
});
|
||||
|
||||
wbot.on("disconnected", reason => {
|
||||
console.log("disconnected", reason); //todo> save connection status to DB
|
||||
setTimeout(
|
||||
() =>
|
||||
init()
|
||||
.then(res => {
|
||||
wbotMessageListener();
|
||||
wbotMonitor();
|
||||
})
|
||||
.catch(err => console.log(err)),
|
||||
2000
|
||||
);
|
||||
});
|
||||
|
||||
// setInterval(() => {
|
||||
// wbot.resetState();
|
||||
// }, 20000);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = wbotMonitor;
|
||||
22
backend/src/controllers/whatsapp.js
Normal file
22
backend/src/controllers/whatsapp.js
Normal file
@@ -0,0 +1,22 @@
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const { getIO } = require("../libs/socket");
|
||||
const { getWbot, init } = require("./wbot");
|
||||
|
||||
exports.getSession = async (req, res, next) => {
|
||||
const dbSession = await Whatsapp.findOne({ where: { id: 1 } });
|
||||
|
||||
if (!dbSession) {
|
||||
return res.status(200).json({ message: "Session not found" });
|
||||
}
|
||||
|
||||
return res.status(200).json(dbSession);
|
||||
};
|
||||
|
||||
exports.getContacts = async (req, res, next) => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot();
|
||||
|
||||
const phoneContacts = await wbot.getContacts();
|
||||
|
||||
return res.status(200).json(phoneContacts);
|
||||
};
|
||||
Reference in New Issue
Block a user