const fs = require('fs'); let mysql_conn = require('./mysql_conn.js'); async function sessionNumber(db_info, whatsappId, number, dirSessionsApp) { let numberSession = 1 let whatsappName const dirSessionsNumberAppDirectories = fs.readdirSync(dirSessionsApp, { withFileTypes: true }) .filter((item) => item.isDirectory() && item.name.includes(`${number}`)) .map((item) => item.name); if (dirSessionsNumberAppDirectories.length > 0) { let session_number = dirSessionsNumberAppDirectories.map((e) => +e.split('_')[2]) numberSession = Math.max(...session_number) + 1 console.log('Number session: ', numberSession) if (numberSession > 4) { res.status(400).json({ message: 'Cannot create more than 4 sessions from the same number' }) return } } let db = db_info.filter((e) => e.client_url == client_url) if (db && db.length > 0) { db = db[0].db_conf let whatsName const whatsapp = await new Promise((resolve, reject) => { mysql_conn(db).query("SELECT name from Whatsapps where id = ?", [whatsappId], (err, result) => { if (err) { reject(err) } else { resolve(result) } }); }) if (whatsapp[0]["name"].split('->').length > 0) { whatsName = `${whatsapp[0]["name"].split('->')[0]} -> S${numberSession}` } else { whatsName = `${whatsapp[0]["name"]} -> S${numberSession}` } console.log('whatsName: ', whatsName) console.log(`url: ${process.env.BASE_URL}:${appPort}\n whatsname: ${whatsName}\n whatsappId: ${whatsappId}`) // await new Promise((resolve, reject) => { // mysql_conn(db).query("UPDATE Whatsapps SET name = ? where id = ?", [ `${whatsName}`, whatsappId], // function (err, result) { // if (err) { // reject(err) // console.log("===> ERROR: " + err); // } // else { // resolve(result) // console.log('RESULT: ', result) // } // // else // // console.log('myslq result: ', result); // }); // }) whatsappName = `${number} - s${numberSession}` console.log('-------------- numberSession', numberSession) if (whatsapp.length > 0) { if (whatsapp[0]['name'].split(' ').length > 0) { whatsappName = `${whatsapp[0]['name'].split(' ')[0]} - S${numberSession}` } } } console.log('---------> whatsappName', whatsappName) return whatsappName } module.exports = sessionNumber