gancio-upstream/server/api/storage.js

65 lines
1.6 KiB
JavaScript
Raw Normal View History

2019-04-03 00:25:12 +02:00
const fs = require('fs')
const path = require('path')
const crypto = require('crypto')
const mkdirp = require('mkdirp')
const sharp = require('sharp')
2021-03-05 14:17:10 +01:00
const log = require('../log')
2021-09-27 10:42:17 +02:00
const config = require('../config')
2019-04-03 00:25:12 +02:00
2019-07-03 16:58:24 +02:00
try {
mkdirp.sync(config.upload_path + '/thumb')
2021-07-08 20:41:56 +02:00
} catch (e) {}
2019-04-03 00:25:12 +02:00
const DiskStorage = {
2019-09-11 19:12:24 +02:00
_handleFile (req, file, cb) {
2020-07-08 23:02:08 +02:00
const filename = crypto.randomBytes(16).toString('hex') + '.jpg'
const finalPath = path.resolve(config.upload_path, filename)
const thumbPath = path.resolve(config.upload_path, 'thumb', filename)
2019-04-03 00:25:12 +02:00
const outStream = fs.createWriteStream(finalPath)
const thumbStream = fs.createWriteStream(thumbPath)
2021-03-11 12:28:50 +01:00
const resizer = sharp().resize(1200).jpeg({ quality: 98 })
2022-01-24 14:12:59 +01:00
const thumbnailer = sharp().resize(500).jpeg({ quality: 98 })
let onError = false
const err = e => {
if (onError) {
2021-07-08 20:41:56 +02:00
log.error('[UPLOAD]', err)
return
}
onError = true
2021-07-08 20:41:56 +02:00
log.error('[UPLOAD]', e)
req.err = e
cb(null)
}
file.stream
.pipe(thumbnailer)
.on('error', err)
.pipe(thumbStream)
.on('error', err)
file.stream
.pipe(resizer)
.on('error', err)
.pipe(outStream)
.on('error', err)
2019-04-03 00:25:12 +02:00
outStream.on('finish', () => {
2019-04-03 00:25:12 +02:00
cb(null, {
destination: config.upload_path,
2019-04-03 00:25:12 +02:00
filename,
path: finalPath,
size: outStream.bytesWritten
})
})
},
2019-09-11 19:12:24 +02:00
_removeFile (req, file, cb) {
delete file.destination
delete file.filename
fs.unlink(file.path, cb)
delete file.path
}
2019-04-03 00:25:12 +02:00
}
module.exports = DiskStorage