index.ts
⎇
Raw
1import staticPlugin from "@elysiajs/static";
2import { Elysia, type InferHandler, t } from "elysia";
3import path, { basename } from "node:path";
4import { parseArgs } from "node:util";
5import {
6 musicRoot,
7 fileTypeCache,
8 ServerError,
9 allowedTypes,
10 probeCache,
11 mediaTypes,
12 generatedPlaylistIds,
13 username,
14 password,
15 authTokens,
16} from "./shared";
17import {
18 getPathInfo,
19 listFiles,
20 findCover,
21 matchesType,
22 convertWithFFmpeg,
23 packWithTar,
24 probeFile,
25 toAvif,
26} from "./utils";
27import { stat } from "node:fs/promises";
28
29import parseRange from "range-parser";
30import { MediaFormat } from "music-server-shared/types";
31import { decodePath } from "music-server-shared/utils";
32import { stringifyMap } from "music-server-shared/mapconversion";
33import { randomUUIDv7 } from "bun";
34
35//TODO: transcoding cache?
36//TODO: add reasonable timeouts for caches
37//TODO: better ffmpeg errors
38//TODO: more cover detection
39
40const { values } = parseArgs({
41 args: Bun.argv,
42 options: {
43 serve: {
44 type: "string",
45 },
46 },
47 strict: true,
48 allowPositionals: true,
49});
50
51if (!values.serve) {
52 console.error("Missing --serve, set it to the directory containing the frontend code");
53 process.exit(1);
54}
55
56//increase timeout to not abort when listing huge folders
57const setup = new Elysia({ serve: { idleTimeout: 255 } });
58
59const paramType = t.ArrayString();
60type DownloadHandler = InferHandler<typeof setup, "/download/*", { params: typeof paramType }>;
61
62const downloadHandler: DownloadHandler = async ({ headers, params, set, request }) => {
63 if (request.method !== "GET" && request.method !== "HEAD") {
64 set.status = "Not Found";
65 return "NOT_FOUND";
66 }
67 const filePath = path.join(musicRoot, decodePath(params["*"]));
68 const fileScan = await getPathInfo(filePath);
69 if (!fileScan || fileScan instanceof ServerError) {
70 set.status = fileScan?.status || "Internal Server Error";
71 return fileScan?.error || "Not a file";
72 }
73 if (!matchesType(fileScan.mimeType, allowedTypes)) {
74 set.status = "Forbidden";
75 return "Forbidden file type";
76 }
77
78 set.status = "OK";
79 if (fileScan.mimeType === "audio/x-flac") fileScan.mimeType = "audio/flac"; //seems to be better supported
80 set.headers["content-type"] = fileScan.mimeType;
81
82 const statResult = await stat(filePath);
83 const fileSize = statResult.size;
84
85 if (request.method === "HEAD") {
86 set.headers["accept-ranges"] = "bytes";
87 set.headers["content-length"] = fileSize;
88 return;
89 }
90
91 if (!headers.range) {
92 set.status = "OK";
93 return Bun.file(filePath);
94 }
95
96 const rangeData = parseRange(fileSize, headers.range, { combine: true });
97 if (rangeData === -1 || rangeData === -2 || rangeData.length > 1) {
98 set.status = "Range Not Satisfiable";
99 return "Range Not Satisfiable";
100 }
101 const { start, end } = rangeData[0];
102 set.status = "Partial Content";
103 set.headers["Content-Range"] = `bytes ${start}-${end}/${fileSize}`;
104 // set.headers["content-length"] = end - start + 1; //currently broken in bun/elysiajs, overwritten in final response, seems to be fine though
105 // return createReadStream(filePath, { start, end });
106 return new Response(Bun.file(filePath).slice(start, end));
107};
108
109const app = setup
110 .use(staticPlugin({ assets: values.serve, prefix: "/" }))
111 .onBeforeHandle(({ request, path }) => {
112 if (path === "/remote-log") return;
113 console.info(request.method, path);
114 })
115 .post(
116 "/login",
117 ({ body, set }) => {
118 const [givenUser, givenPassword] = (body as string).split(":", 2);
119 if (givenUser === username && givenPassword === password) {
120 set.status = 200;
121 const millisInYear = 365 * 24 * 60 * 60 * 1000;
122 const endDate = new Date(Date.now() + millisInYear);
123 const token = randomUUIDv7();
124 authTokens.set(token, endDate);
125 set.headers["set-cookie"] =
126 `authToken=${token}; Expires=${endDate.toUTCString()}; Secure; HttpOnly; SameSite=Strict"`;
127 return "Logged in successfully";
128 }
129 set.status = 401;
130 return "Invalid username or password";
131 },
132 { body: t.String() },
133 )
134 .guard(
135 {
136 beforeHandle({ cookie: { authToken }, set }) {
137 if (username && password && (!authToken.value || !authTokens.has(authToken.value))) {
138 set.status = 401;
139 set.headers.location;
140 return "Unauthorized";
141 }
142 },
143 },
144 (guarded) =>
145 guarded
146 .post("/reset-cache", () => {
147 fileTypeCache.clear();
148 probeCache.clear();
149 })
150 .get("/download/*", downloadHandler)
151 .head("/download/*", downloadHandler)
152 .get(
153 "/transcode/*",
154 async ({ request, query, set, params }) => {
155 const filePath = path.join(musicRoot, decodePath(params["*"]));
156 const fileScan = await getPathInfo(filePath);
157 if (!fileScan || fileScan instanceof ServerError) {
158 set.status = fileScan?.status || "Internal Server Error";
159 return fileScan?.error || "Not a file";
160 }
161 if (!matchesType(fileScan.mimeType, allowedTypes)) {
162 set.status = "Forbidden";
163 return "Forbidden file type";
164 }
165 const probe = await probeFile(filePath);
166 //don't use higher bitrate than what the file has, use requested bitrate if unknown, default to 96kbit if not provided
167 const bitrate =
168 query.bitrate && probe.bitrate ? Math.min(query.bitrate, probe.bitrate) : query.bitrate || 96000;
169 if (!matchesType(fileScan.mimeType, mediaTypes)) {
170 set.status = "Temporary Redirect";
171 set.headers.Location = `/download/${params["*"]}`;
172 return "Not a media file, redirecting to normal endpoint";
173 }
174
175 const { cmd, mimeType } = convertWithFFmpeg(filePath, bitrate, query.format ?? MediaFormat["opus/ogg"]);
176 request.signal.addEventListener("abort", () => cmd.kill("SIGKILL"));
177 set.headers["content-type"] = mimeType;
178 if (query.disableChunkedTranscoding) {
179 const chunks: Uint8Array[] = [];
180 for await (const chunk of cmd.stdout) {
181 chunks.push(chunk);
182 }
183 const full = new Uint8Array(chunks.reduce((acc, val) => acc + val.length, 0));
184 let offset = 0;
185 for (const chunk of chunks) {
186 full.set(chunk, offset);
187 offset += chunk.length;
188 }
189 return full;
190 }
191 return new Response(cmd.stdout);
192 },
193 {
194 query: t.Optional(
195 t.Object({ bitrate: t.Number(), format: t.Enum(MediaFormat), disableChunkedTranscoding: t.Boolean() }),
196 ),
197 },
198 )
199 .get(
200 "/list/*",
201 async ({ params, set, query }) => {
202 const dirPath = path.join(musicRoot, decodePath(params["*"]));
203 const fileList = await listFiles(dirPath, query.recursive || false);
204 if (fileList instanceof ServerError) {
205 set.status = fileList.status;
206 return fileList.error;
207 }
208 set.headers["Content-Type"] = "application/json";
209 set.status = "OK";
210 return stringifyMap(fileList);
211 },
212 { query: t.Optional(t.Object({ recursive: t.Boolean() })) },
213 )
214 .get(
215 "/cover/*",
216 async ({ params, set, query }) => {
217 set.status = "Not Found";
218 const dirPath = path.join(musicRoot, decodePath(params["*"]));
219 const fileScanResult = await findCover(dirPath);
220 const setContentType = (type: string) => {
221 set.headers["Content-Type"] = type;
222 };
223 if ("path" in fileScanResult) {
224 set.headers["Content-Type"] = fileScanResult.info.mimeType;
225 set.status = "OK";
226 if (query.transcode)
227 return new Response(
228 await toAvif(
229 await Bun.file(fileScanResult.path).bytes(),
230 fileScanResult.info.mimeType,
231 setContentType,
232 ),
233 );
234 //wrapping in new response discards the accept-range header, which we don't support here
235 return new Response(Bun.file(fileScanResult.path));
236 }
237 if ("content" in fileScanResult) {
238 set.headers["Content-Type"] = fileScanResult.info.mimeType;
239 set.status = "OK";
240 if (query.transcode)
241 return new Response(await toAvif(fileScanResult.content, fileScanResult.info.mimeType, setContentType));
242 return new Response(fileScanResult.content);
243 }
244 set.status = fileScanResult.info.status;
245 return fileScanResult.info.error;
246 },
247 { query: t.Optional(t.Object({ transcode: t.Boolean() })) },
248 )
249 .post("/prepare-playlist", async ({ set, body }) => {
250 set.status = "OK";
251 set.headers["Content-Type"] = "text/plain";
252 const id = randomUUIDv7();
253 generatedPlaylistIds.set(id, JSON.parse(body as string) as string[]);
254 setTimeout(
255 () => {
256 generatedPlaylistIds.delete(id);
257 },
258 1000 * 60 * 60, // 1 hour
259 );
260 return id;
261 })
262 .get(
263 "/download-playlist/:id",
264 async ({ set, params }) => {
265 const playlist = generatedPlaylistIds.get(params.id);
266 if (!playlist) {
267 set.status = "Not Found";
268 return "Playlist ID not found";
269 }
270 set.status = "OK";
271 if (playlist.length === 1) {
272 set.headers["Content-Disposition"] = `attachment; filename="${basename(playlist[0])}"`;
273 return new Response(Bun.file(path.join(musicRoot, playlist[0])));
274 }
275 set.headers["Content-Type"] = "application/x-tar";
276 set.headers["Content-Disposition"] = `attachment; filename="playlist.tar"`;
277 return new Response(packWithTar(playlist).stdout);
278 },
279 { params: t.Object({ id: t.String({ minLength: 1 }) }) },
280 )
281 .post("remote-log", ({ body }) => {
282 console.log(body);
283 }),
284 )
285 .listen(3000);
286
287console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`);
288