411 lines
11 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.
*/
2022-01-04 19:21:05 +01:00
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const fs = require('fs');
const fse = require('fs-extra');
const _ = require('lodash');
const {
sanitize,
nameToSlug,
contentTypes: contentTypesUtils,
webhook: webhookUtils,
2021-04-29 13:51:12 +02:00
} = require('@strapi/utils');
2022-01-04 19:21:05 +01:00
const { NotFoundError } = require('@strapi/utils').errors;
const { MEDIA_UPDATE, MEDIA_CREATE, MEDIA_DELETE } = webhookUtils.webhookEvents;
2021-08-19 22:27:00 +02:00
const { getService } = require('../utils');
const { bytesToKbytes } = require('../utils/file');
const { UPDATED_BY_ATTRIBUTE, CREATED_BY_ATTRIBUTE } = contentTypesUtils.constants;
const randomSuffix = () => crypto.randomBytes(5).toString('hex');
const generateFileName = name => {
const baseName = nameToSlug(name, { separator: '_', lowercase: false });
return `${baseName}_${randomSuffix()}`;
};
const sendMediaMetrics = data => {
if (_.has(data, 'caption') && !_.isEmpty(data.caption)) {
strapi.telemetry.send('didSaveMediaWithCaption');
}
if (_.has(data, 'alternativeText') && !_.isEmpty(data.alternativeText)) {
strapi.telemetry.send('didSaveMediaWithAlternativeText');
}
};
2022-03-01 14:52:31 +01:00
const createAndAssignTmpWorkingDirectoryToFiles = async files => {
const tmpWorkingDirectory = await fse.mkdtemp(path.join(os.tmpdir(), 'strapi-upload-'));
Array.isArray(files)
? files.forEach(file => (file.tmpWorkingDirectory = tmpWorkingDirectory))
: (files.tmpWorkingDirectory = tmpWorkingDirectory);
return tmpWorkingDirectory;
};
2021-07-08 11:20:13 +02:00
module.exports = ({ strapi }) => ({
async emitEvent(event, data) {
2021-09-07 21:29:34 +02:00
const modelDef = strapi.getModel('plugin::upload.file');
2021-11-10 17:08:54 +01:00
const sanitizedData = await sanitize.sanitizers.defaultSanitizeOutput(modelDef, data);
strapi.eventHub.emit(event, { media: sanitizedData });
2021-07-08 18:15:32 +02:00
},
formatFileInfo({ filename, type, size }, fileInfo = {}, metas = {}) {
const ext = path.extname(filename);
const basename = path.basename(fileInfo.name || filename, ext);
const usedName = fileInfo.name || filename;
const entity = {
name: usedName,
alternativeText: fileInfo.alternativeText,
caption: fileInfo.caption,
hash: generateFileName(basename),
ext,
mime: type,
size: bytesToKbytes(size),
};
2021-07-28 21:03:32 +02:00
const { refId, ref, field } = metas;
if (refId && ref && field) {
entity.related = [
{
2021-07-28 21:03:32 +02:00
id: refId,
__type: ref,
__pivot: { field },
},
];
2018-02-19 14:26:20 +01:00
}
if (metas.path) {
entity.path = metas.path;
}
if (metas.tmpWorkingDirectory) {
entity.tmpWorkingDirectory = metas.tmpWorkingDirectory;
}
return entity;
},
async enhanceFile(file, fileInfo = {}, metas = {}) {
2022-01-04 19:21:05 +01:00
const currentFile = this.formatFileInfo(
{
filename: file.name,
type: file.type,
size: file.size,
},
fileInfo,
{
...metas,
tmpWorkingDirectory: file.tmpWorkingDirectory,
}
);
2022-01-04 19:21:05 +01:00
currentFile.getStream = () => fs.createReadStream(file.path);
2022-02-08 15:24:32 +01:00
const { optimize, isSupportedImage } = strapi.plugin('upload').service('image-manipulation');
2022-01-04 19:21:05 +01:00
2022-02-08 15:24:32 +01:00
if (!(await isSupportedImage(currentFile))) {
return currentFile;
}
return optimize(currentFile);
2018-02-19 14:26:20 +01:00
},
async upload({ data, files }, { user } = {}) {
2022-01-04 19:21:05 +01:00
// create temporary folder to store files for stream manipulation
2022-03-01 14:52:31 +01:00
const tmpWorkingDirectory = await createAndAssignTmpWorkingDirectoryToFiles(files);
2022-01-04 19:21:05 +01:00
let uploadedFiles = [];
2022-01-04 19:21:05 +01:00
try {
const { fileInfo, ...metas } = data;
2022-01-04 19:21:05 +01:00
const fileArray = Array.isArray(files) ? files : [files];
const fileInfoArray = Array.isArray(fileInfo) ? fileInfo : [fileInfo];
2018-03-07 14:18:15 +01:00
2022-01-04 19:21:05 +01:00
const doUpload = async (file, fileInfo) => {
const fileData = await this.enhanceFile(file, fileInfo, metas);
2022-01-04 19:21:05 +01:00
return this.uploadFileAndPersist(fileData, { user });
2022-01-04 19:21:05 +01:00
};
uploadedFiles = await Promise.all(
fileArray.map((file, idx) => doUpload(file, fileInfoArray[idx] || {}))
);
} finally {
// delete temporary folder
await fse.remove(tmpWorkingDirectory);
2022-01-04 19:21:05 +01:00
}
2022-01-04 19:21:05 +01:00
return uploadedFiles;
},
async uploadFileAndPersist(fileData, { user } = {}) {
2021-08-17 19:28:10 +02:00
const config = strapi.config.get('plugin.upload');
2022-02-08 15:24:32 +01:00
const {
getDimensions,
generateThumbnail,
generateResponsiveFormats,
isSupportedImage,
} = getService('image-manipulation');
2022-01-05 19:02:04 +01:00
await getService('provider').upload(fileData);
2022-02-08 15:24:32 +01:00
if (await isSupportedImage(fileData)) {
const thumbnailFile = await generateThumbnail(fileData);
2022-02-08 15:24:32 +01:00
if (thumbnailFile) {
await getService('provider').upload(thumbnailFile);
_.set(fileData, 'formats.thumbnail', thumbnailFile);
}
const formats = await generateResponsiveFormats(fileData);
2022-02-08 15:24:32 +01:00
if (Array.isArray(formats) && formats.length > 0) {
for (const format of formats) {
if (!format) continue;
2022-02-08 15:24:32 +01:00
const { key, file } = format;
2022-02-08 15:24:32 +01:00
await getService('provider').upload(file);
2022-02-08 15:24:32 +01:00
_.set(fileData, ['formats', key], file);
}
}
2022-02-08 15:24:32 +01:00
const { width, height } = await getDimensions(fileData);
2022-02-08 15:24:32 +01:00
_.assign(fileData, {
provider: config.provider,
width,
height,
});
}
return this.add(fileData, { user });
},
async updateFileInfo(id, { name, alternativeText, caption }, { user } = {}) {
2021-09-24 15:40:02 +02:00
const dbFile = await this.findOne(id);
if (!dbFile) {
2021-10-27 18:54:58 +02:00
throw new NotFoundError();
}
const newInfos = {
name: _.isNil(name) ? dbFile.name : name,
alternativeText: _.isNil(alternativeText) ? dbFile.alternativeText : alternativeText,
caption: _.isNil(caption) ? dbFile.caption : caption,
};
return this.update(id, newInfos, { user });
},
async replace(id, { data, file }, { user } = {}) {
2021-08-19 22:27:00 +02:00
const config = strapi.config.get('plugin.upload');
2021-08-19 22:27:00 +02:00
const { getDimensions, generateThumbnail, generateResponsiveFormats } = getService(
'image-manipulation'
);
2021-09-24 15:40:02 +02:00
const dbFile = await this.findOne(id);
if (!dbFile) {
2021-10-27 18:54:58 +02:00
throw new NotFoundError();
}
// create temporary folder to store files for stream manipulation
2022-03-01 14:52:31 +01:00
const tmpWorkingDirectory = await createAndAssignTmpWorkingDirectoryToFiles(file);
let fileData;
try {
const { fileInfo } = data;
fileData = await this.enhanceFile(file, fileInfo);
// keep a constant hash
_.assign(fileData, {
hash: dbFile.hash,
ext: dbFile.ext,
});
// execute delete function of the provider
if (dbFile.provider === config.provider) {
await strapi.plugin('upload').provider.delete(dbFile);
2022-02-08 15:24:32 +01:00
if (dbFile.formats) {
await Promise.all(
Object.keys(dbFile.formats).map(key => {
return strapi.plugin('upload').provider.delete(dbFile.formats[key]);
})
);
}
2022-02-08 15:24:32 +01:00
}
getService('provider').upload(fileData);
// clear old formats
_.set(fileData, 'formats', {});
const { isSupportedImage } = getService('image-manipulation');
if (await isSupportedImage(fileData)) {
const thumbnailFile = await generateThumbnail(fileData);
if (thumbnailFile) {
getService('provider').upload(thumbnailFile);
_.set(fileData, 'formats.thumbnail', thumbnailFile);
2022-02-08 15:24:32 +01:00
}
const formats = await generateResponsiveFormats(fileData);
if (Array.isArray(formats) && formats.length > 0) {
for (const format of formats) {
if (!format) continue;
const { key, file } = format;
getService('provider').upload(file);
_.set(fileData, ['formats', key], file);
}
}
const { width, height } = await getDimensions(fileData);
_.assign(fileData, {
provider: config.provider,
width,
height,
});
}
} finally {
// delete temporary folder
await fse.remove(tmpWorkingDirectory);
2022-02-08 15:24:32 +01:00
}
return this.update(id, fileData, { user });
},
async update(id, values, { user } = {}) {
const fileValues = { ...values };
if (user) {
fileValues[UPDATED_BY_ATTRIBUTE] = user.id;
}
sendMediaMetrics(fileValues);
const res = await strapi.entityService.update('plugin::upload.file', id, { data: fileValues });
2021-07-08 18:15:32 +02:00
await this.emitEvent(MEDIA_UPDATE, res);
2021-07-08 18:15:32 +02:00
return res;
},
async add(values, { user } = {}) {
const fileValues = { ...values };
if (user) {
fileValues[UPDATED_BY_ATTRIBUTE] = user.id;
fileValues[CREATED_BY_ATTRIBUTE] = user.id;
}
sendMediaMetrics(fileValues);
2021-08-06 18:09:49 +02:00
const res = await strapi.query('plugin::upload.file').create({ data: fileValues });
2021-07-08 18:15:32 +02:00
await this.emitEvent(MEDIA_CREATE, res);
2021-07-08 18:15:32 +02:00
return res;
},
2021-09-24 15:40:02 +02:00
findOne(id, populate) {
return strapi.entityService.findOne('plugin::upload.file', id, { populate });
},
2021-10-07 17:23:42 +02:00
findMany(query) {
2021-09-24 15:40:02 +02:00
return strapi.entityService.findMany('plugin::upload.file', query);
},
2021-10-07 17:23:42 +02:00
findPage(query) {
return strapi.entityService.findPage('plugin::upload.file', query);
},
async remove(file) {
2021-08-19 22:27:00 +02:00
const config = strapi.config.get('plugin.upload');
2018-02-21 17:18:33 +01:00
// execute delete function of the provider
if (file.provider === config.provider) {
2021-08-19 22:27:00 +02:00
await strapi.plugin('upload').provider.delete(file);
if (file.formats) {
await Promise.all(
Object.keys(file.formats).map(key => {
2021-08-19 22:27:00 +02:00
return strapi.plugin('upload').provider.delete(file.formats[key]);
})
);
}
2018-03-07 14:18:15 +01:00
}
2018-02-19 16:00:37 +01:00
2021-08-06 18:09:49 +02:00
const media = await strapi.query('plugin::upload.file').findOne({
2021-07-08 21:53:30 +02:00
where: { id: file.id },
2019-12-17 20:59:57 +01:00
});
await this.emitEvent(MEDIA_DELETE, media);
2019-12-17 20:59:57 +01:00
2021-08-06 18:09:49 +02:00
return strapi.query('plugin::upload.file').delete({ where: { id: file.id } });
},
2021-07-28 21:03:32 +02:00
async uploadToEntity(params, files) {
const { id, model, field } = params;
// create temporary folder to store files for stream manipulation
2022-03-01 14:52:31 +01:00
const tmpWorkingDirectory = await createAndAssignTmpWorkingDirectoryToFiles(files);
const arr = Array.isArray(files) ? files : [files];
try {
const enhancedFiles = await Promise.all(
arr.map(file => {
return this.enhanceFile(
file,
{},
{
refId: id,
ref: model,
field,
}
);
})
);
await Promise.all(enhancedFiles.map(file => this.uploadFileAndPersist(file)));
} finally {
// delete temporary folder
await fse.remove(tmpWorkingDirectory);
}
},
getSettings() {
return strapi.store({ type: 'plugin', name: 'upload', key: 'settings' }).get();
},
setSettings(value) {
if (value.responsiveDimensions === true) {
strapi.telemetry.send('didEnableResponsiveDimensions');
} else {
strapi.telemetry.send('didDisableResponsiveDimensions');
}
return strapi.store({ type: 'plugin', name: 'upload', key: 'settings' }).set({ value });
},
2021-07-08 11:20:13 +02:00
});