-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
270 lines (236 loc) · 7.6 KB
/
index.js
File metadata and controls
270 lines (236 loc) · 7.6 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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import "dotenv/config";
import fs from "node:fs/promises";
import express from "express";
import archiver from "archiver";
import path from "node:path";
const PORT = process.env["PORT"];
const PUBLIC_DIRECTORY = process.env["PUBLIC_DIRECTORY"];
const ZIP_FILE_NAME = "files.zip";
let app = express();
app.set("view engine", "pug");
app.use("/static", express.static("static"));
function formatSize(sizeInBytes) {
const KB = 1024;
const MB = KB * 1024;
const GB = MB * 1024;
if (sizeInBytes >= GB) return `${(sizeInBytes / GB).toFixed(1)} GB`;
if (sizeInBytes >= MB) return `${(sizeInBytes / MB).toFixed(1)} MB`;
return `${(sizeInBytes / KB).toFixed(1)} KB`;
}
// Helper function: Recursively list all files in the flight directory
async function walkFilesRecursively(dir) {
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch (e) {
console.warn(`Cannot read directory ${dir}: ${e.message}`);
return [];
}
let files = [];
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
const nested = await walkFilesRecursively(fullPath);
files = files.concat(nested);
} else if (entry.isFile()) {
try {
const stat = await fs.stat(fullPath);
files.push({
path: path.relative(PUBLIC_DIRECTORY, fullPath),
name: path.basename(fullPath),
mtime: stat.mtime,
size: stat.size,
displaySize: formatSize(stat.size),
});
} catch (e) {
console.warn(`Failed to stat file ${fullPath}: ${e.message}`);
}
} else {
console.warn(
`Skipping non-file entry: ${fullPath} (type: ${entry.constructor.name})`
);
}
}
return files;
}
// Home Page
app.get("/", async (request, response, next) => {
try {
const topEntries = await fs.readdir(PUBLIC_DIRECTORY, {
withFileTypes: true,
});
const structure = await Promise.all(
topEntries
.filter((d) => d.isDirectory())
.map(async (d) => {
try {
const dirPath = path.join(PUBLIC_DIRECTORY, d.name);
const dirContents = await fs.readdir(dirPath, {
withFileTypes: true,
});
// 1. Handle standard nested "Flight" folders
const subDirectories = dirContents.filter((f) => f.isDirectory());
const nestedFlights = await Promise.all(
subDirectories.map(async (f) => {
const flightPath = path.join(dirPath, f.name);
let allFiles = await walkFilesRecursively(flightPath).then(
(files) => files.sort((a, b) => b.mtime - a.mtime)
);
return {
name: f.name,
files: allFiles
.filter((x) => x !== null)
.sort((a, b) => b.mtime - a.mtime),
};
})
);
// 2. Handle "Flat" files (like your video folder)
// We grab everything that isn't a directory and isn't the main log file
const directFiles = dirContents.filter(
(f) => f.isFile() && !f.name.endsWith(".log")
);
let directFlight = null;
if (directFiles.length > 0) {
const processedFiles = await Promise.all(
directFiles.map(async (f) => {
const fullPath = path.join(dirPath, f.name);
try {
const stat = await fs.stat(fullPath);
return {
path: path.relative(PUBLIC_DIRECTORY, fullPath),
name: f.name,
mtime: stat.mtime,
size: stat.size,
displaySize: formatSize(stat.size),
};
} catch (e) {
return null;
}
})
);
directFlight = {
name: "Recordings", // This will appear as the "flight" name in the dropdown
files: processedFiles
.filter((x) => x !== null)
.sort((a, b) => b.mtime - a.mtime),
};
}
// Combine nested flights with the direct file "flight"
const allFlights = nestedFlights.concat(
directFlight ? [directFlight] : []
);
// 3. Handle the folder-level log file
const logFileEntry = dirContents.find(
(f) => f.isFile() && f.name.endsWith(".log")
);
const logFile = logFileEntry
? path.relative(
PUBLIC_DIRECTORY,
path.join(dirPath, logFileEntry.name)
)
: null;
return {
directory: d.name,
flights: allFlights,
log: logFile,
};
} catch (err) {
console.warn(`Skipping folder ${d.name}: ${err.message}`);
return null;
}
})
);
response.render("index", {
structure: structure
.filter((x) => x !== null)
.sort((a, b) => b.directory.localeCompare(a.directory)),
});
} catch (error) {
next(error);
}
});
// Download All Files
app.get("/download-all", (request, response, next) => {
try {
response.writeHead(200, {
"Content-Type": "application/octet-stream",
"Content-Disposition": "attachment; filename=" + ZIP_FILE_NAME,
});
let zip = archiver("zip", { zlib: { level: 9 } });
zip.on("warning", next);
zip.on("error", next);
zip.pipe(response);
zip.directory(PUBLIC_DIRECTORY, false);
zip.finalize();
} catch (error) {
next(error);
}
});
// Download File
app.get("/download/:filePath(*)", async (req, res, next) => {
try {
const relativePath = req.params.filePath;
const absolutePath = path.join(PUBLIC_DIRECTORY, relativePath);
res.download(absolutePath);
} catch (error) {
next(error);
}
});
// Delete File
app.delete("/delete/:filePath(*)", async (req, res, next) => {
try {
const filePath = path.join(PUBLIC_DIRECTORY, req.params.filePath);
await fs.unlink(filePath);
res.status(200).send({ success: true });
} catch (error) {
next(error);
}
});
// Error Handler
app.use((error, request, response, next) => {
console.error(error.stack);
response.render("error", { error: error.stack });
});
// Multi-select
app.post(
"/",
express.urlencoded({ extended: true }),
async (req, res, next) => {
try {
const { _action, folders } = req.body;
if (!folders) return res.redirect("/");
const folderList = Array.isArray(folders) ? folders : [folders];
if (_action === "delete") {
await Promise.all(
folderList.map((folder) =>
fs.rm(path.join(PUBLIC_DIRECTORY, folder), {
recursive: true,
force: true,
})
)
);
return res.redirect("/");
}
if (_action === "download") {
res.writeHead(200, {
"Content-Type": "application/zip",
"Content-Disposition": "attachment; filename=selected-folders.zip",
});
const zip = archiver("zip", { zlib: { level: 9 } });
zip.on("warning", next);
zip.on("error", next);
zip.pipe(res);
folderList.forEach((folder) => {
zip.directory(path.join(PUBLIC_DIRECTORY, folder), folder);
});
await zip.finalize();
}
} catch (error) {
next(error);
}
}
);
// Start Server
app.listen(PORT, () => {
console.log("Listening on port", PORT);
});