Migrate from moment to date-fns and some changes

This commit is contained in:
canove
2020-07-06 18:21:08 -03:00
parent 1bc4831f8f
commit 3679c94baa
33 changed files with 430 additions and 12010 deletions

View File

@@ -1,60 +0,0 @@
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()) {
const error = new Error("Validation failed");
error.statusCode = 422;
error.data = errors.array();
throw error;
}
const { name, password, email } = req.body;
try {
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 });
} catch (err) {
next(err);
}
};
exports.login = async (req, res, next) => {
const { email, password } = req.body;
let loadedUser;
try {
const user = await User.findOne({ where: { email: email } });
if (!user) {
const error = new Error("Usuário não encontrado");
error.statusCode = 401;
throw error;
}
loadedUser = user;
const isEqual = await bcrypt.compare(password, user.password);
if (!isEqual) {
const error = new Error("Senha incorreta");
error.statusCode = 401;
throw error;
}
const token = jwt.sign(
{ email: loadedUser.email, userId: loadedUser.id },
"mysecret",
{ expiresIn: "24h" }
);
return res
.status(200)
.json({ token: token, username: loadedUser.name, userId: loadedUser.id });
} catch (err) {
next(err);
}
};

View File

@@ -1,75 +0,0 @@
const Contact = require("../models/Contact");
const Message = require("../models/Message");
const Sequelize = require("sequelize");
const { getIO } = require("../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
try {
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);
} catch (err) {
console.log(err);
}
};
exports.createContact = async (req, res, next) => {
const wbot = getWbot();
const io = getIO();
const { number, name } = req.body;
try {
const res = await wbot.isRegisteredUser(`55${number}@c.us`);
if (!res) {
const error = new Error("O número informado não é um Whatsapp Válido");
error.statusCode = 422;
throw error;
}
const profilePicUrl = await wbot.getProfilePicUrl(`55${number}@c.us`);
const contact = await Contact.create({
name,
number: `55${number}`,
profilePicUrl,
});
res.status(200).json(contact);
} catch (err) {
next(err);
}
};

View File

@@ -1,155 +0,0 @@
const fs = require("fs");
const Message = require("../models/Message");
const Contact = require("../models/Contact");
const { getIO } = require("../socket");
const { getWbot } = require("./wbot");
const Sequelize = require("sequelize");
const { MessageMedia } = require("whatsapp-web.js");
const setMessagesAsRead = async contactId => {
const io = getIO();
try {
const result = await Message.update(
{ read: true },
{
where: {
contactId: contactId,
read: false,
},
}
);
if (!result) {
const error = new Error(
"Erro ao definir as mensagens como lidas no banco de dados"
);
error.statusCode = 501;
throw error;
}
io.to("notification").emit("contact", {
action: "updateUnread",
contactId: contactId,
});
} catch (err) {
console.log(err);
}
};
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);
try {
const contact = await Contact.findByPk(contactId);
if (!contact) {
const error = new Error("Erro ao localizar o contato no banco de dados");
error.statusCode = 501;
throw error;
}
await setMessagesAsRead(contactId);
const messagesFound = await contact.countMessages({
where: whereCondition,
});
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,
messagesFound,
});
} catch (err) {
next(err);
}
};
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;
try {
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);
if (!newMessage) {
const error = new Error("Erro ao inserir a mensagem no banco de dados");
error.statusCode = 501;
throw error;
}
io.to(contactId).emit("appMessage", {
action: "create",
message: {
...newMessage.dataValues,
mediaUrl: `${
message.mediaUrl
? `http://${process.env.HOST}:${process.env.PORT}/public/${message.mediaUrl}`
: ""
}`,
},
});
await setMessagesAsRead(contactId);
return res.json({ message: "Mensagem enviada" });
} catch (err) {
next(err);
}
};

View File

@@ -1,78 +0,0 @@
const qrCode = require("qrcode-terminal");
const { Client } = require("whatsapp-web.js");
const Whatsapp = require("../models/Whatsapp");
const { getIO } = require("../socket");
let wbot;
module.exports = {
init: async () => {
try {
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;
} catch (err) {
console.log(err);
}
},
getWbot: () => {
if (!wbot) {
throw new Error("Wbot not initialized");
}
return wbot;
},
};

View File

@@ -1,30 +0,0 @@
const Whatsapp = require("../models/Whatsapp");
const { getIO } = require("../socket");
const { getWbot, init } = require("./wbot");
exports.getSession = async (req, res, next) => {
try {
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);
} catch (err) {
next(err);
}
};
exports.getContacts = async (req, res, next) => {
const io = getIO();
const wbot = getWbot();
try {
const phoneContacts = await wbot.getContacts();
return res.status(200).json(phoneContacts);
} catch (err) {
next(err);
}
};

View File

@@ -4,7 +4,7 @@
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js",
"start": "nodemon src/app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"nodemonConfig": {
@@ -19,6 +19,7 @@
"cors": "^2.8.5",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"express-async-errors": "^3.1.1",
"express-validator": "^6.5.0",
"jsonwebtoken": "^8.5.1",
"multer": "^1.4.2",
@@ -27,7 +28,8 @@
"sequelize": "^5.21.13",
"sequelize-cli": "^5.5.1",
"socket.io": "^2.3.0",
"whatsapp-web.js": "^1.7.0"
"whatsapp-web.js": "^1.7.0",
"youch": "^2.0.10"
},
"devDependencies": {
"nodemon": "^2.0.4"

View File

@@ -1,12 +1,13 @@
require("dotenv/config");
// require("dotenv/config");
require("express-async-errors");
const express = require("express");
const path = require("path");
const Youch = require("youch");
const cors = require("cors");
const sequelize = require("./util/database");
const sequelize = require("./database/");
const multer = require("multer");
const wBot = require("./controllers/wbot");
const Contact = require("./models/Contact");
const wbotMessageListener = require("./controllers/wbotMessageListener");
const wbotMonitor = require("./controllers/wbotMonitor");
@@ -36,19 +37,20 @@ app.use(ContactRoutes);
app.use(WhatsRoutes);
app.use("/auth", AuthRoutes);
app.use((error, req, res, next) => {
// console.log(error);
const status = error.statusCode || 500;
const message = error.message;
const data = error.data;
res.status(status).json({ message: message, data: data });
app.use(async (err, req, res, next) => {
if (process.env.NODE_ENV === "development") {
const errors = await new Youch(err, req).toJSON();
return res.status(500).json(errors);
}
return res.status(500).json({ error: "Internal server error" });
});
sequelize
.sync()
.then(() => {
const server = app.listen(process.env.PORT);
const io = require("./socket").init(server);
const io = require("./libs/socket").init(server);
io.on("connection", socket => {
console.log("Client Connected");
socket.on("joinChatBox", contactId => {

View File

@@ -1,18 +1,15 @@
require("dotenv/config");
const Sequelize = require("sequelize");
const sequelize = new Sequelize({
define: {
charset: "utf8mb4",
collate: "utf8mb4_bin",
},
dialect: "mysql",
timezone: "-03:00",
host: process.env.DB_HOST,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASS,
logging: false,
});
module.exports = sequelize;
require("dotenv/config");
module.exports = {
define: {
charset: "utf8mb4",
collate: "utf8mb4_bin",
},
dialect: "mysql",
timezone: "-03:00",
host: process.env.DB_HOST,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASS,
logging: false,
};

View 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 });
};

View 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);
};

View 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" });
};

View 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;
},
};

View File

@@ -4,7 +4,7 @@ const Message = require("../models/Message");
const path = require("path");
const fs = require("fs");
const { getIO } = require("../socket");
const { getIO } = require("../libs/socket");
const { getWbot, init } = require("./wbot");
const wbotMessageListener = () => {

View File

@@ -1,7 +1,7 @@
const Whatsapp = require("../models/Whatsapp");
const wbotMessageListener = require("./wbotMessageListener");
const { getIO } = require("../socket");
const { getIO } = require("../libs/socket");
const { getWbot, init } = require("./wbot");
const wbotMonitor = () => {

View 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);
};

View File

@@ -0,0 +1,6 @@
const Sequelize = require("sequelize");
const dbConfig = require("../config/dbConfig");
const sequelize = new Sequelize(dbConfig);
module.exports = sequelize;

View File

@@ -1,6 +1,6 @@
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const sequelize = require("../database");
const Message = require("./Message");

View File

@@ -1,5 +1,5 @@
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const sequelize = require("../database");
const Message = sequelize.define("message", {
id: {

View File

@@ -1,6 +1,6 @@
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const sequelize = require("../database");
const User = sequelize.define("user", {
id: {

View File

@@ -1,6 +1,6 @@
const Sequelize = require("sequelize");
const sequelize = require("../util/database");
const sequelize = require("../database");
const Whatsapp = sequelize.define("whatsapp", {
session: { type: Sequelize.TEXT() },

View File

@@ -6,7 +6,7 @@ const isAuth = require("../middleware/is-auth");
const routes = express.Router();
routes.put(
routes.post(
"/signup",
[
body("email")
@@ -15,7 +15,7 @@ routes.put(
.custom((value, { req }) => {
return User.findOne({ where: { email: value } }).then(user => {
if (user) {
return Promise.reject("Um cadastro com este email já existe!");
return Promise.reject("An user with this email already exists!");
}
});
})

View File

@@ -482,7 +482,7 @@ cookie-signature@1.0.6:
resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c"
integrity sha1-4wOogrNCzD7oylE6eZmXNNqzriw=
cookie@0.3.1:
cookie@0.3.1, cookie@^0.3.1:
version "0.3.1"
resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.3.1.tgz#e7e0a1f9ef43b4c8ba925c5c5a96e806d16873bb"
integrity sha1-5+Ch+e9DtMi6klxcWpboBtFoc7s=
@@ -761,6 +761,11 @@ event-emitter@^0.3.5:
d "1"
es5-ext "~0.10.14"
express-async-errors@^3.1.1:
version "3.1.1"
resolved "https://registry.yarnpkg.com/express-async-errors/-/express-async-errors-3.1.1.tgz#6053236d61d21ddef4892d6bd1d736889fc9da41"
integrity sha512-h6aK1da4tpqWSbyCa3FxB/V6Ehd4EEB15zyQq9qe75OZBp0krinNKuH4rAY+S/U/2I36vdLAUFSjQJ+TFmODng==
express-validator@^6.5.0:
version "6.6.0"
resolved "https://registry.yarnpkg.com/express-validator/-/express-validator-6.6.0.tgz#46b8327926e9b1752f9823ee0631e534b6ac41e8"
@@ -1496,6 +1501,11 @@ multer@^1.4.2:
type-is "^1.6.4"
xtend "^4.0.0"
mustache@^3.0.0:
version "3.2.1"
resolved "https://registry.yarnpkg.com/mustache/-/mustache-3.2.1.tgz#89e78a9d207d78f2799b1e95764a25bf71a28322"
integrity sha512-RERvMFdLpaFfSRIEe632yDm5nsd0SDKn8hGmcUwswnyiE5mtdZLDybtHAz6hjJhawokF0hXvGLtx9mrQfm6FkA==
mysql2@^2.1.0:
version "2.1.0"
resolved "https://registry.yarnpkg.com/mysql2/-/mysql2-2.1.0.tgz#55ecfd4353114c148cc4c253192dbbfd000e6642"
@@ -2097,6 +2107,11 @@ sqlstring@^2.3.1:
resolved "https://registry.yarnpkg.com/sqlstring/-/sqlstring-2.3.2.tgz#cdae7169389a1375b18e885f2e60b3e460809514"
integrity sha512-vF4ZbYdKS8OnoJAWBmMxCQDkiEBkGQYU7UZPtL8flbDRSNkhaXvRJ279ZtI6M+zDaQovVU4tuRgzK5fVhvFAhg==
stack-trace@0.0.10:
version "0.0.10"
resolved "https://registry.yarnpkg.com/stack-trace/-/stack-trace-0.0.10.tgz#547c70b347e8d32b4e108ea1a2a159e5fdde19c0"
integrity sha1-VHxws0fo0ytOEI6hoqFZ5f3eGcA=
"statuses@>= 1.5.0 < 2", statuses@~1.5.0:
version "1.5.0"
resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c"
@@ -2511,3 +2526,12 @@ yeast@0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/yeast/-/yeast-0.1.2.tgz#008e06d8094320c372dbc2f8ed76a0ca6c8ac419"
integrity sha1-AI4G2AlDIMNy28L47XagymyKxBk=
youch@^2.0.10:
version "2.0.10"
resolved "https://registry.yarnpkg.com/youch/-/youch-2.0.10.tgz#e0f6312b12304fd330a0c4a0e0925b0123f7d495"
integrity sha512-qPLQW2TuwlcK9sm5i1Gbb9ezRZRZyzr6NsY5cqxsbh+2iEyKPxLlz0OSAc+pQ7mv1pYZLri1MXynggP6R2FcNQ==
dependencies:
cookie "^0.3.1"
mustache "^3.0.0"
stack-trace "0.0.10"

View File

@@ -3564,11 +3564,6 @@
}
}
},
"classnames": {
"version": "2.2.6",
"resolved": "https://registry.npmjs.org/classnames/-/classnames-2.2.6.tgz",
"integrity": "sha512-JR/iSQOSt+LQIWwrwEzJ9uk0xfN3mTVYMwt1Ir5mUcSN6pU+V4zQFFaJsclJbPuAUQH+yfWef6tm7l1quW3C8Q=="
},
"clean-css": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/clean-css/-/clean-css-4.2.3.tgz",
@@ -4356,6 +4351,11 @@
}
}
},
"date-fns": {
"version": "2.14.0",
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-2.14.0.tgz",
"integrity": "sha512-1zD+68jhFgDIM0rF05rcwYO8cExdNqxjq4xP1QKM60Q45mnO6zaMWB4tOzrIr4M4GSLntsKeE4c9Bdl2jhL/yw=="
},
"debug": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz",
@@ -8579,19 +8579,6 @@
"minimist": "^1.2.5"
}
},
"moment": {
"version": "2.26.0",
"resolved": "https://registry.npmjs.org/moment/-/moment-2.26.0.tgz",
"integrity": "sha512-oIixUO+OamkUkwjhAVE18rAMfRJNsNe/Stid/gwHSOfHrOtw9EhAY2AHvdKZ/k/MggcYELFCJz/Sn2pL8b8JMw=="
},
"moment-timezone": {
"version": "0.5.31",
"resolved": "https://registry.npmjs.org/moment-timezone/-/moment-timezone-0.5.31.tgz",
"integrity": "sha512-+GgHNg8xRhMXfEbv81iDtrVeTcWt0kWmTEY1XQK14dICTXnWJnT0dxdlPspwqF3keKMVPXwayEsk1DI0AA/jdA==",
"requires": {
"moment": ">= 2.9.0"
}
},
"move-concurrently": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/move-concurrently/-/move-concurrently-1.0.1.tgz",
@@ -10990,11 +10977,6 @@
"resolved": "https://registry.npmjs.org/react-modal-image/-/react-modal-image-2.5.0.tgz",
"integrity": "sha512-QucQrgOLmF44CD4EFDLZ9ICrbHEZwztjALgx1GsNmMWZrAtmzDLarG+T1TK2OSE4w1eHfkXtmEhQibjbt0mT2g=="
},
"react-moment": {
"version": "0.9.7",
"resolved": "https://registry.npmjs.org/react-moment/-/react-moment-0.9.7.tgz",
"integrity": "sha512-ifzUrUGF6KRsUN2pRG5k56kO0mJBr8kRkWb0wNvtFIsBIxOuPxhUpL1YlXwpbQCbHq23hUu6A0VEk64HsFxk9g=="
},
"react-router": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-5.2.0.tgz",
@@ -11101,16 +11083,6 @@
"workbox-webpack-plugin": "4.3.1"
}
},
"react-toastify": {
"version": "6.0.4",
"resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-6.0.4.tgz",
"integrity": "sha512-ieNHqMZim/8h0NfSigWsmqly9dG4JwtTnBCq3y5UVua73Os8VyvsZkdu5CHORqXXgIe9CGIIPz4AbIiFXWkLHg==",
"requires": {
"classnames": "^2.2.6",
"prop-types": "^15.7.2",
"react-transition-group": "^4.4.1"
}
},
"react-transition-group": {
"version": "4.4.1",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.1.tgz",

View File

@@ -9,19 +9,16 @@
"@testing-library/react": "^9.5.0",
"@testing-library/user-event": "^7.2.1",
"axios": "^0.19.2",
"date-fns": "^2.14.0",
"dotenv": "^8.2.0",
"emoji-mart": "^3.0.0",
"moment": "^2.26.0",
"moment-timezone": "^0.5.31",
"qrcode.react": "^1.0.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-infinite-scroll-reverse": "^1.0.3",
"react-modal-image": "^2.5.0",
"react-moment": "^0.9.7",
"react-router-dom": "^5.2.0",
"react-scripts": "3.4.1",
"react-toastify": "^6.0.4",
"socket.io-client": "^2.3.0"
},
"scripts": {

View File

@@ -2,7 +2,8 @@ import React, { useState, useEffect } from "react";
import { useHistory, useParams } from "react-router-dom";
import api from "../../../../util/api";
import openSocket from "socket.io-client";
import moment from "moment-timezone";
import { parseISO, format } from "date-fns";
import profileDefaultPic from "../../../../Images/profile_default.png";
@@ -219,9 +220,7 @@ const ContactsList = () => {
const showDesktopNotification = data => {
const options = {
body: `${data.message.messageBody} - ${moment(new Date())
.tz("America/Sao_Paulo")
.format("DD/MM/YY - HH:mm")}`,
body: `${data.message.messageBody} - ${format(new Date(), "HH:mm")}`,
icon: data.contact.profilePicUrl,
};
new Notification(`Mensagem de ${data.contact.name}`, options);
@@ -322,9 +321,7 @@ const ContactsList = () => {
variant="body2"
color="textSecondary"
>
{moment(contact.updatedAt)
.tz("America/Sao_Paulo")
.format("HH:mm")}
{format(parseISO(contact.updatedAt), "HH:mm")}
</Typography>
)}
</span>

View File

@@ -1,6 +1,11 @@
import React, { useState, useEffect, useRef } from "react";
import { useParams } from "react-router-dom";
import { isSameDay, parseISO, format } from "date-fns";
import openSocket from "socket.io-client";
import InfiniteScrollReverse from "react-infinite-scroll-reverse";
import ModalImage from "react-modal-image";
import { makeStyles } from "@material-ui/core/styles";
import AccessTimeIcon from "@material-ui/icons/AccessTime";
import CircularProgress from "@material-ui/core/CircularProgress";
@@ -18,11 +23,7 @@ import { green } from "@material-ui/core/colors";
import whatsBackground from "../../../../Images/wa-background.png";
import api from "../../../../util/api";
import openSocket from "socket.io-client";
import moment from "moment-timezone";
import InfiniteScrollReverse from "react-infinite-scroll-reverse";
import ModalImage from "react-modal-image";
import MessagesInput from "../MessagesInput/MessagesInput";
const useStyles = makeStyles(theme => ({
@@ -164,7 +165,7 @@ const useStyles = makeStyles(theme => ({
fontSize: 11,
position: "absolute",
bottom: 0,
right: 10,
right: 5,
color: "#999",
},
@@ -188,12 +189,14 @@ const useStyles = makeStyles(theme => ({
ackIcons: {
fontSize: 18,
verticalAlign: "middle",
marginLeft: 4,
},
ackDoneAllIcon: {
color: green[500],
fontSize: 18,
verticalAlign: "middle",
marginLeft: 4,
},
}));
@@ -362,32 +365,23 @@ const MessagesList = () => {
key={`timestamp-${message.id}`}
>
<div className={classes.dailyTimestampText}>
{moment(messagesList[index].createdAt)
.tz("America/Sao_Paulo")
.format("DD/MM/YY")}
{format(parseISO(messagesList[index].createdAt), "dd/MM/yyyy")}
</div>
</span>
);
}
if (index < messagesList.length - 1) {
let messageDay = moment(messagesList[index].createdAt)
.tz("America/Sao_Paulo")
.format("DD/MM/YY");
let messageDay = parseISO(messagesList[index].createdAt);
let previousMessageDay = parseISO(messagesList[index - 1].createdAt);
let previousMessageDay = moment(messagesList[index - 1].createdAt)
.tz("America/Sao_Paulo")
.format("DD/MM/YY");
if (messageDay > previousMessageDay) {
if (!isSameDay(messageDay, previousMessageDay)) {
return (
<span
className={classes.dailyTimestamp}
key={`timestamp-${message.id}`}
>
<div className={classes.dailyTimestampText}>
{moment(messagesList[index].createdAt)
.tz("America/Sao_Paulo")
.format("DD/MM/YY")}
{format(parseISO(messagesList[index].createdAt), "dd/MM/yyyy")}
</div>
</span>
);
@@ -415,9 +409,7 @@ const MessagesList = () => {
<div className={classes.textContentItem}>
{message.messageBody}
<span className={classes.timestamp}>
{moment(message.createdAt)
.tz("America/Sao_Paulo")
.format("HH:mm")}
{format(parseISO(message.createdAt), "HH:mm")}
</span>
</div>
</div>,
@@ -430,9 +422,7 @@ const MessagesList = () => {
<div className={classes.textContentItem}>
{message.messageBody}
<span className={classes.timestamp}>
{moment(message.createdAt)
.tz("America/Sao_Paulo")
.format("HH:mm")}{" "}
{format(parseISO(message.createdAt), "HH:mm")}
{renderMessageAck(message)}
</span>
</div>

File diff suppressed because it is too large Load Diff