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 = probe.audioBitrate
184 ? Math.min(query.audioBitrate, probe.audioBitrate)
185 : query.audioBitrate;
186 const videoBitrate =
187 probe.videoBitrate && query.videoBitrate
188 ? Math.min(query.videoBitrate, probe.videoBitrate)
189 : query.videoBitrate;
190
191 if (!matchesType(fileScan.mimeType, mediaTypes)) {
192 set.status = "Temporary Redirect";
193 set.headers.Location = `/download/${params["*"]}`;
194 return "Not a media file, redirecting to normal endpoint";
195 }
196
197 if (query.videoCodec && query.videoCodec !== VideoCodec.none && !videoBitrate) {
198 set.status = "Bad Request";
199 return "videoBitrate is required when videoCodec is set";
200 }
201 const { cmd, mimeType, stderrText } = await convertWithFFmpeg(
202 filePath,
203 audioBitrate,
204 videoBitrate || 0,
205 query.container,
206 query.audioCodec,
207 query.videoCodec || VideoCodec.none,
208 query.videoEncodingSetting || VideoEncodingSetting.balanced,
209 query.seekTo,
210 query.languages || "",
211 probe,
212 );
213 request.signal.addEventListener("abort", () => cmd.kill("SIGKILL"));
214
215 if (query.disableChunkedTranscoding) {
216 const full = await readStream(cmd.stdout);
217 if (full.length === 0) return transcodeFailed(set, await cmd.exited, await stderrText);
218 set.headers["content-type"] = mimeType;
219 return full;
220 }
221
222 //peek ffmpeg to check for failure and return 500
223 const reader = cmd.stdout.getReader();
224 const first = await reader.read();
225 if (first.done) {
226 reader.releaseLock();
227 return transcodeFailed(set, await cmd.exited, await stderrText);
228 }
229 set.headers["content-type"] = mimeType;
230 return new Response(
231 new ReadableStream<Uint8Array>({
232 start(controller) {
233 controller.enqueue(first.value);
234 },
235 async pull(controller) {
236 const { done, value } = await reader.read();
237 if (done) controller.close();
238 else controller.enqueue(value);
239 },
240 cancel(reason) {
241 void reader.cancel(reason);
242 },
243 }),
244 );
245 },
246 {
247 query: t.Object({
248 seekTo: t.Optional(t.Number()),
249 languages: t.Optional(t.String()),
250 disableChunkedTranscoding: t.Optional(t.Boolean()),
251 container: t.Enum(MediaContainer),
252 videoCodec: t.Optional(t.Enum(VideoCodec)),
253 videoBitrate: t.Optional(t.Number()),
254 videoEncodingSetting: t.Optional(t.Enum(VideoEncodingSetting)),
255 audioCodec: t.Enum(AudioCodec),
256 audioBitrate: t.Number(),
257 }),
258 },
259 )
260 .get(
261 "/list/*",
262 async ({ params, set, query }) => {
263 const dirPath = path.join(musicRoot, decodePath(params["*"]));
264 const fileList = await listFiles(dirPath, query.recursive || false);
265 if (fileList instanceof ServerError) {
266 set.status = fileList.status;
267 return fileList.error;
268 }
269 set.headers["Content-Type"] = "application/json";
270 set.status = "OK";
271 return stringifyMap(fileList);
272 },
273 { query: t.Optional(t.Object({ recursive: t.Boolean() })) },
274 )
275 .get("/isVideo/*", async ({ params, set }) => {
276 const dirPath = resolveInRoot(params["*"]);
277 if (dirPath instanceof ServerError) {
278 set.status = dirPath.status;
279 return dirPath.error;
280 }
281 const probeData = await probeFile(dirPath).catch(() => ({}) as Metadata);
282 return { isVideo: probeData.videoCodec !== undefined } as IsVideoResponse;
283 })
284 .get(
285 "/cover/*",
286 async ({ params, set, query }) => {
287 set.status = "Not Found";
288 const dirPath = resolveInRoot(params["*"]);
289 if (dirPath instanceof ServerError) {
290 set.status = dirPath.status;
291 return dirPath.error;
292 }
293 const fileScanResult = await findCover(dirPath);
294 const setContentType = (type: string) => {
295 set.headers["Content-Type"] = type;
296 };
297 if ("path" in fileScanResult) {
298 set.status = "OK";
299 if (query.transcode)
300 return new Response(
301 await toAvif(
302 await Bun.file(fileScanResult.path).bytes(),
303 fileScanResult.info.mimeType,
304 setContentType,
305 ),
306 );
307 set.headers["Content-Type"] = fileScanResult.info.mimeType;
308 //wrapping in new response discards the accept-range header, which we don't support here
309 return new Response(Bun.file(fileScanResult.path));
310 }
311 if ("content" in fileScanResult) {
312 set.status = "OK";
313 if (query.transcode)
314 return new Response(await toAvif(fileScanResult.content, fileScanResult.info.mimeType, setContentType));
315 set.headers["Content-Type"] = fileScanResult.info.mimeType;
316 return new Response(fileScanResult.content);
317 }
318 set.status = fileScanResult.info.status;
319 return fileScanResult.info.error;
320 },
321 { query: t.Optional(t.Object({ transcode: t.Boolean() })) },
322 )
323 .post("/prepare-playlist", async ({ set, body }) => {
324 set.status = "OK";
325 set.headers["Content-Type"] = "text/plain";
326 const id = randomUUIDv7();
327 generatedPlaylistIds.set(id, JSON.parse(body as string) as string[]);
328 setTimeout(
329 () => {
330 generatedPlaylistIds.delete(id);
331 },
332 1000 * 60 * 60, // 1 hour
333 );
334 return id;
335 })
336 .get(
337 "/download-playlist/:id",
338 async ({ set, params }) => {
339 const playlist = generatedPlaylistIds.get(params.id);
340 if (!playlist) {
341 set.status = "Not Found";
342 return "Playlist ID not found";
343 }
344 set.status = "OK";
345 if (playlist.length === 1) {
346 set.headers["Content-Disposition"] = `attachment; filename="${basename(playlist[0])}"`;
347 return new Response(Bun.file(path.join(musicRoot, playlist[0])));
348 }
349 set.headers["Content-Type"] = "application/x-tar";
350 set.headers["Content-Disposition"] = `attachment; filename="playlist.tar"`;
351 return new Response(packWithTar(playlist).stdout);
352 },
353 { params: t.Object({ id: t.String({ minLength: 1 }) }) },
354 )
355 .post("remote-log", ({ body }) => {
356 console.log(body);
357 }),
358 )
359 .listen(3000);
360
361console.log(`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`);
362