-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
206 lines (174 loc) · 6.55 KB
/
Copy pathserver.js
File metadata and controls
206 lines (174 loc) · 6.55 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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
const express = require("express");
const fs = require("fs");
const path = require("path");
const app = express();
const PORT = 8000;
const ROOT_DIR = path.resolve(__dirname, "sharing");
/* ───────────── LOGGING ───────────── */
app.use((req, res, next) => {
res.on("finish", () => {
const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress;
const ua = req.headers["user-agent"] || "Unknown";
console.log(`(${ip})(${ua})(${req.method})(${req.path})(${res.statusCode})`);
});
next();
});
/* ───────────── FILE TYPES ───────────── */
function mediaType(file) {
const ext = path.extname(file).toLowerCase();
return {
image: [".png", ".jpg", ".jpeg", ".gif", ".webp"].includes(ext),
audio: [".mp3", ".wav", ".ogg"].includes(ext),
video: [".mp4", ".webm", ".mov"].includes(ext),
html: [".html", ".htm"].includes(ext),
text: [".txt", ".md", ".json", ".js", ".css"].includes(ext),
};
}
/* ───────────── MIME ───────────── */
function mimeType(file) {
const ext = path.extname(file).toLowerCase();
return {
".mp3": "audio/mpeg",
".wav": "audio/wav",
".ogg": "audio/ogg",
".mp4": "video/mp4",
".webm": "video/webm",
".mov": "video/quicktime",
".html": "text/html",
".htm": "text/html",
}[ext] || "application/octet-stream";
}
/* ───────────── RAW STREAM ───────────── */
app.get(/^\/raw\/(.+)/, (req, res) => {
const rel = "/" + req.params[0];
const abs = path.resolve(ROOT_DIR, "." + rel);
if (!abs.startsWith(ROOT_DIR) || !fs.existsSync(abs)) return res.sendStatus(404);
const stat = fs.statSync(abs);
const range = req.headers.range;
const type = mimeType(abs);
if (range) {
const [startStr, endStr] = range.replace("bytes=", "").split("-");
const start = parseInt(startStr, 10);
const end = endStr ? parseInt(endStr, 10) : stat.size - 1;
res.writeHead(206, {
"Content-Range": `bytes ${start}-${end}/${stat.size}`,
"Accept-Ranges": "bytes",
"Content-Length": end - start + 1,
"Content-Type": type,
});
return fs.createReadStream(abs, { start, end }).pipe(res);
}
res.writeHead(200, {
"Content-Length": stat.size,
"Accept-Ranges": "bytes",
"Content-Type": type,
});
fs.createReadStream(abs).pipe(res);
});
/* ───────────── MAIN ROUTE ───────────── */
app.use((req, res) => {
try {
if (req.path === "/favicon.ico") return res.sendStatus(204);
const decoded = decodeURIComponent(req.path);
const abs = path.resolve(ROOT_DIR, "." + decoded);
if (!abs.startsWith(ROOT_DIR) || !fs.existsSync(abs)) {
return res.status(404).send("Not Found");
}
const stat = fs.statSync(abs);
const media = mediaType(abs);
/* 📁 DIRECTORY */
if (stat.isDirectory()) {
const items = fs.readdirSync(abs);
const list = items.map(name => {
const link = encodeURI(path.posix.join(decoded, name));
return `<li><a href="${link}">${name}</a></li>`;
}).join("");
return res.send(directoryPage(decoded, list));
}
const raw = "/raw" + encodeURI(decoded);
const download = encodeURI(decoded) + "?download=1";
const preview = encodeURI(decoded) + "?preview=1";
if (req.query.download === "1") {
return res.download(abs);
}
/* 🖼 IMAGE */
if (media.image) {
return res.send(previewPage(`<img src="${raw}">`, download));
}
/* 🎥 VIDEO */
if (media.video) {
return res.send(previewPage(`<video controls playsinline src="${raw}"></video>`, download));
}
/* 🔊 AUDIO */
if (media.audio) {
return res.send(previewPage(`<audio controls src="${raw}"></audio>`, download));
}
/* 🌐 HTML */
if (media.html && req.query.preview === "1") {
return res.sendFile(abs);
}
/* 📄 TEXT / HTML AS TEXT */
if (media.text || media.html) {
const text = fs.readFileSync(abs, "utf8")
.replace(/</g, "<")
.replace(/>/g, ">");
const extraBtn = media.html
? `<a href="${preview}" class="btn">👁 Preview</a>`
: "";
return res.send(previewPage(`<pre>${text}</pre>${extraBtn}`, download));
}
res.sendFile(abs);
} catch (e) {
console.error(e);
res.status(500).send("Server Error");
}
});
/* ───────────── UI TEMPLATES ───────────── */
function directoryPage(pathName, list) {
return `
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<style>
body{background:#0f172a;color:#e5e7eb;font-family:system-ui;padding:16px}
h2{margin-bottom:10px}
ul{list-style:none;padding:0}
li{background:#020617;margin:8px 0;padding:12px;border-radius:12px}
a{color:#4cff7a;text-decoration:none;font-weight:500}
</style>
</head>
<body>
<h2>📂 ${pathName}</h2>
<ul>${list}</ul>
</body>
</html>`;
}
function previewPage(content, download) {
return `
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width">
<style>
body{background:#020617;color:#e5e7eb;font-family:system-ui;padding:16px;text-align:center}
img,video{max-width:100%;border-radius:14px}
audio{width:100%}
pre{background:#020617;padding:14px;border-radius:12px;overflow:auto;text-align:left}
.top{display:flex;gap:10px;justify-content:center;margin-bottom:14px}
.btn{padding:10px 16px;border-radius:14px;background:#4cff7a;color:black;font-weight:700;text-decoration:none}
.back{color:#4cff7a;text-decoration:none;font-weight:600}
</style>
</head>
<body>
<div class="top">
<a class="back" href="javascript:history.back()">⬅ Back</a>
<a class="btn" href="${download}">⬇ Download</a>
</div>
${content}
</body>
</html>`;
}
app.listen(PORT, "0.0.0.0", () => {
console.log(`✅ Server running at http://localhost:${PORT}`);
});