salix/back/methods/image/download.js

97 lines
2.9 KiB
JavaScript
Raw Normal View History

2020-11-10 07:39:34 +00:00
const UserError = require('vn-loopback/util/user-error');
const fs = require('fs-extra');
module.exports = Self => {
Self.remoteMethod('download', {
description: 'Get the user image',
accessType: 'READ',
accepts: [
{
arg: 'collection',
type: 'String',
description: 'The image collection',
http: {source: 'path'}
},
{
arg: 'size',
type: 'String',
description: 'The image size',
http: {source: 'path'}
},
{
arg: 'id',
type: 'Number',
description: 'The user id',
http: {source: 'path'}
}
],
returns: [
{
arg: 'body',
type: 'file',
root: true
},
{
arg: 'Content-Type',
type: 'String',
http: {target: 'header'}
},
{
arg: 'Content-Disposition',
type: 'String',
http: {target: 'header'}
}
],
http: {
path: `/:collection/:size/:id/download`,
verb: 'GET'
}
});
Self.download = async function(collection, size, id) {
2020-11-11 09:52:35 +00:00
const models = Self.app.models;
2020-11-10 07:39:34 +00:00
const filter = {
where: {
2020-11-11 09:52:35 +00:00
name: collection},
2020-11-10 07:39:34 +00:00
include: {
2020-11-11 09:52:35 +00:00
relation: 'readRole'
2020-11-10 07:39:34 +00:00
}
};
2020-11-11 09:52:35 +00:00
const imageCollection = await models.ImageCollection.findOne(filter);
const entity = await models[imageCollection.model].findById(id, {
fields: ['id', imageCollection.property]
});
const image = await models.Image.findOne({where: {
collectionFk: collection,
name: entity[imageCollection.property]}
});
2020-11-10 10:33:01 +00:00
if (!image) return false;
2020-11-10 07:39:34 +00:00
2020-11-11 09:52:35 +00:00
const imageRole = imageCollection.readRole().name;
const hasRole = await models.Account.hasRole(id, imageRole);
2020-11-10 07:39:34 +00:00
if (!hasRole)
throw new UserError(`You don't have enough privileges`);
let file;
let env = process.env.NODE_ENV;
if (env && env != 'development') {
file = {
2020-11-11 09:52:35 +00:00
path: `/var/lib/salix/image/${collection}/${size}/${image.name}.png`,
2020-11-10 07:39:34 +00:00
contentType: 'image/png',
2020-11-11 09:52:35 +00:00
name: `${image.name}.png`
2020-11-10 07:39:34 +00:00
};
} else {
file = {
2020-11-11 09:52:35 +00:00
path: `${process.cwd()}/storage/image/${collection}/${size}/${image.name}.png`,
2020-11-10 07:39:34 +00:00
contentType: 'image/png',
2020-11-11 09:52:35 +00:00
name: `${image.name}.png`
2020-11-10 07:39:34 +00:00
};
}
await fs.access(file.path);
let stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${file.name}"`];
};
};