index.ts
⎇
Raw
1import path, { basename } from "node:path";
2import staticPlugin from "@elysiajs/static";
3import { randomUUIDv7 } from "bun";
4import { type Context, Elysia, StatusMap, t } from "elysia";
5import { stringifyMap } from "music-server-shared/mapconversion";
6import {
7 AudioCodec,
8 type IsVideoResponse,
9 MediaContainer,
10 type Metadata,
11 VideoCodec,
12 VideoEncodingSetting,
13} from "music-server-shared/types";
14import { decodePath } from "music-server-shared/utils";
15import { convertWithFFmpeg } from "./ffmpeg";
16import {
17 allowedTypes,
18 args,
19 authTokens,
20 fileTypeCache,
21 generatedPlaylistIds,
22 mediaTypes,
23 musicRoot,
24 type PathInfo,
25 password,
26 probeCache,
27 ServerError,
28 username,
29} from "./shared";
30import {
31 findCover,
32 getPathInfo,
33 isBelow,
34 listFiles,
35 matchesType,
36 packWithTar,
37 probeFile,
38 readStream,
39 toAvif,
40} from "./utils";
41
42//TODO: transcoding cache?
43//TODO: add reasonable timeouts for caches
44//TODO: better ffmpeg errors
45//TODO: more cover detection
46
47//increase timeout to not abort when listing huge folders
48const setup = new Elysia({ serve: { idleTimeout: 255 } });
49
50function resolveInRoot(encodedPath: string): string | ServerError {
51 const filePath = path.join(musicRoot, decodePath(encodedPath));
52 if (!isBelow(musicRoot, filePath)) return new ServerError(StatusMap.Forbidden, "Path outside the music root");
53 return filePath;
54}
55
56async function resolveMediaFile(encodedPath: string): Promise<{ filePath: string; info: PathInfo } | ServerError> {
57 const filePath = resolveInRoot(encodedPath);
58 if (filePath instanceof ServerError) return filePath;
59 const info = await getPathInfo(filePath);
60 //undefined means it is a directory rather than a file
61 if (!info || info instanceof ServerError)
62 return info ?? new ServerError(StatusMap["Internal Server Error"], "Not a file");
63 if (!matchesType(info.mimeType, allowedTypes)) return new ServerError(StatusMap.Forbidden, "Forbidden file type");
64 return { filePath, info };
65}
66
67type FileHandlerContext = Context<{ params: { "*": string } }>;
68
69function transcodeFailed(set: FileHandlerContext["set"], exitCode: number | null, stderr: string) {
70 set.status = "Internal Server Error";
71 //the first lines are the root cause; what follows is each thread unwinding and reporting the same
72 //failure again, so a tail would report the least informative part of it
73 const reason = stderr.trim().split("\n").slice(0, 3).join("\n");
74 return `Transcoding failed (ffmpeg exit ${exitCode})${reason ? `:\n${reason}` : ""}`;
75}
76
77const downloadHandler = async ({ params, set }: FileHandlerContext) => {
78 const resolved = await resolveMediaFile(params["*"]);
79 if (resolved instanceof ServerError) {
80 set.status = resolved.status;
81 return resolved.error;
82 }
83
84 set.status = "OK";
85 //audio/flac seems to be better supported than the x-flac the sniffer reports
86 set.headers["content-type"] = resolved.info.mimeType === "audio/x-flac" ? "audio/flac" : resolved.info.mimeType;
87 //returning the BunFile directly lets elysia serve range requests natively (Accept-Ranges/206/416)
88 return Bun.file(resolved.filePath);
89};
90
91//the PWA entry points must always be revalidated: a stale index.html references hashed assets that no
92//longer exist, and a stale sw.js pins an outdated precache manifest. everything with a content hash in
93//its name can be cached forever instead. other static files keep the plugin's default (1 day + etag).
94const noCachePaths = new Set(["/", "/index.html", "/sw.js", "/registerSW.js", "/manifest.webmanifest"]);
95const hashedAssetPattern = /-[A-Za-z0-9_-]{8,}\.(js|css)$/;
96
97const app = setup
98 .onAfterHandle({ as: "global" }, ({ path, set, responseValue }) => {
99 const cacheControl = noCachePaths.has(path)
100 ? "no-cache"
101 : hashedAssetPattern.test(path)
102 ? "public, max-age=31536000, immutable"
103 : undefined;
104 if (!cacheControl) return;
105 set.headers["cache-control"] = cacheControl;
106 //the static plugin already put its own cache-control on the Response, and set.headers
107 //alone does not override that, so patch the response headers directly as well
108 if (responseValue instanceof Response) responseValue.headers.set("cache-control", cacheControl);
109 })
110 .use(staticPlugin({ assets: args.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 .get(
135 "/auth/status",
136 ({ cookie: { authToken } }) => {
137 const authRequired = !!(username && password);
138 //when no AUTH is configured every route is open, so treat the user as logged in
139 const loggedIn = !authRequired || (!!authToken.value && authTokens.has(authToken.value));
140 return { authRequired, loggedIn };
141 },
142 { cookie: t.Cookie({ authToken: t.Optional(t.String()) }) },
143 )
144 .post(
145 "/logout",
146 ({ cookie: { authToken }, set }) => {
147 if (authToken.value) authTokens.delete(authToken.value); //invalidate the token server-side
148 //the cookie is HttpOnly, so only the server can clear it - expire it in the past
149 set.headers["set-cookie"] = `authToken=; Expires=${new Date(0).toUTCString()}; Secure; HttpOnly; SameSite=Strict`;
150 return "Logged out";
151 },
152 { cookie: t.Cookie({ authToken: t.Optional(t.String()) }) },
153 )
154 .guard(
155 {
156 cookie: t.Cookie({ authToken: t.Optional(t.String()) }),
157 beforeHandle({ cookie: { authToken }, set }) {
158 if (username && password && (!authToken.value || !authTokens.has(authToken.value))) {
159 set.status = 401;
160 return "Unauthorized";
161 }
162 },
163 },
164 (guarded) =>
165 guarded
166 .post("/reset-cache", () => {
167 fileTypeCache.clear();
168 probeCache.clear();
169 })
170 .get("/download/*", downloadHandler)
171 .head("/download/*", downloadHandler)
172 .get(
173 "/transcode/*",
174 async ({ request, query, set, params }) => {
175 const resolved = await resolveMediaFile(params["*"]);
176 if (resolved instanceof ServerError) {
177 set.status = resolved.status;
178 return resolved.error;
179 }
180 const { filePath, info: fileScan } = resolved;
181 const probe = await probeFile(filePath);
182 //don't use higher bitrate than what the file has, use requested bitrate if unknown
183 const audioBitrate =
184 query.audioBitrate && probe.audioBitrate
185 ? Math.min(query.audioBitrate, probe.audioBitrate)
186 : query.audioBitrate;
187 const videoBitrate =
188 probe.videoBitrate && query.videoBitrate
189 ? Math.min(query.videoBitrate, probe.videoBitrate)
190 : query.videoBitrate;
191
192 if (!matchesType(fileScan.mimeType, mediaTypes)) {
193 set.status = "Temporary Redirect";
194 set.headers.Location = `/download/${params["*"]}`;
195 return "Not a media file, redirecting to normal endpoint";
196 }
197
198 if (query.videoCodec && query.videoCodec !== VideoCodec.none && !videoBitrate) {
199 set.status = "Bad Request";
200 return "videoBitrate is required when videoCodec is set";
201 }
202 const { cmd, mimeType, stderrText } = await convertWithFFmpeg(
203 filePath,
204 audioBitrate,
205 videoBitrate || 0,
206 query.container,
207 query.audioCodec,
208 query.videoCodec || VideoCodec.none,
209 query.videoEncodingSetting || VideoEncodingSetting.balanced,
210 query.seekTo,
211 query.languages || "",
212 probe,
213 );
214 request.signal.addEventListener("abort", () => cmd.kill("SIGKILL"));
215
216 if (query.disableChunkedTranscoding) {
217 const full = await readStream(cmd.stdout);
218 if (full.length === 0) return transcodeFailed(set, await cmd.exited, await stderrText);
219 set.headers["content-type"] = mimeType;
220 return full;
221 }
222
223 //peek ffmpeg to check for failure and return 500
224 const reader = cmd.stdout.getReader();
225 const first = await reader.read();
226 if (first.done) {
227 reader.releaseLock();
228 return transcodeFailed(set, await cmd.exited, await stderrText);
229 }
230 set.headers["content-type"] = mimeType;
231 return new Response(
232 new ReadableStream<Uint8Array>({
233 start(controller) {
234 controller.enqueue(first.value);
235 },
236 async pull(controller) {
237 const { done, value } = await reader.read();
238 if (done) controller.close();
239 else controller.enqueue(value);
240 },
241 cancel(reason) {
242 void reader.cancel(reason);
243 },
244 }),
245 );
246 },
247 {
248 query: t.Object({
249 seekTo: t.Optional(t.Number()),
250 languages: t.Optional(t.String()),
251 disableChunkedTranscoding: t.Optional(t.Boolean()),
252 container: t.Enum(MediaContainer),
253 videoCodec: t.Optional(t.Enum(VideoCodec)),
254 videoBitrate: t.Optional(t.Number()),
255 videoEncodingSetting: t.Optional(t.Enum(VideoEncodingSetting)),
256 audioCodec: t.Enum(AudioCodec),
257 audioBitrate: t.Optional(t.Number()),
258 }),
259 },
260 )
261 .get(
262 "/list/*",
263 async ({ params, set, query }) => {
264 const dirPath = path.join(musicRoot, decodePath(params["*"]));
265 const fileList = await listFiles(dirPath, query.recursive || false);
266 if (fileList instanceof ServerError) {
267 set.status = fileList.status;
268 return fileList.error;
269 }
270 set.headers["Content-Type"] = "application/json";
271 set.status = "OK";
272 return stringifyMap(fileList);
273 },
274 { query: t.Optional(t.Object({ recursive: t.Boolean() })) },
275 )
276 .get("/isVideo/*", async ({ params, set }) => {
277 const dirPath = resolveInRoot(params["*"]);
278 if (dirPath instanceof ServerError) {
279 set.status = dirPath.status;
280 return dirPath.error;
281 }
282 const probeData = await probeFile(dirPath).catch(() => ({}) as Metadata);
283 return { isVideo: probeData.videoCodec !== undefined } as IsVideoResponse;
284 })
285 .get(
286 "/cover/*",
287 async ({ params, set, query }) => {
288 set.status = "Not Found";
289 const dirPath = resolveInRoot(params["*"]);
290 if (dirPath instanceof ServerError) {
291 set.status = dirPath.status;
292 return dirPath.error;
293 }
294 const fileScanResult = await findCover(dirPath);
295 const setContentType = (type: string) => {
296 set.headers["Content-Type"] = type;
297 };
298 if ("path" in fileScanResult) {
299 set.status = "OK";
300 if (query.transcode)
301 return new Response(
302 await toAvif(
303 await Bun.file(fileScanResult.path).bytes(),
304 fileScanResult.info.mimeType,
305 setContentType,
306 ),
307 );
308 set.headers["Content-Type"] = fileScanResult.info.mimeType;
309 //wrapping in new response discards the accept-range header, which we don't support here
310 return new Response(Bun.file(fileScanResult.path));
311 }
312 if ("content" in fileScanResult) {
313 set.status = "OK";
314 if (query.transcode)
315 return new Response(await toAvif(fileScanResult.content, fileScanResult.info.mimeType, setContentType));
316 set.headers["Content-Type"] = fileScanResult.info.mimeType;
317 return new Response(fileScanResult.content);
318 }
319 set.status = fileScanResult.info.status;
320 return fileScanResult.info.error;
321 },
322 { query: t.Optional(t.Object({ transcode: t.Boolean() })) },
323 )
324 .post("/prepare-playlist", async ({ set, body }) => {
325 set.status = "OK";
326 set.headers["Content-Type"] = "text/plain";
327 const id = randomUUIDv7();
328 generatedPlaylistIds.set(id, JSON.parse(body as string) as string[]);
329 setTimeout(
330 () => {
331 generatedPlaylistIds.delete(id);
332 },
333 1000 * 60 * 60, // 1 hour
334 );
335 return id;
336 })
337 .get(
338 "/download-playlist/:id",
339 async ({ set, params }) => {
340 const playlist = generatedPlaylistIds.get(params.id);
341 if (!playlist) {
342 set.status = "Not Found";
343 return "Playlist ID not found";
344 }
345 set.status = "OK";
346 if (playlist.length === 1) {
347 set.headers["Content-Disposition"] = `attachment; filename="${basename(playlist[0])}"`;
348 return new Response(Bun.file(path.join(musicRoot, playlist[0])));
349 }
350 set.headers["Content-Type"] = "application/x-tar";
351 set.headers["Content-Disposition"] = `attachment; filename="playlist.tar"`;
352 return new Response(packWithTar(playlist).stdout);
353 },
354 { params: t.Object({ id: t.String({ minLength: 1 }) }) },
355 )
356 .post("remote-log", ({ body }) => {
357 console.log(body);
358 }),
359 )
360 .listen(3000);
361
362console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`);
363