90 lines
3.0 KiB
JavaScript
90 lines
3.0 KiB
JavaScript
const https = require('https');
|
|
const fs = require('fs-extra');
|
|
const path = require('path');
|
|
|
|
module.exports = Self => {
|
|
Self.remoteMethod('downloadImages', {
|
|
description: 'Returns last entries',
|
|
accessType: 'WRITE',
|
|
returns: {
|
|
type: ['Object'],
|
|
root: true
|
|
},
|
|
http: {
|
|
path: `/downloadImages`,
|
|
verb: 'POST'
|
|
}
|
|
});
|
|
|
|
Self.downloadImages = async() => {
|
|
const models = Self.app.models;
|
|
|
|
try {
|
|
const tempPath = path.join('/tmp/salix-image');
|
|
|
|
// Create temporary path
|
|
await fs.mkdir(tempPath, {recursive: true});
|
|
|
|
const timer = setInterval(async() => {
|
|
const image = await Self.findOne({
|
|
where: {error: null, url: {neq: null}}
|
|
});
|
|
|
|
// Exit loop
|
|
if (!image) return clearInterval(timer);
|
|
|
|
const srcFile = image.url.split('/').pop();
|
|
const fileName = srcFile.split('.')[0];
|
|
const file = `${fileName}.png`;
|
|
const filePath = path.join(tempPath, file);
|
|
|
|
const writeStream = fs.createWriteStream(filePath);
|
|
writeStream.on('open', () => {
|
|
https.get(image.url, async response => {
|
|
if (response.statusCode != 200) {
|
|
const error = new Error(`Could not download the image. Status code ${response.statusCode}`);
|
|
|
|
return await errorHandler(image.itemFk, error, filePath);
|
|
}
|
|
|
|
response.pipe(writeStream);
|
|
}).on('error', async error => {
|
|
await errorHandler(image.itemFk, error, filePath);
|
|
});
|
|
});
|
|
|
|
writeStream.on('error', async error => {
|
|
await errorHandler(image.itemFk, error, filePath);
|
|
});
|
|
|
|
writeStream.on('finish', async function() {
|
|
try {
|
|
await models.Image.registerImage('catalog', filePath, fileName, image.itemFk);
|
|
await image.destroy();
|
|
} catch (error) {
|
|
await errorHandler(image.itemFk, error, filePath);
|
|
}
|
|
});
|
|
}, 1000);
|
|
} catch (error) {
|
|
throw new Error('Try-catch error: ', error);
|
|
}
|
|
|
|
async function errorHandler(rowId, error, filePath) {
|
|
try {
|
|
const row = await Self.findById(rowId);
|
|
|
|
if (!row)
|
|
throw new Error(`Could not update due error ${error}`);
|
|
|
|
await row.updateAttribute('error', error);
|
|
|
|
if (filePath && fs.existsSync(filePath))
|
|
await fs.unlink(filePath);
|
|
} catch (err) {
|
|
throw new Error(`ErrorHandler error: ${err}`);
|
|
}
|
|
}
|
|
};
|
|
};
|