Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
525eda3cbb | ||
|
|
d0709a684c | ||
|
|
cf075040e8 |
No files matched your search
@@ -70,16 +70,4 @@ API key authentication enables programmatic access for:
|
||||
- Automation scripts and CI/CD pipelines
|
||||
- Third-party integrations
|
||||
- Custom dashboards and monitoring tools
|
||||
- Container orchestration systems that need to sync app definitions
|
||||
|
||||
## Board Automation
|
||||
|
||||
The OpenAPI and MCP APIs include board management endpoints for common automation workflows:
|
||||
|
||||
- Create, duplicate, rename and delete boards
|
||||
- Change board visibility
|
||||
- Update board visual and behavior settings
|
||||
- Set desktop and mobile home boards for the current user
|
||||
- Configure global board defaults such as public home boards and status behavior
|
||||
|
||||
Use the interactive API reference to inspect the exact request body for each endpoint under the `boards` and `settings` tags.
|
||||
- Container orchestration systems that need to sync app definitions
|
||||
+1
-1
@@ -1 +1 @@
|
||||
{"openapi":"3.1.0","info":{"title":"Homarr API documentation","version":"1.1.0"},"servers":[{"url":"http://localhost:3000"}],"externalDocs":{"url":"https://homarr.dev"},"paths":{"/api/apps/paginated":{"get":{"operationId":"appRouter-getPaginated","tags":["apps"],"security":[{"apikey":[]}],"parameters":[{"in":"query","name":"search","schema":{"type":"string"}},{"in":"query","name":"pageSize","schema":{"default":10,"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991}},{"in":"query","name":"page","schema":{"default":1,"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}},"totalCount":{"type":"number"}},"required":["items","totalCount"],"additionalProperties":false}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.BAD_REQUEST"}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"404":{"description":"Not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.NOT_FOUND"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}}},"/api/apps":{"get":{"operationId":"appRouter-all","tags":["apps"],"security":[{"apikey":[]}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}},"post":{"operationId":"appRouter-create","tags":["apps"],"security":[{"apikey":[]}],"parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":64},"description":{"anyOf":[{"type":"string","maxLength":512},{"type":"null"}]},"iconUrl":{"type":"string","minLength":1},"href":{"anyOf":[{"anyOf":[{"type":"string","pattern":"^(?!javascript)[a-zA-Z]*:\\/\\/"},{"type":"string","const":""}]},{"type":"null"}]},"pingUrl":{"anyOf":[{"anyOf":[{"type":"string","pattern":"^https?:\\/\\/"},{"type":"string","const":""}]},{"type":"null"}]}},"required":["name","description","iconUrl","href","pingUrl"]}}}},"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"allOf":[{"type":"object","properties":{"appId":{"type":"string"}},"required":["appId"],"additionalProperties":false},{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}]}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.BAD_REQUEST"}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}}},"/api/apps/search":{"get":{"operationId":"appRouter-search","tags":["apps"],"security":[{"apikey":[]}],"parameters":[{"in":"query","name":"query","schema":{"type":"string"},"required":true},{"in":"queLine truncated
|
||||
{"openapi":"3.1.0","info":{"title":"Homarr API documentation","version":"1.0.0"},"servers":[{"url":"http://localhost:3000"}],"externalDocs":{"url":"https://homarr.dev"},"paths":{"/api/apps/paginated":{"get":{"operationId":"appRouter-getPaginated","tags":["apps"],"security":[{"apikey":[]}],"parameters":[{"in":"query","name":"search","schema":{"type":"string"}},{"in":"query","name":"pageSize","schema":{"default":10,"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991}},{"in":"query","name":"page","schema":{"default":1,"type":"integer","exclusiveMinimum":0,"maximum":9007199254740991}}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"object","properties":{"items":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}},"totalCount":{"type":"number"}},"required":["items","totalCount"],"additionalProperties":false}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.BAD_REQUEST"}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"404":{"description":"Not found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.NOT_FOUND"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}}},"/api/apps":{"get":{"operationId":"appRouter-all","tags":["apps"],"security":[{"apikey":[]}],"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"type":"array","items":{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}},"post":{"operationId":"appRouter-create","tags":["apps"],"security":[{"apikey":[]}],"parameters":[],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","properties":{"name":{"type":"string","minLength":1,"maxLength":64},"description":{"anyOf":[{"type":"string","maxLength":512},{"type":"null"}]},"iconUrl":{"type":"string","minLength":1},"href":{"anyOf":[{"anyOf":[{"type":"string","pattern":"^(?!javascript)[a-zA-Z]*:\\/\\/"},{"type":"string","const":""}]},{"type":"null"}]},"pingUrl":{"anyOf":[{"anyOf":[{"type":"string","pattern":"^https?:\\/\\/"},{"type":"string","const":""}]},{"type":"null"}]}},"required":["name","description","iconUrl","href","pingUrl"]}}}},"responses":{"200":{"description":"Successful response","content":{"application/json":{"schema":{"allOf":[{"type":"object","properties":{"appId":{"type":"string"}},"required":["appId"],"additionalProperties":false},{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"description":{"anyOf":[{"type":"string"},{"type":"null"}]},"iconUrl":{"type":"string"},"href":{"anyOf":[{"type":"string"},{"type":"null"}]},"pingUrl":{"anyOf":[{"type":"string"},{"type":"null"}]}},"required":["id","name","description","iconUrl","href","pingUrl"],"additionalProperties":false}]}}}},"400":{"description":"Invalid input data","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.BAD_REQUEST"}}}},"401":{"description":"Authorization not provided","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.UNAUTHORIZED"}}}},"403":{"description":"Insufficient access","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.FORBIDDEN"}}}},"500":{"description":"Internal server error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/error.INTERNAL_SERVER_ERROR"}}}}}}},"/api/apps/search":{"get":{"operationId":"appRouter-search","tags":["apps"],"security":[{"apikey":[]}],"parameters":[{"in":"query","name":"query","schema":{"type":"string"},"required":true},{"in":"queLine truncated
|
||||
@@ -1,22 +1,39 @@
|
||||
import { createAsyncStoragePersister } from "@tanstack/query-async-storage-persister";
|
||||
import { TRPCClientError } from "@trpc/client";
|
||||
import superjson from "superjson";
|
||||
|
||||
import { fetchApi } from "@homarr/api/client";
|
||||
import { getActiveQueryCacheBoardId, queryCacheStoragePrefix } from "@homarr/api/query-cache";
|
||||
|
||||
// Set once the server rejects a persist mutation as read-only (demo mode),
|
||||
// so we stop retrying a mutation that can never succeed.
|
||||
let persistDisabled = false;
|
||||
|
||||
const isReadOnlyError = (error: unknown) => error instanceof TRPCClientError && error.data?.code === "FORBIDDEN";
|
||||
|
||||
const queryCacheStorage = {
|
||||
getItem: (_key: string) => null as string | null,
|
||||
async setItem(_key: string, value: string) {
|
||||
if (persistDisabled) return;
|
||||
const boardId = getActiveQueryCacheBoardId();
|
||||
if (!boardId) return;
|
||||
await fetchApi.queryCache.setItem.mutate({ boardId, value }).catch((error) => {
|
||||
if (isReadOnlyError(error)) {
|
||||
persistDisabled = true;
|
||||
return;
|
||||
}
|
||||
console.warn("[query-cache] persist failed", error);
|
||||
});
|
||||
},
|
||||
async removeItem(_key: string) {
|
||||
if (persistDisabled) return;
|
||||
const boardId = getActiveQueryCacheBoardId();
|
||||
if (!boardId) return;
|
||||
await fetchApi.queryCache.removeItem.mutate({ boardId }).catch((error) => {
|
||||
if (isReadOnlyError(error)) {
|
||||
persistDisabled = true;
|
||||
return;
|
||||
}
|
||||
console.warn("[query-cache] remove failed", error);
|
||||
});
|
||||
},
|
||||
|
||||
@@ -7,6 +7,7 @@ import "~/styles/gridstack.scss";
|
||||
|
||||
import { dehydrate, HydrationBoundary } from "@tanstack/react-query";
|
||||
import type { PersistedClient } from "@tanstack/react-query-persist-client";
|
||||
import SuperJSON from "superjson";
|
||||
import { getQueryClient } from "@homarr/api/server";
|
||||
import { IntegrationProvider } from "@homarr/auth/client";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
@@ -121,7 +122,7 @@ async function QueryCacheHydration({ userId, boardId }: { userId: string; boardI
|
||||
const serialized = await getQueryCacheAsync(userId, boardId);
|
||||
if (!serialized) return null;
|
||||
|
||||
const persisted = JSON.parse(serialized) as PersistedClient;
|
||||
const persisted = SuperJSON.parse<PersistedClient>(serialized);
|
||||
if (!persisted?.clientState?.queries?.length) return null;
|
||||
|
||||
return <HydrationBoundary state={persisted.clientState} />;
|
||||
|
||||
@@ -9,7 +9,6 @@ import { iconsRouter } from "./router/icons";
|
||||
import { infoRouter } from "./router/info";
|
||||
import { integrationRouter } from "./router/integration/integration-router";
|
||||
import { inviteRouter } from "./router/invite";
|
||||
import { serverSettingsRouter } from "./router/serverSettings";
|
||||
import { beszelRouter } from "./router/widgets/beszel";
|
||||
import { calendarRouter } from "./router/widgets/calendar";
|
||||
import { dnsHoleRouter } from "./router/widgets/dns-hole";
|
||||
@@ -29,7 +28,6 @@ export const mcpRouter = createTRPCRouter({
|
||||
info: infoRouter,
|
||||
integration: integrationRouter,
|
||||
invite: inviteRouter,
|
||||
serverSettings: serverSettingsRouter,
|
||||
beszel: beszelRouter,
|
||||
calendar: calendarRouter,
|
||||
dnsHole: dnsHoleRouter,
|
||||
|
||||
@@ -6,7 +6,6 @@ import { appRouter } from "./router/app";
|
||||
import { boardRouter } from "./router/board";
|
||||
import { infoRouter } from "./router/info";
|
||||
import { inviteRouter } from "./router/invite";
|
||||
import { serverSettingsRouter } from "./router/serverSettings";
|
||||
import { userRouter } from "./router/user";
|
||||
import { createTRPCRouter } from "./trpc";
|
||||
|
||||
@@ -15,14 +14,13 @@ export const openApiRouter = createTRPCRouter({
|
||||
boardRouter,
|
||||
infoRouter,
|
||||
inviteRouter,
|
||||
serverSettingsRouter,
|
||||
userRouter,
|
||||
});
|
||||
|
||||
export const openApiDocument = (base: string) =>
|
||||
generateOpenApiDocument(openApiRouter, {
|
||||
title: "Homarr API documentation",
|
||||
version: "1.1.0",
|
||||
version: "1.0.0",
|
||||
baseUrl: base,
|
||||
docsUrl: "https://homarr.dev",
|
||||
securitySchemes: {
|
||||
|
||||
@@ -330,16 +330,7 @@ export const boardRouter = createTRPCRouter({
|
||||
}),
|
||||
duplicateBoard: permissionRequiredProcedure
|
||||
.requiresPermission("board-create")
|
||||
.meta({
|
||||
openapi: { method: "POST", path: "/api/boards/{id}/duplicate", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Duplicate an existing board into a new board. Requires board-create permission and view permission on the source board. REQUIRED: id (source board ID), name (unique name for the new board). Returns { boardId }",
|
||||
},
|
||||
})
|
||||
.input(boardDuplicateSchema)
|
||||
.output(z.object({ boardId: z.string() }))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "view");
|
||||
await noBoardWithSimilarNameAsync(ctx.db, input.name);
|
||||
@@ -553,57 +544,33 @@ export const boardRouter = createTRPCRouter({
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
return { boardId: newBoardId };
|
||||
}),
|
||||
renameBoard: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/name", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Rename a board by ID. Requires full permission on the board. REQUIRED: id (board ID), name (new unique board name)",
|
||||
},
|
||||
})
|
||||
.input(boardRenameSchema)
|
||||
.output(z.void())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full");
|
||||
renameBoard: protectedProcedure.input(boardRenameSchema).mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full");
|
||||
|
||||
await noBoardWithSimilarNameAsync(ctx.db, input.name, [input.id]);
|
||||
await noBoardWithSimilarNameAsync(ctx.db, input.name, [input.id]);
|
||||
|
||||
await ctx.db.update(boards).set({ name: input.name }).where(eq(boards.id, input.id));
|
||||
}),
|
||||
changeBoardVisibility: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/visibility", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Change board visibility. Requires full permission on the board. REQUIRED: id (board ID), visibility ('public' or 'private'). Home boards cannot be made private",
|
||||
},
|
||||
})
|
||||
.input(boardChangeVisibilitySchema)
|
||||
.output(z.void())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full");
|
||||
const boardSettings = await getServerSettingByKeyAsync(ctx.db, "board");
|
||||
await ctx.db.update(boards).set({ name: input.name }).where(eq(boards.id, input.id));
|
||||
}),
|
||||
changeBoardVisibility: protectedProcedure.input(boardChangeVisibilitySchema).mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "full");
|
||||
const boardSettings = await getServerSettingByKeyAsync(ctx.db, "board");
|
||||
|
||||
if (
|
||||
input.visibility !== "public" &&
|
||||
(boardSettings.homeBoardId === input.id || boardSettings.mobileHomeBoardId === input.id)
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Cannot make home board private",
|
||||
});
|
||||
}
|
||||
if (
|
||||
input.visibility !== "public" &&
|
||||
(boardSettings.homeBoardId === input.id || boardSettings.mobileHomeBoardId === input.id)
|
||||
) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: "Cannot make home board private",
|
||||
});
|
||||
}
|
||||
|
||||
await ctx.db
|
||||
.update(boards)
|
||||
.set({ isPublic: input.visibility === "public" })
|
||||
.where(eq(boards.id, input.id));
|
||||
}),
|
||||
await ctx.db
|
||||
.update(boards)
|
||||
.set({ isPublic: input.visibility === "public" })
|
||||
.where(eq(boards.id, input.id));
|
||||
}),
|
||||
deleteBoard: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "DELETE", path: "/api/boards/{id}", tags: ["boards"], protect: true },
|
||||
@@ -620,38 +587,16 @@ export const boardRouter = createTRPCRouter({
|
||||
|
||||
await ctx.db.delete(boards).where(eq(boards.id, input.id));
|
||||
}),
|
||||
setHomeBoard: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/home", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Set the current user's desktop home board. Requires view permission on the board. REQUIRED: id (board ID)",
|
||||
},
|
||||
})
|
||||
.input(z.object({ id: z.string() }))
|
||||
.output(z.void())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "view");
|
||||
setHomeBoard: protectedProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "view");
|
||||
|
||||
await ctx.db.update(users).set({ homeBoardId: input.id }).where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
setMobileHomeBoard: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/mobile-home", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Set the current user's mobile home board. Requires view permission on the board. REQUIRED: id (board ID)",
|
||||
},
|
||||
})
|
||||
.input(z.object({ id: z.string() }))
|
||||
.output(z.void())
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "view");
|
||||
await ctx.db.update(users).set({ homeBoardId: input.id }).where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
setMobileHomeBoard: protectedProcedure.input(z.object({ id: z.string() })).mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "view");
|
||||
|
||||
await ctx.db.update(users).set({ mobileHomeBoardId: input.id }).where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
await ctx.db.update(users).set({ mobileHomeBoardId: input.id }).where(eq(users.id, ctx.session.user.id));
|
||||
}),
|
||||
getHomeBoard: publicProcedure.query(async ({ ctx }) => {
|
||||
const userId = ctx.session?.user.id;
|
||||
const user = userId
|
||||
@@ -807,16 +752,7 @@ export const boardRouter = createTRPCRouter({
|
||||
}
|
||||
}),
|
||||
savePartialBoardSettings: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/boards/{id}/settings", tags: ["boards"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Update visual and behavior settings for a board. Requires modify permission. REQUIRED: id (board ID). Optional fields include pageTitle, metaTitle, logoImageUrl, faviconImageUrl, backgroundImageUrl, colors, opacity, customCss, itemRadius, and disableStatus",
|
||||
},
|
||||
})
|
||||
.input(boardSavePartialSettingsSchema.extend({ id: z.string() }))
|
||||
.output(z.void())
|
||||
.input(boardSavePartialSettingsSchema.and(z.object({ id: z.string() })))
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await throwIfActionForbiddenAsync(ctx, eq(boards.id, input.id), "modify");
|
||||
|
||||
|
||||
@@ -1,14 +1,6 @@
|
||||
import { TRPCError } from "@trpc/server";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { and, eq, inArray } from "@homarr/db";
|
||||
import {
|
||||
getServerSettingByKeyAsync,
|
||||
getServerSettingsAsync,
|
||||
insertServerSettingByKeyAsync,
|
||||
updateServerSettingByKeyAsync,
|
||||
} from "@homarr/db/queries";
|
||||
import { boards, serverSettings } from "@homarr/db/schema";
|
||||
import { getServerSettingByKeyAsync, getServerSettingsAsync, updateServerSettingByKeyAsync } from "@homarr/db/queries";
|
||||
import type { ServerSettings } from "@homarr/server-settings";
|
||||
import { defaultServerSettingsKeys } from "@homarr/server-settings";
|
||||
import { settingsInitSchema } from "@homarr/validation/settings";
|
||||
@@ -16,15 +8,6 @@ import { settingsInitSchema } from "@homarr/validation/settings";
|
||||
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, publicProcedure } from "../trpc";
|
||||
import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
|
||||
|
||||
const boardServerSettingsSchema = z.object({
|
||||
homeBoardId: z.string().nullable(),
|
||||
mobileHomeBoardId: z.string().nullable(),
|
||||
enableStatusByDefault: z.boolean(),
|
||||
forceDisableStatus: z.boolean(),
|
||||
}) satisfies z.ZodType<ServerSettings["board"]>;
|
||||
|
||||
const boardServerSettingsUpdateSchema = boardServerSettingsSchema.partial();
|
||||
|
||||
export const serverSettingsRouter = createTRPCRouter({
|
||||
getCulture: publicProcedure.query(async ({ ctx }) => {
|
||||
return await getServerSettingByKeyAsync(ctx.db, "culture");
|
||||
@@ -32,67 +15,6 @@ export const serverSettingsRouter = createTRPCRouter({
|
||||
getAll: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
|
||||
return await getServerSettingsAsync(ctx.db);
|
||||
}),
|
||||
getBoardSettings: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
openapi: { method: "GET", path: "/api/settings/board", tags: ["settings"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Get global board defaults, including desktop/mobile home board IDs and status behavior. Requires admin permission",
|
||||
},
|
||||
})
|
||||
.input(z.void())
|
||||
.output(boardServerSettingsSchema)
|
||||
.query(async ({ ctx }) => {
|
||||
return await getServerSettingByKeyAsync(ctx.db, "board");
|
||||
}),
|
||||
updateBoardSettings: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
openapi: { method: "PATCH", path: "/api/settings/board", tags: ["settings"], protect: true },
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description:
|
||||
"Update global board defaults. Requires admin permission. Optional fields: homeBoardId, mobileHomeBoardId, enableStatusByDefault, forceDisableStatus. Home board IDs must reference public boards or be null",
|
||||
},
|
||||
})
|
||||
.input(boardServerSettingsUpdateSchema)
|
||||
.output(boardServerSettingsSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const inputBoardIds = [input.homeBoardId, input.mobileHomeBoardId].filter(
|
||||
(id) => id !== undefined && id !== null,
|
||||
);
|
||||
|
||||
if (inputBoardIds.length > 0) {
|
||||
const publicBoards = await ctx.db.query.boards.findMany({
|
||||
columns: { id: true },
|
||||
where: and(inArray(boards.id, inputBoardIds), eq(boards.isPublic, true)),
|
||||
});
|
||||
const publicBoardIds = new Set(publicBoards.map((board) => board.id));
|
||||
const invalidBoardIds = inputBoardIds.filter((id) => !publicBoardIds.has(id));
|
||||
if (invalidBoardIds.length > 0) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `Board settings home board IDs must reference public boards: ${invalidBoardIds.join(", ")}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const current = await getServerSettingByKeyAsync(ctx.db, "board");
|
||||
const next = { ...current, ...input };
|
||||
const existing = await ctx.db.query.serverSettings.findFirst({
|
||||
where: eq(serverSettings.settingKey, "board"),
|
||||
});
|
||||
|
||||
if (existing) {
|
||||
await updateServerSettingByKeyAsync(ctx.db, "board", next);
|
||||
} else {
|
||||
await insertServerSettingByKeyAsync(ctx.db, "board", next);
|
||||
}
|
||||
|
||||
return next;
|
||||
}),
|
||||
saveSettings: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.input(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { stringify } from "superjson";
|
||||
import SuperJSON from "superjson";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { Session } from "@homarr/auth";
|
||||
import { createId } from "@homarr/common";
|
||||
import { boards, serverSettings } from "@homarr/db/schema";
|
||||
import { serverSettings } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import { defaultServerSettings, defaultServerSettingsKeys } from "@homarr/server-settings";
|
||||
|
||||
@@ -33,7 +33,7 @@ describe("getAll server settings", () => {
|
||||
await db.insert(serverSettings).values([
|
||||
{
|
||||
settingKey: defaultServerSettingsKeys[0],
|
||||
value: stringify(defaultServerSettings.analytics),
|
||||
value: SuperJSON.stringify(defaultServerSettings.analytics),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -67,7 +67,7 @@ describe("saveSettings", () => {
|
||||
await db.insert(serverSettings).values([
|
||||
{
|
||||
settingKey: defaultServerSettingsKeys[0],
|
||||
value: stringify(defaultServerSettings.analytics),
|
||||
value: SuperJSON.stringify(defaultServerSettings.analytics),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -82,7 +82,7 @@ describe("saveSettings", () => {
|
||||
expect(dbSettings).toStrictEqual([
|
||||
{
|
||||
settingKey: "analytics",
|
||||
value: stringify({
|
||||
value: SuperJSON.stringify({
|
||||
enableGeneral: true,
|
||||
instanceId: null,
|
||||
}),
|
||||
@@ -90,91 +90,3 @@ describe("saveSettings", () => {
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("board settings API", () => {
|
||||
test("getBoardSettings should return board defaults", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
|
||||
await expect(caller.getBoardSettings()).resolves.toStrictEqual(defaultServerSettings.board);
|
||||
});
|
||||
|
||||
test("updateBoardSettings should insert settings when defaults are not persisted", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
const boardId = createId();
|
||||
await db.insert(boards).values({ id: boardId, name: "default", isPublic: true });
|
||||
|
||||
const result = await caller.updateBoardSettings({
|
||||
homeBoardId: boardId,
|
||||
forceDisableStatus: true,
|
||||
});
|
||||
|
||||
expect(result).toStrictEqual({
|
||||
...defaultServerSettings.board,
|
||||
homeBoardId: boardId,
|
||||
forceDisableStatus: true,
|
||||
});
|
||||
const dbSettings = await db.select().from(serverSettings);
|
||||
expect(dbSettings).toStrictEqual([
|
||||
{
|
||||
settingKey: "board",
|
||||
value: stringify(result),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("updateBoardSettings should update existing settings", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
const boardId = createId();
|
||||
await db.insert(boards).values({ id: boardId, name: "default", isPublic: true });
|
||||
|
||||
await caller.updateBoardSettings({ homeBoardId: boardId });
|
||||
const result = await caller.updateBoardSettings({
|
||||
mobileHomeBoardId: boardId,
|
||||
enableStatusByDefault: false,
|
||||
});
|
||||
|
||||
expect(result).toStrictEqual({
|
||||
...defaultServerSettings.board,
|
||||
homeBoardId: boardId,
|
||||
mobileHomeBoardId: boardId,
|
||||
enableStatusByDefault: false,
|
||||
});
|
||||
const dbSettings = await db.select().from(serverSettings);
|
||||
expect(dbSettings).toStrictEqual([
|
||||
{
|
||||
settingKey: "board",
|
||||
value: stringify(result),
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("updateBoardSettings should reject private home boards", async () => {
|
||||
const db = createDb();
|
||||
const caller = serverSettingsRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: defaultSession,
|
||||
});
|
||||
const boardId = createId();
|
||||
await db.insert(boards).values({ id: boardId, name: "private", isPublic: false });
|
||||
|
||||
const actAsync = async () => await caller.updateBoardSettings({ homeBoardId: boardId });
|
||||
|
||||
await expect(actAsync()).rejects.toThrow("must reference public boards");
|
||||
});
|
||||
});
|
||||
@@ -2,20 +2,16 @@ import { expect, test, vi } from "vitest";
|
||||
import { extractToolsFromProcedures } from "trpc-to-mcp";
|
||||
|
||||
import { appRouter } from "../router/app";
|
||||
import { boardRouter } from "../router/board";
|
||||
import { infoRouter } from "../router/info";
|
||||
import { inviteRouter } from "../router/invite";
|
||||
import { serverSettingsRouter } from "../router/serverSettings";
|
||||
import { createTRPCRouter } from "../trpc";
|
||||
|
||||
vi.mock("@homarr/auth", () => ({}));
|
||||
|
||||
const mcpTestRouter = createTRPCRouter({
|
||||
app: appRouter,
|
||||
board: boardRouter,
|
||||
info: infoRouter,
|
||||
invite: inviteRouter,
|
||||
serverSettings: serverSettingsRouter,
|
||||
});
|
||||
|
||||
test("MCP tools should be extractable from the router", () => {
|
||||
@@ -32,12 +28,8 @@ test("MCP tools should contain expected procedures", () => {
|
||||
expect(toolNames).toContain("app_all");
|
||||
expect(toolNames).toContain("app_byId");
|
||||
expect(toolNames).toContain("app_create");
|
||||
expect(toolNames).toContain("board_savePartialBoardSettings");
|
||||
expect(toolNames).toContain("board_duplicateBoard");
|
||||
expect(toolNames).toContain("info_getInfo");
|
||||
expect(toolNames).toContain("invite_getAll");
|
||||
expect(toolNames).toContain("serverSettings_getBoardSettings");
|
||||
expect(toolNames).toContain("serverSettings_updateBoardSettings");
|
||||
});
|
||||
|
||||
test("MCP tools should have descriptions", () => {
|
||||
|
||||
@@ -14,12 +14,3 @@ test("OpenAPI documentation should be generated", () => {
|
||||
// Assert
|
||||
expect(act).not.toThrow();
|
||||
});
|
||||
|
||||
test("OpenAPI documentation should expose board automation endpoints", () => {
|
||||
const document = openApiDocument("https://homarr.dev");
|
||||
|
||||
expect(document.info.version).toBe("1.1.0");
|
||||
expect(document.paths).toHaveProperty("/api/boards/{id}/settings");
|
||||
expect(document.paths).toHaveProperty("/api/boards/{id}/duplicate");
|
||||
expect(document.paths).toHaveProperty("/api/settings/board");
|
||||
});
|
||||
@@ -60,8 +60,8 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/tags/connections"
|
||||
| "/docs/tags/custom-widgets"
|
||||
| "/docs/tags/customization"
|
||||
| "/docs/tags/data"
|
||||
| "/docs/tags/data-sources"
|
||||
| "/docs/tags/data"
|
||||
| "/docs/tags/database"
|
||||
| "/docs/tags/developer"
|
||||
| "/docs/tags/development"
|
||||
@@ -99,8 +99,8 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/tags/redis"
|
||||
| "/docs/tags/responsive"
|
||||
| "/docs/tags/roles"
|
||||
| "/docs/tags/search"
|
||||
| "/docs/tags/search-engines"
|
||||
| "/docs/tags/search"
|
||||
| "/docs/tags/secrets"
|
||||
| "/docs/tags/security"
|
||||
| "/docs/tags/self-signed"
|
||||
@@ -132,6 +132,15 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/advanced/running-as-different-user"
|
||||
| "/docs/advanced/single-sign-on"
|
||||
| "/docs/advanced/styling"
|
||||
| "/docs/category/advanced"
|
||||
| "/docs/category/community"
|
||||
| "/docs/category/developer-guides"
|
||||
| "/docs/category/getting-started"
|
||||
| "/docs/category/installation-1"
|
||||
| "/docs/category/installation"
|
||||
| "/docs/category/integrations"
|
||||
| "/docs/category/management"
|
||||
| "/docs/category/widgets"
|
||||
| "/docs/community/donate"
|
||||
| "/docs/community/faq"
|
||||
| "/docs/community/get-in-touch"
|
||||
@@ -196,11 +205,9 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/integrations/slskd"
|
||||
| "/docs/integrations/sonarr"
|
||||
| "/docs/integrations/speedtest-tracker"
|
||||
| "/docs/integrations/synology"
|
||||
| "/docs/integrations/tdarr"
|
||||
| "/docs/integrations/technitium-dns"
|
||||
| "/docs/integrations/tracearr"
|
||||
| "/docs/integrations/traefik"
|
||||
| "/docs/integrations/transmission"
|
||||
| "/docs/integrations/truenas"
|
||||
| "/docs/integrations/umami"
|
||||
@@ -259,11 +266,9 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/widgets/smart-home-execute-automation"
|
||||
| "/docs/widgets/speedtest-tracker"
|
||||
| "/docs/widgets/stock-price"
|
||||
| "/docs/widgets/system-disks"
|
||||
| "/docs/widgets/system-resources"
|
||||
| "/docs/widgets/timetable"
|
||||
| "/docs/widgets/tracearr"
|
||||
| "/docs/widgets/traefik"
|
||||
| "/docs/widgets/umami"
|
||||
| "/docs/widgets/ups"
|
||||
| "/docs/widgets/uptime-kuma"
|
||||
|
||||
@@ -14,17 +14,28 @@ interface Options<TData, TKind extends IntegrationKind, TInput extends Record<st
|
||||
requestAsync: (integration: IntegrationOfKind<TKind>, input: TInput) => Promise<TData>;
|
||||
}
|
||||
|
||||
let integrationHandlerCounter = 0;
|
||||
|
||||
export const createIntegrationRequestHandler = <
|
||||
TData,
|
||||
TKind extends IntegrationKind,
|
||||
TInput extends Record<string, unknown>,
|
||||
>(
|
||||
options: Options<TData, TKind, TInput>,
|
||||
) => ({
|
||||
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
|
||||
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
|
||||
requestAsync: async (input) => options.requestAsync(integration, input.options),
|
||||
});
|
||||
return inner.handler({ integrationId: integration.id, options: itemOptions });
|
||||
},
|
||||
});
|
||||
) => {
|
||||
// Stable per handler definition: the inner request handler is re-created on every
|
||||
// call, so without an explicit cacheKey each call would get a fresh namespace
|
||||
// (no cache hits) — and without any namespace different handlers hitting the same
|
||||
// integration with equal options would share cache entries and cross their data.
|
||||
const cacheKey = `integration-handler-${integrationHandlerCounter++}`;
|
||||
|
||||
return {
|
||||
handler: (integration: IntegrationOfKind<TKind>, itemOptions: TInput) => {
|
||||
const inner = createRequestHandler<TData, { integrationId: string; options: TInput }>({
|
||||
cacheKey,
|
||||
requestAsync: async (input) => options.requestAsync(integration, input.options),
|
||||
});
|
||||
return inner.handler({ integrationId: integration.id, options: itemOptions });
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -1,6 +1,13 @@
|
||||
interface Options<TData, TInput extends Record<string, unknown>> {
|
||||
requestAsync: (input: TInput) => Promise<TData>;
|
||||
cacheTtlMs?: number;
|
||||
/**
|
||||
* Namespace for cache entries of this handler. Defaults to a unique id per
|
||||
* createRequestHandler call. Callers that re-create handlers per request
|
||||
* (e.g. createIntegrationRequestHandler) must pass a stable key themselves,
|
||||
* otherwise the cache never hits.
|
||||
*/
|
||||
cacheKey?: string;
|
||||
}
|
||||
|
||||
type CacheEntry<TData> = { data: TData; timestamp: Date; expiresAt: number };
|
||||
@@ -18,43 +25,52 @@ const evictExpired = () => {
|
||||
}
|
||||
};
|
||||
|
||||
let autoCacheKeyCounter = 0;
|
||||
|
||||
export const createRequestHandler = <TData, TInput extends Record<string, unknown>>(
|
||||
options: Options<TData, TInput>,
|
||||
) => ({
|
||||
handler: (input: TInput) => ({
|
||||
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
||||
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||
const key = JSON.stringify(input);
|
||||
) => {
|
||||
// The cache map is shared between all handlers, so entries have to be namespaced
|
||||
// per handler — otherwise handlers receiving the same input (e.g. the same
|
||||
// integrationId with empty options) would read each other's data.
|
||||
const cacheKey = options.cacheKey ?? `handler-${autoCacheKeyCounter++}`;
|
||||
|
||||
const cached = cache.get(key) as CacheEntry<TData> | undefined;
|
||||
if (cached && Date.now() < cached.expiresAt) {
|
||||
return { data: cached.data, timestamp: cached.timestamp };
|
||||
}
|
||||
if (cached) cache.delete(key);
|
||||
return {
|
||||
handler: (input: TInput) => ({
|
||||
async getDataAsync(): Promise<{ data: TData; timestamp: Date }> {
|
||||
const ttl = options.cacheTtlMs ?? DEFAULT_TTL_MS;
|
||||
const key = `${cacheKey}:${JSON.stringify(input)}`;
|
||||
|
||||
const existing = inflight.get(key);
|
||||
if (existing) return existing as Promise<CacheEntry<TData>>;
|
||||
const cached = cache.get(key) as CacheEntry<TData> | undefined;
|
||||
if (cached && Date.now() < cached.expiresAt) {
|
||||
return { data: cached.data, timestamp: cached.timestamp };
|
||||
}
|
||||
if (cached) cache.delete(key);
|
||||
|
||||
const promise = options
|
||||
.requestAsync(input)
|
||||
.then((data) => {
|
||||
if (cache.size >= MAX_CACHE_SIZE) evictExpired();
|
||||
if (cache.size >= MAX_CACHE_SIZE) {
|
||||
const oldest = cache.keys().next().value;
|
||||
if (oldest) cache.delete(oldest);
|
||||
}
|
||||
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
||||
cache.set(key, entry as CacheEntry<unknown>);
|
||||
inflight.delete(key);
|
||||
return entry;
|
||||
})
|
||||
.catch((err) => {
|
||||
inflight.delete(key);
|
||||
throw err;
|
||||
});
|
||||
const existing = inflight.get(key);
|
||||
if (existing) return existing as Promise<CacheEntry<TData>>;
|
||||
|
||||
inflight.set(key, promise as Promise<CacheEntry<unknown>>);
|
||||
return promise;
|
||||
},
|
||||
}),
|
||||
});
|
||||
const promise = options
|
||||
.requestAsync(input)
|
||||
.then((data) => {
|
||||
if (cache.size >= MAX_CACHE_SIZE) evictExpired();
|
||||
if (cache.size >= MAX_CACHE_SIZE) {
|
||||
const oldest = cache.keys().next().value;
|
||||
if (oldest) cache.delete(oldest);
|
||||
}
|
||||
const entry: CacheEntry<TData> = { data, timestamp: new Date(), expiresAt: Date.now() + ttl };
|
||||
cache.set(key, entry as CacheEntry<unknown>);
|
||||
inflight.delete(key);
|
||||
return entry;
|
||||
})
|
||||
.catch((err) => {
|
||||
inflight.delete(key);
|
||||
throw err;
|
||||
});
|
||||
|
||||
inflight.set(key, promise as Promise<CacheEntry<unknown>>);
|
||||
return promise;
|
||||
},
|
||||
}),
|
||||
};
|
||||
};
|
||||
@@ -6,6 +6,7 @@ import { clientApi } from "@homarr/api/client";
|
||||
import { humanFileSize } from "@homarr/common";
|
||||
import { getIconUrl } from "@homarr/definitions";
|
||||
|
||||
import { WidgetEmptyState } from "../common/empty-state";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export default function ArchiveTeamWarriorWidget({
|
||||
@@ -28,7 +29,9 @@ const ArchiveTeamWarriorWidgetContent = ({
|
||||
integrationId: string;
|
||||
options: WidgetComponentProps<"archiveTeamWarrior">["options"];
|
||||
}) => {
|
||||
const [data] = clientApi.widget.archiveTeamWarrior.getStatus.useSuspenseQuery({ integrationId });
|
||||
const { data } = clientApi.widget.archiveTeamWarrior.getStatus.useQuery({ integrationId });
|
||||
|
||||
if (!data) return <WidgetEmptyState />;
|
||||
|
||||
const status = data.status;
|
||||
const projectName = status.project?.title ?? status.selectedProject ?? "No project selected";
|
||||
|
||||
@@ -46,7 +46,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
|
||||
};
|
||||
const navidromeStats = navidromeStatsByBackend[backend];
|
||||
const showNowPlayingSection =
|
||||
navidromeStats !== null && Boolean(options.showNowPlaying) && navidromeStats.nowPlaying.length > 0;
|
||||
navidromeStats !== null && Boolean(options.showNowPlaying) && (navidromeStats.nowPlaying ?? []).length > 0;
|
||||
|
||||
const nowPlayingLimitByListVisibility = {
|
||||
true: options.maxNowPlayingItems ?? 3,
|
||||
@@ -54,7 +54,7 @@ export function AudioStatsContent({ backend, stats, options, width }: AudioStats
|
||||
} as const;
|
||||
|
||||
const nowPlayingTracks =
|
||||
navidromeStats?.nowPlaying.slice(
|
||||
(navidromeStats?.nowPlaying ?? []).slice(
|
||||
0,
|
||||
nowPlayingLimitByListVisibility[
|
||||
String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility
|
||||
|
||||
@@ -54,12 +54,12 @@ export default function BeszelAlertsWidget({
|
||||
}, [results]);
|
||||
|
||||
const alerts = useMemo(
|
||||
() => results.flatMap((r) => r.alerts.map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))),
|
||||
() => results.flatMap((r) => (r.alerts ?? []).map((a) => ({ ...a, _key: `${r.integrationId}:${a.id}` }))),
|
||||
[results],
|
||||
);
|
||||
|
||||
const history = useMemo(() => {
|
||||
const all = results.flatMap((r) => r.history.map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` })));
|
||||
const all = results.flatMap((r) => (r.history ?? []).map((h) => ({ ...h, _key: `${r.integrationId}:${h.id}` })));
|
||||
return all
|
||||
.toSorted((a, b) => new Date(b.created).getTime() - new Date(a.created).getTime())
|
||||
.slice(0, options.maxHistoryItems);
|
||||
|
||||
@@ -70,7 +70,7 @@ export default function BeszelSystemStatsWidget({
|
||||
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds });
|
||||
|
||||
const systems = useMemo(
|
||||
() => systemsResult.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name }))),
|
||||
() => systemsResult.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name }))),
|
||||
[systemsResult],
|
||||
);
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ export const { definition, componentLoader } = createWidgetDefinition("beszelSys
|
||||
isPending,
|
||||
isError,
|
||||
} = clientApi.widget.beszel.getSystems.useQuery({ integrationIds }, { enabled: integrationIds.length > 0 });
|
||||
const selectData = data.flatMap((r) => r.systems.map((s) => ({ value: s.id, label: s.name })));
|
||||
const selectData = data.flatMap((r) => (r.systems ?? []).map((s) => ({ value: s.id, label: s.name })));
|
||||
return { data: selectData, isPending, isError };
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -187,7 +187,7 @@ export const useDockerChartData = (
|
||||
const { fmt, ordered } = prepareRecords(containerStats, timePeriod);
|
||||
const mapped = ordered.map((record) => {
|
||||
const point: Record<string, unknown> = { time: fmt(record.created), rawTime: record.created };
|
||||
const byName = new Map(record.stats.map((c) => [c.n, c]));
|
||||
const byName = new Map((record.stats ?? []).map((c) => [c.n, c]));
|
||||
for (const name of containerNames) {
|
||||
point[name] = extract(byName.get(name));
|
||||
}
|
||||
|
||||
@@ -13,8 +13,8 @@ export const useBeszelFilteredSystems = (
|
||||
const allSystems = useMemo(
|
||||
() =>
|
||||
results
|
||||
.flatMap((r) => r.systems.map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
|
||||
.toSorted((a, b) => a.name.localeCompare(b.name)),
|
||||
.flatMap((r) => (r.systems ?? []).map((s) => ({ ...s, _key: `${r.integrationId}:${s.id}` })))
|
||||
.toSorted((a, b) => (a.name ?? "").localeCompare(b.name ?? "")),
|
||||
[results],
|
||||
);
|
||||
|
||||
|
||||
@@ -137,7 +137,7 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
|
||||
.filter(
|
||||
(event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType),
|
||||
)
|
||||
.toSorted((eventA, eventB) => eventA.startDate.getTime() - eventB.startDate.getTime());
|
||||
.toSorted((eventA, eventB) => new Date(eventA.startDate).getTime() - new Date(eventB.startDate).getTime());
|
||||
|
||||
return (
|
||||
<CalendarDay
|
||||
|
||||
@@ -32,22 +32,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
||||
defaultValue: ["applications"],
|
||||
});
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(
|
||||
instance.instanceInfo.servers,
|
||||
instance.instanceInfo.applications,
|
||||
instance.instanceInfo.services,
|
||||
);
|
||||
const servers = instance.instanceInfo.servers ?? [];
|
||||
const applications = instance.instanceInfo.applications ?? [];
|
||||
const services = instance.instanceInfo.services ?? [];
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
|
||||
|
||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||
const relativeTime = useTimeAgo(instance.updatedAt);
|
||||
|
||||
const onlineServers = instance.instanceInfo.servers.filter((s) => s.is_reachable !== false).length;
|
||||
const runningApps = instance.instanceInfo.applications.filter(
|
||||
(a) => parseStatus(a.status ?? "") === "running",
|
||||
).length;
|
||||
const runningServices = instance.instanceInfo.services.filter(
|
||||
(s) => parseStatus(s.status ?? "") === "running",
|
||||
).length;
|
||||
const onlineServers = servers.filter((s) => s.is_reachable !== false).length;
|
||||
const runningApps = applications.filter((a) => parseStatus(a.status ?? "") === "running").length;
|
||||
const runningServices = services.filter((s) => parseStatus(s.status ?? "") === "running").length;
|
||||
|
||||
return (
|
||||
<Card p={0} radius="sm">
|
||||
@@ -65,26 +61,18 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{options.showServers && (
|
||||
<Badge variant="dot" color={getBadgeColor(onlineServers, instance.instanceInfo.servers.length)} size="xs">
|
||||
{onlineServers}/{instance.instanceInfo.servers.length}
|
||||
<Badge variant="dot" color={getBadgeColor(onlineServers, servers.length)} size="xs">
|
||||
{onlineServers}/{servers.length}
|
||||
</Badge>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<Badge
|
||||
variant="dot"
|
||||
color={getBadgeColor(runningApps, instance.instanceInfo.applications.length)}
|
||||
size="xs"
|
||||
>
|
||||
{runningApps}/{instance.instanceInfo.applications.length}
|
||||
<Badge variant="dot" color={getBadgeColor(runningApps, applications.length)} size="xs">
|
||||
{runningApps}/{applications.length}
|
||||
</Badge>
|
||||
)}
|
||||
{options.showServices && (
|
||||
<Badge
|
||||
variant="dot"
|
||||
color={getBadgeColor(runningServices, instance.instanceInfo.services.length)}
|
||||
size="xs"
|
||||
>
|
||||
{runningServices}/{instance.instanceInfo.services.length}
|
||||
<Badge variant="dot" color={getBadgeColor(runningServices, services.length)} size="xs">
|
||||
{runningServices}/{services.length}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
@@ -93,7 +81,7 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
||||
<Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||
{options.showServers && (
|
||||
<ServersSection
|
||||
servers={instance.instanceInfo.servers}
|
||||
servers={servers}
|
||||
serverResourceCounts={serverResourceCounts}
|
||||
baseUrl={baseUrl}
|
||||
isTiny={isTiny}
|
||||
@@ -102,11 +90,9 @@ export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceC
|
||||
/>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && (
|
||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
<ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
|
||||
</Accordion>
|
||||
|
||||
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
|
||||
|
||||
@@ -31,11 +31,11 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
||||
defaultValue: ["applications"],
|
||||
});
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(
|
||||
instance.instanceInfo.servers,
|
||||
instance.instanceInfo.applications,
|
||||
instance.instanceInfo.services,
|
||||
);
|
||||
const servers = instance.instanceInfo.servers ?? [];
|
||||
const applications = instance.instanceInfo.applications ?? [];
|
||||
const services = instance.instanceInfo.services ?? [];
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(servers, applications, services);
|
||||
|
||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||
const displayUrl = baseUrl.replace(/^https?:\/\//, "");
|
||||
@@ -59,7 +59,7 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
||||
<Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||
{options.showServers && (
|
||||
<ServersSection
|
||||
servers={instance.instanceInfo.servers}
|
||||
servers={servers}
|
||||
serverResourceCounts={serverResourceCounts}
|
||||
baseUrl={baseUrl}
|
||||
isTiny={isTiny}
|
||||
@@ -68,11 +68,9 @@ export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: S
|
||||
/>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && (
|
||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
<ApplicationsSection applications={applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && <ServicesSection services={services} baseUrl={baseUrl} isTiny={isTiny} />}
|
||||
</Accordion>
|
||||
|
||||
<Group
|
||||
|
||||
@@ -104,7 +104,9 @@ export default function DownloadClientsWidget({
|
||||
const [quickFilters, setQuickFilters] = useState<QuickFilter>({ integrationKinds: [], statuses: [] });
|
||||
const availableStatuses = useMemo<QuickFilter["statuses"]>(() => {
|
||||
//Redefine list of available statuses from current items
|
||||
const statuses = Array.from(new Set(currentItems.flatMap(({ data }) => data.items.map(({ state }) => state))));
|
||||
const statuses = Array.from(
|
||||
new Set(currentItems.flatMap(({ data }) => (data.items ?? []).map(({ state }) => state))),
|
||||
);
|
||||
//Reset user filters accordingly to remove unavailable statuses
|
||||
setQuickFilters(({ integrationKinds: names, statuses: prevStatuses }) => {
|
||||
return { integrationKinds: names, statuses: prevStatuses.filter((status) => statuses.includes(status)) };
|
||||
@@ -127,7 +129,7 @@ export default function DownloadClientsWidget({
|
||||
//Construct normalized items list
|
||||
.flatMap((pair) =>
|
||||
//Apply user white/black list
|
||||
pair.data.items
|
||||
(pair.data.items ?? [])
|
||||
.filter(
|
||||
({ category }) =>
|
||||
options.filterIsWhitelist ===
|
||||
@@ -202,7 +204,7 @@ export default function DownloadClientsWidget({
|
||||
const interact = integrationsWithInteractions.includes(integration.id);
|
||||
const isTorrent = getIntegrationKindsByCategory("torrent").some((kind) => kind === integration.kind);
|
||||
/** Derived from current items */
|
||||
const { totalUp, totalDown } = data.items
|
||||
const { totalUp, totalDown } = (data.items ?? [])
|
||||
.filter(
|
||||
({ category }) =>
|
||||
!options.applyFilterToRatio ||
|
||||
|
||||
@@ -41,19 +41,21 @@ export const ClusterHealthMonitoring = ({
|
||||
|
||||
if (!healthData) return <WidgetEmptyState />;
|
||||
|
||||
const activeNodes = healthData.nodes.reduce(running, 0);
|
||||
const activeVMs = healthData.vms.reduce(running, 0);
|
||||
const activeLXCs = healthData.lxcs.reduce(running, 0);
|
||||
const activeStorage = healthData.storages.reduce(running, 0);
|
||||
const nodes = healthData.nodes ?? [];
|
||||
const vms = healthData.vms ?? [];
|
||||
const lxcs = healthData.lxcs ?? [];
|
||||
const storages = healthData.storages ?? [];
|
||||
|
||||
const usedMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0);
|
||||
const maxMem = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0);
|
||||
const maxCpu = healthData.nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0);
|
||||
const usedCpu = healthData.nodes.reduce(
|
||||
(sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum),
|
||||
0,
|
||||
);
|
||||
const uptime = healthData.nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0);
|
||||
const activeNodes = nodes.reduce(running, 0);
|
||||
const activeVMs = vms.reduce(running, 0);
|
||||
const activeLXCs = lxcs.reduce(running, 0);
|
||||
const activeStorage = storages.reduce(running, 0);
|
||||
|
||||
const usedMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.used + sum : sum), 0);
|
||||
const maxMem = nodes.reduce((sum, item) => (item.isRunning ? item.memory.total + sum : sum), 0);
|
||||
const maxCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.cores + sum : sum), 0);
|
||||
const usedCpu = nodes.reduce((sum, item) => (item.isRunning ? item.cpu.utilization * item.cpu.cores + sum : sum), 0);
|
||||
const uptime = nodes.reduce((sum, { uptime }) => (sum > uptime ? sum : uptime), 0);
|
||||
|
||||
const cpuPercent = maxCpu ? (usedCpu / maxCpu) * 100 : 0;
|
||||
const memPercent = maxMem ? (usedMem / maxMem) * 100 : 0;
|
||||
@@ -89,12 +91,12 @@ export const ClusterHealthMonitoring = ({
|
||||
icon={IconServer}
|
||||
badge={addBadgeColor({
|
||||
activeCount: activeNodes,
|
||||
totalCount: healthData.nodes.length,
|
||||
totalCount: nodes.length,
|
||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||
})}
|
||||
isTiny={isTiny}
|
||||
>
|
||||
<ResourceTable type="node" data={healthData.nodes} isTiny={isTiny} />
|
||||
<ResourceTable type="node" data={nodes} isTiny={isTiny} />
|
||||
</ResourceAccordionItem>
|
||||
)}
|
||||
|
||||
@@ -105,12 +107,12 @@ export const ClusterHealthMonitoring = ({
|
||||
icon={IconDeviceLaptop}
|
||||
badge={addBadgeColor({
|
||||
activeCount: activeVMs,
|
||||
totalCount: healthData.vms.length,
|
||||
totalCount: vms.length,
|
||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||
})}
|
||||
isTiny={isTiny}
|
||||
>
|
||||
<ResourceTable type="qemu" data={healthData.vms} isTiny={isTiny} />
|
||||
<ResourceTable type="qemu" data={vms} isTiny={isTiny} />
|
||||
</ResourceAccordionItem>
|
||||
)}
|
||||
|
||||
@@ -121,12 +123,12 @@ export const ClusterHealthMonitoring = ({
|
||||
icon={IconCube}
|
||||
badge={addBadgeColor({
|
||||
activeCount: activeLXCs,
|
||||
totalCount: healthData.lxcs.length,
|
||||
totalCount: lxcs.length,
|
||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||
})}
|
||||
isTiny={isTiny}
|
||||
>
|
||||
<ResourceTable type="lxc" data={healthData.lxcs} isTiny={isTiny} />
|
||||
<ResourceTable type="lxc" data={lxcs} isTiny={isTiny} />
|
||||
</ResourceAccordionItem>
|
||||
)}
|
||||
|
||||
@@ -137,12 +139,12 @@ export const ClusterHealthMonitoring = ({
|
||||
icon={IconDatabase}
|
||||
badge={addBadgeColor({
|
||||
activeCount: activeStorage,
|
||||
totalCount: healthData.storages.length,
|
||||
totalCount: storages.length,
|
||||
sectionIndicatorRequirement: options.sectionIndicatorRequirement,
|
||||
})}
|
||||
isTiny={isTiny}
|
||||
>
|
||||
<ResourceTable type="storage" data={healthData.storages} isTiny={isTiny} />
|
||||
<ResourceTable type="storage" data={storages} isTiny={isTiny} />
|
||||
</ResourceAccordionItem>
|
||||
)}
|
||||
</Accordion>
|
||||
|
||||
@@ -65,7 +65,7 @@ export const SystemHealthMonitoring = ({
|
||||
return (
|
||||
<Stack h="100%" gap="sm" className="health-monitoring">
|
||||
{healthData.map(({ integrationId, integrationName, healthInfo }) => {
|
||||
const disksData = matchFileSystemAndSmart(healthInfo.fileSystem, healthInfo.smart);
|
||||
const disksData = matchFileSystemAndSmart(healthInfo.fileSystem ?? [], healthInfo.smart ?? []);
|
||||
const memoryUsage = formatMemoryUsage(healthInfo.memAvailableInBytes, healthInfo.memUsedInBytes);
|
||||
return (
|
||||
<Stack
|
||||
@@ -165,7 +165,7 @@ export const SystemHealthMonitoring = ({
|
||||
/>
|
||||
)}
|
||||
{options.gpu &&
|
||||
healthInfo.gpu.map((gpu) => (
|
||||
(healthInfo.gpu ?? []).map((gpu) => (
|
||||
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
|
||||
))}
|
||||
</Flex>
|
||||
@@ -301,5 +301,5 @@ export const matchFileSystemAndSmart = (fileSystems: FileSystem[], smartData: Sm
|
||||
overallStatus: smartDisk?.overallStatus ?? "",
|
||||
};
|
||||
})
|
||||
.toSorted((fileSystemA, fileSystemB) => fileSystemA.deviceName.localeCompare(fileSystemB.deviceName));
|
||||
.toSorted((fileSystemA, fileSystemB) => (fileSystemA.deviceName ?? "").localeCompare(fileSystemB.deviceName ?? ""));
|
||||
};
|
||||
@@ -65,7 +65,7 @@ export default function IndexerManagerWidget({
|
||||
<ScrollArea className="indexer-manager-list-scroll-area" h="100%" scrollbars="y">
|
||||
{indexersData.map(({ integrationId, indexers }) => (
|
||||
<Stack gap={4} className={`indexer-manager-${integrationId}-list-container`} p={0} key={integrationId}>
|
||||
{indexers.map((indexer) => (
|
||||
{(indexers ?? []).map((indexer) => (
|
||||
<Group
|
||||
className={`indexer-manager-line indexer-manager-${indexer.name}`}
|
||||
key={indexer.id}
|
||||
|
||||
@@ -80,7 +80,7 @@ const Item = ({ item, options }: ItemProps) => {
|
||||
top={0}
|
||||
left={0}
|
||||
style={{
|
||||
backgroundImage: `url(${item.imageUrls.backdrop})`,
|
||||
backgroundImage: `url(${item.imageUrls?.backdrop})`,
|
||||
borderRadius: 8,
|
||||
backgroundRepeat: "no-repeat",
|
||||
backgroundSize: "cover",
|
||||
@@ -91,7 +91,7 @@ const Item = ({ item, options }: ItemProps) => {
|
||||
)}
|
||||
<Group justify="space-between" h="100%" wrap="nowrap">
|
||||
<Group align="start" wrap="nowrap" style={{ zIndex: 0 }}>
|
||||
{options.layout === "poster" && <Image w={60} src={item.imageUrls.poster} alt={item.title} />}
|
||||
{options.layout === "poster" && <Image w={60} src={item.imageUrls?.poster} alt={item.title} />}
|
||||
<Stack gap={4}>
|
||||
<Stack gap={0}>
|
||||
<Text size="sm" fw="bold" lineClamp={2}>
|
||||
@@ -130,7 +130,7 @@ const Item = ({ item, options }: ItemProps) => {
|
||||
</>
|
||||
)}
|
||||
</Group>
|
||||
{item.tags.length > 0 && (
|
||||
{(item.tags ?? []).length > 0 && (
|
||||
<OverflowBadge
|
||||
size="xs"
|
||||
groupGap={4}
|
||||
|
||||
@@ -43,48 +43,49 @@ export default function MediaServerWidget({
|
||||
const board = useRequiredBoard();
|
||||
|
||||
if (!requestStats) return <WidgetEmptyState />;
|
||||
if (requestStats.users.length === 0 && requestStats.stats.length === 0) throw new NoIntegrationDataError();
|
||||
if ((requestStats.users ?? []).length === 0 && (requestStats.stats ?? []).length === 0)
|
||||
throw new NoIntegrationDataError();
|
||||
|
||||
const data = [
|
||||
{
|
||||
name: "approved",
|
||||
icon: IconThumbUp,
|
||||
number: requestStats.stats.reduce((count, { approved }) => count + approved, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { approved }) => count + approved, 0),
|
||||
},
|
||||
{
|
||||
name: "pending",
|
||||
icon: IconHourglass,
|
||||
number: requestStats.stats.reduce((count, { pending }) => count + pending, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { pending }) => count + pending, 0),
|
||||
},
|
||||
{
|
||||
name: "processing",
|
||||
icon: IconLoaderQuarter,
|
||||
number: requestStats.stats.reduce((count, { processing }) => count + processing, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { processing }) => count + processing, 0),
|
||||
},
|
||||
{
|
||||
name: "declined",
|
||||
icon: IconThumbDown,
|
||||
number: requestStats.stats.reduce((count, { declined }) => count + declined, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { declined }) => count + declined, 0),
|
||||
},
|
||||
{
|
||||
name: "available",
|
||||
icon: IconPlayerPlay,
|
||||
number: requestStats.stats.reduce((count, { available }) => count + available, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { available }) => count + available, 0),
|
||||
},
|
||||
{
|
||||
name: "tv",
|
||||
icon: IconDeviceTv,
|
||||
number: requestStats.stats.reduce((count, { tv }) => count + tv, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { tv }) => count + tv, 0),
|
||||
},
|
||||
{
|
||||
name: "movie",
|
||||
icon: IconMovie,
|
||||
number: requestStats.stats.reduce((count, { movie }) => count + movie, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { movie }) => count + movie, 0),
|
||||
},
|
||||
{
|
||||
name: "total",
|
||||
icon: IconReceipt,
|
||||
number: requestStats.stats.reduce((count, { total }) => count + total, 0),
|
||||
number: (requestStats.stats ?? []).reduce((count, { total }) => count + total, 0),
|
||||
},
|
||||
] satisfies { name: keyof RequestStats; icon: Icon; number: number }[];
|
||||
|
||||
@@ -132,7 +133,7 @@ export default function MediaServerWidget({
|
||||
{t("titles.users.main")} ({t("titles.users.requests")})
|
||||
</Text>
|
||||
<Stack className="mediaRequests-stats-users-wrapper" flex={1} w="100%" gap={4} style={{ overflow: "hidden" }}>
|
||||
{requestStats.users.slice(0, 10).map((user) => (
|
||||
{(requestStats.users ?? []).slice(0, 10).map((user) => (
|
||||
<Card
|
||||
component="a"
|
||||
href={user.link}
|
||||
|
||||
@@ -76,7 +76,7 @@ export default function MediaServerWidget({ options, integrationIds }: WidgetCom
|
||||
const flatSessions = useMemo(
|
||||
() =>
|
||||
currentStreams.flatMap((pair) =>
|
||||
pair.sessions.map((session) => ({
|
||||
(pair.sessions ?? []).map((session) => ({
|
||||
...session,
|
||||
integrationKind: pair.integrationKind,
|
||||
integrationName: integrationDefs[pair.integrationKind].name,
|
||||
|
||||
@@ -27,7 +27,7 @@ export function QueuePanel(props: QueuePanelProps) {
|
||||
|
||||
const t = useI18n("widget.mediaTranscoding.panel.queue");
|
||||
|
||||
if (queue.array.length === 0) {
|
||||
if ((queue.array ?? []).length === 0) {
|
||||
return (
|
||||
<Center style={{ flex: "1" }}>
|
||||
<Title order={6}>{t("empty")}</Title>
|
||||
@@ -53,7 +53,7 @@ export function QueuePanel(props: QueuePanelProps) {
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{queue.array.map((item) => (
|
||||
{(queue.array ?? []).map((item) => (
|
||||
<TableTr key={item.id}>
|
||||
<TableTd py={2}>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
|
||||
@@ -26,7 +26,7 @@ interface WorkersPanelProps {
|
||||
export function WorkersPanel(props: WorkersPanelProps) {
|
||||
const t = useI18n("widget.mediaTranscoding.panel.workers");
|
||||
|
||||
if (props.workers.length === 0) {
|
||||
if ((props.workers ?? []).length === 0) {
|
||||
return (
|
||||
<Center style={{ flex: "1" }}>
|
||||
<Title order={6}>{t("empty")}</Title>
|
||||
|
||||
@@ -25,19 +25,19 @@ export default function NetworkControllerNetworkStatusWidget({
|
||||
integrationIds,
|
||||
});
|
||||
|
||||
const data = useMemo(() => summaries.flatMap(({ summary }) => summary), [summaries]);
|
||||
const data = useMemo(() => summaries.flatMap(({ summary }) => (summary ? [summary] : [])), [summaries]);
|
||||
|
||||
return (
|
||||
<Box p={"sm"}>
|
||||
{options.content === "wifi" ? (
|
||||
<WifiVariant
|
||||
countGuests={data.reduce((sum, summary) => sum + summary.wifi.guests, 0)}
|
||||
countUsers={data.reduce((sum, summary) => sum + summary.wifi.users, 0)}
|
||||
countGuests={data.reduce((sum, summary) => sum + (summary.wifi?.guests ?? 0), 0)}
|
||||
countUsers={data.reduce((sum, summary) => sum + (summary.wifi?.users ?? 0), 0)}
|
||||
/>
|
||||
) : (
|
||||
<WiredVariant
|
||||
countGuests={data.reduce((sum, summary) => sum + summary.lan.guests, 0)}
|
||||
countUsers={data.reduce((sum, summary) => sum + summary.lan.users, 0)}
|
||||
countGuests={data.reduce((sum, summary) => sum + (summary.lan?.guests ?? 0), 0)}
|
||||
countUsers={data.reduce((sum, summary) => sum + (summary.lan?.users ?? 0), 0)}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
|
||||
@@ -24,8 +24,8 @@ export default function NotificationsWidget({ options, integrationIds }: WidgetC
|
||||
const sortedNotifications = useMemo(
|
||||
() =>
|
||||
notificationIntegrations
|
||||
.flatMap((integration) => integration.data)
|
||||
.sort((entryA, entryB) => entryB.time.getTime() - entryA.time.getTime()),
|
||||
.flatMap((integration) => integration.data ?? [])
|
||||
.sort((a, b) => (b.time?.getTime?.() ?? 0) - (a.time?.getTime?.() ?? 0)),
|
||||
[notificationIntegrations],
|
||||
);
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
|
||||
(acc, item) => ({
|
||||
latestResult: item.dashboard.latestResult ?? acc.latestResult,
|
||||
stats: mergeStats(acc.stats, item.dashboard.stats),
|
||||
recentResults: [...acc.recentResults, ...item.dashboard.recentResults],
|
||||
recentResults: [...acc.recentResults, ...(item.dashboard.recentResults ?? [])],
|
||||
}),
|
||||
{ latestResult: null, stats: null, recentResults: [] },
|
||||
),
|
||||
@@ -32,7 +32,9 @@ export default function SpeedtestTrackerWidget({ options, integrationIds }: Widg
|
||||
);
|
||||
|
||||
const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000;
|
||||
const recentFiltered = combined.recentResults.filter((result) => result.created_at.getTime() > twelveHoursAgo);
|
||||
const recentFiltered = combined.recentResults.filter(
|
||||
(result) => new Date(result.created_at).getTime() > twelveHoursAgo,
|
||||
);
|
||||
|
||||
const hasStatSection =
|
||||
(options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null);
|
||||
|
||||
@@ -40,7 +40,7 @@ function buildXAxisTicks(data: { ts: number }[]): XAxisTicks {
|
||||
|
||||
return {
|
||||
midnightTs: foundMidnight,
|
||||
xTicks: Array.from(tickSet).sort((tsA, tsB) => tsA - tsB),
|
||||
xTicks: Array.from(tickSet).toSorted((tsA, tsB) => tsA - tsB),
|
||||
topDateTicks: topTicks,
|
||||
};
|
||||
}
|
||||
@@ -161,10 +161,10 @@ function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResul
|
||||
const data = useMemo(
|
||||
() =>
|
||||
[...results]
|
||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
||||
.toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
|
||||
.filter((result) => (result.download_bits ?? 0) > 0)
|
||||
.map((result) => ({
|
||||
ts: result.created_at.getTime(),
|
||||
ts: new Date(result.created_at).getTime(),
|
||||
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
|
||||
Upload:
|
||||
result.upload_bits != null && result.upload_bits > 0
|
||||
@@ -273,12 +273,12 @@ function PingHistoryChart({ results, height }: { results: SpeedtestTrackerResult
|
||||
const data = useMemo(
|
||||
() =>
|
||||
[...results]
|
||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
||||
.toSorted((resultA, resultB) => new Date(resultA.created_at).getTime() - new Date(resultB.created_at).getTime())
|
||||
.map((result) =>
|
||||
result.ping === null
|
||||
? null
|
||||
: {
|
||||
ts: result.created_at.getTime(),
|
||||
ts: new Date(result.created_at).getTime(),
|
||||
Ping: result.ping,
|
||||
},
|
||||
)
|
||||
|
||||
@@ -35,8 +35,9 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
|
||||
calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.previousClose),
|
||||
);
|
||||
|
||||
const stockValuesMin = Math.min(...data.priceHistory);
|
||||
const stockGraphValues = data.priceHistory.map((value) => value - stockValuesMin + 50);
|
||||
const priceHistory = data.priceHistory ?? [];
|
||||
const stockValuesMin = priceHistory.length > 0 ? Math.min(...priceHistory) : 0;
|
||||
const stockGraphValues = priceHistory.map((value) => value - stockValuesMin + 50);
|
||||
const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6";
|
||||
|
||||
return (
|
||||
|
||||
@@ -34,7 +34,7 @@ const TimetableWidgetInner = ({ station, baseUrl }: TimetableWidgetInnerProps) =
|
||||
<Stack w="100%" gap="xs" p="sm">
|
||||
<Text fw="bold">{t("title", { station: station.label })}</Text>
|
||||
{(timetable?.entries ?? []).map((entry) => (
|
||||
<Group key={`${entry.timestamp.toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
||||
<Group key={`${new Date(entry.timestamp).toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
||||
<Group gap="sm">
|
||||
{entry.line && (
|
||||
<Badge
|
||||
|
||||
@@ -37,24 +37,28 @@ function TracearrContent({ integrationIds, options, width }: TracearrContentProp
|
||||
const { stats, streams, violations, recentActivity } = item.dashboard;
|
||||
const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||
const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||
const sData = streams ?? {
|
||||
data: [],
|
||||
summary: { total: 0, transcodes: 0, directStreams: 0, directPlays: 0, totalBitrate: "0", byServer: [] },
|
||||
};
|
||||
|
||||
return {
|
||||
stats: {
|
||||
activeStreams: acc.stats.activeStreams + stats.activeStreams,
|
||||
totalUsers: acc.stats.totalUsers + stats.totalUsers,
|
||||
totalSessions: acc.stats.totalSessions + stats.totalSessions,
|
||||
recentViolations: acc.stats.recentViolations + stats.recentViolations,
|
||||
timestamp: stats.timestamp,
|
||||
activeStreams: acc.stats.activeStreams + (stats?.activeStreams ?? 0),
|
||||
totalUsers: acc.stats.totalUsers + (stats?.totalUsers ?? 0),
|
||||
totalSessions: acc.stats.totalSessions + (stats?.totalSessions ?? 0),
|
||||
recentViolations: acc.stats.recentViolations + (stats?.recentViolations ?? 0),
|
||||
timestamp: stats?.timestamp ?? "",
|
||||
},
|
||||
streams: {
|
||||
data: [...acc.streams.data, ...streams.data],
|
||||
data: [...acc.streams.data, ...(sData.data ?? [])],
|
||||
summary: {
|
||||
total: acc.streams.summary.total + streams.summary.total,
|
||||
transcodes: acc.streams.summary.transcodes + streams.summary.transcodes,
|
||||
directStreams: acc.streams.summary.directStreams + streams.summary.directStreams,
|
||||
directPlays: acc.streams.summary.directPlays + streams.summary.directPlays,
|
||||
totalBitrate: streams.summary.totalBitrate,
|
||||
byServer: [...acc.streams.summary.byServer, ...streams.summary.byServer],
|
||||
total: acc.streams.summary.total + (sData.summary?.total ?? 0),
|
||||
transcodes: acc.streams.summary.transcodes + (sData.summary?.transcodes ?? 0),
|
||||
directStreams: acc.streams.summary.directStreams + (sData.summary?.directStreams ?? 0),
|
||||
directPlays: acc.streams.summary.directPlays + (sData.summary?.directPlays ?? 0),
|
||||
totalBitrate: sData.summary?.totalBitrate ?? "0",
|
||||
byServer: [...acc.streams.summary.byServer, ...(sData.summary?.byServer ?? [])],
|
||||
},
|
||||
},
|
||||
violations: {
|
||||
|
||||
@@ -57,7 +57,7 @@ export function UmamiContent({
|
||||
);
|
||||
|
||||
const multiEventTotal = multiEventSeries
|
||||
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints).reduce((sum, { y }) => sum + y, 0)
|
||||
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints ?? []).reduce((sum, { y }) => sum + y, 0)
|
||||
: undefined;
|
||||
|
||||
const firstResult = results[0];
|
||||
@@ -73,13 +73,13 @@ export function UmamiContent({
|
||||
|
||||
const { visitorStats } = firstResult;
|
||||
|
||||
const chartData = visitorStats.dataPoints.map((point: UmamiVisitorStats["dataPoints"][number]) => ({
|
||||
const chartData = (visitorStats.dataPoints ?? []).map((point: UmamiVisitorStats["dataPoints"][number]) => ({
|
||||
label: formatXLabel(point.timestamp, timeFrame),
|
||||
visitors: point.visitors,
|
||||
...(point.events !== undefined ? { events: point.events } : {}),
|
||||
}));
|
||||
|
||||
const hasEventSeries = visitorStats.dataPoints.some(({ events }) => events !== undefined);
|
||||
const hasEventSeries = (visitorStats.dataPoints ?? []).some(({ events }) => events !== undefined);
|
||||
const series = [
|
||||
{ name: "visitors", color: "blue.5" },
|
||||
...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []),
|
||||
|
||||
@@ -45,14 +45,14 @@ export function UmamiEventsContent({
|
||||
|
||||
// Collect all unique timestamps across all series
|
||||
const allTimestamps = Array.from(
|
||||
new Set(series.flatMap(({ dataPoints }) => dataPoints.map(({ x: xPoint }) => xPoint))),
|
||||
new Set(series.flatMap(({ dataPoints }) => (dataPoints ?? []).map(({ x: xPoint }) => xPoint))),
|
||||
).toSorted();
|
||||
|
||||
// Build per-event lookup by timestamp string
|
||||
const byEvent = new Map(
|
||||
series.map((serie: UmamiEventSeries) => [
|
||||
serie.eventName,
|
||||
new Map(serie.dataPoints.map((point) => [point.x, point.y])),
|
||||
new Map((serie.dataPoints ?? []).map((point) => [point.x, point.y])),
|
||||
]),
|
||||
);
|
||||
|
||||
|
||||
@@ -44,7 +44,7 @@ function UpsContent({ integrationIds, options, width }: UpsContentProps) {
|
||||
if (!data) return <WidgetEmptyState />;
|
||||
|
||||
const devices = data.flatMap((instance) =>
|
||||
instance.summaries.map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })),
|
||||
(instance.summaries ?? []).map((summary) => ({ key: `${instance.integrationId}:${summary.id}`, summary })),
|
||||
);
|
||||
|
||||
if (devices.length === 0) {
|
||||
|
||||
@@ -112,7 +112,7 @@ function UptimeKumaContent({ integrationIds, options, width }: UptimeKumaContent
|
||||
downCount: acc.downCount + item.dashboard.downCount,
|
||||
pausedCount: acc.pausedCount + item.dashboard.pausedCount,
|
||||
averageUptimePercent: acc.averageUptimePercent + item.dashboard.averageUptimePercent,
|
||||
monitors: [...acc.monitors, ...item.dashboard.monitors],
|
||||
monitors: [...acc.monitors, ...(item.dashboard.monitors ?? [])],
|
||||
}),
|
||||
emptyDashboard,
|
||||
);
|
||||
|
||||
Generated
+2
-2
@@ -564,7 +564,7 @@ overrides:
|
||||
'@babel/runtime@<7.26.10': '>=7.29.7'
|
||||
axios@>=1.0.0 <1.8.2: '>=1.18.1'
|
||||
brace-expansion@>=2.0.0 <=2.0.1: '>=5.0.7'
|
||||
brace-expansion@>=1.0.0 <=1.1.11: '>=5.0.7'
|
||||
brace-expansion@>=1.0.0 <=1.1.11: '>=5.0.6'
|
||||
esbuild@<=0.24.2: '>=0.28.0'
|
||||
form-data@>=4.0.0 <4.0.4: '>=4.0.6'
|
||||
hono@<4.6.5: '>=4.12.27'
|
||||
@@ -26240,7 +26240,7 @@ snapshots:
|
||||
|
||||
minimatch@3.1.5:
|
||||
dependencies:
|
||||
brace-expansion: 5.0.7
|
||||
brace-expansion: 5.0.6
|
||||
|
||||
minimatch@5.1.9:
|
||||
dependencies:
|
||||
|
||||
+1
-1
@@ -210,7 +210,7 @@ overrides:
|
||||
"@babel/runtime@<7.26.10": ">=7.29.7"
|
||||
"axios@>=1.0.0 <1.8.2": ">=1.18.1"
|
||||
"brace-expansion@>=2.0.0 <=2.0.1": ">=5.0.7"
|
||||
"brace-expansion@>=1.0.0 <=1.1.11": ">=5.0.7"
|
||||
"brace-expansion@>=1.0.0 <=1.1.11": ">=5.0.6"
|
||||
"esbuild@<=0.24.2": ">=0.28.0"
|
||||
"form-data@>=4.0.0 <4.0.4": ">=4.0.6"
|
||||
"hono@<4.6.5": ">=4.12.27"
|
||||
|
||||
Reference in new issue
Block a user