2
0
mirror of https://github.com/frappe/books.git synced 2024-12-23 11:29:03 +00:00

Thumbnail creation using Sharp

This commit is contained in:
Saqib Ansari 2018-09-29 17:05:41 +05:30
parent 96292f92c0
commit 7f3fb7713a
3 changed files with 61 additions and 5 deletions

View File

@ -33,7 +33,6 @@
"frappe-datatable": "^1.3.1",
"friendly-errors-webpack-plugin": "^1.7.0",
"html-webpack-plugin": "^3.2.0",
"imagemagick": "^0.1.3",
"jquery": "^3.3.1",
"jwt-simple": "^0.5.1",
"luxon": "^1.0.0",
@ -48,8 +47,8 @@
"passport": "^0.4.0",
"passport-jwt": "^4.0.0",
"puppeteer": "^1.2.0",
"quickthumb": "^0.0.12",
"sass-loader": "^7.0.3",
"sharp": "^0.20.8",
"showdown": "^1.8.6",
"socket.io": "^2.0.4",
"sqlite3": "^3.1.13",

View File

@ -17,8 +17,8 @@ const { setupExpressRoute: setRouteForPDF } = require('frappejs/server/pdf');
const auth = require('./../auth/auth')();
const morgan = require('morgan');
const { addWebpackMiddleware } = require('../webpack/serve');
const { getAppConfig } = require('../webpack/utils');
const quickthumb = require('quickthumb')
const { getAppConfig, resolveAppDir } = require('../webpack/utils');
const { thumbnailMiddleware } = require('./utils');
frappe.conf = getAppConfig();
@ -42,7 +42,7 @@ module.exports = {
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(frappe.conf.distPath));
app.use('/static', quickthumb.static(path.resolve(frappe.conf.staticPath), { type: 'resize' }));
app.use('/static', thumbnailMiddleware(resolveAppDir(frappe.conf.staticPath)));
app.use(morgan('tiny'));

View File

@ -2,6 +2,7 @@ const mkdirp = require('mkdirp');
const fs = require('fs');
const getDirName = require('path').dirname;
const os = require('os');
const sharp = require('sharp');
module.exports = {
writeFile(fullpath, contents) {
@ -22,5 +23,61 @@ module.exports = {
getTmpDir() {
return os.tmpdir();
},
thumbnailMiddleware(staticPath) {
return function(req, res, next){
const file = (req.url).toString().replace(/\?.*/, "");
const dimension = req.query.size || ""
const staticFile = staticPath + file
fs.exists(staticFile, (exists) => {
if(!exists){
return next()
}
fs.stat(staticFile, (err, stats) => {
if(err){
throw err
}
//Check if url is static file
if(stats.isFile()){
//Check if url has dimension parameters
if(dimension != ""){
const width = parseInt(dimension.split('x')[0])
const height = parseInt(dimension.split('x')[1])
const destination = staticPath + '/.thumbnails/' + width + 'x' + height + file.replace('/', '')
//Check if thumbnail already present
fs.existsSync(destination, (exists) => {
if(exists)
return res.sendFile(destination)
})
//Resize image
sharp(staticFile)
.resize(width, height)
.toFile(destination)
.then(() => {
return res.sendFile(destination)
})
.catch(err => {
console.error(err)
})
} else {
return res.sendFile(staticFile)
}
} else {
console.log('File is not static.')
return next()
}
})
})
}
}
}