Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
88 lines (74 loc) · 2.33 KB
/
Copy pathserver.js
File metadata and controls
88 lines (74 loc) · 2.33 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
const express = require("express");
const serveIndex = require("serve-index");
const path = require("path");
const fs = require("fs");
const utils = require("./src/utils/common");
const os = require("os");
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 3008;
const API_VERSION = process.env.API_VERSION || "v1";
const API_PREFIX = `/api/${API_VERSION}`;
const moviesDirectory = process.env.MOVIES_DIRECTORY;
// static content for all movies
app.use(
`${API_PREFIX}/stream`,
express.static(moviesDirectory),
serveIndex(moviesDirectory, { icons: true })
);
/**
* API to list all the movies in the directory
*/
app.get(`${API_PREFIX}/movies`, (req, res) => {
const dir = req.query.dir || "";
const movieData = listMoviesRecursively(moviesDirectory, dir);
res.json(movieData);
});
/**
* get all moview and directories from the provided directory
*/
function listMoviesRecursively(baseDirectory, directory) {
const directoryPath = baseDirectory + directory || "";
const files = fs.readdirSync(directoryPath, { withFileTypes: true });
const filesData = [];
const directoriesData = [];
files.forEach((file) => {
const filePath = path.join(directoryPath, file.name);
const item = {};
if (file.isDirectory()) {
directoriesData.push(filePath.replace(moviesDirectory, ""));
} else {
if (!/\.(mp4|avi|webm|mp3)$/.test(file.name)) {
return;
}
const stats = fs.statSync(filePath);
// Convert the size to a human-readable format
const size = utils.getSizeInGB(stats);
item.filename = utils.removeSpecialCharsAndExtension(file.name);
item.path =
`${API_PREFIX}/stream` + filePath.replace(moviesDirectory, "");
filesData.push(item);
item.size = size;
item.createdTime = stats.ctime;
item.modifiedTime = stats.mtime;
}
});
return {
servingFrom: os.hostname(),
directoryPath,
files: filesData,
directories: directoriesData,
totalFiles: filesData.length,
totalDirectories: directoriesData.length,
basePath: moviesDirectory,
};
}
// Serve the HTML file
app.use(express.static(path.join(__dirname, "./build")));
app.use("/static", express.static(path.join(__dirname, "./build/static")));
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "./build/index.html"));
});
app.listen(PORT, () => {
console.log(`Server is running at http://localhost:${PORT}`);
});