This repository has been archived by the owner on Oct 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.ts
275 lines (240 loc) · 8.07 KB
/
server.ts
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
271
272
273
274
275
import express, { Express, Request, Response } from "express";
import bodyParser from "body-parser";
import cors from "cors";
import fs from "fs";
import path from "path";
import { isNotJunk } from "junk";
import multer from "multer";
import morgan from "morgan";
import slash from "slash";
import { getFileType, ServerOptions } from "./types.js";
import { resolveFilePath, pathExists } from "./utils.js";
import { IndexingServer } from "./indexing.js";
export type Server = ReturnType<typeof express.application.listen>;
export type Event = {
type: string;
payload: any;
};
export type EventCallback = (event: Event) => void;
export function startServer(
options: ServerOptions,
workFolder: string,
onEvent?: EventCallback
): Server {
const app: Express = express();
const upload = multer({ dest: path.join(workFolder, "uploads") });
const { port, folder } = options;
const log = (message: string, type = "log") => {
const logFunc = type === "error" ? console.error : console.log;
logFunc(message);
if (onEvent) {
onEvent({ type, payload: message });
}
};
if (!folder || !fs.existsSync(folder)) {
log(`Folder ${folder} does not exist`, "error");
process.exit(1);
}
app.use(morgan("tiny"));
app.use(cors());
app.use("/download", express.static(folder));
app.get("/", (req: Request, res: Response) => {
res.send("<h1>GM's Notebook Local File Server</h1>");
});
app.get("/api/files", async (req: Request, res: Response) => {
try {
const parentFolderPathParamValue =
req?.query?.parentFolderPath?.toString();
const parentFolderPath = parentFolderPathParamValue
? path.join(folder, parentFolderPathParamValue)
: folder;
const files = await fs.promises.readdir(parentFolderPath);
const filesAndFolders = await Promise.all(
files.filter(isNotJunk).map(async (file) => {
const stats = await fs.promises.stat(
path.join(parentFolderPath, file)
);
return {
name: file,
type: stats.isDirectory() ? "directory" : "file",
};
})
);
res.json(filesAndFolders);
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
});
app.get("/api/file", async (req: Request, res: Response) => {
try {
const filePathParamValue = req?.query?.filePath?.toString();
if (!filePathParamValue) {
res.status(400).json({ error: "filePath is required" });
return;
}
const filePath = await resolveFilePath(
path.join(folder, filePathParamValue)
);
if (!filePath) {
res.status(404).json({ error: "no such file or directory" });
return;
}
const fileType = getFileType(filePath);
const isText = ["markdown", "xfdf"].includes(fileType);
res.json({
name: path.basename(filePath),
type: "file",
fileType,
contents: isText
? await fs.promises.readFile(filePath, "utf8")
: undefined,
downloadUrl: `http://localhost:${port}/download/${slash(
path.relative(folder, filePath)
)}`,
});
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
});
app.post(
"/api/file",
upload.array("file", 1),
async (req: Request, res: Response) => {
try {
const filePathParamValue = req?.query?.filePath?.toString();
if (!filePathParamValue) {
res.status(400).json({ error: "filePath is required" });
return;
}
if (req?.files?.length !== 1) {
res.status(400).json({ error: "file is required" });
return;
}
const autorenameParamValue = req?.query?.autorename?.toString();
const autorename = autorenameParamValue === "true";
let filePath = await resolveFilePath(
path.join(folder, filePathParamValue),
false
);
const parentFolderPath = path.dirname(filePath);
if (!(await pathExists(parentFolderPath))) {
await fs.promises.mkdir(parentFolderPath, { recursive: true });
}
let exists = await pathExists(filePath);
let counter = 1;
const ext = path.extname(filePath);
while (exists && autorename) {
const base = path.basename(filePath, ext);
if (/-\d+$/.test(base)) {
filePath = path.join(
parentFolderPath,
base.replace(/-\d+$/, "") + `-${counter}${ext}`
);
} else {
filePath = path.join(parentFolderPath, base + `-${counter}${ext}`);
}
counter++;
exists = await pathExists(filePath);
}
const file = (req.files as Express.Multer.File[])[0];
await fs.promises.copyFile(file.path, filePath);
await fs.promises.unlink(file.path);
res.json({ success: true, name: path.basename(filePath) });
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
}
);
app.patch("/api/file", async (req: Request, res: Response) => {
try {
const filePathParamValue = req?.query?.filePath?.toString();
if (!filePathParamValue) {
res.status(400).json({ error: "filePath is required" });
return;
}
const newName = req?.query?.newName?.toString();
if (!newName) {
res.status(400).json({ error: "newName is required" });
return;
}
const filePath = await resolveFilePath(
path.join(folder, filePathParamValue)
);
if (!filePath) {
res.status(404).json({ error: "no such file or directory" });
return;
}
const newPath = path.join(path.dirname(filePath), newName);
await fs.promises.rename(filePath, newPath);
res.json({ success: true });
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
});
app.delete("/api/file", async (req: Request, res: Response) => {
try {
const filePathParamValue = req?.query?.filePath?.toString();
if (!filePathParamValue) {
res.status(400).json({ error: "filePath is required" });
return;
}
const filePath = await resolveFilePath(
path.join(folder, filePathParamValue)
);
if (!filePath) {
res.status(404).json({ error: "no such file or directory" });
return;
}
const isDirectory = (await fs.promises.stat(filePath)).isDirectory();
if (!isDirectory) {
await fs.promises.unlink(filePath);
} else {
await fs.promises.rm(filePath, { recursive: true });
}
res.json({ success: true });
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
});
app.put("/api/create-directory", async (req: Request, res: Response) => {
try {
const directoryPathParamValue = req?.query?.directoryPath?.toString();
if (!directoryPathParamValue) {
res.status(400).json({ error: "directoryPath is required" });
return;
}
const directoryPath = path.join(folder, directoryPathParamValue);
await fs.promises.mkdir(directoryPath, { recursive: true });
res.json({ success: true });
} catch (error: any) {
log(error.message, "error");
res.status(500).json({ error: error.message });
}
});
app.post(
"/api/connect",
bodyParser.json(),
async (req: Request, res: Response) => {
if (onEvent) {
onEvent({ type: "connect", payload: req.body });
return res.json({ success: true });
}
res
.status(404)
.json({ success: false, message: "No listener to accept event." });
}
);
const server = app.listen(port, () => {
log(`Server is running at http://localhost:${port}`);
if (options.indexingEnabled && options.indexingKey) {
const indexingServer = new IndexingServer(options, log);
indexingServer.checkTimer();
}
});
return server;
}