2
0
mirror of https://github.com/frappe/books.git synced 2024-12-27 20:45:04 +00:00
books/server/utils.js

91 lines
3.0 KiB
JavaScript
Raw Normal View History

2018-03-30 16:57:25 +00:00
const mkdirp = require('mkdirp');
const fs = require('fs');
2018-09-30 14:08:44 +00:00
const path = require('path');
const getDirName = path.dirname;
const os = require('os');
2018-09-29 11:35:41 +00:00
const sharp = require('sharp');
2018-03-30 16:57:25 +00:00
module.exports = {
writeFile(fullpath, contents) {
return new Promise((resolve, reject) => {
mkdirp(getDirName(fullpath), (err) => {
if (err) reject(err);
fs.writeFile(fullpath, contents, (err) => {
if (err) reject(err);
resolve();
});
});
});
},
2018-07-14 16:31:14 +00:00
readFile(filepath) {
2018-09-30 14:08:44 +00:00
return fs.readFileSync(filepath, 'utf-8');
2018-07-14 16:31:14 +00:00
},
getTmpDir() {
return os.tmpdir();
2018-09-29 11:35:41 +00:00
},
2018-09-30 14:08:44 +00:00
2018-09-29 11:35:41 +00:00
thumbnailMiddleware(staticPath) {
2018-09-30 14:08:44 +00:00
return function (req, res, next) {
2018-09-29 11:35:41 +00:00
2018-09-30 14:08:44 +00:00
const filename = req.path.split(path.sep).slice(-1)[0]
const dimension = req.query.size || null
const staticFile = path.join(staticPath, filename)
2018-09-29 11:35:41 +00:00
fs.exists(staticFile, (exists) => {
2018-09-30 14:08:44 +00:00
if (!exists) {
2018-09-29 11:35:41 +00:00
return next()
}
fs.stat(staticFile, (err, stats) => {
2018-09-30 14:08:44 +00:00
if (err) {
2018-09-29 11:35:41 +00:00
throw err
}
//Check if url is static file
2018-09-30 14:08:44 +00:00
if (stats.isFile()) {
// Check if url has dimension parameters
if (dimension) {
let [width, height] = dimension.split('x');
width = +width;
height = +height;
const thumbnailPath = path.join(staticPath, 'thumbnails');
const destination = path.join(thumbnailPath, `${width}x${height}-${filename}`)
// create thumbnails folder if not exists
if (!fs.existsSync(thumbnailPath)) {
fs.mkdirSync(thumbnailPath);
}
2018-09-29 11:35:41 +00:00
2018-09-30 14:08:44 +00:00
// Check if thumbnail already present
2018-09-29 11:35:41 +00:00
fs.existsSync(destination, (exists) => {
2018-09-30 14:08:44 +00:00
if (exists)
2018-09-29 11:35:41 +00:00
return res.sendFile(destination)
})
2018-09-30 14:08:44 +00:00
// Resize image
2018-09-29 11:35:41 +00:00
sharp(staticFile)
.resize(width, height)
.toFile(destination)
.then(() => {
return res.sendFile(destination)
})
.catch(err => {
console.error(err)
})
} else {
return res.sendFile(staticFile)
}
} else {
2018-09-30 14:08:44 +00:00
// File is not static
2018-09-29 11:35:41 +00:00
return next()
}
})
})
}
2018-03-30 16:57:25 +00:00
}
}