- Continuazione del Catalogo

This commit is contained in:
Surya Paolo
2024-10-26 17:11:52 +02:00
parent 2ac1bc4b7d
commit 5dac17d1d1
8 changed files with 133 additions and 30 deletions

BIN
.DS_Store vendored

Binary file not shown.

View File

@@ -1,12 +1,12 @@
DATABASE=test_FreePlanet DATABASE=test_PiuCheBuono
UDB=paofreeplanet UDB=paofreeplanet
PDB=mypassword@1A PDB=mypassword@1A
SEND_EMAIL=0 SEND_EMAIL=0
SEND_EMAIL_ORDERS=1 SEND_EMAIL_ORDERS=1
PORT=3000 PORT=3000
appTelegram_TEST=["1","13"] appTelegram_TEST=["1","17"]
appTelegram=["1","13"] appTelegram=["1","17"]
appTelegram_DEVELOP=["13"] appTelegram_DEVELOP=["17"]
DOMAIN=mongodb://localhost:27017/ DOMAIN=mongodb://localhost:27017/
AUTH_MONGODB=1 AUTH_MONGODB=1
MONGODB_USER=admin MONGODB_USER=admin
@@ -42,3 +42,6 @@ FTPSERVER_PWD=ftpmypwd@1A_
AUTH_NEW_SITES=123123123 AUTH_NEW_SITES=123123123
SCRIPTS_DIR=admin_scripts SCRIPTS_DIR=admin_scripts
CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}] CLOUDFLARE_TOKENS=[{"label":"Paolo.arena77@gmail.com","value":"M9EM309v8WFquJKpYgZCw-TViM2wX6vB3wlK6GD0"},{"label":"gruppomacro.com","value":"bqmzGShoX7WqOBzkXocoECyBkPq3GfqcM5t6VFd8"}]
MIAB_HOST=box.lamiaposta.org
MIAB_ADMIN_EMAIL=admin@lamiaposta.org
MIAB_ADMIN_PASSWORD=passpao1pabox@1A

Binary file not shown.

After

Width:  |  Height:  |  Size: 556 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.2 KiB

View File

@@ -53,6 +53,20 @@ const catalogo = new Schema(
excludeproductTypes: [{ type: Number }], excludeproductTypes: [{ type: Number }],
Editore: [{ type: String }], Editore: [{ type: String }],
pdf: { type: Boolean }, pdf: { type: Boolean },
printable: { type: Boolean },
backgroundimage: { type: String },
backgroundimage_printable: { type: String },
widthpag: { type: Number },
widthpagPrintable: { type: Number },
width: { type: String },
widthscheda: { type: String },
height: { type: String },
numschede_perRiga: { type: Number },
numschede_perCol: { type: Number },
margine_pagina: { type: String },
margine_riga: { type: String },
margine_paginaPrintable: { type: String },
margine_rigaPrintable: { type: String },
// formato: [{ type: String, default: '' }], // formato: [{ type: String, default: '' }],
// categoria: [{ type: String, default: '' }], // categoria: [{ type: String, default: '' }],
} }

View File

@@ -60,16 +60,46 @@ async function downloadImgIfMissing(productInfo) {
if (!productInfo.image_link) if (!productInfo.image_link)
return { prodInfo: null, aggiornatoimg: false }; return { prodInfo: null, aggiornatoimg: false };
const relativeimg = productInfo.image_link.split('/').pop();
const img = 'upload/products/' + productInfo.image_link.split('/').pop(); const img = 'upload/products/' + productInfo.image_link.split('/').pop();
const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine const savePath = path.resolve(__dirname, img); // Sostituisci con il percorso dove salvare l'immagine
if (!productInfo.imagefile || !fs.existsSync(savePath)) { let scaricaimg = !productInfo.imagefile || !fs.existsSync(savePath);
if (!productInfo.imagefile && fs.existsSync(savePath)) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size > 0) { // Controlla se la dimensione del file è maggiore di zero
// Esiste il file ed è non vuoto, ma sul DB non è corretto
productInfo.imagefile = relativeimg;
return { prodInfo: productInfo, aggiornatoimg: true };
} else {
scaricaimg = true;
}
}
if (productInfo.imagefile && fs.existsSync(savePath)) {
// esiste il file, ma sul DB non è corretto
const stats = fs.statSync(savePath); // Ottieni informazioni sul file
if (stats.size <= 0) { // Controlla se la dimensione del file è maggiore di zero
scaricaimg = true;
}
}
if (scaricaimg) {
// Download image from the URL productInfo.image_link // Download image from the URL productInfo.image_link
productInfo.imagefile = img; productInfo.imagefile = relativeimg;
const downloader = new ImageDownloader(); const downloader = new ImageDownloader();
const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath).then(result => { const aggiornatoimg = await downloader.downloadImage(productInfo.image_link, savePath,
{
maxRetries: 3,
initialDelay: 300,
timeout: 15000,
}).then(result => {
if (result) { if (result) {
// console.log('Download completato con successo!'); // console.log('Download completato con successo!');
} else { } else {
@@ -82,6 +112,7 @@ async function downloadImgIfMissing(productInfo) {
return { prodInfo: productInfo, aggiornatoimg }; return { prodInfo: productInfo, aggiornatoimg };
} }
return { prodInfo: null, aggiornatoimg: false }; return { prodInfo: null, aggiornatoimg: false };
} }

View File

@@ -423,44 +423,99 @@ class ImageDownloader {
* @param {number} delay - Ritardo in millisecondi tra i tentativi (default: 1000) * @param {number} delay - Ritardo in millisecondi tra i tentativi (default: 1000)
* @returns {Promise<boolean>} * @returns {Promise<boolean>}
*/ */
async downloadImage(url, filepath, maxRetries = 1, delay = 1000) { async downloadImage(url, filepath, options = {}) {
const {
maxRetries = 3, // Aumentato il numero di tentativi predefiniti
initialDelay = 1000, // Ritardo iniziale
maxDelay = 10000, // Ritardo massimo
timeout = 30000, // Timeout della richiesta
validateContentType = true // Verifica del tipo di contenuto
} = options;
// Funzione per il backoff esponenziale
const getDelay = (attempt) => {
return Math.min(initialDelay * Math.pow(2, attempt - 1), maxDelay);
};
for (let attempt = 1; attempt <= maxRetries; attempt++) { for (let attempt = 1; attempt <= maxRetries; attempt++) {
try { try {
const writer = fs.createWriteStream(filepath); // Verifica se il filepath esiste già
if (fs.existsSync(filepath)) {
fs.unlinkSync(filepath);
}
console.log('url da scaricare:', url); const writer = fs.createWriteStream(filepath);
if (attempt > 1)
console.log(`📥 Tentativo ${attempt}/${maxRetries} - Scaricamento: ${url}`);
const response = await axios({ const response = await axios({
url, url,
method: 'GET', method: 'GET',
responseType: 'stream', responseType: 'stream',
timeout: timeout,
maxRedirects: 5,
headers: { headers: {
'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' 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'image/jpeg,image/png,image/webp,image/gif,image/*', // Specifico per immagini
'Cache-Control': 'no-cache', // Evita problemi di caching
'Connection': 'keep-alive'
},
validateStatus: (status) => status === 200, // Per immagini ci aspettiamo 200
maxContentLength: 10 * 1024 * 1024 // Limite di 10MB per immagine
});
// Verifica del content-type se richiesto
if (validateContentType) {
const contentType = response.headers['content-type'];
if (!contentType || !contentType.startsWith('image/')) {
throw new Error(`Content-Type non valido: ${contentType}`);
} }
}
// Verifica della dimensione del file
const contentLength = parseInt(response.headers['content-length']);
if (contentLength && contentLength > 100 * 1024 * 1024) { // 100MB limit
throw new Error('File troppo grande');
}
let downloadedBytes = 0;
response.data.on('data', chunk => {
downloadedBytes += chunk.length;
}); });
response.data.pipe(writer); response.data.pipe(writer);
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
writer.on('finish', () => { writer.on('finish', resolve);
console.info('✅ Immagine scaricata ' + url + ' in ' + filepath); writer.on('error', error => {
resolve(true); fs.unlink(filepath, () => { }); // Pulizia in caso di errore
reject(error);
});
response.data.on('error', error => {
fs.unlink(filepath, () => { });
reject(error);
}); });
writer.on('error', reject);
}); });
console.info(`✅ Immagine scaricata con successo in ${filepath}`);
return true; return true;
} catch (error) { } catch (error) {
console.error(`Tentativo ${attempt} fallito per l'URL ${url}. Errore:`, error.message); console.error(`Errore nel tentativo ${attempt}/${maxRetries}:`, error.message);
// Pulizia del file in caso di errore
if (fs.existsSync(filepath)) {
fs.unlinkSync(filepath);
}
if (attempt === maxRetries) { if (attempt === maxRetries) {
console.error('❌ Tutti i tentativi sono falliti. Scaricamento interrotto.'); console.error(`Download fallito dopo ${maxRetries} tentativi: ${error.message}`);
return false; return false;
} else {
console.info(`🔁 Ritentando... (${attempt + 1} di ${maxRetries})`);
await sleep(delay);
} }
const delay = getDelay(attempt);
console.info(`🔄 Attendo ${delay}ms prima del prossimo tentativo...`);
await new Promise(resolve => setTimeout(resolve, delay));
} }
} }
} }