|
fs = require 'fs' |
|
os = require 'os' |
|
bytes = require 'bytes' |
|
cors = require 'cors' |
|
express = require 'express' |
|
{ fromBuffer } = require 'file-type' |
|
multer = require 'multer' |
|
archiver = require 'archiver' |
|
|
|
limitSize = '5000mb' |
|
tmpFolder = os.tmpdir() |
|
|
|
app = express() |
|
app.set 'json spaces', 4 |
|
|
|
app.use cors() |
|
|
|
app.use express.json limit: limitSize |
|
app.use express.urlencoded extended: true, limit: limitSize |
|
|
|
|
|
upload = multer({ dest: tmpFolder }) |
|
|
|
|
|
app.use (req, res, next) -> |
|
time = new Date().toLocaleString 'id', timeZone: 'Asia/Jakarta' |
|
console.log "[#{time}] #{req.method}: #{req.url}" |
|
next() |
|
|
|
|
|
app.use '/file', express.static tmpFolder |
|
|
|
app.all '/', (_, res) -> |
|
res.send """ |
|
<!doctype html> |
|
<html> |
|
<head> |
|
<title>File Upload</title> |
|
</head> |
|
<body> |
|
<h1>Upload a file</h1> |
|
<form action="/upload" method="post" enctype="multipart/form-data"> |
|
<input type="file" name="file" /> |
|
<button type="submit">Upload</button> |
|
</form> |
|
</body> |
|
</html> |
|
""" |
|
|
|
app.post '/upload', upload.single('file'), (req, res) -> |
|
do -> |
|
return res.json(message: 'No file uploaded') unless req.file |
|
|
|
fileBuffer = fs.readFileSync req.file.path |
|
ftype = await fromBuffer fileBuffer |
|
ftype = { mime: 'file', ext: 'bin' } unless ftype |
|
|
|
randomName = Math.random().toString(36).slice(2) |
|
fileName = "#{ftype.mime.split('/')[0]}-#{randomName}.#{ftype.ext}" |
|
await fs.promises.rename req.file.path, "#{tmpFolder}/#{fileName}" |
|
res.json |
|
name: fileName |
|
size: |
|
bytes: fileBuffer.length |
|
readable: bytes(fileBuffer.length, unitSeparator: ' ') |
|
type: ftype |
|
url: "https://#{process.env.SPACE_HOST}/file/#{fileName}" |
|
|
|
|
|
app.get '/download-zip', (req, res) -> |
|
do -> |
|
archive = archiver 'zip', zlib: level: 9 |
|
|
|
res.attachment 'files.zip' |
|
|
|
archive.on 'error', (err) -> |
|
throw err |
|
|
|
archive.pipe res |
|
|
|
|
|
fs.readdir tmpFolder, (err, files) -> |
|
return res.status(500).send 'Could not list the directory.' if err |
|
|
|
files.forEach (file) -> |
|
filePath = "#{tmpFolder}/#{file}" |
|
archive.file filePath, name: file |
|
|
|
archive.finalize() |
|
|
|
app.listen 7860, -> console.log 'App running on port', 7860 |