- attivita

- gestione degli script sul server
 - creato websocket per interagire con gli script del server.
This commit is contained in:
Surya Paolo
2024-08-29 23:30:58 +02:00
parent d527f49c5e
commit 45f601bd26
25 changed files with 534 additions and 45 deletions

View File

@@ -1,6 +1,7 @@
const os = require('os');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
require('../config/config');
require('../models/subscribers');
@@ -43,6 +44,12 @@ const FIELDS_REGEX = ['username', 'name', 'surname'];
const sanitizeHtml = require('sanitize-html');
const { exec } = require('child_process');
const { spawn } = require('child_process');
const readline = require('readline');
// Code goes here
const keySize = 256;
const ivSize = 128;
@@ -430,7 +437,7 @@ class ImageDownloader {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}
});
response.data.pipe(writer);
await new Promise((resolve, reject) => {
@@ -1899,6 +1906,10 @@ module.exports = {
return this.getConfSiteOptionEnabledByIdApp(idapp, shared_consts.ConfSite.Need_Aportador_On_DataReg_To_Verify_Reg);
},
getidMyGroupBySite: function (idapp) {
return this.getConfSiteOptionEnabledByIdApp(idapp, shared_consts.ConfSite.Need_Aportador_On_DataReg_To_Verify_Reg);
},
isManagAndAdminDifferent(idapp) {
const manag = this.getManagerEmailByIdApp(idapp);
return (manag !== this.getAdminEmailByIdApp(idapp)) && (manag !== '');
@@ -2686,16 +2697,40 @@ module.exports = {
query.push({ $match: { $and: filtriadded } });
}
let numrowend = params.endRow - params.startRow;
if (numrowend < 0)
numrowend = 1;
let projectEnd = { $slice: ['$results', params.startRow, numrowend] };
let querymatch = {};
if (idapp > 0) {
query.push({ $match: { idapp } });
querymatch.idapp = idapp;
}
if (params.searchByBoundariesMap) {
projectEnd = "$results";
querymatch.coordinate_gps = {
$geoWithin: {
$box: [
[params.searchByBoundariesMap.sw.lng, params.searchByBoundariesMap.sw.lat],
[params.searchByBoundariesMap.ne.lng, params.searchByBoundariesMap.ne.lat]
]
}
};
};
if (Object.keys(querymatch).length > 0) {
query.push(
{ $match: querymatch });
}
// console.log('QUERYMATCH', query[0].$match.or);
// console.log('filter', params.filter);
let numrowend = params.endRow - params.startRow;
if (numrowend < 0)
numrowend = 1;
if (params.querytype === shared_consts.QUERYTYPE_MYGROUP || params.querytype === shared_consts.QUERYTYPE_CIRCUIT) {
@@ -2806,13 +2841,33 @@ module.exports = {
if (qa1) query = [...query, ...qa1];
query.push({ $unwind: '$group' });
query.push({
$match: {
$and: [
{ 'group.idapp': params.idapp },
],
},
});
if (true) {
query.push({
$match: {
$and: [
{ 'group.idapp': params.idapp },
],
coordinate_gps: {
$geoWithin: {
$box: [
[searchByBoudariesMap.sw.lng, searchByBoudariesMap.sw.lat],
[searchByBoudariesMap.ne.lng, searchByBoudariesMap.ne.lat]
]
}
}
},
});
} else {
query.push({
$match: {
$and: [
{ 'group.idapp': params.idapp },
],
},
});
}
query.push({
@@ -3146,7 +3201,7 @@ module.exports = {
if (q1) query = [...query, ...q1];
}
if (params.sortBy) {
if (params.sortBy && !params.searchByBoundariesMap) {
// maybe we want to sort by blog title or something
const mysort = { $sort: params.sortBy };
// console.log('sortBy', params.sortBy);
@@ -3165,18 +3220,22 @@ module.exports = {
},
},
// and finally trim the results to within the range given by start/endRow
{
$project: {
count: 1,
rows: { $slice: ['$results', params.startRow, numrowend] },
},
},
);
if (projectEnd) {
query.push(
{
$project: {
count: 1,
rows: projectEnd,
},
},
);
}
if (this.testing()) {
// console.log('query', query);
}
// console.log('query', query);
//console.log('query', query);
return query;
} catch (e) {
@@ -4424,7 +4483,134 @@ module.exports = {
return strlinkreg;
},
execScript: function (idapp, msg, script, testo) {
execScriptOnServer: async function (idapp, script, dir, listafiles, extfiles) {
return new Promise(async (resolve, reject) => {
exec(script, async (error, stdout, stderr) => { // Aggiunto async qui
if (error) {
console.error(`error: ${error}`);
return reject(`Execution failed: ${error}`);
}
if (stderr) {
console.error(`stderr: ${stderr}`);
}
// Se vuoi mantenere questa parte, puoi decommentarla
// if (stdout) {
// console.log(`OUT: ${stdout}`);
// }
let arrout = [];
let arrscripts = stdout
.split('\n')
.filter((script) => script.trim() !== '')
.map((script) => script.replace(/\//g, ''));
for (let i = 0; i < arrscripts.length; i++) {
let label = arrscripts[i];
let description = '';
if (listafiles) {
if (arrscripts[i].endsWith('.sh')) {
let labelFilePath = path.join(__dirname, '..', '..', '..', dir, `${arrscripts[i]}`);
// Verifica se il file esiste
try {
// console.log(__dirname);
// console.log(labelFilePath);
// Leggi il contenuto del file .label
const labelContent = await fs.readFileSync(labelFilePath, 'utf-8');
const lines = labelContent.split('\n');
for (let i = 0; i < lines.length; i++) {
let linea = lines[i];
// se la linea inizia con #DATA
if (linea.indexOf('#DATA') !== -1) {
// estrai la linea separata da |
let arrparams = linea.split('|');
if (arrparams && arrparams.length > 0) {
let paramstr = arrparams[1].trim();
let value = arrparams[2].trim();
if (paramstr === 'TITLE') {
label = value;
} else if (paramstr === 'DESCRIZ') {
description = value;
}
}
}
}
} catch (error) {
// Se desideri, puoi tenere un avviso o un log qui
}
}
} else {
label = '';
}
if ((label) && (!extfiles || (extfiles && arrscripts[i].endsWith('.' + extfiles)))) {
arrout.push({ label, value: arrscripts[i], description });
}
}
resolve({ error, stdout, stderr, arrout });
});
});
},
execScriptWithInputOnServer: async function (idapp, script) {
return new Promise((resolve, reject) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
// Esegui il processo
const child = spawn('bash', [script]);
let outputData = '';
let errorData = '';
// Gestisci l'output standard
child.stdout.on('data', (data) => {
outputData += data.toString(); // Accumulate output data
console.log(`Output: ${data}`);
// Chiedi l'input dell'utente
rl.question('Your input: ', (answer) => {
child.stdin.write(`${answer}\n`); // Invia la risposta allo script
});
});
// Gestisci l'output di errore
child.stderr.on('data', (data) => {
errorData += data.toString(); // Accumulate error data
console.error(`Error: ${data}`);
});
// Gestisci la chiusura del processo
child.on('close', (code) => {
console.log(`Process exited with code ${code}`);
rl.close(); // Chiusura dell'interfaccia readline
// Risolvi la promessa con i dati raccolti
if (code !== 0) {
reject(new Error(`Process exited with code ${code}: ${errorData}`)); // Rifiuta in caso di errore
} else {
resolve({ stdout: outputData, stderr: errorData });
}
});
// Gestisci errori nel processo
child.on('error', (error) => {
reject(new Error(`Failed to start process: ${error.message}`));
});
});
},
execScriptByTelegram: function (idapp, msg, script, testo) {
const { exec } = require('child_process');
const telegrambot = require('../telegram/telegrambot');
@@ -4581,7 +4767,7 @@ module.exports = {
/*if (params.openUrl)
content = content + '\n' + '<a href="' + myhost + params.openUrl + '">' + i18n.__('OPEN PAGE') + '</a>';
*/
}