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: {
|
2020-07-13 12:13:21 +00:00
|
|
|
type: ['Object'],
|
2020-07-13 09:58:31 +00:00
|
|
|
root: true
|
|
|
|
},
|
|
|
|
http: {
|
|
|
|
path: `/download`,
|
|
|
|
verb: 'GET'
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
Self.download = async() => {
|
|
|
|
const models = Self.app.models;
|
|
|
|
|
2020-07-13 12:22:19 +00:00
|
|
|
let filePath;
|
2020-07-13 09:58:31 +00:00
|
|
|
try {
|
|
|
|
const imageQueue = await Self.find({
|
2020-07-13 12:13:21 +00:00
|
|
|
where: {
|
|
|
|
itemFk: 410421
|
|
|
|
}
|
2020-07-13 09:58:31 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
// 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) {
|
2020-07-13 12:13:21 +00:00
|
|
|
const fileName = `${image.itemFk}.png`;
|
2020-07-13 12:22:19 +00:00
|
|
|
filePath = path.join(tempPath, fileName);
|
2020-07-13 09:58:31 +00:00
|
|
|
|
|
|
|
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();
|
|
|
|
});
|
|
|
|
}
|
2020-07-13 12:22:19 +00:00
|
|
|
|
|
|
|
return imageQueue;
|
2020-07-13 09:58:31 +00:00
|
|
|
} catch (e) {
|
|
|
|
fs.unlink(filePath);
|
|
|
|
throw e;
|
|
|
|
}
|
|
|
|
};
|
|
|
|
};
|