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