salix/back/methods/image/download.js

93 lines
2.8 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');
2020-12-18 16:23:04 +00:00
const path = require('path');
2020-11-10 07:39:34 +00:00
module.exports = Self => {
2020-11-27 12:10:39 +00:00
Self.remoteMethodCtx('download', {
2020-11-10 07:39:34 +00:00
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'
}
});
2020-11-27 12:10:39 +00:00
Self.download = async function(ctx, collection, size, id) {
2020-11-11 09:52:35 +00:00
const models = Self.app.models;
2020-11-27 12:10:39 +00:00
const filter = {where: {name: collection}};
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]
});
2021-02-03 11:43:30 +00:00
if (!entity) return false;
2020-11-11 09:52:35 +00:00
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
2023-04-28 07:35:15 +00:00
const hasReadRole = await models.ImageCollection.hasReadRole(ctx, collection);
2020-11-27 12:10:39 +00:00
if (!hasReadRole)
2020-11-10 07:39:34 +00:00
throw new UserError(`You don't have enough privileges`);
2020-11-27 12:10:39 +00:00
const container = await models.ImageContainer.getContainer(collection);
const rootPath = container.client.root;
2020-12-18 16:23:04 +00:00
const fileSrc = path.join(rootPath, collection, size);
const ext = image.name.substring((image.name.length - 4));
const fileName = ext !== '.png' ? `${image.name}.png` : image.name;
2020-11-27 12:10:39 +00:00
const file = {
path: `${fileSrc}/${fileName}`,
2020-11-27 12:10:39 +00:00
contentType: 'image/png',
name: image.name
2020-11-27 12:10:39 +00:00
};
if (!fs.existsSync(file.path)) return [];
2020-11-10 07:39:34 +00:00
await fs.access(file.path);
2020-11-27 12:10:39 +00:00
const stream = fs.createReadStream(file.path);
return [stream, file.contentType, `filename="${fileName}"`];
2020-11-10 07:39:34 +00:00
};
};