2018-12-24 20:31:02 +01:00
require ( './config/config' ) ;
2021-06-04 10:07:57 +02:00
// console.log(" lodash");
2025-05-08 23:32:19 +02:00
console . log ( 'VERSIONE NODE.JS :' , process . versions . node ) ;
2025-03-03 00:46:08 +01:00
if ( process . env . AUTH _MONGODB === undefined ) {
console . error ( "AUTH_MONGODB non presente. VARIABILI D'AMBIENTE NON SETTATI!" ) ;
2025-03-10 17:20:57 +01:00
process . exit ( 1 ) ;
2025-03-03 00:46:08 +01:00
}
2018-12-24 20:31:02 +01:00
const _ = require ( 'lodash' ) ;
2021-06-04 10:07:57 +02:00
// console.log(" cors");
2018-12-24 20:31:02 +01:00
const cors = require ( 'cors' ) ;
2018-12-27 20:09:40 +01:00
2021-06-04 10:07:57 +02:00
// console.log(" 2) fs");
2025-05-15 14:27:46 +02:00
const fs = require ( 'fs' ) ; // 👈 Usa il modulo promises
2019-12-07 00:20:06 +01:00
2024-07-23 12:25:10 +02:00
var https = require ( 'https' ) ;
var http = require ( 'http' ) ;
2024-08-29 23:30:58 +02:00
const WebSocket = require ( 'ws' ) ;
const { spawn } = require ( 'child_process' ) ;
2025-09-22 19:09:02 +02:00
const helmet = require ( 'helmet' ) ;
const morgan = require ( 'morgan' ) ;
const apiRouter = require ( './routes/index-aa' ) ;
const { notFound , errorHandler } = require ( './middleware/error' ) ;
const rateLimit = require ( './middleware/rateLimit' ) . rateLimit ;
2023-02-20 02:19:53 +01:00
const NUOVO _METODO _TEST = true ;
2023-02-16 20:13:38 +01:00
2024-09-17 17:38:47 +02:00
const METODO _MULTI _CORS = true ;
2024-07-23 12:25:10 +02:00
2022-02-27 16:56:02 +01:00
const server _constants = require ( './tools/server_constants' ) ;
2019-12-07 00:20:06 +01:00
//const throttle = require('express-throttle-bandwidth');
2022-01-23 23:25:34 +01:00
// app.use(throttle(1024 * 128)) // throttling bandwidth
2018-12-27 20:09:40 +01:00
2021-12-21 18:12:28 +01:00
// var cookieParser = require('cookie-parser')
// var csrf = require('csurf')
2019-02-05 03:40:22 +01:00
const express = require ( 'express' ) ;
2024-07-23 12:25:10 +02:00
const vhost = require ( 'vhost' ) ;
2019-02-05 03:40:22 +01:00
const bodyParser = require ( 'body-parser' ) ;
const path = require ( 'path' ) ;
2019-11-21 00:18:40 +01:00
const cron = require ( 'node-cron' ) ;
2023-02-15 21:40:19 +01:00
console . log ( 'Starting mongoose...' ) ;
2019-02-14 19:01:41 +01:00
2023-02-15 21:40:19 +01:00
// console.log('Starting pem...');
// const pem = require('pem')
const { Settings } = require ( './models/settings' ) ;
2022-02-22 21:14:49 +01:00
2023-12-07 08:34:24 +01:00
const Site = require ( './models/site' ) ;
2022-11-10 19:33:23 +01:00
// test
2022-03-01 23:50:58 +01:00
2022-02-22 21:14:49 +01:00
const i18n = require ( 'i18n' ) ;
2020-05-19 00:18:13 +02:00
2024-08-29 23:30:58 +02:00
const readline = require ( 'readline' ) ;
2023-02-20 02:19:53 +01:00
let credentials = null ;
2022-02-22 21:14:49 +01:00
console . log ( 'DB: ' + process . env . DATABASE ) ;
2021-06-04 10:07:57 +02:00
// console.log("PORT: " + port);
// console.log("MONGODB_URI: " + process.env.MONGODB_URI);
2018-12-24 20:31:02 +01:00
var app = express ( ) ;
2021-12-29 18:26:08 +01:00
let telegrambot = null ;
2019-02-14 19:01:41 +01:00
const tools = require ( './tools/general' ) ;
2022-01-16 23:21:03 +01:00
const shared _consts = require ( './tools/shared_nodejs' ) ;
2025-03-04 20:20:26 +01:00
const { connectToDatabase , connectionUrl , options } = require ( './db/mongoose' ) ;
// Avvia la connessione
connectToDatabase ( connectionUrl , options )
. then ( ( ) => {
console . log ( '------------------------------------------------------------------' ) ;
console . log ( '--------------- CONNESSIONE AL DB EFFETTUATA ! -----------------' ) ;
2025-03-12 21:03:02 +01:00
console . log ( '------------------------------------------------------------------' ) ;
2025-03-04 20:20:26 +01:00
const { CfgServer } = require ( './models/cfgserver' ) ;
const { ObjectId } = require ( 'mongodb' ) ;
const populate = require ( './populate/populate' ) ;
const { Circuit } = require ( './models/circuit' ) ;
const printf = require ( 'util' ) . format ;
2025-05-08 23:32:19 +02:00
myLoad ( ) . then ( ( ris ) => {
2025-03-04 20:20:26 +01:00
const { User } = require ( './models/user' ) ;
require ( './models/todo' ) ;
require ( './models/project' ) ;
require ( './models/subscribers' ) ;
require ( './models/booking' ) ;
require ( './models/sendmsg' ) ;
require ( './models/sendnotif' ) ;
require ( './models/mailinglist' ) ;
require ( './models/newstosent' ) ;
require ( './models/mypage' ) ;
require ( './models/myelem' ) ;
require ( './models/myscheda' ) ;
require ( './models/bot' ) ;
require ( './models/calzoom' ) ;
2025-09-05 01:06:46 +02:00
2025-03-04 20:20:26 +01:00
const mysql _func = require ( './mysql/mysql_func' ) ;
const index _router = require ( './router/index_router' ) ;
const push _router = require ( './router/push_router' ) ;
const newsletter _router = require ( './router/newsletter_router' ) ;
const booking _router = require ( './router/booking_router' ) ;
const dashboard _router = require ( './router/dashboard_router' ) ;
const myevent _router = require ( './router/myevent_router' ) ;
const subscribe _router = require ( './router/subscribe_router' ) ;
const sendmsg _router = require ( './router/sendmsg_router' ) ;
const sendnotif _router = require ( './router/sendnotif_router' ) ;
const email _router = require ( './router/email_router' ) ;
const todos _router = require ( './router/todos_router' ) ;
const test _router = require ( './router/test_router' ) ;
const projects _router = require ( './router/projects_router' ) ;
const report _router = require ( './router/report_router' ) ;
const users _router = require ( './router/users_router' ) ;
const reactions _router = require ( './router/reactions_router' ) ;
const mygroups _router = require ( './router/mygroups_router' ) ;
const circuits _router = require ( './router/circuits_router' ) ;
const accounts _router = require ( './router/accounts_router' ) ;
const iscrittiConacreis _router = require ( './router/iscrittiConacreis_router' ) ;
const iscrittiArcadei _router = require ( './router/iscrittiArcadei_router' ) ;
const site _router = require ( './router/site_router' ) ;
const admin _router = require ( './router/admin_router' ) ;
const products _router = require ( './router/products_router' ) ;
2025-05-20 12:21:51 +02:00
const myscraping _router = require ( './router/myscraping_router' ) ;
2025-05-15 18:22:43 +02:00
const catalogs _router = require ( './router/catalogs_router' ) ;
2025-03-04 20:20:26 +01:00
const cart _router = require ( './router/cart_router' ) ;
const orders _router = require ( './router/orders_router' ) ;
const city _router = require ( './router/city_router' ) ;
const myskills _router = require ( './router/myskills_router' ) ;
const mygoods _router = require ( './router/mygoods_router' ) ;
const mygen _router = require ( './router/mygen_router' ) ;
const aitools _router = require ( './router/aitools_router' ) ;
const article _router = require ( './router/articleRoutes' ) ;
2025-05-15 14:27:46 +02:00
const api _router = require ( './router/api_router' ) ;
2025-03-04 20:20:26 +01:00
const { MyEvent } = require ( './models/myevent' ) ;
app . use ( bodyParser . json ( { limit : '50mb' } ) ) ;
app . use ( bodyParser . urlencoded ( { limit : '50mb' , extended : true } ) ) ;
app . use ( express . static ( 'views' ) ) ;
2025-05-08 23:32:19 +02:00
app . use ( express . json ( { limit : '100mb' } ) ) ;
app . use ( express . urlencoded ( { extended : true , limit : '100mb' } ) ) ;
2025-03-04 20:20:26 +01:00
// app.use(express.static(path.join(__dirname, 'client')));
app . use ( bodyParser . json ( ) ) ;
// app.set('view engine', 'pug');
// Set static folder
// app.use(express.static(path.join(__dirname, 'public')));
i18n . configure ( {
locales : [ 'it' , 'enUs' , 'es' , 'fr' , 'pt' , 'si' ] ,
defaultLocale : 'it' ,
// cookie: 'cook',
directory : _ _dirname + '/locales' ,
api : {
2025-05-08 23:32:19 +02:00
_ _ : 'translate' ,
_ _n : 'translateN' ,
2025-03-04 20:20:26 +01:00
} ,
} ) ;
2018-12-24 20:31:02 +01:00
2025-03-04 20:20:26 +01:00
// Serve il tuo service worker da una certa directory
/ * a p p . g e t ( ' / s e r v i c e - w o r k e r . j s ' , ( r e q , r e s ) = > {
res . set ( 'Cache-Control' , 'no-cache' ) ; // Aggiunge l'intestazione
// res.sendFile(path.join(__dirname, 'service-worker.js')); // Modifica il percorso secondo la tua struttura
} ) ; * /
2018-12-24 20:31:02 +01:00
2025-03-04 20:20:26 +01:00
app . use ( bodyParser . json ( ) ) ;
2023-02-15 21:40:19 +01:00
2025-03-04 20:20:26 +01:00
// app.use(express.cookieParser());
app . use ( i18n . init ) ;
2018-12-24 20:31:02 +01:00
2025-05-08 23:32:19 +02:00
console . log ( 'Use Routes ...' ) ;
2021-04-30 01:31:12 +02:00
2025-03-04 20:20:26 +01:00
// catch 404 and forward to error handler
// app.use(function (req, res, next) {
// var err = new Error('Not Found');
// err.status = 404;
// next(err);
2021-04-30 01:31:12 +02:00
// });
2020-01-03 22:02:18 +01:00
2025-03-04 20:20:26 +01:00
// app.set('views', path.join(__dirname, 'views'));
// app.set('view engine', 'pug');
// development error handler
// will print stacktrace
if ( app . get ( 'env' ) === 'development' ) {
app . use ( function ( err , req , res , next ) {
console . log ( 'Server Error: ' , err . message ) ;
// console.trace();
res . status ( err . status || 500 ) . send ( { error : err . message } ) ;
// res.render('error', {
// message: err.message,
// error: err
// });
} ) ;
}
if ( process . env . NODE _ENV === 'production' ) {
console . log ( '*** PRODUCTION! ' ) ;
}
2024-09-06 19:57:09 +02:00
2025-05-08 23:32:19 +02:00
if ( process . env . NODE _ENV === 'production' || process . env . NODE _ENV === 'test' ) {
2025-03-04 20:20:26 +01:00
}
startServer ( app , process . env . PORT ) ;
// Use Routes
app . use ( '/' , index _router ) ;
app . use ( '/subscribe' , subscribe _router ) ;
app . use ( '/sendmsg' , sendmsg _router ) ;
app . use ( '/sendnotif' , sendnotif _router ) ;
app . use ( '/push' , push _router ) ;
app . use ( '/news' , newsletter _router ) ;
app . use ( '/booking' , booking _router ) ;
app . use ( '/dashboard' , dashboard _router ) ;
app . use ( '/event' , myevent _router ) ;
app . use ( '/email' , email _router ) ;
app . use ( '/todos' , todos _router ) ;
app . use ( '/test' , test _router ) ;
app . use ( '/projects' , projects _router ) ;
app . use ( '/users' , users _router ) ;
app . use ( '/reactions' , reactions _router ) ;
app . use ( '/mygroup' , mygroups _router ) ;
app . use ( '/circuit' , circuits _router ) ;
app . use ( '/account' , accounts _router ) ;
app . use ( '/iscritti_conacreis' , iscrittiConacreis _router ) ;
app . use ( '/iscritti_arcadei' , iscrittiArcadei _router ) ;
app . use ( '/report' , report _router ) ;
app . use ( '/site' , site _router ) ;
app . use ( '/admin' , admin _router ) ;
app . use ( '/products' , products _router ) ;
2025-05-20 12:21:51 +02:00
app . use ( '/myscraping' , myscraping _router ) ;
2025-05-15 18:22:43 +02:00
app . use ( '/catalogs' , catalogs _router ) ;
2025-03-04 20:20:26 +01:00
app . use ( '/cart' , cart _router ) ;
app . use ( '/orders' , orders _router ) ;
app . use ( '/city' , city _router ) ;
app . use ( '/myskills' , myskills _router ) ;
app . use ( '/mygoods' , mygoods _router ) ;
app . use ( '/mygen' , mygen _router ) ;
app . use ( '/aitools' , aitools _router ) ;
app . use ( '/apisqlsrv' , article _router ) ;
2025-05-15 14:27:46 +02:00
app . use ( '/api' , api _router ) ;
2025-03-04 20:20:26 +01:00
mystart ( ) ;
} ) ;
2022-07-23 17:48:33 +02:00
2025-03-04 20:20:26 +01:00
// app.use(throttle(1024 * 128)); // throttling bandwidth
2021-03-17 02:24:11 +01:00
2025-03-04 20:20:26 +01:00
async function myLoad ( ) {
return tools . loadApps ( ) ;
}
2020-04-24 10:29:25 +02:00
2025-03-04 20:20:26 +01:00
async function mystart ( ) {
// await estraiTutteLeImmagini();
2021-04-30 01:31:12 +02:00
2025-05-08 23:32:19 +02:00
console . log ( 'Versione Server: ' + ( await tools . getVersServer ( ) ) ) ;
2022-07-23 17:48:33 +02:00
2025-03-04 20:20:26 +01:00
await tools . getApps ( ) ;
2021-04-30 01:31:12 +02:00
2025-07-29 12:53:28 +02:00
let miapass = '' ;
2025-03-04 20:20:26 +01:00
if ( process . env . PROD !== 1 ) {
testmsgwebpush ( ) ;
2021-04-30 01:31:12 +02:00
2025-03-04 20:20:26 +01:00
// tools.sendNotifToAdmin('Riparti', 'Riparti');
2022-01-23 23:25:34 +01:00
2025-03-04 20:20:26 +01:00
if ( miapass !== '' ) {
let crypt = tools . cryptdata ( miapass ) ;
let decrypt = tools . decryptdata ( crypt ) ;
2021-04-30 01:31:12 +02:00
2025-03-04 20:20:26 +01:00
console . log ( 'crypted:' , crypt ) ;
console . log ( 'decrypted:' , decrypt ) ;
}
2019-10-05 20:01:56 +02:00
2025-03-04 20:20:26 +01:00
mycron ( ) ;
}
2021-04-30 01:31:12 +02:00
2025-07-29 12:53:28 +02:00
miapass = 'PROVA123@' ;
let crypt = tools . cryptdata ( miapass ) ;
let decrypt = tools . decryptdata ( crypt ) ;
2025-03-04 20:20:26 +01:00
telegrambot = require ( './telegram/telegrambot' ) ;
2019-02-22 10:23:39 +01:00
2025-07-29 12:53:28 +02:00
if ( decrypt === miapass ) {
console . log ( '✅ Decrypt OK' ) ;
// OK FUNZIONA
} else {
let msgerr = '❌ ERRORE! la decrittazione non funziona! ' ;
console . error ( msgerr ) ;
2025-09-22 19:09:02 +02:00
await telegrambot . sendMsgTelegramToTheAdminAllSites ( msgerr , false ) ;
2025-07-29 12:53:28 +02:00
}
2025-03-04 20:20:26 +01:00
await inizia ( ) ;
2019-02-22 10:23:39 +01:00
2025-03-04 20:20:26 +01:00
await resetProcessingJob ( ) ;
2019-02-22 10:23:39 +01:00
2025-03-04 20:20:26 +01:00
populate . popolaTabelleNuove ( ) ;
2019-02-22 10:23:39 +01:00
2025-03-04 20:20:26 +01:00
faitest ( ) ;
2024-02-08 01:34:30 +01:00
2025-03-04 20:20:26 +01:00
// ----------------- MAILCHIMP -----
const querystring = require ( 'querystring' ) ;
const mailchimpClientId = 'xxxxxxxxxxxxxxxx' ;
app . get ( '/mailchimp/auth/authorize' , function ( req , res ) {
2025-05-08 23:32:19 +02:00
res . redirect (
'https://login.mailchimp.com/oauth2/authorize?' +
querystring . stringify ( {
response _type : 'code' ,
client _id : mailchimpClientId ,
redirect _uri : 'http://127.0.0.1:3000/mailchimp/auth/callback' ,
} )
) ;
2025-03-04 20:20:26 +01:00
} ) ;
2024-02-08 01:34:30 +01:00
}
2020-05-19 00:18:13 +02:00
2025-03-04 20:20:26 +01:00
// -----------------
2020-06-08 13:31:05 +02:00
2025-03-04 20:20:26 +01:00
function populateDBadmin ( ) {
const cfgserv = [
{
_id : new ObjectId ( ) ,
idapp : '9' ,
chiave : 'vers' ,
userId : 'ALL' ,
valore : '0.1.2' ,
2025-05-08 23:32:19 +02:00
} ,
] ;
2020-05-19 00:18:13 +02:00
2025-03-04 20:20:26 +01:00
let cfg = new CfgServer ( cfgserv [ 0 ] ) . save ( ) ;
2020-05-19 00:18:13 +02:00
}
2019-10-20 01:21:54 +02:00
2025-03-04 20:20:26 +01:00
async function mycron ( ) {
try {
const sendemail = require ( './sendemail' ) ;
2024-03-21 21:22:57 +01:00
2025-05-07 21:58:43 +02:00
const { Cron } = require ( './models/cron' ) ;
2024-03-21 21:22:57 +01:00
2025-05-07 21:58:43 +02:00
const arr = await tools . getApps ( ) ;
2025-03-04 20:20:26 +01:00
for ( const app of arr ) {
await sendemail . checkifPendingNewsletter ( app . idapp ) ;
await sendemail . checkifSentNewsletter ( app . idapp ) ;
2024-03-21 21:22:57 +01:00
2025-05-07 21:58:43 +02:00
await Cron . startJobCron ( app . idapp ) ;
2025-03-04 20:20:26 +01:00
}
} catch ( e ) {
console . error ( 'Err mycron' , e ) ;
}
2024-03-21 21:22:57 +01:00
}
2025-03-04 20:20:26 +01:00
async function mycron _30min ( ) {
for ( const app of await tools . getApps ( ) ) {
let enablecrontab = false ;
2019-10-05 20:01:56 +02:00
2025-05-08 23:32:19 +02:00
enablecrontab = await Settings . getValDbSettings ( app . idapp , tools . ENABLE _CRONTAB , false ) ;
2019-02-14 19:01:41 +01:00
2025-03-04 20:20:26 +01:00
if ( enablecrontab ) {
// ...
}
2020-04-10 13:02:33 +02:00
}
2019-02-14 19:01:41 +01:00
}
2025-03-04 20:20:26 +01:00
async function mycron _everyday ( ) {
try {
const { User } = require ( './models/user' ) ;
2020-05-19 00:18:13 +02:00
2025-03-04 20:20:26 +01:00
const arrapps = await tools . getApps ( ) ;
for ( const app of arrapps ) {
// Azzera le richieste di password:
const usersblocked = await User . find ( { idapp : app . idapp , retry _pwd : { $exists : true , $gte : 29 } } ) . lean ( ) ;
for ( const user of usersblocked ) {
await User . findOneAndUpdate ( { _id : user . _id } , { $set : { retry _pwd : 20 } } ) ;
let text = ` ⚠️⚠️⚠️ L \' utente ${ user . username } ( ${ user . name } ${ user . surname } ) viene sbloccato dal numero massimo di tentativi di richiesta password! \n Telerlo d \' occhio ! \n @ ${ user . profile . username _telegram } ` ;
await telegrambot . sendMsgTelegramToTheAdminAllSites ( text , false ) ;
}
}
} catch ( e ) {
console . error ( 'mycron_everyday: ' , e ) ;
}
}
2020-06-08 13:31:05 +02:00
2025-03-04 20:20:26 +01:00
function testmsgwebpush ( ) {
const { User } = require ( './models/user' ) ;
2021-04-30 01:31:12 +02:00
2025-03-04 20:20:26 +01:00
// console.log('nomeapp 1: ' , tools.getNomeAppByIdApp(1));
// console.log('nomeapp 2: ' , tools.getNomeAppByIdApp(2));
2020-02-07 22:08:46 +01:00
2025-03-04 20:20:26 +01:00
User . find ( { username : 'paoloar77' , idapp : '1' } ) . then ( async ( arrusers ) => {
if ( arrusers !== null ) {
for ( const user of arrusers ) {
2025-05-08 23:32:19 +02:00
await tools
. sendNotificationToUser ( user . _id , 'Server' , 'Il Server è Ripartito' , '/' , '' , 'server' , [ ] )
. then ( ( ris ) => {
2025-03-04 20:20:26 +01:00
if ( ris ) {
} else {
// already sent the error on calling sendNotificationToUser
}
} ) ;
}
}
2023-02-15 21:40:19 +01:00
} ) ;
2025-03-04 20:20:26 +01:00
}
2018-12-27 20:09:40 +01:00
2025-05-07 21:58:43 +02:00
// Esecuzione ogni 1 minuto (*/1 * * * *)
// La sintassi di cron è:
// 0 12 * * * comando
// che significa: esegui il comando ogni giorno alle 12:00
// La sintassi di node-cron è:
// cron.schedule('0 12 * * *', () => {
// che significa: esegui il comando ogni giorno alle 12:00
// La sintassi di node-cron con */1 esegue il comando ogni 1 minuto
2025-03-04 20:20:26 +01:00
cron . schedule ( '*/1 * * * *' , ( ) => {
// console.log('Running Cron Job');
// if (!process.env.VITE_DEBUG) {
mycron ( ) ;
// }
} ) ;
2021-04-30 01:31:12 +02:00
2025-05-07 21:58:43 +02:00
// Cron every 1 HOUR
2025-03-04 20:20:26 +01:00
cron . schedule ( '*/60 * * * *' , async ( ) => {
if ( ! process . env . VITE _DEBUG ) {
mycron _30min ( ) ;
}
} ) ;
2024-03-23 00:21:32 +01:00
2025-03-04 20:20:26 +01:00
// Cron every 21:00 (1 volta al giorno)
cron . schedule ( '0 21 * * *' , async ( ) => {
mycron _everyday ( ) ;
} ) ;
// mycron_30min();
2021-12-23 14:13:40 +01:00
2025-03-04 20:20:26 +01:00
// tools.writelogfile('test', 'prova.txt');
2020-01-03 22:02:18 +01:00
2025-03-04 20:20:26 +01:00
async function resetProcessingJob ( ) {
const { Newstosent } = require ( './models/newstosent' ) ;
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
arrrec = await Newstosent . find ( { } ) ;
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
for ( const rec of arrrec ) {
rec . processing _job = false ;
2025-05-08 23:32:19 +02:00
await Newstosent . findOneAndUpdate ( { _id : rec . id } , { $set : rec } , { new : false } ) . then ( ( item ) => { } ) ;
2025-03-04 20:20:26 +01:00
}
2022-03-12 21:38:19 +01:00
}
2022-11-06 13:39:01 +01:00
2025-03-04 20:20:26 +01:00
//app.listen(port, () => {
// console.log(`Server started at port ${port}`);
//});
2023-12-07 08:34:24 +01:00
2025-03-04 20:20:26 +01:00
async function inizia ( ) {
try {
if ( true ) {
const url = 'https://raw.githubusercontent.com/matteocontrini/comuni-json/master/comuni.json' ;
const outputPath = './comuni_italia_geojson.json' ;
downloadGeoJSON ( url , outputPath ) ;
}
2024-07-03 14:21:02 +02:00
2025-03-04 20:20:26 +01:00
mycron _everyday ( ) ;
2022-11-10 19:33:23 +01:00
2025-03-04 20:20:26 +01:00
if ( process . env . NODE _ENV === 'development' ) {
2025-05-08 23:32:19 +02:00
await telegrambot . sendMsgTelegram (
tools . FREEPLANET ,
2025-03-04 20:20:26 +01:00
shared _consts . ADMIN _USER _SERVER ,
2025-05-08 23:32:19 +02:00
` Ciao ${ telegrambot . ADMIN _USER _NAME _SERVER } ! `
) ;
2023-02-20 02:19:53 +01:00
2025-05-08 23:32:19 +02:00
await telegrambot . sendMsgTelegramByIdTelegram (
tools . FREEPLANET ,
2025-03-04 20:20:26 +01:00
telegrambot . ADMIN _IDTELEGRAM _SERVER ,
2025-05-08 23:32:19 +02:00
` Ciao ${ telegrambot . ADMIN _USER _NAME _SERVER } \n ` + ` 🔅 Il Server ${ process . env . DATABASE } è appena ripartito! `
) ;
2025-03-04 20:20:26 +01:00
} else {
2025-05-08 23:32:19 +02:00
await telegrambot . sendMsgTelegramToTheAdminAllSites (
` Ciao Admin \n ` + ` 🔅🔅🔅 Il Server col BOT di {appname} è appena ripartito! ` ,
false
) ;
2025-03-04 20:20:26 +01:00
}
2020-02-19 16:09:16 +01:00
2025-03-04 20:20:26 +01:00
await Site . createFirstUserAdmin ( ) ;
2020-02-07 22:08:46 +01:00
2025-03-04 20:20:26 +01:00
/ * c o n s t { C i r c u i t } = r e q u i r e ( ' . / m o d e l s / c i r c u i t ' ) ;
await Circuit . setDeperimentoOff ( ) ;
* /
2025-05-08 23:32:19 +02:00
} catch ( e ) { }
2025-03-04 20:20:26 +01:00
}
2022-07-23 17:48:33 +02:00
2025-03-04 20:20:26 +01:00
//
2022-07-23 17:48:33 +02:00
2025-03-04 20:20:26 +01:00
// telegrambot.sendMsgTelegramToTheManagers('7', 'PROVAAA!');
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
// if (process.env.PROD !== 1) {
// const reg = require('./reg/registration');
// const link = reg.getlinkregByEmail('7', 'tomasihelen@dasdasgmail.comAAAA' , 'HelenTomasidasdasd');
// const link2 = reg.getlinkregByEmail('7', 'tomasihelen@gmail.com' , 'HelenTomasi');
// //const link2 = reg.getlinkregByEmail('7', 'elenaliubicich@gmail.com' , 'Elenaliu');
//
// console.log(link);
// console.log(link2);
// }
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
async function estraiImmagini ( table ) {
const { User } = require ( './models/user' ) ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
let idapp = '13' ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
let arrlist ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
const globalTables = require ( './tools/globalTables' ) ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
const mytable = globalTables . getTableByTableName ( table ) ;
2025-05-08 23:32:19 +02:00
if ( ! mytable ) return ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
console . log ( 'INIZIO - estraiImmagini' , table ) ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
arrlist = await mytable . find ( { idapp } ) . lean ( ) ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
let file = '' ;
let filetocheck = '' ;
let dirmain = '' ;
let filefrom = '' ;
let filefrom2 = '' ;
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
try {
if ( ! tools . sulServer ( ) ) {
2025-03-31 23:56:01 +02:00
dirmain = server _constants . DIR _PUBLIC _LOCALE ;
2025-03-04 20:20:26 +01:00
}
2022-03-01 23:50:58 +01:00
2025-05-11 21:59:25 +02:00
let dir = tools . getdirByIdApp ( idapp ) + dirmain + '/upload/' ;
2025-03-04 20:20:26 +01:00
for ( const rec of arrlist ) {
const myuser = await User . findOne ( { idapp , _id : rec . userId } ) . lean ( ) ;
if ( myuser ) {
const myphotos = rec . photos ;
if ( myphotos . length > 0 ) {
let folderprof = dir + 'profile/' + myuser . username ;
try {
// console.log('checkdir', folderprof);
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( folderprof ) ) ) {
2025-03-04 20:20:26 +01:00
console . log ( '*** Creadir' , folderprof ) ;
2025-05-15 14:27:46 +02:00
await fs . mkdirSync ( folderprof ) ;
2025-03-04 20:20:26 +01:00
}
folderprof = dir + 'profile/' + myuser . username + '/' + table ;
// console.log('checkdir', folderprof);
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( folderprof ) ) ) {
2025-03-04 20:20:26 +01:00
console . log ( 'creadir' , folderprof ) ;
2025-05-15 14:27:46 +02:00
await fs . mkdirSync ( folderprof ) ;
2025-03-04 20:20:26 +01:00
}
2025-05-08 23:32:19 +02:00
} catch ( e ) { }
2022-03-01 23:50:58 +01:00
}
2025-03-04 20:20:26 +01:00
for ( const photo of myphotos ) {
if ( photo . imagefile ) {
2025-05-08 23:32:19 +02:00
file = dir + 'profile/' + myuser . username + '/' + table + '/' + photo . imagefile ;
2025-03-04 20:20:26 +01:00
filefrom = dir + 'profile/undefined/' + table + '/' + photo . imagefile ;
filefrom2 = dir + 'profile/' + myuser . username + '/' + photo . imagefile ;
// console.log('file', file);
// console.log('filefrom', filefrom);
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( file ) ) ) {
2025-03-04 20:20:26 +01:00
// non esiste
console . log ( 'non esiste' , file ) ;
console . log ( ' filefrom' , filefrom ) ;
console . log ( ' filefrom2' , filefrom2 ) ;
}
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( file ) ) && ( await tools . isFileExistsAsync ( filefrom ) ) ) {
2025-03-04 20:20:26 +01:00
console . log ( '@@@@@@ copia file:' , filefrom , 'a' , file ) ;
tools . copy ( filefrom , file ) ;
}
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( file ) ) && ( await tools . isFileExistsAsync ( filefrom2 ) ) ) {
2025-03-04 20:20:26 +01:00
console . log ( '@@@@@@ copia file 2:' , filefrom2 , 'a' , file ) ;
tools . copy ( filefrom2 , file ) ;
}
}
2022-03-01 23:50:58 +01:00
}
}
}
2025-03-04 20:20:26 +01:00
console . log ( 'FINE - estraiImmagini' , table ) ;
} catch ( e ) {
console . error ( 'e' , e ) ;
2022-03-01 23:50:58 +01:00
}
}
2025-03-04 20:20:26 +01:00
async function estraiTutteLeImmagini ( ) {
await estraiImmagini ( 'myskills' ) ;
await estraiImmagini ( 'mygoods' ) ;
await estraiImmagini ( 'mybachecas' ) ;
}
2022-03-01 23:50:58 +01:00
2025-03-04 20:20:26 +01:00
async function faitest ( ) {
// console.log('Fai Test:')
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
const testfind = false ;
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
// const $vers = tools.getVersionint('1.92.45');
2021-10-28 00:38:10 +02:00
2025-03-04 20:20:26 +01:00
if ( true ) {
// tools.execScript("ls -la");
}
2022-03-12 21:38:19 +01:00
2025-03-04 20:20:26 +01:00
if ( false ) {
prova = tools . removeAtChar ( '@prova' ) ;
}
2022-07-10 01:25:19 +02:00
2025-03-04 20:20:26 +01:00
if ( false ) {
const prova = tools . getConfSiteOptionEnabledByIdApp ( '13' , shared _consts . ConfSite . Notif _Reg _Push _Admin ) ;
console . log ( 'prova' , prova ) ;
}
2022-02-27 16:56:02 +01:00
2025-03-04 20:20:26 +01:00
if ( testfind ) {
const { City } = require ( './models/city' ) ;
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
let miacity = 'roma' ;
const ris = await City . findByCity ( miacity ) ;
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
console . log ( 'ris' , ris ) ;
}
2021-10-08 00:38:35 +02:00
2025-03-04 20:20:26 +01:00
const { User } = require ( './models/user' ) ;
2022-01-16 23:21:03 +01:00
2025-03-04 20:20:26 +01:00
if ( false ) {
let myuser = await User . findOne ( {
idapp : '1' ,
username : 'paoloar77' ,
} ) ;
const langdest = 'it' ;
2022-01-16 23:21:03 +01:00
2025-03-04 20:20:26 +01:00
telegrambot . askConfirmationUser ( myuser . idapp , shared _consts . CallFunz . REGISTRATION , myuser ) ;
}
2022-01-16 23:21:03 +01:00
2025-03-04 20:20:26 +01:00
if ( false ) {
const user = await User . findOne ( {
idapp : 12 ,
username : 'paolotest1' ,
} ) ;
2022-01-16 23:21:03 +01:00
2025-05-08 23:32:19 +02:00
await sendemail . sendEmail _Registration ( 'it' , 'paolo@arcodiluce.it' , user , '12' , '' ) ;
2025-03-04 20:20:26 +01:00
}
2022-01-07 01:18:01 +01:00
2025-03-04 20:20:26 +01:00
if ( false ) {
const { User } = require ( './models/user' ) ;
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
const idapp = tools . FREEPLANET ;
const idreg = 0 ;
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
try {
const user = await User . findOne ( {
idapp ,
username : 'paoloar773' ,
} ) ;
2021-12-29 18:26:08 +01:00
2025-03-04 20:20:26 +01:00
user . aportador _solidario = 'paoloar77' ;
let mylocalsconf = {
idapp ,
dataemail : null ,
locale : user . lang ,
nomeapp : tools . getNomeAppByIdApp ( idapp ) ,
strlinksito : tools . getHostByIdApp ( idapp ) ,
strlinkreg : '' ,
username : user . username ,
name : user . name ,
surname : user . surname ,
forgetpwd : tools . getHostByIdApp ( idapp ) + '/requestresetpwd' ,
emailto : '' ,
user ,
} ;
2021-10-08 00:38:35 +02:00
2025-05-08 23:32:19 +02:00
await telegrambot . notifyToTelegram ( telegrambot . phase . REGISTRATION , mylocalsconf ) ;
2025-03-04 20:20:26 +01:00
} catch ( e ) {
console . log ( 'error ' + e ) ;
}
}
}
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// Funzione migliorata per ottenere chiave e certificato
2025-05-19 17:33:58 +02:00
async function getCredentials ( hostname ) {
2025-05-15 14:27:46 +02:00
try {
let keyPath , certPath ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
if ( NUOVO _METODO _TEST ) {
if ( METODO _MULTI _CORS ) {
// Percorso basato su hostname (Let's Encrypt)
keyPath = ` /etc/letsencrypt/live/ ${ hostname } / ${ process . env . PATH _CERT _KEY } ` ;
certPath = ` /etc/letsencrypt/live/ ${ hostname } / ${ process . env . PATH _SERVER _CRT } ` ;
} else {
// Percorso relativo
keyPath = path . resolve ( ` ./ ${ process . env . PATH _CERT _KEY } ` ) ;
certPath = path . resolve ( ` ./ ${ process . env . PATH _SERVER _CRT } ` ) ;
2025-03-04 20:20:26 +01:00
}
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// Verifica esistenza file
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( keyPath ) ) ) {
2025-05-15 14:27:46 +02:00
throw new Error ( ` Chiave privata non trovata: ${ keyPath } ` ) ;
}
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( certPath ) ) ) {
2025-05-15 14:27:46 +02:00
throw new Error ( ` Certificato non trovato: ${ certPath } ` ) ;
}
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// Leggi chiave e certificato
const key = fs . readFileSync ( keyPath , 'utf8' ) ;
const cert = fs . readFileSync ( certPath , 'utf8' ) ;
// Restituisci oggetto con credenziali + configurazione TLS avanzata
return {
key ,
cert ,
ciphers :
'ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384' ,
honorCipherOrder : true ,
secureOptions : require ( 'constants' ) . OPENSSL _OPTIONS _TLS _NODELAY ,
secureProtocol : 'TLSv1_2_method' , // Forza TLS 1.2+ (meglio se usi TLSv1_3)
} ;
} else {
// Metodo legacy (opzionale)
throw new Error ( 'Metodo legacy non supportato' ) ;
2025-03-04 20:20:26 +01:00
}
2025-05-15 14:27:46 +02:00
} catch ( error ) {
console . error ( ` [getCredentials] Errore per ${ hostname } : ` , error . message ) ;
throw error ;
2024-09-17 17:38:47 +02:00
}
2024-07-23 12:25:10 +02:00
}
2025-05-15 14:27:46 +02:00
// 🔧 Funzione factory per creare e configurare un server HTTPS
function createHttpsServer ( { hostname , port , website , app , credentials , timeoutMinutes = 5 } ) {
const server = https . createServer ( credentials , app ) ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
const timeoutMs = 1000 * 60 * timeoutMinutes ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// ⏱️ Timeout globale per la connessione TCP
server . setTimeout ( timeoutMs , ( ) => {
console . log ( ` TCP timeout su server: ${ hostname } : ${ port } ` ) ;
} ) ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// ⏱️ Timeout per singola richiesta HTTP
server . on ( 'request' , ( req , res ) => {
req . setTimeout ( timeoutMs ) ;
res . setTimeout ( timeoutMs ) ;
} ) ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// 📡 Eventuali altri eventi utili
server . on ( 'clientError' , ( err , socket ) => {
console . error ( ` Client error su ${ hostname } : ${ port } : ` , err . message ) ;
} ) ;
2024-07-23 12:25:10 +02:00
2025-05-15 14:27:46 +02:00
// Avvia il server
server . listen ( port , ( ) => {
console . log (
'⭐️⭐️⭐️⭐️⭐️ HTTPS server: %s Port: %d%s' ,
hostname ,
port ,
website ? ' WebSite = ' + website : ''
) ;
} ) ;
2024-08-29 23:30:58 +02:00
2025-05-15 14:27:46 +02:00
return server ;
}
2024-09-06 19:57:09 +02:00
2025-05-15 14:27:46 +02:00
function parseDomains ( ) {
let domains = [ ] ;
let domainsAllowed = [ ] ;
try {
if ( process . env . DOMAINS ) domains = JSON . parse ( process . env . DOMAINS ) ;
if ( process . env . DOMAINS _ALLOWED ) domainsAllowed = JSON . parse ( process . env . DOMAINS _ALLOWED ) ;
} catch ( error ) {
console . error ( 'Errore parsing DOMAINS:' , error ) ;
}
return { domains , domainsAllowed } ;
}
2024-10-29 02:33:29 +01:00
2025-05-15 14:27:46 +02:00
function buildAllowedOrigins ( domains , domainsAllowed , isProduction ) {
if ( ! isProduction ) {
2025-07-29 12:53:28 +02:00
return [
'https://localhost:3000' ,
'https://localhost:8089' ,
2025-09-02 16:22:31 +02:00
'https://localhost:8082' ,
'https://localhost:8083' ,
2025-07-29 12:53:28 +02:00
'https://localhost:8084' ,
2025-09-02 16:22:31 +02:00
'https://localhost:8085' ,
2025-07-29 12:53:28 +02:00
'https://localhost:8088' ,
'https://localhost:8099' ,
] ;
2025-05-15 14:27:46 +02:00
}
2024-10-03 03:55:05 +02:00
2025-05-15 14:27:46 +02:00
const baseOrigins = domains . flatMap ( ( domain ) => [
` https:// ${ domain . hostname } ` ,
` https://api. ${ domain . hostname } ` ,
` https://test. ${ domain . hostname } ` ,
` https://testapi. ${ domain . hostname } ` ,
` http:// ${ domain . hostname } ` ,
` http://api. ${ domain . hostname } ` ,
` http://test. ${ domain . hostname } ` ,
` http://testapi. ${ domain . hostname } ` ,
] ) ;
2024-10-03 03:55:05 +02:00
2025-05-15 14:27:46 +02:00
const allowedExtra = domainsAllowed . flatMap ( ( domain ) => [ ` https:// ${ domain } ` , ` http:// ${ domain } ` ] ) ;
2025-03-12 21:03:02 +01:00
2025-05-15 14:27:46 +02:00
return [ ... baseOrigins , ... allowedExtra ] ;
}
2025-03-12 21:03:02 +01:00
2025-05-15 14:27:46 +02:00
function createCorsOptions ( domains , domainsAllowed , isProduction , noCors = false ) {
if ( noCors ) {
console . log ( 'NOCORS mode enabled' ) ;
return {
exposedHeaders : [ 'x-auth' , 'x-refrtok' ] ,
} ;
}
2025-03-12 21:03:02 +01:00
2025-05-15 14:27:46 +02:00
const allowedOrigins = buildAllowedOrigins ( domains , domainsAllowed , isProduction ) ;
2025-03-12 21:03:02 +01:00
2025-05-15 14:27:46 +02:00
const originValidator = ( origin , callback ) => {
if ( ! origin ) {
2025-07-29 12:53:28 +02:00
// console.log('✅ Origin undefined or empty — allowing');
2025-05-15 14:27:46 +02:00
return callback ( null , true ) ;
}
2025-03-04 20:20:26 +01:00
2025-05-15 14:27:46 +02:00
if ( typeof origin !== 'string' || ! /^https?:\/\/[^\s/$.?#].[^\s]*$/ . test ( origin ) ) {
console . error ( '❌ Invalid origin:' , origin ) ;
return callback ( new Error ( 'Origine non valida' ) , false ) ;
}
2025-03-04 20:20:26 +01:00
2025-05-15 14:27:46 +02:00
if ( allowedOrigins . includes ( origin ) ) {
return callback ( null , true ) ;
}
2025-03-12 21:03:02 +01:00
2025-05-15 14:27:46 +02:00
console . warn ( '❌ Origin blocked:' , origin ) ;
return callback ( new Error ( 'CORS non permesso per questa origine' ) , false ) ;
} ;
return {
origin : originValidator ,
credentials : true ,
methods : [ 'GET' , 'POST' , 'PUT' , 'DELETE' , 'OPTIONS' , 'PATCH' ] ,
allowedHeaders : [
'Origin' ,
'X-Requested-With' ,
'Content-Type' ,
'Accept' ,
'Authorization' ,
'x-auth' ,
'x-refrtok' ,
] ,
exposedHeaders : [ 'x-auth' , 'x-refrtok' ] ,
maxAge : 86400 ,
preflightContinue : false ,
optionsSuccessStatus : 204 ,
} ;
}
function setupMiddleware ( app , corsOptions , isDebug = false ) {
2025-09-22 19:09:02 +02:00
app . use ( helmet ( ) ) ;
2025-05-15 14:27:46 +02:00
app . use ( cors ( corsOptions ) ) ;
2025-09-02 16:22:31 +02:00
app . set ( 'trust proxy' , true ) ;
2025-05-15 14:27:46 +02:00
app . use ( express . json ( ) ) ;
2025-09-22 19:09:02 +02:00
app . use ( morgan ( 'dev' ) ) ;
app . use ( rateLimit ) ;
app . get ( '/health' , ( _req , res ) => res . json ( { ok : true } ) ) ;
app . use ( '/apinew' , apiRouter ) ;
// app.use(notFound);
app . use ( errorHandler ) ;
2025-05-15 14:27:46 +02:00
app . options ( '*' , cors ( corsOptions ) ) ;
if ( isDebug ) {
app . use ( ( req , res , next ) => {
console . log ( ` ${ new Date ( ) . toISOString ( ) } - ${ req . method } ${ req . url } ` ) ;
console . log ( 'Request Headers:' , req . headers ) ;
const oldSend = res . send ;
res . send = function ( ... args ) {
console . log ( 'Response Headers:' , res . getHeaders ( ) ) ;
return oldSend . apply ( res , args ) ;
} ;
next ( ) ;
} ) ;
}
app . use ( ( err , req , res , next ) => {
if ( err . message === 'CORS non permesso per questa origine' ) {
console . error ( '❌ Errore CORS:' , {
origin : req . headers . origin ,
method : req . method ,
path : req . path ,
} ) ;
return res . status ( 403 ) . json ( {
error : ` ❌ CORS non permesso per questa origine ( ${ req . headers . origin } ) ` ,
origin : req . headers . origin ,
} ) ;
}
next ( err ) ;
} ) ;
}
2025-03-03 00:46:08 +01:00
2025-05-19 17:33:58 +02:00
async function createHttpOrHttpsServer ( app , port , isProduction , domains ) {
2025-05-15 14:27:46 +02:00
if ( isProduction ) {
2025-05-19 17:33:58 +02:00
const promises = domains . map ( async ( domain ) => {
const credentials = await getCredentials ( domain . hostname ) ;
return createHttpsServer ( {
2025-05-15 14:27:46 +02:00
hostname : domain . hostname ,
port : domain . port ,
website : domain . website ,
app ,
2025-03-04 20:20:26 +01:00
credentials ,
2025-05-15 14:27:46 +02:00
timeoutMinutes : 6 ,
} ) ;
} ) ;
2025-05-19 17:33:58 +02:00
await Promise . all ( promises ) ;
2025-05-15 14:27:46 +02:00
return null ;
}
if ( process . env . HTTPS _LOCALHOST === 'true' ) {
try {
const key = fs . readFileSync ( path . resolve ( ` ./ ${ process . env . PATH _CERT _KEY } ` ) , 'utf8' ) ;
const cert = fs . readFileSync ( path . resolve ( ` ./ ${ process . env . PATH _SERVER _CRT } ` ) , 'utf8' ) ;
const credentials = {
key ,
cert ,
ciphers :
'ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:ECDHE-RSA-AES256-SHA384' ,
honorCipherOrder : true ,
secureProtocol : 'TLSv1_2_method' ,
2025-03-04 20:20:26 +01:00
} ;
2025-03-03 00:46:08 +01:00
2025-05-15 14:27:46 +02:00
const httpsServer = https . createServer ( credentials , app ) ;
httpsServer . listen ( port ) ;
console . log ( '⭐️ HTTPS server running locally on port' , port ) ;
return httpsServer ;
} catch ( error ) {
console . error ( 'Errore caricamento certificati HTTPS locali:' , error . message ) ;
// fallback HTTP server
}
}
2025-03-04 20:20:26 +01:00
2025-05-15 14:27:46 +02:00
const httpServer = http . createServer ( app ) ;
httpServer . listen ( port ) ;
console . log ( '⭐️ HTTP server running on port' , port ) ;
return httpServer ;
}
2025-03-04 20:20:26 +01:00
2025-05-15 14:27:46 +02:00
function setupWebSocketServer ( httpOrHttpsServer ) {
if ( ! httpOrHttpsServer ) {
console . error ( 'Nessun server HTTP o HTTPS disponibile per WebSocket' ) ;
return null ;
}
2024-10-03 03:55:05 +02:00
2025-05-15 14:27:46 +02:00
const wss = new WebSocket . Server ( { server : httpOrHttpsServer } ) ;
2025-03-03 00:46:08 +01:00
2025-05-15 14:27:46 +02:00
wss . on ( 'connection' , ( ws ) => {
console . log ( 'Client socket connected...' ) ;
2024-10-29 02:33:29 +01:00
2025-05-15 14:27:46 +02:00
const { User } = require ( './models/user' ) ;
const pty = require ( 'node-pty' ) ;
let scriptProcess = null ;
2024-10-29 02:33:29 +01:00
2025-05-19 17:33:58 +02:00
ws . on ( 'message' , async ( message ) => {
2025-05-15 14:27:46 +02:00
try {
const parsed = JSON . parse ( message ) ;
2024-10-29 02:33:29 +01:00
2025-05-15 14:27:46 +02:00
if ( parsed . type === 'start_script' && User . isAdminById ( parsed . user _id ) ) {
if ( scriptProcess ) scriptProcess . kill ( ) ;
2024-10-03 03:55:05 +02:00
2025-05-15 14:27:46 +02:00
const scriptPath = path . join ( _ _dirname , '..' , '..' , parsed . scriptName ) ;
2025-07-29 12:53:28 +02:00
if ( ! ( await tools . isFileExistsAsync ( scriptPath ) ) ) {
2025-05-15 14:27:46 +02:00
return ws . send ( JSON . stringify ( { type : 'error' , data : 'Script non trovato o non autorizzato' } ) ) ;
2025-03-04 20:20:26 +01:00
}
2024-10-03 03:55:05 +02:00
2025-05-15 14:27:46 +02:00
scriptProcess = pty . spawn ( 'bash' , [ scriptPath ] , {
name : 'xterm-color' ,
cols : 80 ,
rows : 40 ,
cwd : process . cwd ( ) ,
env : process . env ,
} ) ;
let buffer = '' ;
scriptProcess . on ( 'data' , ( data ) => {
buffer += data ;
ws . send ( JSON . stringify ( { type : 'output' , data } ) ) ;
if (
buffer . endsWith ( ': ' ) ||
buffer . includes ( '? ' ) ||
buffer . toLowerCase ( ) . includes ( 'password' ) ||
buffer . includes ( 'Inserisci' ) ||
buffer . includes ( 'Inserted' ) ||
buffer . includes ( '(Y)' )
) {
ws . send ( JSON . stringify ( { type : 'input_required' , prompt : data . trim ( ) } ) ) ;
buffer = '' ;
}
if ( buffer . length > 5024 ) buffer = buffer . slice ( - 500 ) ;
} ) ;
scriptProcess . on ( 'exit' , ( code ) => {
const closeMsg = code === 0 ? '*** FINE SCRIPT ***' : ` Script terminato con codice ${ code } ` ;
ws . send ( JSON . stringify ( { type : 'close' , data : closeMsg } ) ) ;
} ) ;
} else if ( parsed . type === 'input' ) {
if ( scriptProcess ) {
scriptProcess . write ( parsed . data + '\n' ) ;
}
2025-03-04 20:20:26 +01:00
}
2025-05-15 14:27:46 +02:00
} catch ( err ) {
console . error ( "Errore durante l'elaborazione del messaggio:" , err . message ) ;
2024-07-31 15:02:40 +02:00
}
2025-05-15 14:27:46 +02:00
} ) ;
2024-07-31 15:02:40 +02:00
2025-05-15 14:27:46 +02:00
ws . on ( 'close' , ( ) => {
console . log ( '*** Client socket disconnected' ) ;
if ( scriptProcess ) scriptProcess . kill ( ) ;
} ) ;
} ) ;
2024-07-31 15:02:40 +02:00
2025-05-15 14:27:46 +02:00
return wss ;
}
2024-08-29 23:30:58 +02:00
2025-05-19 17:33:58 +02:00
async function startServer ( app , port ) {
2025-05-15 14:27:46 +02:00
try {
const isProduction = [ 'production' , 'test' ] . includes ( process . env . NODE _ENV ) ;
const ISDEBUG = false ;
const NOCORS = false ;
2024-08-29 23:30:58 +02:00
2025-05-15 14:27:46 +02:00
const { domains , domainsAllowed } = parseDomains ( ) ;
2024-08-29 23:30:58 +02:00
2025-05-15 14:27:46 +02:00
console . log ( 'domains:' , domains ) ;
console . log ( 'isProduction:' , isProduction ) ;
2024-09-09 21:49:25 +02:00
2025-05-15 14:27:46 +02:00
const corsOptions = createCorsOptions ( domains , domainsAllowed , isProduction , NOCORS ) ;
2024-09-06 19:57:09 +02:00
2025-05-15 14:27:46 +02:00
setupMiddleware ( app , corsOptions , ISDEBUG ) ;
2024-08-29 23:30:58 +02:00
2025-05-19 17:33:58 +02:00
const server = await createHttpOrHttpsServer ( app , port , isProduction , domains ) ;
2025-03-04 20:20:26 +01:00
2025-05-15 14:27:46 +02:00
const wss = setupWebSocketServer ( server ) ;
return { server , wss } ;
} catch ( error ) {
console . error ( 'Errore in startServer:' , error ) ;
2025-03-04 20:20:26 +01:00
}
2024-09-06 19:57:09 +02:00
}
2025-03-04 20:20:26 +01:00
} )
2025-05-08 23:32:19 +02:00
. catch ( ( err ) => {
console . error ( 'Impossibile connettersi al database dopo diversi tentativi:' , err ) ;
2025-03-04 20:20:26 +01:00
process . exit ( 1 ) ; // Termina il processo se non riesce a connettersi
} ) ;
2025-09-22 19:09:02 +02:00
function add _numbers ( a , b ) { }
2025-09-05 01:06:46 +02:00
2023-02-15 21:40:19 +01:00
module . exports = { app } ;