-
Notifications
You must be signed in to change notification settings - Fork 9
/
filebrowser.js
205 lines (183 loc) · 6 KB
/
filebrowser.js
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
const fs = require("fs");
const fs_async = require("fs").promises;
const path = require("path");
const express = require("express");
const router = express.Router();
const nodeDiskInfo = require("node-disk-info");
const { getMediastatusEntries, getCollections } = require("./crud");
const { settings } = require("./settings");
const FILE_FORMATS = require("./fileformats").FILE_FORMATS;
function detectFileType(extension) {
extension = extension.toLowerCase();
if (FILE_FORMATS.video.includes(extension)) {
return "video";
} else if (FILE_FORMATS.audio.includes(extension)) {
return "audio";
} else if (FILE_FORMATS.subtitle.includes(extension)) {
return "subtitle";
} else {
return "file";
}
}
async function getDirectoryContents(qpath) {
// TODO Handle exceptions
let content = [];
// Add path seperator to qpath end
/*
Interesting because C: (System partition) needs a path seperator to work correctly,
but for my network drives works without path sep.
*/
if (qpath[qpath.length - 1] != path.sep) qpath += path.sep;
let mediaStatus = [];
if (settings.uselocaldb)
mediaStatus = await getMediastatusEntries(null, qpath);
for (const item of await fs_async.readdir(qpath)) {
try {
if (fs.lstatSync(path.join(qpath, item)).isDirectory()) {
let entry = {
priority: 1,
type: "directory",
name: item,
fullPath: path.join(qpath, item),
};
entry.lastModified = await fs_async
.stat(entry.fullPath)
.then((stat) => stat.mtime)
.catch(() => null);
content.push(entry);
} else {
let fileType = detectFileType(path.extname(item));
// Render only media, sub types.
if (fileType !== "file") {
let entry = {
priority: 2,
type: fileType,
name: item,
fullPath: path.join(qpath, item),
};
entry.lastModified = await fs_async
.stat(entry.fullPath)
.then((stat) => stat.mtime)
.catch(() => null);
if (settings.uselocaldb)
entry.mediaStatus = mediaStatus.find((el) => el.file_name == item);
content.push(entry);
}
}
} catch (exc) {
console.log(exc);
}
}
return content;
}
router.get("/api/v1/drives", async (req, res) => {
try {
if (settings.unsafefilebrowsing) {
let disks = await nodeDiskInfo.getDiskInfo();
// ignore snap, flatpak stuff linux
disks = disks.filter(
(disk) =>
!disk._mounted.includes("snap") && !disk._mounted.includes("flatpak")
);
disks = disks.map((disk) => {
return {
path: disk._mounted,
};
});
return res.json(disks);
} else
return res
.status(403)
.json({ message: "mpvremote-unsafefilebrowsing disabled!" });
} catch (e) {
console.log(e);
res.status(500).json({ message: exc });
}
});
router.get("/api/v1/filebrowser/paths", async (req, res) => {
try {
return res.json(settings.filebrowserPaths);
} catch (exc) {
console.log(exc);
return res.status(500).json({ message: exc });
}
});
router.post("/api/v1/filebrowser/browse", async (req, res) => {
try {
let p = req.body.path;
let collectionId = req.body.collection_id;
// Find FILEBROWSER_PATH entry
if (!p && !collectionId)
return res
.status(400)
.json({ message: "path or collection id missing from request data!" });
let retval = {};
if (p) {
// If unsafe filebrowsing disabled we've to check FILEBROWSER_PATHS
if (!settings.unsafefilebrowsing) {
// Security: Protect against path-traversal attack by resolving synlinks and ..
p = await fs_async.realpath(p);
let fbe = settings.filebrowserPaths.find((el) => {
return p.startsWith(el.path);
});
if (!fbe)
return res
.status(400)
.send({ message: `Path not exists on filebrowserpaths: ${p}` });
}
if (!fs.existsSync(p))
return res.status(404).send({ message: "Path not exists!" });
// Get files from directory
retval.content = await getDirectoryContents(p);
retval.dirname = path.basename(p);
retval.prevDir = path.resolve(p, "..");
retval.cwd = p;
} else if (collectionId) {
// Get collection contents if local database enabled!
if (!settings.uselocaldb)
return res
.status(400)
.send({ message: "mpvremote-uselocaldb is disabled!" });
let collection = await getCollections(collectionId);
if (!collection) return res.status(404).send("Collection not exists!");
retval.content = [];
retval.errors = [];
await Promise.all(
collection.paths.map(async (item) => {
// Check if exists on filebrowserpaths
if (!settings.unsafefilebrowsing) {
let fbe = settings.filebrowserPaths.find((el) => {
return item.path.includes(el.path);
});
if (!fbe) {
console.log(`Not exists on filebrowserpaths: ${item.path}`);
retval.errors.push(
`Not exists on filebrowserpaths: ${item.path}`
);
}
} else if (fs.existsSync(item.path)) {
const dir = await getDirectoryContents(item.path);
retval.content = [...retval.content, ...dir];
} else {
console.log(`Path not exists ${item.path}`);
}
})
);
retval.collection_id = collectionId;
}
// Sort content firstly by priority and alphabet order.
retval.content.sort((a, b) => {
return (
a.priority - b.priority ||
a.name.toLowerCase().localeCompare(b.name.toLowerCase())
);
});
return res.json(retval);
} catch (exc) {
console.log(exc);
return res.status(500).json({ message: exc });
}
});
exports.getDirectoryContents = getDirectoryContents;
exports.detectFileType = detectFileType;
module.exports = router;