Atualização na api de sessão remota para centralizar informações de banco de dados
parent
21ce9e1825
commit
398a6be82b
|
@ -1,3 +1,7 @@
|
||||||
PORT=8019
|
PORT=8019
|
||||||
PORT_START=8020
|
PORT_START=8020
|
||||||
BASE_URL=http://localhost
|
BASE_URL=http://localhost
|
||||||
|
PASS="strongpassword, strongpassword32"
|
||||||
|
DB_MONGO_URL=mongodb://localhost:27017
|
||||||
|
DB_MONGO_NAME=session_out_omnihit_db
|
||||||
|
|
|
@ -1,45 +1,56 @@
|
||||||
const express = require('express');
|
const express = require('express')
|
||||||
const bodyparser = require('body-parser');
|
const bodyparser = require('body-parser')
|
||||||
const dotenv = require('dotenv');
|
const dotenv = require('dotenv')
|
||||||
dotenv.config({ path: '.env' });
|
dotenv.config({ path: '.env' })
|
||||||
const copyFolder = require('./helpers/copyFolder')
|
const copyFolder = require('./helpers/copyFolder')
|
||||||
const createDir = require('./helpers/createDir')
|
const createDir = require('./helpers/createDir')
|
||||||
const createFile = require('./helpers/createFile')
|
const createFile = require('./helpers/createFile')
|
||||||
const path = require('path');
|
const path = require('path')
|
||||||
const db_info = require('./db_conn')
|
const db_info = require('./db_conn')
|
||||||
const fs = require('fs');
|
const fs = require('fs')
|
||||||
let mysql_conn = require('./helpers/mysql_conn.js');
|
let mysql_conn = require('./helpers/mysql_conn.js')
|
||||||
const { exec, execSync, spawn } = require("child_process");
|
const { exec, execSync, spawn } = require('child_process')
|
||||||
|
|
||||||
const startPm2Process = require('./helpers/startPm2Process');
|
const startPm2Process = require('./helpers/startPm2Process')
|
||||||
const removeDir = require('./helpers/remove_dir');
|
const removeDir = require('./helpers/remove_dir')
|
||||||
const setSessionName = require('./helpers/setSessionNumber')
|
const setSessionName = require('./helpers/setSessionNumber')
|
||||||
const getNumberFromName = require('./helpers/getNumberSequence')
|
const getNumberFromName = require('./helpers/getNumberSequence')
|
||||||
const pm2 = require('pm2');
|
const pm2 = require('pm2')
|
||||||
|
const bcrypt = require('bcrypt')
|
||||||
|
const OmnihitDBConn = require('./model/db_conn')
|
||||||
|
|
||||||
const app = express();
|
const app = express()
|
||||||
|
|
||||||
app.use(bodyparser.json());
|
app.use(bodyparser.json())
|
||||||
|
|
||||||
app.get('/', function (req, res) { return res.send('Express + TypeScript Server'); });
|
app.get('/', function (req, res) {
|
||||||
|
return res.send('Express + TypeScript Server')
|
||||||
|
})
|
||||||
|
|
||||||
app.post('/api/session', async function (req, res) {
|
app.post('/api/session', async function (req, res) {
|
||||||
|
|
||||||
let { app_name, whatsappId, client_url, number } = req.body
|
let { app_name, whatsappId, client_url, number } = req.body
|
||||||
|
|
||||||
if(app_name){
|
if (app_name) {
|
||||||
app_name = app_name.trim()
|
app_name = app_name.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('__dirname: ', path.join(__dirname, '..', app_name))
|
console.log('__dirname: ', path.join(__dirname, '..', app_name))
|
||||||
|
|
||||||
console.log('app_name: ', app_name, ' | whatsappId: ', whatsappId, ' | client_url: ',client_url)
|
console.log(
|
||||||
|
'app_name: ',
|
||||||
|
app_name,
|
||||||
|
' | whatsappId: ',
|
||||||
|
whatsappId,
|
||||||
|
' | client_url: ',
|
||||||
|
client_url
|
||||||
|
)
|
||||||
|
|
||||||
const sessionsPath = path.join(__dirname, '..', 'sessions')
|
const sessionsPath = path.join(__dirname, '..', 'sessions')
|
||||||
|
|
||||||
const directoriesInDIrectory = fs.readdirSync(sessionsPath, { withFileTypes: true })
|
const directoriesInDIrectory = fs
|
||||||
|
.readdirSync(sessionsPath, { withFileTypes: true })
|
||||||
.filter((item) => item.isDirectory())
|
.filter((item) => item.isDirectory())
|
||||||
.map((item) => item.name);
|
.map((item) => item.name)
|
||||||
|
|
||||||
console.log('directoriesInDIrectory: ', directoriesInDIrectory)
|
console.log('directoriesInDIrectory: ', directoriesInDIrectory)
|
||||||
|
|
||||||
|
@ -48,146 +59,141 @@ app.post('/api/session', async function (req, res) {
|
||||||
let dirSessionsApp = path.join(sessionsPath, app_name)
|
let dirSessionsApp = path.join(sessionsPath, app_name)
|
||||||
|
|
||||||
if (dirExist.length == 0) {
|
if (dirExist.length == 0) {
|
||||||
|
|
||||||
let create = createDir(dirSessionsApp)
|
let create = createDir(dirSessionsApp)
|
||||||
|
|
||||||
if (!create) {
|
if (!create) {
|
||||||
|
|
||||||
res.status(500).json({ message: 'Cannot create the directory path!' })
|
res.status(500).json({ message: 'Cannot create the directory path!' })
|
||||||
return
|
return
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let appPort = []
|
let appPort = []
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let existSubDir = false
|
let existSubDir = false
|
||||||
|
|
||||||
for (let i = 0; i < directoriesInDIrectory.length; i++) {
|
for (let i = 0; i < directoriesInDIrectory.length; i++) {
|
||||||
|
|
||||||
console.log('directoriesInDIrectory[i]', directoriesInDIrectory[i])
|
console.log('directoriesInDIrectory[i]', directoriesInDIrectory[i])
|
||||||
|
|
||||||
const subDir = fs.readdirSync(path.join(sessionsPath, directoriesInDIrectory[i]), { withFileTypes: true })
|
const subDir = fs
|
||||||
|
.readdirSync(path.join(sessionsPath, directoriesInDIrectory[i]), {
|
||||||
|
withFileTypes: true,
|
||||||
|
})
|
||||||
.filter((item) => item.isDirectory())
|
.filter((item) => item.isDirectory())
|
||||||
.map((item) => item.name);
|
.map((item) => item.name)
|
||||||
|
|
||||||
for (let x = 0; x < subDir.length; x++) {
|
for (let x = 0; x < subDir.length; x++) {
|
||||||
|
|
||||||
console.log('subdir: ', subDir[x])
|
console.log('subdir: ', subDir[x])
|
||||||
|
|
||||||
let whatsId = subDir[x].split('_')[0]
|
let whatsId = subDir[x].split('_')[0]
|
||||||
|
|
||||||
if (whatsId == whatsappId && app_name == directoriesInDIrectory[i]) {
|
if (whatsId == whatsappId && app_name == directoriesInDIrectory[i]) {
|
||||||
|
let currPath = path.join(
|
||||||
|
sessionsPath,
|
||||||
|
directoriesInDIrectory[i],
|
||||||
|
subDir[x]
|
||||||
|
)
|
||||||
|
|
||||||
let currPath = path.join(sessionsPath, directoriesInDIrectory[i], subDir[x])
|
console.log(
|
||||||
|
'PATH: ',
|
||||||
console.log('PATH: ', path.join(sessionsPath, directoriesInDIrectory[i], subDir[x]))
|
path.join(sessionsPath, directoriesInDIrectory[i], subDir[x])
|
||||||
|
)
|
||||||
|
|
||||||
let oldNumber = subDir[x].split('_')[1]
|
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)
|
|
||||||
|
|
||||||
// console.log(`number: ${number}\noldNumber: ${oldNumber}\nsessionNum: ${sessionNum}\nsessionPort: ${sessionPort}\nnewSessionAppName:${newSessionAppName}`)
|
|
||||||
|
|
||||||
if (oldNumber != number) {
|
if (oldNumber != number) {
|
||||||
|
|
||||||
deletePm2Process(subDir[x], currPath)
|
deletePm2Process(subDir[x], currPath)
|
||||||
|
|
||||||
removeDir(currPath)
|
removeDir(currPath)
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
res.send('ok')
|
res.send('ok')
|
||||||
return
|
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])
|
let auxPort = subDir[x].split('_')[3]
|
||||||
|
|
||||||
console.log('---------> appPort: '+appPort)
|
console.log('---------> auxPort: ' + auxPort)
|
||||||
|
|
||||||
|
if (auxPort) {
|
||||||
|
auxPort = +auxPort.trim()
|
||||||
|
|
||||||
|
if (!isNaN(auxPort)) {
|
||||||
|
appPort.push(auxPort)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
existSubDir = true
|
existSubDir = true
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
appPort = existSubDir ? Math.max(...appPort) + 1 : process.env.PORT_START
|
appPort = existSubDir ? Math.max(...appPort) + 1 : process.env.PORT_START
|
||||||
|
|
||||||
console.log('new port: ', appPort)
|
console.log('new port: ', appPort)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
let dirSessionAppName
|
let dirSessionAppName
|
||||||
|
|
||||||
let numberSession = 1
|
let numberSession = 1
|
||||||
|
|
||||||
// const dirSessionsNumberAppDirectories = fs.readdirSync(dirSessionsApp, { withFileTypes: true })
|
let lstPass = process.env.PASS
|
||||||
// .filter((item) => item.isDirectory() && item.name.includes(`${number}`))
|
|
||||||
// .map((item) => item.name);
|
|
||||||
|
|
||||||
// console.log('dirSessionsNumberAppDirectories', dirSessionsNumberAppDirectories, ' | dirSessionsApp: ', dirSessionsApp)
|
if (!lstPass) {
|
||||||
|
console.log('PASS VARIABLE NOT FOUND INTO .ENV!')
|
||||||
console.log('client_url: ', client_url)
|
return res.send('OK')
|
||||||
|
|
||||||
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 db_credentials
|
||||||
|
try {
|
||||||
|
db_credentials = await OmnihitDBConn.findOne({ client_url })
|
||||||
|
|
||||||
if (db && Object.keys(db).length > 0) {
|
if (!db_credentials) {
|
||||||
|
db_credentials = new OmnihitDBConn({
|
||||||
|
client_url: client_url,
|
||||||
|
db_conf: {
|
||||||
|
DB: '',
|
||||||
|
DB_HOST: '',
|
||||||
|
DB_USER: '',
|
||||||
|
DB_PASS: '',
|
||||||
|
DB_PORT: '',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
await db_credentials.save()
|
||||||
|
return res.send('ok')
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (db_credentials && db_credentials.db_conf.DB.trim().length > 0) {
|
||||||
|
lstPass = lstPass.split(',')
|
||||||
|
let password = null
|
||||||
|
|
||||||
|
password = await lstPass.find(
|
||||||
|
async (pass) =>
|
||||||
|
await bcrypt.compare(pass.trim(), db_credentials.db_conf.DB_PASS)
|
||||||
|
)
|
||||||
|
if (password) {
|
||||||
|
db_credentials.db_conf.DB_PASS = password
|
||||||
|
} else {
|
||||||
|
return res.send('ok')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
db_credentials.db_conf &&
|
||||||
|
Object.keys(db_credentials.db_conf).length > 0
|
||||||
|
) {
|
||||||
const whatsapp_numbers = await new Promise((resolve, reject) => {
|
const whatsapp_numbers = await new Promise((resolve, reject) => {
|
||||||
mysql_conn(db).query('SELECT name FROM Whatsapps WHERE name LIKE ?', [`%${number}%`], (err, result) => {
|
mysql_conn(db_credentials.db_conf).query(
|
||||||
|
'SELECT name FROM Whatsapps WHERE name LIKE ?',
|
||||||
|
[`%${number}%`],
|
||||||
|
(err, result) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
resolve(result)
|
resolve(result)
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
console.log('whatsapp_numbers: ', whatsapp_numbers)
|
console.log('whatsapp_numbers: ', whatsapp_numbers)
|
||||||
|
@ -195,11 +201,12 @@ app.post('/api/session', async function (req, res) {
|
||||||
let session_num = []
|
let session_num = []
|
||||||
|
|
||||||
if (whatsapp_numbers && whatsapp_numbers.length > 0) {
|
if (whatsapp_numbers && whatsapp_numbers.length > 0) {
|
||||||
|
|
||||||
console.log('whatsapp_numbers.length: ', whatsapp_numbers.length)
|
console.log('whatsapp_numbers.length: ', whatsapp_numbers.length)
|
||||||
|
|
||||||
if (whatsapp_numbers.length == 5) {
|
if (whatsapp_numbers.length == 5) {
|
||||||
res.status(400).json({ message: 'Cannot create more than 4 sessions from the same number' })
|
res.status(400).json({
|
||||||
|
message: 'Cannot create more than 4 sessions from the same number',
|
||||||
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -209,16 +216,21 @@ app.post('/api/session', async function (req, res) {
|
||||||
|
|
||||||
console.log('numbered_sessions: ', numbered_sessions)
|
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]))
|
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)
|
console.log('session_num', session_num)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let index = 1;
|
let index = 1
|
||||||
|
|
||||||
while (index <= 4) {
|
while (index <= 4) {
|
||||||
|
|
||||||
if (!session_num.includes(index)) {
|
if (!session_num.includes(index)) {
|
||||||
console.log(index)
|
console.log(index)
|
||||||
numberSession = index
|
numberSession = index
|
||||||
|
@ -226,11 +238,8 @@ app.post('/api/session', async function (req, res) {
|
||||||
}
|
}
|
||||||
index++
|
index++
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// numberSession = Math.max(...session_number) + 1
|
// numberSession = Math.max(...session_number) + 1
|
||||||
|
|
||||||
console.log('Number session: ', numberSession)
|
console.log('Number session: ', numberSession)
|
||||||
|
@ -239,61 +248,63 @@ app.post('/api/session', async function (req, res) {
|
||||||
|
|
||||||
dirSessionAppName = `${whatsappId}_${number}_${numberSession}_${appPort}`
|
dirSessionAppName = `${whatsappId}_${number}_${numberSession}_${appPort}`
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
destDir = path.join(dirSessionsApp, dirSessionAppName)
|
destDir = path.join(dirSessionsApp, dirSessionAppName)
|
||||||
|
|
||||||
originDir = path.join(__dirname, '..', 'whats')
|
originDir = path.join(__dirname, '..', 'whats')
|
||||||
|
|
||||||
copyFolder(originDir, destDir)
|
copyFolder(originDir, destDir)
|
||||||
|
|
||||||
|
if (
|
||||||
if (db && Object.keys(db).length > 0) {
|
db_credentials.db_conf &&
|
||||||
|
Object.keys(db_credentials.db_conf).length > 0
|
||||||
console.log('kkkkkkkkkkkkkkk')
|
) {
|
||||||
|
console.log('***SUCCESS SEED DIRECTORY CREATED***')
|
||||||
|
|
||||||
let whatsName
|
let whatsName
|
||||||
|
|
||||||
const whatsapp = await new Promise((resolve, reject) => {
|
const whatsapp = await new Promise((resolve, reject) => {
|
||||||
|
mysql_conn(db_credentials.db_conf).query(
|
||||||
mysql_conn(db).query("SELECT name from Whatsapps where id = ?", [whatsappId], (err, result) => {
|
'SELECT name from Whatsapps where id = ?',
|
||||||
|
[whatsappId],
|
||||||
|
(err, result) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
resolve(result)
|
resolve(result)
|
||||||
}
|
}
|
||||||
});
|
}
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
if (whatsapp[0]["name"].split('->').length > 0) {
|
if (whatsapp[0]['name'].split('->').length > 0) {
|
||||||
whatsName = `${whatsapp[0]["name"].split('->')[0]} -> S${numberSession}`
|
whatsName = `${whatsapp[0]['name'].split('->')[0]} -> S${numberSession}`
|
||||||
}
|
} else {
|
||||||
else {
|
whatsName = `${whatsapp[0]['name']} -> S${numberSession}`
|
||||||
whatsName = `${whatsapp[0]["name"]} -> S${numberSession}`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('whatsName: ', whatsName)
|
console.log('whatsName: ', whatsName)
|
||||||
|
|
||||||
console.log(`url: ${process.env.BASE_URL}:${appPort}\n whatsname: ${whatsName}\n whatsappId: ${whatsappId}`)
|
console.log(
|
||||||
|
`url: ${process.env.BASE_URL}:${appPort}\n whatsname: ${whatsName}\n whatsappId: ${whatsappId}`
|
||||||
|
)
|
||||||
|
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
mysql_conn(db).query("UPDATE Whatsapps SET url = ?, name = ? where id = ?", [`${process.env.BASE_URL}:${appPort}`, `${whatsName}`, whatsappId],
|
mysql_conn(db_credentials.db_conf).query(
|
||||||
|
'UPDATE Whatsapps SET url = ?, name = ? where id = ?',
|
||||||
|
[`${process.env.BASE_URL}:${appPort}`, `${whatsName}`, whatsappId],
|
||||||
|
|
||||||
function (err, result) {
|
function (err, result) {
|
||||||
if (err) {
|
if (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
console.log("===> ERROR: " + err);
|
console.log('===> ERROR: ' + err)
|
||||||
}
|
} else {
|
||||||
else {
|
|
||||||
resolve(result)
|
resolve(result)
|
||||||
// console.log('RESULT: ', result)
|
// console.log('RESULT: ', result)
|
||||||
}
|
}
|
||||||
// else
|
// else
|
||||||
// console.log('myslq result: ', result);
|
// console.log('myslq result: ', result);
|
||||||
});
|
}
|
||||||
|
)
|
||||||
})
|
})
|
||||||
|
|
||||||
let whatsappName = `${number} - s${numberSession}`
|
let whatsappName = `${number} - s${numberSession}`
|
||||||
|
@ -301,91 +312,84 @@ app.post('/api/session', async function (req, res) {
|
||||||
console.log('-------------- numberSession', numberSession)
|
console.log('-------------- numberSession', numberSession)
|
||||||
|
|
||||||
if (whatsapp.length > 0) {
|
if (whatsapp.length > 0) {
|
||||||
|
|
||||||
if (whatsapp[0]['name'].split(' ').length > 0) {
|
if (whatsapp[0]['name'].split(' ').length > 0) {
|
||||||
|
whatsappName = `${
|
||||||
whatsappName = `${whatsapp[0]['name'].split(' ')[0]} - S${numberSession}`
|
whatsapp[0]['name'].split(' ')[0]
|
||||||
|
} - S${numberSession}`
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('whatsapp: ', whatsapp)
|
console.log('whatsapp: ', whatsapp)
|
||||||
console.log("whatsapp[0]['name']: ", whatsapp[0]['name'])
|
console.log("whatsapp[0]['name']: ", whatsapp[0]['name'])
|
||||||
|
|
||||||
const keys = Object.keys(db);
|
const keys = Object.keys(db_credentials.db_conf)
|
||||||
|
|
||||||
var stream = fs.createWriteStream(path.join(destDir, '.env'));
|
var stream = fs.createWriteStream(path.join(destDir, '.env'))
|
||||||
stream.once('open', function (fd) {
|
stream.once('open', function (fd) {
|
||||||
stream.write("# NUMBER AND NAME THAT WILL BE DISPLAYED ON CONSOLE\n");
|
stream.write('# NUMBER AND NAME THAT WILL BE DISPLAYED ON CONSOLE\n')
|
||||||
stream.write(`MOBILEUID=${number}\n`);
|
stream.write(`MOBILEUID=${number}\n`)
|
||||||
stream.write(`MOBILENAME=${whatsappName}\n`);
|
stream.write(`MOBILENAME=${whatsappName}\n`)
|
||||||
stream.write("\n");
|
stream.write('\n')
|
||||||
|
|
||||||
stream.write("# PORT NUMBER FOR THIS API\n");
|
stream.write('# PORT NUMBER FOR THIS API\n')
|
||||||
stream.write(`PORT=${appPort}\n`);
|
stream.write(`PORT=${appPort}\n`)
|
||||||
stream.write("\n");
|
stream.write('\n')
|
||||||
|
|
||||||
stream.write("# URL FROM THE OMNIHIT BACKEND API\n");
|
stream.write('# URL FROM THE OMNIHIT BACKEND API\n')
|
||||||
stream.write(`CLIENT_URL=${client_url}\n`);
|
stream.write(`CLIENT_URL=${client_url}\n`)
|
||||||
stream.write("\n");
|
stream.write('\n')
|
||||||
|
|
||||||
stream.write("# OMNIHIT DATABASE\n");
|
stream.write('# OMNIHIT DATABASE\n')
|
||||||
keys.forEach((key, index) => {
|
keys.forEach((key, index) => {
|
||||||
stream.write(`${key}=${db[key]}\n`);
|
stream.write(`${key}=${db_credentials.db_conf[key]}\n`)
|
||||||
});
|
})
|
||||||
stream.write("\n");
|
stream.write('\n')
|
||||||
|
|
||||||
stream.write(`# WHATSAPP ID OF THE TABLE Whatsapps FROM THE OMNIHIT DATABASE\n`);
|
|
||||||
stream.write(`WHATSAPP_ID=${whatsappId}`);
|
|
||||||
|
|
||||||
stream.end();
|
|
||||||
});
|
|
||||||
|
|
||||||
|
stream.write(
|
||||||
|
`# WHATSAPP ID OF THE TABLE Whatsapps FROM THE OMNIHIT DATABASE\n`
|
||||||
|
)
|
||||||
|
stream.write(`WHATSAPP_ID=${whatsappId}`)
|
||||||
|
|
||||||
|
stream.end()
|
||||||
|
})
|
||||||
|
|
||||||
console.log('----------------destDir: ', destDir)
|
console.log('----------------destDir: ', destDir)
|
||||||
|
|
||||||
|
|
||||||
execSync(`npm install`, { cwd: destDir }, (error, stdout, stderr) => {
|
execSync(`npm install`, { cwd: destDir }, (error, stdout, stderr) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log(`error: ${error.message}`);
|
console.log(`error: ${error.message}`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (stderr) {
|
if (stderr) {
|
||||||
console.log(`stderr: ${stderr}`);
|
console.log(`stderr: ${stderr}`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
console.log(`stdout: ${stdout}`);
|
console.log(`stdout: ${stdout}`)
|
||||||
});
|
})
|
||||||
|
|
||||||
startPm2Process(dirSessionAppName, 'app.js', destDir, appPort)
|
startPm2Process(dirSessionAppName, 'app.js', destDir, appPort)
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
res.send("OK");
|
res.send('OK')
|
||||||
|
})
|
||||||
});
|
|
||||||
|
|
||||||
app.post('/api/session/edit', async function (req, res) {
|
app.post('/api/session/edit', async function (req, res) {
|
||||||
|
|
||||||
const { app_name, whatsappId, client_url, number } = req.body
|
const { app_name, whatsappId, client_url, number } = req.body
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
app.post('/api/session/del', async function (req, res) {
|
app.post('/api/session/del', async function (req, res) {
|
||||||
|
|
||||||
let { whatsappId, app_name } = req.body
|
let { whatsappId, app_name } = req.body
|
||||||
|
|
||||||
if(app_name){
|
if (app_name) {
|
||||||
app_name = app_name.trim()
|
app_name = app_name.trim()
|
||||||
}
|
}
|
||||||
|
|
||||||
const sessionsPath = path.join(__dirname, '..', 'sessions')
|
const sessionsPath = path.join(__dirname, '..', 'sessions')
|
||||||
|
|
||||||
const directoriesInDIrectory = fs.readdirSync(sessionsPath, { withFileTypes: true })
|
const directoriesInDIrectory = fs
|
||||||
|
.readdirSync(sessionsPath, { withFileTypes: true })
|
||||||
.filter((item) => item.isDirectory())
|
.filter((item) => item.isDirectory())
|
||||||
.map((item) => item.name);
|
.map((item) => item.name)
|
||||||
|
|
||||||
console.log('directoriesInDIrectory: ', directoriesInDIrectory)
|
console.log('directoriesInDIrectory: ', directoriesInDIrectory)
|
||||||
|
|
||||||
|
@ -393,94 +397,95 @@ app.post('/api/session/del', async function (req, res) {
|
||||||
|
|
||||||
console.log('dirExist: ', dirExist)
|
console.log('dirExist: ', dirExist)
|
||||||
|
|
||||||
if (dirExist.length == 0)
|
if (dirExist.length == 0) res.send('ok')
|
||||||
res.send('ok')
|
|
||||||
|
|
||||||
|
|
||||||
for (let i = 0; i < directoriesInDIrectory.length; i++) {
|
for (let i = 0; i < directoriesInDIrectory.length; i++) {
|
||||||
|
|
||||||
console.log('directoriesInDIrectory[i]', directoriesInDIrectory[i])
|
console.log('directoriesInDIrectory[i]', directoriesInDIrectory[i])
|
||||||
|
|
||||||
const subDir = fs.readdirSync(path.join(sessionsPath, directoriesInDIrectory[i]), { withFileTypes: true })
|
const subDir = fs
|
||||||
|
.readdirSync(path.join(sessionsPath, directoriesInDIrectory[i]), {
|
||||||
|
withFileTypes: true,
|
||||||
|
})
|
||||||
.filter((item) => item.isDirectory())
|
.filter((item) => item.isDirectory())
|
||||||
.map((item) => item.name);
|
.map((item) => item.name)
|
||||||
|
|
||||||
for (let x = 0; x < subDir.length; x++) {
|
for (let x = 0; x < subDir.length; x++) {
|
||||||
|
|
||||||
console.log('subdir: ', subDir[x])
|
console.log('subdir: ', subDir[x])
|
||||||
|
|
||||||
let whatsId = subDir[x].split('_')[0]
|
let whatsId = subDir[x].split('_')[0]
|
||||||
|
|
||||||
if (whatsId == whatsappId && app_name == directoriesInDIrectory[i]) {
|
if (whatsId == whatsappId && app_name == directoriesInDIrectory[i]) {
|
||||||
|
let currPath = path.join(
|
||||||
|
sessionsPath,
|
||||||
|
directoriesInDIrectory[i],
|
||||||
|
subDir[x]
|
||||||
|
)
|
||||||
|
|
||||||
let currPath = path.join(sessionsPath, directoriesInDIrectory[i], subDir[x])
|
deletePm2Process(subDir[x], currPath)
|
||||||
|
|
||||||
deletePm2Process(subDir[x], currPath);
|
|
||||||
|
|
||||||
console.log('currPath: ', currPath)
|
console.log('currPath: ', currPath)
|
||||||
|
|
||||||
removeDir(currPath)
|
removeDir(currPath)
|
||||||
|
|
||||||
return res.send('ok')
|
return res.send('ok')
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
res.send('ok')
|
res.send('ok')
|
||||||
|
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
app.listen(process.env.PORT || 8003, function () {
|
app.listen(process.env.PORT || 8003, function () {
|
||||||
console.log("\u26A1[server]: Server is running at Port ::: " + process.env.PORT || 8003);
|
console.log(
|
||||||
});
|
'\u26A1[server]: Server is running at Port ::: ' + process.env.PORT || 8003
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
process.on('uncaughtException', function (err) {
|
process.on('uncaughtException', function (err) {
|
||||||
console.error(' ');
|
console.error(' ')
|
||||||
console.error('----- ' + (new Date).toUTCString() + ' ----------------------------------')
|
console.error(
|
||||||
|
'----- ' + new Date().toUTCString() + ' ----------------------------------'
|
||||||
|
)
|
||||||
console.error('Erro uncaughtException: ', err.message)
|
console.error('Erro uncaughtException: ', err.message)
|
||||||
console.error(err.stack)
|
console.error(err.stack)
|
||||||
console.error(' ');
|
console.error(' ')
|
||||||
return
|
return
|
||||||
});
|
})
|
||||||
|
|
||||||
function deletePm2Process(process_name, currPath) {
|
function deletePm2Process(process_name, currPath) {
|
||||||
pm2.connect(function (err) {
|
pm2.connect(function (err) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(err);
|
console.error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
pm2.list(function (err, processes) {
|
pm2.list(function (err, processes) {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.error(err);
|
console.error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
processes.forEach(function (process) {
|
processes.forEach(function (process) {
|
||||||
|
console.log('.........process.name: ', process.name)
|
||||||
console.log(".........process.name: ", process.name);
|
|
||||||
|
|
||||||
if (process.name === process_name) {
|
if (process.name === process_name) {
|
||||||
execSync(`pm2 delete ${process_name} && pm2 save --force`, { cwd: currPath }, (error, stdout, stderr) => {
|
execSync(
|
||||||
|
`pm2 delete ${process_name} && pm2 save --force`,
|
||||||
|
{ cwd: currPath },
|
||||||
|
(error, stdout, stderr) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
console.log(`error: ${error.message}`);
|
console.log(`error: ${error.message}`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
if (stderr) {
|
if (stderr) {
|
||||||
console.log(`stderr: ${stderr}`);
|
console.log(`stderr: ${stderr}`)
|
||||||
return;
|
return
|
||||||
}
|
}
|
||||||
console.log(`stdout: ${stdout}`);
|
console.log(`stdout: ${stdout}`)
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
});
|
pm2.disconnect()
|
||||||
|
})
|
||||||
pm2.disconnect();
|
})
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
@ -0,0 +1,11 @@
|
||||||
|
const mongoose = require('mongoose')
|
||||||
|
require('dotenv').config({ path: `${process.cwd()}/.env` })
|
||||||
|
|
||||||
|
async function main(){
|
||||||
|
await mongoose.connect(process.env.DB_MONGO_URL, { dbName: process.env.DB_MONGO_NAME })
|
||||||
|
console.log('Conectou ao Mongoose!')
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err)=>console.log(err))
|
||||||
|
|
||||||
|
module.exports = mongoose
|
|
@ -0,0 +1,20 @@
|
||||||
|
const bcrypt = require('bcrypt')
|
||||||
|
|
||||||
|
const pass = async () => {
|
||||||
|
// create a password
|
||||||
|
const salt = await bcrypt.genSalt(12)
|
||||||
|
const passwordHash = await bcrypt.hash('strongpassword', salt)
|
||||||
|
console.log(passwordHash)
|
||||||
|
}
|
||||||
|
pass()
|
||||||
|
|
||||||
|
// const passDec = async () => {
|
||||||
|
// const _pass = await bcrypt.compare(
|
||||||
|
// 'strongpassword',
|
||||||
|
// '$2b$12$R/bpS7b9FzdXlHAijmP.3.gJqgeUjwQVSuK6q.G0PZbb0wowCnrN.'
|
||||||
|
// )
|
||||||
|
// console.log('_pass: ', _pass)
|
||||||
|
// }
|
||||||
|
// passDec()
|
||||||
|
|
||||||
|
console.log('process.cwd(): ', process.cwd())
|
|
@ -0,0 +1,33 @@
|
||||||
|
const mongoose = require('../db/connMongo')
|
||||||
|
const { Schema } = mongoose
|
||||||
|
|
||||||
|
const OmnihitDBConn = mongoose.model(
|
||||||
|
'Omnihit_db_conn',
|
||||||
|
new Schema(
|
||||||
|
{
|
||||||
|
client_url: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
db_conf: {
|
||||||
|
DB: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
DB_HOST: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
DB_USER: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
DB_PASS: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
DB_PORT: {
|
||||||
|
type: String,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ timestamps: true }
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
module.exports = OmnihitDBConn
|
File diff suppressed because it is too large
Load Diff
|
@ -11,10 +11,12 @@
|
||||||
"author": "Adriano <adriano08andrade@hotmail.com>",
|
"author": "Adriano <adriano08andrade@hotmail.com>",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"bcrypt": "^5.1.0",
|
||||||
"body-parser": "^1.20.1",
|
"body-parser": "^1.20.1",
|
||||||
"dotenv": "^16.0.3",
|
"dotenv": "^16.0.3",
|
||||||
"express": "^4.18.2",
|
"express": "^4.18.2",
|
||||||
"fs-extra": "^11.1.0",
|
"fs-extra": "^11.1.0",
|
||||||
|
"mongoose": "^7.4.0",
|
||||||
"mysql": "^2.18.1",
|
"mysql": "^2.18.1",
|
||||||
"nodemon": "^2.0.20",
|
"nodemon": "^2.0.20",
|
||||||
"socket.io": "^4.5.4"
|
"socket.io": "^4.5.4"
|
||||||
|
|
Loading…
Reference in New Issue