Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

feat(media): support mp4 and webm board backgrounds (#7299)

Amalkrishna A S24e91abf0c0c
diff --git a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
index 6529ad555..d734aeeda 100644
--- a/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/[name]/settings/_background.tsx
@@ -10,10 +10,14 @@ import { useSession } from "@homarr/auth/client";
import { backgroundImageAttachments, backgroundImageRepeats, backgroundImageSizes } from "@homarr/definitions";
import type { UseFormReturnType } from "@homarr/form";
import { UploadMedia } from "@homarr/forms-collection";
+import { createLocalMediaUrl } from "@homarr/icons/local-media-url";
import type { TranslationObject } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client";
import type { SelectItemWithDescriptionBadge } from "@homarr/ui";
import { SelectWithDescriptionBadge } from "@homarr/ui";
+import { supportedMediaUploadFormats } from "@homarr/validation/media";
+
+import { useIsVideo } from "~/components/layout/background";
import type { FormValues } from "./_settings-form";
@@ -32,8 +36,11 @@ export const BackgroundSettingsContent = ({ form }: Props) => {
includeFromAllUsers: true,
search: debouncedSearch ?? "",
});
- const images = medias.data?.items.filter((media) => media.contentType.startsWith("image/")) ?? [];
- const imageMap = new Map(images.map((image) => [`/api/user-medias/${image.id}`, image]));
+ const backgrounds =
+ medias.data?.items.filter(
+ (media) => media.contentType.startsWith("image/") || media.contentType.startsWith("video/"),
+ ) ?? [];
+ const backgroundMap = new Map(backgrounds.map((media) => [createLocalMediaUrl(media.id), media]));
const backgroundImageAttachmentData = useBackgroundOptionData(
"backgroundImageAttachment",
@@ -68,7 +75,7 @@ export const BackgroundSettingsContent = ({ form }: Props) => {
label={tBoard("field.backgroundImageUrl.label")}
placeholder={`${tBoard("field.backgroundImageUrl.placeholder")}...`}
renderOption={({ option }) => {
- const current = imageMap.get(option.value);
+ const current = backgroundMap.get(option.value);
if (!current) return null;
return (
@@ -86,21 +93,22 @@ export const BackgroundSettingsContent = ({ form }: Props) => {
data={[
{
group: tBoard("field.backgroundImageUrl.group.your"),
- items: images
+ items: backgrounds
.filter((media) => media.creatorId === session?.user.id)
- .map((media) => `/api/user-medias/${media.id}`),
+ .map((media) => createLocalMediaUrl(media.id)),
},
{
group: tBoard("field.backgroundImageUrl.group.other"),
- items: images
+ items: backgrounds
.filter((media) => media.creatorId !== session?.user.id)
- .map((media) => `/api/user-medias/${media.id}`),
+ .map((media) => createLocalMediaUrl(media.id)),
},
]}
{...form.getInputProps("backgroundImageUrl")}
/>
{session?.user.permissions.includes("media-upload") && (
<UploadMedia
+ accept={supportedMediaUploadFormats}
onSuccess={(uploadedMedias) => {
const first = uploadedMedias.at(0);
if (!first) return;
@@ -150,12 +158,18 @@ interface ImagePreviewProps {
}
const ImagePreview = ({ src, w, h }: ImagePreviewProps) => {
+ const isVideo = useIsVideo(src);
if (!["/", "http://", "https://"].some((prefix) => src.startsWith(prefix))) {
return <IconPhotoOff size={w} />;
}
+ if (isVideo === undefined) return <IconPhotoOff size={w} />;
+ if (isVideo) {
+ return <video src={src} muted preload="metadata" style={{ width: w, height: h, objectFit: "contain" }} />;
+ }
+
// eslint-disable-next-line @next/next/no-img-element
- return <img src={src} alt="preview image" style={{ width: w, height: h, objectFit: "contain" }} />;
+ return <img src={src} alt="Background preview" style={{ width: w, height: h, objectFit: "contain" }} />;
};
type BackgroundImageKey = "backgroundImageAttachment" | "backgroundImageSize" | "backgroundImageRepeat";
diff --git a/apps/nextjs/src/app/[locale]/manage/medias/_actions/copy-media.tsx b/apps/nextjs/src/app/[locale]/manage/medias/_actions/copy-media.tsx
index 705cd1353..d680976a3 100644
--- a/apps/nextjs/src/app/[locale]/manage/medias/_actions/copy-media.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/medias/_actions/copy-media.tsx
@@ -4,6 +4,7 @@ import { ActionIcon, CopyButton, Tooltip } from "@mantine/core";
import { IconCheck, IconCopy } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
+import { createLocalMediaUrl } from "@homarr/icons/local-media-url";
import { useI18n } from "@homarr/translation/client";
interface CopyMediaProps {
@@ -14,7 +15,7 @@ export const CopyMedia = ({ media }: CopyMediaProps) => {
const t = useI18n("media");
const label = t("action.copy.labelNamed", { name: media.name });
- const url = typeof window !== "undefined" ? `${window.location.origin}/api/user-medias/${media.id}` : "";
+ const url = typeof window !== "undefined" ? `${window.location.origin}${createLocalMediaUrl(media.id)}` : "";
// Clipboard only works on localhost or secure connections (https)
if (url.startsWith("http://") && !url.startsWith("http://localhost")) {
diff --git a/apps/nextjs/src/app/[locale]/manage/medias/_actions/upload-media.tsx b/apps/nextjs/src/app/[locale]/manage/medias/_actions/upload-media.tsx
index 971132d71..8a07b31bf 100644
--- a/apps/nextjs/src/app/[locale]/manage/medias/_actions/upload-media.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/medias/_actions/upload-media.tsx
@@ -6,6 +6,7 @@ import { IconUpload } from "@tabler/icons-react";
import { revalidatePathActionAsync } from "@homarr/common/client";
import { UploadMedia } from "@homarr/forms-collection";
import { useI18n } from "@homarr/translation/client";
+import { supportedMediaUploadFormats } from "@homarr/validation/media";
export const UploadMediaButton = () => {
const t = useI18n("media");
@@ -14,7 +15,7 @@ export const UploadMediaButton = () => {
};
return (
- <UploadMedia onSettled={onSettledAsync} multiple>
+ <UploadMedia onSettled={onSettledAsync} accept={supportedMediaUploadFormats} multiple>
{({ onClick, loading }) => (
<Button onClick={onClick} loading={loading} rightSection={<IconUpload size={16} stroke={1.5} />}>
{t("action.upload.label")}
diff --git a/apps/nextjs/src/app/[locale]/manage/medias/page.tsx b/apps/nextjs/src/app/[locale]/manage/medias/page.tsx
index e24fa032d..0c0b8b692 100644
--- a/apps/nextjs/src/app/[locale]/manage/medias/page.tsx
+++ b/apps/nextjs/src/app/[locale]/manage/medias/page.tsx
@@ -24,7 +24,7 @@ import { auth } from "@homarr/auth/next";
import { defaultByteUnitSystem, formatBytes } from "@homarr/common";
import type { ByteUnitSystem } from "@homarr/common";
import type { inferSearchParamsFromSchema } from "@homarr/common/types";
-import { createLocalImageUrl } from "@homarr/icons/local";
+import { createLocalImageUrl, createLocalMediaUrl } from "@homarr/icons/local";
import { getI18n } from "@homarr/translation/server";
import { Link, SearchInput, TablePagination, UserAvatar } from "@homarr/ui";
@@ -155,14 +155,26 @@ const Row = async ({ media, byteUnitSystem }: RowProps) => {
return (
<TableTr>
<TableTd w={64}>
- <Image
- // Switched to mantine image because next/image doesn't support svgs
- src={createLocalImageUrl(media.id)}
- alt={media.name}
- w={64}
- h={64}
- fit="contain"
- />
+ {media.contentType.startsWith("video/") ? (
+ <video
+ src={createLocalMediaUrl(media.id)}
+ aria-label={media.name}
+ muted
+ preload="metadata"
+ width={64}
+ height={64}
+ style={{ objectFit: "contain" }}
+ />
+ ) : (
+ <Image
+ // Switched to mantine image because next/image doesn't support svgs
+ src={createLocalImageUrl(media.id)}
+ alt={media.name}
+ w={64}
+ h={64}
+ fit="contain"
+ />
+ )}
</TableTd>
<TableTh scope="row">{media.name}</TableTh>
<TableTd>{formatBytes(media.size, { unit: byteUnitSystem })}</TableTd>
@@ -185,7 +197,7 @@ const Row = async ({ media, byteUnitSystem }: RowProps) => {
<ActionIcon
aria-label={tMedia("action.open.labelNamed", { name: media.name })}
component="a"
- href={createLocalImageUrl(media.id)}
+ href={createLocalMediaUrl(media.id)}
target="_blank"
rel="noopener noreferrer"
color="gray"
diff --git a/apps/nextjs/src/app/api/backup/import/route.ts b/apps/nextjs/src/app/api/backup/import/route.ts
index 93f08696b..d3f83fc56 100644
--- a/apps/nextjs/src/app/api/backup/import/route.ts
+++ b/apps/nextjs/src/app/api/backup/import/route.ts
@@ -23,6 +23,7 @@ import { db } from "@homarr/db";
import type { Database } from "@homarr/db";
import { applyCustomMigrationsAsync } from "@homarr/db/migrations/custom";
import { schema } from "@homarr/db/schema";
+import { mediaUploadMaxSize } from "@homarr/validation/media";
import { findMigrationsFolder } from "../shared";
@@ -320,6 +321,13 @@ export async function POST(req: Request) {
reEncryptSecrets(tempDb, importedKey);
}
+ const oversizedMedia = tempDb
+ .prepare('SELECT 1 FROM "media" WHERE length("content") > ? OR "size" > ? LIMIT 1')
+ .get(mediaUploadMaxSize.bytes, mediaUploadMaxSize.bytes);
+ if (oversizedMedia) {
+ return NextResponse.json({ error: "Backup contains media exceeding the 32 MiB limit" }, { status: 413 });
+ }
+
const homeBoardName = getHomeBoardName(tempDb);
tempDb.close();
diff --git a/apps/nextjs/src/app/api/user-medias/[id]/route.spec.ts b/apps/nextjs/src/app/api/user-medias/[id]/route.spec.ts
new file mode 100644
index 000000000..854277d09
--- /dev/null
+++ b/apps/nextjs/src/app/api/user-medias/[id]/route.spec.ts
@@ -0,0 +1,117 @@
+// @vitest-environment node
+
+import { NextRequest } from "next/server";
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const routeMocks = vi.hoisted(() => ({
+ findFirst: vi.fn(),
+ eq: vi.fn((_column: unknown, value: unknown) => value),
+}));
+
+vi.mock("@homarr/db", () => ({
+ db: { query: { medias: { findFirst: routeMocks.findFirst } } },
+ eq: routeMocks.eq,
+}));
+vi.mock("@homarr/db/schema", () => ({ medias: { id: "id" } }));
+
+import { GET } from "./route";
+
+const video = { content: Buffer.from("0123456789"), contentType: "video/mp4" };
+
+const requestAsync = (id: string, headers: Record<string, string> = {}) =>
+ GET(new NextRequest(`http://localhost/api/user-medias/${id}`, { headers }), {
+ params: Promise.resolve({ id }),
+ });
+
+describe("GET /api/user-medias/[id]", () => {
+ beforeEach(() => {
+ routeMocks.findFirst.mockReset();
+ routeMocks.findFirst.mockResolvedValue(video);
+ });
+
+ test("looks a video up by the id in front of its extension", async () => {
+ await requestAsync("abc.mp4");
+
+ expect(routeMocks.eq).toHaveBeenLastCalledWith(expect.anything(), "abc");
+ });
+
+ test("sends the whole file and advertises byte ranges", async () => {
+ const response = await requestAsync("abc.mp4");
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Accept-Ranges")).toBe("bytes");
+ expect(await response.text()).toBe("0123456789");
+ });
+
+ test.each([
+ ["bytes=2-5", "2345", "bytes 2-5/10"],
+ ["bytes=7-", "789", "bytes 7-9/10"],
+ ["bytes=-3", "789", "bytes 7-9/10"],
+ ["bytes=8-100", "89", "bytes 8-9/10"],
+ ])("answers %s with the requested bytes", async (range, body, contentRange) => {
+ const response = await requestAsync("abc.mp4", { range });
+
+ expect(response.status).toBe(206);
+ expect(response.headers.get("Content-Range")).toBe(contentRange);
+ expect(response.headers.get("Content-Length")).toBe(body.length.toString());
+ expect(await response.text()).toBe(body);
+ });
+
+ test("rejects a range past the end", async () => {
+ const response = await requestAsync("abc.mp4", { range: "bytes=10-" });
+
+ expect(response.status).toBe(416);
+ expect(response.headers.get("Content-Range")).toBe("bytes */10");
+ });
+
+ test("sends the whole file for a range it does not support", async () => {
+ const response = await requestAsync("abc.mp4", { range: "bytes=0-1,4-5" });
+
+ expect(response.status).toBe(200);
+ });
+
+ test("sends the requested bytes when If-Range matches the current ETag", async () => {
+ const etag = (await requestAsync("abc.mp4")).headers.get("ETag") ?? "";
+
+ const response = await requestAsync("abc.mp4", { range: "bytes=2-5", "if-range": etag });
+
+ expect(response.status).toBe(206);
+ });
+
+ test("sends the whole file when If-Range no longer matches", async () => {
+ const response = await requestAsync("abc.mp4", { range: "bytes=2-5", "if-range": '"outdated"' });
+
+ expect(response.status).toBe(200);
+ expect(await response.text()).toBe("0123456789");
+ });
+
+ test("ignores ranges on an empty file", async () => {
+ routeMocks.findFirst.mockResolvedValue({ content: Buffer.alloc(0), contentType: "video/mp4" });
+
+ const response = await requestAsync("abc.mp4", { range: "bytes=-1" });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Content-Range")).toBeNull();
+ });
+
+ test("still answers a matching ETag with 304", async () => {
+ const first = await requestAsync("abc.mp4");
+ const etag = first.headers.get("ETag") ?? "";
+
+ const response = await requestAsync("abc.mp4", { "if-none-match": etag });
+
+ expect(response.status).toBe(304);
+ });
+
+ test("always sends a sanitized SVG whole", async () => {
+ routeMocks.findFirst.mockResolvedValue({
+ content: Buffer.from('<svg xmlns="http://www.w3.org/2000/svg"></svg>'),
+ contentType: "image/svg+xml",
+ });
+
+ const response = await requestAsync("logo", { range: "bytes=0-3" });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get("Accept-Ranges")).toBeNull();
+ });
+});
diff --git a/apps/nextjs/src/app/api/user-medias/[id]/route.ts b/apps/nextjs/src/app/api/user-medias/[id]/route.ts
index 2b0b4ffa5..b23acf0d6 100644
--- a/apps/nextjs/src/app/api/user-medias/[id]/route.ts
+++ b/apps/nextjs/src/app/api/user-medias/[id]/route.ts
@@ -48,10 +48,57 @@ const hasMatchingValidator = (ifNoneMatch: string | null, etag: string) => {
return false;
};
+const parseRange = (header: string | null, size: number) => {
+ if (size === 0) return null;
+ const match = header?.trim().match(/^bytes=(\d*)-(\d*)$/i);
+ if (!match) return null;
+ const [, startText = "", endText = ""] = match;
+ if (startText === "" && endText === "") return null;
+
+ if (startText === "") {
+ const length = Number(endText);
+ if (length === 0) return "unsatisfiable";
+ return { start: Math.max(0, size - length), end: size - 1 };
+ }
+
+ const start = Number(startText);
+ if (endText !== "" && Number(endText) < start) return null;
+ const end = endText === "" ? size - 1 : Math.min(Number(endText), size - 1);
+ if (start >= size || end < start) return "unsatisfiable";
+ return { start, end };
+};
+
+const createMediaHeaders = (contentType: string) => {
+ const headers = new Headers();
+ headers.set("Cache-Control", "private, no-cache");
+ headers.set("Content-Type", contentType);
+ headers.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
+ headers.set("X-Content-Type-Options", "nosniff");
+ if (contentType !== "image/svg+xml" && contentType !== "image/svg") {
+ headers.set("Accept-Ranges", "bytes");
+ }
+ return headers;
+};
+
+export async function HEAD(request: NextRequest, props: { params: Promise<{ id: string }> }) {
+ if (request.headers.has("if-none-match")) return GET(request, props);
+ const { id } = await props.params;
+ const media = await db.query.medias.findFirst({
+ where: eq(medias.id, id.replace(/\.(mp4|webm)$/i, "")),
+ columns: { contentType: true, size: true },
+ });
+ if (!media) notFound();
+
+ const headers = createMediaHeaders(media.contentType);
+ if (headers.has("Accept-Ranges")) headers.set("Content-Length", media.size.toString());
+ return new NextResponse(null, { status: 200, headers });
+}
+
export async function GET(request: NextRequest, props: { params: Promise<{ id: string }> }) {
const params = await props.params;
+ const id = params.id.replace(/\.(mp4|webm)$/i, "");
const image = await db.query.medias.findFirst({
- where: eq(medias.id, params.id),
+ where: eq(medias.id, id),
columns: {
content: true,
contentType: true,
@@ -62,32 +109,46 @@ export async function GET(request: NextRequest, props: { params: Promise<{ id: s
notFound();
}
- let content = new Uint8Array(image.content);
+ let content = image.content;
+ const isSvg = image.contentType === "image/svg+xml" || image.contentType === "image/svg";
// Sanitize SVG content to prevent XSS attacks
- if (image.contentType === "image/svg+xml" || image.contentType === "image/svg") {
+ if (isSvg) {
const svgText = new TextDecoder().decode(content);
const sanitized = sanitize(svgText, {
USE_PROFILES: { svg: true, svgFilters: true },
});
- content = new TextEncoder().encode(sanitized);
+ content = Buffer.from(sanitized);
}
- const headers = new Headers();
+ const headers = createMediaHeaders(image.contentType);
const etag = `"${createHash("sha256").update(content).digest("base64url")}"`;
- headers.set("Cache-Control", "private, no-cache");
headers.set("ETag", etag);
- headers.set("Content-Type", image.contentType);
headers.set("Content-Length", content.length.toString());
- headers.set("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; sandbox");
- headers.set("X-Content-Type-Options", "nosniff");
if (hasMatchingValidator(request.headers.get("if-none-match"), etag)) {
headers.delete("Content-Length");
return new NextResponse(null, { status: 304, headers });
}
- return new NextResponse(content, {
+ if (request.method === "HEAD") return new NextResponse(null, { status: 200, headers });
+
+ const ifRange = request.headers.get("if-range");
+ if (!isSvg && (ifRange === null || ifRange.trim() === etag)) {
+ const range = parseRange(request.headers.get("range"), content.length);
+ if (range === "unsatisfiable") {
+ headers.set("Content-Length", "0");
+ headers.set("Content-Range", `bytes */${content.length}`);
+ return new NextResponse(null, { status: 416, headers });
+ }
+ if (range) {
+ headers.set("Content-Range", `bytes ${range.start}-${range.end}/${content.length}`);
+ headers.set("Content-Length", (range.end - range.start + 1).toString());
+ return new NextResponse(new Uint8Array(content.subarray(range.start, range.end + 1)), { status: 206, headers });
+ }
+ }
+
+ return new NextResponse(new Uint8Array(content), {
status: 200,
headers,
});
diff --git a/apps/nextjs/src/components/layout/background.tsx b/apps/nextjs/src/components/layout/background.tsx
index 70efc6b14..a4c24b34f 100644
--- a/apps/nextjs/src/components/layout/background.tsx
+++ b/apps/nextjs/src/components/layout/background.tsx
@@ -1,21 +1,48 @@
import { usePathname } from "next/navigation";
import type { AppShellProps } from "@mantine/core";
+import { useReducedMotion } from "@mantine/hooks";
+import { useQuery } from "@tanstack/react-query";
import { useOptionalBoard } from "@homarr/boards/context";
const supportedVideoFormats = ["mp4", "webm", "ogg"];
-const isVideo = (url: string) => supportedVideoFormats.some((format) => url.toLowerCase().endsWith(`.${format}`));
+const isVideoUrl = (url: string) =>
+ supportedVideoFormats.some((format) => url.split(/[?#]/)[0]?.toLowerCase().endsWith(`.${format}`));
+
+export const useIsVideo = (url: string | null | undefined) => {
+ const canDetectContentType = Boolean(url && /^(\/|https?:\/\/)/.test(url));
+ const { data, isError } = useQuery({
+ queryKey: ["background-content-type", url],
+ enabled: canDetectContentType,
+ staleTime: Infinity,
+ retry: false,
+ queryFn: async ({ signal }) => {
+ const response = await fetch(url ?? "", {
+ method: "HEAD",
+ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]),
+ });
+ if (!response.ok) throw new Error(`Background HEAD request failed: ${response.status}`);
+ const contentType = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase();
+ if (!contentType || contentType === "application/octet-stream") return isVideoUrl(url ?? "");
+ return contentType.startsWith("video/");
+ },
+ });
+ if (!canDetectContentType) return false;
+ if (isError) return isVideoUrl(url ?? "");
+ return data;
+};
export const useOptionalBackgroundProps = (): Partial<AppShellProps> => {
const board = useOptionalBoard();
const pathname = usePathname();
+ const isVideo = useIsVideo(board?.backgroundImageUrl);
if (!board?.backgroundImageUrl) return {};
// Check if we are on a client board page
if (pathname.split("/").length > 3) return {};
- if (isVideo(board.backgroundImageUrl)) {
+ if (isVideo !== false) {
return {};
}
@@ -30,31 +57,33 @@ export const useOptionalBackgroundProps = (): Partial<AppShellProps> => {
export const BoardBackgroundVideo = () => {
const board = useOptionalBoard();
+ const isVideo = useIsVideo(board?.backgroundImageUrl);
+ const reducedMotion = useReducedMotion(true);
if (!board?.backgroundImageUrl) return null;
- if (!isVideo(board.backgroundImageUrl)) return null;
-
- const videoFormat = board.backgroundImageUrl.split(".").pop()?.toLowerCase();
-
- if (!videoFormat) return null;
+ if (!isVideo) return null;
return (
<video
- autoPlay
+ key={`${board.backgroundImageUrl}:${reducedMotion}`}
+ src={board.backgroundImageUrl}
+ autoPlay={!reducedMotion}
muted
loop
playsInline
+ preload="metadata"
aria-hidden="true"
style={{
- position: "fixed",
- width: "100vw",
- height: "100vh",
+ position: board.backgroundImageAttachment === "fixed" ? "fixed" : "absolute",
+ width: "100%",
+ height: "100%",
+ minHeight: "100vh",
top: 0,
left: 0,
objectFit: board.backgroundImageSize,
+ objectPosition: "center center",
+ pointerEvents: "none",
}}
- >
- <source src={board.backgroundImageUrl} type={`video/${videoFormat}`} />
- </video>
+ />
);
};
diff --git a/packages/api/src/router/medias/media-router.ts b/packages/api/src/router/medias/media-router.ts
index 7f12bb042..b5b45383b 100644
--- a/packages/api/src/router/medias/media-router.ts
+++ b/packages/api/src/router/medias/media-router.ts
@@ -5,7 +5,12 @@ import { createId } from "@homarr/common";
import type { InferInsertModel } from "@homarr/db";
import { and, desc, eq, like } from "@homarr/db";
import { iconRepositories, icons, medias } from "@homarr/db/schema";
-import { createLocalImageUrl, LOCAL_ICON_REPOSITORY_SLUG, mapMediaToIcon } from "@homarr/icons/local";
+import {
+ createLocalImageUrl,
+ createLocalMediaUrl,
+ LOCAL_ICON_REPOSITORY_SLUG,
+ mapMediaToIcon,
+} from "@homarr/icons/local";
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
import { mediaUploadSchema } from "@homarr/validation/media";
@@ -79,11 +84,15 @@ export const mediaRouter = createTRPCRouter({
where: eq(iconRepositories.slug, LOCAL_ICON_REPOSITORY_SLUG),
});
- const ids = files.map((file) => file.id);
- if (!localIconRepository) return ids;
+ const uploaded = insertMedias.map((media) => ({
+ id: media.id,
+ url: createLocalMediaUrl(media.id),
+ }));
+ const images = insertMedias.filter((media) => media.contentType.startsWith("image/"));
+ if (!localIconRepository || images.length === 0) return uploaded;
await ctx.db.insert(icons).values(
- insertMedias.map((media) => {
+ images.map((media) => {
const icon = mapMediaToIcon(media);
return {
@@ -96,7 +105,7 @@ export const mediaRouter = createTRPCRouter({
}),
);
- return ids;
+ return uploaded;
}),
deleteMedia: protectedProcedure.input(byIdSchema).mutation(async ({ ctx, input }) => {
const dbMedia = await ctx.db.query.medias.findFirst({
diff --git a/packages/api/src/router/test/media.spec.ts b/packages/api/src/router/test/media.spec.ts
new file mode 100644
index 000000000..867a98167
--- /dev/null
+++ b/packages/api/src/router/test/media.spec.ts
@@ -0,0 +1,62 @@
+// @vitest-environment node
+
+import { describe, expect, test } from "vitest";
+
+import type { Session } from "@homarr/auth";
+import { createId } from "@homarr/common";
+import { iconRepositories, icons, medias, users } from "@homarr/db/schema";
+import { createDb } from "@homarr/db/test";
+
+import { mediaRouter } from "../medias/media-router";
+
+const createSession = (userId: string): Session => ({
+ user: { id: userId, permissions: ["media-upload"], colorScheme: "light" },
+ expires: new Date().toISOString(),
+});
+
+const setupAsync = async () => {
+ const db = createDb();
+ const userId = createId();
+ await db.insert(users).values({ id: userId });
+ await db.insert(iconRepositories).values({ id: createId(), slug: "local" });
+ const caller = mediaRouter.createCaller({ db, deviceType: undefined, session: createSession(userId) });
+ return { db, caller };
+};
+
+const upload = (...files: File[]) => {
+ const formData = new FormData();
+ files.forEach((file) => formData.append("files", file));
+ return formData;
+};
+
+describe("uploadMedia", () => {
+ test("stores a video as media with a canonical url, but not as an icon", async () => {
+ const { db, caller } = await setupAsync();
+
+ const [uploaded] = await caller.uploadMedia(
+ upload(
+ new File(
+ [new Uint8Array([0, 0, 0, 16, 102, 116, 121, 112, 105, 115, 111, 109, 0, 0, 0, 0])],
+ "background.mp4",
+ { type: "video/mp4" },
+ ),
+ ),
+ );
+
+ expect(uploaded?.url).toBe(`/api/user-medias/${uploaded?.id}`);
+ expect(await db.select().from(medias)).toHaveLength(1);
+ expect(await db.select().from(icons)).toHaveLength(0);
+ });
+
+ test("stores an image as media and as a local icon", async () => {
+ const { db, caller } = await setupAsync();
+
+ const [uploaded] = await caller.uploadMedia(
+ upload(new File([new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10])], "logo.png", { type: "image/png" })),
+ );
+
+ expect(uploaded?.url).toBe(`/api/user-medias/${uploaded?.id}`);
+ const storedIcons = await db.select().from(icons);
+ expect(storedIcons.map((icon) => icon.url)).toEqual([uploaded?.url]);
+ });
+});
diff --git a/packages/forms-collection/src/upload-media/upload-media.tsx b/packages/forms-collection/src/upload-media/upload-media.tsx
index 9da7a52d1..01eafe46c 100644
--- a/packages/forms-collection/src/upload-media/upload-media.tsx
+++ b/packages/forms-collection/src/upload-media/upload-media.tsx
@@ -5,25 +5,27 @@ import { clientApi } from "@homarr/api/client";
import type { MaybePromise } from "@homarr/common/types";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useI18n } from "@homarr/translation/client";
-import { supportedMediaUploadFormats } from "@homarr/validation/media";
+import { mediaUploadMaxSize, supportedImageUploadFormats } from "@homarr/validation/media";
interface UploadMediaProps {
children: (props: { onClick: () => void; loading: boolean }) => JSX.Element;
multiple?: boolean;
+ accept?: string[];
onSettled?: () => MaybePromise<void>;
onSuccess?: (media: { id: string; url: string }[]) => MaybePromise<void>;
}
-export const UploadMedia = ({ children, onSettled, onSuccess, multiple = false }: UploadMediaProps) => {
+export const UploadMedia = ({
+ children,
+ onSettled,
+ onSuccess,
+ multiple = false,
+ accept = supportedImageUploadFormats,
+}: UploadMediaProps) => {
const t = useI18n();
const { mutateAsync, isPending } = clientApi.media.uploadMedia.useMutation({
- async onSuccess(mediaIds) {
- await onSuccess?.(
- mediaIds.map((id) => ({
- id,
- url: `/api/user-medias/${id}`,
- })),
- );
+ async onSuccess(uploaded) {
+ await onSuccess?.(uploaded);
},
async onSettled() {
await onSettled?.();
@@ -33,6 +35,12 @@ export const UploadMedia = ({ children, onSettled, onSuccess, multiple = false }
const handleFileUploadAsync = async (files: File[] | File | null) => {
if (!files || (Array.isArray(files) && files.length === 0)) return;
const filesArray: File[] = Array.isArray(files) ? files : [files];
+ if (filesArray.some((file) => file.size > mediaUploadMaxSize.bytes)) {
+ showErrorNotification({
+ message: t("common.zod.errors.custom.fileTooLarge", { maxSize: mediaUploadMaxSize.label }),
+ });
+ return;
+ }
const formData = new FormData();
filesArray.forEach((file) => formData.append("files", file));
await mutateAsync(formData, {
@@ -50,7 +58,7 @@ export const UploadMedia = ({ children, onSettled, onSuccess, multiple = false }
};
return (
- <FileButton onChange={handleFileUploadAsync} accept={supportedMediaUploadFormats.join(",")} multiple={multiple}>
+ <FileButton onChange={handleFileUploadAsync} accept={accept.join(",")} multiple={multiple}>
{({ onClick }) => children({ onClick, loading: isPending })}
</FileButton>
);
diff --git a/packages/icons/package.json b/packages/icons/package.json
index d4e526e63..f4c2437a0 100644
--- a/packages/icons/package.json
+++ b/packages/icons/package.json
@@ -13,7 +13,8 @@
},
"exports": {
".": "./index.ts",
- "./local": "./src/local.ts"
+ "./local": "./src/local.ts",
+ "./local-media-url": "./src/local-media-url.ts"
},
"scripts": {
"clean": "rm -rf .turbo node_modules",
diff --git a/packages/icons/src/local-media-url.ts b/packages/icons/src/local-media-url.ts
new file mode 100644
index 000000000..ec5567e2d
--- /dev/null
+++ b/packages/icons/src/local-media-url.ts
@@ -0,0 +1,2 @@
+export const createLocalImageUrl = (id: string) => `/api/user-medias/${id}`;
+export const createLocalMediaUrl = createLocalImageUrl;
diff --git a/packages/icons/src/local.ts b/packages/icons/src/local.ts
index a7ca63c45..c6770b4e8 100644
--- a/packages/icons/src/local.ts
+++ b/packages/icons/src/local.ts
@@ -1 +1,2 @@
-export { createLocalImageUrl, mapMediaToIcon, LOCAL_ICON_REPOSITORY_SLUG } from "./repositories/local.icon-repository";
+export { createLocalImageUrl, createLocalMediaUrl } from "./local-media-url";
+export { mapMediaToIcon, LOCAL_ICON_REPOSITORY_SLUG } from "./repositories/local.icon-repository";
diff --git a/packages/icons/src/repositories/local.icon-repository.ts b/packages/icons/src/repositories/local.icon-repository.ts
index c0d9a5b27..42bcb2538 100644
--- a/packages/icons/src/repositories/local.icon-repository.ts
+++ b/packages/icons/src/repositories/local.icon-repository.ts
@@ -1,9 +1,10 @@
import { createHash } from "crypto";
import type { InferSelectModel } from "@homarr/db";
-import { db } from "@homarr/db";
+import { db, like } from "@homarr/db";
import type { medias } from "@homarr/db/schema";
+import { createLocalImageUrl } from "../local-media-url";
import type { RepositoryIcon, RepositoryIconGroup } from "../types";
import { IconRepository } from "./icon-repository";
@@ -14,7 +15,7 @@ export class LocalIconRepository extends IconRepository {
super("Local", LOCAL_ICON_REPOSITORY_SLUG, undefined, undefined, undefined, undefined);
}
protected async getAllIconsInternalAsync(): Promise<RepositoryIconGroup> {
- const medias = await db.query.medias.findMany();
+ const medias = await db.query.medias.findMany({ where: (media) => like(media.contentType, "image/%") });
return {
success: true,
icons: medias.map(mapMediaToIcon),
@@ -23,8 +24,6 @@ export class LocalIconRepository extends IconRepository {
}
}
-export const createLocalImageUrl = (id: string) => `/api/user-medias/${id}`;
-
export const mapMediaToIcon = (
media: Pick<InferSelectModel<typeof medias>, "name" | "id" | "content" | "size">,
): RepositoryIcon => ({
diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.json
index f9e6024bf..b3a439d7f 100644
--- a/packages/translation/src/lang/en.json
+++ b/packages/translation/src/lang/en.json
@@ -6314,11 +6314,11 @@
"label": "Favicon image URL"
},
"backgroundImageUrl": {
- "label": "Background image URL",
- "placeholder": "Start typing to search local images",
+ "label": "Background image or video URL",
+ "placeholder": "Start typing to search local images and videos",
"group": {
- "your": "Your images",
- "other": "Other images"
+ "your": "Your media",
+ "other": "Other media"
}
},
"backgroundImageAttachment": {
@@ -6356,15 +6356,15 @@
}
},
"backgroundImageSize": {
- "label": "Background image size",
+ "label": "Background size",
"option": {
"cover": {
"label": "Cover",
- "description": "Scales the image as small as possible to cover the entire window by cropping excessive space."
+ "description": "Scales the background as small as possible to cover the entire window by cropping excessive space."
},
"contain": {
"label": "Contain",
- "description": "Scales the image as large as possible within its container without cropping or stretching the image."
+ "description": "Scales the background as large as possible within its container without cropping or stretching it."
}
}
},
diff --git a/packages/validation/src/media.ts b/packages/validation/src/media.ts
index 3f7cdcf6a..021c4001a 100644
--- a/packages/validation/src/media.ts
+++ b/packages/validation/src/media.ts
@@ -3,12 +3,49 @@ import { zfd } from "zod-form-data";
import { createCustomErrorParams } from "./form/i18n";
-export const supportedMediaUploadFormats = ["image/png", "image/jpeg", "image/webp", "image/gif", "image/svg+xml"];
+export const supportedImageUploadFormats = ["image/png", "image/jpeg", "image/webp", "image/gif", "image/svg+xml"];
+export const supportedVideoUploadFormats = ["video/mp4", "video/webm"];
+export const supportedMediaUploadFormats = [...supportedImageUploadFormats, ...supportedVideoUploadFormats];
+
+export const mediaUploadMaxSize = { bytes: 1024 * 1024 * 32, label: "32 MiB" };
+
+const matchesMediaContentType = (header: Uint8Array, contentType: string) => {
+ const startsWith = (...bytes: number[]) => bytes.every((value, index) => header[index] === value);
+ if (contentType === "image/png") return startsWith(0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a);
+ if (contentType === "image/jpeg") return startsWith(0xff, 0xd8, 0xff);
+ const text = new TextDecoder("latin1").decode(header);
+ if (contentType === "image/gif") return ["GIF87a", "GIF89a"].includes(text.slice(0, 6));
+ if (contentType === "image/webp") return text.startsWith("RIFF") && text.slice(8, 12) === "WEBP";
+ if (contentType === "image/svg+xml") return true;
+ if (contentType === "video/mp4") {
+ if (text.slice(4, 8) !== "ftyp" || header.length < 16) return false;
+ const boxSize = new DataView(header.buffer, header.byteOffset, header.byteLength).getUint32(0);
+ if (boxSize < 16 || boxSize > header.length) return false;
+ for (let offset = 8; offset + 4 <= boxSize; offset += 4) {
+ if (offset === 12) continue;
+ if (/^(isom|iso[2-9]|mp4[12]|avc1|dash|M4V |MSNV)$/.test(text.slice(offset, offset + 4))) return true;
+ }
+ return false;
+ }
+ return (
+ header[0] === 0x1a &&
+ header[1] === 0x45 &&
+ header[2] === 0xdf &&
+ header[3] === 0xa3 &&
+ header.some(
+ (value, index) =>
+ value === 0x42 &&
+ header[index + 1] === 0x82 &&
+ header[index + 2] === 0x84 &&
+ text.slice(index + 3, index + 7) === "webm",
+ )
+ );
+};
export const mediaUploadSchema = zfd.formData({
files: zfd.repeatable(
z.array(
- zfd.file().check((context) => {
+ zfd.file().check(async (context) => {
if (!supportedMediaUploadFormats.includes(context.value.type)) {
context.issues.push({
code: "custom",
@@ -21,18 +58,29 @@ export const mediaUploadSchema = zfd.formData({
return;
}
- if (context.value.size > 1024 * 1024 * 32) {
- // Don't forget to update the limit in nginx.conf (client_max_body_size)
+ if (context.value.size > mediaUploadMaxSize.bytes) {
context.issues.push({
code: "custom",
params: createCustomErrorParams({
key: "fileTooLarge",
- params: { maxSize: "32 MiB" },
+ params: { maxSize: mediaUploadMaxSize.label },
}),
input: context.value.size,
});
return;
}
+
+ const header = new Uint8Array(await context.value.slice(0, 4096).arrayBuffer());
+ if (!matchesMediaContentType(header, context.value.type)) {
+ context.issues.push({
+ code: "custom",
+ params: createCustomErrorParams({
+ key: "invalidFileType",
+ params: { expected: `one of ${supportedMediaUploadFormats.join(", ")}` },
+ }),
+ input: context.value.type,
+ });
+ }
}),
),
),