mirror of
https://github.com/cheveguerra/whaticket-community.git
synced 2026-04-17 19:37:02 +00:00
migration to WSL
This commit is contained in:
14
.vscode/launch.json
vendored
Normal file
14
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,14 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"name": "Launch Program",
|
||||
"program": "${workspaceFolder}\\backend\\app.js"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
NODE_ENV=development
|
||||
PORT=8080
|
||||
|
||||
DB_HOST=
|
||||
DB_USER=
|
||||
DB_PASS=
|
||||
NODE_ENV=development
|
||||
HOST=localhost
|
||||
PORT=8080
|
||||
|
||||
DB_HOST=
|
||||
DB_USER=
|
||||
DB_PASS=
|
||||
DB_NAME=
|
||||
6
backend/.gitignore
vendored
6
backend/.gitignore
vendored
@@ -1,4 +1,4 @@
|
||||
node_modules
|
||||
public/*
|
||||
!public/.gitkeep
|
||||
node_modules
|
||||
public/*
|
||||
!public/.gitkeep
|
||||
.env
|
||||
152
backend/app.js
152
backend/app.js
@@ -1,76 +1,76 @@
|
||||
require("dotenv/config");
|
||||
const express = require("express");
|
||||
const path = require("path");
|
||||
const cors = require("cors");
|
||||
const sequelize = require("./util/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");
|
||||
|
||||
const messageRoutes = require("./routes/message");
|
||||
const ContactRoutes = require("./routes/contacts");
|
||||
const AuthRoutes = require("./routes/auth");
|
||||
const WhatsRoutes = require("./routes/whatsapp");
|
||||
|
||||
const app = express();
|
||||
|
||||
const fileStorage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, "public");
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
cb(null, new Date().getTime() + "-" + file.originalname.replace(/\s/g, ""));
|
||||
},
|
||||
});
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(multer({ storage: fileStorage }).single("media"));
|
||||
app.use("/public", express.static(path.join(__dirname, "public")));
|
||||
|
||||
app.use(messageRoutes);
|
||||
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 });
|
||||
});
|
||||
|
||||
sequelize
|
||||
.sync()
|
||||
.then(() => {
|
||||
const server = app.listen(process.env.PORT);
|
||||
const io = require("./socket").init(server);
|
||||
io.on("connection", socket => {
|
||||
console.log("Client Connected");
|
||||
socket.on("joinChatBox", contactId => {
|
||||
socket.join(contactId);
|
||||
});
|
||||
|
||||
socket.on("joinNotification", () => {
|
||||
console.log("chat entrou no canal de notificações");
|
||||
socket.join("notification");
|
||||
});
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
console.log("Client disconnected");
|
||||
});
|
||||
});
|
||||
|
||||
wBot.init().then(() => {
|
||||
wbotMessageListener();
|
||||
wbotMonitor();
|
||||
});
|
||||
console.log("Server started on", process.env.PORT);
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
require("dotenv/config");
|
||||
const express = require("express");
|
||||
const path = require("path");
|
||||
const cors = require("cors");
|
||||
const sequelize = require("./util/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");
|
||||
|
||||
const messageRoutes = require("./routes/message");
|
||||
const ContactRoutes = require("./routes/contacts");
|
||||
const AuthRoutes = require("./routes/auth");
|
||||
const WhatsRoutes = require("./routes/whatsapp");
|
||||
|
||||
const app = express();
|
||||
|
||||
const fileStorage = multer.diskStorage({
|
||||
destination: (req, file, cb) => {
|
||||
cb(null, "public");
|
||||
},
|
||||
filename: (req, file, cb) => {
|
||||
cb(null, new Date().getTime() + "-" + file.originalname.replace(/\s/g, ""));
|
||||
},
|
||||
});
|
||||
|
||||
app.use(cors());
|
||||
app.use(express.json());
|
||||
app.use(multer({ storage: fileStorage }).single("media"));
|
||||
app.use("/public", express.static(path.join(__dirname, "public")));
|
||||
|
||||
app.use(messageRoutes);
|
||||
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 });
|
||||
});
|
||||
|
||||
sequelize
|
||||
.sync()
|
||||
.then(() => {
|
||||
const server = app.listen(process.env.PORT);
|
||||
const io = require("./socket").init(server);
|
||||
io.on("connection", socket => {
|
||||
console.log("Client Connected");
|
||||
socket.on("joinChatBox", contactId => {
|
||||
socket.join(contactId);
|
||||
});
|
||||
|
||||
socket.on("joinNotification", () => {
|
||||
console.log("chat entrou no canal de notificações");
|
||||
socket.join("notification");
|
||||
});
|
||||
|
||||
socket.on("disconnect", () => {
|
||||
console.log("Client disconnected");
|
||||
});
|
||||
});
|
||||
|
||||
wBot.init().then(() => {
|
||||
wbotMessageListener();
|
||||
wbotMonitor();
|
||||
});
|
||||
console.log("Server started on", process.env.PORT);
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
@@ -1,60 +1,60 @@
|
||||
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);
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,46 +1,75 @@
|
||||
const Contact = require("../models/Contact");
|
||||
const Message = require("../models/Message");
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,155 +1,155 @@
|
||||
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.satusCode = 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.satusCode = 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.satusCode = 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);
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,78 +1,78 @@
|
||||
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;
|
||||
},
|
||||
};
|
||||
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;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,131 +1,131 @@
|
||||
const Contact = require("../models/Contact");
|
||||
const Message = require("../models/Message");
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const { getIO } = require("../socket");
|
||||
const { getWbot, init } = require("./wbot");
|
||||
|
||||
const wbotMessageListener = () => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot();
|
||||
|
||||
wbot.on("message", async msg => {
|
||||
let newMessage;
|
||||
// console.log(msg);
|
||||
if (msg.from === "status@broadcast") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const msgContact = await msg.getContact();
|
||||
const imageUrl = await msgContact.getProfilePicUrl();
|
||||
try {
|
||||
let contact = await Contact.findOne({
|
||||
where: { number: msgContact.number },
|
||||
});
|
||||
|
||||
if (contact) {
|
||||
await contact.update({ imageURL: imageUrl });
|
||||
}
|
||||
|
||||
if (!contact) {
|
||||
try {
|
||||
contact = await Contact.create({
|
||||
name: msgContact.pushname || msgContact.number.toString(),
|
||||
number: msgContact.number,
|
||||
imageURL: imageUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
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.satusCode = 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;
|
||||
const Contact = require("../models/Contact");
|
||||
const Message = require("../models/Message");
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
const { getIO } = require("../socket");
|
||||
const { getWbot, init } = require("./wbot");
|
||||
|
||||
const wbotMessageListener = () => {
|
||||
const io = getIO();
|
||||
const wbot = getWbot();
|
||||
|
||||
wbot.on("message", async msg => {
|
||||
let newMessage;
|
||||
// console.log(msg);
|
||||
if (msg.from === "status@broadcast") {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const msgContact = await msg.getContact();
|
||||
const imageUrl = await msgContact.getProfilePicUrl();
|
||||
try {
|
||||
let contact = await Contact.findOne({
|
||||
where: { number: msgContact.number },
|
||||
});
|
||||
|
||||
if (contact) {
|
||||
await contact.update({ profilePicUrl: imageUrl });
|
||||
}
|
||||
|
||||
if (!contact) {
|
||||
try {
|
||||
contact = await Contact.create({
|
||||
name: msgContact.pushname || msgContact.number.toString(),
|
||||
number: msgContact.number,
|
||||
profilePicUrl: imageUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
@@ -1,50 +1,50 @@
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const wbotMessageListener = require("./wbotMessageListener");
|
||||
|
||||
const { getIO } = require("../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;
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
const wbotMessageListener = require("./wbotMessageListener");
|
||||
|
||||
const { getIO } = require("../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;
|
||||
|
||||
@@ -1,15 +1,30 @@
|
||||
const Whatsapp = require("../models/Whatsapp");
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
module.exports = (req, res, next) => {
|
||||
let decodedToken;
|
||||
try {
|
||||
const [, token] = req.get("Authorization").split(" ");
|
||||
decodedToken = jwt.verify(token, "mysecret");
|
||||
} catch (err) {
|
||||
err.statusCode = 401;
|
||||
err.message = "invalidToken";
|
||||
next(err);
|
||||
}
|
||||
|
||||
if (!decodedToken) {
|
||||
const error = new Error("Falha na autenticação");
|
||||
error.statusCode = 401;
|
||||
next(error);
|
||||
}
|
||||
|
||||
req.userId = decodedToken.userId;
|
||||
next();
|
||||
};
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
module.exports = (req, res, next) => {
|
||||
let decodedToken;
|
||||
try {
|
||||
const [, token] = req.get("Authorization").split(" ");
|
||||
decodedToken = jwt.verify(token, "mysecret");
|
||||
req.userId = decodedToken.userId;
|
||||
} catch (err) {
|
||||
err.statusCode = 401;
|
||||
err.message = "invalidToken";
|
||||
next(err);
|
||||
}
|
||||
|
||||
if (!decodedToken) {
|
||||
const error = new Error("Falha na autenticação");
|
||||
error.statusCode = 401;
|
||||
next(error);
|
||||
}
|
||||
|
||||
next();
|
||||
};
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Message = require("./Message");
|
||||
|
||||
const Contact = sequelize.define("contact", {
|
||||
name: { type: Sequelize.STRING(100), allowNull: false },
|
||||
number: { type: Sequelize.STRING(15), allowNull: false },
|
||||
imageURL: { type: Sequelize.STRING(200) },
|
||||
lastMessage: { type: Sequelize.TEXT },
|
||||
});
|
||||
|
||||
Contact.hasMany(Message, {
|
||||
onDelete: "CASCADE",
|
||||
onUpdate: "RESTRICT",
|
||||
});
|
||||
|
||||
module.exports = Contact;
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Message = require("./Message");
|
||||
|
||||
const Contact = sequelize.define("contact", {
|
||||
name: { type: Sequelize.STRING(100), allowNull: false },
|
||||
number: { type: Sequelize.STRING(15), allowNull: false },
|
||||
profilePicUrl: { type: Sequelize.STRING(200) },
|
||||
lastMessage: { type: Sequelize.TEXT },
|
||||
});
|
||||
|
||||
Contact.hasMany(Message, {
|
||||
onDelete: "CASCADE",
|
||||
onUpdate: "RESTRICT",
|
||||
});
|
||||
|
||||
module.exports = Contact;
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const Sequelize = require("sequelize");
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Message = sequelize.define("message", {
|
||||
id: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
primaryKey: true,
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE(6),
|
||||
},
|
||||
userId: { type: Sequelize.INTEGER, defaultValue: 0 },
|
||||
ack: { type: Sequelize.INTEGER, defaultValue: 0 },
|
||||
messageBody: { type: Sequelize.TEXT, allowNull: false },
|
||||
read: { type: Sequelize.BOOLEAN, defaultValue: false },
|
||||
mediaUrl: { type: Sequelize.STRING(250) },
|
||||
mediaType: { type: Sequelize.STRING(250) },
|
||||
});
|
||||
|
||||
module.exports = Message;
|
||||
const Sequelize = require("sequelize");
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Message = sequelize.define("message", {
|
||||
id: {
|
||||
type: Sequelize.STRING(50),
|
||||
allowNull: false,
|
||||
primaryKey: true,
|
||||
},
|
||||
createdAt: {
|
||||
allowNull: false,
|
||||
type: Sequelize.DATE(6),
|
||||
},
|
||||
userId: { type: Sequelize.INTEGER, defaultValue: 0 },
|
||||
ack: { type: Sequelize.INTEGER, defaultValue: 0 },
|
||||
messageBody: { type: Sequelize.TEXT, allowNull: false },
|
||||
read: { type: Sequelize.BOOLEAN, defaultValue: false },
|
||||
mediaUrl: { type: Sequelize.STRING(250) },
|
||||
mediaType: { type: Sequelize.STRING(250) },
|
||||
});
|
||||
|
||||
module.exports = Message;
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const User = sequelize.define("user", {
|
||||
id: {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: false,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
name: { type: Sequelize.STRING(100), allowNull: false },
|
||||
password: { type: Sequelize.STRING(100), allowNull: false },
|
||||
email: { type: Sequelize.STRING(100), allowNull: false },
|
||||
});
|
||||
|
||||
module.exports = User;
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const User = sequelize.define("user", {
|
||||
id: {
|
||||
type: Sequelize.INTEGER,
|
||||
allowNull: false,
|
||||
primaryKey: true,
|
||||
autoIncrement: true,
|
||||
},
|
||||
name: { type: Sequelize.STRING(100), allowNull: false },
|
||||
password: { type: Sequelize.STRING(100), allowNull: false },
|
||||
email: { type: Sequelize.STRING(100), allowNull: false },
|
||||
});
|
||||
|
||||
module.exports = User;
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Whatsapp = sequelize.define("whatsapp", {
|
||||
session: { type: Sequelize.TEXT() },
|
||||
qrcode: { type: Sequelize.TEXT() },
|
||||
status: { type: Sequelize.STRING(60) },
|
||||
battery: { type: Sequelize.STRING(20) },
|
||||
plugged: { type: Sequelize.BOOLEAN() },
|
||||
});
|
||||
|
||||
module.exports = Whatsapp;
|
||||
const Sequelize = require("sequelize");
|
||||
|
||||
const sequelize = require("../util/database");
|
||||
|
||||
const Whatsapp = sequelize.define("whatsapp", {
|
||||
session: { type: Sequelize.TEXT() },
|
||||
qrcode: { type: Sequelize.TEXT() },
|
||||
status: { type: Sequelize.STRING(60) },
|
||||
battery: { type: Sequelize.STRING(20) },
|
||||
plugged: { type: Sequelize.BOOLEAN() },
|
||||
});
|
||||
|
||||
module.exports = Whatsapp;
|
||||
|
||||
@@ -1,30 +1,35 @@
|
||||
const express = require("express");
|
||||
const { body } = require("express-validator");
|
||||
const User = require("../models/User");
|
||||
const authController = require("../controllers/auth");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.put(
|
||||
"/signup",
|
||||
[
|
||||
body("email")
|
||||
.isEmail()
|
||||
.withMessage("Email inválido")
|
||||
.custom((value, { req }) => {
|
||||
return User.findOne({ where: { email: value } }).then(user => {
|
||||
if (user) {
|
||||
return Promise.reject("Um cadastro com este email já existe!");
|
||||
}
|
||||
});
|
||||
})
|
||||
.normalizeEmail(),
|
||||
body("password").trim().isLength({ min: 5 }),
|
||||
body("name").trim().not().isEmpty(),
|
||||
],
|
||||
authController.signup
|
||||
);
|
||||
|
||||
routes.post("/login", authController.login);
|
||||
|
||||
module.exports = routes;
|
||||
const express = require("express");
|
||||
const { body } = require("express-validator");
|
||||
const User = require("../models/User");
|
||||
const authController = require("../controllers/auth");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.put(
|
||||
"/signup",
|
||||
[
|
||||
body("email")
|
||||
.isEmail()
|
||||
.withMessage("Email inválido")
|
||||
.custom((value, { req }) => {
|
||||
return User.findOne({ where: { email: value } }).then(user => {
|
||||
if (user) {
|
||||
return Promise.reject("Um cadastro com este email já existe!");
|
||||
}
|
||||
});
|
||||
})
|
||||
.normalizeEmail(),
|
||||
body("password").trim().isLength({ min: 5 }),
|
||||
body("name").trim().not().isEmpty(),
|
||||
],
|
||||
authController.signup
|
||||
);
|
||||
|
||||
routes.post("/login", authController.login);
|
||||
|
||||
routes.get("/check", isAuth, (req, res) => {
|
||||
res.status(200).json({ authenticated: true });
|
||||
});
|
||||
|
||||
module.exports = routes;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const ContactController = require("../controllers/contact");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get("/contacts", isAuth, ContactController.getContacts);
|
||||
// routes.post(ContactController.postCreateContact);
|
||||
|
||||
module.exports = routes;
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const ContactController = require("../controllers/contact");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get("/contacts", isAuth, ContactController.getContacts);
|
||||
// routes.post(ContactController.postCreateContact);
|
||||
|
||||
routes.post("/contacts", isAuth, ContactController.createContact);
|
||||
|
||||
module.exports = routes;
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const MessangeController = require("../controllers/message");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get(
|
||||
"/messages/:contactId",
|
||||
isAuth,
|
||||
MessangeController.getContactMessages
|
||||
);
|
||||
routes.post(
|
||||
"/messages/:contactId",
|
||||
isAuth,
|
||||
MessangeController.postCreateContactMessage
|
||||
);
|
||||
|
||||
module.exports = routes;
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const MessangeController = require("../controllers/message");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get(
|
||||
"/messages/:contactId",
|
||||
isAuth,
|
||||
MessangeController.getContactMessages
|
||||
);
|
||||
routes.post(
|
||||
"/messages/:contactId",
|
||||
isAuth,
|
||||
MessangeController.postCreateContactMessage
|
||||
);
|
||||
|
||||
module.exports = routes;
|
||||
|
||||
@@ -1,15 +1,22 @@
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const WhatsappController = require("../controllers/whatsapp");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get("/whatsapp/session", isAuth, WhatsappController.getSession);
|
||||
// routes.post(
|
||||
// "/messages/:contactId",
|
||||
// isAuth,
|
||||
// WhatsappController.postCreateContactMessage
|
||||
// );
|
||||
|
||||
module.exports = routes;
|
||||
const express = require("express");
|
||||
const isAuth = require("../middleware/is-auth");
|
||||
|
||||
const WhatsappController = require("../controllers/whatsapp");
|
||||
|
||||
const routes = express.Router();
|
||||
|
||||
routes.get("/whatsapp/session", isAuth, WhatsappController.getSession);
|
||||
// routes.post(
|
||||
// "/messages/:contactId",
|
||||
// isAuth,
|
||||
// WhatsappController.postCreateContactMessage
|
||||
// );
|
||||
|
||||
routes.get("/whatsapp/contacts", isAuth, WhatsappController.getContacts);
|
||||
// routes.post(
|
||||
// "/messages/:contactId",
|
||||
// isAuth,
|
||||
// WhatsappController.postCreateContactMessage
|
||||
// );
|
||||
|
||||
module.exports = routes;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
let io;
|
||||
|
||||
module.exports = {
|
||||
init: httpServer => {
|
||||
io = require("socket.io")(httpServer);
|
||||
return io;
|
||||
},
|
||||
getIO: () => {
|
||||
if (!io) {
|
||||
throw new Error("Socket IO not initialized");
|
||||
}
|
||||
return io;
|
||||
},
|
||||
};
|
||||
let io;
|
||||
|
||||
module.exports = {
|
||||
init: httpServer => {
|
||||
io = require("socket.io")(httpServer);
|
||||
return io;
|
||||
},
|
||||
getIO: () => {
|
||||
if (!io) {
|
||||
throw new Error("Socket IO not initialized");
|
||||
}
|
||||
return io;
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
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");
|
||||
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;
|
||||
|
||||
29026
frontend/package-lock.json
generated
29026
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,48 +1,48 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@material-ui/core": "^4.9.14",
|
||||
"@material-ui/icons": "^4.9.1",
|
||||
"@testing-library/jest-dom": "^4.2.4",
|
||||
"@testing-library/react": "^9.5.0",
|
||||
"@testing-library/user-event": "^7.2.1",
|
||||
"axios": "^0.19.2",
|
||||
"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": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "react-app"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
{
|
||||
"name": "frontend",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@material-ui/core": "^4.9.14",
|
||||
"@material-ui/icons": "^4.9.1",
|
||||
"@testing-library/jest-dom": "^4.2.4",
|
||||
"@testing-library/react": "^9.5.0",
|
||||
"@testing-library/user-event": "^7.2.1",
|
||||
"axios": "^0.19.2",
|
||||
"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": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "react-app"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
button:active {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
button:focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
img:active {
|
||||
opacity: 0.5;
|
||||
}
|
||||
button:active {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
button:focus {
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
img:active {
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
import React, { createContext } from "react";
|
||||
|
||||
import useAuth from "./useAuth";
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
const AuthProvider = ({ children }) => {
|
||||
const { isAuth, loading, handleLogin, handleLogout } = useAuth();
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ loading, isAuth, handleLogin, handleLogout }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { AuthContext, AuthProvider };
|
||||
import React, { createContext } from "react";
|
||||
|
||||
import useAuth from "./useAuth";
|
||||
|
||||
const AuthContext = createContext();
|
||||
|
||||
const AuthProvider = ({ children }) => {
|
||||
const { isAuth, loading, handleLogin, handleLogout } = useAuth();
|
||||
|
||||
return (
|
||||
<AuthContext.Provider
|
||||
value={{ loading, isAuth, handleLogin, handleLogout }}
|
||||
>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export { AuthContext, AuthProvider };
|
||||
|
||||
@@ -1,50 +1,70 @@
|
||||
import { useState, useEffect } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
|
||||
import api from "../../util/api";
|
||||
|
||||
const useAuth = () => {
|
||||
const history = useHistory();
|
||||
const [isAuth, setIsAuth] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
if (token) {
|
||||
api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
|
||||
setIsAuth(true);
|
||||
}
|
||||
|
||||
setLoading(false);
|
||||
}, []);
|
||||
|
||||
const handleLogin = async (e, user) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const res = await api.post("/auth/login", user);
|
||||
localStorage.setItem("token", JSON.stringify(res.data.token));
|
||||
localStorage.setItem("username", res.data.username);
|
||||
localStorage.setItem("userId", res.data.userId);
|
||||
api.defaults.headers.Authorization = `Bearer ${res.data.token}`;
|
||||
setIsAuth(true);
|
||||
history.push("/chat");
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = e => {
|
||||
e.preventDefault();
|
||||
setIsAuth(false);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("username");
|
||||
localStorage.removeItem("userId");
|
||||
api.defaults.headers.Authorization = undefined;
|
||||
history.push("/login");
|
||||
};
|
||||
|
||||
return { isAuth, loading, handleLogin, handleLogout };
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
import { useState, useEffect } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
|
||||
import api from "../../util/api";
|
||||
|
||||
const useAuth = () => {
|
||||
const history = useHistory();
|
||||
const [isAuth, setIsAuth] = useState(false);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem("token");
|
||||
|
||||
if (token) {
|
||||
api.defaults.headers.Authorization = `Bearer ${JSON.parse(token)}`;
|
||||
setIsAuth(true);
|
||||
}
|
||||
const checkAuth = async () => {
|
||||
if (
|
||||
history.location.pathname === "/login" ||
|
||||
history.location.pathname === "/signup"
|
||||
) {
|
||||
setLoading(false);
|
||||
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await api.get("/auth/check");
|
||||
if (res.status === 200) {
|
||||
setIsAuth(true);
|
||||
setLoading(false);
|
||||
}
|
||||
} catch (err) {
|
||||
setLoading(false);
|
||||
setIsAuth(false);
|
||||
alert("Erro de autenticação. Por favor, faça login novamente");
|
||||
}
|
||||
};
|
||||
checkAuth();
|
||||
}, [history.location.pathname]);
|
||||
|
||||
const handleLogin = async (e, user) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const res = await api.post("/auth/login", user);
|
||||
localStorage.setItem("token", JSON.stringify(res.data.token));
|
||||
localStorage.setItem("username", res.data.username);
|
||||
localStorage.setItem("userId", res.data.userId);
|
||||
api.defaults.headers.Authorization = `Bearer ${res.data.token}`;
|
||||
setIsAuth(true);
|
||||
history.push("/chat");
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLogout = e => {
|
||||
e.preventDefault();
|
||||
setIsAuth(false);
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("username");
|
||||
localStorage.removeItem("userId");
|
||||
api.defaults.headers.Authorization = undefined;
|
||||
history.push("/login");
|
||||
};
|
||||
|
||||
return { isAuth, loading, handleLogin, handleLogout };
|
||||
};
|
||||
|
||||
export default useAuth;
|
||||
|
||||
@@ -1,229 +1,229 @@
|
||||
import React, { useState, useContext, useEffect } from "react";
|
||||
import clsx from "clsx";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import Drawer from "@material-ui/core/Drawer";
|
||||
|
||||
import AppBar from "@material-ui/core/AppBar";
|
||||
import Toolbar from "@material-ui/core/Toolbar";
|
||||
import List from "@material-ui/core/List";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import Divider from "@material-ui/core/Divider";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import Badge from "@material-ui/core/Badge";
|
||||
|
||||
import MenuIcon from "@material-ui/icons/Menu";
|
||||
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
|
||||
import NotificationsIcon from "@material-ui/icons/Notifications";
|
||||
import MainListItems from "./MainListItems";
|
||||
import AccountCircle from "@material-ui/icons/AccountCircle";
|
||||
|
||||
import MenuItem from "@material-ui/core/MenuItem";
|
||||
import Menu from "@material-ui/core/Menu";
|
||||
|
||||
import { AuthContext } from "../../Context/Auth/AuthContext";
|
||||
|
||||
const drawerWidth = 240;
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
root: {
|
||||
display: "flex",
|
||||
height: "100vh",
|
||||
},
|
||||
|
||||
toolbar: {
|
||||
paddingRight: 24, // keep right padding when drawer closed
|
||||
},
|
||||
toolbarIcon: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
padding: "0 8px",
|
||||
...theme.mixins.toolbar,
|
||||
},
|
||||
appBar: {
|
||||
zIndex: theme.zIndex.drawer + 1,
|
||||
transition: theme.transitions.create(["width", "margin"], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.leavingScreen,
|
||||
}),
|
||||
},
|
||||
appBarShift: {
|
||||
marginLeft: drawerWidth,
|
||||
width: `calc(100% - ${drawerWidth}px)`,
|
||||
transition: theme.transitions.create(["width", "margin"], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
},
|
||||
menuButton: {
|
||||
marginRight: 36,
|
||||
},
|
||||
menuButtonHidden: {
|
||||
display: "none",
|
||||
},
|
||||
title: {
|
||||
flexGrow: 1,
|
||||
},
|
||||
drawerPaper: {
|
||||
position: "relative",
|
||||
whiteSpace: "nowrap",
|
||||
width: drawerWidth,
|
||||
transition: theme.transitions.create("width", {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
},
|
||||
drawerPaperClose: {
|
||||
overflowX: "hidden",
|
||||
transition: theme.transitions.create("width", {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.leavingScreen,
|
||||
}),
|
||||
width: theme.spacing(7),
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
width: theme.spacing(9),
|
||||
},
|
||||
},
|
||||
appBarSpacer: theme.mixins.toolbar,
|
||||
content: {
|
||||
flex: 1,
|
||||
// height: "100%",
|
||||
overflow: "auto",
|
||||
},
|
||||
container: {
|
||||
paddingTop: theme.spacing(4),
|
||||
paddingBottom: theme.spacing(4),
|
||||
},
|
||||
paper: {
|
||||
padding: theme.spacing(2),
|
||||
display: "flex",
|
||||
overflow: "auto",
|
||||
flexDirection: "column",
|
||||
},
|
||||
}));
|
||||
|
||||
const MainDrawer = ({ appTitle, children }) => {
|
||||
const { handleLogout } = useContext(AuthContext);
|
||||
const classes = useStyles();
|
||||
const [open, setOpen] = useState(true);
|
||||
const [anchorEl, setAnchorEl] = React.useState(null);
|
||||
const menuOpen = Boolean(anchorEl);
|
||||
const drawerState = localStorage.getItem("drawerOpen");
|
||||
|
||||
useEffect(() => {
|
||||
if (drawerState === "0") {
|
||||
setOpen(false);
|
||||
}
|
||||
}, [drawerState]);
|
||||
|
||||
const handleDrawerOpen = () => {
|
||||
setOpen(true);
|
||||
localStorage.setItem("drawerOpen", 1);
|
||||
};
|
||||
const handleDrawerClose = () => {
|
||||
setOpen(false);
|
||||
localStorage.setItem("drawerOpen", 0);
|
||||
};
|
||||
|
||||
const handleMenu = event => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classes.root}>
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
classes={{
|
||||
paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose),
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<div className={classes.toolbarIcon}>
|
||||
<IconButton onClick={handleDrawerClose}>
|
||||
<ChevronLeftIcon />
|
||||
</IconButton>
|
||||
</div>
|
||||
<Divider />
|
||||
<List>
|
||||
<MainListItems />
|
||||
</List>
|
||||
<Divider />
|
||||
</Drawer>
|
||||
<AppBar
|
||||
position="absolute"
|
||||
className={clsx(classes.appBar, open && classes.appBarShift)}
|
||||
>
|
||||
<Toolbar className={classes.toolbar}>
|
||||
<IconButton
|
||||
edge="start"
|
||||
color="inherit"
|
||||
aria-label="open drawer"
|
||||
onClick={handleDrawerOpen}
|
||||
className={clsx(
|
||||
classes.menuButton,
|
||||
open && classes.menuButtonHidden
|
||||
)}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h6"
|
||||
color="inherit"
|
||||
noWrap
|
||||
className={classes.title}
|
||||
>
|
||||
{appTitle}
|
||||
</Typography>
|
||||
<IconButton color="inherit">
|
||||
<Badge badgeContent={0} color="secondary">
|
||||
<NotificationsIcon />
|
||||
</Badge>
|
||||
</IconButton>
|
||||
|
||||
<div>
|
||||
<IconButton
|
||||
aria-label="account of current user"
|
||||
aria-controls="menu-appbar"
|
||||
aria-haspopup="true"
|
||||
onClick={handleMenu}
|
||||
color="inherit"
|
||||
>
|
||||
<AccountCircle />
|
||||
</IconButton>
|
||||
<Menu
|
||||
id="menu-appbar"
|
||||
anchorEl={anchorEl}
|
||||
anchorOrigin={{
|
||||
vertical: "top",
|
||||
horizontal: "right",
|
||||
}}
|
||||
keepMounted
|
||||
transformOrigin={{
|
||||
vertical: "top",
|
||||
horizontal: "right",
|
||||
}}
|
||||
open={menuOpen}
|
||||
onClose={handleClose}
|
||||
>
|
||||
<MenuItem onClick={handleClose}>Profile</MenuItem>
|
||||
<MenuItem onClick={handleLogout}>Logout</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<main className={classes.content}>
|
||||
<div className={classes.appBarSpacer} />
|
||||
|
||||
{children ? children : <h1>Dashboard</h1>}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainDrawer;
|
||||
import React, { useState, useContext, useEffect } from "react";
|
||||
import clsx from "clsx";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import Drawer from "@material-ui/core/Drawer";
|
||||
|
||||
import AppBar from "@material-ui/core/AppBar";
|
||||
import Toolbar from "@material-ui/core/Toolbar";
|
||||
import List from "@material-ui/core/List";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import Divider from "@material-ui/core/Divider";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import Badge from "@material-ui/core/Badge";
|
||||
|
||||
import MenuIcon from "@material-ui/icons/Menu";
|
||||
import ChevronLeftIcon from "@material-ui/icons/ChevronLeft";
|
||||
import NotificationsIcon from "@material-ui/icons/Notifications";
|
||||
import MainListItems from "./MainListItems";
|
||||
import AccountCircle from "@material-ui/icons/AccountCircle";
|
||||
|
||||
import MenuItem from "@material-ui/core/MenuItem";
|
||||
import Menu from "@material-ui/core/Menu";
|
||||
|
||||
import { AuthContext } from "../../Context/Auth/AuthContext";
|
||||
|
||||
const drawerWidth = 240;
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
root: {
|
||||
display: "flex",
|
||||
height: "100vh",
|
||||
},
|
||||
|
||||
toolbar: {
|
||||
paddingRight: 24, // keep right padding when drawer closed
|
||||
},
|
||||
toolbarIcon: {
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "flex-end",
|
||||
padding: "0 8px",
|
||||
...theme.mixins.toolbar,
|
||||
},
|
||||
appBar: {
|
||||
zIndex: theme.zIndex.drawer + 1,
|
||||
transition: theme.transitions.create(["width", "margin"], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.leavingScreen,
|
||||
}),
|
||||
},
|
||||
appBarShift: {
|
||||
marginLeft: drawerWidth,
|
||||
width: `calc(100% - ${drawerWidth}px)`,
|
||||
transition: theme.transitions.create(["width", "margin"], {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
},
|
||||
menuButton: {
|
||||
marginRight: 36,
|
||||
},
|
||||
menuButtonHidden: {
|
||||
display: "none",
|
||||
},
|
||||
title: {
|
||||
flexGrow: 1,
|
||||
},
|
||||
drawerPaper: {
|
||||
position: "relative",
|
||||
whiteSpace: "nowrap",
|
||||
width: drawerWidth,
|
||||
transition: theme.transitions.create("width", {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.enteringScreen,
|
||||
}),
|
||||
},
|
||||
drawerPaperClose: {
|
||||
overflowX: "hidden",
|
||||
transition: theme.transitions.create("width", {
|
||||
easing: theme.transitions.easing.sharp,
|
||||
duration: theme.transitions.duration.leavingScreen,
|
||||
}),
|
||||
width: theme.spacing(7),
|
||||
[theme.breakpoints.up("sm")]: {
|
||||
width: theme.spacing(9),
|
||||
},
|
||||
},
|
||||
appBarSpacer: theme.mixins.toolbar,
|
||||
content: {
|
||||
flex: 1,
|
||||
// height: "100%",
|
||||
overflow: "auto",
|
||||
},
|
||||
container: {
|
||||
paddingTop: theme.spacing(4),
|
||||
paddingBottom: theme.spacing(4),
|
||||
},
|
||||
paper: {
|
||||
padding: theme.spacing(2),
|
||||
display: "flex",
|
||||
overflow: "auto",
|
||||
flexDirection: "column",
|
||||
},
|
||||
}));
|
||||
|
||||
const MainDrawer = ({ appTitle, children }) => {
|
||||
const { handleLogout } = useContext(AuthContext);
|
||||
const classes = useStyles();
|
||||
const [open, setOpen] = useState(true);
|
||||
const [anchorEl, setAnchorEl] = React.useState(null);
|
||||
const menuOpen = Boolean(anchorEl);
|
||||
const drawerState = localStorage.getItem("drawerOpen");
|
||||
|
||||
useEffect(() => {
|
||||
if (drawerState === "0") {
|
||||
setOpen(false);
|
||||
}
|
||||
}, [drawerState]);
|
||||
|
||||
const handleDrawerOpen = () => {
|
||||
setOpen(true);
|
||||
localStorage.setItem("drawerOpen", 1);
|
||||
};
|
||||
const handleDrawerClose = () => {
|
||||
setOpen(false);
|
||||
localStorage.setItem("drawerOpen", 0);
|
||||
};
|
||||
|
||||
const handleMenu = event => {
|
||||
setAnchorEl(event.currentTarget);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
setAnchorEl(null);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classes.root}>
|
||||
<Drawer
|
||||
variant="permanent"
|
||||
classes={{
|
||||
paper: clsx(classes.drawerPaper, !open && classes.drawerPaperClose),
|
||||
}}
|
||||
open={open}
|
||||
>
|
||||
<div className={classes.toolbarIcon}>
|
||||
<IconButton onClick={handleDrawerClose}>
|
||||
<ChevronLeftIcon />
|
||||
</IconButton>
|
||||
</div>
|
||||
<Divider />
|
||||
<List>
|
||||
<MainListItems />
|
||||
</List>
|
||||
<Divider />
|
||||
</Drawer>
|
||||
<AppBar
|
||||
position="absolute"
|
||||
className={clsx(classes.appBar, open && classes.appBarShift)}
|
||||
>
|
||||
<Toolbar className={classes.toolbar}>
|
||||
<IconButton
|
||||
edge="start"
|
||||
color="inherit"
|
||||
aria-label="open drawer"
|
||||
onClick={handleDrawerOpen}
|
||||
className={clsx(
|
||||
classes.menuButton,
|
||||
open && classes.menuButtonHidden
|
||||
)}
|
||||
>
|
||||
<MenuIcon />
|
||||
</IconButton>
|
||||
<Typography
|
||||
component="h1"
|
||||
variant="h6"
|
||||
color="inherit"
|
||||
noWrap
|
||||
className={classes.title}
|
||||
>
|
||||
{appTitle}
|
||||
</Typography>
|
||||
<IconButton color="inherit">
|
||||
<Badge badgeContent={0} color="secondary">
|
||||
<NotificationsIcon />
|
||||
</Badge>
|
||||
</IconButton>
|
||||
|
||||
<div>
|
||||
<IconButton
|
||||
aria-label="account of current user"
|
||||
aria-controls="menu-appbar"
|
||||
aria-haspopup="true"
|
||||
onClick={handleMenu}
|
||||
color="inherit"
|
||||
>
|
||||
<AccountCircle />
|
||||
</IconButton>
|
||||
<Menu
|
||||
id="menu-appbar"
|
||||
anchorEl={anchorEl}
|
||||
anchorOrigin={{
|
||||
vertical: "top",
|
||||
horizontal: "right",
|
||||
}}
|
||||
keepMounted
|
||||
transformOrigin={{
|
||||
vertical: "top",
|
||||
horizontal: "right",
|
||||
}}
|
||||
open={menuOpen}
|
||||
onClose={handleClose}
|
||||
>
|
||||
<MenuItem onClick={handleClose}>Profile</MenuItem>
|
||||
<MenuItem onClick={handleLogout}>Logout</MenuItem>
|
||||
</Menu>
|
||||
</div>
|
||||
</Toolbar>
|
||||
</AppBar>
|
||||
<main className={classes.content}>
|
||||
<div className={classes.appBarSpacer} />
|
||||
|
||||
{children ? children : <h1>Dashboard</h1>}
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default MainDrawer;
|
||||
|
||||
@@ -1,125 +1,125 @@
|
||||
import React from "react";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import List from "@material-ui/core/List";
|
||||
import ListItem from "@material-ui/core/ListItem";
|
||||
import ListItemIcon from "@material-ui/core/ListItemIcon";
|
||||
import ListItemText from "@material-ui/core/ListItemText";
|
||||
// import ListSubheader from "@material-ui/core/ListSubheader";
|
||||
import Collapse from "@material-ui/core/Collapse";
|
||||
|
||||
import DashboardIcon from "@material-ui/icons/Dashboard";
|
||||
import WhatsAppIcon from "@material-ui/icons/WhatsApp";
|
||||
// import PeopleIcon from "@material-ui/icons/People";
|
||||
import SyncAltIcon from "@material-ui/icons/SyncAlt";
|
||||
import ChatIcon from "@material-ui/icons/Chat";
|
||||
import BarChartIcon from "@material-ui/icons/BarChart";
|
||||
import LayersIcon from "@material-ui/icons/Layers";
|
||||
// import AssignmentIcon from "@material-ui/icons/Assignment";
|
||||
import ExpandLess from "@material-ui/icons/ExpandLess";
|
||||
import ExpandMore from "@material-ui/icons/ExpandMore";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
nested: {
|
||||
paddingLeft: theme.spacing(4),
|
||||
},
|
||||
}));
|
||||
|
||||
function ListItemLink(props) {
|
||||
const { icon, primary, to, className } = props;
|
||||
|
||||
const renderLink = React.useMemo(
|
||||
() =>
|
||||
React.forwardRef((itemProps, ref) => (
|
||||
<RouterLink to={to} ref={ref} {...itemProps} />
|
||||
)),
|
||||
[to]
|
||||
);
|
||||
|
||||
return (
|
||||
<li>
|
||||
<ListItem button component={renderLink} className={className}>
|
||||
{icon ? <ListItemIcon>{icon}</ListItemIcon> : null}
|
||||
<ListItemText primary={primary} />
|
||||
</ListItem>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
const MainListItems = () => {
|
||||
const classes = useStyles();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
const handleClick = () => {
|
||||
setOpen(!open);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ListItemLink to="/" primary="Dashboard" icon={<DashboardIcon />} />
|
||||
|
||||
<ListItem button onClick={handleClick}>
|
||||
<ListItemIcon>
|
||||
<WhatsAppIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="WhatsApp" />
|
||||
{open ? <ExpandLess /> : <ExpandMore />}
|
||||
</ListItem>
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<List component="div" disablePadding>
|
||||
<ListItemLink
|
||||
className={classes.nested}
|
||||
to="/whats-auth"
|
||||
primary="Conexão"
|
||||
icon={<SyncAltIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
className={classes.nested}
|
||||
to="/chat"
|
||||
primary="Chat"
|
||||
icon={<ChatIcon />}
|
||||
/>
|
||||
</List>
|
||||
</Collapse>
|
||||
|
||||
<ListItem button disabled>
|
||||
<ListItemIcon>
|
||||
<BarChartIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="Relatórios" />
|
||||
</ListItem>
|
||||
<ListItem button disabled>
|
||||
<ListItemIcon>
|
||||
<LayersIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="Integrações" />
|
||||
</ListItem>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
// export const secondaryListItems = (
|
||||
// <div>
|
||||
// <ListSubheader inset>Saved reports</ListSubheader>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Current month" />
|
||||
// </ListItem>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Last quarter" />
|
||||
// </ListItem>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Year-end sale" />
|
||||
// </ListItem>
|
||||
// </div>
|
||||
// );
|
||||
|
||||
export default MainListItems;
|
||||
import React from "react";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import List from "@material-ui/core/List";
|
||||
import ListItem from "@material-ui/core/ListItem";
|
||||
import ListItemIcon from "@material-ui/core/ListItemIcon";
|
||||
import ListItemText from "@material-ui/core/ListItemText";
|
||||
// import ListSubheader from "@material-ui/core/ListSubheader";
|
||||
import Collapse from "@material-ui/core/Collapse";
|
||||
|
||||
import DashboardIcon from "@material-ui/icons/Dashboard";
|
||||
import WhatsAppIcon from "@material-ui/icons/WhatsApp";
|
||||
// import PeopleIcon from "@material-ui/icons/People";
|
||||
import SyncAltIcon from "@material-ui/icons/SyncAlt";
|
||||
import ChatIcon from "@material-ui/icons/Chat";
|
||||
import BarChartIcon from "@material-ui/icons/BarChart";
|
||||
import LayersIcon from "@material-ui/icons/Layers";
|
||||
// import AssignmentIcon from "@material-ui/icons/Assignment";
|
||||
import ExpandLess from "@material-ui/icons/ExpandLess";
|
||||
import ExpandMore from "@material-ui/icons/ExpandMore";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
nested: {
|
||||
paddingLeft: theme.spacing(4),
|
||||
},
|
||||
}));
|
||||
|
||||
function ListItemLink(props) {
|
||||
const { icon, primary, to, className } = props;
|
||||
|
||||
const renderLink = React.useMemo(
|
||||
() =>
|
||||
React.forwardRef((itemProps, ref) => (
|
||||
<RouterLink to={to} ref={ref} {...itemProps} />
|
||||
)),
|
||||
[to]
|
||||
);
|
||||
|
||||
return (
|
||||
<li>
|
||||
<ListItem button component={renderLink} className={className}>
|
||||
{icon ? <ListItemIcon>{icon}</ListItemIcon> : null}
|
||||
<ListItemText primary={primary} />
|
||||
</ListItem>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
const MainListItems = () => {
|
||||
const classes = useStyles();
|
||||
const [open, setOpen] = React.useState(false);
|
||||
|
||||
const handleClick = () => {
|
||||
setOpen(!open);
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<ListItemLink to="/" primary="Dashboard" icon={<DashboardIcon />} />
|
||||
|
||||
<ListItem button onClick={handleClick}>
|
||||
<ListItemIcon>
|
||||
<WhatsAppIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="WhatsApp" />
|
||||
{open ? <ExpandLess /> : <ExpandMore />}
|
||||
</ListItem>
|
||||
<Collapse in={open} timeout="auto" unmountOnExit>
|
||||
<List component="div" disablePadding>
|
||||
<ListItemLink
|
||||
className={classes.nested}
|
||||
to="/whats-auth"
|
||||
primary="Conexão"
|
||||
icon={<SyncAltIcon />}
|
||||
/>
|
||||
<ListItemLink
|
||||
className={classes.nested}
|
||||
to="/chat"
|
||||
primary="Chat"
|
||||
icon={<ChatIcon />}
|
||||
/>
|
||||
</List>
|
||||
</Collapse>
|
||||
|
||||
<ListItem button disabled>
|
||||
<ListItemIcon>
|
||||
<BarChartIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="Relatórios" />
|
||||
</ListItem>
|
||||
<ListItem button disabled>
|
||||
<ListItemIcon>
|
||||
<LayersIcon />
|
||||
</ListItemIcon>
|
||||
<ListItemText primary="Integrações" />
|
||||
</ListItem>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
// export const secondaryListItems = (
|
||||
// <div>
|
||||
// <ListSubheader inset>Saved reports</ListSubheader>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Current month" />
|
||||
// </ListItem>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Last quarter" />
|
||||
// </ListItem>
|
||||
// <ListItem button>
|
||||
// <ListItemIcon>
|
||||
// <AssignmentIcon />
|
||||
// </ListItemIcon>
|
||||
// <ListItemText primary="Year-end sale" />
|
||||
// </ListItem>
|
||||
// </div>
|
||||
// );
|
||||
|
||||
export default MainListItems;
|
||||
|
||||
@@ -1,37 +1,37 @@
|
||||
import React from "react";
|
||||
|
||||
import { Navbar, Nav, Container } from "react-bootstrap";
|
||||
import { LinkContainer } from "react-router-bootstrap";
|
||||
|
||||
const LogedinNavbar = () => {
|
||||
return (
|
||||
<div>
|
||||
<Navbar variant="dark" bg="dark" expand="lg">
|
||||
<Container>
|
||||
<LinkContainer to="/" style={{ color: "#519032" }}>
|
||||
<Navbar.Brand>EconoWhatsBot</Navbar.Brand>
|
||||
</LinkContainer>
|
||||
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
|
||||
<Navbar.Collapse id="responsive-navbar-nav">
|
||||
<Nav className="mr-auto">
|
||||
<LinkContainer to="/">
|
||||
<Nav.Link href="#home">Home</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat">
|
||||
<Nav.Link href="#link">Chat</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Nav>
|
||||
<LinkContainer to="/login">
|
||||
<Nav.Link href="#login">Login</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/signup">
|
||||
<Nav.Link href="#signup">Signup</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LogedinNavbar;
|
||||
import React from "react";
|
||||
|
||||
import { Navbar, Nav, Container } from "react-bootstrap";
|
||||
import { LinkContainer } from "react-router-bootstrap";
|
||||
|
||||
const LogedinNavbar = () => {
|
||||
return (
|
||||
<div>
|
||||
<Navbar variant="dark" bg="dark" expand="lg">
|
||||
<Container>
|
||||
<LinkContainer to="/" style={{ color: "#519032" }}>
|
||||
<Navbar.Brand>EconoWhatsBot</Navbar.Brand>
|
||||
</LinkContainer>
|
||||
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
|
||||
<Navbar.Collapse id="responsive-navbar-nav">
|
||||
<Nav className="mr-auto">
|
||||
<LinkContainer to="/">
|
||||
<Nav.Link href="#home">Home</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat">
|
||||
<Nav.Link href="#link">Chat</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Nav>
|
||||
<LinkContainer to="/login">
|
||||
<Nav.Link href="#login">Login</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/signup">
|
||||
<Nav.Link href="#signup">Signup</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LogedinNavbar;
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
import React from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { Navbar, Nav, Container } from "react-bootstrap";
|
||||
import { LinkContainer } from "react-router-bootstrap";
|
||||
import "./Navbar.css";
|
||||
|
||||
const DefaultNavbar = () => {
|
||||
const username = localStorage.getItem("username");
|
||||
const history = useHistory();
|
||||
|
||||
const handleLogout = e => {
|
||||
e.preventDefault();
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("userName");
|
||||
localStorage.removeItem("userId");
|
||||
history.push("/");
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Navbar variant="dark" bg="dark" expand="lg">
|
||||
<Container>
|
||||
<LinkContainer to="/" style={{ color: "#519032" }}>
|
||||
<Navbar.Brand>EconoWhatsBot</Navbar.Brand>
|
||||
</LinkContainer>
|
||||
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
|
||||
<Navbar.Collapse id="responsive-navbar-nav">
|
||||
<Nav className="mr-auto">
|
||||
<LinkContainer to="/">
|
||||
<Nav.Link href="#home">Home</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat">
|
||||
<Nav.Link href="#link">Chat</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat2">
|
||||
<Nav.Link href="#link">Chat MaterialUi</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Nav>
|
||||
<Navbar.Text>
|
||||
Logado como: <a href="#login">{username}</a>
|
||||
</Navbar.Text>
|
||||
<Nav.Link href="#logout" onClick={handleLogout}>
|
||||
Logout
|
||||
</Nav.Link>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DefaultNavbar;
|
||||
import React from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import { Navbar, Nav, Container } from "react-bootstrap";
|
||||
import { LinkContainer } from "react-router-bootstrap";
|
||||
import "./Navbar.css";
|
||||
|
||||
const DefaultNavbar = () => {
|
||||
const username = localStorage.getItem("username");
|
||||
const history = useHistory();
|
||||
|
||||
const handleLogout = e => {
|
||||
e.preventDefault();
|
||||
localStorage.removeItem("token");
|
||||
localStorage.removeItem("userName");
|
||||
localStorage.removeItem("userId");
|
||||
history.push("/");
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Navbar variant="dark" bg="dark" expand="lg">
|
||||
<Container>
|
||||
<LinkContainer to="/" style={{ color: "#519032" }}>
|
||||
<Navbar.Brand>EconoWhatsBot</Navbar.Brand>
|
||||
</LinkContainer>
|
||||
<Navbar.Toggle aria-controls="responsive-navbar-nav" />
|
||||
<Navbar.Collapse id="responsive-navbar-nav">
|
||||
<Nav className="mr-auto">
|
||||
<LinkContainer to="/">
|
||||
<Nav.Link href="#home">Home</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat">
|
||||
<Nav.Link href="#link">Chat</Nav.Link>
|
||||
</LinkContainer>
|
||||
<LinkContainer to="/chat2">
|
||||
<Nav.Link href="#link">Chat MaterialUi</Nav.Link>
|
||||
</LinkContainer>
|
||||
</Nav>
|
||||
<Navbar.Text>
|
||||
Logado como: <a href="#login">{username}</a>
|
||||
</Navbar.Text>
|
||||
<Nav.Link href="#logout" onClick={handleLogout}>
|
||||
Logout
|
||||
</Nav.Link>
|
||||
</Navbar.Collapse>
|
||||
</Container>
|
||||
</Navbar>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default DefaultNavbar;
|
||||
|
||||
@@ -1,85 +1,85 @@
|
||||
import React from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import ContactsList from "./components/ContactsList/ContactsList";
|
||||
import MessagesList from "./components/MessagesList/MessagesList";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
chatContainer: {
|
||||
flex: 1,
|
||||
backgroundColor: "#eee",
|
||||
// padding: 20,
|
||||
height: `calc(100% - 64px)`,
|
||||
overflowY: "hidden",
|
||||
},
|
||||
|
||||
chatPapper: {
|
||||
backgroundColor: "#eee",
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
overflowY: "hidden",
|
||||
},
|
||||
|
||||
contactsWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
messagessWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
welcomeMsg: {
|
||||
backgroundColor: "#eee",
|
||||
display: "flex",
|
||||
justifyContent: "space-evenly",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
|
||||
const Chat = () => {
|
||||
const classes = useStyles();
|
||||
const { contactId } = useParams();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="Chat">
|
||||
<div className={classes.chatContainer}>
|
||||
<Paper square className={classes.chatPapper}>
|
||||
<Grid container spacing={0}>
|
||||
<Grid item xs={4} className={classes.contactsWrapper}>
|
||||
<ContactsList />
|
||||
</Grid>
|
||||
<Grid item xs={8} className={classes.messagessWrapper}>
|
||||
{contactId ? (
|
||||
<>
|
||||
<MessagesList />
|
||||
</>
|
||||
) : (
|
||||
<Paper
|
||||
square
|
||||
variant="outlined"
|
||||
className={classes.welcomeMsg}
|
||||
>
|
||||
<span>Selecione um contato para começar a conversar</span>
|
||||
</Paper>
|
||||
)}
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Paper>
|
||||
</div>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Chat;
|
||||
import React from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import ContactsList from "./components/ContactsList/ContactsList";
|
||||
import MessagesList from "./components/MessagesList/MessagesList";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
chatContainer: {
|
||||
flex: 1,
|
||||
backgroundColor: "#eee",
|
||||
// padding: 20,
|
||||
height: `calc(100% - 64px)`,
|
||||
overflowY: "hidden",
|
||||
},
|
||||
|
||||
chatPapper: {
|
||||
backgroundColor: "#eee",
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
overflowY: "hidden",
|
||||
},
|
||||
|
||||
contactsWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
messagessWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
welcomeMsg: {
|
||||
backgroundColor: "#eee",
|
||||
display: "flex",
|
||||
justifyContent: "space-evenly",
|
||||
alignItems: "center",
|
||||
height: "100%",
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
|
||||
const Chat = () => {
|
||||
const classes = useStyles();
|
||||
const { contactId } = useParams();
|
||||
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="Chat">
|
||||
<div className={classes.chatContainer}>
|
||||
<Paper square className={classes.chatPapper}>
|
||||
<Grid container spacing={0}>
|
||||
<Grid item xs={4} className={classes.contactsWrapper}>
|
||||
<ContactsList />
|
||||
</Grid>
|
||||
<Grid item xs={8} className={classes.messagessWrapper}>
|
||||
{contactId ? (
|
||||
<>
|
||||
<MessagesList />
|
||||
</>
|
||||
) : (
|
||||
<Paper
|
||||
square
|
||||
variant="outlined"
|
||||
className={classes.welcomeMsg}
|
||||
>
|
||||
<span>Selecione um contato para começar a conversar</span>
|
||||
</Paper>
|
||||
)}
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Paper>
|
||||
</div>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Chat;
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
import React, { useState } from "react";
|
||||
import Button from "@material-ui/core/Button";
|
||||
import TextField from "@material-ui/core/TextField";
|
||||
import Dialog from "@material-ui/core/Dialog";
|
||||
import DialogActions from "@material-ui/core/DialogActions";
|
||||
import DialogContent from "@material-ui/core/DialogContent";
|
||||
import DialogTitle from "@material-ui/core/DialogTitle";
|
||||
|
||||
const AddContactModal = ({ modalOpen, setModalOpen, handleAddContact }) => {
|
||||
const initialState = { name: "", number: "" };
|
||||
const [contact, setContact] = useState(initialState);
|
||||
|
||||
const handleClose = () => {
|
||||
setModalOpen(false);
|
||||
};
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setContact({ ...contact, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<Dialog
|
||||
open={modalOpen}
|
||||
onClose={handleClose}
|
||||
aria-labelledby="form-dialog-title"
|
||||
>
|
||||
<DialogTitle id="form-dialog-title">Adicionar contato</DialogTitle>
|
||||
<DialogContent>
|
||||
<TextField
|
||||
autoComplete="false"
|
||||
autoFocus
|
||||
margin="dense"
|
||||
name="number"
|
||||
id="contactNumber"
|
||||
label="Número"
|
||||
type="text"
|
||||
value={contact.number}
|
||||
onChange={handleChangeInput}
|
||||
fullWidth
|
||||
/>
|
||||
<TextField
|
||||
margin="dense"
|
||||
name="name"
|
||||
id="contactName"
|
||||
label="Nome do contato"
|
||||
type="text"
|
||||
value={contact.name}
|
||||
onChange={handleChangeInput}
|
||||
fullWidth
|
||||
/>
|
||||
</DialogContent>
|
||||
<DialogActions>
|
||||
<Button onClick={handleClose} color="primary">
|
||||
Cancelar
|
||||
</Button>
|
||||
<Button
|
||||
onClick={e => {
|
||||
handleAddContact(contact);
|
||||
setContact(initialState);
|
||||
}}
|
||||
color="primary"
|
||||
>
|
||||
Adicionar
|
||||
</Button>
|
||||
</DialogActions>
|
||||
</Dialog>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default AddContactModal;
|
||||
@@ -1,47 +1,47 @@
|
||||
import React from "react";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Card from "@material-ui/core/Card";
|
||||
import CardHeader from "@material-ui/core/CardHeader";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import MoreVertIcon from "@material-ui/icons/MoreVert";
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
|
||||
import profileDefaultPic from "../../../../Images/profile_default.png";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contactsHeader: {
|
||||
display: "flex",
|
||||
flex: "none",
|
||||
// height: 80,
|
||||
backgroundColor: "#eee",
|
||||
borderBottomLeftRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
},
|
||||
settingsIcon: {
|
||||
alignSelf: "center",
|
||||
marginLeft: "auto",
|
||||
padding: 8,
|
||||
},
|
||||
}));
|
||||
|
||||
const ContactsHeader = () => {
|
||||
const classes = useStyles();
|
||||
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
return (
|
||||
<Card variant="outlined" square className={classes.contactsHeader}>
|
||||
<CardHeader
|
||||
avatar={<Avatar alt="logged_user" src={profileDefaultPic} />}
|
||||
title={username}
|
||||
/>
|
||||
<IconButton className={classes.settingsIcon} aria-label="settings">
|
||||
<MoreVertIcon />
|
||||
</IconButton>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactsHeader;
|
||||
import React from "react";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Card from "@material-ui/core/Card";
|
||||
import CardHeader from "@material-ui/core/CardHeader";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import MoreVertIcon from "@material-ui/icons/MoreVert";
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
|
||||
import profileDefaultPic from "../../../../Images/profile_default.png";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contactsHeader: {
|
||||
display: "flex",
|
||||
flex: "none",
|
||||
// height: 80,
|
||||
backgroundColor: "#eee",
|
||||
borderBottomLeftRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
},
|
||||
settingsIcon: {
|
||||
alignSelf: "center",
|
||||
marginLeft: "auto",
|
||||
padding: 8,
|
||||
},
|
||||
}));
|
||||
|
||||
const ContactsHeader = () => {
|
||||
const classes = useStyles();
|
||||
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
return (
|
||||
<Card variant="outlined" square className={classes.contactsHeader}>
|
||||
<CardHeader
|
||||
avatar={<Avatar alt="logged_user" src={profileDefaultPic} />}
|
||||
title={username}
|
||||
/>
|
||||
<IconButton className={classes.settingsIcon} aria-label="settings">
|
||||
<MoreVertIcon />
|
||||
</IconButton>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactsHeader;
|
||||
|
||||
@@ -1,333 +1,381 @@
|
||||
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 profileDefaultPic from "../../../../Images/profile_default.png";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import { green } from "@material-ui/core/colors";
|
||||
import CircularProgress from "@material-ui/core/CircularProgress";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import List from "@material-ui/core/List";
|
||||
import ListItem from "@material-ui/core/ListItem";
|
||||
import ListItemText from "@material-ui/core/ListItemText";
|
||||
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import Divider from "@material-ui/core/Divider";
|
||||
import Badge from "@material-ui/core/Badge";
|
||||
import SearchIcon from "@material-ui/icons/Search";
|
||||
import InputBase from "@material-ui/core/InputBase";
|
||||
|
||||
import ContactsHeader from "../ContactsHeader/ContactsHeader";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contactsWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
|
||||
contactsHeader: {
|
||||
display: "flex",
|
||||
backgroundColor: "#eee",
|
||||
borderBottomLeftRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
},
|
||||
|
||||
settingsIcon: {
|
||||
alignSelf: "center",
|
||||
marginLeft: "auto",
|
||||
padding: 8,
|
||||
},
|
||||
|
||||
contactsList: {
|
||||
position: "relative",
|
||||
borderTopLeftRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
flexGrow: 1,
|
||||
overflowY: "scroll",
|
||||
"&::-webkit-scrollbar": {
|
||||
width: "8px",
|
||||
},
|
||||
"&::-webkit-scrollbar-thumb": {
|
||||
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
|
||||
backgroundColor: "#e8e8e8",
|
||||
},
|
||||
},
|
||||
contactsSearchBox: {
|
||||
position: "relative",
|
||||
background: "#fafafa",
|
||||
padding: "10px 13px",
|
||||
},
|
||||
|
||||
serachInputWrapper: {
|
||||
background: "#fff",
|
||||
display: "flex",
|
||||
borderRadius: 40,
|
||||
padding: 4,
|
||||
},
|
||||
|
||||
searchIcon: {
|
||||
color: "grey",
|
||||
marginLeft: 6,
|
||||
marginRight: 6,
|
||||
alignSelf: "center",
|
||||
},
|
||||
|
||||
contactsSearchInput: {
|
||||
flex: 1,
|
||||
border: "none",
|
||||
borderRadius: 30,
|
||||
},
|
||||
|
||||
contactNameWrapper: {
|
||||
display: "flex",
|
||||
// display: "inline",
|
||||
},
|
||||
|
||||
lastMessageTime: {
|
||||
marginLeft: "auto",
|
||||
},
|
||||
|
||||
contactLastMessage: {
|
||||
paddingRight: 20,
|
||||
},
|
||||
|
||||
newMessagesCount: {
|
||||
alignSelf: "center",
|
||||
marginRight: 8,
|
||||
marginLeft: "auto",
|
||||
},
|
||||
|
||||
badgeStyle: {
|
||||
color: "white",
|
||||
backgroundColor: green[500],
|
||||
},
|
||||
circleLoading: {
|
||||
color: green[500],
|
||||
opacity: "70%",
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: "50%",
|
||||
marginTop: 12,
|
||||
// marginLeft: -12,
|
||||
},
|
||||
}));
|
||||
|
||||
const ContactsList = () => {
|
||||
const classes = useStyles();
|
||||
const token = localStorage.getItem("token");
|
||||
const { contactId } = useParams();
|
||||
const [contacts, setContacts] = useState([]);
|
||||
const [loading, setLoading] = useState();
|
||||
const [searchParam, setSearchParam] = useState("");
|
||||
|
||||
const history = useHistory();
|
||||
|
||||
useEffect(() => {
|
||||
if (!("Notification" in window)) {
|
||||
console.log("Esse navegador não suporte notificações");
|
||||
} else {
|
||||
Notification.requestPermission();
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
const delayDebounceFn = setTimeout(() => {
|
||||
const fetchContacts = async () => {
|
||||
try {
|
||||
const res = await api.get("/contacts", {
|
||||
params: { searchParam },
|
||||
});
|
||||
setContacts(res.data);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
};
|
||||
fetchContacts();
|
||||
}, 1000);
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [searchParam, token]);
|
||||
|
||||
useEffect(() => {
|
||||
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
|
||||
|
||||
socket.emit("joinNotification");
|
||||
|
||||
socket.on("contact", data => {
|
||||
if (data.action === "updateUnread") {
|
||||
resetUnreadMessages(data.contactId);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("appMessage", data => {
|
||||
if (data.action === "create") {
|
||||
updateUnreadMessagesCount(data);
|
||||
if (
|
||||
contactId &&
|
||||
data.message.contactId === +contactId &&
|
||||
document.visibilityState === "visible"
|
||||
)
|
||||
return;
|
||||
showDesktopNotification(data);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [contactId]);
|
||||
|
||||
const updateUnreadMessagesCount = data => {
|
||||
setContacts(prevState => {
|
||||
const contactIndex = prevState.findIndex(
|
||||
contact => contact.id === data.message.contactId
|
||||
);
|
||||
|
||||
if (contactIndex !== -1) {
|
||||
let aux = [...prevState];
|
||||
aux[contactIndex].unreadMessages++;
|
||||
aux[contactIndex].lastMessage = data.message.messageBody;
|
||||
aux.unshift(aux.splice(contactIndex, 1)[0]);
|
||||
return aux;
|
||||
} else {
|
||||
return [data.contact, ...prevState];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const showDesktopNotification = data => {
|
||||
const options = {
|
||||
body: `${data.message.messageBody} - ${moment(new Date())
|
||||
.tz("America/Sao_Paulo")
|
||||
.format("DD/MM/YY - HH:mm")}`,
|
||||
icon: data.contact.imageURL,
|
||||
};
|
||||
new Notification(`Mensagem de ${data.contact.name}`, options);
|
||||
document.getElementById("sound").play();
|
||||
};
|
||||
|
||||
const resetUnreadMessages = contactId => {
|
||||
setContacts(prevState => {
|
||||
let aux = [...prevState];
|
||||
let contactIndex = aux.findIndex(contact => contact.id === +contactId);
|
||||
aux[contactIndex].unreadMessages = 0;
|
||||
|
||||
return aux;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSelectContact = (e, contact) => {
|
||||
history.push(`/chat/${contact.id}`);
|
||||
};
|
||||
|
||||
const handleSearchContact = e => {
|
||||
// let searchTerm = e.target.value.toLowerCase();
|
||||
setSearchParam(e.target.value.toLowerCase());
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classes.contactsWrapper}>
|
||||
<ContactsHeader />
|
||||
<Paper variant="outlined" square className={classes.contactsSearchBox}>
|
||||
<div className={classes.serachInputWrapper}>
|
||||
<SearchIcon className={classes.searchIcon} />
|
||||
<InputBase
|
||||
className={classes.contactsSearchInput}
|
||||
placeholder="Buscar contatos"
|
||||
type="search"
|
||||
onChange={handleSearchContact}
|
||||
/>
|
||||
</div>
|
||||
</Paper>
|
||||
<Paper variant="outlined" className={classes.contactsList}>
|
||||
<List>
|
||||
{contacts.map((contact, index) => (
|
||||
<React.Fragment key={contact.id}>
|
||||
<ListItem
|
||||
button
|
||||
onClick={e => handleSelectContact(e, contact)}
|
||||
selected={contactId && +contactId === contact.id}
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<Avatar
|
||||
src={
|
||||
contact.imageURL ? contact.imageURL : profileDefaultPic
|
||||
}
|
||||
></Avatar>
|
||||
</ListItemAvatar>
|
||||
<ListItemText
|
||||
primary={
|
||||
<span className={classes.contactNameWrapper}>
|
||||
<Typography
|
||||
noWrap
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textPrimary"
|
||||
>
|
||||
{contact.name}
|
||||
</Typography>
|
||||
{contact.lastMessage && (
|
||||
<Typography
|
||||
className={classes.lastMessageTime}
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textSecondary"
|
||||
>
|
||||
{moment(contact.updatedAt)
|
||||
.tz("America/Sao_Paulo")
|
||||
.format("HH:mm")}
|
||||
</Typography>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
secondary={
|
||||
<span className={classes.contactNameWrapper}>
|
||||
<Typography
|
||||
className={classes.contactLastMessage}
|
||||
noWrap
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textSecondary"
|
||||
>
|
||||
{contact.lastMessage || <br />}
|
||||
</Typography>
|
||||
<Badge
|
||||
className={classes.newMessagesCount}
|
||||
badgeContent={contact.unreadMessages}
|
||||
classes={{
|
||||
badge: classes.badgeStyle,
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
<Divider variant="inset" component="li" />
|
||||
</React.Fragment>
|
||||
))}
|
||||
</List>
|
||||
{loading ? (
|
||||
<div>
|
||||
<CircularProgress className={classes.circleLoading} />
|
||||
</div>
|
||||
) : null}
|
||||
</Paper>
|
||||
<audio id="sound" preload="auto">
|
||||
<source src={require("../../../../util/sound.mp3")} type="audio/mpeg" />
|
||||
<source src={require("../../../../util/sound.ogg")} type="audio/ogg" />
|
||||
<embed hidden={true} autostart="false" loop={false} src="./sound.mp3" />
|
||||
</audio>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactsList;
|
||||
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 profileDefaultPic from "../../../../Images/profile_default.png";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import { green } from "@material-ui/core/colors";
|
||||
import CircularProgress from "@material-ui/core/CircularProgress";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import List from "@material-ui/core/List";
|
||||
import ListItem from "@material-ui/core/ListItem";
|
||||
import ListItemText from "@material-ui/core/ListItemText";
|
||||
import ListItemAvatar from "@material-ui/core/ListItemAvatar";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import AddIcon from "@material-ui/icons/Add";
|
||||
import Divider from "@material-ui/core/Divider";
|
||||
import Badge from "@material-ui/core/Badge";
|
||||
import SearchIcon from "@material-ui/icons/Search";
|
||||
import InputBase from "@material-ui/core/InputBase";
|
||||
import Fab from "@material-ui/core/Fab";
|
||||
import AddContactModal from "../AddContact/AddContactModal";
|
||||
|
||||
import ContactsHeader from "../ContactsHeader/ContactsHeader";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
contactsWrapper: {
|
||||
display: "flex",
|
||||
height: "100%",
|
||||
flexDirection: "column",
|
||||
overflow: "hidden",
|
||||
},
|
||||
|
||||
contactsHeader: {
|
||||
display: "flex",
|
||||
backgroundColor: "#eee",
|
||||
borderBottomLeftRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
},
|
||||
|
||||
settingsIcon: {
|
||||
alignSelf: "center",
|
||||
marginLeft: "auto",
|
||||
padding: 8,
|
||||
},
|
||||
|
||||
contactsList: {
|
||||
position: "relative",
|
||||
borderTopLeftRadius: 0,
|
||||
borderTopRightRadius: 0,
|
||||
borderBottomRightRadius: 0,
|
||||
flexGrow: 1,
|
||||
overflowY: "scroll",
|
||||
"&::-webkit-scrollbar": {
|
||||
width: "8px",
|
||||
},
|
||||
"&::-webkit-scrollbar-thumb": {
|
||||
boxShadow: "inset 0 0 6px rgba(0, 0, 0, 0.3)",
|
||||
backgroundColor: "#e8e8e8",
|
||||
},
|
||||
},
|
||||
contactsSearchBox: {
|
||||
position: "relative",
|
||||
background: "#fafafa",
|
||||
padding: "10px 13px",
|
||||
},
|
||||
|
||||
serachInputWrapper: {
|
||||
background: "#fff",
|
||||
display: "flex",
|
||||
borderRadius: 40,
|
||||
padding: 4,
|
||||
},
|
||||
|
||||
searchIcon: {
|
||||
color: "grey",
|
||||
marginLeft: 6,
|
||||
marginRight: 6,
|
||||
alignSelf: "center",
|
||||
},
|
||||
|
||||
contactsSearchInput: {
|
||||
flex: 1,
|
||||
border: "none",
|
||||
borderRadius: 30,
|
||||
},
|
||||
|
||||
contactNameWrapper: {
|
||||
display: "flex",
|
||||
// display: "inline",
|
||||
},
|
||||
|
||||
lastMessageTime: {
|
||||
marginLeft: "auto",
|
||||
},
|
||||
|
||||
contactLastMessage: {
|
||||
paddingRight: 20,
|
||||
},
|
||||
|
||||
newMessagesCount: {
|
||||
alignSelf: "center",
|
||||
marginRight: 8,
|
||||
marginLeft: "auto",
|
||||
},
|
||||
|
||||
badgeStyle: {
|
||||
color: "white",
|
||||
backgroundColor: green[500],
|
||||
},
|
||||
circleLoading: {
|
||||
color: green[500],
|
||||
opacity: "70%",
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: "50%",
|
||||
marginTop: 12,
|
||||
// marginLeft: -12,
|
||||
},
|
||||
fabButton: {
|
||||
position: "absolute",
|
||||
zIndex: 1,
|
||||
bottom: 20,
|
||||
left: 0,
|
||||
right: 0,
|
||||
margin: "0 auto",
|
||||
},
|
||||
}));
|
||||
|
||||
const ContactsList = () => {
|
||||
const classes = useStyles();
|
||||
const token = localStorage.getItem("token");
|
||||
const { contactId } = useParams();
|
||||
const [contacts, setContacts] = useState([]);
|
||||
const [loading, setLoading] = useState();
|
||||
const [searchParam, setSearchParam] = useState("");
|
||||
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
|
||||
const history = useHistory();
|
||||
|
||||
useEffect(() => {
|
||||
if (!("Notification" in window)) {
|
||||
console.log("Esse navegador não suporte notificações");
|
||||
} else {
|
||||
Notification.requestPermission();
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
setLoading(true);
|
||||
const delayDebounceFn = setTimeout(() => {
|
||||
const fetchContacts = async () => {
|
||||
try {
|
||||
const res = await api.get("/contacts", {
|
||||
params: { searchParam },
|
||||
});
|
||||
setContacts(res.data);
|
||||
setLoading(false);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
};
|
||||
fetchContacts();
|
||||
}, 1000);
|
||||
return () => clearTimeout(delayDebounceFn);
|
||||
}, [searchParam, token]);
|
||||
|
||||
useEffect(() => {
|
||||
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
|
||||
|
||||
socket.emit("joinNotification");
|
||||
|
||||
socket.on("contact", data => {
|
||||
if (data.action === "updateUnread") {
|
||||
resetUnreadMessages(data.contactId);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("appMessage", data => {
|
||||
if (data.action === "create") {
|
||||
updateUnreadMessagesCount(data);
|
||||
if (
|
||||
contactId &&
|
||||
data.message.contactId === +contactId &&
|
||||
document.visibilityState === "visible"
|
||||
)
|
||||
return;
|
||||
showDesktopNotification(data);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [contactId]);
|
||||
|
||||
const updateUnreadMessagesCount = data => {
|
||||
setContacts(prevState => {
|
||||
const contactIndex = prevState.findIndex(
|
||||
contact => contact.id === data.message.contactId
|
||||
);
|
||||
|
||||
if (contactIndex !== -1) {
|
||||
let aux = [...prevState];
|
||||
aux[contactIndex].unreadMessages++;
|
||||
aux[contactIndex].lastMessage = data.message.messageBody;
|
||||
aux.unshift(aux.splice(contactIndex, 1)[0]);
|
||||
return aux;
|
||||
} else {
|
||||
return [data.contact, ...prevState];
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const showDesktopNotification = data => {
|
||||
const options = {
|
||||
body: `${data.message.messageBody} - ${moment(new Date())
|
||||
.tz("America/Sao_Paulo")
|
||||
.format("DD/MM/YY - HH:mm")}`,
|
||||
icon: data.contact.profilePicUrl,
|
||||
};
|
||||
new Notification(`Mensagem de ${data.contact.name}`, options);
|
||||
document.getElementById("sound").play();
|
||||
};
|
||||
|
||||
const resetUnreadMessages = contactId => {
|
||||
setContacts(prevState => {
|
||||
let aux = [...prevState];
|
||||
let contactIndex = aux.findIndex(contact => contact.id === +contactId);
|
||||
aux[contactIndex].unreadMessages = 0;
|
||||
|
||||
return aux;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSelectContact = (e, contact) => {
|
||||
history.push(`/chat/${contact.id}`);
|
||||
};
|
||||
|
||||
const handleSearchContact = e => {
|
||||
// let searchTerm = e.target.value.toLowerCase();
|
||||
setSearchParam(e.target.value.toLowerCase());
|
||||
};
|
||||
|
||||
const handleShowContactModal = e => {
|
||||
setModalOpen(true);
|
||||
};
|
||||
|
||||
const handleAddContact = async contact => {
|
||||
try {
|
||||
const res = await api.post("/contacts", contact);
|
||||
setContacts(prevState => [res.data, ...prevState]);
|
||||
setModalOpen(false);
|
||||
console.log(res.data);
|
||||
} catch (err) {
|
||||
if (err.response.status === 422) {
|
||||
console.log("deu erro", err.response);
|
||||
alert(err.response.data.message);
|
||||
} else {
|
||||
alert(err);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={classes.contactsWrapper}>
|
||||
<ContactsHeader />
|
||||
<AddContactModal
|
||||
setModalOpen={setModalOpen}
|
||||
modalOpen={modalOpen}
|
||||
handleAddContact={handleAddContact}
|
||||
/>
|
||||
<Paper variant="outlined" square className={classes.contactsSearchBox}>
|
||||
<div className={classes.serachInputWrapper}>
|
||||
<SearchIcon className={classes.searchIcon} />
|
||||
<InputBase
|
||||
className={classes.contactsSearchInput}
|
||||
placeholder="Buscar contatos"
|
||||
type="search"
|
||||
onChange={handleSearchContact}
|
||||
/>
|
||||
</div>
|
||||
</Paper>
|
||||
<Paper variant="outlined" className={classes.contactsList}>
|
||||
<List>
|
||||
{contacts.map((contact, index) => (
|
||||
<React.Fragment key={contact.id}>
|
||||
<ListItem
|
||||
button
|
||||
onClick={e => handleSelectContact(e, contact)}
|
||||
selected={contactId && +contactId === contact.id}
|
||||
>
|
||||
<ListItemAvatar>
|
||||
<Avatar
|
||||
src={
|
||||
contact.profilePicUrl
|
||||
? contact.profilePicUrl
|
||||
: profileDefaultPic
|
||||
}
|
||||
></Avatar>
|
||||
</ListItemAvatar>
|
||||
<ListItemText
|
||||
primary={
|
||||
<span className={classes.contactNameWrapper}>
|
||||
<Typography
|
||||
noWrap
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textPrimary"
|
||||
>
|
||||
{contact.name}
|
||||
</Typography>
|
||||
{contact.lastMessage && (
|
||||
<Typography
|
||||
className={classes.lastMessageTime}
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textSecondary"
|
||||
>
|
||||
{moment(contact.updatedAt)
|
||||
.tz("America/Sao_Paulo")
|
||||
.format("HH:mm")}
|
||||
</Typography>
|
||||
)}
|
||||
</span>
|
||||
}
|
||||
secondary={
|
||||
<span className={classes.contactNameWrapper}>
|
||||
<Typography
|
||||
className={classes.contactLastMessage}
|
||||
noWrap
|
||||
component="span"
|
||||
variant="body2"
|
||||
color="textSecondary"
|
||||
>
|
||||
{contact.lastMessage || <br />}
|
||||
</Typography>
|
||||
<Badge
|
||||
className={classes.newMessagesCount}
|
||||
badgeContent={contact.unreadMessages}
|
||||
classes={{
|
||||
badge: classes.badgeStyle,
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</ListItem>
|
||||
<Divider variant="inset" component="li" />
|
||||
</React.Fragment>
|
||||
))}
|
||||
</List>
|
||||
{loading ? (
|
||||
<div>
|
||||
<CircularProgress className={classes.circleLoading} />
|
||||
</div>
|
||||
) : null}
|
||||
<Fab
|
||||
color="secondary"
|
||||
aria-label="add"
|
||||
className={classes.fabButton}
|
||||
onClick={handleShowContactModal}
|
||||
>
|
||||
<AddIcon />
|
||||
</Fab>
|
||||
</Paper>
|
||||
<audio id="sound" preload="auto">
|
||||
<source src={require("../../../../util/sound.mp3")} type="audio/mpeg" />
|
||||
<source src={require("../../../../util/sound.ogg")} type="audio/ogg" />
|
||||
<embed hidden={true} autostart="false" loop={false} src="./sound.mp3" />
|
||||
</audio>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default ContactsList;
|
||||
|
||||
@@ -1,254 +1,254 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import api from "../../../../util/api";
|
||||
import "emoji-mart/css/emoji-mart.css";
|
||||
import { Picker } from "emoji-mart";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import InputBase from "@material-ui/core/InputBase";
|
||||
import CircularProgress from "@material-ui/core/CircularProgress";
|
||||
import { green } from "@material-ui/core/colors";
|
||||
|
||||
import AttachFileIcon from "@material-ui/icons/AttachFile";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import MoodIcon from "@material-ui/icons/Mood";
|
||||
import SendIcon from "@material-ui/icons/Send";
|
||||
import CancelIcon from "@material-ui/icons/Cancel";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
newMessageBox: {
|
||||
background: "#eee",
|
||||
display: "flex",
|
||||
padding: "10px",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
messageInputWrapper: {
|
||||
padding: 6,
|
||||
background: "#fff",
|
||||
display: "flex",
|
||||
borderRadius: 40,
|
||||
flex: 1,
|
||||
},
|
||||
|
||||
messageInput: {
|
||||
paddingLeft: 10,
|
||||
flex: 1,
|
||||
border: "none",
|
||||
},
|
||||
|
||||
sendMessageIcons: {
|
||||
color: "grey",
|
||||
},
|
||||
|
||||
uploadInput: {
|
||||
display: "none",
|
||||
},
|
||||
|
||||
viewMediaInputWrapper: {
|
||||
display: "flex",
|
||||
padding: "10px 13px",
|
||||
position: "relative",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
backgroundColor: "#eee",
|
||||
},
|
||||
|
||||
emojiBox: {
|
||||
position: "absolute",
|
||||
bottom: 63,
|
||||
width: 40,
|
||||
borderTop: "1px solid #e8e8e8",
|
||||
},
|
||||
|
||||
circleLoading: {
|
||||
color: green[500],
|
||||
opacity: "70%",
|
||||
position: "absolute",
|
||||
top: "20%",
|
||||
left: "50%",
|
||||
// marginTop: 8,
|
||||
// marginBottom: 6,
|
||||
marginLeft: -12,
|
||||
},
|
||||
}));
|
||||
|
||||
const MessagesInput = ({ searchParam }) => {
|
||||
const classes = useStyles();
|
||||
const { contactId } = useParams();
|
||||
const userId = localStorage.getItem("userId");
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
const mediaInitialState = { preview: "", raw: "", name: "" };
|
||||
const [media, setMedia] = useState(mediaInitialState);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
const [showEmoji, setShowEmoji] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setInputMessage("");
|
||||
setShowEmoji(false);
|
||||
setMedia({});
|
||||
};
|
||||
}, [contactId]);
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setInputMessage(e.target.value);
|
||||
};
|
||||
|
||||
const handleAddEmoji = e => {
|
||||
let emoji = e.native;
|
||||
setInputMessage(prevState => prevState + emoji);
|
||||
};
|
||||
|
||||
const handleChangeMedia = e => {
|
||||
if (e.target.files.length) {
|
||||
setMedia({
|
||||
preview: URL.createObjectURL(e.target.files[0]),
|
||||
raw: e.target.files[0],
|
||||
name: e.target.files[0].name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputPaste = e => {
|
||||
if (e.clipboardData.files[0]) {
|
||||
setMedia({
|
||||
preview: URL.createObjectURL(e.clipboardData.files[0]),
|
||||
raw: e.clipboardData.files[0],
|
||||
name: e.clipboardData.files[0].name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleUploadMedia = async e => {
|
||||
setLoading(true);
|
||||
e.preventDefault();
|
||||
const formData = new FormData();
|
||||
formData.append("media", media.raw);
|
||||
formData.append("userId", userId);
|
||||
formData.append("messageBody", media.name);
|
||||
|
||||
try {
|
||||
await api.post(`/messages/${contactId}`, formData);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
alert(err);
|
||||
}
|
||||
setLoading(false);
|
||||
setMedia(mediaInitialState);
|
||||
};
|
||||
|
||||
const handleSendMessage = async () => {
|
||||
if (inputMessage.trim() === "") return;
|
||||
const message = {
|
||||
read: 1,
|
||||
userId: userId,
|
||||
mediaUrl: "",
|
||||
messageBody: `${username}: ${inputMessage.trim()}`,
|
||||
};
|
||||
try {
|
||||
await api.post(`/messages/${contactId}`, message);
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
setInputMessage("");
|
||||
setShowEmoji(false);
|
||||
};
|
||||
|
||||
if (media.preview)
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
square
|
||||
className={classes.viewMediaInputWrapper}
|
||||
>
|
||||
<IconButton
|
||||
aria-label="cancel-upload"
|
||||
component="span"
|
||||
onClick={e => setMedia(mediaInitialState)}
|
||||
>
|
||||
<CancelIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
|
||||
{loading ? (
|
||||
<div>
|
||||
<CircularProgress className={classes.circleLoading} />
|
||||
</div>
|
||||
) : (
|
||||
<span>
|
||||
{media.name}
|
||||
{/* <img src={media.preview} alt=""></img> */}
|
||||
</span>
|
||||
)}
|
||||
<IconButton
|
||||
aria-label="send-upload"
|
||||
component="span"
|
||||
onClick={handleUploadMedia}
|
||||
>
|
||||
<SendIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</Paper>
|
||||
);
|
||||
else {
|
||||
return (
|
||||
<Paper variant="outlined" square className={classes.newMessageBox}>
|
||||
<IconButton
|
||||
aria-label="emojiPicker"
|
||||
component="span"
|
||||
onClick={e => setShowEmoji(prevState => !prevState)}
|
||||
>
|
||||
<MoodIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
{showEmoji ? (
|
||||
<div className={classes.emojiBox}>
|
||||
<Picker
|
||||
perLine={16}
|
||||
showPreview={false}
|
||||
showSkinTones={false}
|
||||
onSelect={handleAddEmoji}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<input
|
||||
type="file"
|
||||
id="upload-button"
|
||||
className={classes.uploadInput}
|
||||
onChange={handleChangeMedia}
|
||||
/>
|
||||
<label htmlFor="upload-button">
|
||||
<IconButton aria-label="upload" component="span">
|
||||
<AttachFileIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</label>
|
||||
<div className={classes.messageInputWrapper}>
|
||||
<InputBase
|
||||
inputRef={input => input && !searchParam && input.focus()}
|
||||
className={classes.messageInput}
|
||||
placeholder="Escreva uma mensagem"
|
||||
value={inputMessage}
|
||||
onChange={handleChangeInput}
|
||||
onPaste={handleInputPaste}
|
||||
onKeyPress={e => {
|
||||
if (e.key === "Enter") {
|
||||
handleSendMessage();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<IconButton
|
||||
aria-label="emojiPicker"
|
||||
component="span"
|
||||
onClick={handleSendMessage}
|
||||
>
|
||||
<SendIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default MessagesInput;
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useParams } from "react-router-dom";
|
||||
import api from "../../../../util/api";
|
||||
import "emoji-mart/css/emoji-mart.css";
|
||||
import { Picker } from "emoji-mart";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import InputBase from "@material-ui/core/InputBase";
|
||||
import CircularProgress from "@material-ui/core/CircularProgress";
|
||||
import { green } from "@material-ui/core/colors";
|
||||
|
||||
import AttachFileIcon from "@material-ui/icons/AttachFile";
|
||||
import IconButton from "@material-ui/core/IconButton";
|
||||
import MoodIcon from "@material-ui/icons/Mood";
|
||||
import SendIcon from "@material-ui/icons/Send";
|
||||
import CancelIcon from "@material-ui/icons/Cancel";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
newMessageBox: {
|
||||
background: "#eee",
|
||||
display: "flex",
|
||||
padding: "10px",
|
||||
alignItems: "center",
|
||||
},
|
||||
|
||||
messageInputWrapper: {
|
||||
padding: 6,
|
||||
background: "#fff",
|
||||
display: "flex",
|
||||
borderRadius: 40,
|
||||
flex: 1,
|
||||
},
|
||||
|
||||
messageInput: {
|
||||
paddingLeft: 10,
|
||||
flex: 1,
|
||||
border: "none",
|
||||
},
|
||||
|
||||
sendMessageIcons: {
|
||||
color: "grey",
|
||||
},
|
||||
|
||||
uploadInput: {
|
||||
display: "none",
|
||||
},
|
||||
|
||||
viewMediaInputWrapper: {
|
||||
display: "flex",
|
||||
padding: "10px 13px",
|
||||
position: "relative",
|
||||
justifyContent: "space-between",
|
||||
alignItems: "center",
|
||||
backgroundColor: "#eee",
|
||||
},
|
||||
|
||||
emojiBox: {
|
||||
position: "absolute",
|
||||
bottom: 63,
|
||||
width: 40,
|
||||
borderTop: "1px solid #e8e8e8",
|
||||
},
|
||||
|
||||
circleLoading: {
|
||||
color: green[500],
|
||||
opacity: "70%",
|
||||
position: "absolute",
|
||||
top: "20%",
|
||||
left: "50%",
|
||||
// marginTop: 8,
|
||||
// marginBottom: 6,
|
||||
marginLeft: -12,
|
||||
},
|
||||
}));
|
||||
|
||||
const MessagesInput = ({ searchParam }) => {
|
||||
const classes = useStyles();
|
||||
const { contactId } = useParams();
|
||||
const userId = localStorage.getItem("userId");
|
||||
const username = localStorage.getItem("username");
|
||||
|
||||
const mediaInitialState = { preview: "", raw: "", name: "" };
|
||||
const [media, setMedia] = useState(mediaInitialState);
|
||||
const [inputMessage, setInputMessage] = useState("");
|
||||
const [showEmoji, setShowEmoji] = useState(false);
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
setInputMessage("");
|
||||
setShowEmoji(false);
|
||||
setMedia({});
|
||||
};
|
||||
}, [contactId]);
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setInputMessage(e.target.value);
|
||||
};
|
||||
|
||||
const handleAddEmoji = e => {
|
||||
let emoji = e.native;
|
||||
setInputMessage(prevState => prevState + emoji);
|
||||
};
|
||||
|
||||
const handleChangeMedia = e => {
|
||||
if (e.target.files.length) {
|
||||
setMedia({
|
||||
preview: URL.createObjectURL(e.target.files[0]),
|
||||
raw: e.target.files[0],
|
||||
name: e.target.files[0].name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleInputPaste = e => {
|
||||
if (e.clipboardData.files[0]) {
|
||||
setMedia({
|
||||
preview: URL.createObjectURL(e.clipboardData.files[0]),
|
||||
raw: e.clipboardData.files[0],
|
||||
name: e.clipboardData.files[0].name,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const handleUploadMedia = async e => {
|
||||
setLoading(true);
|
||||
e.preventDefault();
|
||||
const formData = new FormData();
|
||||
formData.append("media", media.raw);
|
||||
formData.append("userId", userId);
|
||||
formData.append("messageBody", media.name);
|
||||
|
||||
try {
|
||||
await api.post(`/messages/${contactId}`, formData);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
alert(err);
|
||||
}
|
||||
setLoading(false);
|
||||
setMedia(mediaInitialState);
|
||||
};
|
||||
|
||||
const handleSendMessage = async () => {
|
||||
if (inputMessage.trim() === "") return;
|
||||
const message = {
|
||||
read: 1,
|
||||
userId: userId,
|
||||
mediaUrl: "",
|
||||
messageBody: `${username}: ${inputMessage.trim()}`,
|
||||
};
|
||||
try {
|
||||
await api.post(`/messages/${contactId}`, message);
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
setInputMessage("");
|
||||
setShowEmoji(false);
|
||||
};
|
||||
|
||||
if (media.preview)
|
||||
return (
|
||||
<Paper
|
||||
variant="outlined"
|
||||
square
|
||||
className={classes.viewMediaInputWrapper}
|
||||
>
|
||||
<IconButton
|
||||
aria-label="cancel-upload"
|
||||
component="span"
|
||||
onClick={e => setMedia(mediaInitialState)}
|
||||
>
|
||||
<CancelIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
|
||||
{loading ? (
|
||||
<div>
|
||||
<CircularProgress className={classes.circleLoading} />
|
||||
</div>
|
||||
) : (
|
||||
<span>
|
||||
{media.name}
|
||||
{/* <img src={media.preview} alt=""></img> */}
|
||||
</span>
|
||||
)}
|
||||
<IconButton
|
||||
aria-label="send-upload"
|
||||
component="span"
|
||||
onClick={handleUploadMedia}
|
||||
>
|
||||
<SendIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</Paper>
|
||||
);
|
||||
else {
|
||||
return (
|
||||
<Paper variant="outlined" square className={classes.newMessageBox}>
|
||||
<IconButton
|
||||
aria-label="emojiPicker"
|
||||
component="span"
|
||||
onClick={e => setShowEmoji(prevState => !prevState)}
|
||||
>
|
||||
<MoodIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
{showEmoji ? (
|
||||
<div className={classes.emojiBox}>
|
||||
<Picker
|
||||
perLine={16}
|
||||
showPreview={false}
|
||||
showSkinTones={false}
|
||||
onSelect={handleAddEmoji}
|
||||
/>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<input
|
||||
type="file"
|
||||
id="upload-button"
|
||||
className={classes.uploadInput}
|
||||
onChange={handleChangeMedia}
|
||||
/>
|
||||
<label htmlFor="upload-button">
|
||||
<IconButton aria-label="upload" component="span">
|
||||
<AttachFileIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</label>
|
||||
<div className={classes.messageInputWrapper}>
|
||||
<InputBase
|
||||
inputRef={input => input && !searchParam && input.focus()}
|
||||
className={classes.messageInput}
|
||||
placeholder="Escreva uma mensagem"
|
||||
value={inputMessage}
|
||||
onChange={handleChangeInput}
|
||||
onPaste={handleInputPaste}
|
||||
onKeyPress={e => {
|
||||
if (e.key === "Enter") {
|
||||
handleSendMessage();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<IconButton
|
||||
aria-label="emojiPicker"
|
||||
component="span"
|
||||
onClick={handleSendMessage}
|
||||
>
|
||||
<SendIcon className={classes.sendMessageIcons} />
|
||||
</IconButton>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export default MessagesInput;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,14 +1,14 @@
|
||||
import React from "react";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
|
||||
const Dashboard = () => {
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="Dashboard">
|
||||
<h1>Todo Dashboard</h1>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
import React from "react";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
|
||||
const Dashboard = () => {
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="Dashboard">
|
||||
<h1>Todo Dashboard</h1>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Dashboard;
|
||||
|
||||
@@ -1,144 +1,144 @@
|
||||
import React, { useState, useContext } from "react";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import Button from "@material-ui/core/Button";
|
||||
import CssBaseline from "@material-ui/core/CssBaseline";
|
||||
import TextField from "@material-ui/core/TextField";
|
||||
// import FormControlLabel from "@material-ui/core/FormControlLabel";
|
||||
// import Checkbox from "@material-ui/core/Checkbox";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Box from "@material-ui/core/Box";
|
||||
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Container from "@material-ui/core/Container";
|
||||
|
||||
import { AuthContext } from "../../Context/Auth/AuthContext";
|
||||
|
||||
const Copyright = () => {
|
||||
return (
|
||||
<Typography variant="body2" color="textSecondary" align="center">
|
||||
{"Copyright © "}
|
||||
<Link color="inherit" href="https://material-ui.com/">
|
||||
Canove
|
||||
</Link>{" "}
|
||||
{new Date().getFullYear()}
|
||||
{"."}
|
||||
</Typography>
|
||||
);
|
||||
};
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
paper: {
|
||||
marginTop: theme.spacing(8),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
},
|
||||
avatar: {
|
||||
margin: theme.spacing(1),
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
},
|
||||
form: {
|
||||
width: "100%", // Fix IE 11 issue.
|
||||
marginTop: theme.spacing(1),
|
||||
},
|
||||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
}));
|
||||
|
||||
const Login = ({ showToast }) => {
|
||||
const classes = useStyles();
|
||||
|
||||
const [user, setUser] = useState({ email: "", password: "" });
|
||||
|
||||
const { handleLogin } = useContext(AuthContext);
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setUser({ ...user, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline />
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon />
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Login
|
||||
</Typography>
|
||||
<form
|
||||
className={classes.form}
|
||||
noValidate
|
||||
onSubmit={e => handleLogin(e, user)}
|
||||
>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
id="email"
|
||||
label="Email"
|
||||
name="email"
|
||||
value={user.email}
|
||||
onChange={handleChangeInput}
|
||||
autoComplete="email"
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
name="password"
|
||||
label="Senha"
|
||||
type="password"
|
||||
id="password"
|
||||
value={user.password}
|
||||
onChange={handleChangeInput}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
{/* <FormControlLabel
|
||||
control={<Checkbox value="remember" color="primary" />}
|
||||
label="Lembrar"
|
||||
/> */}
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
className={classes.submit}
|
||||
>
|
||||
Entrar
|
||||
</Button>
|
||||
<Grid container>
|
||||
{/* <Grid item xs>
|
||||
<Link href="#" variant="body2">
|
||||
Forgot password?
|
||||
</Link>
|
||||
</Grid> */}
|
||||
<Grid item>
|
||||
<Link
|
||||
href="#"
|
||||
variant="body2"
|
||||
component={RouterLink}
|
||||
to="/signup"
|
||||
>
|
||||
{"Não tem uma conta? Cadastre-se!"}
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={8}>
|
||||
<Copyright />
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
import React, { useState, useContext } from "react";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import Button from "@material-ui/core/Button";
|
||||
import CssBaseline from "@material-ui/core/CssBaseline";
|
||||
import TextField from "@material-ui/core/TextField";
|
||||
// import FormControlLabel from "@material-ui/core/FormControlLabel";
|
||||
// import Checkbox from "@material-ui/core/Checkbox";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Box from "@material-ui/core/Box";
|
||||
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Container from "@material-ui/core/Container";
|
||||
|
||||
import { AuthContext } from "../../Context/Auth/AuthContext";
|
||||
|
||||
const Copyright = () => {
|
||||
return (
|
||||
<Typography variant="body2" color="textSecondary" align="center">
|
||||
{"Copyright © "}
|
||||
<Link color="inherit" href="https://material-ui.com/">
|
||||
Canove
|
||||
</Link>{" "}
|
||||
{new Date().getFullYear()}
|
||||
{"."}
|
||||
</Typography>
|
||||
);
|
||||
};
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
paper: {
|
||||
marginTop: theme.spacing(8),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
},
|
||||
avatar: {
|
||||
margin: theme.spacing(1),
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
},
|
||||
form: {
|
||||
width: "100%", // Fix IE 11 issue.
|
||||
marginTop: theme.spacing(1),
|
||||
},
|
||||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
}));
|
||||
|
||||
const Login = ({ showToast }) => {
|
||||
const classes = useStyles();
|
||||
|
||||
const [user, setUser] = useState({ email: "", password: "" });
|
||||
|
||||
const { handleLogin } = useContext(AuthContext);
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setUser({ ...user, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline />
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon />
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Login
|
||||
</Typography>
|
||||
<form
|
||||
className={classes.form}
|
||||
noValidate
|
||||
onSubmit={e => handleLogin(e, user)}
|
||||
>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
id="email"
|
||||
label="Email"
|
||||
name="email"
|
||||
value={user.email}
|
||||
onChange={handleChangeInput}
|
||||
autoComplete="email"
|
||||
autoFocus
|
||||
/>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
margin="normal"
|
||||
required
|
||||
fullWidth
|
||||
name="password"
|
||||
label="Senha"
|
||||
type="password"
|
||||
id="password"
|
||||
value={user.password}
|
||||
onChange={handleChangeInput}
|
||||
autoComplete="current-password"
|
||||
/>
|
||||
{/* <FormControlLabel
|
||||
control={<Checkbox value="remember" color="primary" />}
|
||||
label="Lembrar"
|
||||
/> */}
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
className={classes.submit}
|
||||
>
|
||||
Entrar
|
||||
</Button>
|
||||
<Grid container>
|
||||
{/* <Grid item xs>
|
||||
<Link href="#" variant="body2">
|
||||
Forgot password?
|
||||
</Link>
|
||||
</Grid> */}
|
||||
<Grid item>
|
||||
<Link
|
||||
href="#"
|
||||
variant="body2"
|
||||
component={RouterLink}
|
||||
to="/signup"
|
||||
>
|
||||
{"Não tem uma conta? Cadastre-se!"}
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={8}>
|
||||
<Copyright />
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default Login;
|
||||
|
||||
@@ -1,154 +1,154 @@
|
||||
import React, { useState } from "react";
|
||||
|
||||
import { useHistory } from "react-router-dom";
|
||||
import api from "../../util/api";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import Button from "@material-ui/core/Button";
|
||||
import CssBaseline from "@material-ui/core/CssBaseline";
|
||||
import TextField from "@material-ui/core/TextField";
|
||||
// import FormControlLabel from "@material-ui/core/FormControlLabel";
|
||||
// import Checkbox from "@material-ui/core/Checkbox";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Box from "@material-ui/core/Box";
|
||||
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Container from "@material-ui/core/Container";
|
||||
|
||||
function Copyright() {
|
||||
return (
|
||||
<Typography variant="body2" color="textSecondary" align="center">
|
||||
{"Copyright © "}
|
||||
<Link color="inherit" href="https://material-ui.com/">
|
||||
Canove
|
||||
</Link>{" "}
|
||||
{new Date().getFullYear()}
|
||||
{"."}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
paper: {
|
||||
marginTop: theme.spacing(8),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
},
|
||||
avatar: {
|
||||
margin: theme.spacing(1),
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
},
|
||||
form: {
|
||||
width: "100%", // Fix IE 11 issue.
|
||||
marginTop: theme.spacing(3),
|
||||
},
|
||||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
}));
|
||||
|
||||
const SignUp = () => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
|
||||
const [user, setUser] = useState({ name: "", email: "", password: "" });
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setUser({ ...user, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSignUp = async e => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await api.put("/auth/signup", user);
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
history.push("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline />
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon />
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Cadastre-se
|
||||
</Typography>
|
||||
<form className={classes.form} noValidate onSubmit={handleSignUp}>
|
||||
<Grid container spacing={2}>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
autoComplete="name"
|
||||
name="name"
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="name"
|
||||
label="Nome"
|
||||
value={user.name}
|
||||
onChange={handleChangeInput}
|
||||
autoFocus
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="email"
|
||||
label="Email"
|
||||
name="email"
|
||||
autoComplete="email"
|
||||
value={user.email}
|
||||
onChange={handleChangeInput}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
name="password"
|
||||
label="Senha"
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
value={user.password}
|
||||
onChange={handleChangeInput}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
className={classes.submit}
|
||||
>
|
||||
Cadastrar
|
||||
</Button>
|
||||
<Grid container justify="flex-end">
|
||||
<Grid item>
|
||||
<Link href="#" variant="body2" component={RouterLink} to="/login">
|
||||
Já tem uma conta? Entre!
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={5}>
|
||||
<Copyright />
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default SignUp;
|
||||
import React, { useState } from "react";
|
||||
|
||||
import { useHistory } from "react-router-dom";
|
||||
import api from "../../util/api";
|
||||
import { Link as RouterLink } from "react-router-dom";
|
||||
|
||||
import Avatar from "@material-ui/core/Avatar";
|
||||
import Button from "@material-ui/core/Button";
|
||||
import CssBaseline from "@material-ui/core/CssBaseline";
|
||||
import TextField from "@material-ui/core/TextField";
|
||||
// import FormControlLabel from "@material-ui/core/FormControlLabel";
|
||||
// import Checkbox from "@material-ui/core/Checkbox";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Box from "@material-ui/core/Box";
|
||||
import LockOutlinedIcon from "@material-ui/icons/LockOutlined";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Container from "@material-ui/core/Container";
|
||||
|
||||
function Copyright() {
|
||||
return (
|
||||
<Typography variant="body2" color="textSecondary" align="center">
|
||||
{"Copyright © "}
|
||||
<Link color="inherit" href="https://material-ui.com/">
|
||||
Canove
|
||||
</Link>{" "}
|
||||
{new Date().getFullYear()}
|
||||
{"."}
|
||||
</Typography>
|
||||
);
|
||||
}
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
paper: {
|
||||
marginTop: theme.spacing(8),
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
},
|
||||
avatar: {
|
||||
margin: theme.spacing(1),
|
||||
backgroundColor: theme.palette.secondary.main,
|
||||
},
|
||||
form: {
|
||||
width: "100%", // Fix IE 11 issue.
|
||||
marginTop: theme.spacing(3),
|
||||
},
|
||||
submit: {
|
||||
margin: theme.spacing(3, 0, 2),
|
||||
},
|
||||
}));
|
||||
|
||||
const SignUp = () => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
|
||||
const [user, setUser] = useState({ name: "", email: "", password: "" });
|
||||
|
||||
const handleChangeInput = e => {
|
||||
setUser({ ...user, [e.target.name]: e.target.value });
|
||||
};
|
||||
|
||||
const handleSignUp = async e => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await api.put("/auth/signup", user);
|
||||
} catch (err) {
|
||||
alert(err);
|
||||
}
|
||||
history.push("/login");
|
||||
};
|
||||
|
||||
return (
|
||||
<Container component="main" maxWidth="xs">
|
||||
<CssBaseline />
|
||||
<div className={classes.paper}>
|
||||
<Avatar className={classes.avatar}>
|
||||
<LockOutlinedIcon />
|
||||
</Avatar>
|
||||
<Typography component="h1" variant="h5">
|
||||
Cadastre-se
|
||||
</Typography>
|
||||
<form className={classes.form} noValidate onSubmit={handleSignUp}>
|
||||
<Grid container spacing={2}>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
autoComplete="name"
|
||||
name="name"
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="name"
|
||||
label="Nome"
|
||||
value={user.name}
|
||||
onChange={handleChangeInput}
|
||||
autoFocus
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
id="email"
|
||||
label="Email"
|
||||
name="email"
|
||||
autoComplete="email"
|
||||
value={user.email}
|
||||
onChange={handleChangeInput}
|
||||
/>
|
||||
</Grid>
|
||||
<Grid item xs={12}>
|
||||
<TextField
|
||||
variant="outlined"
|
||||
required
|
||||
fullWidth
|
||||
name="password"
|
||||
label="Senha"
|
||||
type="password"
|
||||
id="password"
|
||||
autoComplete="current-password"
|
||||
value={user.password}
|
||||
onChange={handleChangeInput}
|
||||
/>
|
||||
</Grid>
|
||||
</Grid>
|
||||
<Button
|
||||
type="submit"
|
||||
fullWidth
|
||||
variant="contained"
|
||||
color="primary"
|
||||
className={classes.submit}
|
||||
>
|
||||
Cadastrar
|
||||
</Button>
|
||||
<Grid container justify="flex-end">
|
||||
<Grid item>
|
||||
<Link href="#" variant="body2" component={RouterLink} to="/login">
|
||||
Já tem uma conta? Entre!
|
||||
</Link>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</form>
|
||||
</div>
|
||||
<Box mt={5}>
|
||||
<Copyright />
|
||||
</Box>
|
||||
</Container>
|
||||
);
|
||||
};
|
||||
|
||||
export default SignUp;
|
||||
|
||||
@@ -1,126 +1,126 @@
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import api from "../../util/api";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
import openSocket from "socket.io-client";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import Container from "@material-ui/core/Container";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import Bateryinfo from "./components/Bateryinfo";
|
||||
import Qrcode from "./components/Qrcode";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
root: {
|
||||
display: "flex",
|
||||
},
|
||||
|
||||
title: {
|
||||
flexGrow: 1,
|
||||
},
|
||||
|
||||
appBarSpacer: theme.mixins.toolbar,
|
||||
content: {
|
||||
flexGrow: 1,
|
||||
|
||||
overflow: "auto",
|
||||
},
|
||||
container: {
|
||||
// paddingTop: theme.spacing(4),
|
||||
// paddingBottom: theme.spacing(4),
|
||||
height: `calc(100% - 64px)`,
|
||||
},
|
||||
paper: {
|
||||
padding: theme.spacing(2),
|
||||
display: "flex",
|
||||
overflow: "auto",
|
||||
flexDirection: "column",
|
||||
},
|
||||
fixedHeight: {
|
||||
height: 640,
|
||||
},
|
||||
}));
|
||||
|
||||
const WhatsAuth = () => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
|
||||
const [qrCode, setQrCode] = useState("");
|
||||
const [session, setSession] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSession = async () => {
|
||||
try {
|
||||
const res = await api.get("/whatsapp/session");
|
||||
setQrCode(res.data.qrcode);
|
||||
setSession(res.data);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
};
|
||||
fetchSession();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
|
||||
|
||||
socket.on("qrcode", data => {
|
||||
if (data.action === "update") {
|
||||
setQrCode(data.qr);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("whats_auth", data => {
|
||||
if (data.action === "authentication") {
|
||||
history.push("/chat");
|
||||
setQrCode("");
|
||||
setSession(data.session);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [history]);
|
||||
|
||||
console.log(session);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="QR Code">
|
||||
<div className={classes.root}>
|
||||
<main className={classes.content}>
|
||||
<div className={classes.appBarSpacer} />
|
||||
<Container maxWidth="lg" className={classes.container}>
|
||||
<Grid container spacing={3}>
|
||||
{session.status === "pending" ? (
|
||||
<Grid item xs={6}>
|
||||
<Paper className={classes.paper}>
|
||||
<Qrcode qrCode={qrCode} />
|
||||
</Paper>
|
||||
</Grid>
|
||||
) : (
|
||||
<Grid item xs={6}>
|
||||
<Paper className={classes.paper}>
|
||||
<Bateryinfo sessio={session} />
|
||||
</Paper>
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* <Grid item xs={12} md={4} lg={3}>
|
||||
<Paper className={fixedHeightPaper}>
|
||||
<h1>paper2</h1>
|
||||
</Paper>
|
||||
</Grid> */}
|
||||
</Grid>
|
||||
</Container>
|
||||
</main>
|
||||
</div>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WhatsAuth;
|
||||
import React, { useState, useEffect } from "react";
|
||||
import { useHistory } from "react-router-dom";
|
||||
import api from "../../util/api";
|
||||
import MainDrawer from "../../components/Layout/MainDrawer";
|
||||
import openSocket from "socket.io-client";
|
||||
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
import Container from "@material-ui/core/Container";
|
||||
import Grid from "@material-ui/core/Grid";
|
||||
import Paper from "@material-ui/core/Paper";
|
||||
import Bateryinfo from "./components/Bateryinfo";
|
||||
import Qrcode from "./components/Qrcode";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
root: {
|
||||
display: "flex",
|
||||
},
|
||||
|
||||
title: {
|
||||
flexGrow: 1,
|
||||
},
|
||||
|
||||
appBarSpacer: theme.mixins.toolbar,
|
||||
content: {
|
||||
flexGrow: 1,
|
||||
|
||||
overflow: "auto",
|
||||
},
|
||||
container: {
|
||||
// paddingTop: theme.spacing(4),
|
||||
// paddingBottom: theme.spacing(4),
|
||||
height: `calc(100% - 64px)`,
|
||||
},
|
||||
paper: {
|
||||
padding: theme.spacing(2),
|
||||
display: "flex",
|
||||
overflow: "auto",
|
||||
flexDirection: "column",
|
||||
},
|
||||
fixedHeight: {
|
||||
height: 640,
|
||||
},
|
||||
}));
|
||||
|
||||
const WhatsAuth = () => {
|
||||
const classes = useStyles();
|
||||
const history = useHistory();
|
||||
|
||||
const [qrCode, setQrCode] = useState("");
|
||||
const [session, setSession] = useState({});
|
||||
|
||||
useEffect(() => {
|
||||
const fetchSession = async () => {
|
||||
try {
|
||||
const res = await api.get("/whatsapp/session");
|
||||
setQrCode(res.data.qrcode);
|
||||
setSession(res.data);
|
||||
} catch (err) {
|
||||
console.log(err);
|
||||
}
|
||||
};
|
||||
fetchSession();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const socket = openSocket(process.env.REACT_APP_BACKEND_URL);
|
||||
|
||||
socket.on("qrcode", data => {
|
||||
if (data.action === "update") {
|
||||
setQrCode(data.qr);
|
||||
}
|
||||
});
|
||||
|
||||
socket.on("whats_auth", data => {
|
||||
if (data.action === "authentication") {
|
||||
history.push("/chat");
|
||||
setQrCode("");
|
||||
setSession(data.session);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
socket.disconnect();
|
||||
};
|
||||
}, [history]);
|
||||
|
||||
console.log(session);
|
||||
|
||||
return (
|
||||
<div>
|
||||
<MainDrawer appTitle="QR Code">
|
||||
<div className={classes.root}>
|
||||
<main className={classes.content}>
|
||||
<div className={classes.appBarSpacer} />
|
||||
<Container maxWidth="lg" className={classes.container}>
|
||||
<Grid container spacing={3}>
|
||||
{session.status === "pending" ? (
|
||||
<Grid item xs={6}>
|
||||
<Paper className={classes.paper}>
|
||||
<Qrcode qrCode={qrCode} />
|
||||
</Paper>
|
||||
</Grid>
|
||||
) : (
|
||||
<Grid item xs={6}>
|
||||
<Paper className={classes.paper}>
|
||||
<Bateryinfo sessio={session} />
|
||||
</Paper>
|
||||
</Grid>
|
||||
)}
|
||||
|
||||
{/* <Grid item xs={12} md={4} lg={3}>
|
||||
<Paper className={fixedHeightPaper}>
|
||||
<h1>paper2</h1>
|
||||
</Paper>
|
||||
</Grid> */}
|
||||
</Grid>
|
||||
</Container>
|
||||
</main>
|
||||
</div>
|
||||
</MainDrawer>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WhatsAuth;
|
||||
|
||||
@@ -1,34 +1,34 @@
|
||||
import React from "react";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
|
||||
const useStyles = makeStyles({
|
||||
main: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const Bateryinfo = ({ session }) => {
|
||||
const classes = useStyles();
|
||||
return (
|
||||
<React.Fragment>
|
||||
<Typography component="h2" variant="h6" color="primary" gutterBottom>
|
||||
Bateria
|
||||
</Typography>
|
||||
<Typography component="p" variant="h6">
|
||||
{(session && session.baterry) || "Não disponível"}
|
||||
</Typography>
|
||||
<Typography color="textSecondary" className={classes.main}>
|
||||
Carregando: {(session && session.plugged) || "Não disponível"}
|
||||
</Typography>
|
||||
<div>
|
||||
<Link color="primary" href="#">
|
||||
Verificar bateria
|
||||
</Link>
|
||||
</div>
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
export default Bateryinfo;
|
||||
import React from "react";
|
||||
import Link from "@material-ui/core/Link";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
|
||||
const useStyles = makeStyles({
|
||||
main: {
|
||||
flex: 1,
|
||||
},
|
||||
});
|
||||
|
||||
const Bateryinfo = ({ session }) => {
|
||||
const classes = useStyles();
|
||||
return (
|
||||
<React.Fragment>
|
||||
<Typography component="h2" variant="h6" color="primary" gutterBottom>
|
||||
Bateria
|
||||
</Typography>
|
||||
<Typography component="p" variant="h6">
|
||||
{(session && session.baterry) || "Não disponível"}
|
||||
</Typography>
|
||||
<Typography color="textSecondary" className={classes.main}>
|
||||
Carregando: {(session && session.plugged) || "Não disponível"}
|
||||
</Typography>
|
||||
<div>
|
||||
<Link color="primary" href="#">
|
||||
Verificar bateria
|
||||
</Link>
|
||||
</div>
|
||||
</React.Fragment>
|
||||
);
|
||||
};
|
||||
|
||||
export default Bateryinfo;
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import React from "react";
|
||||
import QRCode from "qrcode.react";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
|
||||
const Qrcode = ({ qrCode }) => {
|
||||
return (
|
||||
<div>
|
||||
<Typography component="h2" variant="h6" color="primary" gutterBottom>
|
||||
Leia o QrCode para iniciar a sessão
|
||||
</Typography>
|
||||
<QRCode value={qrCode} size={256} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Qrcode;
|
||||
import React from "react";
|
||||
import QRCode from "qrcode.react";
|
||||
import Typography from "@material-ui/core/Typography";
|
||||
|
||||
const Qrcode = ({ qrCode }) => {
|
||||
return (
|
||||
<div>
|
||||
<Typography component="h2" variant="h6" color="primary" gutterBottom>
|
||||
Leia o QrCode para iniciar a sessão
|
||||
</Typography>
|
||||
<QRCode value={qrCode} size={256} />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default Qrcode;
|
||||
|
||||
@@ -1,71 +1,93 @@
|
||||
import React, { useContext } from "react";
|
||||
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
|
||||
|
||||
import { AuthContext, AuthProvider } from "./Context/Auth/AuthContext";
|
||||
|
||||
import Dashboard from "./pages/Home/Dashboard";
|
||||
import Chat from "./pages/Chat/Chat";
|
||||
import Profile from "./pages/Profile/Profile";
|
||||
import Signup from "./pages/Signup/Signup";
|
||||
import Login from "./pages/Login/Login";
|
||||
import WhatsAuth from "./pages/WhatsAuth/WhatsAuth";
|
||||
|
||||
const PrivateRoute = ({ component: Component, ...rest }) => {
|
||||
const { isAuth, loading } = useContext(AuthContext);
|
||||
|
||||
if (loading) return <h1>Loading...</h1>;
|
||||
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={props =>
|
||||
isAuth ? (
|
||||
<Component {...props} />
|
||||
) : (
|
||||
<Redirect
|
||||
to={{ pathname: "/login", state: { from: props.location } }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const PublicRoute = ({ component: Component, ...rest }) => {
|
||||
const { isAuth, loading } = useContext(AuthContext);
|
||||
|
||||
if (loading) return <h1>Loading...</h1>;
|
||||
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={props =>
|
||||
!isAuth ? (
|
||||
<Component {...props} />
|
||||
) : (
|
||||
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const Routes = () => {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Switch>
|
||||
<PrivateRoute exact path="/" component={Dashboard} />
|
||||
<PrivateRoute exact path="/chat" component={Chat} />
|
||||
<PrivateRoute exact path="/chat/:contactId" component={Chat} />
|
||||
<PrivateRoute exact path="/profile" component={Profile} />
|
||||
<PrivateRoute exact path="/whats-auth" component={WhatsAuth} />
|
||||
<PublicRoute exact path="/login" component={Login} />
|
||||
<PublicRoute exact path="/signup" component={Signup} />
|
||||
</Switch>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
export default Routes;
|
||||
import React, { useContext } from "react";
|
||||
import { BrowserRouter, Route, Switch, Redirect } from "react-router-dom";
|
||||
|
||||
import { AuthContext, AuthProvider } from "./Context/Auth/AuthContext";
|
||||
|
||||
import Dashboard from "./pages/Home/Dashboard";
|
||||
import Chat from "./pages/Chat/Chat";
|
||||
import Profile from "./pages/Profile/Profile";
|
||||
import Signup from "./pages/Signup/Signup";
|
||||
import Login from "./pages/Login/Login";
|
||||
import WhatsAuth from "./pages/WhatsAuth/WhatsAuth";
|
||||
import Backdrop from "@material-ui/core/Backdrop";
|
||||
import CircularProgress from "@material-ui/core/CircularProgress";
|
||||
import { makeStyles } from "@material-ui/core/styles";
|
||||
|
||||
const useStyles = makeStyles(theme => ({
|
||||
backdrop: {
|
||||
zIndex: theme.zIndex.drawer + 1,
|
||||
color: "#fff",
|
||||
},
|
||||
}));
|
||||
|
||||
const PrivateRoute = ({ component: Component, ...rest }) => {
|
||||
const classes = useStyles();
|
||||
const { isAuth, loading } = useContext(AuthContext);
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<Backdrop className={classes.backdrop} open={loading}>
|
||||
<CircularProgress color="inherit" />
|
||||
</Backdrop>
|
||||
);
|
||||
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={props =>
|
||||
isAuth ? (
|
||||
<Component {...props} />
|
||||
) : (
|
||||
<Redirect
|
||||
to={{ pathname: "/login", state: { from: props.location } }}
|
||||
/>
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const PublicRoute = ({ component: Component, ...rest }) => {
|
||||
const classes = useStyles();
|
||||
const { isAuth, loading } = useContext(AuthContext);
|
||||
|
||||
if (loading)
|
||||
return (
|
||||
<Backdrop className={classes.backdrop} open={loading}>
|
||||
<CircularProgress color="inherit" />
|
||||
</Backdrop>
|
||||
);
|
||||
|
||||
return (
|
||||
<Route
|
||||
{...rest}
|
||||
render={props =>
|
||||
!isAuth ? (
|
||||
<Component {...props} />
|
||||
) : (
|
||||
<Redirect to={{ pathname: "/", state: { from: props.location } }} />
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const Routes = () => {
|
||||
return (
|
||||
<BrowserRouter>
|
||||
<AuthProvider>
|
||||
<Switch>
|
||||
<PrivateRoute exact path="/" component={Dashboard} />
|
||||
<PrivateRoute exact path="/chat" component={Chat} />
|
||||
<PrivateRoute exact path="/chat/:contactId" component={Chat} />
|
||||
<PrivateRoute exact path="/profile" component={Profile} />
|
||||
<PrivateRoute exact path="/whats-auth" component={WhatsAuth} />
|
||||
<PublicRoute exact path="/login" component={Login} />
|
||||
<PublicRoute exact path="/signup" component={Signup} />
|
||||
</Switch>
|
||||
</AuthProvider>
|
||||
</BrowserRouter>
|
||||
);
|
||||
};
|
||||
|
||||
export default Routes;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import axios from "axios";
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||
});
|
||||
|
||||
export default api;
|
||||
import axios from "axios";
|
||||
|
||||
const api = axios.create({
|
||||
baseURL: process.env.REACT_APP_BACKEND_URL,
|
||||
});
|
||||
|
||||
export default api;
|
||||
|
||||
4
frontend/src/util/sound.mp3:Zone.Identifier
Normal file
4
frontend/src/util/sound.mp3:Zone.Identifier
Normal file
@@ -0,0 +1,4 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=https://notificationsounds.com/message-tones/juntos-607
|
||||
HostUrl=https://notificationsounds.com/message-tones/juntos-607/download/mp3
|
||||
4
frontend/src/util/sound.ogg:Zone.Identifier
Normal file
4
frontend/src/util/sound.ogg:Zone.Identifier
Normal file
@@ -0,0 +1,4 @@
|
||||
[ZoneTransfer]
|
||||
ZoneId=3
|
||||
ReferrerUrl=https://notificationsounds.com/message-tones/juntos-607
|
||||
HostUrl=https://notificationsounds.com/message-tones/juntos-607/download/ogg
|
||||
Reference in New Issue
Block a user