Criação de commit para url da api que gerencia a criaçado api de sessoes remotas

pull/21/head
adriano 2023-02-13 09:43:00 -03:00
parent b309a43fe3
commit 3c2790e3d4
32 changed files with 10005 additions and 7 deletions

View File

@ -0,0 +1,3 @@
PORT=8019
PORT_START=8020
BASE_URL=http://localhost

View File

@ -0,0 +1,315 @@
const express = require('express');
const bodyparser = require('body-parser');
const dotenv = require('dotenv');
dotenv.config({ path: '.env' });
const copyFolder = require('./helpers/copyFolder')
const createDir = require('./helpers/createDir')
const createFile = require('./helpers/createFile')
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 app = express();
app.use(bodyparser.json());
app.get('/', function (req, res) { return res.send('Express + TypeScript Server'); });
app.post('/api/session', async function (req, res) {
const { app_name, whatsappId, client_url, number } = req.body
console.log('__dirname: ', path.join(__dirname, '..', app_name))
console.log(app_name, whatsappId, client_url)
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)
let dirSessionsApp = path.join(sessionsPath, app_name)
if (dirExist.length == 0) {
let create = createDir(dirSessionsApp)
if (!create) {
res.status(500).json({ message: 'Cannot create the directory path!' })
return
}
}
let appPort = []
let existSubDir = false
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])
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 newPath = path.join(sessionsPath, directoriesInDIrectory[i], newSessionAppName)
try {
fs.renameSync(currPath, newPath)
console.log("Successfully renamed the directory.")
} catch (err) {
console.log(err)
}
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
}
appPort.push(+subDir[x].split('_')[3])
existSubDir = true
}
}
appPort = existSubDir ? Math.max(...appPort) + 1 : process.env.PORT_START
console.log('new port: ', appPort)
let dirSessionAppName
let numberSession = 1
const dirSessionsNumberAppDirectories = fs.readdirSync(dirSessionsApp, { withFileTypes: true })
.filter((item) => item.isDirectory() && item.name.includes(`${number}`))
.map((item) => item.name);
console.log('dirSessionsNumberAppDirectories', dirSessionsNumberAppDirectories, ' | dirSessionsApp: ', dirSessionsApp)
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
}
}
dirSessionAppName = `${whatsappId}_${number}_${numberSession}_${appPort}`
destDir = path.join(dirSessionsApp, dirSessionAppName)
originDir = path.join(__dirname, '..', 'whats')
copyFolder(originDir, destDir)
let db = db_info.filter((e) => e.client_url == client_url)
if (db && db.length > 0) {
db = db[0].db_conf
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)
}
});
})
let whatsName
if (whatsapp[0]["name"].split('->').length > 0) {
whatsName = `${whatsapp[0]["name"].split('->')[0]} -> S${numberSession}`
}
else {
whatsName = `${whatsapp[0]["name"]} -> S${numberSession}`
}
mysql_conn(db).query("UPDATE Whatsapps SET url = ?, name = ? where id = ?", [`${process.env.BASE_URL}:${appPort}`, `${whatsName}`, whatsappId],
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
let 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('whatsapp: ', whatsapp)
console.log("whatsapp[0]['name']: ", whatsapp[0]['name'])
const keys = Object.keys(db);
var stream = fs.createWriteStream(path.join(destDir, '.env'));
stream.once('open', function (fd) {
stream.write("# NUMBER AND NAME THAT WILL BE DISPLAYED ON CONSOLE\n");
stream.write(`MOBILEUID=${number}\n`);
stream.write(`MOBILENAME=${whatsappName}\n`);
stream.write("\n");
stream.write("# PORT NUMBER FOR THIS API\n");
stream.write(`PORT=${appPort}\n`);
stream.write("\n");
stream.write("# URL FROM THE OMNIHIT BACKEND API\n");
stream.write(`CLIENT_URL=${client_url}\n`);
stream.write("\n");
stream.write("# OMNIHIT DATABASE\n");
keys.forEach((key, index) => {
stream.write(`${key}=${db[key]}\n`);
});
stream.write("\n");
stream.write(`# WHATSAPP ID OF THE TABLE Whatsapps FROM THE OMNIHIT DATABASE\n`);
stream.write(`WHATSAPP_ID=${whatsappId}`);
stream.end();
});
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}`);
// });
}
res.send("OK");
});
app.post('/api/session/edit', async function (req, res) {
const { app_name, whatsappId, client_url, number } = req.body
})
app.listen(process.env.PORT || 8003, function () {
console.log("\u26A1[server]: Server is running at Port ::: " + process.env.PORT || 8003);
});
process.on('uncaughtException', function (err) {
console.error(' ');
console.error('----- ' + (new Date).toUTCString() + ' ----------------------------------')
console.error('Erro uncaughtException: ', err.message)
console.error(err.stack)
console.error(' ');
return
});

View File

@ -0,0 +1,27 @@
const db = [
{
client_url: "http://localhost:8080",
db_conf: {
DB: "whaticket",
DB_HOST: "localhost",
DB_USER: "whaticket",
DB_PASS: "strongpassword",
DB_PORT: "3306"
}
},
{
client_url: "http://localhost:8081",
db_conf: {
DB: "whaticket",
DB_HOST: "localhost",
DB_USER: "whaticket",
DB_PASS: "strongpassword",
DB_PORT: "3306"
}
}
]
module.exports = db;

View File

@ -0,0 +1,17 @@
const fsPromises = require("fs/promises");
const fs = require('fs-extra')
// Delete a directory and its children
function copyFolder(sourcePath, destPath) {
fs.copySync(sourcePath, destPath, { overwrite: true }, (err) => {
if (err) {
console.error(err);
} else {
console.log("Copy dir success!");
}
});
}
module.exports = copyFolder;

View File

@ -0,0 +1,22 @@
const fs = require('fs');
function createDir(dir) {
// create new directory
try {
// check if directory already exists
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir);
console.log("Directory is created.");
} else {
console.log("Directory already exists.");
}
} catch (err) {
console.log(err);
return false
}
return true
}
module.exports = createDir;

View File

@ -0,0 +1,17 @@
const fs = require('fs');
function createFile(saveDir, rows, fileName) {
var stream = fs.createWriteStream(path.join(saveDir, fileName));
stream.once('open', function (fd) {
rows.forEach(element => {
stream.write(element);
});
stream.end();
});
}
module.exports = createFile

View File

@ -0,0 +1,109 @@
const dotenv = require('dotenv');
dotenv.config({ path: `${process.cwd()}/.env` });
const path = require('path')
function mysql_conn(config) {
// Ubicua Plataform - MYSQL Module
try {
var mysql_npm = require('mysql');
} catch (err) {
console.log("Cannot find `mysql` module. Is it installed ? Try `npm install mysql` or `npm install`.");
}
var db_config = {
host: config.DB_HOST,
user: config.DB_USER,
password: config.DB_PASS,
database: config.DB,
charset: 'utf8mb4_general_ci',
port: config.DB_PORT
};
//-
//- Create the connection variable
//-
var connection = mysql_npm.createPool(db_config);
//-
//- Establish a new connection
//-
connection.getConnection(function (err) {
if (err) {
// mysqlErrorHandling(connection, err);
console.log("\n\t *** Cannot establish a connection with the database. ***");
connection = reconnect(connection);
} else {
console.log("\n\t *** New connection established with the database. ***")
}
});
//-
//- Reconnection function
//-
function reconnect(connection) {
console.log("\n New connection tentative...");
//- Create a new one
connection = mysql_npm.createPool(db_config);
//- Try to reconnect
connection.getConnection(function (err) {
if (err) {
//- Try to connect every 2 seconds.
setTimeout(reconnect(connection), 2000);
} else {
console.log("\n\t *** New connection established with the database. ***")
return connection;
}
});
}
//-
//- Error listener
//-
connection.on('error', function (err) {
//-
//- The server close the connection.
//-
if (err.code === "PROTOCOL_CONNECTION_LOST") {
console.log("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
return reconnect(connection);
}
else if (err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT") {
console.log("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
return reconnect(connection);
}
else if (err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR") {
console.log("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
return reconnect(connection);
}
else if (err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE") {
console.log("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
}
else {
console.log("/!\\ Cannot establish a connection with the database. /!\\ (" + err.code + ")");
return reconnect(connection);
}
});
return connection
}
//-
//- Export
//-
module.exports = mysql_conn;

View File

@ -0,0 +1,28 @@
const fsPromises = require("fs/promises");
const fs = require('fs')
// Delete a directory and its children
const removeDir = async (dirPath) => {
if (fs.existsSync(dirPath)) {
try {
await fsPromises.rm(dirPath, { recursive: true, force: true });
console.log("Directory removed!");
return true
}
catch (err) {
console.log('An error occurred while removing the directory: ', err);
}
}
else {
console.log('Directory not found to remove: ', dirPath)
}
return false
}
module.exports = removeDir ;

View File

@ -0,0 +1,152 @@
import os from 'os';
import dir from 'path';
import fs from 'fs';
export const setJSON = (obj) => {
const sessionControlFile = dir.join(process.cwd(), `sessionsDir.json`);
try {
if (fs.existsSync(sessionControlFile)) {
const sessionsDir = fs.readFileSync(sessionControlFile, { encoding: 'utf8', flag: 'r' });
let lstRestore = JSON.parse(sessionsDir)
lstRestore.push(obj)
fs.writeFileSync(sessionControlFile, JSON.stringify(lstRestore), "utf8");
} else {
console.log('sessionsDir.json file not found! It will be created.');
if (Array.isArray(obj)) {
fs.writeFileSync(sessionControlFile, JSON.stringify(obj), "utf8");
}
else {
fs.writeFileSync(sessionControlFile, JSON.stringify([obj]), "utf8");
}
}
} catch (error) {
console.log('There was an error on try to read the sessionsDir.json file: ', error)
}
}
export const shifRestoreControll = () => {
const sessionControlFile = dir.join(os.tmpdir(), `sessionsDir.json`);
try {
if (fs.existsSync(sessionControlFile)) {
const sessionsDir = fs.readFileSync(sessionControlFile, { encoding: 'utf8', flag: 'r' });
let lstRestore: any = JSON.parse(sessionsDir)
let whatsapp: any = lstRestore.shift()
fs.writeFileSync(sessionControlFile, JSON.stringify(lstRestore), "utf8");
return whatsapp
}
} catch (error) {
console.log('There was an error on try to read the sessionsDir.json file: ', error)
}
return {}
}
export const delRestoreControllFile = () => {
const sessionControlFile = dir.join(os.tmpdir(), `sessionsDir.json`);
try {
if (fs.existsSync(sessionControlFile)) {
fs.unlinkSync(sessionControlFile)
} else {
console.log('sessionsDir.json file not found!');
}
} catch (error) {
console.log('There was an error on try delete the sessionsDir.json file: ', error)
}
}
export const getRestoreControll = () => {
const sessionControlFile = dir.join(os.tmpdir(), `sessionsDir.json`);
try {
if (fs.existsSync(sessionControlFile)) {
const sessionsDir = fs.readFileSync(sessionControlFile, { encoding: 'utf8', flag: 'r' });
let lstRestore: any = JSON.parse(sessionsDir)
return lstRestore
} else {
console.log('sessionsDir.json file not found!');
}
} catch (error) {
console.log('There was an error on try to read the sessionsDir.json file: ', error)
}
return []
}
export const _restore = async (whatsapp: Whatsapp, msg_file_title: string) => {
return
if (whatsapp.status != 'RESTORING' && whatsapp.status != 'qrcode') {
console.log('THE WHATSAAP ID: ', whatsapp.id, ' WILL BE RESTORED SOON!')
await whatsapp.update({ status: "RESTORING", });
const io = getIO();
io.emit("whatsappSession", {
action: "update",
session: whatsapp
});
// await insertOrUpeateWhatsCache(`whatsapp:${whatsapp.id}`, { status: "RESTORING", })
setTimeout(async () => await autoRestore(whatsapp.id, msg_file_title), 95000);
}
}

2194
TEST_SERVER1/api/package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,22 @@
{
"name": "api-sessions-controller",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "nodemon app.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "Adriano <adriano08andrade@hotmail.com>",
"license": "MIT",
"dependencies": {
"body-parser": "^1.20.1",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"fs-extra": "^11.1.0",
"mysql": "^2.18.1",
"nodemon": "^2.0.20",
"socket.io": "^4.5.4"
}
}

View File

@ -0,0 +1,20 @@
# NUMBER AND NAME THAT WILL BE DISPLAYED ON CONSOLE
MOBILEUID=5517988310949
MOBILENAME=Numero de teste
# PORT NUMBER FOR THIS API
PORT=8020
# URL FROM THE OMNIHIT BACKEND API
CLIENT_URL=http://localhost:8080
# OMNIHIT DATABASE
DB=whaticket
DB_HOST=localhost
DB_USER=whaticket
DB_PASS=strongpassword
DB_PORT=3306
# WHATSAPP ID OF THE TABLE Whatsapps FROM THE OMNIHIT DATABASE
WHATSAPP_ID=46

31
TEST_SERVER1/whats/.gitignore vendored 100644
View File

@ -0,0 +1,31 @@
# dependencies
node_modules
/node_modules
/medias/*.*
/medias/in/*.*
/WWebJS/session-OmniHIT/Default/**
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
DevToolsActivePort*
npm-debug.log*
yarn-debug.log*
yarn-error.log*

View File

@ -0,0 +1,922 @@
'use strict';
const { initIO } = require("./helpers/socket")
const backup_session = require('./helpers/backup_session');
const restore = require('./helpers/restore');
const { Client, Location, List, Buttons, LocalAuth } = require('whatsapp-web.js/index');
const { MessageMedia } = require('./node_modules/whatsapp-web.js/src/structures');
const qrencode = require('qr-encode');
const axios = require('axios').default;
const bodyparser = require('body-parser');
const path = require('path');
const fs = require('fs');
const express = require('express');
// const dbcloud = require('./funcs/dbcloud.js');
const FormData = require('form-data');
const logger = require('logger')
const dotenv = require('dotenv');
dotenv.config({ path: '.env' });
const mime = require('mime');
const qrcode = require('qrcode-terminal');
const omnihit = require('./funcs/omnihit.js');
const { allowedNodeEnvironmentFlags } = require('process');
require("./funcs/tools.js")();
let scheduler_messages_outbound;
let scheduler_monitor;
let scheduler_monitor_cell;
let client;
// const PORT = 80;
let sendSeen = false
let unreadMessaesProcess
const { imageUpload } = require('./helpers/image-uploader')
var QRCODE = "0";
var mobileuid;
var destroy;
let asking_qrcode = false
const dbcc = require('./helpers/mysql_conn.js');
const removeDir = require('./helpers/remove_dir');
// (async()=>{
// backup_session(destroy)
// clearTimeout(destroy)
// })
// console.log('PASSOU............')
// return
// Sleep
const sleep = (ms) => {
return new Promise((resolve) => setTimeout(resolve, ms));
};
const app = express();
app.use(express.static(path.join(__dirname, 'public')));
//app.use(bodyparser.urlencoded({ extended: true }));
app.use(bodyparser.json());
const sessionName = process.env.MOBILEUID;
// console.log('DIRNAME: ', path.join(__dirname, '.wwebjs_auth', 'session-omnihit_sesssion'))
//TEST DEL
console.log('process.env.CLIENT_URL: ', process.env.CLIENT_URL)
console.log('1');
// Connect to server
var io = require('socket.io-client');
// const socket = initIO('http://localhost:8024')
const socketIo = io(process.env.CLIENT_URL, { reconnect: true, maxHttpBufferSize: 1e8 });
socketIo.on('connect', async function () {
console.log('Made socket connection', socketIo.id);
console.log('process.env.WHATSAPP_ID: ', process.env.WHATSAPP_ID)
socketIo.emit('joinWhatsSession', process.env.WHATSAPP_ID);
sendSeen = true
if (mobileuid) {
console.log('Socket conectado com o cliente: ', mobileuid)
setTimeout(async () => {
console.log('Entro no syncUnreadMessages ON CONNECTED SOCKET')
await syncUnreadMessages(client)
client.sendPresenceAvailable();
}, 5000)
}
});
socketIo.on('message_from_server', function () {
console.log('message_from_server data: ');
});
// socketIo.on('disconnect', function () {
// console.log('disconnect');
// });
// Send a message to the server 3 seconds after initial connection.
// setInterval(function () {
// socketIo.emit('message_from_client', 'Sent an event from the client!');
// }, 3000);
socketIo.on('connect_error', async function (err) {
console.log('connection errror', err);
sendSeen = false
if (mobileuid) {
client.sendPresenceUnavailable()
}
});
//
//NOVA OPÇÃO MD
client = new Client({
authStrategy: new LocalAuth({ clientId: 'omnihit_sesssion' }),
puppeteer: { args: ['--no-sandbox', '--disable-setuid-sandbox'], executablePath: process.env.CHROME_BIN || '/usr/bin/google-chrome-stable' },
});
client.initialize();
client.on("qr", async qr => {
console.log("Session:", sessionName);
// Generate and scan this code with your phone
QRCODE = qr;
qrcode.generate(qr, { small: true })
console.log('QR RECEIVED', qr);
// omnihit.qrcode(process.env.MOBILEUID, process.env.MOBILENAME, qr);
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, "STARTUP");
asking_qrcode = true
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ? where id = ?", [qr, 'qrcode', 0, process.env.WHATSAPP_ID],
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
try {
let response = await axios.post(url, { whatsappId: process.env.WHATSAPP_ID });
} catch (error) {
console.log('There was an error on POST THE DATA TO URL: ', url, '\n' + error);
}
});
client.on("authenticated", async session => {
console.log(`Session: ${sessionName} AUTHENTICATED`);
});
client.on("auth_failure", async msg => {
console.log(
`Session: ${sessionName} AUTHENTICATION FAILURE! Reason: ${msg}`
);
omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, "AUTHFAILURE");
//reject(new Error("Error starting whatsapp session."));
});
client.on("ready", async () => {
console.log(`Session: ${sessionName} READY`);
// console.log('>>>>>>>>>>>>>> ready client.ts MOBILE NUMBER: ', client.info["wid"]["user"])
mobileuid = client.info["wid"]["user"];
console.log(new Date().toISOString() + " >>> Mobile UID ::: " + mobileuid);
// logger.info(`Session: ${sessionName} READY`);
const whatsapp = await new Promise((resolve, reject) => {
dbcc.query("SELECT * from Whatsapps where id = ?", [process.env.WHATSAPP_ID], (err, result) => {
if (err) {
reject(err)
}
else {
resolve(result)
}
});
})
if (whatsapp[0]['name'].includes(client.info["wid"]["user"])) {
console.log('-----------------> THIS IS THE RIGHT NUMBER')
}
else {
console.log('-----------------> THIS IS THE WRONG NUMBER')
let read_number = client.info["wid"]["user"]
let url = process.env.CLIENT_URL + '/whatsapp/connection/number'
try {
await client.logout()
let response = await axios.post(url, { number: read_number });
} catch (error) {
console.log('There was an error on POST THE DATA TO URL: ', url, '\n' + error);
}
return
}
dbcc.query("UPDATE Whatsapps SET qrcode = ?, status = ?, retries = ?, number = ? where id = ?", ["", 'CONNECTED', 0, client.info["wid"]["user"], process.env.WHATSAPP_ID],
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
let url = process.env.CLIENT_URL + '/whatsapp/connection/qrcode'
try {
let response = await axios.post(url, { whatsappId: process.env.WHATSAPP_ID });
} catch (error) {
console.log('There was an error on POST THE DATA TO URL: ', url, '\n' + error);
}
console.log('SEND SEEN: ', sendSeen)
await syncUnreadMessages(client)
if (sendSeen) {
client.sendPresenceAvailable();
}
// if(asking_qrcode){
// // backup_session(destroy, 120000, true)
// }
backup_session(destroy, 120000, false)
asking_qrcode = false
console.log('PASSOU............')
});
async function read() {
let chats = await client.getState();
console.log(chats);
}
client.on("message_create", async msg => {
if (msg.hasMedia && msg.fromMe)
return
await handleMessage(msg);
});
client.on("media_uploaded", async msg => {
console.log('Entrou no midia upload')
let msgContact = null
let media = null
if (msg.fromMe) {
msgContact = await client.getContactById(msg.to);
}
else {
msgContact = await msg.getContact();
}
const chat = await msg.getChat();
msgContact.getProfilePicUrl = await msgContact.getProfilePicUrl()
let quotedMsg = await msg.getQuotedMessage();
if (msg.hasMedia) {
media = await msg.downloadMedia();
}
let data = {
id: process.env.WHATSAPP_ID,
msg: msg,
msgContact: msgContact,
chat: chat,
quotedMsg: quotedMsg ? quotedMsg.id.id : null,
media: media
}
socketIo.emit("media_uploaded", data);
});
client.on("message_ack", async (msg, ack) => {
let data = {
whatsappId: process.env.WHATSAPP_ID,
id: msg.id.id,
ack: ack
}
socketIo.emit("message_ack", data);
});
socketIo.on('send_message', async data => {
console.log('#')
console.log('--------------> send_message from number: ', mobileuid);
console.log('--------------> send_message to number: ', data.msg.number);
console.log('--------------> send_message body: ', data.msg.body);
console.log('--------------> send_message quotedMessageId: ', data.msg.quotedMessageId);
console.log('--------------> send_message linkPreview: ', data.msg.linkPreview);
console.log('#')
const sentMessage = await client.sendMessage(data.msg.number, data.msg.body, { quotedMessageId: data.msg.quotedMessageId, linkPreview: data.msg.linkPreview });
// console.log('=====================> sentMessage: ', sentMessage)
});
socketIo.on('send_media', async data => {
console.log('#')
console.log('--------------> send_message from number: ', mobileuid);
console.log('--------------> send_message to number: ', data.msg.number);
// console.log('--------------> send_message media: ', data.msg.media);
console.log('--------------> send_message sendAudioAsVoice: ', data.msg.sendAudioAsVoice);
console.log('--------------> data.msg.media.mimetype: ', data.msg.media.mimetype);
console.log('--------------> data.msg.media.filename: ', data.msg.media.filename);
console.log('#')
let media = new MessageMedia(data.msg.media.mimetype, data.msg.media.data, data.msg.media.file);
if (media && !media.filename)
media.filename = data.msg.media.filename
const sentMessage = await client.sendMessage(data.msg.number, media, { sendAudioAsVoice: data.msg.sendAudioAsVoice });
// const fullFilename = process.cwd() + process.env.MEDIA_DOWNLOAD_IN + data.msg.media.filename;
// console.log('fullFIlename: ', fullFilename)
// fs.writeFileSync(fullFilename, data.msg.media.data, { encoding: 'base64' });
});
client.on("change_state", async newState => {
let omnihit_url = process.env.CLIENT_URL + '/whatsapp/connection/monitor'
// logger.info(`Monitor session: ${sessionName}, ${newState}`);
console.log('>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ', client.info["wid"]["user"])
let data = {
action: 'change_state',
whatsappId: process.env.WHATSAPP_ID
};
await whatsappMonitor(newState, omnihit_url, data);
});
client.on("disconnected", async reason => {
let omnihit_url = process.env.CLIENT_URL + '/whatsapp/connection/monitor'
console.log('>>>>>>>>>>>>>> change_state wbotMonitor.ts MOBILE NUMBER: ', client.info["wid"]["user"])
let data = {
action: 'disconnected',
whatsappId: process.env.WHATSAPP_ID,
reason: reason
};
await removeDir(path.join(__dirname, '.wwebjs_auth', 'session-omnihit_sesssion'))
setTimeout(() => {
process.exit()
}, 3000)
await whatsappMonitor('OPENING', omnihit_url, data);
});
app.get('/', function (req, res) { return res.send('Express + TypeScript Server'); });
app.post('/start', function (req, res) {
client.initialize();
res.send("OK");
});
app.post('/qr', function (req, res) {
res.send(QRCODE);
});
app.post('/api/getWbotMessage', async (req, res) => {
const { number, messageId, limit } = req.body
console.log('number: ', number, ' | limit: ', limit)
const wbotChat = await client.getChatById(number);
const fetchWbotMessagesGradually = async () => {
const chatMessages = await wbotChat.fetchMessages({ limit });
const msgFound = chatMessages.find(msg => msg.id.id === messageId);
if (!msgFound && limit < 100) {
limit += 20;
return fetchWbotMessagesGradually();
}
return msgFound;
};
try {
const msgFound = await fetchWbotMessagesGradually();
if (!msgFound) {
res.status(404).json({ message: "Cannot found message within 100 last messages" });
return
}
res.status(200).json({ message: "ok", data: msgFound });
} catch (err) {
console.log('ERR_FETCH_WAPP_MSG: ', err)
res.status(404).json({ message: "ERR_FETCH_WAPP_MSG" });
}
})
app.post('/api/disconnect', async (req, res) => {
try {
console.log('Restaring the session.........')
await removeDir(path.join(__dirname, '.wwebjs_auth', 'session-omnihit_sesssion'))
await client.logout();
setTimeout(() => {
process.exit()
}, 3000)
} catch (error) {
console.log('There was an error on try disconnect the whatsapp: ', error)
}
res.status(200).json({ message: "ok" });
})
app.post('/api/DeleteWhatsAppMessage', async (req, res) => {
const { number, messageId, limit } = req.body
console.log('number: ', number, ' | messageId: ', messageId, ' | limit: ', limit)
try {
const messageToDelete = await getWbotMessage(messageId, number, limit)
await messageToDelete.delete(true);
res.status(200).json({ message: "ok", data: messageToDelete });
return
} catch (error) {
console.log('There was an error on try disconnect the whatsapp: ', error)
res.status(500).json({ message: "There was an error on trying delete the message" });
return
}
})
app.post('/api/GetProfilePicUrl', async (req, res) => {
const { number } = req.body
console.log('THE NUMBER: ', number)
const profilePicUrl = await client.getProfilePicUrl(`${number}@c.us`);
res.status(200).json({ message: "ok", data: profilePicUrl });
})
app.post('/api/restore', async (req, res) => {
await restore(client)
res.status(200).json({ message: "ok" });
})
app.get('/api/connection/status', async (req, res) => {
let stat
try {
stat = await client.getState();
} catch (err) {
let terr = err.message;
stat = (terr.search('Session closed') > -1 ? 'SESSIONCLOSED' : 'UNKNOWN')
}
res.status(200).json({ message: "ok", data: stat });
})
const syncUnreadMessages = async (wbot) => {
console.log('ENTROU NO UNREAD MESSAGES +++++++++++++=')
const chats = await wbot.getChats();
/* eslint-disable no-restricted-syntax */
/* eslint-disable no-await-in-loop */
for (const chat of chats) {
if (chat.unreadCount > 0) {
const unreadMessages = await chat.fetchMessages({
limit: chat.unreadCount
});
for (const msg of unreadMessages) {
// console.log('--BACKEND MSG: ', msg)
if (!sendSeen) {
return
}
await handleMessage(msg, wbot);
}
console.log(':::::::::::::::::::::::::::::PASSOU')
await chat.sendSeen();
}
}
};
const getWbotMessage = async (messageId, number, limit,) => {
const wbotChat = await client.getChatById(number);
const fetchWbotMessagesGradually = async () => {
const chatMessages = await wbotChat.fetchMessages({ limit });
const msgFound = chatMessages.find(msg => msg.id.id === messageId);
if (!msgFound && limit < 100) {
limit += 20;
return fetchWbotMessagesGradually();
}
return msgFound;
};
try {
const msgFound = await fetchWbotMessagesGradually();
if (!msgFound) {
return null
}
return msgFound
} catch (err) {
console.log('ERR_FETCH_WAPP_MSG: ', err)
}
return null
}
async function whatsappMonitor(newState, omnihit_url, data) {
dbcc.query("UPDATE Whatsapps SET status = ? where id = ?", [newState, process.env.WHATSAPP_ID],
function (err, result) {
if (err)
console.log("ERROR: " + err);
// else
// console.log('myslq result: ', result);
});
try {
let response = await axios.post(omnihit_url, data);
} catch (error) {
console.log('There was an error on POST THE DATA TO URL: ', omnihit_url, '\n' + error);
}
}
async function handleMessage(msg) {
console.log('Entrou no message_create');
let msgContact = null;
let media = null;
if (msg.fromMe) {
msgContact = await client.getContactById(msg.to);
}
else {
console.log('################# RECEIVING MESSAGE FROM: ', msg.from, ' to ', msg.to)
msgContact = await msg.getContact();
}
const chat = await msg.getChat();
msgContact.getProfilePicUrl = await msgContact.getProfilePicUrl();
let quotedMsg = await msg.getQuotedMessage();
if (msg.hasMedia) {
media = await msg.downloadMedia();
}
let data = {
id: process.env.WHATSAPP_ID,
msg: msg,
msgContact: msgContact,
chat: chat,
quotedMsg: quotedMsg ? quotedMsg.id.id : null,
media: media
};
socketIo.emit("message_create", data);
}
async function getlabels() {
var ret = await client.getContactById('551721379544-1625752306@g.us');
//createGroup('The books', ['551100000000@c.us']);
console.log("-- Chats --------------------------------");
console.log(ret);
return ret;
}
function base64_encode(file) {
// read binary data
var bitmap = fs.readFileSync(file);
// convert binary data to base64 encoded string
return new Buffer(bitmap).toString('base64');
}
function getBase64(url) {
return axios
.get(url, {
responseType: 'arraybuffer'
})
.then(response => Buffer.from(response.data, 'binary').toString('base64'))
}
function downloadMedia(url) {
let base64 = axios.get(url, { response: "arraybuffer" }).toString("base64");
console.log("-- BASE64 -------------------------------");
console.log(base64);
return base64;
}
async function validate(mobile, cb) {
// let ret = await client.isRegisteredUser(mobile);
let ret = await client.isRegisteredUser(`${mobile}@c.us`);
// ///////////////////////////////////////////////////// 5571992888229 casaes
let _validNumber = null
console.log('******** mobile: ', mobile)
try {
_validNumber = (await client.getNumberId(`${mobile}@c.us`)).user;
} catch (err) {
console.log(`Error number: ${err}`)
}
console.log('_validNumber: ', _validNumber)
////////////////////////////////////////////////////////////////////
cb({ isValid: ret, number: _validNumber });
// cb(ret)
}
app.post('/api/validate', (req, res) => {
console.log('ENTROU')
let mobile = req.body['mobile'];
console.log(new Date() + " >>> Validating Registration Number ::: " + mobile + " on WhatsApp ...");
validate(mobile, function (e) {
res.send(e);
});
});
app.post('/api/chat', (req, res) => {
let mobile = req.body['mobile'];
let message = req.body['message'];
console.log(new Date() + " >>> Send Message ::: " + mobile + " ...");
client.sendMessage(mobile, message);
res.send('OK');
});
app.post('/group', function (req, res) {
//var ret = client.createGroup("Prueba", ["55@c.us"]);
var ret = getlabels()
res.send(ret);
});
app.post('/stop', function (req, res) {
client.destroy();
res.send("OK");
});
app.post('/api/status', function (req, res) {
res.send("OK");
});
async function monitor() {
let _nextime = 0;
try {
clearInterval(scheduler_monitor);
let stat;
if (mobileuid != undefined) {
try {
stat = await client.getState();
} catch (err) {
let terr = err.message;
stat = (terr.search('Session closed') > -1 ? 'SESSIONCLOSED' : 'UNKNOWN')
}
// omnihit.monitor(process.env.MOBILEUID, process.env.MOBILENAME, stat);
_nextime = 30000;
} else {
_nextime = 10000;
}
console.log(`WHATSAPP_ID: ${process.env.WHATSAPP_ID} | CLIENT MOBILEUID: ${mobileuid} | NAME: ${process.env.MOBILENAME} | ENV MOBILEUID: ${process.env.MOBILEUID} | STATUS: ${stat}`)
} catch (error) {
//new Date(new Date() + 'UTC')
// console.log(new Date().toISOString() + " >>> ", error);
console.log(new Date(new Date() + 'UTC') + " >>> ", error);
} finally {
scheduler_monitor = setInterval(monitor, _nextime);
}
}
async function monitorCell() {
try {
clearInterval(scheduler_monitor_cell);
// let _contact_mobile = "5511954803572@c.us";
let _message = new Date(new Date() + 'UTC');
if (client.info && client.info["wid"]["user"]) {
client.sendMessage(`${process.env.MONITOR_NUMBER}@c.us`, _message);
}
} catch (error) {
console.log(`Error on send monitor message to number ${process.env.MONITOR_NUMBER} from monitorCell function: ${error}`);
} finally {
scheduler_monitor_cell = setInterval(monitorCell, 1800000);
}
}
function comercialBuss(until_hour) {
const _hour = new Date().getHours()
console.log(' _hour: ', _hour)
// const _minute = new Date().getMinutes()
// const _second = new Date().getSeconds()
if (_hour >= until_hour) {
console.log('Trying send message into comercial buss!')
return
}
}
scheduler_monitor = setInterval(monitor, 10000);
app.listen(process.env.PORT || 8003, function () {
console.log("\u26A1[server]: Server is running at Port ::: " + process.env.PORT || 8003);
});
process.on('uncaughtException', function (err) {
console.error(' ');
console.error('----- ' + (new Date).toUTCString() + ' ----------------------------------')
console.error('Erro uncaughtException: ', err.message)
console.error(err.stack)
console.error(' ');
return
});

View File

@ -0,0 +1,141 @@
const dotenv = require('dotenv');
dotenv.config({ path: `${process.cwd()}/.env` });
const path = require('path')
const MongoClient = require( 'mongodb' ).MongoClient;
const url = process.env.DB_URL;
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
_db = client.db(process.env.DB_NAME);
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
// // PRODUCTION CONNECTION
// const MongoClient = require( 'mongodb' ).MongoClient;
// const url = "mongodb://admin:d1nf54012022prod*@172.31.187.8:27017";
// var _db;
// module.exports = {
// connectToServer: function( callback ) {
// MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
// _db = client.db('db_omnihit');
// return callback( err );
// } );
// },
// getDb: function() {
// return _db;
// }
// };
// LOCA CONNECTION
// const MongoClient = require( 'mongodb' ).MongoClient;
// const url = 'mongodb://localhost:27017';
// var _db;
// module.exports = {
// connectToServer: function( callback ) {
// MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
// _db = client.db('db_omnihit');
// return callback( err );
// } );
// },
// getDb: function() {
// return _db;
// }
// }
/*
const MongoClient = require( 'mongodb' ).MongoClient;
const url = "mongodb://admin:d1nf54012022*@172.31.187.2:27017";
var _db;
module.exports = {
connectToServer: function( callback ) {
MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
_db = client.db('db_omnihit_todoo');
return callback( err );
} );
},
getDb: function() {
return _db;
}
};
*/
// const MongoClient = require( 'mongodb' ).MongoClient;
// const url = "mongodb://admin:d1nf5401@192.168.15.13/admin?retryWrites=true&w=majority";
// var _db;
// module.exports = {
// connectToServer: function( callback ) {
// MongoClient.connect( url, { useNewUrlParser: true }, function( err, client ) {
// _db = client.db('db_omnihit');
// return callback( err );
// } );
// },
// getDb: function() {
// return _db;
// }
// };

View File

@ -0,0 +1,85 @@
const os = require('os');
const dbcloud = require('./dbcloud.js');
const dotenv = require('dotenv');
const axios = require('axios').default;
dotenv.config({path: '../.env'});
module.exports = {
// qrcode: async function(mobileuid, mobilename, qr ) {
// payload = {}
// payload['mobileuid'] = mobileuid;
// payload['mobilename'] = mobilename;
// payload['qrcode'] = qr;
// await axios.post(process.env.URL_QRCODE, payload, { timeout: 2000, headers: { 'content-type': 'application/json' } });
// console.log(new Date().toISOString() + " >>> SEND QR CODE ---------------------------------------");
// return 200;
// },
monitor: async function(mobileuid, mobilename, stat) {
let _totalmem = parseInt(os.totalmem());
let _freemem = parseInt(os.freemem());
let _memory = 100 - (_freemem / _totalmem * 100);
payload = {}
payload['mobileuid'] = mobileuid;
payload['mobilename'] = mobilename;
payload['memory'] = _memory;
let db = dbcloud.getDb();
let mco = await db.collection('tab_counts').find({ "_id": mobileuid }).limit(1).toArray();
if ( mco.length == 0 ) {
payload['_id'] = mobileuid;
payload['hour'] = 0;
payload['in'] = 0;
payload['out'] = 0;
payload['lastmessage'] = new Date(new Date() + 'UTC');
payload['in_today'] = 0;
payload['out_today'] = 0;
await db.collection('tab_counts').insertOne(payload);
}else{
payload['hour'] = mco[0]['hour'];
payload['in'] = mco[0]['in'];
payload['out'] = mco[0]['out'];
payload['lastmessage'] = mco[0]['lastmessage']
payload['in_today'] = mco[0]['in_today'];
payload['out_today'] = mco[0]['out_today'];
}
payload['dt'] = new Date(new Date() + 'UTC');
payload['status'] = stat;
console.log(new Date().toISOString() + " >>> SEND MONITOR ALARM ---------------------------------------");
console.log(new Date().toISOString() + " >>> payload: ",payload);
let monitor = await db.collection('tab_monitor').find({ "_id": mobileuid }).limit(1).toArray();
if ( monitor.length == 0 ) {
payload['_id'] = mobileuid
await db.collection('tab_monitor').insertOne(payload);
}
else{
await db.collection('tab_monitor').updateOne({ "_id": mobileuid }, { $set: payload }, true);
}
return 200;
}
}

View File

@ -0,0 +1,43 @@
module.exports = function() {
this.getTimestamp = function() {
var date = new Date();
var year = date.getFullYear();
var month = ("0"+(date.getMonth()+1)).substr(-2);
var day = ("0"+date.getDate()).substr(-2);
var hour = ("0"+date.getHours()).substr(-2);
var minutes = ("0"+date.getMinutes()).substr(-2);
var seconds = ("0"+date.getSeconds()).substr(-2);
return year+"-"+month+"-"+day+" "+hour+":"+minutes+":"+seconds;
};
this.log = function(desc, message) {
console.log(getTimestamp() + ' >> ' + desc + " :: ");
console.log(message);
};
this.getTime = function() {
var date = new Date();
var hour = ("0"+date.getHours()).substr(-2);
var minutes = ("0"+date.getMinutes()).substr(-2);
var seconds = ("0"+date.getSeconds()).substr(-2);
return hour+":"+minutes+":"+seconds;
};
this.forceGC = function() {
if (global.gc) {
console.log(getTimestamp() + " >> Starting Garbage Collector...");
global.gc();
} else {
console.warn("Garbage Collector não habilitado! Execute seu programa com node --expose-gc app.js.");
}
};
this.isJSON = function(str) {
try {
return (JSON.parse(str) && !!str);
} catch (e) {
return false;
}
}
}

View File

@ -0,0 +1,39 @@
const removeDir = require('./remove_dir');
const copyFolder = require('./copyFolder');
const path = require('path');
const fs = require('fs');
async function backup_session(destroy, save_session_after, save_first_read_only=false) {
console.log('process.cwd(): ', process.cwd())
const sessionBackupPath = path.join(process.cwd(), `session_backup`, `session-omnihit_sesssion`)
if (fs.existsSync(sessionBackupPath) && save_first_read_only) return
destroy = setTimeout(async () => {
const sessionPath = path.join(process.cwd(), '.wwebjs_auth', 'session-omnihit_sesssion')
if (fs.existsSync(path.join(process.cwd(), '.wwebjs_auth'))) {
await removeDir(sessionBackupPath)
// copy the good session for backup dir
copyFolder(sessionPath, sessionBackupPath)
}
else {
console.log('Directory not found to copy backup_session: ', sessionPath)
}
}, save_session_after);
return destroy
}
module.exports = backup_session;

View File

@ -0,0 +1,17 @@
const fsPromises = require("fs/promises");
const fs = require('fs-extra')
// Delete a directory and its children
function copyFolder(sourcePath, destPath) {
fs.copySync(sourcePath, destPath, { overwrite: true }, (err) => {
if (err) {
console.error(err);
} else {
console.log("Copy dir success!");
}
});
}
module.exports = copyFolder;

View File

@ -0,0 +1,36 @@
const multer = require('multer')
const path = require('path')
//Destination to store the images
const imageStorage = multer.diskStorage({
destination: function(req, file, cb){
// let folder = ""
// if(req.baseUrl.includes("users")){
// folder = "users"
// }else if(req.baseUrl.includes("pets")){
// folder = "pets"
// }
cb(null, path.join(process.cwd(),'medias', 'out'))
},
filename: function(req, file, cb) {
cb(null, Date.now() + path.extname(file.originalname))
}
})
const imageUpload = multer({
storage: imageStorage,
// fileFilter(req, file, cb){
// if (!file.originalname.match(/\.(jpg|jpeg|png)$/)){
// return cb(new Error('Por favor, envie apenas jpg ou png!'))
// }
// cb(undefined, true)
// }
})
module.exports = { imageUpload }

View File

@ -0,0 +1,129 @@
const dotenv = require('dotenv');
dotenv.config({ path: `${process.cwd()}/.env` });
const path = require('path')
// Ubicua Plataform - MYSQL Module
try{
var mysql_npm = require('mysql');
}catch(err){
console.log("Cannot find `mysql` module. Is it installed ? Try `npm install mysql` or `npm install`.");
}
var db_config = {
host : process.env.DB_HOST,
user : process.env.DB_USER,
password : process.env.DB_PASS,
database : process.env.DB,
charset : 'utf8mb4_general_ci',
port : process.env.DB_PORT
};
//-
//- Connection configuration
//-
// var db_config = {
// host : 'localhost',
// user : 'whaticket',
// password : '9147teste',
// database : 'db_cdnwork',
// charset : 'utf8mb4_general_ci',
// port : '6603'
// };
// var db_config = {
// host : '172.31.187.7',
// user : 'todoo',
// password : '7901228899',
// database : 'db_cdnwork',
// charset : 'utf8mb4_general_ci'
// };
//-
//- Create the connection variable
//-
var connection = mysql_npm.createPool(db_config);
//-
//- Establish a new connection
//-
connection.getConnection(function(err){
if(err) {
// mysqlErrorHandling(connection, err);
console.log("\n\t *** Cannot establish a connection with the database. ***");
connection = reconnect(connection);
}else {
console.log("\n\t *** New connection established with the database. ***")
}
});
//-
//- Reconnection function
//-
function reconnect(connection){
console.log("\n New connection tentative...");
//- Create a new one
connection = mysql_npm.createPool(db_config);
//- Try to reconnect
connection.getConnection(function(err){
if(err) {
//- Try to connect every 2 seconds.
setTimeout(reconnect(connection), 2000);
}else {
console.log("\n\t *** New connection established with the database. ***")
return connection;
}
});
}
//-
//- Error listener
//-
connection.on('error', function(err) {
//-
//- The server close the connection.
//-
if(err.code === "PROTOCOL_CONNECTION_LOST"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_AFTER_QUIT"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
else if(err.code === "PROTOCOL_ENQUEUE_HANDSHAKE_TWICE"){
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
}
else{
console.log("/!\\ Cannot establish a connection with the database. /!\\ ("+err.code+")");
return reconnect(connection);
}
});
//-
//- Export
//-
module.exports = connection;

View File

@ -0,0 +1,28 @@
const fsPromises = require("fs/promises");
const fs = require('fs')
// Delete a directory and its children
const removeDir = async (dirPath) => {
if (fs.existsSync(dirPath)) {
try {
await fsPromises.rm(dirPath, { recursive: true, force: true });
console.log("Directory removed!");
return true
}
catch (err) {
console.log('An error occurred while removing the directory: ', err);
}
}
else {
console.log('Directory not found to remove: ', dirPath)
}
return false
}
module.exports = removeDir ;

View File

@ -0,0 +1,35 @@
const removeDir = require('./remove_dir');
const copyFolder = require('./copyFolder');
const path = require('path');
const fs = require('fs');
async function restore(client) {
await client.destroy()
const sessionBackupPath = path.join(process.cwd(), `session_backup`, `session-omnihit_sesssion`)
const sessionPath = path.join(process.cwd(), '.wwebjs_auth', 'session-omnihit_sesssion')
if (fs.existsSync(path.join(process.cwd(), `session_backup`, `session-omnihit_sesssion`))) {
await removeDir(sessionPath)
// copy the good session for backup dir
copyFolder(sessionBackupPath, sessionPath)
}
else {
console.log('Directory not found to copy: ', sessionPath)
}
setTimeout(() => {
console.log('process.exit: kkkkkkkkkkkkkkkkkkkkk')
process.exit()
}, 5000)
}
module.exports = restore;

View File

@ -0,0 +1,67 @@
var io = require('socket.io-client');
var lst = []
const _clear_lst = () => {
if (lst.length <= 199) return
const chunk = Math.floor((lst.length / 2))
lst = lst.slice(chunk, chunk + lst.length);
}
const multisessionIdControll = (msgId) => {
_clear_lst()
let index = lst.findIndex((x) => x.id == msgId)
console.log('INDEX: ', index)
if (index == -1) {
lst.push({ id: msgId })
}
else {
console.log('IGNORED ID: ', msgId)
return
}
// console.log('LIST OF ID MESSAGE lst: ', lst)
console.log('PASSOU.................................ID: ', msgId)
}
const initIO = (url) => {
const socket = io(url, { reconnect: true });
socket.on('connect', async () => {
console.log('Made socket connection2');
});
socket.on('messageId', messageId => {
console.log('-------> messageId: ', messageId);
multisessionIdControll(messageId)
console.log('socket lst: ', lst)
});
return socket;
};
module.exports = { initIO, lst }

5393
TEST_SERVER1/whats/package-lock.json generated 100644

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,33 @@
{
"name": "omnihit",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon ./app.js"
},
"author": "Edson da Silva",
"license": "ISC",
"dependencies": {
"axios": "^0.21.4",
"body-parser": "^1.19.0",
"dotenv": "^16.0.0",
"express": "^4.17.1",
"form-data": "^4.0.0",
"logger": "^0.0.1",
"mime": "^2.4.5",
"mongodb": "^4.1.1",
"multer": "^1.4.4",
"mysql": "^2.18.1",
"node-os-utils": "^1.3.5",
"qr-encode": "^0.3.0",
"qrcode-terminal": "^0.12.0",
"socket.io": "^4.5.4",
"socket.io-client": "^4.5.4",
"whatsapp-web.js": "github:pedroslopez/whatsapp-web.js"
},
"devDependencies": {
"nodemon": "^2.0.20"
}
}

View File

@ -19,6 +19,8 @@ import path from 'path';
interface WhatsappData { interface WhatsappData {
name: string; name: string;
queueIds: number[]; queueIds: number[];
url: string;
urlApi: string;
greetingMessage?: string; greetingMessage?: string;
farewellMessage?: string; farewellMessage?: string;
status?: string; status?: string;
@ -38,15 +40,30 @@ export const store = async (req: Request, res: Response): Promise<Response> => {
isDefault, isDefault,
greetingMessage, greetingMessage,
farewellMessage, farewellMessage,
queueIds queueIds,
url,
urlApi
}: WhatsappData = req.body; }: WhatsappData = req.body;
// console.log( name,
// status,
// isDefault,
// greetingMessage,
// farewellMessage,
// queueIds,
// url,
// urlApi)
// return res.status(200);
if (req.user.profile !== "master") { if (req.user.profile !== "master") {
throw new AppError("ERR_NO_PERMISSION", 403); throw new AppError("ERR_NO_PERMISSION", 403);
} }
const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({ const { whatsapp, oldDefaultWhatsapp } = await CreateWhatsAppService({
name, name,
url,
urlApi,
status, status,
isDefault, isDefault,
greetingMessage, greetingMessage,
@ -123,7 +140,7 @@ export const remove = async (
removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`)) removeDir(path.join(process.cwd(), '.wwebjs_auth', `session-bd_${whatsappId}`))
removeDir(path.join(process.cwd(), '.wwebjs_auth','sessions', `session-bd_${whatsappId}`)) removeDir(path.join(process.cwd(), '.wwebjs_auth', 'sessions', `session-bd_${whatsappId}`))
removeWbot(+whatsappId); removeWbot(+whatsappId);

View File

@ -0,0 +1,13 @@
import { QueryInterface, DataTypes } from "sequelize";
module.exports = {
up: (queryInterface: QueryInterface) => {
return queryInterface.addColumn("Whatsapps", "urlApi", {
type: DataTypes.TEXT
});
},
down: (queryInterface: QueryInterface) => {
return queryInterface.removeColumn("Whatsapps", "urlApi");
}
};

View File

@ -59,6 +59,9 @@ class Whatsapp extends Model<Whatsapp> {
@Column @Column
url: string; url: string;
@Column
urlApi: string;
@Default(false) @Default(false)
@AllowNull @AllowNull
@Column @Column

View File

@ -6,6 +6,8 @@ import AssociateWhatsappQueue from "./AssociateWhatsappQueue";
interface Request { interface Request {
name: string; name: string;
url: string;
urlApi: string;
queueIds?: number[]; queueIds?: number[];
greetingMessage?: string; greetingMessage?: string;
farewellMessage?: string; farewellMessage?: string;
@ -20,11 +22,13 @@ interface Response {
const CreateWhatsAppService = async ({ const CreateWhatsAppService = async ({
name, name,
url,
urlApi,
status = "OPENING", status = "OPENING",
queueIds = [], queueIds = [],
greetingMessage, greetingMessage,
farewellMessage, farewellMessage,
isDefault = false isDefault = false,
}: Request): Promise<Response> => { }: Request): Promise<Response> => {
const schema = Yup.object().shape({ const schema = Yup.object().shape({
name: Yup.string() name: Yup.string()
@ -74,6 +78,8 @@ const CreateWhatsAppService = async ({
{ {
name, name,
status, status,
url,
urlApi,
greetingMessage, greetingMessage,
farewellMessage, farewellMessage,
isDefault isDefault

View File

@ -61,6 +61,8 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
const classes = useStyles(); const classes = useStyles();
const initialState = { const initialState = {
name: "", name: "",
urlApi: "",
url: "",
greetingMessage: "", greetingMessage: "",
farewellMessage: "", farewellMessage: "",
isDefault: false, isDefault: false,
@ -134,6 +136,7 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
{({ values, touched, errors, isSubmitting }) => ( {({ values, touched, errors, isSubmitting }) => (
<Form> <Form>
<DialogContent dividers> <DialogContent dividers>
<div className={classes.multFieldLine}> <div className={classes.multFieldLine}>
<Field <Field
as={TextField} as={TextField}
@ -158,6 +161,35 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
label={i18n.t("whatsappModal.form.default")} label={i18n.t("whatsappModal.form.default")}
/> />
</div> </div>
<div className={classes.multFieldLine}>
<Field
as={TextField}
label='url API'
autoFocus
name="urlApi"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
<Field
as={TextField}
label='url session'
autoFocus
name="url"
error={touched.name && Boolean(errors.name)}
helperText={touched.name && errors.name}
variant="outlined"
margin="dense"
className={classes.textField}
/>
</div>
<div> <div>
<Field <Field
as={TextField} as={TextField}
@ -177,6 +209,8 @@ const WhatsAppModal = ({ open, onClose, whatsAppId }) => {
margin="dense" margin="dense"
/> />
</div> </div>
<div> <div>
<Field <Field
as={TextField} as={TextField}