-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
173 lines (150 loc) · 6.08 KB
/
app.js
File metadata and controls
173 lines (150 loc) · 6.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
const express = require('express');
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const https = require('https');
const cron = require('node-cron');
const app = express();
require('dotenv').config();
const UPLOAD_DIR = path.join(__dirname, 'uploads')
const SSL_DIR = path.join(__dirname, 'ssl')
const ALLOWED_EXTENSIONS = process.env.ALLOWED_EXTENSIONS ? process.env.ALLOWED_EXTENSIONS.split(',') : []
const MAIN_DOMAIN = process.env.DOMAIN
if (MAIN_DOMAIN === 'test.com') return console.log('Please change default domain name')
const fileExtensions = {
image: [
".jpeg", ".jpg", ".png", ".gif", ".bmp", ".tiff", ".tif", ".webp",
".svg", ".heic", ".cr2", ".crw", ".nef", ".nrw", ".arw", ".srf",
".sr2", ".dng", ".raf", ".orf", ".rw2", ".srw"
],
video: [
".mp4", ".mov", ".avi", ".mkv", ".wmv", ".flv", ".webm", ".mpeg",
".mpg", ".mpe", ".3gp", ".ogv", ".ogg"
],
audio: [
".mp3", ".wav", ".aac", ".flac", ".ogg", ".wma", ".m4a", ".alac",
".aiff", ".pcm", ".opus"
]
}
// Separate limits based on file type
const MAX_FILE_SIZE_IMAGE = parseInt(process.env.MAX_FILE_SIZE_IMAGE) || Infinity
const MAX_FILE_SIZE_AUDIO = parseInt(process.env.MAX_FILE_SIZE_AUDIO) || Infinity
const MAX_FILE_SIZE_VIDEO = parseInt(process.env.MAX_FILE_SIZE_VIDEO) || Infinity
const MAX_FILE_SIZE_DEFAULT = parseInt(process.env.MAX_FILE_SIZE_DEFAULT) || Infinity
// Ensure the upload directory exists
if (!fs.existsSync(UPLOAD_DIR)) {
fs.mkdirSync(UPLOAD_DIR, { recursive: true })
}
// Ensure the SSL folder exists, create if not
if (!fs.existsSync(SSL_DIR)) {
fs.mkdirSync(SSL_DIR, { recursive: true })
}
// Storage configuration for multer
const storage = multer.diskStorage({
destination: UPLOAD_DIR,
filename: (req, file, cb) => {
let fileName = file.originalname.replace(/[<>:"/\\|?*\x00-\x1F]/g, '_')
fileName = fileName.length > process.env.MAX_FILENAME_LENGTH ? fileName.substring(0, process.env.MAX_FILENAME_LENGTH) : fileName
const randomNumber = Math.floor(Math.random() * 10000)
const uniqueName = `${Date.now()}-${randomNumber}-${file.originalname}`
cb(null, uniqueName)
},
})
// File filter for validating extensions
const fileFilter = (req, file, cb) => {
if (ALLOWED_EXTENSIONS.length === 0) return cb(null, true) // No validation if empty
const ext = path.extname(file.originalname).toLowerCase()
if (ALLOWED_EXTENSIONS.includes(ext)) {
cb(null, true)
} else {
cb(new Error(`File type not allowed. Allowed types: ${ALLOWED_EXTENSIONS.join(', ')}`))
}
}
// Dynamic file size limit based on file extension
const getFileSizeLimit = (file) => {
const ext = path.extname(file.originalname).toLowerCase()
if (fileExtensions.image.includes(ext)) {
return MAX_FILE_SIZE_IMAGE
} else if (fileExtensions.video.includes(ext)) {
return MAX_FILE_SIZE_VIDEO
} else if (fileExtensions.audio.includes(ext)) {
return MAX_FILE_SIZE_AUDIO
} else {
return MAX_FILE_SIZE_DEFAULT
}
}
const upload = multer({
storage,
fileFilter,
limits: {
fileSize: (req, file, cb) => getFileSizeLimit(file),
}
})
// Middleware to parse JSON data
app.use(express.json())
// If the requst is not with main domain redirect it
app.use((req, res, next) => {
if (req.hostname !== MAIN_DOMAIN) {
const redirectUrl = `https://${MAIN_DOMAIN}:${process.env.PORT}${req.url}`
return res.redirect(301, redirectUrl)
}
next()
})
// Upload route
app.post('/upload', (req, res) => {
upload.single('files[]')(req, res, err => {
if (err) {
console.log(err)
const errorMsg = err.message || 'File upload failed'
return res.status(400).send(errorMsg)
}
const imageURL = `https://${req.headers.host}/uploads/${req.file.filename}`
res.status(200).json((process.env.DISCORD_SCHEMA == 'true') ? {
attachments: [
{
url: imageURL,
proxy_url: imageURL
}
]
} : imageURL)
})
})
// Serve uploaded files statically
app.use('/uploads', express.static(UPLOAD_DIR, {maxAge: (parseInt(process.env.CACHE_TIME) ?? 0) * 1000}))
// Schedule the cleanup job to run every day at midnight
if (process.env.EXPIRATION_DAYS > 0) {
cron.schedule('0 0 * * *', function() {
const now = Date.now()
const expirationTime = parseInt(process.env.EXPIRATION_DAYS) * 86_400_000 // Expiration in milliseconds
fs.readdir(UPLOAD_DIR, (err, files) => {
if (err) {
return console.error('Error reading upload directory:', err)
}
files.forEach(file => {
const filePath = path.join(UPLOAD_DIR, file)
fs.stat(filePath, (err, stats) => {
if (err) {
return console.error('Error getting file stats:', err)
}
if (now - stats.mtimeMs > expirationTime) {
fs.unlink(filePath, err => {
if (err) console.error('Error deleting file:', err)
else console.log('Deleted expired file:', file)
})
}
})
})
})
})
}
const sslOptions = {
key: fs.readFileSync(path.join(SSL_DIR, 'key.pem')),
cert: fs.readFileSync(path.join(SSL_DIR, 'cert.pem')),
ca: fs.existsSync(path.join(SSL_DIR, 'chain.pem')) ? fs.readFileSync(path.join(SSL_DIR, 'chain.pem')) : undefined, // Optional, if you have a CA chain
}
// Create HTTPS server and listen for requests only on the specified domain
https.createServer(sslOptions, app).listen(process.env.PORT, () => {
console.log(`Server is running securely at https://${MAIN_DOMAIN}:${process.env.PORT}`)
console.log(`Use https://${MAIN_DOMAIN}:${process.env.PORT}/upload for uploading files`)
console.log(`Use https://${MAIN_DOMAIN}:${process.env.PORT}/uploads/filename for serving files`)
})