316 lines
9.0 KiB
JavaScript
316 lines
9.0 KiB
JavaScript
|
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
|
||
|
});
|