76 lines
2.0 KiB
JavaScript
76 lines
2.0 KiB
JavaScript
'use strict';
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const checkDiskSpace = require('check-disk-space').default;
|
|
const { AppError } = require('./errors');
|
|
|
|
const UPLOADS_DIR = () => path.resolve(process.env.UPLOADS_DIR || path.join(__dirname, '..', 'uploads'));
|
|
const WARN_BYTES = () => parseInt(process.env.STORAGE_WARN_BYTES || String(5 * 1024 ** 3), 10);
|
|
|
|
let cache = null;
|
|
let cacheTime = 0;
|
|
let inflightPromise = null;
|
|
|
|
async function getUploadsSize() {
|
|
const dir = UPLOADS_DIR();
|
|
let total = 0;
|
|
let count = 0;
|
|
try {
|
|
const files = fs.readdirSync(dir);
|
|
for (const f of files) {
|
|
try {
|
|
const stat = fs.statSync(path.join(dir, f));
|
|
if (stat.isFile()) { total += stat.size; count++; }
|
|
} catch {}
|
|
}
|
|
} catch {}
|
|
return { size: total, fileCount: count };
|
|
}
|
|
|
|
async function getStorageInfo() {
|
|
if (cache && Date.now() - cacheTime < 60_000) return cache;
|
|
if (inflightPromise) return inflightPromise;
|
|
|
|
inflightPromise = (async () => {
|
|
const dir = UPLOADS_DIR();
|
|
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
|
|
const [disk, uploads] = await Promise.all([
|
|
checkDiskSpace(dir),
|
|
getUploadsSize(),
|
|
]);
|
|
|
|
const result = {
|
|
disk: {
|
|
total: disk.size,
|
|
used: disk.size - disk.free,
|
|
free: disk.free,
|
|
usedPercent: Math.round(((disk.size - disk.free) / disk.size) * 100),
|
|
},
|
|
uploads,
|
|
warning: disk.free < WARN_BYTES(),
|
|
warnThresholdBytes: WARN_BYTES(),
|
|
};
|
|
|
|
cache = result;
|
|
cacheTime = Date.now();
|
|
return result;
|
|
})().finally(() => { inflightPromise = null; });
|
|
|
|
return inflightPromise;
|
|
}
|
|
|
|
async function checkUploadAllowed(req, res, next) {
|
|
try {
|
|
const info = await getStorageInfo();
|
|
if (info.warning) {
|
|
return next(new AppError('STORAGE_INSUFFICIENT', 'Not enough disk space to upload. Contact your administrator.', 507));
|
|
}
|
|
next();
|
|
} catch (err) {
|
|
next(err);
|
|
}
|
|
}
|
|
|
|
module.exports = { getStorageInfo, checkUploadAllowed };
|