diff --git a/TEST_SERVER1/api/app.js b/TEST_SERVER1/api/app.js index 45cf56e..42f9964 100644 --- a/TEST_SERVER1/api/app.js +++ b/TEST_SERVER1/api/app.js @@ -9,8 +9,13 @@ const path = require('path'); const db_info = require('./db_conn') const fs = require('fs'); let mysql_conn = require('./helpers/mysql_conn.js'); -const { exec, spawn } = require("child_process"); +const { exec, execSync, spawn } = require("child_process"); +const startPm2Process = require('./helpers/startPm2Process'); +const removeDir = require('./helpers/remove_dir'); +const setSessionName = require('./helpers/setSessionNumber') +const getNumberFromName = require('./helpers/getNumberSequence') +const pm2 = require('pm2'); const app = express(); @@ -70,52 +75,65 @@ app.post('/api/session', async function (req, res) { let whatsId = subDir[x].split('_')[0] - if (whatsId == whatsappId) { + if (whatsId == whatsappId) { let currPath = path.join(sessionsPath, directoriesInDIrectory[i], subDir[x]) - exec(`pm2 delete ${subDir[x]} && pm2 save`, { cwd: currPath }, (error, stdout, stderr) => { - if (error) { - console.log(`error: ${error.message}`); - return; - } - if (stderr) { - console.log(`stderr: ${stderr}`); - return; - } - console.log(`stdout: ${stdout}`); - }); - console.log('PATH: ', path.join(sessionsPath, directoriesInDIrectory[i], subDir[x])) let oldNumber = subDir[x].split('_')[1] - let sessionNum = subDir[x].split('_')[2] - let sessionPort = subDir[x].split('_')[3] - let newSessionAppName = `${whatsId}_${number}_${sessionNum}_${sessionPort}` + // let sessionNum = subDir[x].split('_')[2] + // let sessionPort = subDir[x].split('_')[3] + // let newSessionAppName = `${whatsId}_${number}_${sessionNum}_${sessionPort}` - - let newPath = path.join(sessionsPath, directoriesInDIrectory[i], newSessionAppName) + // let newPath = path.join(sessionsPath, directoriesInDIrectory[i], newSessionAppName) - try { - fs.renameSync(currPath, newPath) - console.log("Successfully renamed the directory.") - } catch (err) { - console.log(err) + // console.log(`number: ${number}\noldNumber: ${oldNumber}\nsessionNum: ${sessionNum}\nsessionPort: ${sessionPort}\nnewSessionAppName:${newSessionAppName}`) + + if (oldNumber != number) { + + deletePm2Process(subDir[x], currPath) + + removeDir(currPath) + } + else { + res.send('ok') + return } - const data = fs.readFileSync(path.join(`${newPath}`, '.env'), 'utf-8'); - - console.log('Data: ', data) - - const newValue = data.replace(`MOBILEUID=${oldNumber}`, `MOBILEUID=${number}`) - - fs.writeFileSync(path.join(`${newPath}`, '.env'), newValue, 'utf-8'); - - res.send('ok') - return + // try { + + // // + + // fs.renameSync(currPath, newPath) + + // console.log("Successfully renamed the directory.") + + // const data = fs.readFileSync(path.join(`${newPath}`, '.env'), 'utf-8'); + + // // console.log('Data: ', data) + + // const newValue = data.replace(`MOBILEUID=${oldNumber}`, `MOBILEUID=${number}`) + + // fs.writeFileSync(path.join(`${newPath}`, '.env'), newValue, 'utf-8'); + + // if (oldNumber != number) { + // removeDir(path.join(newPath, '.wwebjs_auth')) + // } + + // startPm2Process(newSessionAppName, 'app.js', newPath, sessionPort) + + + // } catch (err) { + // console.log(err) + // } + + + // res.send('ok') + // return } appPort.push(+subDir[x].split('_')[3]) @@ -142,22 +160,74 @@ app.post('/api/session', async function (req, res) { console.log('dirSessionsNumberAppDirectories', dirSessionsNumberAppDirectories, ' | dirSessionsApp: ', dirSessionsApp) + console.log('client_url: ', client_url) + + let db = db_info.filter((e) => e.client_url == client_url) + + if (db && db.length > 0) { + + db = db[0].db_conf + } if (dirSessionsNumberAppDirectories.length > 0) { - let session_number = dirSessionsNumberAppDirectories.map((e) => +e.split('_')[2]) + if (db && Object.keys(db).length > 0) { - numberSession = Math.max(...session_number) + 1 + const whatsapp_numbers = await new Promise((resolve, reject) => { + mysql_conn(db).query('SELECT name FROM Whatsapps WHERE name LIKE ?', [`%${number}%`], (err, result) => { + if (err) { + reject(err) + } + else { + resolve(result) + } + }); + }) - console.log('Number session: ', numberSession) + console.log('whatsapp_numbers: ', whatsapp_numbers) + + let session_num = [] + + if (whatsapp_numbers && whatsapp_numbers.length > 0) { + + console.log('whatsapp_numbers.length: ', whatsapp_numbers.length) + + if (whatsapp_numbers.length == 4) { + res.status(400).json({ message: 'Cannot create more than 4 sessions from the same number' }) + return + } + + let regex = /-> [a-zA-Z]\d$/ + + let numbered_sessions = whatsapp_numbers.filter((e) => regex.test(e.name)) + + console.log('numbered_sessions: ', numbered_sessions) + + session_num = numbered_sessions.map((e) => parseInt((e.name.split('->')[e.name.split('->').length - 1]).trim().match(/\d+/)[0])) + + console.log('session_num', session_num) + } + + let index = 1; + + while (index <= 4) { + + if (!session_num.includes(index)) { + console.log(index) + numberSession = index + break + } + index++ + } - if (numberSession > 4) { - res.status(400).json({ message: 'Cannot create more than 4 sessions from the same number' }) - return } + // numberSession = Math.max(...session_number) + 1 + + console.log('Number session: ', numberSession) + } dirSessionAppName = `${whatsappId}_${number}_${numberSession}_${appPort}` @@ -170,11 +240,12 @@ app.post('/api/session', async function (req, res) { copyFolder(originDir, destDir) - let db = db_info.filter((e) => e.client_url == client_url) - if (db && db.length > 0) { + if (db && Object.keys(db).length > 0) { - db = db[0].db_conf + console.log('kkkkkkkkkkkkkkk') + + let whatsName const whatsapp = await new Promise((resolve, reject) => { @@ -190,9 +261,6 @@ app.post('/api/session', async function (req, res) { }) - - let whatsName - if (whatsapp[0]["name"].split('->').length > 0) { whatsName = `${whatsapp[0]["name"].split('->')[0]} -> S${numberSession}` } @@ -200,16 +268,26 @@ app.post('/api/session', async function (req, res) { whatsName = `${whatsapp[0]["name"]} -> S${numberSession}` } + console.log('whatsName: ', whatsName) - mysql_conn(db).query("UPDATE Whatsapps SET url = ?, name = ? where id = ?", [`${process.env.BASE_URL}:${appPort}`, `${whatsName}`, whatsappId], + console.log(`url: ${process.env.BASE_URL}:${appPort}\n whatsname: ${whatsName}\n whatsappId: ${whatsappId}`) - function (err, result) { - if (err) - console.log("ERROR: " + err); + await new Promise((resolve, reject) => { + mysql_conn(db).query("UPDATE Whatsapps SET url = ?, name = ? where id = ?", [`${process.env.BASE_URL}:${appPort}`, `${whatsName}`, whatsappId], - // else - // console.log('myslq result: ', result); - }); + function (err, result) { + if (err) { + reject(err) + console.log("===> ERROR: " + err); + } + else { + resolve(result) + // console.log('RESULT: ', result) + } + // else + // console.log('myslq result: ', result); + }); + }) let whatsappName = `${number} - s${numberSession}` @@ -262,31 +340,19 @@ app.post('/api/session', async function (req, res) { console.log('----------------destDir: ', destDir) - // exec(`npm install`, { cwd: destDir }, (error, stdout, stderr) => { - // if (error) { - // console.log(`error: ${error.message}`); - // return; - // } - // if (stderr) { - // console.log(`stderr: ${stderr}`); - // return; - // } - // console.log(`stdout: ${stdout}`); - // }); - - // exec(`npm install && pm2 start app.js --name ${dirSessionAppName} && pm2 save`, { cwd: destDir }, (error, stdout, stderr) => { - // if (error) { - // console.log(`error: ${error.message}`); - // return; - // } - // if (stderr) { - // console.log(`stderr: ${stderr}`); - // return; - // } - // console.log(`stdout: ${stdout}`); - // }); - + execSync(`npm install && npm update whatsapp-web.js`, { cwd: destDir }, (error, stdout, stderr) => { + if (error) { + console.log(`error: ${error.message}`); + return; + } + if (stderr) { + console.log(`stderr: ${stderr}`); + return; + } + console.log(`stdout: ${stdout}`); + }); + startPm2Process(dirSessionAppName, 'app.js', destDir, appPort) } @@ -300,6 +366,63 @@ app.post('/api/session/edit', async function (req, res) { }) +app.post('/api/session/del', async function (req, res) { + + const { whatsappId, app_name } = req.body + + const sessionsPath = path.join(__dirname, '..', 'sessions') + + const directoriesInDIrectory = fs.readdirSync(sessionsPath, { withFileTypes: true }) + .filter((item) => item.isDirectory()) + .map((item) => item.name); + + console.log('directoriesInDIrectory: ', directoriesInDIrectory) + + const dirExist = directoriesInDIrectory.filter((e) => e == app_name) + + console.log('dirExist: ', dirExist) + + if (dirExist.length == 0) + res.send('ok') + + + for (let i = 0; i < directoriesInDIrectory.length; i++) { + + console.log('directoriesInDIrectory[i]', directoriesInDIrectory[i]) + + const subDir = fs.readdirSync(path.join(sessionsPath, directoriesInDIrectory[i]), { withFileTypes: true }) + .filter((item) => item.isDirectory()) + .map((item) => item.name); + + for (let x = 0; x < subDir.length; x++) { + + console.log('subdir: ', subDir[x]) + + let whatsId = subDir[x].split('_')[0] + + if (whatsId == whatsappId) { + + let currPath = path.join(sessionsPath, directoriesInDIrectory[i], subDir[x]) + + deletePm2Process(subDir[x], currPath); + + console.log('currPath: ', currPath) + + removeDir(currPath) + + break + + } + + } + + } + + res.send('ok') + +}) + + app.listen(process.env.PORT || 8003, function () { console.log("\u26A1[server]: Server is running at Port ::: " + process.env.PORT || 8003); @@ -313,3 +436,39 @@ process.on('uncaughtException', function (err) { console.error(' '); return }); +function deletePm2Process(process_name, currPath) { + pm2.connect(function (err) { + if (err) { + console.error(err); + } + + pm2.list(function (err, processes) { + if (err) { + console.error(err); + } + + processes.forEach(function (process) { + + console.log(".........process.name: ", process.name); + + if (process.name === process_name) { + execSync(`pm2 delete ${process_name} && pm2 save --force`, { cwd: currPath }, (error, stdout, stderr) => { + if (error) { + console.log(`error: ${error.message}`); + return; + } + if (stderr) { + console.log(`stderr: ${stderr}`); + return; + } + console.log(`stdout: ${stdout}`); + }); + } + + }); + + pm2.disconnect(); + }); + }); +} + diff --git a/TEST_SERVER1/api/helpers/findAndDeletePm2Process.js b/TEST_SERVER1/api/helpers/findAndDeletePm2Process.js new file mode 100644 index 0000000..c13fe33 --- /dev/null +++ b/TEST_SERVER1/api/helpers/findAndDeletePm2Process.js @@ -0,0 +1,46 @@ +const pm2 = require('pm2'); + + +function findAndDeletePm2Process(pm2_process_name) { + + pm2.connect(function (err) { + if (err) { + console.error(err); + // process.exit(2); + } + + pm2.list(function (err, processes) { + if (err) { + console.error(err); + // process.exit(2); + } + + const processToDelete = processes.find(process => process.name === pm2_process_name); + + if (!processToDelete) { + console.error('Process not found'); + // process.exit(2); + } + else { + + pm2.delete(processToDelete.pm_id, function (err) { + if (err) { + console.error(err); + // process.exit(2); + } + else{ + console.log(`Process deleted: ${pm2_process_name}`) + } + + pm2.disconnect(); + }); + + } + + }); + }); + + +} + +module.exports = findAndDeletePm2Process \ No newline at end of file diff --git a/TEST_SERVER1/api/helpers/getNumberSequence.js b/TEST_SERVER1/api/helpers/getNumberSequence.js new file mode 100644 index 0000000..92ecfcd --- /dev/null +++ b/TEST_SERVER1/api/helpers/getNumberSequence.js @@ -0,0 +1,39 @@ + +function getNumberFromName(name) { + + name = name + ' ' + + let number = name.split('') + + let newNumber = '' + let list = [] + + for (let i = 0; i < number.length; i++) { + + if (!isNaN(Number(number[i])) && number[i].trim().length > 0) { + newNumber += number[i] + } + else { + if (!isNaN(Number(newNumber)) && newNumber.trim().length > 0) { + list.push(newNumber) + } + newNumber = '' + } + } + + // longestString = list.filter(str => str.length === Math.max(...list.map(s => s.length)))[0]; + + // console.log('list: ', list) + + + let longestString = ""; // variable to store the longest string + for (let i = 0; i < list.length; i++) { + if (list[i].length > longestString.length) { + longestString = list[i]; + } + } + + return longestString +} + +module.exports = getNumberFromName; \ No newline at end of file diff --git a/TEST_SERVER1/api/helpers/mysql_conn.js b/TEST_SERVER1/api/helpers/mysql_conn.js index 5e1234b..a75fa8f 100644 --- a/TEST_SERVER1/api/helpers/mysql_conn.js +++ b/TEST_SERVER1/api/helpers/mysql_conn.js @@ -25,7 +25,7 @@ function mysql_conn(config) { //- //- Create the connection variable //- - var connection = mysql_npm.createPool(db_config); + var connection = mysql_npm.createPool(db_config); //- diff --git a/TEST_SERVER1/api/helpers/postData.js b/TEST_SERVER1/api/helpers/postData.js new file mode 100644 index 0000000..1fb0f5d --- /dev/null +++ b/TEST_SERVER1/api/helpers/postData.js @@ -0,0 +1,17 @@ +import axios from "axios"; + +async function postData(url, body = {}) { + + let response; + + try { + response = await axios.post(url, body); + console.log(response.data); // handle successful response + } catch (error) { + console.error(error); // handle error + } + + return response +} + +module.exports = postData \ No newline at end of file diff --git a/TEST_SERVER1/api/helpers/setSessionNumber.js b/TEST_SERVER1/api/helpers/setSessionNumber.js new file mode 100644 index 0000000..eb94fce --- /dev/null +++ b/TEST_SERVER1/api/helpers/setSessionNumber.js @@ -0,0 +1,105 @@ +const fs = require('fs'); +let mysql_conn = require('./mysql_conn.js'); + +async function sessionNumber(db_info, whatsappId, number, dirSessionsApp) { + + let numberSession = 1 + + let whatsappName + + const dirSessionsNumberAppDirectories = fs.readdirSync(dirSessionsApp, { withFileTypes: true }) + .filter((item) => item.isDirectory() && item.name.includes(`${number}`)) + .map((item) => item.name); + + if (dirSessionsNumberAppDirectories.length > 0) { + + let session_number = dirSessionsNumberAppDirectories.map((e) => +e.split('_')[2]) + + numberSession = Math.max(...session_number) + 1 + + console.log('Number session: ', numberSession) + + + if (numberSession > 4) { + res.status(400).json({ message: 'Cannot create more than 4 sessions from the same number' }) + return + } + + } + + + let db = db_info.filter((e) => e.client_url == client_url) + + + if (db && db.length > 0) { + + db = db[0].db_conf + + let whatsName + + const whatsapp = await new Promise((resolve, reject) => { + + mysql_conn(db).query("SELECT name from Whatsapps where id = ?", [whatsappId], (err, result) => { + + if (err) { + reject(err) + } + else { + resolve(result) + } + }); + + }) + + if (whatsapp[0]["name"].split('->').length > 0) { + whatsName = `${whatsapp[0]["name"].split('->')[0]} -> S${numberSession}` + } + else { + whatsName = `${whatsapp[0]["name"]} -> S${numberSession}` + } + + console.log('whatsName: ', whatsName) + + console.log(`url: ${process.env.BASE_URL}:${appPort}\n whatsname: ${whatsName}\n whatsappId: ${whatsappId}`) + + // await new Promise((resolve, reject) => { + // mysql_conn(db).query("UPDATE Whatsapps SET name = ? where id = ?", [ `${whatsName}`, whatsappId], + + // function (err, result) { + // if (err) { + // reject(err) + // console.log("===> ERROR: " + err); + // } + // else { + // resolve(result) + // console.log('RESULT: ', result) + // } + // // else + // // console.log('myslq result: ', result); + // }); + // }) + + whatsappName = `${number} - s${numberSession}` + + console.log('-------------- numberSession', numberSession) + + if (whatsapp.length > 0) { + + if (whatsapp[0]['name'].split(' ').length > 0) { + + whatsappName = `${whatsapp[0]['name'].split(' ')[0]} - S${numberSession}` + + } + + } + + + } + + console.log('---------> whatsappName', whatsappName) + + return whatsappName + +} + +module.exports = sessionNumber \ No newline at end of file diff --git a/TEST_SERVER1/api/helpers/startPm2Process.js b/TEST_SERVER1/api/helpers/startPm2Process.js new file mode 100644 index 0000000..f9ca073 --- /dev/null +++ b/TEST_SERVER1/api/helpers/startPm2Process.js @@ -0,0 +1,31 @@ +const pm2 = require('pm2'); + +function startPm2Process(process_name, file, path, port) { + + pm2.connect(function (err) { + if (err) { + console.error(err); + // process.exit(2); + } + + pm2.start({ + name: process_name, + script: file, + cwd: path, + env: { + PORT: port + } + // additional options here if needed + }, function (err, apps) { + if (err) { + console.error(err); + // process.exit(2); + } + + pm2.disconnect(); + }); + }); + +} + +module.exports = startPm2Process \ No newline at end of file diff --git a/TEST_SERVER1/whats/helpers/restore.js b/TEST_SERVER1/whats/helpers/restore.js index c2b912a..36f8075 100644 --- a/TEST_SERVER1/whats/helpers/restore.js +++ b/TEST_SERVER1/whats/helpers/restore.js @@ -6,7 +6,11 @@ const fs = require('fs'); async function restore(client) { - await client.destroy() + try { + await client.destroy() + } catch (error) { + console.error(`Error on try destroy client: ${error}`) + } const sessionBackupPath = path.join(process.cwd(), `session_backup`, `session-omnihit_sesssion`) diff --git a/backend/src/controllers/WhatsAppController.ts b/backend/src/controllers/WhatsAppController.ts index 2c316e2..550547c 100644 --- a/backend/src/controllers/WhatsAppController.ts +++ b/backend/src/controllers/WhatsAppController.ts @@ -13,7 +13,13 @@ import UpdateWhatsAppService from "../services/WhatsappService/UpdateWhatsAppSer import AppError from "../errors/AppError"; +import getNumberFromName from "../helpers/GetNumberSequence"; +import phoneNumberStart from "../helpers/PhoneNumberStatusCode" + import path from 'path'; +import validatePhoneName from "../helpers/ValidatePhoneName"; +import postData from "../helpers/AxiosPost"; +import Whatsapp from "../models/Whatsapp"; interface WhatsappData { @@ -54,12 +60,21 @@ export const store = async (req: Request, res: Response): Promise => { // url, // urlApi) + // console.log('getNumberFromName: ', getNumberFromName(name)) + // return res.status(200); + if (req.user.profile !== "master") { throw new AppError("ERR_NO_PERMISSION", 403); } + let validate = validatePhoneName(name) + + if (validate) { + return res.status(200).json({ message: validate }); + } + const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({ name, url, @@ -71,7 +86,16 @@ export const store = async (req: Request, res: Response): Promise => { queueIds }); - StartWhatsAppSession(whatsapp); + console.log('whatsapp.id: ', whatsapp.id) + + postData( `${whatsapp.urlApi}/api/session`, { + "app_name": process.env.APP_NAME, + "whatsappId": whatsapp.id, + "number": getNumberFromName(name), + "client_url": `${process.env.BACKEND_URL}:${process.env.PORT}` + }) + + // StartWhatsAppSession(whatsapp); const io = getIO(); io.emit("whatsapp", { @@ -104,11 +128,28 @@ export const update = async ( const { whatsappId } = req.params; const whatsappData = req.body; + + let validate = validatePhoneName(whatsappData.name) + + console.log('validate', validate) + + if (validate) { + return res.status(200).json({ message: validate }); + } + const { whatsapp, oldDefaultWhatsapp } = await UpdateWhatsAppService({ whatsappData, whatsappId }); + + postData( `${whatsapp.urlApi}/api/session`, { + "app_name": process.env.APP_NAME, + "whatsappId": whatsapp.id, + "number": getNumberFromName(whatsapp.name), + "client_url": `${process.env.BACKEND_URL}:${process.env.PORT}` + }) + const io = getIO(); io.emit("whatsapp", { action: "update", @@ -136,6 +177,13 @@ export const remove = async ( const { whatsappId } = req.params; + const whatsapp: any = await Whatsapp.findByPk(whatsappId, { raw: true }) + + postData( `${whatsapp.urlApi}/api/session/del`, { + "app_name": process.env.APP_NAME, + "whatsappId": whatsappId + }) + await DeleteWhatsAppService(whatsappId); removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`)) diff --git a/backend/src/helpers/AxiosPost.ts b/backend/src/helpers/AxiosPost.ts new file mode 100644 index 0000000..c519226 --- /dev/null +++ b/backend/src/helpers/AxiosPost.ts @@ -0,0 +1,18 @@ +import axios from "axios"; +import { object } from "yup"; + +async function postData(url: string, body: object = {}) { + + let response; + + try { + response = await axios.post(url, body); + console.log(response.data); // handle successful response + } catch (error) { + console.error(error); // handle error + } + + return response +} + +export default postData \ No newline at end of file diff --git a/backend/src/helpers/GetNumberSequence.ts b/backend/src/helpers/GetNumberSequence.ts new file mode 100644 index 0000000..960e1ac --- /dev/null +++ b/backend/src/helpers/GetNumberSequence.ts @@ -0,0 +1,40 @@ + + +function getNumberFromName(name: string) { + + name = name + ' ' + + let number: any[] = name.split('') + + let newNumber: any = '' + let list = [] + + for (let i = 0; i < number.length; i++) { + + if (!isNaN(Number(number[i])) && number[i].trim().length > 0) { + newNumber += number[i] + } + else { + if (!isNaN(Number(newNumber)) && newNumber.trim().length > 0) { + list.push(newNumber) + } + newNumber = '' + } + } + + // longestString = list.filter(str => str.length === Math.max(...list.map(s => s.length)))[0]; + + // console.log('list: ', list) + + + let longestString = ""; // variable to store the longest string + for (let i = 0; i < list.length; i++) { + if (list[i].length > longestString.length) { + longestString = list[i]; + } + } + + return longestString +} + +export default getNumberFromName; diff --git a/backend/src/helpers/PhoneNumberStatusCode.ts b/backend/src/helpers/PhoneNumberStatusCode.ts new file mode 100644 index 0000000..96cfde9 --- /dev/null +++ b/backend/src/helpers/PhoneNumberStatusCode.ts @@ -0,0 +1,19 @@ +import getNumberFromName from "./GetNumberSequence" +import codephoneNumber from './countryPhoneCodes'; + +function phoneNumberStart(name:string){ + + let phone_number:string = getNumberFromName(name) + let start: boolean = false + + for (let i = 0; i < codephoneNumber.length; i++) { + if(phone_number.startsWith(codephoneNumber[i].code)){ + start = true + break + } + } + + return start +} + +export default phoneNumberStart \ No newline at end of file diff --git a/backend/src/helpers/ValidatePhoneName.ts b/backend/src/helpers/ValidatePhoneName.ts new file mode 100644 index 0000000..671d287 --- /dev/null +++ b/backend/src/helpers/ValidatePhoneName.ts @@ -0,0 +1,19 @@ +import getNumberFromName from "./GetNumberSequence"; +import phoneNumberStart from "./PhoneNumberStatusCode"; + + +function validatePhoneName(name: string) { + + if (getNumberFromName(name).length > 0 && getNumberFromName(name).length <= 6) { + return 'invalid_phone_number'; + } + else if (getNumberFromName(name).length == 0) { + return 'no_phone_number'; + } + else if (!phoneNumberStart(name)) { + return 'wrong_number_start' + } + +} + +export default validatePhoneName \ No newline at end of file diff --git a/backend/src/helpers/countryPhoneCodes.ts b/backend/src/helpers/countryPhoneCodes.ts new file mode 100644 index 0000000..7fd4352 --- /dev/null +++ b/backend/src/helpers/countryPhoneCodes.ts @@ -0,0 +1,242 @@ +const country_code = [{"country":"Afghanistan","code":"93","iso":"AF"}, +{"country":"Albania","code":"355","iso":"AL"}, +{"country":"Algeria","code":"213","iso":"DZ"}, +{"country":"American Samoa","code":"1-684","iso":"AS"}, +{"country":"Andorra","code":"376","iso":"AD"}, +{"country":"Angola","code":"244","iso":"AO"}, +{"country":"Anguilla","code":"1-264","iso":"AI"}, +{"country":"Antarctica","code":"672","iso":"AQ"}, +{"country":"Antigua and Barbuda","code":"1-268","iso":"AG"}, +{"country":"Argentina","code":"54","iso":"AR"}, +{"country":"Armenia","code":"374","iso":"AM"}, +{"country":"Aruba","code":"297","iso":"AW"}, +{"country":"Australia","code":"61","iso":"AU"}, +{"country":"Austria","code":"43","iso":"AT"}, +{"country":"Azerbaijan","code":"994","iso":"AZ"}, +{"country":"Bahamas","code":"1-242","iso":"BS"}, +{"country":"Bahrain","code":"973","iso":"BH"}, +{"country":"Bangladesh","code":"880","iso":"BD"}, +{"country":"Barbados","code":"1-246","iso":"BB"}, +{"country":"Belarus","code":"375","iso":"BY"}, +{"country":"Belgium","code":"32","iso":"BE"}, +{"country":"Belize","code":"501","iso":"BZ"}, +{"country":"Benin","code":"229","iso":"BJ"}, +{"country":"Bermuda","code":"1-441","iso":"BM"}, +{"country":"Bhutan","code":"975","iso":"BT"}, +{"country":"Bolivia","code":"591","iso":"BO"}, +{"country":"Bosnia and Herzegovina","code":"387","iso":"BA"}, +{"country":"Botswana","code":"267","iso":"BW"}, +{"country":"Brazil","code":"55","iso":"BR"}, +{"country":"British Indian Ocean Territory","code":"246","iso":"IO"}, +{"country":"British Virgin Islands","code":"1-284","iso":"VG"}, +{"country":"Brunei","code":"673","iso":"BN"}, +{"country":"Bulgaria","code":"359","iso":"BG"}, +{"country":"Burkina Faso","code":"226","iso":"BF"}, +{"country":"Burundi","code":"257","iso":"BI"}, +{"country":"Cambodia","code":"855","iso":"KH"}, +{"country":"Cameroon","code":"237","iso":"CM"}, +{"country":"Canada","code":"1","iso":"CA"}, +{"country":"Cape Verde","code":"238","iso":"CV"}, +{"country":"Cayman Islands","code":"1-345","iso":"KY"}, +{"country":"Central African Republic","code":"236","iso":"CF"}, +{"country":"Chad","code":"235","iso":"TD"}, +{"country":"Chile","code":"56","iso":"CL"}, +{"country":"China","code":"86","iso":"CN"}, +{"country":"Christmas Island","code":"61","iso":"CX"}, +{"country":"Cocos Islands","code":"61","iso":"CC"}, +{"country":"Colombia","code":"57","iso":"CO"}, +{"country":"Comoros","code":"269","iso":"KM"}, +{"country":"Cook Islands","code":"682","iso":"CK"}, +{"country":"Costa Rica","code":"506","iso":"CR"}, +{"country":"Croatia","code":"385","iso":"HR"}, +{"country":"Cuba","code":"53","iso":"CU"}, +{"country":"Curacao","code":"599","iso":"CW"}, +{"country":"Cyprus","code":"357","iso":"CY"}, +{"country":"Czech Republic","code":"420","iso":"CZ"}, +{"country":"Democratic Republic of the Congo","code":"243","iso":"CD"}, +{"country":"Denmark","code":"45","iso":"DK"}, +{"country":"Djibouti","code":"253","iso":"DJ"}, +{"country":"Dominica","code":"1-767","iso":"DM"}, +{"country":"Dominican Republic","code":"1-809, 1-829, 1-849","iso":"DO"}, +{"country":"East Timor","code":"670","iso":"TL"}, +{"country":"Ecuador","code":"593","iso":"EC"}, +{"country":"Egypt","code":"20","iso":"EG"}, +{"country":"El Salvador","code":"503","iso":"SV"}, +{"country":"Equatorial Guinea","code":"240","iso":"GQ"}, +{"country":"Eritrea","code":"291","iso":"ER"}, +{"country":"Estonia","code":"372","iso":"EE"}, +{"country":"Ethiopia","code":"251","iso":"ET"}, +{"country":"Falkland Islands","code":"500","iso":"FK"}, +{"country":"Faroe Islands","code":"298","iso":"FO"}, +{"country":"Fiji","code":"679","iso":"FJ"}, +{"country":"Finland","code":"358","iso":"FI"}, +{"country":"France","code":"33","iso":"FR"}, +{"country":"French Polynesia","code":"689","iso":"PF"}, +{"country":"Gabon","code":"241","iso":"GA"}, +{"country":"Gambia","code":"220","iso":"GM"}, +{"country":"Georgia","code":"995","iso":"GE"}, +{"country":"Germany","code":"49","iso":"DE"}, +{"country":"Ghana","code":"233","iso":"GH"}, +{"country":"Gibraltar","code":"350","iso":"GI"}, +{"country":"Greece","code":"30","iso":"GR"}, +{"country":"Greenland","code":"299","iso":"GL"}, +{"country":"Grenada","code":"1-473","iso":"GD"}, +{"country":"Guam","code":"1-671","iso":"GU"}, +{"country":"Guatemala","code":"502","iso":"GT"}, +{"country":"Guernsey","code":"44-1481","iso":"GG"}, +{"country":"Guinea","code":"224","iso":"GN"}, +{"country":"Guinea-Bissau","code":"245","iso":"GW"}, +{"country":"Guyana","code":"592","iso":"GY"}, +{"country":"Haiti","code":"509","iso":"HT"}, +{"country":"Honduras","code":"504","iso":"HN"}, +{"country":"Hong Kong","code":"852","iso":"HK"}, +{"country":"Hungary","code":"36","iso":"HU"}, +{"country":"Iceland","code":"354","iso":"IS"}, +{"country":"India","code":"91","iso":"IN"}, +{"country":"Indonesia","code":"62","iso":"ID"}, +{"country":"Iran","code":"98","iso":"IR"}, +{"country":"Iraq","code":"964","iso":"IQ"}, +{"country":"Ireland","code":"353","iso":"IE"}, +{"country":"Isle of Man","code":"44-1624","iso":"IM"}, +{"country":"Israel","code":"972","iso":"IL"}, +{"country":"Italy","code":"39","iso":"IT"}, +{"country":"Ivory Coast","code":"225","iso":"CI"}, +{"country":"Jamaica","code":"1-876","iso":"JM"}, +{"country":"Japan","code":"81","iso":"JP"}, +{"country":"Jersey","code":"44-1534","iso":"JE"}, +{"country":"Jordan","code":"962","iso":"JO"}, +{"country":"Kazakhstan","code":"7","iso":"KZ"}, +{"country":"Kenya","code":"254","iso":"KE"}, +{"country":"Kiribati","code":"686","iso":"KI"}, +{"country":"Kosovo","code":"383","iso":"XK"}, +{"country":"Kuwait","code":"965","iso":"KW"}, +{"country":"Kyrgyzstan","code":"996","iso":"KG"}, +{"country":"Laos","code":"856","iso":"LA"}, +{"country":"Latvia","code":"371","iso":"LV"}, +{"country":"Lebanon","code":"961","iso":"LB"}, +{"country":"Lesotho","code":"266","iso":"LS"}, +{"country":"Liberia","code":"231","iso":"LR"}, +{"country":"Libya","code":"218","iso":"LY"}, +{"country":"Liechtenstein","code":"423","iso":"LI"}, +{"country":"Lithuania","code":"370","iso":"LT"}, +{"country":"Luxembourg","code":"352","iso":"LU"}, +{"country":"Macao","code":"853","iso":"MO"}, +{"country":"Macedonia","code":"389","iso":"MK"}, +{"country":"Madagascar","code":"261","iso":"MG"}, +{"country":"Malawi","code":"265","iso":"MW"}, +{"country":"Malaysia","code":"60","iso":"MY"}, +{"country":"Maldives","code":"960","iso":"MV"}, +{"country":"Mali","code":"223","iso":"ML"}, +{"country":"Malta","code":"356","iso":"MT"}, +{"country":"Marshall Islands","code":"692","iso":"MH"}, +{"country":"Mauritania","code":"222","iso":"MR"}, +{"country":"Mauritius","code":"230","iso":"MU"}, +{"country":"Mayotte","code":"262","iso":"YT"}, +{"country":"Mexico","code":"52","iso":"MX"}, +{"country":"Micronesia","code":"691","iso":"FM"}, +{"country":"Moldova","code":"373","iso":"MD"}, +{"country":"Monaco","code":"377","iso":"MC"}, +{"country":"Mongolia","code":"976","iso":"MN"}, +{"country":"Montenegro","code":"382","iso":"ME"}, +{"country":"Montserrat","code":"1-664","iso":"MS"}, +{"country":"Morocco","code":"212","iso":"MA"}, +{"country":"Mozambique","code":"258","iso":"MZ"}, +{"country":"Myanmar","code":"95","iso":"MM"}, +{"country":"Namibia","code":"264","iso":"NA"}, +{"country":"Nauru","code":"674","iso":"NR"}, +{"country":"Nepal","code":"977","iso":"NP"}, +{"country":"Netherlands","code":"31","iso":"NL"}, +{"country":"Netherlands Antilles","code":"599","iso":"AN"}, +{"country":"New Caledonia","code":"687","iso":"NC"}, +{"country":"New Zealand","code":"64","iso":"NZ"}, +{"country":"Nicaragua","code":"505","iso":"NI"}, +{"country":"Niger","code":"227","iso":"NE"}, +{"country":"Nigeria","code":"234","iso":"NG"}, +{"country":"Niue","code":"683","iso":"NU"}, +{"country":"North Korea","code":"850","iso":"KP"}, +{"country":"Northern Mariana Islands","code":"1-670","iso":"MP"}, +{"country":"Norway","code":"47","iso":"NO"}, +{"country":"Oman","code":"968","iso":"OM"}, +{"country":"Pakistan","code":"92","iso":"PK"}, +{"country":"Palau","code":"680","iso":"PW"}, +{"country":"Palestine","code":"970","iso":"PS"}, +{"country":"Panama","code":"507","iso":"PA"}, +{"country":"Papua New Guinea","code":"675","iso":"PG"}, +{"country":"Paraguay","code":"595","iso":"PY"}, +{"country":"Peru","code":"51","iso":"PE"}, +{"country":"Philippines","code":"63","iso":"PH"}, +{"country":"Pitcairn","code":"64","iso":"PN"}, +{"country":"Poland","code":"48","iso":"PL"}, +{"country":"Portugal","code":"351","iso":"PT"}, +{"country":"Puerto Rico","code":"1-787, 1-939","iso":"PR"}, +{"country":"Qatar","code":"974","iso":"QA"}, +{"country":"Republic of the Congo","code":"242","iso":"CG"}, +{"country":"Reunion","code":"262","iso":"RE"}, +{"country":"Romania","code":"40","iso":"RO"}, +{"country":"Russia","code":"7","iso":"RU"}, +{"country":"Rwanda","code":"250","iso":"RW"}, +{"country":"Saint Barthelemy","code":"590","iso":"BL"}, +{"country":"Saint Helena","code":"290","iso":"SH"}, +{"country":"Saint Kitts and Nevis","code":"1-869","iso":"KN"}, +{"country":"Saint Lucia","code":"1-758","iso":"LC"}, +{"country":"Saint Martin","code":"590","iso":"MF"}, +{"country":"Saint Pierre and Miquelon","code":"508","iso":"PM"}, +{"country":"Saint Vincent and the Grenadines","code":"1-784","iso":"VC"}, +{"country":"Samoa","code":"685","iso":"WS"}, +{"country":"San Marino","code":"378","iso":"SM"}, +{"country":"Sao Tome and Principe","code":"239","iso":"ST"}, +{"country":"Saudi Arabia","code":"966","iso":"SA"}, +{"country":"Senegal","code":"221","iso":"SN"}, +{"country":"Serbia","code":"381","iso":"RS"}, +{"country":"Seychelles","code":"248","iso":"SC"}, +{"country":"Sierra Leone","code":"232","iso":"SL"}, +{"country":"Singapore","code":"65","iso":"SG"}, +{"country":"Sint Maarten","code":"1-721","iso":"SX"}, +{"country":"Slovakia","code":"421","iso":"SK"}, +{"country":"Slovenia","code":"386","iso":"SI"}, +{"country":"Solomon Islands","code":"677","iso":"SB"}, +{"country":"Somalia","code":"252","iso":"SO"}, +{"country":"South Africa","code":"27","iso":"ZA"}, +{"country":"South Korea","code":"82","iso":"KR"}, +{"country":"South Sudan","code":"211","iso":"SS"}, +{"country":"Spain","code":"34","iso":"ES"}, +{"country":"Sri Lanka","code":"94","iso":"LK"}, +{"country":"Sudan","code":"249","iso":"SD"}, +{"country":"Suriname","code":"597","iso":"SR"}, +{"country":"Svalbard and Jan Mayen","code":"47","iso":"SJ"}, +{"country":"Swaziland","code":"268","iso":"SZ"}, +{"country":"Sweden","code":"46","iso":"SE"}, +{"country":"Switzerland","code":"41","iso":"CH"}, +{"country":"Syria","code":"963","iso":"SY"}, +{"country":"Taiwan","code":"886","iso":"TW"}, +{"country":"Tajikistan","code":"992","iso":"TJ"}, +{"country":"Tanzania","code":"255","iso":"TZ"}, +{"country":"Thailand","code":"66","iso":"TH"}, +{"country":"Togo","code":"228","iso":"TG"}, +{"country":"Tokelau","code":"690","iso":"TK"}, +{"country":"Tonga","code":"676","iso":"TO"}, +{"country":"Trinidad and Tobago","code":"1-868","iso":"TT"}, +{"country":"Tunisia","code":"216","iso":"TN"}, +{"country":"Turkey","code":"90","iso":"TR"}, +{"country":"Turkmenistan","code":"993","iso":"TM"}, +{"country":"Turks and Caicos Islands","code":"1-649","iso":"TC"}, +{"country":"Tuvalu","code":"688","iso":"TV"}, +{"country":"U.S. Virgin Islands","code":"1-340","iso":"VI"}, +{"country":"Uganda","code":"256","iso":"UG"}, +{"country":"Ukraine","code":"380","iso":"UA"}, +{"country":"United Arab Emirates","code":"971","iso":"AE"}, +{"country":"United Kingdom","code":"44","iso":"GB"}, +{"country":"United States","code":"1","iso":"US"}, +{"country":"Uruguay","code":"598","iso":"UY"}, +{"country":"Uzbekistan","code":"998","iso":"UZ"}, +{"country":"Vanuatu","code":"678","iso":"VU"}, +{"country":"Vatican","code":"379","iso":"VA"}, +{"country":"Venezuela","code":"58","iso":"VE"}, +{"country":"Vietnam","code":"84","iso":"VN"}, +{"country":"Wallis and Futuna","code":"681","iso":"WF"}, +{"country":"Western Sahara","code":"212","iso":"EH"}, +{"country":"Yemen","code":"967","iso":"YE"}, +{"country":"Zambia","code":"260","iso":"ZM"}, +{"country":"Zimbabwe","code":"263","iso":"ZW"}] + +export default country_code; diff --git a/backend/src/server.ts b/backend/src/server.ts index d7c2d29..2ab92c0 100644 --- a/backend/src/server.ts +++ b/backend/src/server.ts @@ -112,7 +112,7 @@ setTimeout(async () => { console.log('USER ID: ', users[i].id) - await new Promise(f => setTimeout(f, 300)); + await new Promise(f => setTimeout(f, 100)); } } diff --git a/backend/src/services/MessageServices/CreateMessageService.ts b/backend/src/services/MessageServices/CreateMessageService.ts index b0d991b..853cd07 100644 --- a/backend/src/services/MessageServices/CreateMessageService.ts +++ b/backend/src/services/MessageServices/CreateMessageService.ts @@ -19,7 +19,7 @@ interface Request { const CreateMessageService = async ({ messageData }: Request): Promise => { - console.log('UPSERT MESSAGE messageData: ', messageData) + // console.log('UPSERT MESSAGE messageData: ', messageData) await Message.upsert(messageData); diff --git a/backend/src/services/WbotServices/wbotMessageListener.ts b/backend/src/services/WbotServices/wbotMessageListener.ts index 99cecba..74a1837 100644 --- a/backend/src/services/WbotServices/wbotMessageListener.ts +++ b/backend/src/services/WbotServices/wbotMessageListener.ts @@ -418,9 +418,7 @@ const handleMessage = async ( msg: any, wbot: any ): Promise => { - - console.log('kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk') - + if (!msg.fromMe) { _clear_lst() diff --git a/backend/src/services/WhatsappService/CreateWhatsAppService.ts b/backend/src/services/WhatsappService/CreateWhatsAppService.ts index 5217316..070c949 100644 --- a/backend/src/services/WhatsappService/CreateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/CreateWhatsAppService.ts @@ -45,11 +45,12 @@ const CreateWhatsAppService = async ({ return !nameExists; } ), - isDefault: Yup.boolean().required() + isDefault: Yup.boolean().required(), + urlApi: Yup.string().required() }); try { - await schema.validate({ name, status, isDefault }); + await schema.validate({ name, status, isDefault, urlApi }); } catch (err: any) { throw new AppError(err.message); } diff --git a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts index 5bd97cf..4c20829 100644 --- a/backend/src/services/WhatsappService/UpdateWhatsAppService.ts +++ b/backend/src/services/WhatsappService/UpdateWhatsAppService.ts @@ -13,6 +13,8 @@ import { restartWhatsSession } from "../../helpers/RestartWhatsSession"; interface WhatsappData { name?: string; + url?: string; + urlApi?: string; status?: string; session?: string; isDefault?: boolean; @@ -45,6 +47,8 @@ const UpdateWhatsAppService = async ({ name, status, isDefault, + url, + urlApi, session, greetingMessage, farewellMessage, @@ -88,6 +92,8 @@ const UpdateWhatsAppService = async ({ name, status, session, + url, + urlApi, greetingMessage, farewellMessage, isDefault diff --git a/frontend/src/components/WhatsAppModal/index.js b/frontend/src/components/WhatsAppModal/index.js index a930703..57d0cd0 100644 --- a/frontend/src/components/WhatsAppModal/index.js +++ b/frontend/src/components/WhatsAppModal/index.js @@ -53,7 +53,7 @@ const useStyles = makeStyles(theme => ({ const SessionSchema = Yup.object().shape({ name: Yup.string() .min(2, "Too Short!") - .max(50, "Too Long!") + .max(100, "Too Long!") .required("Required"), }); @@ -90,14 +90,31 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => { const handleSaveWhatsApp = async values => { const whatsappData = { ...values, queueIds: selectedQueueIds }; + let response = null + try { if (whatsAppId) { - await api.put(`/whatsapp/${whatsAppId}`, whatsappData); + response = await api.put(`/whatsapp/${whatsAppId}`, whatsappData); } else { - await api.post("/whatsapp", whatsappData); + response = await api.post("/whatsapp", whatsappData); } - toast.success(i18n.t("whatsappModal.success")); - handleClose(); + + console.log('response: ', response.data.message) + + if(response && response.data.message === 'wrong_number_start'){ + alert('O numero contido no nome da conexão deve iniciar com o código do país!') + } + else if(response && response.data.message === 'invalid_phone_number'){ + alert('A quantidade de numeros digitados no nome do contato é invalida! Certifique-se de que você digitou o numero correto acompanhado pelo código do país!') + } + else if( response && response.data.message === 'no_phone_number'){ + alert('Para criar/editar uma sessão de Whatsapp é necessário que o numero do Whatsapp acompanhado pelo código do país esteja presente no nome da sessão!') + } + else{ + toast.success(i18n.t("whatsappModal.success")); + handleClose(); + } + } catch (err) { toastError(err); }