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