2020-07-13 09:58:31 +00:00
|
|
|
const https = require('https');
|
|
|
|
const fs = require('fs-extra');
|
|
|
|
const path = require('path');
|
|
|
|
|
|
|
|
module.exports = Self => {
|
|
|
|
Self.remoteMethod('download', {
|
|
|
|
description: 'Returns last entries',
|
|
|
|
accessType: 'WRITE',
|
|
|
|
returns: {
|
|
|
|
type: 'Boolean',
|
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/download`,
|
|
|
|
verb: 'GET'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.download = async() => {
|
|
|
|
const models = Self.app.models;
|
|
|
|
|
|
|
|
try {
|
|
|
|
const imageQueue = await Self.find({
|
|
|
|
limit: 2
|
|
|
|
});
|
|
|
|
|
|
|
|
// const rootPath = 'C:\\Users\\jsanc\\Desktop\\images';
|
2020-07-13 10:23:47 +00:00
|
|
|
const rootPath = '/var/lib/salix/image';
|
2020-07-13 09:58:31 +00:00
|
|
|
const tempPath = path.join(rootPath, 'temp');
|
|
|
|
|
|
|
|
// Create temporary path
|
|
|
|
await fs.mkdir(tempPath);
|
|
|
|
|
|
|
|
for (let image of imageQueue) {
|
|
|
|
const fileName = `${image.itemFk}.jpg`;
|
|
|
|
const filePath = path.join(tempPath, fileName);
|
|
|
|
|
|
|
|
https.get(image.url, async response => {
|
|
|
|
// Upload file to temporary path
|
|
|
|
const file = fs.createWriteStream(filePath);
|
|
|
|
response.pipe(file);
|
|
|
|
|
|
|
|
await models.Image.register('catalog', fileName, filePath);
|
|
|
|
// await image.destroy();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
} catch (e) {
|
|
|
|
fs.unlink(filePath);
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
};
|