173 lines
4.3 KiB
JavaScript
Raw Normal View History

'use strict';
/**
* Upload.js service
*
* @description: A set of functions similar to controller's actions to avoid code duplication.
*/
2018-02-19 14:26:20 +01:00
const fs = require('fs');
const crypto = require('crypto');
2018-04-30 18:00:01 +02:00
const _ = require('lodash');
2018-02-19 14:26:20 +01:00
const toArray = require('stream-to-array');
const uuid = require('uuid/v4');
function niceHash(buffer) {
return crypto
.createHash('sha256')
.update(buffer)
.digest('base64')
.replace(/=/g, '')
.replace(/\//g, '-')
.replace(/\+/, '_');
}
module.exports = {
bufferize: async files => {
if (_.isEmpty(files) === 0) {
2018-02-19 14:26:20 +01:00
throw 'Missing files.';
}
2018-02-21 17:18:33 +01:00
// files is always an array to map on
files = _.isArray(files) ? files : [files];
2018-02-19 14:26:20 +01:00
2018-02-21 17:18:33 +01:00
// transform all files in buffer
2018-02-19 14:26:20 +01:00
return Promise.all(
files.map(async stream => {
const parts = await toArray(fs.createReadStream(stream.path));
const buffers = parts.map(part =>
_.isBuffer(part) ? part : Buffer.from(part)
2018-02-19 14:26:20 +01:00
);
const buffer = Buffer.concat(buffers);
2018-02-19 14:26:20 +01:00
return {
tmpPath: stream.path,
name: stream.name,
sha256: niceHash(buffer),
hash: uuid().replace(/-/g, ''),
ext:
stream.name.split('.').length > 1
? `.${_.last(stream.name.split('.'))}`
: '',
buffer,
mime: stream.type,
size: (stream.size / 1000).toFixed(2),
2018-02-19 14:26:20 +01:00
};
})
2018-02-19 14:26:20 +01:00
);
},
async upload(files, config) {
2018-02-27 16:53:06 +01:00
// Get upload provider settings to configure the provider to use.
const provider = _.find(strapi.plugins.upload.config.providers, {
provider: config.provider,
});
2018-03-06 15:49:11 +01:00
if (!provider) {
throw new Error(
`The provider package isn't installed. Please run \`npm install strapi-provider-upload-${config.provider}\``
);
2018-03-06 15:49:11 +01:00
}
2018-02-27 16:53:06 +01:00
const actions = provider.init(config);
2018-02-20 17:10:25 +01:00
2018-02-27 16:53:06 +01:00
// Execute upload function of the provider for all files.
2018-02-19 14:26:20 +01:00
return Promise.all(
files.map(async file => {
2018-02-20 17:10:25 +01:00
await actions.upload(file);
2018-02-27 16:53:06 +01:00
// Remove buffer to don't save it.
delete file.buffer;
2018-03-07 14:18:15 +01:00
file.provider = provider.provider;
const res = await strapi.plugins['upload'].services.upload.add(file);
// Remove temp file
fs.unlinkSync(file.tmpPath);
return res;
})
2018-02-19 14:26:20 +01:00
);
},
add(values) {
return strapi.query('file', 'upload').create(values);
},
fetch(params) {
return strapi.query('file', 'upload').findOne({
id: params._id || params.id,
});
},
fetchAll(params) {
return strapi.query('file', 'upload').find(params);
},
async count(params) {
return strapi.query('file', 'upload').count(params);
2018-02-19 19:54:45 +01:00
},
async remove(file, config) {
2018-02-21 17:18:33 +01:00
// get upload provider settings to configure the provider to use
const provider = _.cloneDeep(
_.find(strapi.plugins.upload.config.providers, {
provider: config.provider,
})
);
2018-02-20 17:10:25 +01:00
_.assign(provider, config);
2018-03-07 14:18:15 +01:00
const actions = provider.init(config);
2018-02-20 17:10:25 +01:00
2018-02-21 17:18:33 +01:00
// execute delete function of the provider
2018-03-07 14:18:15 +01:00
if (file.provider === provider.provider) {
await actions.delete(file);
}
2018-02-19 16:00:37 +01:00
return strapi.query('file', 'upload').delete({ id: file.id });
},
async uploadToEntity(params, files, source) {
// Retrieve provider settings from database.
const config = await strapi
.store({
environment: strapi.config.environment,
type: 'plugin',
name: 'upload',
})
.get({ key: 'provider' });
const model =
source && source !== 'content-manager'
? strapi.plugins[source].models[params.model]
: strapi.models[params.model];
// Asynchronous upload.
await Promise.all(
Object.keys(files).map(async attribute => {
// Bufferize files per attribute.
const buffers = await this.bufferize(files[attribute]);
const enhancedFiles = buffers.map(file => {
const details = model.attributes[attribute];
// Add related information to be able to make
// the relationships later.
file[details.via] = [
{
refId: params.id,
ref: params.model,
source,
field: attribute,
},
];
return file;
});
// Make upload async.
return this.upload(enhancedFiles, config);
})
);
},
};