generated from NodeBB/nodebb-plugin-quickstart
-
Notifications
You must be signed in to change notification settings - Fork 0
/
library.js
86 lines (70 loc) · 2.19 KB
/
library.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
'use strict';
const nconf = require.main.require('nconf');
const winston = require.main.require('winston');
const controllers = require('./lib/controllers');
const fs = require('fs');
const os = require('os');
const node_image = require.main.require('./src/image');
const uploadsController = require.main.require('./src/controllers/uploads.js');
const routeHelpers = require.main.require('./src/routes/helpers');
const settings = require.main.require('./src/meta/settings');
const plugin = {};
let plugin_settings = {};
function requireSharp() {
const sharp = require('sharp');
if (os.platform() === 'win32') {
// https://github.com/lovell/sharp/issues/1259
sharp.cache(false);
}
return sharp;
}
plugin.init = async (params) => {
const {
router,
middleware/* , controllers */
} = params;
routeHelpers.setupAdminPageRoute(router, '/admin/plugins/always-webp', middleware, [], controllers.renderAdminPage);
plugin_settings = await settings.get('always-webp');
if (!plugin_settings.hasOwnProperty('quality')) {
plugin_settings['quality'] = 80;
settings.set('always-webp', plugin_settings);
}
plugin_settings['quality'] = Number(plugin_settings['quality']);
};
plugin.addAdminNavigation = (header) => {
header.plugins.push({
route: '/plugins/always-webp',
icon: 'fa-tint',
name: 'AlwaysWebp',
});
return header;
};
plugin.uploadImgHook = async function (data) {
let {
image,
uid,
folder
} = data;
await node_image.isFileTypeAllowed(image.path);
// sharp can't save svgs skip resize for them
const isSVG = image.type === 'image/svg+xml';
if (isSVG) {
return await uploadsController.uploadFile(uid, image);
}
const sharp = requireSharp();
const buffer = await fs.promises.readFile(image.path);
const sharpImage = sharp(buffer, {
failOnError: true,
animated: image.path.endsWith('gif'),
});
sharpImage.rotate(); // auto-orients based on exif data
sharpImage.webp({ quality: plugin_settings.quality });
await sharpImage.toFile(image.path);
let fileObj = await uploadsController.uploadFile(uid, image);
return {
url: fileObj.url,
path: fileObj.path,
name: fileObj.name,
};
};
module.exports = plugin;