feat: rebuild onboarding experience
This commit is contained in:
1 parent
d091362db2
commit
e41605640b
249 files changed
+8216
-14060
No files matched your search
@@ -17,7 +17,9 @@
|
||||
"./websocket": "./src/websocket.ts",
|
||||
"./shared": "./src/shared.ts",
|
||||
"./open-api": "./src/open-api.ts",
|
||||
"./onboarding-claim": "./src/onboarding-claim.ts",
|
||||
"./assistant": "./src/assistant.ts",
|
||||
"./onboarding-step": "./src/onboarding-step.ts",
|
||||
"./custom-widget/display-data": "./src/router/custom-widget/display-data.ts",
|
||||
"./mcp": "./src/mcp.ts",
|
||||
"./custom-widget-configuration": "./src/custom-widget-configuration.ts"
|
||||
@@ -41,8 +43,6 @@
|
||||
"@homarr/docker": "workspace:^0.1.0",
|
||||
"@homarr/icons": "workspace:^0.1.0",
|
||||
"@homarr/integrations": "workspace:^0.1.0",
|
||||
"@homarr/old-import": "workspace:^0.1.0",
|
||||
"@homarr/old-schema": "workspace:^0.1.0",
|
||||
"@homarr/ping": "workspace:^0.1.0",
|
||||
"@homarr/redis": "workspace:^0.1.0",
|
||||
"@homarr/request-handler": "workspace:^0.1.0",
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import type { Database } from "@homarr/db";
|
||||
import { and, eq } from "@homarr/db";
|
||||
import { serverSettings } from "@homarr/db/schema";
|
||||
|
||||
export const onboardingClaimCookieName = "homarr-onboarding-claim";
|
||||
export const onboardingClaimSettingKey = "__onboarding_claim";
|
||||
export const onboardingClaimTtlMs = 4 * 60 * 60 * 1000;
|
||||
|
||||
interface StoredOnboardingClaim {
|
||||
hash: string;
|
||||
expiresAt: number;
|
||||
}
|
||||
|
||||
export type ClaimOnboardingResult =
|
||||
| { status: "issued" | "active"; token: string; expiresAt: number }
|
||||
| { status: "locked"; expiresAt: number }
|
||||
| { status: "finished" | "forbidden" };
|
||||
|
||||
const hashToken = (token: string) => createHash("sha256").update(token).digest("hex");
|
||||
|
||||
const parseStoredClaim = (value: string): StoredOnboardingClaim | null => {
|
||||
try {
|
||||
const parsed = JSON.parse(value) as Partial<StoredOnboardingClaim>;
|
||||
if (typeof parsed.hash !== "string" || !/^[0-9a-f]{64}$/.test(parsed.hash)) return null;
|
||||
if (typeof parsed.expiresAt !== "number" || !Number.isSafeInteger(parsed.expiresAt)) return null;
|
||||
return { hash: parsed.hash, expiresAt: parsed.expiresAt };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const tokenMatches = (claim: StoredOnboardingClaim, token: string, now: number) => {
|
||||
if (claim.expiresAt <= now || token.length === 0) return false;
|
||||
const expected = Buffer.from(claim.hash, "hex");
|
||||
const actual = Buffer.from(hashToken(token), "hex");
|
||||
return expected.length === actual.length && timingSafeEqual(expected, actual);
|
||||
};
|
||||
|
||||
const getClaimRowAsync = async (db: Database) =>
|
||||
await db.query.serverSettings.findFirst({ where: eq(serverSettings.settingKey, onboardingClaimSettingKey) });
|
||||
|
||||
export const getOnboardingClaimTokenFromCookieHeader = (cookieHeader: string | null) => {
|
||||
if (!cookieHeader) return undefined;
|
||||
for (const part of cookieHeader.split(";")) {
|
||||
const separator = part.indexOf("=");
|
||||
if (separator < 0) continue;
|
||||
const name = part.slice(0, separator).trim();
|
||||
if (name !== onboardingClaimCookieName) continue;
|
||||
const value = part.slice(separator + 1).trim();
|
||||
return value || undefined;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
export const isOnboardingClaimValidAsync = async (db: Database, token: string | undefined, now = Date.now()) => {
|
||||
if (!token) return false;
|
||||
const row = await getClaimRowAsync(db);
|
||||
const claim = row ? parseStoredClaim(row.value) : null;
|
||||
return claim ? tokenMatches(claim, token, now) : false;
|
||||
};
|
||||
|
||||
export const isClaimOnlyOnboardingAccessAllowedAsync = async (
|
||||
db: Database,
|
||||
token: string | undefined,
|
||||
now = Date.now(),
|
||||
) => {
|
||||
const existingUser = await db.query.users.findFirst({ columns: { id: true } });
|
||||
return !existingUser && (await isOnboardingClaimValidAsync(db, token, now));
|
||||
};
|
||||
|
||||
export const claimOnboardingAsync = async (
|
||||
db: Database,
|
||||
options: { currentToken?: string; force?: boolean; now?: number; ttlMs?: number } = {},
|
||||
): Promise<ClaimOnboardingResult> => {
|
||||
const onboarding = await db.query.onboarding.findFirst();
|
||||
if (onboarding?.step === "finish") return { status: "finished" };
|
||||
const existingUser = await db.query.users.findFirst({ columns: { id: true } });
|
||||
if (existingUser && !options.force) return { status: "forbidden" };
|
||||
|
||||
const now = options.now ?? Date.now();
|
||||
const currentRow = await getClaimRowAsync(db);
|
||||
const currentClaim = currentRow ? parseStoredClaim(currentRow.value) : null;
|
||||
if (currentClaim && options.currentToken && tokenMatches(currentClaim, options.currentToken, now)) {
|
||||
return { status: "active", token: options.currentToken, expiresAt: currentClaim.expiresAt };
|
||||
}
|
||||
if (currentClaim && currentClaim.expiresAt > now && !options.force) {
|
||||
return { status: "locked", expiresAt: currentClaim.expiresAt };
|
||||
}
|
||||
|
||||
if (currentRow) {
|
||||
await db
|
||||
.delete(serverSettings)
|
||||
.where(and(eq(serverSettings.settingKey, onboardingClaimSettingKey), eq(serverSettings.value, currentRow.value)));
|
||||
}
|
||||
|
||||
const token = randomBytes(32).toString("base64url");
|
||||
const expiresAt = now + (options.ttlMs ?? onboardingClaimTtlMs);
|
||||
const value = JSON.stringify({ hash: hashToken(token), expiresAt } satisfies StoredOnboardingClaim);
|
||||
try {
|
||||
await db.insert(serverSettings).values({ settingKey: onboardingClaimSettingKey, value });
|
||||
} catch (error) {
|
||||
const winner = await getClaimRowAsync(db);
|
||||
const winnerClaim = winner ? parseStoredClaim(winner.value) : null;
|
||||
if (winnerClaim?.expiresAt && winnerClaim.expiresAt > now) {
|
||||
return { status: "locked", expiresAt: winnerClaim.expiresAt };
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
return { status: "issued", token, expiresAt };
|
||||
};
|
||||
@@ -0,0 +1 @@
|
||||
export { normalizeOnboardingStep } from "./router/onboard/onboard-queries";
|
||||
@@ -16,7 +16,6 @@ export const appRouter = createTRPCRouter({
|
||||
location: lazy(() => import("./router/location").then((mod) => mod.locationRouter)),
|
||||
log: lazy(() => import("./router/log").then((mod) => mod.logRouter)),
|
||||
icon: lazy(() => import("./router/icons").then((mod) => mod.iconsRouter)),
|
||||
import: lazy(() => import("./router/import/import-router").then((mod) => mod.importRouter)),
|
||||
onboard: lazy(() => import("./router/onboard/onboard-router").then((mod) => mod.onboardRouter)),
|
||||
home: lazy(() => import("./router/home").then((mod) => mod.homeRouter)),
|
||||
docker: lazy(() => import("./router/docker/docker-router").then((mod) => mod.dockerRouter)),
|
||||
|
||||
@@ -18,8 +18,7 @@ import { AppAccessControl } from "./app/app-access-control";
|
||||
const defaultIcon = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/homarr.svg";
|
||||
|
||||
export const appRouter = createTRPCRouter({
|
||||
getPaginated: permissionRequiredProcedure
|
||||
.requiresPermission("board-modify-all")
|
||||
getPaginated: protectedProcedure
|
||||
.input(paginatedSchema)
|
||||
.output(z.object({ items: z.array(selectAppSchema), totalCount: z.number() }))
|
||||
.meta({
|
||||
|
||||
@@ -31,26 +31,22 @@ import {
|
||||
sections,
|
||||
users,
|
||||
} from "@homarr/db/schema";
|
||||
import type { BoardLane, WidgetKind } from "@homarr/definitions";
|
||||
import type { BoardLane, IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
import {
|
||||
boardLanes,
|
||||
emptySuperJSON,
|
||||
everyoneGroup,
|
||||
getBoardLaneColumnCount,
|
||||
getRootSectionLane,
|
||||
getWidgetIntegrationIssue,
|
||||
getWidgetIntegrationIssueMessage,
|
||||
getPermissionsWithChildren,
|
||||
getPermissionsWithParents,
|
||||
normalizeBoardLayoutRoles,
|
||||
rootSectionOffsets,
|
||||
widgetDefaultSizes,
|
||||
widgetIntegrationLimits,
|
||||
widgetIntegrationSupport,
|
||||
widgetKindsWithOptionalIntegrations,
|
||||
widgetKinds,
|
||||
} from "@homarr/definitions";
|
||||
import { importOldmarrAsync } from "@homarr/old-import";
|
||||
import { importJsonFileSchema } from "@homarr/old-import/shared";
|
||||
import { oldmarrConfigSchema } from "@homarr/old-schema";
|
||||
import {
|
||||
addItemToBoardSchema,
|
||||
boardByNameSchema,
|
||||
@@ -193,31 +189,8 @@ export const boardRouter = createTRPCRouter({
|
||||
})
|
||||
.query(async ({ ctx }) => {
|
||||
const userId = ctx.session?.user.id;
|
||||
const permissionsOfCurrentUserWhenPresent = await ctx.db.query.boardUserPermissions.findMany({
|
||||
where: eq(boardUserPermissions.userId, userId ?? ""),
|
||||
});
|
||||
|
||||
const permissionsOfCurrentUserGroupsWhenPresent = await ctx.db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, userId ?? ""),
|
||||
with: {
|
||||
group: {
|
||||
with: {
|
||||
boardPermissions: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
const boardIds = permissionsOfCurrentUserWhenPresent
|
||||
.map((permission) => permission.boardId)
|
||||
.concat(
|
||||
permissionsOfCurrentUserGroupsWhenPresent
|
||||
.map((groupMember) => groupMember.group.boardPermissions.map((permission) => permission.boardId))
|
||||
.flat(),
|
||||
);
|
||||
|
||||
const currentUserWhenPresent = await ctx.db.query.users.findFirst({
|
||||
where: eq(users.id, userId ?? ""),
|
||||
});
|
||||
const { boardIds, currentUser, groupMemberships } = await getBoardAccessContextAsync(ctx.db, userId);
|
||||
const groupPermissionWhere = getBoardGroupPermissionWhere(groupMemberships);
|
||||
|
||||
const dbBoards = await ctx.db.query.boards.findMany({
|
||||
columns: {
|
||||
@@ -239,30 +212,121 @@ export const boardRouter = createTRPCRouter({
|
||||
where: eq(boardUserPermissions.userId, ctx.session?.user.id ?? ""),
|
||||
},
|
||||
groupPermissions: {
|
||||
where:
|
||||
permissionsOfCurrentUserGroupsWhenPresent.length >= 1
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
permissionsOfCurrentUserGroupsWhenPresent.map((groupMember) => groupMember.groupId),
|
||||
)
|
||||
: undefined,
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
},
|
||||
// Allow viewing all boards if the user has the permission
|
||||
where: ctx.session?.user.permissions.includes("board-view-all")
|
||||
? undefined
|
||||
: or(
|
||||
eq(boards.isPublic, true),
|
||||
eq(boards.creatorId, ctx.session?.user.id ?? ""),
|
||||
boardIds.length > 0 ? inArray(boards.id, boardIds) : undefined,
|
||||
),
|
||||
where: getAccessibleBoardsWhere(ctx.session?.user.permissions.includes("board-view-all"), userId, boardIds),
|
||||
});
|
||||
return dbBoards.map((board) => ({
|
||||
...board,
|
||||
isHome: currentUserWhenPresent?.homeBoardId === board.id,
|
||||
isMobileHome: currentUserWhenPresent?.mobileHomeBoardId === board.id,
|
||||
isHome: currentUser?.homeBoardId === board.id,
|
||||
isMobileHome: currentUser?.mobileHomeBoardId === board.id,
|
||||
}));
|
||||
}),
|
||||
getManageOverview: publicProcedure.query(async ({ ctx }) => {
|
||||
const userId = ctx.session?.user.id;
|
||||
const { boardIds, currentUser, groupMemberships } = await getBoardAccessContextAsync(ctx.db, userId);
|
||||
const groupPermissionWhere = getBoardGroupPermissionWhere(groupMemberships);
|
||||
|
||||
const dbBoards = await ctx.db.query.boards.findMany({
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
logoImageUrl: true,
|
||||
isPublic: true,
|
||||
},
|
||||
with: {
|
||||
creator: {
|
||||
columns: {
|
||||
id: true,
|
||||
name: true,
|
||||
image: true,
|
||||
email: true,
|
||||
},
|
||||
},
|
||||
userPermissions: {
|
||||
columns: { permission: true },
|
||||
where: eq(boardUserPermissions.userId, userId ?? ""),
|
||||
},
|
||||
groupPermissions: {
|
||||
columns: { permission: true },
|
||||
where: groupPermissionWhere,
|
||||
},
|
||||
layouts: {
|
||||
columns: {
|
||||
id: true,
|
||||
columnCount: true,
|
||||
leftGutterColumnCount: true,
|
||||
rightGutterColumnCount: true,
|
||||
breakpoint: true,
|
||||
role: true,
|
||||
},
|
||||
},
|
||||
sections: {
|
||||
columns: {
|
||||
id: true,
|
||||
kind: true,
|
||||
xOffset: true,
|
||||
},
|
||||
with: {
|
||||
layouts: {
|
||||
columns: {
|
||||
layoutId: true,
|
||||
parentSectionId: true,
|
||||
xOffset: true,
|
||||
yOffset: true,
|
||||
width: true,
|
||||
height: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
items: {
|
||||
columns: {
|
||||
id: true,
|
||||
},
|
||||
with: {
|
||||
layouts: {
|
||||
columns: {
|
||||
layoutId: true,
|
||||
sectionId: true,
|
||||
xOffset: true,
|
||||
yOffset: true,
|
||||
width: true,
|
||||
height: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
where: getAccessibleBoardsWhere(ctx.session?.user.permissions.includes("board-view-all"), userId, boardIds),
|
||||
});
|
||||
|
||||
return dbBoards.map(({ layouts: boardLayouts, sections: boardSections, items: boardItems, ...board }) => {
|
||||
const previewLayout =
|
||||
boardLayouts.find((layout) => layout.role === "base") ??
|
||||
boardLayouts.toSorted((first, second) => second.breakpoint - first.breakpoint).at(0);
|
||||
|
||||
return {
|
||||
...board,
|
||||
isHome: currentUser?.homeBoardId === board.id,
|
||||
isMobileHome: currentUser?.mobileHomeBoardId === board.id,
|
||||
preview: previewLayout
|
||||
? {
|
||||
layouts: [previewLayout],
|
||||
sections: boardSections.map((section) => ({
|
||||
...section,
|
||||
layouts: section.layouts.filter((layout) => layout.layoutId === previewLayout.id),
|
||||
})),
|
||||
items: boardItems.map((item) => ({
|
||||
...item,
|
||||
layouts: item.layouts.filter((layout) => layout.layoutId === previewLayout.id),
|
||||
})),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
});
|
||||
}),
|
||||
search: publicProcedure
|
||||
.input(z.object({ query: z.string(), limit: z.number().min(1).max(100).default(10) }))
|
||||
.query(async ({ ctx, input }) => {
|
||||
@@ -1846,14 +1910,6 @@ export const boardRouter = createTRPCRouter({
|
||||
},
|
||||
});
|
||||
}),
|
||||
importOldmarrConfig: permissionRequiredProcedure
|
||||
.requiresPermission("board-create")
|
||||
.input(importJsonFileSchema)
|
||||
.mutation(async ({ input, ctx }) => {
|
||||
const content = await input.file.text();
|
||||
const oldmarr = oldmarrConfigSchema.parse(JSON.parse(content));
|
||||
await importOldmarrAsync(ctx.db, oldmarr, input.configuration);
|
||||
}),
|
||||
addItem: protectedProcedure
|
||||
.meta({
|
||||
openapi: { method: "POST", path: "/api/boards/items", tags: ["boards"], protect: true },
|
||||
@@ -1877,25 +1933,7 @@ export const boardRouter = createTRPCRouter({
|
||||
await validateTimetableOptionsChangeAsync(input.options);
|
||||
}
|
||||
|
||||
const supportedIntegrations = widgetIntegrationSupport[input.kind];
|
||||
const integrationLimit = widgetIntegrationLimits[input.kind] ?? Infinity;
|
||||
if (input.integrationIds.length > integrationLimit) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `${input.kind} supports at most ${integrationLimit} integration${integrationLimit === 1 ? "" : "s"}`,
|
||||
});
|
||||
}
|
||||
if (supportedIntegrations === undefined && input.integrationIds.length > 0) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `${input.kind} does not support integrations` });
|
||||
}
|
||||
if (
|
||||
supportedIntegrations !== undefined &&
|
||||
input.integrationIds.length === 0 &&
|
||||
!widgetKindsWithOptionalIntegrations.has(input.kind)
|
||||
) {
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `${input.kind} requires an integration` });
|
||||
}
|
||||
|
||||
let selectedIntegrationKinds: IntegrationKind[] = [];
|
||||
if (input.integrationIds.length > 0) {
|
||||
const existing = await ctx.db.query.integrations.findMany({
|
||||
columns: { id: true, kind: true },
|
||||
@@ -1907,19 +1945,21 @@ export const boardRouter = createTRPCRouter({
|
||||
throw new TRPCError({ code: "BAD_REQUEST", message: `Invalid integration IDs: ${invalid.join(", ")}` });
|
||||
}
|
||||
|
||||
selectedIntegrationKinds = existing.map((integration) => integration.kind);
|
||||
|
||||
await Promise.all(
|
||||
input.integrationIds.map((integrationId) =>
|
||||
throwIfIntegrationActionForbiddenAsync(ctx, eq(integrations.id, integrationId), "use"),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
const incompatible = existing.filter((integration) => !supportedIntegrations?.includes(integration.kind));
|
||||
if (incompatible.length > 0) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: `${input.kind} does not support integration kind${incompatible.length === 1 ? "" : "s"}: ${incompatible.map((integration) => integration.kind).join(", ")}`,
|
||||
});
|
||||
}
|
||||
const integrationIssue = getWidgetIntegrationIssue(input.kind, selectedIntegrationKinds);
|
||||
if (integrationIssue) {
|
||||
throw new TRPCError({
|
||||
code: "BAD_REQUEST",
|
||||
message: getWidgetIntegrationIssueMessage(input.kind, integrationIssue),
|
||||
});
|
||||
}
|
||||
|
||||
return await serializeBoardItemPlacementAsync(input.boardId, async () => {
|
||||
@@ -2372,6 +2412,59 @@ const getElementsForLayout = (board: BoardForLayoutProjection, layoutId: string)
|
||||
|
||||
const protectedLayoutRepairPromises = new Map<string, Promise<void>>();
|
||||
|
||||
const getBoardAccessContextAsync = async (db: Database, userId: string | undefined) => {
|
||||
const [userPermissions, groupMemberships, currentUser] = await Promise.all([
|
||||
db.query.boardUserPermissions.findMany({
|
||||
where: eq(boardUserPermissions.userId, userId ?? ""),
|
||||
}),
|
||||
db.query.groupMembers.findMany({
|
||||
where: eq(groupMembers.userId, userId ?? ""),
|
||||
with: {
|
||||
group: {
|
||||
with: {
|
||||
boardPermissions: {},
|
||||
},
|
||||
},
|
||||
},
|
||||
}),
|
||||
db.query.users.findFirst({
|
||||
where: eq(users.id, userId ?? ""),
|
||||
columns: {
|
||||
homeBoardId: true,
|
||||
mobileHomeBoardId: true,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const boardIds = userPermissions
|
||||
.map((permission) => permission.boardId)
|
||||
.concat(
|
||||
groupMemberships.flatMap((membership) =>
|
||||
membership.group.boardPermissions.map((permission) => permission.boardId),
|
||||
),
|
||||
);
|
||||
|
||||
return { boardIds, currentUser, groupMemberships };
|
||||
};
|
||||
|
||||
const getBoardGroupPermissionWhere = (
|
||||
groupMemberships: Awaited<ReturnType<typeof getBoardAccessContextAsync>>["groupMemberships"],
|
||||
) =>
|
||||
groupMemberships.length > 0
|
||||
? inArray(
|
||||
boardGroupPermissions.groupId,
|
||||
groupMemberships.map((membership) => membership.groupId),
|
||||
)
|
||||
: eq(boardGroupPermissions.groupId, "");
|
||||
|
||||
const getAccessibleBoardsWhere = (canViewAll: boolean | undefined, userId: string | undefined, boardIds: string[]) =>
|
||||
canViewAll
|
||||
? undefined
|
||||
: or(
|
||||
eq(boards.isPublic, true),
|
||||
eq(boards.creatorId, userId ?? ""),
|
||||
boardIds.length > 0 ? inArray(boards.id, boardIds) : undefined,
|
||||
);
|
||||
|
||||
const getFullBoardWithWhereAsync = async (
|
||||
db: Database,
|
||||
where: SQL<unknown>,
|
||||
|
||||
@@ -6,7 +6,7 @@ import { createId } from "@homarr/common";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { and, eq, handleTransactionsAsync, like, not } from "@homarr/db";
|
||||
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
|
||||
import { groupMembers, groupPermissions, groups, users } from "@homarr/db/schema";
|
||||
import { groupMembers, groupPermissions, groups, onboarding, users } from "@homarr/db/schema";
|
||||
import { everyoneGroup } from "@homarr/definitions";
|
||||
import { byIdSchema, paginatedSchema } from "@homarr/validation/common";
|
||||
import {
|
||||
@@ -19,7 +19,6 @@ import {
|
||||
} from "@homarr/validation/group";
|
||||
|
||||
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, protectedProcedure } from "../trpc";
|
||||
import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
|
||||
|
||||
export const groupRouter = createTRPCRouter({
|
||||
getAll: permissionRequiredProcedure.requiresPermission("admin").query(async ({ ctx }) => {
|
||||
@@ -185,18 +184,28 @@ export const groupRouter = createTRPCRouter({
|
||||
const maxPosition = await getMaxGroupPositionAsync(ctx.db);
|
||||
|
||||
const groupId = createId();
|
||||
await ctx.db.insert(groups).values({
|
||||
const groupRow = {
|
||||
id: groupId,
|
||||
name: input.name,
|
||||
position: maxPosition + 1,
|
||||
});
|
||||
};
|
||||
|
||||
await ctx.db.insert(groupPermissions).values({
|
||||
groupId,
|
||||
permission: "admin",
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(db, schema) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await transaction.insert(schema.groups).values(groupRow);
|
||||
await transaction.insert(schema.groupPermissions).values({ groupId, permission: "admin" });
|
||||
await transaction.update(schema.onboarding).set({ previousStep: "group", step: "setup" });
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
transaction.insert(groups).values(groupRow).run();
|
||||
transaction.insert(groupPermissions).values({ groupId, permission: "admin" }).run();
|
||||
transaction.update(onboarding).set({ previousStep: "group", step: "setup" }).run();
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
await nextOnboardingStepAsync(ctx.db, undefined);
|
||||
}),
|
||||
createGroup: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
|
||||
@@ -101,7 +101,7 @@ export const homeRouter = createTRPCRouter({
|
||||
});
|
||||
}
|
||||
|
||||
if (ctx.session?.user.permissions.includes("board-modify-all")) {
|
||||
if (ctx.session?.user.permissions.includes("app-create")) {
|
||||
statistics.push({
|
||||
titleKey: "app",
|
||||
subtitleKey: "resources",
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { analyseOldmarrImportForRouterAsync, analyseOldmarrImportInputSchema } from "@homarr/old-import/analyse";
|
||||
import {
|
||||
ensureValidTokenOrThrow,
|
||||
importInitialOldmarrAsync,
|
||||
importInitialOldmarrInputSchema,
|
||||
} from "@homarr/old-import/import";
|
||||
|
||||
import { createTRPCRouter, onboardingProcedure } from "../../trpc";
|
||||
import { nextOnboardingStepAsync } from "../onboard/onboard-queries";
|
||||
|
||||
export const importRouter = createTRPCRouter({
|
||||
analyseInitialOldmarrImport: onboardingProcedure
|
||||
.requiresStep("import")
|
||||
.input(analyseOldmarrImportInputSchema)
|
||||
.mutation(async ({ input }) => {
|
||||
return await analyseOldmarrImportForRouterAsync(input);
|
||||
}),
|
||||
validateToken: onboardingProcedure
|
||||
.requiresStep("import")
|
||||
.input(
|
||||
z.object({
|
||||
checksum: z.string(),
|
||||
token: z.string(),
|
||||
}),
|
||||
)
|
||||
.mutation(({ input }) => {
|
||||
try {
|
||||
ensureValidTokenOrThrow(input.checksum, input.token);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}),
|
||||
importInitialOldmarrImport: onboardingProcedure
|
||||
.requiresStep("import")
|
||||
.input(importInitialOldmarrInputSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
await importInitialOldmarrAsync(ctx.db, input);
|
||||
await nextOnboardingStepAsync(ctx.db, undefined);
|
||||
}),
|
||||
});
|
||||
@@ -1,84 +1,35 @@
|
||||
import { isProviderEnabled } from "@homarr/auth/server";
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import type { MaybePromise } from "@homarr/common/types";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { eq } from "@homarr/db";
|
||||
import { groups, onboarding } from "@homarr/db/schema";
|
||||
import { onboarding } from "@homarr/db/schema";
|
||||
import type { OnboardingStep } from "@homarr/definitions";
|
||||
import { credentialsAdminGroup } from "@homarr/definitions";
|
||||
|
||||
export const nextOnboardingStepAsync = async (db: Database, preferredStep: OnboardingStep | undefined) => {
|
||||
export const nextOnboardingStepAsync = async (db: Database) => {
|
||||
const { current } = await getOnboardingOrFallbackAsync(db);
|
||||
const nextStepConfiguration = nextSteps[current];
|
||||
if (!nextStepConfiguration) return;
|
||||
if (current !== "start") return;
|
||||
const nextStep = getNextOnboardingStep();
|
||||
if (!nextStep) return;
|
||||
|
||||
for (const conditionalStep of objectEntries(nextStepConfiguration)) {
|
||||
if (!conditionalStep) continue;
|
||||
const [nextStep, condition] = conditionalStep;
|
||||
if (condition === "preferred" && nextStep !== preferredStep) continue;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (typeof condition === "boolean" && !condition) continue;
|
||||
if (typeof condition === "function" && !(await condition(db))) continue;
|
||||
|
||||
await db.update(onboarding).set({
|
||||
previousStep: current,
|
||||
step: nextStep,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await db.update(onboarding).set({ previousStep: current, step: nextStep });
|
||||
};
|
||||
|
||||
export const getOnboardingOrFallbackAsync = async (db: Database) => {
|
||||
const value = await db.query.onboarding.findFirst();
|
||||
if (!value) return { current: "start" as const, previous: null };
|
||||
|
||||
return { current: value.step, previous: value.previousStep };
|
||||
return {
|
||||
current: normalizeOnboardingStep(value.step),
|
||||
previous: value.previousStep ? normalizeOnboardingStep(value.previousStep) : null,
|
||||
};
|
||||
};
|
||||
|
||||
type NextStepCondition = true | "preferred" | ((db: Database) => MaybePromise<boolean>);
|
||||
|
||||
/**
|
||||
* The below object is a definition of which can be the next step of the current one.
|
||||
* If the value is `true`, it means the step can always be the next one.
|
||||
* If the value is `preferred`, it means that the step can only be reached if the input `preferredStep` is set to the step.
|
||||
* If the value is a function, it will be called with the database instance and should return a boolean.
|
||||
* If the value or result is `false`, the step has to be skipped and the next value or callback should be checked.
|
||||
*/
|
||||
const nextSteps: Partial<Record<OnboardingStep, Partial<Record<OnboardingStep, NextStepCondition>>>> = {
|
||||
start: {
|
||||
import: "preferred" as const,
|
||||
user: () => isProviderEnabled("credentials"),
|
||||
group: () => isProviderEnabled("ldap") || isProviderEnabled("oidc"),
|
||||
settings: true,
|
||||
},
|
||||
import: {
|
||||
// eslint-disable-next-line no-restricted-syntax
|
||||
user: async (db: Database) => {
|
||||
if (!isProviderEnabled("credentials")) return false;
|
||||
|
||||
const adminGroup = await db.query.groups.findFirst({
|
||||
where: eq(groups.name, credentialsAdminGroup),
|
||||
with: {
|
||||
members: true,
|
||||
},
|
||||
});
|
||||
|
||||
return !adminGroup || adminGroup.members.length === 0;
|
||||
},
|
||||
group: () => isProviderEnabled("ldap") || isProviderEnabled("oidc"),
|
||||
settings: true,
|
||||
},
|
||||
user: {
|
||||
group: () => isProviderEnabled("ldap") || isProviderEnabled("oidc"),
|
||||
settings: true,
|
||||
},
|
||||
group: {
|
||||
settings: true,
|
||||
},
|
||||
settings: {
|
||||
integrations: true,
|
||||
},
|
||||
integrations: {
|
||||
finish: true,
|
||||
},
|
||||
const getNextOnboardingStep = (): OnboardingStep => {
|
||||
if (isProviderEnabled("credentials")) return "user";
|
||||
if (isProviderEnabled("ldap") || isProviderEnabled("oidc")) return "group";
|
||||
return "setup";
|
||||
};
|
||||
|
||||
export const normalizeOnboardingStep = (step: string | null | undefined): OnboardingStep => {
|
||||
if (step === "user" || step === "group" || step === "setup" || step === "finish") return step;
|
||||
if (step === "settings" || step === "integrations") return "setup";
|
||||
return "start";
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -11,10 +11,8 @@ import {
|
||||
import { boards, serverSettings } from "@homarr/db/schema";
|
||||
import type { ServerSettings } from "@homarr/server-settings";
|
||||
import { defaultServerSettingsKeys } from "@homarr/server-settings";
|
||||
import { settingsInitSchema } from "@homarr/validation/settings";
|
||||
|
||||
import { createTRPCRouter, onboardingProcedure, permissionRequiredProcedure, publicProcedure } from "../trpc";
|
||||
import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
|
||||
import { createTRPCRouter, permissionRequiredProcedure, publicProcedure } from "../trpc";
|
||||
|
||||
const boardServerSettingsSchema = z.object({
|
||||
homeBoardId: z.string().nullable(),
|
||||
@@ -108,13 +106,4 @@ export const serverSettingsRouter = createTRPCRouter({
|
||||
...input.value,
|
||||
} as ServerSettings[keyof ServerSettings]);
|
||||
}),
|
||||
initSettings: onboardingProcedure
|
||||
.requiresStep("settings")
|
||||
.input(settingsInitSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
const currentAnalytics = await getServerSettingByKeyAsync(ctx.db, "analytics");
|
||||
await updateServerSettingByKeyAsync(ctx.db, "analytics", { ...currentAnalytics, ...input.analytics });
|
||||
await updateServerSettingByKeyAsync(ctx.db, "crawlingAndIndexing", input.crawlingAndIndexing);
|
||||
await nextOnboardingStepAsync(ctx.db, undefined);
|
||||
}),
|
||||
});
|
||||
@@ -76,23 +76,23 @@ describe("all should return all apps", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("getPaginated should require board modification access", () => {
|
||||
test("should throw FORBIDDEN without board-modify-all", async () => {
|
||||
describe("getPaginated should return apps to authenticated users", () => {
|
||||
test("should throw UNAUTHORIZED without a session", async () => {
|
||||
const caller = appRouter.createCaller({
|
||||
db: createDb(),
|
||||
deviceType: undefined,
|
||||
session: createDefaultSession(),
|
||||
session: null,
|
||||
});
|
||||
|
||||
await expect(caller.getPaginated({ page: 1, pageSize: 10 })).rejects.toThrow("Permission denied");
|
||||
await expect(caller.getPaginated({ page: 1, pageSize: 10 })).rejects.toThrow("UNAUTHORIZED");
|
||||
});
|
||||
|
||||
test("should return apps with board-modify-all", async () => {
|
||||
test("should return apps without board permissions", async () => {
|
||||
const db = createDb();
|
||||
const caller = appRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: createDefaultSession(["board-modify-all"]),
|
||||
session: createDefaultSession(),
|
||||
});
|
||||
await db.insert(apps).values({ id: "1", name: "Homarr", iconUrl: "https://homarr.dev/icon.svg" });
|
||||
|
||||
|
||||
@@ -287,6 +287,113 @@ describe("getAllBoards should return all boards accessable to the current user",
|
||||
);
|
||||
});
|
||||
|
||||
describe("getManageOverview", () => {
|
||||
test("returns the same accessible board set as getAllBoards", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const otherUserId = await createRandomUserAsync(db);
|
||||
const publicBoardId = createId();
|
||||
const creatorBoardId = createId();
|
||||
const directBoardId = createId();
|
||||
const groupBoardId = createId();
|
||||
const hiddenBoardId = createId();
|
||||
const groupId = createId();
|
||||
|
||||
await db.insert(users).values({ id: defaultCreatorId });
|
||||
await db.insert(boards).values([
|
||||
{ id: publicBoardId, name: "public-overview", creatorId: otherUserId, isPublic: true },
|
||||
{ id: creatorBoardId, name: "creator-overview", creatorId: defaultCreatorId, isPublic: false },
|
||||
{ id: directBoardId, name: "direct-overview", creatorId: otherUserId, isPublic: false },
|
||||
{ id: groupBoardId, name: "group-overview", creatorId: otherUserId, isPublic: false },
|
||||
{ id: hiddenBoardId, name: "hidden-overview", creatorId: otherUserId, isPublic: false },
|
||||
]);
|
||||
await db.insert(boardUserPermissions).values({
|
||||
userId: defaultCreatorId,
|
||||
boardId: directBoardId,
|
||||
permission: "view",
|
||||
});
|
||||
await db.insert(groups).values({ id: groupId, name: "overview-group", position: 1 });
|
||||
await db.insert(groupMembers).values({ userId: defaultCreatorId, groupId });
|
||||
await db.insert(boardGroupPermissions).values({ groupId, boardId: groupBoardId, permission: "view" });
|
||||
|
||||
const [summaries, overview] = await Promise.all([caller.getAllBoards(), caller.getManageOverview()]);
|
||||
|
||||
expect(overview.map((board) => board.id).toSorted()).toEqual(summaries.map((board) => board.id).toSorted());
|
||||
expect(overview.map((board) => board.id)).not.toContain(hiddenBoardId);
|
||||
});
|
||||
|
||||
test("returns one compact base-layout preview for each accessible board", async () => {
|
||||
const db = createDb();
|
||||
const caller = boardRouter.createCaller({ db, deviceType: undefined, session: defaultSession });
|
||||
const boardId = createId();
|
||||
const hiddenBoardId = createId();
|
||||
const baseLayoutId = createId();
|
||||
const mobileLayoutId = createId();
|
||||
const rootSectionId = createId();
|
||||
const itemId = createId();
|
||||
|
||||
await db.insert(users).values({ id: defaultCreatorId });
|
||||
await db.insert(boards).values([
|
||||
{ id: boardId, name: "overview", creatorId: defaultCreatorId, isPublic: false },
|
||||
{ id: hiddenBoardId, name: "hidden", creatorId: await createRandomUserAsync(db), isPublic: false },
|
||||
]);
|
||||
await db.update(users).set({ homeBoardId: boardId }).where(eq(users.id, defaultCreatorId));
|
||||
await db.insert(layouts).values([
|
||||
{
|
||||
id: mobileLayoutId,
|
||||
name: "Mobile",
|
||||
boardId,
|
||||
columnCount: 3,
|
||||
breakpoint: 0,
|
||||
role: "mobile",
|
||||
},
|
||||
{
|
||||
id: baseLayoutId,
|
||||
name: "Base",
|
||||
boardId,
|
||||
columnCount: 12,
|
||||
breakpoint: 768,
|
||||
role: "base",
|
||||
},
|
||||
]);
|
||||
await db.insert(sections).values({
|
||||
id: rootSectionId,
|
||||
boardId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
});
|
||||
await db.insert(items).values({ id: itemId, boardId, kind: "clock" });
|
||||
await db.insert(itemLayouts).values({
|
||||
itemId,
|
||||
sectionId: rootSectionId,
|
||||
layoutId: baseLayoutId,
|
||||
xOffset: 2,
|
||||
yOffset: 1,
|
||||
width: 4,
|
||||
height: 2,
|
||||
});
|
||||
|
||||
const result = await caller.getManageOverview();
|
||||
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result[0]).toMatchObject({
|
||||
id: boardId,
|
||||
isHome: true,
|
||||
preview: {
|
||||
layouts: [{ id: baseLayoutId, role: "base", columnCount: 12 }],
|
||||
items: [
|
||||
{
|
||||
id: itemId,
|
||||
layouts: [{ layoutId: baseLayoutId, sectionId: rootSectionId, width: 4, height: 2 }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(result[0]?.preview?.layouts).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createBoard should create a new board", () => {
|
||||
test("should create a new board with permission board-create", async () => {
|
||||
// Arrange
|
||||
|
||||
@@ -0,0 +1,959 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import SuperJSON from "superjson";
|
||||
import { assert, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { eq, inArray } from "@homarr/db";
|
||||
import {
|
||||
apps,
|
||||
boards,
|
||||
integrationItems,
|
||||
integrationSecrets,
|
||||
integrations,
|
||||
itemLayouts,
|
||||
items,
|
||||
layouts,
|
||||
onboarding,
|
||||
sectionLayouts,
|
||||
sections,
|
||||
users,
|
||||
} from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
|
||||
import { claimOnboardingAsync, isOnboardingClaimValidAsync } from "../../onboarding-claim";
|
||||
import * as integrationConnection from "../integration/integration-test-connection";
|
||||
|
||||
const listDiscoveredContainersAsync = vi.hoisted(() => vi.fn());
|
||||
const createIdMock = vi.hoisted(() => vi.fn());
|
||||
const stableAppIdForSource = (sourceId: string) => {
|
||||
const digest = createHash("sha256").update(sourceId).digest("hex").slice(0, 32);
|
||||
return `onboarding_app_${digest}`;
|
||||
};
|
||||
const stableIntegrationIdForSource = (sourceId: string) => {
|
||||
const digest = createHash("sha256").update(sourceId).digest("hex").slice(0, 32);
|
||||
return `onboarding_integration_${digest}`;
|
||||
};
|
||||
|
||||
vi.mock("@homarr/auth/server", () => ({ isProviderEnabled: () => false }));
|
||||
vi.mock("@homarr/common", async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import("@homarr/common")>()),
|
||||
createId: createIdMock,
|
||||
}));
|
||||
vi.mock("@homarr/docker", () => ({
|
||||
dockerLabels: { hide: "homarr.hide" },
|
||||
listDiscoveredContainersAsync,
|
||||
}));
|
||||
|
||||
import { onboardRouter } from "../onboard/onboard-router";
|
||||
import { normalizeOnboardingStep } from "../onboard/onboard-queries";
|
||||
|
||||
const createCaller = (db: ReturnType<typeof createDb>, onboardingClaimToken?: string) =>
|
||||
onboardRouter.createCaller({ db, deviceType: undefined, session: null, onboardingClaimToken });
|
||||
|
||||
const completionInput = (boardId: string, name = "Configured-board") => ({
|
||||
server: {
|
||||
defaultLocale: "en" as const,
|
||||
defaultColorScheme: "dark" as const,
|
||||
analyticsEnabled: false,
|
||||
},
|
||||
board: {
|
||||
id: boardId,
|
||||
name,
|
||||
primaryColor: "#228BE6",
|
||||
secondaryColor: "#15AABF",
|
||||
itemRadius: "md" as const,
|
||||
layoutPreset: "balanced" as const,
|
||||
leftSidebar: false,
|
||||
rightSidebar: false,
|
||||
},
|
||||
selectedIntegrationIds: [] as string[],
|
||||
selectedAppIds: [] as string[],
|
||||
selectedDockerSourceIds: [] as string[],
|
||||
selectedWidgetKinds: [] as WidgetKind[],
|
||||
});
|
||||
|
||||
const rectanglesOverlap = (
|
||||
first: { xOffset: number; yOffset: number; width: number; height: number },
|
||||
second: { xOffset: number; yOffset: number; width: number; height: number },
|
||||
) =>
|
||||
first.xOffset < second.xOffset + second.width &&
|
||||
first.xOffset + first.width > second.xOffset &&
|
||||
first.yOffset < second.yOffset + second.height &&
|
||||
first.yOffset + first.height > second.yOffset;
|
||||
|
||||
const seedOnboardingAsync = async (db: ReturnType<typeof createDb>) => {
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "setup", previousStep: "group" });
|
||||
const claim = await claimOnboardingAsync(db);
|
||||
if (claim.status !== "issued") throw new Error("Expected an onboarding claim");
|
||||
return claim.token;
|
||||
};
|
||||
|
||||
const seedBoardAsync = async (
|
||||
db: ReturnType<typeof createDb>,
|
||||
input: { boardId: string; itemId?: string; itemKind?: "notebook"; withMobile?: boolean },
|
||||
) => {
|
||||
const layoutId = `${input.boardId}-base`;
|
||||
const sectionId = `${input.boardId}-section`;
|
||||
await db.insert(boards).values({
|
||||
id: input.boardId,
|
||||
name: input.boardId,
|
||||
primaryColor: "#FA5252",
|
||||
secondaryColor: "#FD7E14",
|
||||
});
|
||||
await db.insert(layouts).values({
|
||||
id: layoutId,
|
||||
boardId: input.boardId,
|
||||
name: "Base",
|
||||
role: "base",
|
||||
columnCount: 12,
|
||||
breakpoint: 0,
|
||||
});
|
||||
if (input.withMobile) {
|
||||
await db.insert(layouts).values({
|
||||
id: `${input.boardId}-mobile`,
|
||||
boardId: input.boardId,
|
||||
name: "Mobile",
|
||||
role: "mobile",
|
||||
columnCount: 3,
|
||||
breakpoint: 0,
|
||||
});
|
||||
}
|
||||
await db.insert(sections).values({
|
||||
id: sectionId,
|
||||
boardId: input.boardId,
|
||||
kind: "empty",
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
});
|
||||
if (input.itemId) {
|
||||
await db.insert(items).values({
|
||||
id: input.itemId,
|
||||
boardId: input.boardId,
|
||||
kind: input.itemKind ?? "notebook",
|
||||
options: SuperJSON.stringify({ content: "keep me" }),
|
||||
});
|
||||
await db.insert(itemLayouts).values({
|
||||
itemId: input.itemId,
|
||||
sectionId,
|
||||
layoutId,
|
||||
xOffset: 2,
|
||||
yOffset: 3,
|
||||
width: 4,
|
||||
height: 2,
|
||||
});
|
||||
}
|
||||
return { layoutId, sectionId };
|
||||
};
|
||||
|
||||
describe("onboard.completeSetup", () => {
|
||||
beforeEach(() => {
|
||||
listDiscoveredContainersAsync.mockReset();
|
||||
createIdMock.mockReset();
|
||||
let nextId = 0;
|
||||
createIdMock.mockImplementation(() => `generated-${++nextId}`);
|
||||
});
|
||||
|
||||
it("updates only the exact target board and preserves existing content for explicit empty selections", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const target = await seedBoardAsync(db, { boardId: "target", itemId: "existing-item" });
|
||||
await seedBoardAsync(db, { boardId: "other" });
|
||||
|
||||
const result = await createCaller(db, claimToken).completeSetup(completionInput("target"));
|
||||
|
||||
expect(result).toEqual({
|
||||
boardId: "target",
|
||||
boardName: "Configured-board",
|
||||
docker: { missingSourceIds: [], ignoredSourceIds: [], skippedWidgets: [] },
|
||||
});
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "target") })).toMatchObject({
|
||||
name: "Configured-board",
|
||||
primaryColor: "#228BE6",
|
||||
secondaryColor: "#15AABF",
|
||||
itemRadius: "md",
|
||||
});
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "other") })).toMatchObject({ name: "other" });
|
||||
expect(await db.query.items.findMany()).toEqual([
|
||||
expect.objectContaining({ id: "existing-item", boardId: "target", kind: "notebook" }),
|
||||
]);
|
||||
expect(await db.query.itemLayouts.findFirst({ where: eq(itemLayouts.itemId, "existing-item") })).toMatchObject({
|
||||
layoutId: target.layoutId,
|
||||
xOffset: 2,
|
||||
yOffset: 3,
|
||||
width: 4,
|
||||
height: 2,
|
||||
});
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "finish", previousStep: "setup" });
|
||||
expect(await isOnboardingClaimValidAsync(db, claimToken)).toBe(false);
|
||||
});
|
||||
|
||||
it("requires an exact board id when more than one board exists", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
await seedBoardAsync(db, { boardId: "other" });
|
||||
const input = {
|
||||
...completionInput("target"),
|
||||
board: { ...completionInput("target").board, id: undefined },
|
||||
};
|
||||
|
||||
await expect(createCaller(db, claimToken).completeSetup(input)).rejects.toThrow(
|
||||
"Select the exact board to configure when more than one board exists.",
|
||||
);
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "target") })).toMatchObject({ name: "target" });
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "other") })).toMatchObject({ name: "other" });
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "setup", previousStep: "group" });
|
||||
});
|
||||
|
||||
it("creates a complete first board when setup resumes without any boards", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const input = {
|
||||
...completionInput("missing"),
|
||||
board: {
|
||||
...completionInput("missing").board,
|
||||
id: undefined,
|
||||
name: "Recovered-board",
|
||||
leftSidebar: true,
|
||||
rightSidebar: true,
|
||||
},
|
||||
};
|
||||
|
||||
const result = await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(await db.query.boards.findMany()).toEqual([
|
||||
expect.objectContaining({
|
||||
id: result.boardId,
|
||||
name: "Recovered-board",
|
||||
primaryColor: "#228BE6",
|
||||
secondaryColor: "#15AABF",
|
||||
itemRadius: "md",
|
||||
}),
|
||||
]);
|
||||
expect(await db.query.layouts.findMany({ where: eq(layouts.boardId, result.boardId) })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ role: "mobile", columnCount: 3, breakpoint: 0 }),
|
||||
expect.objectContaining({
|
||||
role: "base",
|
||||
columnCount: 10,
|
||||
breakpoint: 768,
|
||||
leftGutterColumnCount: 1,
|
||||
rightGutterColumnCount: 1,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(await db.query.sections.findMany({ where: eq(sections.boardId, result.boardId) })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: "empty", xOffset: 0, yOffset: 0 }),
|
||||
expect.objectContaining({ kind: "empty", xOffset: -1, yOffset: 0 }),
|
||||
expect.objectContaining({ kind: "empty", xOffset: 1, yOffset: 0 }),
|
||||
]),
|
||||
);
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "finish", previousStep: "setup" });
|
||||
});
|
||||
|
||||
it("rolls back board and layout writes when planned item insertion fails", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const { layoutId } = await seedBoardAsync(db, { boardId: "target", itemId: "generated-id" });
|
||||
const input = completionInput("target", "Must-roll-back");
|
||||
input.selectedWidgetKinds = ["clock"];
|
||||
createIdMock.mockReturnValue("generated-id");
|
||||
|
||||
await expect(createCaller(db, claimToken).completeSetup(input)).rejects.toThrow();
|
||||
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "target") })).toMatchObject({
|
||||
name: "target",
|
||||
primaryColor: "#FA5252",
|
||||
secondaryColor: "#FD7E14",
|
||||
});
|
||||
expect(await db.query.layouts.findFirst({ where: eq(layouts.id, layoutId) })).toMatchObject({ columnCount: 12 });
|
||||
expect(await db.query.items.findMany()).toHaveLength(1);
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "setup", previousStep: "group" });
|
||||
expect(await isOnboardingClaimValidAsync(db, claimToken)).toBe(true);
|
||||
});
|
||||
|
||||
it("retains partial Docker results and places an explicitly selected label widget", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
const service = {
|
||||
sourceId: "docker:good:clock",
|
||||
containerId: "clock",
|
||||
host: "good",
|
||||
group: "Utilities",
|
||||
name: "Clock service",
|
||||
href: "http://clock:3000",
|
||||
externalId: "clock",
|
||||
widgetKind: "clock" as const,
|
||||
};
|
||||
const integrationService = {
|
||||
sourceId: "docker:good:sonarr",
|
||||
containerId: "sonarr",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
externalId: "sonarr",
|
||||
integrationKind: "sonarr" as const,
|
||||
description: "TV automation",
|
||||
pingUrl: "http://sonarr:8989/ping",
|
||||
icon: "custom-sonarr.svg",
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [
|
||||
{ host: "good", status: "success", containers: [], services: [service, integrationService] },
|
||||
{ host: "bad", status: "unavailable", reason: "permission denied", containers: [], services: [] },
|
||||
],
|
||||
services: [service, integrationService],
|
||||
});
|
||||
|
||||
const discovery = await createCaller(db, claimToken).discoverDockerServices();
|
||||
|
||||
expect(discovery).toMatchObject({
|
||||
status: "partial",
|
||||
hosts: [
|
||||
{ host: "good", status: "success", containerCount: 0 },
|
||||
{ host: "bad", status: "unavailable", reason: "permission denied", containerCount: 0 },
|
||||
],
|
||||
apps: [{ sourceId: service.sourceId, widgetKind: "clock" }],
|
||||
integrations: [
|
||||
{
|
||||
sourceId: integrationService.sourceId,
|
||||
iconUrl: integrationService.icon,
|
||||
description: integrationService.description,
|
||||
pingUrl: integrationService.pingUrl,
|
||||
},
|
||||
],
|
||||
});
|
||||
const input = completionInput("target");
|
||||
input.selectedWidgetKinds = discovery.apps.flatMap((app) => (app.widgetKind ? [app.widgetKind] : []));
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(await db.query.items.findMany()).toEqual([expect.objectContaining({ boardId: "target", kind: "clock" })]);
|
||||
});
|
||||
|
||||
it("persists discovery metadata on created apps and integration companion apps", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const caller = createCaller(db, claimToken);
|
||||
const appResult = await caller.createAppsFromDiscovery([
|
||||
{
|
||||
sourceId: "docker:good:status",
|
||||
name: "Status",
|
||||
href: "http://status:3001",
|
||||
pingUrl: "http://status:3001/health",
|
||||
iconUrl: "https://icons.example/status.svg",
|
||||
description: "Internal status page",
|
||||
},
|
||||
]);
|
||||
const createdApp = appResult.apps[0];
|
||||
assert(createdApp);
|
||||
expect(await db.query.apps.findFirst({ where: eq(apps.id, createdApp.id) })).toMatchObject({
|
||||
pingUrl: "http://status:3001/health",
|
||||
iconUrl: "https://icons.example/status.svg",
|
||||
description: "Internal status page",
|
||||
});
|
||||
|
||||
const testConnection = vi.spyOn(integrationConnection, "testConnectionAsync").mockResolvedValue({ success: true });
|
||||
try {
|
||||
const integrationResult = await caller.createIntegration({
|
||||
sourceId: "docker:good:sonarr",
|
||||
name: "Sonarr",
|
||||
url: "http://sonarr:8989",
|
||||
kind: "sonarr",
|
||||
secrets: [{ kind: "apiKey", value: "secret" }],
|
||||
pingUrl: "http://sonarr:8989/ping",
|
||||
iconUrl: "https://icons.example/sonarr.svg",
|
||||
description: "TV automation",
|
||||
});
|
||||
const createdAppId = "appId" in integrationResult ? integrationResult.appId : undefined;
|
||||
expect(createdAppId).toBeDefined();
|
||||
if (!createdAppId) throw new Error("Expected integration creation to succeed");
|
||||
expect(await db.query.apps.findFirst({ where: eq(apps.id, createdAppId) })).toMatchObject({
|
||||
pingUrl: "http://sonarr:8989/ping",
|
||||
iconUrl: "https://icons.example/sonarr.svg",
|
||||
description: "TV automation",
|
||||
});
|
||||
} finally {
|
||||
testConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("reuses a manual integration and companion app across retries", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const caller = createCaller(db, claimToken);
|
||||
const sourceId = "manual:sonarr";
|
||||
const createInput = {
|
||||
sourceId,
|
||||
name: "Sonarr",
|
||||
url: "http://sonarr:8989",
|
||||
kind: "sonarr" as const,
|
||||
secrets: [{ kind: "apiKey" as const, value: "secret" }],
|
||||
};
|
||||
const testConnection = vi.spyOn(integrationConnection, "testConnectionAsync").mockResolvedValue({ success: true });
|
||||
|
||||
try {
|
||||
const first = await caller.createIntegration(createInput);
|
||||
const second = await caller.createIntegration(createInput);
|
||||
|
||||
expect(first).toEqual(second);
|
||||
expect(first).toEqual({
|
||||
id: stableIntegrationIdForSource(sourceId),
|
||||
appId: stableAppIdForSource(sourceId),
|
||||
});
|
||||
expect(await db.query.integrations.findMany()).toHaveLength(1);
|
||||
expect(await db.query.apps.findMany()).toHaveLength(1);
|
||||
expect(
|
||||
await db.query.integrationSecrets.findMany({
|
||||
where: eq(integrationSecrets.integrationId, stableIntegrationIdForSource(sourceId)),
|
||||
}),
|
||||
).toHaveLength(1);
|
||||
} finally {
|
||||
testConnection.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it("re-fetches selected labels into grouped responsive containers and ignores another board target", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const { sectionId: mainSectionId } = await seedBoardAsync(db, {
|
||||
boardId: "target",
|
||||
itemId: "existing-item",
|
||||
withMobile: true,
|
||||
});
|
||||
const groupedSource = {
|
||||
sourceId: "docker:good:sonarr",
|
||||
containerId: "sonarr",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
externalId: "sonarr",
|
||||
widgetKind: "clock" as const,
|
||||
};
|
||||
const ignoredSource = {
|
||||
...groupedSource,
|
||||
sourceId: "docker:good:radarr",
|
||||
containerId: "radarr",
|
||||
externalId: "radarr",
|
||||
name: "Radarr",
|
||||
boardName: "other-board",
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [groupedSource, ignoredSource] }],
|
||||
services: [groupedSource, ignoredSource],
|
||||
});
|
||||
const groupedAppId = stableAppIdForSource(groupedSource.sourceId);
|
||||
const ignoredAppId = stableAppIdForSource(ignoredSource.sourceId);
|
||||
await db.insert(apps).values([
|
||||
{ id: groupedAppId, name: groupedSource.name, iconUrl: "icon", href: groupedSource.href },
|
||||
{ id: ignoredAppId, name: ignoredSource.name, iconUrl: "icon", href: ignoredSource.href },
|
||||
]);
|
||||
const input = completionInput("target");
|
||||
input.selectedAppIds = [groupedAppId, ignoredAppId];
|
||||
input.selectedDockerSourceIds = [groupedSource.sourceId, ignoredSource.sourceId, "docker:missing"];
|
||||
input.selectedWidgetKinds = ["clock"];
|
||||
|
||||
const result = await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(result.docker).toEqual({
|
||||
missingSourceIds: ["docker:missing"],
|
||||
ignoredSourceIds: [ignoredSource.sourceId],
|
||||
skippedWidgets: [],
|
||||
});
|
||||
const mediaSection = await db.query.sections.findFirst({
|
||||
where: (table, operators) =>
|
||||
operators.and(operators.eq(table.boardId, "target"), operators.eq(table.kind, "container")),
|
||||
});
|
||||
expect(mediaSection).toBeDefined();
|
||||
expect(SuperJSON.parse(mediaSection?.options ?? "{}")).toMatchObject({ title: "Media", showLabel: true });
|
||||
const containerPlacements = await db.query.sectionLayouts.findMany({
|
||||
where: eq(sectionLayouts.sectionId, mediaSection?.id ?? "missing"),
|
||||
});
|
||||
expect(containerPlacements).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ layoutId: "target-base", parentSectionId: mainSectionId, width: 10 }),
|
||||
expect.objectContaining({ layoutId: "target-mobile", parentSectionId: mainSectionId, width: 3 }),
|
||||
]),
|
||||
);
|
||||
const groupedItems = await db.query.items.findMany({
|
||||
where: (table, operators) => operators.inArray(table.kind, ["app", "clock"]),
|
||||
with: { layouts: true },
|
||||
});
|
||||
expect(groupedItems).toHaveLength(2);
|
||||
expect(groupedItems.flatMap((item) => item.layouts)).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ layoutId: "target-base", sectionId: mediaSection?.id }),
|
||||
expect.objectContaining({ layoutId: "target-mobile", sectionId: mediaSection?.id }),
|
||||
]),
|
||||
);
|
||||
expect(await db.query.items.findFirst({ where: eq(items.id, "existing-item") })).toBeDefined();
|
||||
expect(
|
||||
groupedItems.some(
|
||||
(item) => item.kind === "app" && SuperJSON.parse<{ appId: string }>(item.options).appId === ignoredAppId,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("places a labeled integration app and linked widget together inside its group", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target", withMobile: true });
|
||||
const source = {
|
||||
sourceId: "docker:good:sonarr",
|
||||
containerId: "sonarr",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
externalId: "sonarr",
|
||||
integrationKind: "sonarr" as const,
|
||||
widgetKind: "calendar" as const,
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [source] }],
|
||||
services: [source],
|
||||
});
|
||||
const appId = stableAppIdForSource(source.sourceId);
|
||||
const integrationId = stableIntegrationIdForSource(source.sourceId);
|
||||
await db.insert(apps).values({ id: appId, name: source.name, iconUrl: "icon", href: source.href });
|
||||
await db.insert(integrations).values({
|
||||
id: integrationId,
|
||||
appId,
|
||||
name: source.name,
|
||||
url: source.href,
|
||||
kind: source.integrationKind,
|
||||
});
|
||||
const input = completionInput("target");
|
||||
input.selectedIntegrationIds = [integrationId];
|
||||
input.selectedAppIds = [appId];
|
||||
input.selectedDockerSourceIds = [source.sourceId];
|
||||
input.selectedWidgetKinds = [source.widgetKind];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
const mediaSection = await db.query.sections.findFirst({
|
||||
where: (table, operators) => operators.eq(table.kind, "container"),
|
||||
});
|
||||
const groupedItems = await db.query.items.findMany({
|
||||
where: (table, operators) => operators.inArray(table.kind, ["app", "calendar"]),
|
||||
with: { layouts: true },
|
||||
});
|
||||
expect(groupedItems).toHaveLength(2);
|
||||
expect(groupedItems.every((item) => item.layouts.every((layout) => layout.sectionId === mediaSection?.id))).toBe(
|
||||
true,
|
||||
);
|
||||
const calendar = groupedItems.find((item) => item.kind === "calendar");
|
||||
expect(calendar).toBeDefined();
|
||||
expect(
|
||||
await db.query.integrationItems.findFirst({ where: eq(integrationItems.itemId, calendar?.id ?? "") }),
|
||||
).toEqual({
|
||||
itemId: calendar?.id,
|
||||
integrationId,
|
||||
});
|
||||
});
|
||||
|
||||
it("links a labeled integration to an existing compatible widget", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
const { sectionId, layoutId } = await seedBoardAsync(db, { boardId: "target", itemId: "existing-seed" });
|
||||
await db.insert(items).values({ id: "calendar", boardId: "target", kind: "calendar" });
|
||||
await db.insert(itemLayouts).values({
|
||||
itemId: "calendar",
|
||||
sectionId,
|
||||
layoutId,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
width: 2,
|
||||
height: 2,
|
||||
});
|
||||
const source = {
|
||||
sourceId: "docker:good:sonarr",
|
||||
containerId: "sonarr",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
externalId: "sonarr",
|
||||
integrationKind: "sonarr" as const,
|
||||
widgetKind: "calendar" as const,
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [source] }],
|
||||
services: [source],
|
||||
});
|
||||
const integrationId = stableIntegrationIdForSource(source.sourceId);
|
||||
await db.insert(integrations).values({
|
||||
id: integrationId,
|
||||
name: source.name,
|
||||
url: source.href,
|
||||
kind: source.integrationKind,
|
||||
});
|
||||
const input = completionInput("target");
|
||||
input.selectedIntegrationIds = [integrationId];
|
||||
input.selectedDockerSourceIds = [source.sourceId];
|
||||
input.selectedWidgetKinds = [source.widgetKind];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(await db.query.integrationItems.findFirst({ where: eq(integrationItems.itemId, "calendar") })).toEqual({
|
||||
itemId: "calendar",
|
||||
integrationId,
|
||||
});
|
||||
expect(await db.query.items.findMany({ where: eq(items.kind, "calendar") })).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("skips integration-required and incompatible label widgets but preserves their selected apps", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target", itemId: "seeded-content" });
|
||||
await db.update(boards).set({ name: "dashboard" }).where(eq(boards.id, "target"));
|
||||
const appOnly = {
|
||||
sourceId: "docker:good:app-only",
|
||||
containerId: "app-only",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "App only",
|
||||
href: "http://app-only:3000",
|
||||
externalId: "app-only",
|
||||
widgetKind: "mediaServer" as const,
|
||||
};
|
||||
const incompatible = {
|
||||
...appOnly,
|
||||
sourceId: "docker:good:sonarr",
|
||||
containerId: "sonarr",
|
||||
externalId: "sonarr",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
integrationKind: "sonarr" as const,
|
||||
};
|
||||
const services = [appOnly, incompatible];
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services }],
|
||||
services,
|
||||
});
|
||||
const appIds = services.map((source) => stableAppIdForSource(source.sourceId));
|
||||
await db.insert(apps).values(
|
||||
services.map((source) => ({
|
||||
id: stableAppIdForSource(source.sourceId),
|
||||
name: source.name,
|
||||
iconUrl: "icon",
|
||||
href: source.href,
|
||||
})),
|
||||
);
|
||||
const integrationId = stableIntegrationIdForSource(incompatible.sourceId);
|
||||
await db.insert(integrations).values({
|
||||
id: integrationId,
|
||||
appId: appIds[1],
|
||||
name: incompatible.name,
|
||||
url: incompatible.href,
|
||||
kind: incompatible.integrationKind,
|
||||
});
|
||||
const input = completionInput("target");
|
||||
input.selectedAppIds = appIds;
|
||||
input.selectedIntegrationIds = [integrationId];
|
||||
input.selectedDockerSourceIds = services.map((source) => source.sourceId);
|
||||
input.selectedWidgetKinds = ["mediaServer"];
|
||||
|
||||
const result = await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(result.docker.skippedWidgets).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ sourceId: appOnly.sourceId, code: "integration-required" }),
|
||||
expect.objectContaining({
|
||||
sourceId: incompatible.sourceId,
|
||||
code: "incompatible-integration",
|
||||
integrationKind: "sonarr",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(await db.query.items.findMany({ where: eq(items.kind, "mediaServer") })).toHaveLength(0);
|
||||
expect(await db.query.items.findMany({ where: eq(items.kind, "app") })).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("splits limited automatic integration widgets instead of over-linking one item", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
await db.insert(integrations).values([
|
||||
{ id: "navidrome", name: "Navidrome", url: "http://navidrome:4533", kind: "navidrome" },
|
||||
{ id: "audiobookshelf", name: "Audiobookshelf", url: "http://audiobookshelf:13378", kind: "audiobookshelf" },
|
||||
]);
|
||||
const input = completionInput("target");
|
||||
input.selectedIntegrationIds = ["navidrome", "audiobookshelf"];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
const audioItems = await db.query.items.findMany({ where: eq(items.kind, "audioStats") });
|
||||
expect(audioItems).toHaveLength(2);
|
||||
const links = await db.query.integrationItems.findMany({
|
||||
where: inArray(
|
||||
integrationItems.itemId,
|
||||
audioItems.map((item) => item.id),
|
||||
),
|
||||
});
|
||||
expect(links).toHaveLength(2);
|
||||
expect(new Set(links.map((link) => link.itemId)).size).toBe(2);
|
||||
});
|
||||
|
||||
it("places an ungrouped labeled app and widget in the main root", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
const source = {
|
||||
sourceId: "docker:good:status",
|
||||
containerId: "status",
|
||||
host: "good",
|
||||
name: "Status",
|
||||
href: "http://status:3001",
|
||||
externalId: "status",
|
||||
widgetKind: "clock" as const,
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [source] }],
|
||||
services: [source],
|
||||
});
|
||||
const appId = stableAppIdForSource(source.sourceId);
|
||||
await db.insert(apps).values({ id: appId, name: source.name, iconUrl: "icon", href: source.href });
|
||||
const input = completionInput("target");
|
||||
input.selectedAppIds = [appId];
|
||||
input.selectedDockerSourceIds = [source.sourceId];
|
||||
input.selectedWidgetKinds = [source.widgetKind];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(await db.query.sections.findMany({ where: eq(sections.kind, "container") })).toHaveLength(0);
|
||||
expect(await db.query.items.findMany()).toEqual(
|
||||
expect.arrayContaining([expect.objectContaining({ kind: "app" }), expect.objectContaining({ kind: "clock" })]),
|
||||
);
|
||||
expect((await db.query.itemLayouts.findMany()).every((layout) => layout.sectionId === "target-section")).toBe(true);
|
||||
});
|
||||
|
||||
it("packs grouped items with their actual dimensions without overlapping pending root content", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target", withMobile: true });
|
||||
const sources = [
|
||||
{
|
||||
sourceId: "docker:good:clock",
|
||||
containerId: "clock",
|
||||
host: "good",
|
||||
group: "Utilities",
|
||||
name: "Clock",
|
||||
href: "http://clock:3000",
|
||||
externalId: "clock",
|
||||
widgetKind: "clock" as const,
|
||||
},
|
||||
{
|
||||
sourceId: "docker:good:weather",
|
||||
containerId: "weather",
|
||||
host: "good",
|
||||
group: "Utilities",
|
||||
name: "Weather",
|
||||
href: "http://weather:3000",
|
||||
externalId: "weather",
|
||||
widgetKind: "weather" as const,
|
||||
},
|
||||
];
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: sources }],
|
||||
services: sources,
|
||||
});
|
||||
const appIds = sources.map((source) => stableAppIdForSource(source.sourceId));
|
||||
await db.insert(apps).values(
|
||||
sources.map((source) => ({
|
||||
id: stableAppIdForSource(source.sourceId),
|
||||
name: source.name,
|
||||
iconUrl: "icon",
|
||||
href: source.href,
|
||||
})),
|
||||
);
|
||||
const input = completionInput("target");
|
||||
input.board.leftSidebar = true;
|
||||
input.board.rightSidebar = true;
|
||||
input.selectedAppIds = appIds;
|
||||
input.selectedDockerSourceIds = sources.map((source) => source.sourceId);
|
||||
input.selectedWidgetKinds = ["bookmarks", "clock", "weather"];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
const container = await db.query.sections.findFirst({ where: (table, { eq }) => eq(table.kind, "container") });
|
||||
expect(container).toBeDefined();
|
||||
const containerLayouts = await db.query.sectionLayouts.findMany({
|
||||
where: eq(sectionLayouts.sectionId, container?.id ?? "missing"),
|
||||
});
|
||||
const groupedLayouts = await db.query.itemLayouts.findMany({
|
||||
where: eq(itemLayouts.sectionId, container?.id ?? "missing"),
|
||||
});
|
||||
for (const layoutId of ["target-base", "target-mobile"]) {
|
||||
const positions = groupedLayouts.filter((layout) => layout.layoutId === layoutId);
|
||||
const containerLayout = containerLayouts.find((layout) => layout.layoutId === layoutId);
|
||||
expect(containerLayout).toBeDefined();
|
||||
expect(Math.max(...positions.map((position) => position.yOffset + position.height))).toBeLessThanOrEqual(
|
||||
containerLayout?.height ?? 0,
|
||||
);
|
||||
for (let firstIndex = 0; firstIndex < positions.length; firstIndex += 1) {
|
||||
for (let secondIndex = firstIndex + 1; secondIndex < positions.length; secondIndex += 1) {
|
||||
const firstPosition = positions[firstIndex];
|
||||
const secondPosition = positions[secondIndex];
|
||||
assert(firstPosition);
|
||||
assert(secondPosition);
|
||||
expect(rectanglesOverlap(firstPosition, secondPosition)).toBe(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
const rootBookmarks = await db.query.itemLayouts.findMany({
|
||||
where: (table, { and, eq, inArray }) =>
|
||||
and(eq(table.sectionId, "target-section"), inArray(table.layoutId, ["target-base", "target-mobile"])),
|
||||
});
|
||||
for (const containerLayout of containerLayouts) {
|
||||
const rootItem = rootBookmarks.find((layout) => layout.layoutId === containerLayout.layoutId);
|
||||
expect(rootItem).toBeDefined();
|
||||
assert(rootItem);
|
||||
expect(rectanglesOverlap(rootItem, containerLayout)).toBe(false);
|
||||
expect(containerLayout.width).toBeLessThanOrEqual(containerLayout.layoutId === "target-base" ? 8 : 3);
|
||||
}
|
||||
});
|
||||
|
||||
it("uses the main root and creates enabled sidebar roots transactionally", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await db.insert(boards).values({ id: "target", name: "target" });
|
||||
await db.insert(layouts).values({
|
||||
id: "target-base",
|
||||
boardId: "target",
|
||||
name: "Base",
|
||||
role: "base",
|
||||
columnCount: 10,
|
||||
breakpoint: 768,
|
||||
});
|
||||
await db.insert(sections).values([
|
||||
{ id: "right-root", boardId: "target", kind: "empty", xOffset: 1, yOffset: 0 },
|
||||
{ id: "main-root", boardId: "target", kind: "empty", xOffset: 0, yOffset: 0 },
|
||||
]);
|
||||
const input = completionInput("target");
|
||||
input.board.leftSidebar = true;
|
||||
input.board.rightSidebar = true;
|
||||
input.selectedWidgetKinds = ["clock"];
|
||||
|
||||
await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(await db.query.sections.findMany({ where: eq(sections.boardId, "target") })).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ id: "main-root", xOffset: 0 }),
|
||||
expect.objectContaining({ id: "right-root", xOffset: 1 }),
|
||||
expect.objectContaining({ xOffset: -1, kind: "empty" }),
|
||||
]),
|
||||
);
|
||||
expect(await db.query.itemLayouts.findFirst()).toMatchObject({ sectionId: "main-root" });
|
||||
expect(await db.query.layouts.findFirst({ where: eq(layouts.id, "target-base") })).toMatchObject({
|
||||
leftGutterColumnCount: 1,
|
||||
rightGutterColumnCount: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it("adopts one label board name for a fresh sole board and ignores sources for other board targets", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target", itemId: "seeded-content" });
|
||||
await db.update(boards).set({ name: "dashboard" }).where(eq(boards.id, "target"));
|
||||
const media = {
|
||||
sourceId: "docker:good:media",
|
||||
containerId: "media",
|
||||
host: "good",
|
||||
group: "Media",
|
||||
name: "Media",
|
||||
href: "http://media:3000",
|
||||
externalId: "media",
|
||||
boardName: "Media board",
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [media] }],
|
||||
services: [media],
|
||||
});
|
||||
const input = completionInput("target");
|
||||
input.selectedDockerSourceIds = [media.sourceId];
|
||||
|
||||
const result = await createCaller(db, claimToken).completeSetup(input);
|
||||
|
||||
expect(result.boardName).toBe("Media-board");
|
||||
expect(await db.query.boards.findFirst({ where: eq(boards.id, "target") })).toMatchObject({ name: "Media-board" });
|
||||
expect(await db.query.items.findFirst({ where: eq(items.id, "seeded-content") })).toBeDefined();
|
||||
|
||||
const conflictDb = createDb();
|
||||
const conflictClaim = await seedOnboardingAsync(conflictDb);
|
||||
await seedBoardAsync(conflictDb, { boardId: "target", itemId: "seeded-content" });
|
||||
await conflictDb.update(boards).set({ name: "dashboard" }).where(eq(boards.id, "target"));
|
||||
const other = { ...media, sourceId: "docker:good:other", containerId: "other", boardName: "Other board" };
|
||||
const ignoredIntegrationSource = {
|
||||
...other,
|
||||
sourceId: "docker:good:other-sonarr",
|
||||
containerId: "other-sonarr",
|
||||
externalId: "other-sonarr",
|
||||
integrationKind: "sonarr" as const,
|
||||
};
|
||||
listDiscoveredContainersAsync.mockResolvedValue({
|
||||
hosts: [{ host: "good", status: "success", containers: [], services: [media, other, ignoredIntegrationSource] }],
|
||||
services: [media, other, ignoredIntegrationSource],
|
||||
});
|
||||
const conflictInput = completionInput("target", "Media-board");
|
||||
const ignoredIntegrationId = stableIntegrationIdForSource(ignoredIntegrationSource.sourceId);
|
||||
await conflictDb.insert(integrations).values({
|
||||
id: ignoredIntegrationId,
|
||||
name: ignoredIntegrationSource.name,
|
||||
url: ignoredIntegrationSource.href,
|
||||
kind: ignoredIntegrationSource.integrationKind,
|
||||
});
|
||||
conflictInput.selectedIntegrationIds = [ignoredIntegrationId];
|
||||
conflictInput.selectedDockerSourceIds = [media.sourceId, other.sourceId, ignoredIntegrationSource.sourceId];
|
||||
const conflictResult = await createCaller(conflictDb, conflictClaim).completeSetup(conflictInput);
|
||||
expect(conflictResult.docker.ignoredSourceIds).toEqual([other.sourceId, ignoredIntegrationSource.sourceId]);
|
||||
expect(await conflictDb.query.boards.findFirst({ where: eq(boards.id, "target") })).toMatchObject({
|
||||
name: "Media-board",
|
||||
});
|
||||
expect(await conflictDb.query.items.findMany({ where: eq(items.kind, "calendar") })).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("rejects setup mutations from an unclaimed browser", async () => {
|
||||
const db = createDb();
|
||||
await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
await expect(createCaller(db).completeSetup(completionInput("target"))).rejects.toThrow(
|
||||
"This onboarding session is not claimed.",
|
||||
);
|
||||
});
|
||||
|
||||
it("requires an authenticated administrator once any user exists", async () => {
|
||||
const db = createDb();
|
||||
const claimToken = await seedOnboardingAsync(db);
|
||||
await seedBoardAsync(db, { boardId: "target" });
|
||||
await db.insert(users).values({ id: "owner", name: "owner" });
|
||||
await expect(createCaller(db, claimToken).completeSetup(completionInput("target"))).rejects.toThrow(
|
||||
"This onboarding session is not claimed.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("onboard.nextStep", () => {
|
||||
it("advances welcome exactly once", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "start" });
|
||||
const claim = await claimOnboardingAsync(db);
|
||||
if (claim.status !== "issued") throw new Error("Expected an onboarding claim");
|
||||
const caller = createCaller(db, claim.token);
|
||||
|
||||
await caller.nextStep();
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "setup", previousStep: "start" });
|
||||
await expect(caller.nextStep()).rejects.toThrow("The welcome step is already complete.");
|
||||
expect(await db.query.onboarding.findFirst()).toMatchObject({ step: "setup", previousStep: "start" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeOnboardingStep", () => {
|
||||
it("keeps legacy import backups eligible for restore from the start step", () => {
|
||||
expect(normalizeOnboardingStep("import")).toBe("start");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { eq } from "@homarr/db";
|
||||
import { onboarding, serverSettings, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
|
||||
import {
|
||||
claimOnboardingAsync,
|
||||
getOnboardingClaimTokenFromCookieHeader,
|
||||
isOnboardingClaimValidAsync,
|
||||
onboardingClaimCookieName,
|
||||
onboardingClaimSettingKey,
|
||||
} from "../../onboarding-claim";
|
||||
|
||||
describe("onboarding claim", () => {
|
||||
it("stores only a token hash and validates the claimed browser", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "start" });
|
||||
|
||||
const result = await claimOnboardingAsync(db, { now: 1_000, ttlMs: 10_000 });
|
||||
expect(result.status).toBe("issued");
|
||||
if (result.status !== "issued") throw new Error("Expected an issued claim");
|
||||
|
||||
const row = await db.query.serverSettings.findFirst({
|
||||
where: eq(serverSettings.settingKey, onboardingClaimSettingKey),
|
||||
});
|
||||
expect(row?.value).not.toContain(result.token);
|
||||
expect(await isOnboardingClaimValidAsync(db, result.token, 5_000)).toBe(true);
|
||||
expect(await isOnboardingClaimValidAsync(db, "not-the-token", 5_000)).toBe(false);
|
||||
});
|
||||
|
||||
it("does not let another browser replace a live claim", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "start" });
|
||||
const issued = await claimOnboardingAsync(db, { now: 1_000, ttlMs: 10_000 });
|
||||
if (issued.status !== "issued") throw new Error("Expected an issued claim");
|
||||
|
||||
expect(await claimOnboardingAsync(db, { now: 2_000 })).toEqual({
|
||||
status: "locked",
|
||||
expiresAt: 11_000,
|
||||
});
|
||||
expect(await claimOnboardingAsync(db, { currentToken: issued.token, now: 2_000 })).toEqual({
|
||||
status: "active",
|
||||
token: issued.token,
|
||||
expiresAt: 11_000,
|
||||
});
|
||||
});
|
||||
|
||||
it("allows a new claim after expiry and invalidates the old token", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "start" });
|
||||
const first = await claimOnboardingAsync(db, { now: 1_000, ttlMs: 100 });
|
||||
if (first.status !== "issued") throw new Error("Expected an issued claim");
|
||||
|
||||
const second = await claimOnboardingAsync(db, { now: 1_101, ttlMs: 100 });
|
||||
if (second.status !== "issued") throw new Error("Expected a replacement claim");
|
||||
expect(second.token).not.toBe(first.token);
|
||||
expect(await isOnboardingClaimValidAsync(db, first.token, 1_102)).toBe(false);
|
||||
expect(await isOnboardingClaimValidAsync(db, second.token, 1_102)).toBe(true);
|
||||
});
|
||||
|
||||
it("refuses claims after setup finishes", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "finish", previousStep: "setup" });
|
||||
await expect(claimOnboardingAsync(db)).resolves.toEqual({ status: "finished" });
|
||||
});
|
||||
|
||||
it("requires an administrator to rotate claims after a user exists", async () => {
|
||||
const db = createDb();
|
||||
await db.insert(onboarding).values({ id: "onboarding", step: "setup", previousStep: "user" });
|
||||
await db.insert(users).values({ id: "owner", name: "owner" });
|
||||
await expect(claimOnboardingAsync(db)).resolves.toEqual({ status: "forbidden" });
|
||||
await expect(claimOnboardingAsync(db, { force: true })).resolves.toMatchObject({ status: "issued" });
|
||||
});
|
||||
|
||||
it("extracts only the exact claim cookie", () => {
|
||||
expect(
|
||||
getOnboardingClaimTokenFromCookieHeader(`theme=dark; ${onboardingClaimCookieName}=secret-token; other=x`),
|
||||
).toBe("secret-token");
|
||||
expect(getOnboardingClaimTokenFromCookieHeader(`${onboardingClaimCookieName}-copy=wrong`)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import { invites, onboarding, users } from "@homarr/db/schema";
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import type { GroupPermissionKey, OnboardingStep } from "@homarr/definitions";
|
||||
|
||||
import { claimOnboardingAsync } from "../../onboarding-claim";
|
||||
import { userRouter } from "../user";
|
||||
|
||||
const defaultOwnerId = createId();
|
||||
@@ -40,11 +41,12 @@ vi.mock("@homarr/auth/env", () => {
|
||||
describe("initUser should initialize the first user", () => {
|
||||
it("should create a user if none exists", async () => {
|
||||
const db = createDb();
|
||||
await createOnboardingStepAsync(db, "user");
|
||||
const onboardingClaimToken = await createOnboardingStepAsync(db, "user");
|
||||
const caller = userRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
onboardingClaimToken,
|
||||
});
|
||||
|
||||
await caller.initUser({
|
||||
@@ -64,11 +66,12 @@ describe("initUser should initialize the first user", () => {
|
||||
|
||||
it("should not create a user if the password and confirmPassword do not match", async () => {
|
||||
const db = createDb();
|
||||
await createOnboardingStepAsync(db, "user");
|
||||
const onboardingClaimToken = await createOnboardingStepAsync(db, "user");
|
||||
const caller = userRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
onboardingClaimToken,
|
||||
});
|
||||
|
||||
const actAsync = async () =>
|
||||
@@ -83,11 +86,12 @@ describe("initUser should initialize the first user", () => {
|
||||
|
||||
it.each([["aB2%"], ["short"]])("should reject passwords shorter than 8 characters for '%s'", async (password) => {
|
||||
const db = createDb();
|
||||
await createOnboardingStepAsync(db, "user");
|
||||
const onboardingClaimToken = await createOnboardingStepAsync(db, "user");
|
||||
const caller = userRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
onboardingClaimToken,
|
||||
});
|
||||
|
||||
const actAsync = async () =>
|
||||
@@ -102,11 +106,12 @@ describe("initUser should initialize the first user", () => {
|
||||
|
||||
it("should accept passwords without complexity requirements", async () => {
|
||||
const db = createDb();
|
||||
await createOnboardingStepAsync(db, "user");
|
||||
const onboardingClaimToken = await createOnboardingStepAsync(db, "user");
|
||||
const caller = userRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
onboardingClaimToken,
|
||||
});
|
||||
|
||||
await caller.initUser({
|
||||
@@ -126,11 +131,12 @@ describe("initUser should initialize the first user", () => {
|
||||
|
||||
it("should accept passwords with special characters like LoveHomarr<3", async () => {
|
||||
const db = createDb();
|
||||
await createOnboardingStepAsync(db, "user");
|
||||
const onboardingClaimToken = await createOnboardingStepAsync(db, "user");
|
||||
const caller = userRouter.createCaller({
|
||||
db,
|
||||
deviceType: undefined,
|
||||
session: null,
|
||||
onboardingClaimToken,
|
||||
});
|
||||
|
||||
await caller.initUser({
|
||||
@@ -439,4 +445,7 @@ const createOnboardingStepAsync = async (db: Database, step: OnboardingStep) =>
|
||||
id: createId(),
|
||||
step,
|
||||
});
|
||||
const claim = await claimOnboardingAsync(db);
|
||||
if (claim.status !== "issued") throw new Error("Expected an onboarding claim");
|
||||
return claim.token;
|
||||
};
|
||||
@@ -4,12 +4,13 @@ import type { QueryResult } from "pg";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { comparePasswordsAsync, hashPasswordAsync } from "@homarr/auth";
|
||||
import { isProviderEnabled } from "@homarr/auth/server";
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { and, eq, handleTransactionsAsync, inArray, like } from "@homarr/db";
|
||||
import { getMaxGroupPositionAsync } from "@homarr/db/queries";
|
||||
import { boards, groupMembers, groupPermissions, groups, invites, users } from "@homarr/db/schema";
|
||||
import { boards, groupMembers, groupPermissions, groups, invites, onboarding, users } from "@homarr/db/schema";
|
||||
import { selectUserSchema } from "@homarr/db/validationSchemas";
|
||||
import type { SupportedAuthProvider } from "@homarr/definitions";
|
||||
import { credentialsAdminGroup, supportedAuthProviders } from "@homarr/definitions";
|
||||
@@ -41,7 +42,6 @@ import {
|
||||
} from "../trpc";
|
||||
import { throwIfActionForbiddenAsync } from "./board/board-access";
|
||||
import { throwIfCredentialsDisabled } from "./invite/checks";
|
||||
import { nextOnboardingStepAsync } from "./onboard/onboard-queries";
|
||||
import { changeSearchPreferencesAsync, changeSearchPreferencesInputSchema } from "./user/change-search-preferences";
|
||||
|
||||
const logger = createLogger({ module: "userRouter" });
|
||||
@@ -52,25 +52,47 @@ export const userRouter = createTRPCRouter({
|
||||
.input(userInitSchema)
|
||||
.mutation(async ({ ctx, input }) => {
|
||||
throwIfCredentialsDisabled();
|
||||
await checkUsernameAlreadyTakenAndThrowAsync(ctx.db, "credentials", input.username);
|
||||
|
||||
const maxPosition = await getMaxGroupPositionAsync(ctx.db);
|
||||
const userId = await createUserAsync(ctx.db, input);
|
||||
const hashedPassword = await hashPasswordAsync(input.password);
|
||||
const userId = createId();
|
||||
const groupId = createId();
|
||||
await ctx.db.insert(groups).values({
|
||||
const userRow = {
|
||||
id: userId,
|
||||
name: input.username,
|
||||
email: input.email,
|
||||
password: hashedPassword,
|
||||
};
|
||||
const groupRow = {
|
||||
id: groupId,
|
||||
name: credentialsAdminGroup,
|
||||
ownerId: userId,
|
||||
position: maxPosition + 1,
|
||||
};
|
||||
|
||||
await handleTransactionsAsync(ctx.db, {
|
||||
async handleAsync(db, schema) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await transaction.insert(schema.users).values(userRow);
|
||||
await transaction.insert(schema.groups).values(groupRow);
|
||||
await transaction.insert(schema.groupPermissions).values({ groupId, permission: "admin" });
|
||||
await transaction.insert(schema.groupMembers).values({ groupId, userId });
|
||||
const nextStep = isProviderEnabled("ldap") || isProviderEnabled("oidc") ? "group" : "setup";
|
||||
await transaction.update(schema.onboarding).set({ previousStep: "user", step: nextStep });
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
transaction.insert(users).values(userRow).run();
|
||||
transaction.insert(groups).values(groupRow).run();
|
||||
transaction.insert(groupPermissions).values({ groupId, permission: "admin" }).run();
|
||||
transaction.insert(groupMembers).values({ groupId, userId }).run();
|
||||
const nextStep = isProviderEnabled("ldap") || isProviderEnabled("oidc") ? "group" : "setup";
|
||||
transaction.update(onboarding).set({ previousStep: "user", step: nextStep }).run();
|
||||
});
|
||||
},
|
||||
});
|
||||
await ctx.db.insert(groupPermissions).values({
|
||||
groupId,
|
||||
permission: "admin",
|
||||
});
|
||||
await ctx.db.insert(groupMembers).values({
|
||||
groupId,
|
||||
userId,
|
||||
});
|
||||
await nextOnboardingStepAsync(ctx.db, undefined);
|
||||
}),
|
||||
register: publicProcedure
|
||||
.input(userRegistrationApiSchema)
|
||||
|
||||
@@ -20,6 +20,7 @@ import { db } from "@homarr/db";
|
||||
import type { GroupPermissionKey, OnboardingStep } from "@homarr/definitions";
|
||||
|
||||
import { env } from "./env";
|
||||
import { getOnboardingClaimTokenFromCookieHeader, isClaimOnlyOnboardingAccessAllowedAsync } from "./onboarding-claim";
|
||||
import { getOnboardingOrFallbackAsync } from "./router/onboard/onboard-queries";
|
||||
import type { McpMeta } from "./mcp-tools";
|
||||
|
||||
@@ -41,6 +42,7 @@ interface ApiContext {
|
||||
session: Session | null;
|
||||
deviceType: DeviceType;
|
||||
baseUrl?: `${string}://${string}`;
|
||||
onboardingClaimToken?: string;
|
||||
db: typeof db;
|
||||
}
|
||||
|
||||
@@ -58,6 +60,7 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
|
||||
session,
|
||||
deviceType: userAgent(opts.headers).device.type,
|
||||
baseUrl: extractBaseUrlFromHeaders(opts.headers),
|
||||
onboardingClaimToken: getOnboardingClaimTokenFromCookieHeader(opts.headers.get("cookie")),
|
||||
db,
|
||||
};
|
||||
};
|
||||
@@ -129,6 +132,19 @@ const baseProcedure = isDemoReadOnly ? t.procedure.use(enforceDemoModeReadOnly)
|
||||
*/
|
||||
export const publicProcedure = baseProcedure;
|
||||
|
||||
const enforceOnboardingAccess = t.middleware(async ({ ctx, next }) => {
|
||||
const isAdmin = ctx.session?.user.permissions.includes("admin") ?? false;
|
||||
if (!isAdmin) {
|
||||
const hasValidClaim = await isClaimOnlyOnboardingAccessAllowedAsync(ctx.db, ctx.onboardingClaimToken);
|
||||
if (!hasValidClaim) {
|
||||
throw new TRPCError({ code: "FORBIDDEN", message: "This onboarding session is not claimed." });
|
||||
}
|
||||
}
|
||||
return next({ ctx });
|
||||
});
|
||||
|
||||
export const onboardingClaimedProcedure = baseProcedure.use(enforceOnboardingAccess);
|
||||
|
||||
export const internalProcedure = t.procedure;
|
||||
|
||||
const enforceUserIsAuthed = t.middleware(({ ctx, next }) => {
|
||||
@@ -177,7 +193,7 @@ export const permissionRequiredProcedure = {
|
||||
|
||||
export const onboardingProcedure = {
|
||||
requiresStep: (step: OnboardingStep) => {
|
||||
return publicProcedure.use(async ({ ctx, input, next }) => {
|
||||
return onboardingClaimedProcedure.use(async ({ ctx, input, next }) => {
|
||||
const currentStep = await getOnboardingOrFallbackAsync(ctx.db).then(({ current }) => current);
|
||||
if (currentStep !== step) {
|
||||
throw new TRPCError({
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
"exports": {
|
||||
"./context": "./src/context.tsx",
|
||||
"./layout-selection": "./src/layout-selection.ts",
|
||||
"./layout-preview": "./src/layout-preview.ts",
|
||||
"./updater": "./src/updater.ts",
|
||||
"./edit-mode": "./src/edit-mode.tsx"
|
||||
},
|
||||
@@ -25,6 +26,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@homarr/api": "workspace:^0.1.0",
|
||||
"@homarr/common": "workspace:^0.1.0",
|
||||
"@homarr/definitions": "workspace:^0.1.0",
|
||||
"react": "catalog:",
|
||||
"react-dom": "catalog:"
|
||||
},
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { BoardPreviewData, BoardPreviewLayout } from "./layout-preview";
|
||||
import { getRepresentativeLayoutWidth, projectBoardLayout } from "./layout-preview";
|
||||
|
||||
const mobile = {
|
||||
id: "mobile",
|
||||
columnCount: 3,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 0,
|
||||
role: "mobile",
|
||||
} satisfies BoardPreviewLayout;
|
||||
const custom = {
|
||||
id: "tablet",
|
||||
columnCount: 6,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 480,
|
||||
role: "custom",
|
||||
} satisfies BoardPreviewLayout;
|
||||
const base = {
|
||||
id: "base",
|
||||
columnCount: 12,
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: 768,
|
||||
role: "base",
|
||||
} satisfies BoardPreviewLayout;
|
||||
|
||||
const root = { id: "root", kind: "empty" as const, xOffset: 0, layouts: [] };
|
||||
|
||||
describe("layout representative widths", () => {
|
||||
test("uses phone, activation midpoint, and desktop widths", () => {
|
||||
const layouts = [mobile, custom, base];
|
||||
expect(getRepresentativeLayoutWidth(mobile, layouts)).toBe(390);
|
||||
expect(getRepresentativeLayoutWidth(custom, layouts)).toBe(624);
|
||||
expect(getRepresentativeLayoutWidth(base, layouts)).toBe(1280);
|
||||
});
|
||||
});
|
||||
|
||||
describe("projectBoardLayout", () => {
|
||||
test("keeps exact saved positions for the active layout", () => {
|
||||
const board = {
|
||||
layouts: [mobile],
|
||||
sections: [
|
||||
root,
|
||||
{
|
||||
id: "container",
|
||||
kind: "container",
|
||||
xOffset: null,
|
||||
layouts: [
|
||||
{
|
||||
layoutId: mobile.id,
|
||||
parentSectionId: root.id,
|
||||
width: 3,
|
||||
height: 2,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: [],
|
||||
} satisfies BoardPreviewData;
|
||||
|
||||
expect(projectBoardLayout(board, mobile, mobile)).toEqual([
|
||||
expect.objectContaining({ id: "container", sectionId: root.id, width: 3, height: 2 }),
|
||||
]);
|
||||
});
|
||||
|
||||
test("reflows root items and containers while retaining nested items", () => {
|
||||
const board = {
|
||||
layouts: [mobile, base],
|
||||
sections: [
|
||||
root,
|
||||
{
|
||||
id: "container",
|
||||
kind: "container",
|
||||
xOffset: null,
|
||||
layouts: [
|
||||
{
|
||||
layoutId: base.id,
|
||||
parentSectionId: root.id,
|
||||
width: 6,
|
||||
height: 3,
|
||||
xOffset: 6,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
items: [
|
||||
{
|
||||
id: "root-item",
|
||||
layouts: [
|
||||
{
|
||||
layoutId: base.id,
|
||||
sectionId: root.id,
|
||||
width: 5,
|
||||
height: 2,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "nested-item",
|
||||
layouts: [
|
||||
{
|
||||
layoutId: base.id,
|
||||
sectionId: "container",
|
||||
width: 4,
|
||||
height: 1,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
} satisfies BoardPreviewData;
|
||||
|
||||
const projected = projectBoardLayout(board, base, mobile);
|
||||
|
||||
expect(projected.find((element) => element.id === "root-item")).toMatchObject({
|
||||
type: "item",
|
||||
width: 3,
|
||||
height: 2,
|
||||
xOffset: 0,
|
||||
yOffset: 0,
|
||||
sectionId: root.id,
|
||||
});
|
||||
expect(projected.find((element) => element.id === "container")).toMatchObject({
|
||||
type: "section",
|
||||
width: 3,
|
||||
xOffset: 0,
|
||||
yOffset: 2,
|
||||
sectionId: root.id,
|
||||
});
|
||||
expect(projected.find((element) => element.id === "nested-item")).toMatchObject({
|
||||
type: "item",
|
||||
width: 3,
|
||||
sectionId: "container",
|
||||
});
|
||||
});
|
||||
|
||||
test("ignores missing positions and supports empty boards", () => {
|
||||
const board = {
|
||||
layouts: [mobile],
|
||||
sections: [root],
|
||||
items: [{ id: "missing", layouts: [] }],
|
||||
} satisfies BoardPreviewData;
|
||||
|
||||
expect(projectBoardLayout(board, base, mobile)).toEqual([]);
|
||||
});
|
||||
|
||||
test("moves fixed-rail items into the mobile canvas without overlap", () => {
|
||||
const baseWithRails = {
|
||||
...base,
|
||||
leftGutterColumnCount: 2,
|
||||
rightGutterColumnCount: 2,
|
||||
};
|
||||
const roots = [
|
||||
{ id: "left", kind: "empty" as const, xOffset: -1, layouts: [] },
|
||||
root,
|
||||
{ id: "right", kind: "empty" as const, xOffset: 1, layouts: [] },
|
||||
];
|
||||
const board = {
|
||||
layouts: [mobile, baseWithRails],
|
||||
sections: roots,
|
||||
items: roots.map((section, index) => ({
|
||||
id: `item-${section.id}`,
|
||||
layouts: [
|
||||
{
|
||||
layoutId: base.id,
|
||||
sectionId: section.id,
|
||||
width: 2,
|
||||
height: 1,
|
||||
xOffset: 0,
|
||||
yOffset: index,
|
||||
},
|
||||
],
|
||||
})),
|
||||
} satisfies BoardPreviewData;
|
||||
|
||||
const projected = projectBoardLayout(board, baseWithRails, mobile);
|
||||
|
||||
expect(projected).toHaveLength(3);
|
||||
expect(projected.every((element) => element.sectionId === root.id)).toBe(true);
|
||||
expect(projected.every((element) => element.xOffset >= 0 && element.xOffset + element.width <= 3)).toBe(true);
|
||||
for (const [index, element] of projected.entries()) {
|
||||
expect(
|
||||
projected
|
||||
.slice(index + 1)
|
||||
.some(
|
||||
(other) =>
|
||||
element.xOffset < other.xOffset + other.width &&
|
||||
element.xOffset + element.width > other.xOffset &&
|
||||
element.yOffset < other.yOffset + other.height &&
|
||||
element.yOffset + element.height > other.yOffset,
|
||||
),
|
||||
).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
test("returns an empty preview when malformed data has no main root", () => {
|
||||
const board = {
|
||||
layouts: [mobile, base],
|
||||
sections: [{ id: "left", kind: "empty", xOffset: -1, layouts: [] }],
|
||||
items: [],
|
||||
} satisfies BoardPreviewData;
|
||||
|
||||
expect(projectBoardLayout(board, base, mobile)).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,176 @@
|
||||
import { generateResponsiveGridFor } from "@homarr/common";
|
||||
import type { GridAlgorithmItem } from "@homarr/common";
|
||||
import type { BoardLane, LayoutRole } from "@homarr/definitions";
|
||||
import { boardLanes, getBoardLaneColumnCount, getRootSectionLane } from "@homarr/definitions";
|
||||
|
||||
export interface BoardPreviewLayout {
|
||||
id: string;
|
||||
columnCount: number;
|
||||
leftGutterColumnCount: number;
|
||||
rightGutterColumnCount: number;
|
||||
breakpoint: number;
|
||||
role: LayoutRole;
|
||||
}
|
||||
|
||||
interface BoardPreviewItemLayout {
|
||||
layoutId: string;
|
||||
sectionId: string;
|
||||
xOffset: number;
|
||||
yOffset: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface BoardPreviewSectionLayout {
|
||||
layoutId: string;
|
||||
parentSectionId: string | null;
|
||||
xOffset: number;
|
||||
yOffset: number;
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
export interface BoardPreviewData {
|
||||
layouts: readonly BoardPreviewLayout[];
|
||||
sections: readonly BoardPreviewSection[];
|
||||
items: readonly {
|
||||
id: string;
|
||||
layouts: readonly BoardPreviewItemLayout[];
|
||||
}[];
|
||||
}
|
||||
|
||||
type BoardPreviewSection =
|
||||
| {
|
||||
id: string;
|
||||
kind: "empty";
|
||||
xOffset: number | null;
|
||||
layouts?: readonly BoardPreviewSectionLayout[];
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
kind: "container";
|
||||
xOffset?: number | null;
|
||||
layouts: readonly BoardPreviewSectionLayout[];
|
||||
};
|
||||
|
||||
type LayoutGeometry = Pick<
|
||||
BoardPreviewLayout,
|
||||
"id" | "columnCount" | "leftGutterColumnCount" | "rightGutterColumnCount"
|
||||
>;
|
||||
|
||||
export const getRepresentativeLayoutWidth = (layout: BoardPreviewLayout, allLayouts: readonly BoardPreviewLayout[]) => {
|
||||
if (layout.role === "mobile") return 390;
|
||||
if (layout.role === "base") return Math.max(1280, layout.breakpoint);
|
||||
|
||||
const nextLayout = allLayouts
|
||||
.filter((candidate) => candidate.breakpoint > layout.breakpoint)
|
||||
.toSorted((layoutA, layoutB) => layoutA.breakpoint - layoutB.breakpoint)
|
||||
.at(0);
|
||||
|
||||
return nextLayout ? Math.round((layout.breakpoint + nextLayout.breakpoint) / 2) : Math.max(1280, layout.breakpoint);
|
||||
};
|
||||
|
||||
export const projectBoardLayout = (
|
||||
board: BoardPreviewData,
|
||||
sourceLayout: LayoutGeometry,
|
||||
targetLayout: LayoutGeometry,
|
||||
) => {
|
||||
const elements = getElementsForLayout(board, sourceLayout.id);
|
||||
|
||||
if (
|
||||
sourceLayout.id === targetLayout.id &&
|
||||
sourceLayout.columnCount === targetLayout.columnCount &&
|
||||
sourceLayout.leftGutterColumnCount === targetLayout.leftGutterColumnCount &&
|
||||
sourceLayout.rightGutterColumnCount === targetLayout.rightGutterColumnCount
|
||||
) {
|
||||
return elements;
|
||||
}
|
||||
|
||||
const emptyRoots = board.sections
|
||||
.filter((section) => section.kind === "empty")
|
||||
.toSorted((first, second) => (first.xOffset ?? 0) - (second.xOffset ?? 0) || first.id.localeCompare(second.id));
|
||||
const rootByLane = new Map<BoardLane, (typeof emptyRoots)[number]>();
|
||||
for (const root of emptyRoots) {
|
||||
const lane = getRootSectionLane(root.xOffset);
|
||||
if (!rootByLane.has(lane)) rootByLane.set(lane, root);
|
||||
}
|
||||
|
||||
const mainRoot = rootByLane.get("main");
|
||||
if (!mainRoot) return [];
|
||||
|
||||
const sourceRootById = new Map(
|
||||
emptyRoots.map((section) => [section.id, getRootSectionLane(section.xOffset)] as const),
|
||||
);
|
||||
const targetLaneBySourceLane = new Map<BoardLane, BoardLane>(
|
||||
boardLanes.map((lane) => [
|
||||
lane,
|
||||
lane !== "main" && getBoardLaneColumnCount(targetLayout, lane) === 0 ? "main" : lane,
|
||||
]),
|
||||
);
|
||||
const remappedElements = elements.map((element) => {
|
||||
const sourceLane = sourceRootById.get(element.sectionId);
|
||||
if (!sourceLane) return element;
|
||||
const targetLane = targetLaneBySourceLane.get(sourceLane) ?? "main";
|
||||
return { ...element, sectionId: (rootByLane.get(targetLane) ?? mainRoot).id };
|
||||
});
|
||||
|
||||
return boardLanes.flatMap((lane) => {
|
||||
const root = rootByLane.get(lane);
|
||||
const width = getBoardLaneColumnCount(targetLayout, lane);
|
||||
if (!root || width === 0) return [];
|
||||
|
||||
const sourceLanes = boardLanes.filter(
|
||||
(sourceLane) =>
|
||||
rootByLane.has(sourceLane) &&
|
||||
getBoardLaneColumnCount(sourceLayout, sourceLane) > 0 &&
|
||||
targetLaneBySourceLane.get(sourceLane) === lane,
|
||||
);
|
||||
const previousWidth =
|
||||
sourceLanes.length === 1
|
||||
? getBoardLaneColumnCount(sourceLayout, sourceLanes[0] ?? "main")
|
||||
: Number.MAX_SAFE_INTEGER;
|
||||
|
||||
return generateResponsiveGridFor({
|
||||
items: remappedElements,
|
||||
previousWidth,
|
||||
width,
|
||||
sectionId: root.id,
|
||||
}).items;
|
||||
});
|
||||
};
|
||||
|
||||
const getElementsForLayout = (board: BoardPreviewData, layoutId: string): GridAlgorithmItem[] => [
|
||||
...board.items.flatMap((item) => {
|
||||
const layout = item.layouts.find((candidate) => candidate.layoutId === layoutId);
|
||||
return layout
|
||||
? [
|
||||
{
|
||||
id: item.id,
|
||||
type: "item" as const,
|
||||
height: layout.height,
|
||||
width: layout.width,
|
||||
xOffset: layout.xOffset,
|
||||
yOffset: layout.yOffset,
|
||||
sectionId: layout.sectionId,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
...board.sections.flatMap((section) => {
|
||||
if (section.kind !== "container") return [];
|
||||
const layout = section.layouts.find((candidate) => candidate.layoutId === layoutId);
|
||||
return layout?.parentSectionId
|
||||
? [
|
||||
{
|
||||
id: section.id,
|
||||
type: "section" as const,
|
||||
height: layout.height,
|
||||
width: layout.width,
|
||||
xOffset: layout.xOffset,
|
||||
yOffset: layout.yOffset,
|
||||
sectionId: layout.parentSectionId,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
}),
|
||||
];
|
||||
@@ -686,7 +686,7 @@ const seedDemoUserAsync = async (db: Database) => {
|
||||
|
||||
await db.update(onboarding).set({
|
||||
step: "finish",
|
||||
previousStep: "settings",
|
||||
previousStep: "setup",
|
||||
});
|
||||
|
||||
const integrationId = createId();
|
||||
|
||||
@@ -8,10 +8,24 @@ export type UrlTemplateMode = "hostPort" | "subdomain";
|
||||
|
||||
const getSlugForKind = (kind: IntegrationKind): string => integrationIconSlugs[kind];
|
||||
|
||||
const buildUrl = (slug: string, host: string, mode: UrlTemplateMode, port?: number): string => {
|
||||
const normalizeBaseHost = (value: string) => {
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed) return null;
|
||||
try {
|
||||
const parsed = new URL(trimmed.includes("://") ? trimmed : `http://${trimmed}`);
|
||||
return { hostname: parsed.hostname, port: parsed.port ? Number(parsed.port) : undefined };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const buildUrl = (slug: string, rawHost: string, mode: UrlTemplateMode, port?: number): string => {
|
||||
const base = normalizeBaseHost(rawHost);
|
||||
if (!base) return "";
|
||||
const effectivePort = port ?? base.port;
|
||||
const modeBuilders: Record<UrlTemplateMode, () => string> = {
|
||||
subdomain: () => `https://${slug}.${host}`,
|
||||
hostPort: () => (port ? `http://${host}:${port}` : `http://${host}`),
|
||||
subdomain: () => (base.hostname.startsWith("[") ? "" : `https://${slug}.${base.hostname}`),
|
||||
hostPort: () => (effectivePort ? `http://${base.hostname}:${effectivePort}` : `http://${base.hostname}`),
|
||||
};
|
||||
return modeBuilders[mode]();
|
||||
};
|
||||
@@ -23,7 +37,6 @@ export const buildIntegrationUrl = (
|
||||
dockerPort?: number,
|
||||
): string => {
|
||||
const host = removeTrailingSlash(baseHost.trim());
|
||||
if (!host) return "";
|
||||
const port = dockerPort ?? getIntegrationDefaultPort(kind);
|
||||
return buildUrl(getSlugForKind(kind), host, mode, port ?? undefined);
|
||||
};
|
||||
@@ -35,7 +48,6 @@ export const buildAppUrl = (
|
||||
dockerPort?: number,
|
||||
): string => {
|
||||
const host = removeTrailingSlash(baseHost.trim());
|
||||
if (!host) return "";
|
||||
const slug = containerName.toLowerCase().replace(/[^a-z0-9-]/g, "-");
|
||||
return buildUrl(slug, host, mode, dockerPort);
|
||||
};
|
||||
@@ -222,6 +222,7 @@ export const integrationDefs = {
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/selfhst/icons/svg/technitium.svg",
|
||||
category: ["dnsHole"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/technitium-dns"),
|
||||
defaultPort: 5380,
|
||||
},
|
||||
homeAssistant: {
|
||||
name: "Home Assistant",
|
||||
@@ -230,6 +231,7 @@ export const integrationDefs = {
|
||||
category: ["smartHomeServer", "calendar"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/home-assistant"),
|
||||
defaultPort: 8123,
|
||||
apiKeySettingsPath: "/profile/security",
|
||||
},
|
||||
openmediavault: {
|
||||
name: "OpenMediaVault",
|
||||
@@ -245,13 +247,14 @@ export const integrationDefs = {
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/png/dashdot.png",
|
||||
category: ["healthMonitoring"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/dash-dot"),
|
||||
defaultPort: 3001,
|
||||
},
|
||||
glances: {
|
||||
name: "Glances",
|
||||
secretKinds: [[]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/glances.svg",
|
||||
category: ["healthMonitoring"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/glances"),
|
||||
defaultPort: 61208,
|
||||
},
|
||||
tdarr: {
|
||||
@@ -293,6 +296,7 @@ export const integrationDefs = {
|
||||
category: ["firewall"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/opnsense"),
|
||||
defaultPort: 443,
|
||||
apiKeySettingsPath: "/system_usermanager.php",
|
||||
},
|
||||
ntfy: {
|
||||
name: "ntfy",
|
||||
@@ -301,6 +305,7 @@ export const integrationDefs = {
|
||||
category: ["notifications"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/ntfy"),
|
||||
defaultPort: 80,
|
||||
apiKeySettingsPath: "/account",
|
||||
},
|
||||
gotify: {
|
||||
name: "Gotify",
|
||||
@@ -308,6 +313,7 @@ export const integrationDefs = {
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gotify.svg",
|
||||
category: ["notifications"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/gotify"),
|
||||
defaultPort: 80,
|
||||
},
|
||||
ical: {
|
||||
name: "iCal",
|
||||
@@ -323,6 +329,7 @@ export const integrationDefs = {
|
||||
category: ["notes"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/anchor"),
|
||||
defaultPort: 8080,
|
||||
apiKeySettingsPath: "/settings",
|
||||
},
|
||||
truenas: {
|
||||
name: "TrueNAS",
|
||||
@@ -347,6 +354,7 @@ export const integrationDefs = {
|
||||
category: ["healthMonitoring"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/unraid"),
|
||||
defaultPort: 80,
|
||||
apiKeySettingsPath: "/Settings/ManagementAccess",
|
||||
},
|
||||
coolify: {
|
||||
name: "Coolify",
|
||||
@@ -355,6 +363,7 @@ export const integrationDefs = {
|
||||
category: ["healthMonitoring"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/coolify"),
|
||||
defaultPort: 8000,
|
||||
apiKeySettingsPath: "/security/api-tokens",
|
||||
},
|
||||
immich: {
|
||||
name: "Immich",
|
||||
@@ -363,13 +372,14 @@ export const integrationDefs = {
|
||||
category: ["photoService"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/immich"),
|
||||
defaultPort: 2283,
|
||||
apiKeySettingsPath: "/user-settings",
|
||||
},
|
||||
paperlessNgx: {
|
||||
name: "Paperless-ngx",
|
||||
secretKinds: [["apiKey"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/paperless-ngx.svg",
|
||||
category: ["documents"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/paperless-ngx"),
|
||||
defaultPort: 8000,
|
||||
},
|
||||
patchmon: {
|
||||
@@ -388,6 +398,7 @@ export const integrationDefs = {
|
||||
category: ["mediaMonitoring"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/tracearr"),
|
||||
defaultPort: 7040,
|
||||
apiKeySettingsPath: "/settings",
|
||||
},
|
||||
speedtestTracker: {
|
||||
name: "Speedtest Tracker",
|
||||
@@ -396,21 +407,23 @@ export const integrationDefs = {
|
||||
category: ["speedtest"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/speedtest-tracker"),
|
||||
defaultPort: 80,
|
||||
apiKeySettingsPath: "/admin/api-tokens",
|
||||
},
|
||||
uptimeKuma: {
|
||||
name: "Uptime Kuma",
|
||||
secretKinds: [[], ["slug"], ["slug", "apiKey"], ["apiKey"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/uptime-kuma.svg",
|
||||
category: ["uptimeMonitoring"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/uptime-kuma"),
|
||||
defaultPort: 3001,
|
||||
apiKeySettingsPath: "/settings/api-keys",
|
||||
},
|
||||
audiobookshelf: {
|
||||
name: "Audiobookshelf",
|
||||
secretKinds: [["apiKey"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/audiobookshelf.svg",
|
||||
category: ["mediaLibrary"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/audiobookshelf"),
|
||||
defaultPort: 13378,
|
||||
apiKeySettingsPath: "/account",
|
||||
},
|
||||
@@ -419,7 +432,7 @@ export const integrationDefs = {
|
||||
secretKinds: [["username", "password"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/navidrome.svg",
|
||||
category: ["mediaLibrary", "mediaService"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/navidrome"),
|
||||
defaultPort: 4533,
|
||||
},
|
||||
umami: {
|
||||
@@ -436,7 +449,8 @@ export const integrationDefs = {
|
||||
secretKinds: [["username", "password"], []],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/peanut.svg",
|
||||
category: ["ups"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/peanut"),
|
||||
defaultPort: 8080,
|
||||
},
|
||||
beszel: {
|
||||
name: "Beszel",
|
||||
@@ -452,6 +466,7 @@ export const integrationDefs = {
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/gluetun.svg",
|
||||
category: ["vpn"],
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/gluetun"),
|
||||
defaultPort: 8000,
|
||||
},
|
||||
traefik: {
|
||||
name: "Traefik",
|
||||
@@ -466,7 +481,8 @@ export const integrationDefs = {
|
||||
secretKinds: [[], ["username", "password"]],
|
||||
iconUrl: "https://cdn.jsdelivr.net/gh/selfhst/icons/png/archiveteam-warrior.png",
|
||||
category: ["archiving"],
|
||||
documentationUrl: null,
|
||||
documentationUrl: createDocumentationLink("/docs/integrations/archiveteam-warrior"),
|
||||
defaultPort: 8001,
|
||||
},
|
||||
wud: {
|
||||
name: "What's Up Docker",
|
||||
@@ -524,6 +540,9 @@ export const getIntegrationDefaultPort = (kind: IntegrationKind): number | undef
|
||||
return "defaultPort" in definition ? definition.defaultPort : undefined;
|
||||
};
|
||||
|
||||
export const getIntegrationDocumentationUrl = (kind: IntegrationKind): string | null =>
|
||||
integrationDefs[kind].documentationUrl;
|
||||
|
||||
export const getIntegrationApiKeyUrl = (integrationUrl: string, kind: IntegrationKind): string | null => {
|
||||
const definition = integrationDefs[kind];
|
||||
if (!("apiKeySettingsPath" in definition)) return null;
|
||||
|
||||
@@ -1,2 +1,5 @@
|
||||
export const onboardingSteps = ["start", "import", "user", "group", "settings", "integrations", "finish"] as const;
|
||||
export const onboardingSteps = ["start", "user", "group", "setup", "finish"] as const;
|
||||
export type OnboardingStep = (typeof onboardingSteps)[number];
|
||||
|
||||
export const onboardingLayoutPresets = ["balanced", "wide", "focused"] as const;
|
||||
export type OnboardingLayoutPreset = (typeof onboardingLayoutPresets)[number];
|
||||
@@ -1,8 +1,16 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getIntegrationApiKeyUrl } from "../integration";
|
||||
import { getIntegrationApiKeyUrl, integrationDefs } from "../integration";
|
||||
|
||||
describe("getIntegrationApiKeyUrl", () => {
|
||||
it("links every user-facing integration to its Homarr setup guide", () => {
|
||||
expect(
|
||||
Object.entries(integrationDefs)
|
||||
.filter(([kind, definition]) => kind !== "mock" && !definition.documentationUrl)
|
||||
.map(([kind]) => kind),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("builds URL for sonarr", () => {
|
||||
expect(getIntegrationApiKeyUrl("http://192.168.1.10:8989", "sonarr")).toBe(
|
||||
"http://192.168.1.10:8989/settings/general",
|
||||
@@ -21,10 +29,28 @@ describe("getIntegrationApiKeyUrl", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null for integrations without apiKeySettingsPath", () => {
|
||||
expect(getIntegrationApiKeyUrl("http://localhost", "plex")).toBeNull();
|
||||
it.each([
|
||||
["homeAssistant", "http://homeassistant.local:8123", "http://homeassistant.local:8123/profile/security"],
|
||||
["opnsense", "https://firewall.local", "https://firewall.local/system_usermanager.php"],
|
||||
["ntfy", "https://ntfy.local", "https://ntfy.local/account"],
|
||||
["anchor", "http://anchor.local:8080", "http://anchor.local:8080/settings"],
|
||||
["unraid", "http://tower.local", "http://tower.local/Settings/ManagementAccess"],
|
||||
["coolify", "https://coolify.local", "https://coolify.local/security/api-tokens"],
|
||||
["immich", "http://immich.local:2283", "http://immich.local:2283/user-settings"],
|
||||
["tracearr", "http://tracearr.local:7040", "http://tracearr.local:7040/settings"],
|
||||
["speedtestTracker", "http://speedtest.local", "http://speedtest.local/admin/api-tokens"],
|
||||
["uptimeKuma", "http://uptime.local:3001", "http://uptime.local:3001/settings/api-keys"],
|
||||
] as const)("builds a verified credential URL for %s", (kind, baseUrl, expected) => {
|
||||
expect(getIntegrationApiKeyUrl(baseUrl, kind)).toBe(expected);
|
||||
});
|
||||
|
||||
it.each(["plex", "piHole", "truenas"] as const)(
|
||||
"returns null when %s has no version-safe credential path",
|
||||
(kind) => {
|
||||
expect(getIntegrationApiKeyUrl("http://localhost", kind)).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
it("returns null for empty URL", () => {
|
||||
expect(getIntegrationApiKeyUrl("", "sonarr")).toBeNull();
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { getIntegrationDefaultPort } from "../integration";
|
||||
import { buildIntegrationUrl } from "../integration-url-template";
|
||||
import { buildAppUrl, buildIntegrationUrl } from "../integration-url-template";
|
||||
|
||||
describe("buildIntegrationUrl", () => {
|
||||
it("builds subdomain URL", () => {
|
||||
@@ -25,6 +25,31 @@ describe("buildIntegrationUrl", () => {
|
||||
expect(buildIntegrationUrl("sonarr", "homelab.local///", "subdomain")).toBe("https://sonarr.homelab.local");
|
||||
});
|
||||
|
||||
it("accepts full URLs but ignores their path when suggesting service URLs", () => {
|
||||
expect(buildIntegrationUrl("sonarr", "https://home.example.com/homarr", "hostPort")).toBe(
|
||||
"http://home.example.com:8989",
|
||||
);
|
||||
expect(buildAppUrl("My Service", "http://home.example.com/path", "subdomain")).toBe(
|
||||
"https://my-service.home.example.com",
|
||||
);
|
||||
});
|
||||
|
||||
it("replaces a supplied base port instead of producing a double port", () => {
|
||||
expect(buildIntegrationUrl("sonarr", "https://home.example.com:8443/homarr", "hostPort")).toBe(
|
||||
"http://home.example.com:8989",
|
||||
);
|
||||
expect(buildAppUrl("My Service", "https://home.example.com:8443/homarr", "hostPort")).toBe(
|
||||
"http://home.example.com:8443",
|
||||
);
|
||||
});
|
||||
|
||||
it("formats IPv6 hosts safely in host-port mode", () => {
|
||||
expect(buildIntegrationUrl("sonarr", "https://[2001:db8::1]:8443/homarr", "hostPort")).toBe(
|
||||
"http://[2001:db8::1]:8989",
|
||||
);
|
||||
expect(buildIntegrationUrl("sonarr", "[2001:db8::1]", "subdomain")).toBe("");
|
||||
});
|
||||
|
||||
it("returns empty string for empty host", () => {
|
||||
expect(buildIntegrationUrl("sonarr", "", "subdomain")).toBe("");
|
||||
});
|
||||
@@ -37,5 +62,11 @@ describe("buildIntegrationUrl", () => {
|
||||
expect(getIntegrationDefaultPort("radarr")).toBe(7878);
|
||||
expect(getIntegrationDefaultPort("prowlarr")).toBe(9696);
|
||||
expect(getIntegrationDefaultPort("jellyfin")).toBe(8096);
|
||||
expect(getIntegrationDefaultPort("technitiumDns")).toBe(5380);
|
||||
expect(getIntegrationDefaultPort("dashDot")).toBe(3001);
|
||||
expect(getIntegrationDefaultPort("gotify")).toBe(80);
|
||||
expect(getIntegrationDefaultPort("peaNut")).toBe(8080);
|
||||
expect(getIntegrationDefaultPort("gluetun")).toBe(8000);
|
||||
expect(getIntegrationDefaultPort("archiveTeamWarrior")).toBe(8001);
|
||||
});
|
||||
});
|
||||
@@ -63,6 +63,40 @@ export const widgetIntegrationLimits: Partial<Record<WidgetKind, number>> = {
|
||||
audioStats: 1,
|
||||
};
|
||||
|
||||
export type WidgetIntegrationIssue =
|
||||
| { code: "integration-not-supported" }
|
||||
| { code: "integration-required" }
|
||||
| { code: "incompatible-integration"; incompatibleKinds: IntegrationKind[] }
|
||||
| { code: "integration-limit"; limit: number };
|
||||
|
||||
export const getWidgetIntegrationIssue = (
|
||||
widgetKind: WidgetKind,
|
||||
integrationKinds: readonly IntegrationKind[],
|
||||
): WidgetIntegrationIssue | null => {
|
||||
const supportedIntegrations = widgetIntegrationSupport[widgetKind];
|
||||
const integrationLimit = widgetIntegrationLimits[widgetKind] ?? Number.POSITIVE_INFINITY;
|
||||
if (integrationKinds.length > integrationLimit) return { code: "integration-limit", limit: integrationLimit };
|
||||
if (supportedIntegrations === undefined && integrationKinds.length > 0) return { code: "integration-not-supported" };
|
||||
if (
|
||||
supportedIntegrations !== undefined &&
|
||||
integrationKinds.length === 0 &&
|
||||
!widgetKindsWithOptionalIntegrations.has(widgetKind)
|
||||
) {
|
||||
return { code: "integration-required" };
|
||||
}
|
||||
const incompatibleKinds = integrationKinds.filter((kind) => !supportedIntegrations?.includes(kind));
|
||||
return incompatibleKinds.length > 0 ? { code: "incompatible-integration", incompatibleKinds } : null;
|
||||
};
|
||||
|
||||
export const getWidgetIntegrationIssueMessage = (widgetKind: WidgetKind, issue: WidgetIntegrationIssue) => {
|
||||
if (issue.code === "integration-limit") {
|
||||
return `${widgetKind} supports at most ${issue.limit} integration${issue.limit === 1 ? "" : "s"}`;
|
||||
}
|
||||
if (issue.code === "integration-not-supported") return `${widgetKind} does not support integrations`;
|
||||
if (issue.code === "integration-required") return `${widgetKind} requires an integration`;
|
||||
return `${widgetKind} does not support integration kind${issue.incompatibleKinds.length === 1 ? "" : "s"}: ${issue.incompatibleKinds.join(", ")}`;
|
||||
};
|
||||
|
||||
export const getWidgetKindsForIntegration = (integrationKind: IntegrationKind): WidgetKind[] => {
|
||||
const result: WidgetKind[] = [];
|
||||
for (const [widgetKind, supportedIntegrations] of Object.entries(widgetIntegrationSupport)) {
|
||||
|
||||
@@ -25,11 +25,13 @@
|
||||
"dependencies": {
|
||||
"@homarr/common": "workspace:^0.1.0",
|
||||
"@homarr/core": "workspace:^0.1.0",
|
||||
"@homarr/definitions": "workspace:^0.1.0",
|
||||
"dockerode": "catalog:"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@homarr/tsconfig": "workspace:^0.1.0",
|
||||
"@types/dockerode": "catalog:",
|
||||
"typescript": "catalog:"
|
||||
"typescript": "catalog:",
|
||||
"vitest": "catalog:"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export { listDiscoveredContainersAsync } from "./list-discovered-containers";
|
||||
export { parseContainerLabels, type ParseContainerLabelsOptions } from "./parse-container-labels";
|
||||
export type { DiscoveredService, DockerDiscoveryHostResult, DockerDiscoveryResult } from "./types";
|
||||
@@ -0,0 +1,83 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const listContainersA = vi.fn();
|
||||
const listContainersB = vi.fn();
|
||||
|
||||
vi.mock("../singleton", () => ({
|
||||
DockerSingleton: {
|
||||
getInstances: () => [
|
||||
{ host: "good", instance: { listContainers: listContainersA } },
|
||||
{ host: "bad", instance: { listContainers: listContainersB } },
|
||||
],
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/core/infrastructure/logs", () => ({
|
||||
createLogger: () => ({ warn: vi.fn() }),
|
||||
}));
|
||||
|
||||
import { listDiscoveredContainersAsync } from "./list-discovered-containers";
|
||||
|
||||
describe("listDiscoveredContainersAsync", () => {
|
||||
beforeEach(() => {
|
||||
listContainersA.mockReset();
|
||||
listContainersB.mockReset();
|
||||
});
|
||||
|
||||
it("preserves successful hosts when another Docker host fails", async () => {
|
||||
listContainersA.mockResolvedValue([
|
||||
{
|
||||
Id: "sonarr",
|
||||
Labels: {
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
},
|
||||
},
|
||||
]);
|
||||
listContainersB.mockRejectedValue(new Error("permission denied"));
|
||||
|
||||
const result = await listDiscoveredContainersAsync();
|
||||
|
||||
expect(result.services).toHaveLength(1);
|
||||
expect(result.hosts).toEqual([
|
||||
expect.objectContaining({ host: "good", status: "success" }),
|
||||
{
|
||||
host: "bad",
|
||||
status: "unavailable",
|
||||
reason: "permission denied",
|
||||
containers: [],
|
||||
services: [],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("times out a blackholed host without losing another host's result", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
listContainersA.mockResolvedValue([
|
||||
{
|
||||
Id: "sonarr",
|
||||
Labels: {
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
},
|
||||
},
|
||||
]);
|
||||
listContainersB.mockReturnValue(new Promise(() => undefined));
|
||||
|
||||
const resultPromise = listDiscoveredContainersAsync({}, 25);
|
||||
await vi.advanceTimersByTimeAsync(25);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result.services).toHaveLength(1);
|
||||
expect(result.hosts).toEqual([
|
||||
expect.objectContaining({ host: "good", status: "success" }),
|
||||
expect.objectContaining({ host: "bad", status: "unavailable", reason: "Docker discovery timed out for bad" }),
|
||||
]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
|
||||
|
||||
import { DockerSingleton } from "../singleton";
|
||||
import type { ParseContainerLabelsOptions } from "./parse-container-labels";
|
||||
import { parseContainerLabels } from "./parse-container-labels";
|
||||
import type { DockerDiscoveryHostResult, DockerDiscoveryResult } from "./types";
|
||||
|
||||
const logger = createLogger({ module: "dockerDiscovery" });
|
||||
export const dockerDiscoveryHostTimeoutMs = 5_000;
|
||||
|
||||
const withTimeoutAsync = async <T>(promise: Promise<T>, timeoutMs: number, host: string) => {
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
return await Promise.race([
|
||||
promise,
|
||||
new Promise<never>((_, reject) => {
|
||||
timeout = setTimeout(() => reject(new Error(`Docker discovery timed out for ${host}`)), timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
|
||||
const reasonFromError = (error: unknown) => {
|
||||
if (error instanceof Error && error.message.trim()) return error.message;
|
||||
return "Docker is not reachable";
|
||||
};
|
||||
|
||||
export const listDiscoveredContainersAsync = async (
|
||||
options: ParseContainerLabelsOptions = {},
|
||||
timeoutMs = dockerDiscoveryHostTimeoutMs,
|
||||
): Promise<DockerDiscoveryResult> => {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const settled = await Promise.allSettled(
|
||||
dockerInstances.map(async ({ instance, host }): Promise<DockerDiscoveryHostResult> => {
|
||||
const containers = await withTimeoutAsync(instance.listContainers({ all: false }), timeoutMs, host);
|
||||
const services = containers
|
||||
.map((container) => parseContainerLabels(container, host, options))
|
||||
.filter((service) => service !== null);
|
||||
return { host, status: "success", containers, services };
|
||||
}),
|
||||
);
|
||||
|
||||
const hosts = settled.map<DockerDiscoveryHostResult>((result, index) => {
|
||||
const host = dockerInstances[index]?.host ?? "unknown";
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
|
||||
logger.warn(new ErrorWithMetadata("Failed to list containers for discovery", { host }, { cause: result.reason }));
|
||||
return {
|
||||
host,
|
||||
status: "unavailable",
|
||||
reason: reasonFromError(result.reason),
|
||||
containers: [],
|
||||
services: [],
|
||||
};
|
||||
});
|
||||
|
||||
return {
|
||||
hosts,
|
||||
services: hosts.flatMap((result) => result.services),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseContainerLabels } from "./parse-container-labels";
|
||||
|
||||
const container = (Labels: Record<string, string>, Id = "container-1") => ({ Id, Labels });
|
||||
|
||||
describe("parseContainerLabels", () => {
|
||||
it("parses complete Homarr labels", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
"homarr.icon": "sonarr.svg",
|
||||
"homarr.description": "TV",
|
||||
"homarr.ping": "http://sonarr:8989/ping",
|
||||
"homarr.id": "sonarr-main",
|
||||
"homarr.board": "dashboard",
|
||||
"homarr.integration": "sonarr",
|
||||
"homarr.widget": "calendar",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toEqual({
|
||||
sourceId: "docker:socket:sonarr-main",
|
||||
containerId: "container-1",
|
||||
host: "socket",
|
||||
group: "Media",
|
||||
name: "Sonarr",
|
||||
href: "http://sonarr:8989",
|
||||
icon: "sonarr.svg",
|
||||
description: "TV",
|
||||
pingUrl: "http://sonarr:8989/ping",
|
||||
externalId: "sonarr-main",
|
||||
boardName: "dashboard",
|
||||
integrationKind: "sonarr",
|
||||
widgetKind: "calendar",
|
||||
});
|
||||
});
|
||||
|
||||
it("supports Homepage labels when Homarr labels are absent", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homepage.name": "Jellyfin",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://jellyfin:8096",
|
||||
"homepage.icon": "jellyfin.svg",
|
||||
}),
|
||||
"remote:2375",
|
||||
),
|
||||
).toMatchObject({
|
||||
sourceId: "docker:remote:2375:container-1",
|
||||
name: "Jellyfin",
|
||||
group: "Media",
|
||||
href: "http://jellyfin:8096",
|
||||
icon: "jellyfin.svg",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a labeled service without a group for root placement", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Status",
|
||||
"homarr.href": "http://status:3001",
|
||||
"homarr.widget": "clock",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toMatchObject({ name: "Status", href: "http://status:3001", group: undefined, widgetKind: "clock" });
|
||||
});
|
||||
|
||||
it("does not mix Homepage required fields into an explicitly Homarr-labeled service", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": "Sonarr",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("can disable Homepage fallback", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homepage.name": "Sonarr",
|
||||
"homepage.group": "Media",
|
||||
"homepage.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
{ readHomepageLabels: false },
|
||||
),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("ignores hidden and incomplete containers", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.hide": "true",
|
||||
"homarr.name": "Sonarr",
|
||||
"homarr.group": "Media",
|
||||
"homarr.href": "http://sonarr:8989",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toBeNull();
|
||||
expect(parseContainerLabels(container({ "homarr.name": "Sonarr" }), "socket")).toBeNull();
|
||||
});
|
||||
|
||||
it("trims values and ignores invalid integration and widget kinds", () => {
|
||||
expect(
|
||||
parseContainerLabels(
|
||||
container({
|
||||
"homarr.name": " Sonarr ",
|
||||
"homarr.group": " Media ",
|
||||
"homarr.href": " http://sonarr:8989 ",
|
||||
"homarr.integration": "not-real",
|
||||
"homarr.widget": "not-real",
|
||||
}),
|
||||
"socket",
|
||||
),
|
||||
).toMatchObject({
|
||||
name: "Sonarr",
|
||||
group: "Media",
|
||||
href: "http://sonarr:8989",
|
||||
integrationKind: undefined,
|
||||
widgetKind: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import type { ContainerInfo } from "dockerode";
|
||||
|
||||
import { integrationKinds, widgetKinds } from "@homarr/definitions";
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
|
||||
import { dockerLabels, homepageLabels } from "../labels";
|
||||
import type { DiscoveredService } from "./types";
|
||||
|
||||
export interface ParseContainerLabelsOptions {
|
||||
readHomepageLabels?: boolean;
|
||||
}
|
||||
|
||||
const integrationKindSet = new Set<string>(integrationKinds);
|
||||
const widgetKindSet = new Set<string>(widgetKinds);
|
||||
|
||||
const readLabel = (labels: Record<string, string>, key: string) => {
|
||||
const value = labels[key]?.trim();
|
||||
return value ? value : undefined;
|
||||
};
|
||||
|
||||
const resolveLabelValue = (
|
||||
labels: Record<string, string>,
|
||||
homarrKey: string,
|
||||
homepageKey: string,
|
||||
useHomepageFallback: boolean,
|
||||
) => readLabel(labels, homarrKey) ?? (useHomepageFallback ? readLabel(labels, homepageKey) : undefined);
|
||||
|
||||
const parseIntegrationKind = (value: string | undefined): IntegrationKind | undefined =>
|
||||
value && integrationKindSet.has(value) ? (value as IntegrationKind) : undefined;
|
||||
|
||||
const parseWidgetKind = (value: string | undefined): WidgetKind | undefined =>
|
||||
value && widgetKindSet.has(value) ? (value as WidgetKind) : undefined;
|
||||
|
||||
export const parseContainerLabels = (
|
||||
container: Pick<ContainerInfo, "Id" | "Labels">,
|
||||
host: string,
|
||||
options: ParseContainerLabelsOptions = {},
|
||||
): DiscoveredService | null => {
|
||||
const labels = container.Labels ?? {};
|
||||
if (dockerLabels.hide in labels) return null;
|
||||
|
||||
const readHomepageLabels = options.readHomepageLabels ?? true;
|
||||
const useHomepageFallback = readHomepageLabels && !readLabel(labels, dockerLabels.name);
|
||||
const name = resolveLabelValue(labels, dockerLabels.name, homepageLabels.name, useHomepageFallback);
|
||||
const href = resolveLabelValue(labels, dockerLabels.href, homepageLabels.href, useHomepageFallback);
|
||||
const group = resolveLabelValue(labels, dockerLabels.group, homepageLabels.group, useHomepageFallback);
|
||||
if (!name || !href) return null;
|
||||
|
||||
const externalId = readLabel(labels, dockerLabels.id) ?? container.Id;
|
||||
return {
|
||||
sourceId: `docker:${host}:${externalId}`,
|
||||
containerId: container.Id,
|
||||
host,
|
||||
group,
|
||||
name,
|
||||
href,
|
||||
icon: resolveLabelValue(labels, dockerLabels.icon, homepageLabels.icon, useHomepageFallback),
|
||||
description: resolveLabelValue(labels, dockerLabels.description, homepageLabels.description, useHomepageFallback),
|
||||
pingUrl: readLabel(labels, dockerLabels.ping),
|
||||
externalId,
|
||||
boardName: readLabel(labels, dockerLabels.board),
|
||||
integrationKind: parseIntegrationKind(readLabel(labels, dockerLabels.integration)),
|
||||
widgetKind: parseWidgetKind(readLabel(labels, dockerLabels.widget)),
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
import type { ContainerInfo } from "dockerode";
|
||||
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
|
||||
export interface DiscoveredService {
|
||||
sourceId: string;
|
||||
containerId: string;
|
||||
host: string;
|
||||
group?: string;
|
||||
name: string;
|
||||
href: string;
|
||||
icon?: string;
|
||||
description?: string;
|
||||
pingUrl?: string;
|
||||
externalId: string;
|
||||
boardName?: string;
|
||||
integrationKind?: IntegrationKind;
|
||||
widgetKind?: WidgetKind;
|
||||
}
|
||||
|
||||
export type DockerDiscoveryHostResult =
|
||||
| {
|
||||
host: string;
|
||||
status: "success";
|
||||
containers: ContainerInfo[];
|
||||
services: DiscoveredService[];
|
||||
}
|
||||
| {
|
||||
host: string;
|
||||
status: "unavailable";
|
||||
reason: string;
|
||||
containers: [];
|
||||
services: [];
|
||||
};
|
||||
|
||||
export interface DockerDiscoveryResult {
|
||||
hosts: DockerDiscoveryHostResult[];
|
||||
services: DiscoveredService[];
|
||||
}
|
||||
@@ -9,3 +9,4 @@ export const containerStates = ["created", "running", "paused", "restarting", "e
|
||||
|
||||
export type ContainerState = (typeof containerStates)[number];
|
||||
export * from "./labels";
|
||||
export * from "./discovery";
|
||||
@@ -1,4 +1,21 @@
|
||||
export const dockerLabels = {
|
||||
// Label to hide a container from Homarrs docker integration
|
||||
hide: "homarr.hide",
|
||||
group: "homarr.group",
|
||||
name: "homarr.name",
|
||||
href: "homarr.href",
|
||||
icon: "homarr.icon",
|
||||
description: "homarr.description",
|
||||
ping: "homarr.ping",
|
||||
id: "homarr.id",
|
||||
board: "homarr.board",
|
||||
integration: "homarr.integration",
|
||||
widget: "homarr.widget",
|
||||
} as const;
|
||||
|
||||
export const homepageLabels = {
|
||||
group: "homepage.group",
|
||||
name: "homepage.name",
|
||||
href: "homepage.href",
|
||||
icon: "homepage.icon",
|
||||
description: "homepage.description",
|
||||
} as const;
|
||||
@@ -27,8 +27,6 @@
|
||||
"@homarr/forms-collection": "workspace:^0.1.0",
|
||||
"@homarr/modals": "workspace:^0.1.0",
|
||||
"@homarr/notifications": "workspace:^0.1.0",
|
||||
"@homarr/old-import": "workspace:^0.1.0",
|
||||
"@homarr/old-schema": "workspace:^0.1.0",
|
||||
"@homarr/translation": "workspace:^0.1.0",
|
||||
"@homarr/ui": "workspace:^0.1.0",
|
||||
"@homarr/validation": "workspace:^0.1.0",
|
||||
|
||||
@@ -48,6 +48,7 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
|
||||
search={search}
|
||||
onSearchChange={setSearch}
|
||||
placeholder={`${t("app.action.select.search")}...`}
|
||||
ariaLabel={t("app.action.select.search")}
|
||||
onSearchKeyDown={(event) => {
|
||||
if (event.key === "Enter" && filteredApps.length === 1 && filteredApps[0]) {
|
||||
handleSelect(filteredApps[0]);
|
||||
|
||||
@@ -1,156 +0,0 @@
|
||||
import { useState } from "react";
|
||||
import { Button, FileInput, Group, Stack, TextInput } from "@mantine/core";
|
||||
import { IconFileUpload } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { createModal } from "@homarr/modals";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { OldmarrImportAppsSettings, SidebarBehaviourSelect } from "@homarr/old-import/components";
|
||||
import type { OldmarrImportConfiguration } from "@homarr/old-import/shared";
|
||||
import { checkJsonImportFile, oldmarrImportConfigurationSchema } from "@homarr/old-import/shared";
|
||||
import { oldmarrConfigSchema } from "@homarr/old-schema";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { useBoardNameStatus } from "./add-board-modal";
|
||||
|
||||
export const ImportBoardModal = createModal(({ actions }) => {
|
||||
const tOldImport = useScopedI18n("board.action.oldImport");
|
||||
const tCommon = useScopedI18n("common");
|
||||
const [fileValid, setFileValid] = useState(true);
|
||||
const form = useZodForm(
|
||||
z.object({
|
||||
file: z.file().check(checkJsonImportFile),
|
||||
configuration: oldmarrImportConfigurationSchema,
|
||||
}),
|
||||
{
|
||||
mode: "controlled",
|
||||
initialValues: {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
file: null!,
|
||||
configuration: {
|
||||
onlyImportApps: false,
|
||||
sidebarBehaviour: "last-section",
|
||||
name: "",
|
||||
},
|
||||
},
|
||||
onValuesChange(values, previous) {
|
||||
// This is a workarround until async validation is supported by mantine
|
||||
void (async () => {
|
||||
if (values.file === previous.file) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Before validation it can still be null
|
||||
// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
|
||||
if (!values.file) {
|
||||
return;
|
||||
}
|
||||
|
||||
const content = await values.file.text();
|
||||
const result = oldmarrConfigSchema.safeParse(JSON.parse(content));
|
||||
|
||||
if (!result.success) {
|
||||
console.error(result.error.issues);
|
||||
setFileValid(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setFileValid(true);
|
||||
form.setFieldValue("configuration.name", result.data.configProperties.name.replaceAll(" ", "-"));
|
||||
})();
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const { mutateAsync, isPending } = clientApi.board.importOldmarrConfig.useMutation({
|
||||
async onSuccess() {
|
||||
await revalidatePathActionAsync("/manage/boards");
|
||||
},
|
||||
});
|
||||
const boardNameStatus = useBoardNameStatus(form.values.configuration.name);
|
||||
|
||||
const handleSubmitAsync = async (values: { file: File; configuration: OldmarrImportConfiguration }) => {
|
||||
const formData = new FormData();
|
||||
formData.set("file", values.file);
|
||||
formData.set("configuration", JSON.stringify(values.configuration));
|
||||
|
||||
await mutateAsync(formData, {
|
||||
onSuccess() {
|
||||
actions.closeModal();
|
||||
showSuccessNotification({
|
||||
title: tOldImport("notification.success.title"),
|
||||
message: tOldImport("notification.success.message"),
|
||||
});
|
||||
},
|
||||
onError() {
|
||||
showErrorNotification({
|
||||
title: tOldImport("notification.error.title"),
|
||||
message: tOldImport("notification.error.message"),
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<form
|
||||
onSubmit={form.onSubmit((values) => {
|
||||
if (!fileValid || !boardNameStatus.canSubmit) {
|
||||
return;
|
||||
}
|
||||
|
||||
void handleSubmitAsync({
|
||||
file: values.file,
|
||||
configuration: values.configuration,
|
||||
});
|
||||
})}
|
||||
>
|
||||
<Stack>
|
||||
<FileInput
|
||||
rightSection={<IconFileUpload />}
|
||||
withAsterisk
|
||||
accept="application/json"
|
||||
{...form.getInputProps("file")}
|
||||
error={
|
||||
(form.getInputProps("file").error as string | undefined) ??
|
||||
(!fileValid && form.isDirty("file") ? tOldImport("form.file.invalidError") : undefined)
|
||||
}
|
||||
type="button"
|
||||
label={tOldImport("form.file.label")}
|
||||
/>
|
||||
|
||||
<OldmarrImportAppsSettings onlyImportApps={form.getInputProps("configuration.onlyImportApps")} />
|
||||
|
||||
<TextInput
|
||||
withAsterisk
|
||||
label={tOldImport("form.name.label")}
|
||||
description={
|
||||
boardNameStatus.description ? (
|
||||
<Group c={boardNameStatus.description.color} gap="xs" align="center">
|
||||
{boardNameStatus.description.icon ? <boardNameStatus.description.icon size={16} /> : null}
|
||||
<span>{boardNameStatus.description.label}</span>
|
||||
</Group>
|
||||
) : null
|
||||
}
|
||||
{...form.getInputProps("configuration.name")}
|
||||
/>
|
||||
|
||||
<SidebarBehaviourSelect {...form.getInputProps("configuration.sidebarBehaviour")} />
|
||||
|
||||
<Group justify="end">
|
||||
<Button variant="subtle" color="gray" onClick={actions.closeModal}>
|
||||
{tCommon("action.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isPending}>
|
||||
{tCommon("action.import")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
}).withOptions({
|
||||
defaultTitle: (t) => t("board.action.oldImport.label"),
|
||||
size: "lg",
|
||||
});
|
||||
@@ -1,3 +1,2 @@
|
||||
export { AddBoardModal } from "./add-board-modal";
|
||||
export { ImportBoardModal } from "./import-board-modal";
|
||||
export { DuplicateBoardModal } from "./duplicate-board-modal";
|
||||
@@ -1 +0,0 @@
|
||||
export * from "./src";
|
||||
@@ -1,73 +0,0 @@
|
||||
import AdmZip from "adm-zip";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
|
||||
import { oldmarrConfigSchema } from "@homarr/old-schema";
|
||||
|
||||
import { oldmarrImportUserSchema } from "../user-schema";
|
||||
import type { analyseOldmarrImportInputSchema } from "./input";
|
||||
|
||||
const logger = createLogger({ module: "analyseOldmarrImport" });
|
||||
|
||||
export const analyseOldmarrImportForRouterAsync = async (input: z.infer<typeof analyseOldmarrImportInputSchema>) => {
|
||||
const { configs, checksum, users } = await analyseOldmarrImportAsync(input.file);
|
||||
|
||||
return {
|
||||
configs,
|
||||
checksum,
|
||||
userCount: users.length,
|
||||
};
|
||||
};
|
||||
|
||||
export const analyseOldmarrImportAsync = async (file: File) => {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const zip = new AdmZip(Buffer.from(arrayBuffer));
|
||||
const entries = zip.getEntries();
|
||||
const configEntries = entries.filter((entry) => entry.entryName.endsWith(".json") && !entry.entryName.includes("/"));
|
||||
const configs = configEntries.map((entry) => {
|
||||
const result = oldmarrConfigSchema.safeParse(JSON.parse(entry.getData().toString()));
|
||||
if (!result.success) {
|
||||
logger.error(
|
||||
new ErrorWithMetadata(
|
||||
"Failed to parse oldmarr config",
|
||||
{ entryName: entry.entryName },
|
||||
{ cause: result.error },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
name: entry.name.replaceAll(" ", "-").replace(".json", ""),
|
||||
config: result.data ?? null,
|
||||
isError: !result.success,
|
||||
};
|
||||
});
|
||||
|
||||
const userEntry = entries.find((entry) => entry.entryName === "users/users.json");
|
||||
const users = parseUsers(userEntry);
|
||||
|
||||
const checksum = entries
|
||||
.find((entry) => entry.entryName === "checksum.txt")
|
||||
?.getData()
|
||||
.toString("utf-8");
|
||||
|
||||
return {
|
||||
configs,
|
||||
users,
|
||||
checksum,
|
||||
};
|
||||
};
|
||||
|
||||
export type AnalyseResult = Awaited<ReturnType<typeof analyseOldmarrImportForRouterAsync>>;
|
||||
|
||||
const parseUsers = (entry: AdmZip.IZipEntry | undefined) => {
|
||||
if (!entry) return [];
|
||||
|
||||
const result = z.array(oldmarrImportUserSchema).safeParse(JSON.parse(entry.getData().toString()));
|
||||
if (!result.success) {
|
||||
logger.error(new Error("Failed to parse users", { cause: result.error }));
|
||||
}
|
||||
|
||||
return result.data ?? [];
|
||||
};
|
||||
@@ -1,2 +0,0 @@
|
||||
export * from "./input";
|
||||
export { analyseOldmarrImportForRouterAsync } from "./analyse-oldmarr-import";
|
||||
@@ -1,5 +0,0 @@
|
||||
import { zfd } from "zod-form-data";
|
||||
|
||||
export const analyseOldmarrImportInputSchema = zfd.formData({
|
||||
file: zfd.file(),
|
||||
});
|
||||
@@ -1,7 +0,0 @@
|
||||
import type { Modify } from "@homarr/common/types";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import type { AnalyseResult } from "./analyse-oldmarr-import";
|
||||
|
||||
export type AnalyseConfig = AnalyseResult["configs"][number];
|
||||
export type ValidAnalyseConfig = Modify<AnalyseConfig, { config: OldmarrConfig }>;
|
||||
@@ -1,3 +0,0 @@
|
||||
export { InitialOldmarrImport } from "./initial-oldmarr-import";
|
||||
export { SidebarBehaviourSelect } from "./shared/sidebar-behaviour-select";
|
||||
export { OldmarrImportAppsSettings } from "./shared/apps-section";
|
||||
@@ -1,94 +0,0 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Stack } from "@mantine/core";
|
||||
import SuperJSON from "superjson";
|
||||
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
|
||||
// We don't have access to the API client here, so we need to import it from the API package
|
||||
// In the future we should consider having the used router also in this package
|
||||
import { clientApi } from "../../../api/src/client";
|
||||
import type { AnalyseResult } from "../analyse/analyse-oldmarr-import";
|
||||
import { prepareMultipleImports } from "../prepare/prepare-multiple";
|
||||
import type { InitialOldmarrImportSettings } from "../settings";
|
||||
import { defaultSidebarBehaviour } from "../settings";
|
||||
import { BoardSelectionCard } from "./initial/board-selection-card";
|
||||
import { ImportSettingsCard } from "./initial/import-settings-card";
|
||||
import { ImportSummaryCard } from "./initial/import-summary-card";
|
||||
import { ImportTokenModal } from "./initial/token-modal";
|
||||
|
||||
interface InitialOldmarrImportProps {
|
||||
file: File;
|
||||
analyseResult: AnalyseResult;
|
||||
}
|
||||
|
||||
export const InitialOldmarrImport = ({ file, analyseResult }: InitialOldmarrImportProps) => {
|
||||
const [boardSelections, setBoardSelections] = useState<Map<string, boolean>>(
|
||||
new Map(analyseResult.configs.filter(({ config }) => config !== null).map(({ name }) => [name, true])),
|
||||
);
|
||||
const [settings, setSettings] = useState<InitialOldmarrImportSettings>({
|
||||
onlyImportApps: false,
|
||||
sidebarBehaviour: defaultSidebarBehaviour,
|
||||
});
|
||||
|
||||
const { preparedApps, preparedBoards, preparedIntegrations } = useMemo(
|
||||
() => prepareMultipleImports(analyseResult.configs, settings, boardSelections),
|
||||
[analyseResult, boardSelections, settings],
|
||||
);
|
||||
|
||||
const { mutateAsync, isPending } = clientApi.import.importInitialOldmarrImport.useMutation({
|
||||
async onSuccess() {
|
||||
await revalidatePathActionAsync("/init");
|
||||
},
|
||||
});
|
||||
const { openModal } = useModalAction(ImportTokenModal);
|
||||
|
||||
const createFormData = (token: string | null) => {
|
||||
const formData = new FormData();
|
||||
formData.set("file", file);
|
||||
formData.set("settings", JSON.stringify(settings));
|
||||
// Map can not be send over the wire without superjson
|
||||
formData.set("boardSelections", SuperJSON.stringify(boardSelections));
|
||||
if (token) {
|
||||
formData.set("token", token);
|
||||
}
|
||||
return formData;
|
||||
};
|
||||
|
||||
const handleSubmitAsync = async () => {
|
||||
if (analyseResult.checksum) {
|
||||
openModal({
|
||||
checksum: analyseResult.checksum,
|
||||
onSuccessAsync: async (token) => {
|
||||
await mutateAsync(createFormData(token));
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
await mutateAsync(createFormData(null));
|
||||
};
|
||||
|
||||
return (
|
||||
<Stack w="100%" mb="sm">
|
||||
<ImportSettingsCard
|
||||
settings={settings}
|
||||
updateSetting={(setting, value) => {
|
||||
setSettings((settings) => ({ ...settings, [setting]: value }));
|
||||
}}
|
||||
/>
|
||||
{settings.onlyImportApps ? null : (
|
||||
<BoardSelectionCard selections={boardSelections} updateSelections={setBoardSelections} />
|
||||
)}
|
||||
<ImportSummaryCard
|
||||
counts={{
|
||||
apps: preparedApps.length,
|
||||
boards: preparedBoards.length,
|
||||
integrations: preparedIntegrations.length,
|
||||
credentialUsers: analyseResult.userCount,
|
||||
}}
|
||||
onSubmit={handleSubmitAsync}
|
||||
loading={isPending}
|
||||
/>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -1,76 +0,0 @@
|
||||
import type { ChangeEvent } from "react";
|
||||
import { Anchor, Card, Checkbox, Group, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export type BoardSelectionMap = Map<string, boolean>;
|
||||
|
||||
interface BoardSelectionCardProps {
|
||||
selections: BoardSelectionMap;
|
||||
updateSelections: (callback: (selections: BoardSelectionMap) => BoardSelectionMap) => void;
|
||||
}
|
||||
|
||||
const allChecked = (map: BoardSelectionMap) => {
|
||||
return [...map.values()].every((selection) => selection);
|
||||
};
|
||||
|
||||
export const BoardSelectionCard = ({ selections, updateSelections }: BoardSelectionCardProps) => {
|
||||
const tBoardSelection = useScopedI18n("init.step.import.boardSelection");
|
||||
const t = useI18n();
|
||||
const areAllChecked = allChecked(selections);
|
||||
|
||||
const handleToggleAll = () => {
|
||||
updateSelections((selections) => {
|
||||
return new Map([...selections.keys()].map((name) => [name, !areAllChecked] as const));
|
||||
});
|
||||
};
|
||||
|
||||
const registerToggle = (name: string) => (event: ChangeEvent<HTMLInputElement>) => {
|
||||
updateSelections((selections) => {
|
||||
const updated = new Map(selections);
|
||||
updated.set(name, event.target.checked);
|
||||
return updated;
|
||||
});
|
||||
};
|
||||
|
||||
if (selections.size === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card w="100%" withBorder={false}>
|
||||
<Stack gap="sm">
|
||||
<Stack gap={0}>
|
||||
<Group justify="space-between" align="center">
|
||||
<Text fw={500}>{tBoardSelection("title", { count: String(selections.size) })}</Text>
|
||||
<Anchor component="button" onClick={handleToggleAll}>
|
||||
{areAllChecked ? tBoardSelection("action.unselectAll") : tBoardSelection("action.selectAll")}
|
||||
</Anchor>
|
||||
</Group>
|
||||
<Text size="sm" c="gray.6">
|
||||
{tBoardSelection("description")}
|
||||
</Text>
|
||||
<Text size="xs" c="gray.6">
|
||||
{t("board.action.oldImport.form.screenSize.description")}
|
||||
</Text>
|
||||
</Stack>
|
||||
|
||||
<Stack gap="sm">
|
||||
{[...selections.entries()].map(([name, selected]) => (
|
||||
<Card key={name}>
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
onChange={registerToggle(name)}
|
||||
label={
|
||||
<Text fw={500} size="sm">
|
||||
{name}
|
||||
</Text>
|
||||
}
|
||||
/>
|
||||
</Card>
|
||||
))}
|
||||
</Stack>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
import { Card, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { InitialOldmarrImportSettings } from "../../settings";
|
||||
import { OldmarrImportAppsSettings } from "../shared/apps-section";
|
||||
import { SidebarBehaviourSelect } from "../shared/sidebar-behaviour-select";
|
||||
|
||||
interface ImportSettingsCardProps {
|
||||
settings: InitialOldmarrImportSettings;
|
||||
updateSetting: <TKey extends keyof InitialOldmarrImportSettings>(
|
||||
setting: TKey,
|
||||
value: InitialOldmarrImportSettings[TKey],
|
||||
) => void;
|
||||
}
|
||||
|
||||
export const ImportSettingsCard = ({ settings, updateSetting }: ImportSettingsCardProps) => {
|
||||
const tImportSettings = useScopedI18n("init.step.import.importSettings");
|
||||
return (
|
||||
<Card w="100%" withBorder={false}>
|
||||
<Stack gap="sm">
|
||||
<Stack gap={0}>
|
||||
<Text fw={500}>{tImportSettings("title")}</Text>
|
||||
<Text size="sm" c="gray.6">
|
||||
{tImportSettings("description")}
|
||||
</Text>
|
||||
</Stack>
|
||||
|
||||
<OldmarrImportAppsSettings
|
||||
background="transparent"
|
||||
onlyImportApps={{
|
||||
checked: settings.onlyImportApps,
|
||||
onChange: (event) => updateSetting("onlyImportApps", event.target.checked),
|
||||
}}
|
||||
/>
|
||||
|
||||
<SidebarBehaviourSelect
|
||||
value={settings.sidebarBehaviour}
|
||||
onChange={(value) => updateSetting("sidebarBehaviour", value)}
|
||||
/>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -1,44 +0,0 @@
|
||||
import { Button, Card, Group, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import type { MaybePromise } from "@homarr/common/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
interface ImportSummaryCardProps {
|
||||
counts: { apps: number; boards: number; integrations: number; credentialUsers: number };
|
||||
loading: boolean;
|
||||
onSubmit: () => MaybePromise<void>;
|
||||
}
|
||||
|
||||
export const ImportSummaryCard = ({ counts, onSubmit, loading }: ImportSummaryCardProps) => {
|
||||
const tSummary = useScopedI18n("init.step.import.summary");
|
||||
return (
|
||||
<Card w="100%" withBorder={false}>
|
||||
<Stack gap="sm">
|
||||
<Stack gap={0}>
|
||||
<Text fw={500}>{tSummary("title")}</Text>
|
||||
<Text size="sm" c="gray.6">
|
||||
{tSummary("description")}
|
||||
</Text>
|
||||
</Stack>
|
||||
|
||||
<Stack gap="xs">
|
||||
{objectEntries(counts).map(([key, count]) => (
|
||||
<Card key={key} p="sm">
|
||||
<Group justify="space-between" align="center">
|
||||
<Text fw={500} size="sm">
|
||||
{tSummary(`entities.${key}`)}
|
||||
</Text>
|
||||
<Text size="sm">{count}</Text>
|
||||
</Group>
|
||||
</Card>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
<Button onClick={onSubmit} loading={loading}>
|
||||
{tSummary("action.import")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Card>
|
||||
);
|
||||
};
|
||||
@@ -1,67 +0,0 @@
|
||||
import { Button, Group, PasswordInput, Stack } from "@mantine/core";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { createModal } from "@homarr/modals";
|
||||
import { showErrorNotification } from "@homarr/notifications";
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
// We don't have access to the API client here, so we need to import it from the API package
|
||||
// In the future we should consider having the used router also in this package
|
||||
import { clientApi } from "../../../../api/src/client";
|
||||
|
||||
interface InnerProps {
|
||||
checksum: string;
|
||||
onSuccessAsync: (token: string) => Promise<void>;
|
||||
}
|
||||
|
||||
const formSchema = z.object({
|
||||
token: z.string().min(1).max(256),
|
||||
});
|
||||
|
||||
export const ImportTokenModal = createModal<InnerProps>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const tTokenModal = useScopedI18n("init.step.import.tokenModal");
|
||||
const { mutate, isPending } = clientApi.import.validateToken.useMutation();
|
||||
const form = useZodForm(formSchema, { initialValues: { token: "" } });
|
||||
|
||||
const handleSubmit = (values: z.infer<typeof formSchema>) => {
|
||||
mutate(
|
||||
{ checksum: innerProps.checksum, token: values.token },
|
||||
{
|
||||
onSuccess(isValid) {
|
||||
if (isValid) {
|
||||
actions.closeModal();
|
||||
void innerProps.onSuccessAsync(values.token);
|
||||
} else {
|
||||
showErrorNotification({
|
||||
title: tTokenModal("notification.error.title"),
|
||||
message: tTokenModal("notification.error.message"),
|
||||
});
|
||||
}
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<form onSubmit={form.onSubmit(handleSubmit)}>
|
||||
<Stack>
|
||||
<PasswordInput
|
||||
{...form.getInputProps("token")}
|
||||
label={tTokenModal("field.token.label")}
|
||||
description={tTokenModal("field.token.description")}
|
||||
withAsterisk
|
||||
/>
|
||||
<Group justify="end">
|
||||
<Button variant="subtle" color="gray" onClick={actions.closeModal}>
|
||||
{t("common.action.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isPending}>
|
||||
{t("common.action.confirm")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
</form>
|
||||
);
|
||||
}).withOptions({ defaultTitle: (t) => t("init.step.import.tokenModal.title") });
|
||||
@@ -1,23 +0,0 @@
|
||||
import { Fieldset, Switch } from "@mantine/core";
|
||||
|
||||
import type { CheckboxProps } from "@homarr/form/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
interface OldmarrImportAppsSettingsProps {
|
||||
onlyImportApps: CheckboxProps;
|
||||
background?: string;
|
||||
}
|
||||
|
||||
export const OldmarrImportAppsSettings = ({ background, onlyImportApps }: OldmarrImportAppsSettingsProps) => {
|
||||
const tApps = useScopedI18n("board.action.oldImport.form.apps");
|
||||
|
||||
return (
|
||||
<Fieldset legend={tApps("label")} bg={background}>
|
||||
<Switch
|
||||
{...onlyImportApps}
|
||||
label={tApps("onlyImportApps.label")}
|
||||
description={tApps("onlyImportApps.description")}
|
||||
/>
|
||||
</Fieldset>
|
||||
);
|
||||
};
|
||||
@@ -1,31 +0,0 @@
|
||||
import type { InputPropsFor } from "@homarr/form/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { SelectWithDescription } from "@homarr/ui";
|
||||
|
||||
import type { SidebarBehaviour } from "../../settings";
|
||||
|
||||
export const SidebarBehaviourSelect = (props: InputPropsFor<SidebarBehaviour, SidebarBehaviour, HTMLButtonElement>) => {
|
||||
const tSidebarBehaviour = useScopedI18n("board.action.oldImport.form.sidebarBehavior");
|
||||
|
||||
return (
|
||||
<SelectWithDescription
|
||||
withAsterisk
|
||||
label={tSidebarBehaviour("label")}
|
||||
description={tSidebarBehaviour("description")}
|
||||
data={[
|
||||
{
|
||||
value: "last-section",
|
||||
label: tSidebarBehaviour("option.lastSection.label"),
|
||||
description: tSidebarBehaviour("option.lastSection.description"),
|
||||
},
|
||||
{
|
||||
value: "remove-items",
|
||||
label: tSidebarBehaviour("option.removeItems.label"),
|
||||
description: tSidebarBehaviour("option.removeItems.description"),
|
||||
},
|
||||
]}
|
||||
{...props}
|
||||
onChange={(value) => (value ? props.onChange(value as SidebarBehaviour) : null)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -1,52 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
const logger = createLogger({ module: "fixSectionIssues" });
|
||||
|
||||
export const fixSectionIssues = (old: OldmarrConfig) => {
|
||||
const wrappers = old.wrappers.sort((wrapperA, wrapperB) => wrapperA.position - wrapperB.position);
|
||||
const categories = old.categories.sort((categoryA, categoryB) => categoryA.position - categoryB.position);
|
||||
|
||||
const neededSectionCount = categories.length * 2 + 1;
|
||||
const hasToMuchEmptyWrappers = wrappers.length > categories.length + 1;
|
||||
|
||||
logger.debug("Fixing section issues", {
|
||||
neededSectionCount,
|
||||
hasToMuchEmptyWrappers,
|
||||
});
|
||||
|
||||
for (let position = 0; position < neededSectionCount; position++) {
|
||||
const index = Math.floor(position / 2);
|
||||
const isEmpty = position % 2 === 0;
|
||||
const section = isEmpty ? wrappers[index] : categories[index];
|
||||
if (!section) {
|
||||
// If there are not enough empty sections for categories we need to insert them
|
||||
if (isEmpty) {
|
||||
// Insert empty wrapper for between categories
|
||||
wrappers.push({
|
||||
id: createId(),
|
||||
position,
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
section.position = position;
|
||||
}
|
||||
|
||||
// Find all wrappers that should be merged into one
|
||||
const wrapperIdsToMerge = wrappers.slice(categories.length).map((section) => section.id);
|
||||
// Remove all wrappers after the first at the end
|
||||
wrappers.splice(categories.length + 1);
|
||||
|
||||
if (wrapperIdsToMerge.length >= 2) {
|
||||
logger.debug("Found wrappers to merge", { count: wrapperIdsToMerge.length });
|
||||
}
|
||||
|
||||
return {
|
||||
wrappers,
|
||||
categories,
|
||||
wrapperIdsToMerge,
|
||||
};
|
||||
};
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
export class OldHomarrImportError extends Error {
|
||||
constructor(oldConfig: OldmarrConfig, cause: unknown) {
|
||||
super(`Failed to import old homarr configuration name=${oldConfig.configProperties.name}`, {
|
||||
cause,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -1,161 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createDbInsertCollectionForTransaction } from "@homarr/db/collection";
|
||||
import { normalizeBoardLayoutRoles } from "@homarr/definitions";
|
||||
import type { BoardSize, OldmarrConfig } from "@homarr/old-schema";
|
||||
import { boardSizes, getBoardSizeName } from "@homarr/old-schema";
|
||||
|
||||
import { fixSectionIssues } from "../../fix-section-issues";
|
||||
import { OldHomarrImportError } from "../../import-error";
|
||||
import { mapBoard } from "../../mappers/map-board";
|
||||
import { mapBreakpoint } from "../../mappers/map-breakpoint";
|
||||
import { mapColumnCount } from "../../mappers/map-column-count";
|
||||
import { moveWidgetsAndAppsIfMerge } from "../../move-widgets-and-apps-merge";
|
||||
import { prepareItems } from "../../prepare/prepare-items";
|
||||
import type { prepareMultipleImports } from "../../prepare/prepare-multiple";
|
||||
import { placePreparedSections, prepareSections } from "../../prepare/prepare-sections";
|
||||
import type { InitialOldmarrImportSettings } from "../../settings";
|
||||
|
||||
const logger = createLogger({ module: "boardCollection" });
|
||||
|
||||
export const createBoardInsertCollection = (
|
||||
{ preparedApps, preparedBoards }: Omit<ReturnType<typeof prepareMultipleImports>, "preparedIntegrations">,
|
||||
settings: InitialOldmarrImportSettings,
|
||||
) => {
|
||||
const insertCollection = createDbInsertCollectionForTransaction([
|
||||
"apps",
|
||||
"boards",
|
||||
"layouts",
|
||||
"sections",
|
||||
"sectionLayouts",
|
||||
"items",
|
||||
"itemLayouts",
|
||||
]);
|
||||
logger.info("Preparing boards for insert collection");
|
||||
|
||||
const appsMap = new Map(
|
||||
preparedApps.flatMap(({ ids, ...app }) => {
|
||||
const id = app.existingId ?? createId();
|
||||
return ids.map((oldId) => [oldId, { id, ...app }] as const);
|
||||
}),
|
||||
);
|
||||
|
||||
for (const app of appsMap.values()) {
|
||||
// Skip duplicate apps
|
||||
if (insertCollection.apps.some((appEntry) => appEntry.id === app.id)) {
|
||||
continue;
|
||||
}
|
||||
// Skip apps that already exist in the database
|
||||
if (app.existingId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
insertCollection.apps.push(app);
|
||||
}
|
||||
|
||||
if (settings.onlyImportApps) {
|
||||
logger.info("Skipping boards and sections import due to onlyImportApps setting", {
|
||||
appCount: insertCollection.apps.length,
|
||||
});
|
||||
return insertCollection;
|
||||
}
|
||||
logger.debug("Added apps to board insert collection", { count: insertCollection.apps.length });
|
||||
|
||||
preparedBoards.forEach((board) => {
|
||||
if (!hasEnoughItemShapes(board.config)) {
|
||||
throw new OldHomarrImportError(
|
||||
board.config,
|
||||
new Error("Your config contains items without shapes for all board sizes."),
|
||||
);
|
||||
}
|
||||
|
||||
const { wrappers, categories, wrapperIdsToMerge } = fixSectionIssues(board.config);
|
||||
const { apps, widgets } = moveWidgetsAndAppsIfMerge(board.config, wrapperIdsToMerge, {
|
||||
...settings,
|
||||
name: board.name,
|
||||
});
|
||||
|
||||
logger.debug("Fixed issues with sections and item positions", { fileName: board.name });
|
||||
|
||||
const mappedBoard = mapBoard(board);
|
||||
logger.debug("Mapped board", { fileName: board.name, boardId: mappedBoard.id });
|
||||
insertCollection.boards.push(mappedBoard);
|
||||
|
||||
const layoutMapping = boardSizes.reduce(
|
||||
(acc, size) => {
|
||||
acc[size] = createId();
|
||||
return acc;
|
||||
},
|
||||
{} as Record<BoardSize, string>,
|
||||
);
|
||||
|
||||
const importedLayouts = normalizeBoardLayoutRoles(
|
||||
boardSizes.map((size) => ({
|
||||
id: layoutMapping[size],
|
||||
boardId: mappedBoard.id,
|
||||
columnCount: mapColumnCount(board.config.settings.customization.gridstack, size),
|
||||
leftGutterColumnCount: 0,
|
||||
rightGutterColumnCount: 0,
|
||||
breakpoint: mapBreakpoint(size),
|
||||
name: getBoardSizeName(size),
|
||||
})),
|
||||
);
|
||||
|
||||
insertCollection.layouts.push(...importedLayouts);
|
||||
|
||||
const preparedSections = prepareSections(mappedBoard.id, { wrappers, categories });
|
||||
|
||||
insertCollection.sections.push(...preparedSections.sections);
|
||||
logger.debug("Added sections to board insert collection", { count: insertCollection.sections.length });
|
||||
|
||||
const preparedItems = prepareItems(
|
||||
{
|
||||
apps,
|
||||
widgets,
|
||||
settings: board.config.settings,
|
||||
},
|
||||
appsMap,
|
||||
preparedSections.byLegacyId,
|
||||
layoutMapping,
|
||||
mappedBoard.id,
|
||||
);
|
||||
insertCollection.sectionLayouts.push(...placePreparedSections(preparedSections, preparedItems, importedLayouts));
|
||||
preparedItems.forEach(({ layouts, ...item }) => {
|
||||
insertCollection.items.push(item);
|
||||
insertCollection.itemLayouts.push(...layouts);
|
||||
});
|
||||
logger.debug("Added items to board insert collection", { count: insertCollection.items.length });
|
||||
});
|
||||
|
||||
logger.info("Board collection prepared", {
|
||||
boardCount: insertCollection.boards.length,
|
||||
sectionCount: insertCollection.sections.length,
|
||||
itemCount: insertCollection.items.length,
|
||||
appCount: insertCollection.apps.length,
|
||||
});
|
||||
|
||||
return insertCollection;
|
||||
};
|
||||
|
||||
export const hasEnoughItemShapes = (config: {
|
||||
apps: Pick<OldmarrConfig["apps"][number], "shape">[];
|
||||
widgets: Pick<OldmarrConfig["widgets"][number], "shape">[];
|
||||
}) => {
|
||||
const invalidSizes: BoardSize[] = [];
|
||||
|
||||
for (const size of boardSizes) {
|
||||
if (invalidSizes.includes(size)) continue;
|
||||
|
||||
if (config.apps.some((app) => app.shape[size] === undefined)) {
|
||||
invalidSizes.push(size);
|
||||
}
|
||||
|
||||
if (invalidSizes.includes(size)) continue;
|
||||
|
||||
if (config.widgets.some((widget) => widget.shape[size] === undefined)) {
|
||||
invalidSizes.push(size);
|
||||
}
|
||||
}
|
||||
|
||||
return invalidSizes.length <= 2;
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
import { encryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createDbInsertCollectionForTransaction } from "@homarr/db/collection";
|
||||
|
||||
import { mapAndDecryptIntegrations } from "../../mappers/map-integration";
|
||||
import type { PreparedIntegration } from "../../prepare/prepare-integrations";
|
||||
|
||||
const logger = createLogger({ module: "integrationCollection" });
|
||||
|
||||
export const createIntegrationInsertCollection = (
|
||||
preparedIntegrations: PreparedIntegration[],
|
||||
encryptionToken: string | null | undefined,
|
||||
) => {
|
||||
const insertCollection = createDbInsertCollectionForTransaction(["integrations", "integrationSecrets"]);
|
||||
|
||||
if (preparedIntegrations.length === 0) {
|
||||
return insertCollection;
|
||||
}
|
||||
|
||||
logger.info("Preparing integrations for insert collection", { count: preparedIntegrations.length });
|
||||
|
||||
if (encryptionToken === null || encryptionToken === undefined) {
|
||||
logger.debug("Skipping integration decryption due to missing token");
|
||||
return insertCollection;
|
||||
}
|
||||
|
||||
const preparedIntegrationsDecrypted = mapAndDecryptIntegrations(preparedIntegrations, encryptionToken);
|
||||
|
||||
preparedIntegrationsDecrypted.forEach((integration) => {
|
||||
insertCollection.integrations.push({
|
||||
id: integration.id,
|
||||
kind: integration.kind,
|
||||
name: integration.name,
|
||||
url: integration.url,
|
||||
});
|
||||
|
||||
integration.secrets
|
||||
.filter((secret) => secret.value !== null)
|
||||
.forEach((secret) => {
|
||||
insertCollection.integrationSecrets.push({
|
||||
integrationId: integration.id,
|
||||
kind: secret.field,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
value: encryptSecret(secret.value!),
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
logger.info("Added integrations and secrets to insert collection", {
|
||||
integrationCount: insertCollection.integrations.length,
|
||||
secretCount: insertCollection.integrationSecrets.length,
|
||||
});
|
||||
|
||||
return insertCollection;
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { createDbInsertCollectionForTransaction } from "@homarr/db/collection";
|
||||
import { credentialsAdminGroup } from "@homarr/definitions";
|
||||
|
||||
import { mapAndDecryptUsers } from "../../mappers/map-user";
|
||||
import type { OldmarrImportUser } from "../../user-schema";
|
||||
|
||||
const logger = createLogger({ module: "userCollection" });
|
||||
|
||||
export const createUserInsertCollection = (
|
||||
importUsers: OldmarrImportUser[],
|
||||
encryptionToken: string | null | undefined,
|
||||
) => {
|
||||
const insertCollection = createDbInsertCollectionForTransaction([
|
||||
"users",
|
||||
"groups",
|
||||
"groupMembers",
|
||||
"groupPermissions",
|
||||
]);
|
||||
|
||||
if (importUsers.length === 0) {
|
||||
return insertCollection;
|
||||
}
|
||||
|
||||
logger.info("Preparing users for insert collection", { count: importUsers.length });
|
||||
|
||||
if (encryptionToken === null || encryptionToken === undefined) {
|
||||
logger.debug("Skipping user decryption due to missing token");
|
||||
return insertCollection;
|
||||
}
|
||||
|
||||
const preparedUsers = mapAndDecryptUsers(importUsers, encryptionToken);
|
||||
preparedUsers.forEach((user) => insertCollection.users.push(user));
|
||||
logger.debug("Added users to insert collection", { count: insertCollection.users.length });
|
||||
|
||||
if (!preparedUsers.some((user) => user.isAdmin)) {
|
||||
logger.warn("No admin users found, skipping admin group creation");
|
||||
return insertCollection;
|
||||
}
|
||||
|
||||
const adminGroupId = createId();
|
||||
insertCollection.groups.push({
|
||||
id: adminGroupId,
|
||||
name: credentialsAdminGroup,
|
||||
position: 1,
|
||||
});
|
||||
|
||||
insertCollection.groupPermissions.push({
|
||||
groupId: adminGroupId,
|
||||
permission: "admin",
|
||||
});
|
||||
|
||||
const admins = preparedUsers.filter((user) => user.isAdmin);
|
||||
|
||||
admins.forEach((user) => {
|
||||
insertCollection.groupMembers.push({
|
||||
groupId: adminGroupId,
|
||||
userId: user.id,
|
||||
});
|
||||
});
|
||||
|
||||
logger.info("Added admin group and permissions to insert collection", {
|
||||
adminGroupId,
|
||||
adminUsersCount: admins.length,
|
||||
});
|
||||
|
||||
return insertCollection;
|
||||
};
|
||||
@@ -1,58 +0,0 @@
|
||||
import type { z } from "zod/v4";
|
||||
|
||||
import { Stopwatch } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import { handleTransactionsAsync } from "@homarr/db";
|
||||
import type { Database } from "@homarr/db";
|
||||
|
||||
import { analyseOldmarrImportAsync } from "../analyse/analyse-oldmarr-import";
|
||||
import { prepareMultipleImports } from "../prepare/prepare-multiple";
|
||||
import { createBoardInsertCollection } from "./collections/board-collection";
|
||||
import { createIntegrationInsertCollection } from "./collections/integration-collection";
|
||||
import { createUserInsertCollection } from "./collections/user-collection";
|
||||
import type { importInitialOldmarrInputSchema } from "./input";
|
||||
import { ensureValidTokenOrThrow } from "./validate-token";
|
||||
|
||||
const logger = createLogger({ module: "importInitialOldmarr" });
|
||||
|
||||
export const importInitialOldmarrAsync = async (
|
||||
db: Database,
|
||||
input: z.infer<typeof importInitialOldmarrInputSchema>,
|
||||
) => {
|
||||
const stopwatch = new Stopwatch();
|
||||
const { checksum, configs, users: importUsers } = await analyseOldmarrImportAsync(input.file);
|
||||
ensureValidTokenOrThrow(checksum, input.token);
|
||||
|
||||
const { preparedApps, preparedBoards, preparedIntegrations } = prepareMultipleImports(
|
||||
configs,
|
||||
input.settings,
|
||||
input.boardSelections,
|
||||
);
|
||||
|
||||
logger.info("Preparing import data in insert collections for database");
|
||||
|
||||
const boardInsertCollection = createBoardInsertCollection({ preparedApps, preparedBoards }, input.settings);
|
||||
const userInsertCollection = createUserInsertCollection(importUsers, input.token);
|
||||
const integrationInsertCollection = createIntegrationInsertCollection(preparedIntegrations, input.token);
|
||||
|
||||
logger.info("Inserting import data to database");
|
||||
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(db) {
|
||||
await db.transaction(async (transaction) => {
|
||||
await boardInsertCollection.insertAllAsync(transaction);
|
||||
await userInsertCollection.insertAllAsync(transaction);
|
||||
await integrationInsertCollection.insertAllAsync(transaction);
|
||||
});
|
||||
},
|
||||
handleSync(db) {
|
||||
db.transaction((transaction) => {
|
||||
boardInsertCollection.insertAll(transaction);
|
||||
userInsertCollection.insertAll(transaction);
|
||||
integrationInsertCollection.insertAll(transaction);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
logger.info("Import successful", { duration: stopwatch.getElapsedInHumanWords() });
|
||||
};
|
||||
@@ -1,42 +0,0 @@
|
||||
import { handleTransactionsAsync, inArray } from "@homarr/db";
|
||||
import type { Database } from "@homarr/db";
|
||||
import { apps } from "@homarr/db/schema";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import { doAppsMatch } from "../prepare/prepare-apps";
|
||||
import { prepareSingleImport } from "../prepare/prepare-single";
|
||||
import type { OldmarrImportConfiguration } from "../settings";
|
||||
import { createBoardInsertCollection } from "./collections/board-collection";
|
||||
|
||||
export const importSingleOldmarrConfigAsync = async (
|
||||
db: Database,
|
||||
config: OldmarrConfig,
|
||||
settings: OldmarrImportConfiguration,
|
||||
) => {
|
||||
const { preparedApps, preparedBoards } = prepareSingleImport(config, settings);
|
||||
const existingApps = await db.query.apps.findMany({
|
||||
where: inArray(
|
||||
apps.href,
|
||||
preparedApps.map((app) => app.href).filter((href) => href !== null),
|
||||
),
|
||||
});
|
||||
|
||||
preparedApps.forEach((app) => {
|
||||
const existingApp = existingApps.find((existingApp) => doAppsMatch(existingApp, app));
|
||||
if (existingApp) {
|
||||
app.existingId = existingApp.id;
|
||||
}
|
||||
return app;
|
||||
});
|
||||
|
||||
const boardInsertCollection = createBoardInsertCollection({ preparedApps, preparedBoards }, settings);
|
||||
|
||||
await handleTransactionsAsync(db, {
|
||||
async handleAsync(db) {
|
||||
await boardInsertCollection.insertAllAsync(db);
|
||||
},
|
||||
handleSync(db) {
|
||||
boardInsertCollection.insertAll(db);
|
||||
},
|
||||
});
|
||||
};
|
||||
@@ -1,3 +0,0 @@
|
||||
export { importInitialOldmarrAsync } from "./import-initial-oldmarr";
|
||||
export * from "./input";
|
||||
export { ensureValidTokenOrThrow } from "./validate-token";
|
||||
@@ -1,17 +0,0 @@
|
||||
import SuperJSON from "superjson";
|
||||
import { zfd } from "zod-form-data";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { initialOldmarrImportSettings } from "../settings";
|
||||
|
||||
const boardSelectionMapSchema = z.map(z.string(), z.boolean());
|
||||
|
||||
export const importInitialOldmarrInputSchema = zfd.formData({
|
||||
file: zfd.file(),
|
||||
settings: zfd.json(initialOldmarrImportSettings),
|
||||
boardSelections: zfd.text().transform((value) => {
|
||||
const map = boardSelectionMapSchema.parse(SuperJSON.parse(value));
|
||||
return map;
|
||||
}),
|
||||
token: zfd.text().nullable().optional(),
|
||||
});
|
||||
@@ -1,53 +0,0 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import type { BoardSize } from "@homarr/old-schema";
|
||||
|
||||
import { hasEnoughItemShapes } from "../collections/board-collection";
|
||||
|
||||
const defaultShape = {
|
||||
location: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
},
|
||||
size: {
|
||||
width: 1,
|
||||
height: 1,
|
||||
},
|
||||
};
|
||||
|
||||
describe("hasEnoughItemShapes should check if there are more than one shape available for automatic reconstruction", () => {
|
||||
test.each([
|
||||
[true, [], []], // no items, so nothing to check
|
||||
[true, [{ lg: true }], []], // lg always exists
|
||||
[true, [], [{ md: true }]], // md always exists
|
||||
[true, [{ md: true, sm: true }], [{ md: true, lg: true }]], // md always exists
|
||||
[true, [{ md: true }], [{ md: true }]], // md always exists
|
||||
[false, [{ md: true }, { md: true }], [{ lg: true }]], // md is missing for widgets
|
||||
[false, [{ md: true }], [{ lg: true }]], // md is missing for widgets
|
||||
[false, [{ md: true }], [{ md: true, lg: true }, { lg: true }]], // md is missing for 2. widget
|
||||
] as [boolean, Shape[], Shape[]][])(
|
||||
"should return %s if there are more than one shape available",
|
||||
(returnValue, appShapes, widgetShapes) => {
|
||||
const result = hasEnoughItemShapes({
|
||||
apps: appShapes.map((shapes) => ({
|
||||
shape: {
|
||||
sm: shapes.sm ? defaultShape : undefined,
|
||||
md: shapes.md ? defaultShape : undefined,
|
||||
lg: shapes.lg ? defaultShape : undefined,
|
||||
},
|
||||
})),
|
||||
widgets: widgetShapes.map((shapes) => ({
|
||||
shape: {
|
||||
sm: shapes.sm ? defaultShape : undefined,
|
||||
md: shapes.md ? defaultShape : undefined,
|
||||
lg: shapes.lg ? defaultShape : undefined,
|
||||
},
|
||||
})),
|
||||
});
|
||||
|
||||
expect(result).toBe(returnValue);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
type Shape = Partial<Record<BoardSize, true>>;
|
||||
@@ -1,18 +0,0 @@
|
||||
import { decryptSecretWithKey } from "@homarr/common/server";
|
||||
|
||||
export const ensureValidTokenOrThrow = (checksum: string | undefined, encryptionToken: string | null | undefined) => {
|
||||
if (!encryptionToken || !checksum) return;
|
||||
|
||||
const [first, second] = checksum.split("\n");
|
||||
if (!first || !second) throw new Error("Malformed checksum");
|
||||
|
||||
const key = Buffer.from(encryptionToken, "hex");
|
||||
let decrypted: string;
|
||||
try {
|
||||
decrypted = decryptSecretWithKey(second as `${string}.${string}`, key);
|
||||
} catch {
|
||||
throw new Error("Invalid checksum");
|
||||
}
|
||||
const isValid = decrypted === first;
|
||||
if (!isValid) throw new Error("Invalid checksum");
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { Database } from "@homarr/db";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import { importSingleOldmarrConfigAsync } from "./import/import-single-oldmarr";
|
||||
import type { OldmarrImportConfiguration } from "./settings";
|
||||
|
||||
export const importOldmarrAsync = async (
|
||||
db: Database,
|
||||
old: OldmarrConfig,
|
||||
configuration: OldmarrImportConfiguration,
|
||||
) => {
|
||||
await importSingleOldmarrConfigAsync(db, old, configuration);
|
||||
};
|
||||
@@ -1,29 +0,0 @@
|
||||
import type { InferSelectModel } from "@homarr/db";
|
||||
import type { apps } from "@homarr/db/schema";
|
||||
import type { OldmarrApp } from "@homarr/old-schema";
|
||||
|
||||
import type { OldmarrBookmarkDefinition } from "../widgets/definitions/bookmark";
|
||||
|
||||
export const mapOldmarrApp = (app: OldmarrApp): InferSelectModel<typeof apps> => {
|
||||
return {
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
iconUrl: app.appearance.iconUrl,
|
||||
description: app.behaviour.tooltipDescription ?? null,
|
||||
href: app.behaviour.externalUrl || app.url,
|
||||
pingUrl: app.url.length > 0 ? app.url : null,
|
||||
};
|
||||
};
|
||||
|
||||
export const mapOldmarrBookmarkApp = (
|
||||
app: OldmarrBookmarkDefinition["options"]["items"][number],
|
||||
): InferSelectModel<typeof apps> => {
|
||||
return {
|
||||
id: app.id,
|
||||
name: app.name,
|
||||
iconUrl: app.iconUrl,
|
||||
description: null,
|
||||
href: app.href,
|
||||
pingUrl: null,
|
||||
};
|
||||
};
|
||||
@@ -1,53 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import type { InferInsertModel } from "@homarr/db";
|
||||
import type { boards } from "@homarr/db/schema";
|
||||
|
||||
import type { prepareMultipleImports } from "../prepare/prepare-multiple";
|
||||
import { mapColor } from "./map-colors";
|
||||
|
||||
type PreparedBoard = ReturnType<typeof prepareMultipleImports>["preparedBoards"][number];
|
||||
|
||||
export const mapBoard = (preparedBoard: PreparedBoard): InferInsertModel<typeof boards> => ({
|
||||
id: createId(),
|
||||
name: preparedBoard.name,
|
||||
backgroundImageAttachment: preparedBoard.config.settings.customization.backgroundImageAttachment,
|
||||
backgroundImageUrl: preparedBoard.config.settings.customization.backgroundImageUrl,
|
||||
backgroundImageRepeat: preparedBoard.config.settings.customization.backgroundImageRepeat,
|
||||
backgroundImageSize: preparedBoard.config.settings.customization.backgroundImageSize,
|
||||
faviconImageUrl: mapFavicon(preparedBoard.config.settings.customization.faviconUrl),
|
||||
isPublic: preparedBoard.config.settings.access.allowGuests,
|
||||
logoImageUrl: mapLogo(preparedBoard.config.settings.customization.logoImageUrl),
|
||||
pageTitle: preparedBoard.config.settings.customization.pageTitle,
|
||||
metaTitle: preparedBoard.config.settings.customization.metaTitle,
|
||||
opacity: preparedBoard.config.settings.customization.appOpacity,
|
||||
primaryColor: mapColor(preparedBoard.config.settings.customization.colors.primary, "#fa5252"),
|
||||
secondaryColor: mapColor(preparedBoard.config.settings.customization.colors.secondary, "#fd7e14"),
|
||||
});
|
||||
|
||||
const defaultOldmarrLogoPath = "/imgs/logo/logo.png";
|
||||
|
||||
const mapLogo = (logo: string | null | undefined) => {
|
||||
if (!logo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (logo.trim() === defaultOldmarrLogoPath) {
|
||||
return null; // We fallback to default logo when null
|
||||
}
|
||||
|
||||
return logo;
|
||||
};
|
||||
|
||||
const defaultOldmarrFaviconPath = "/imgs/favicon/favicon-squared.png";
|
||||
|
||||
const mapFavicon = (favicon: string | null | undefined) => {
|
||||
if (!favicon) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (favicon.trim() === defaultOldmarrFaviconPath) {
|
||||
return null; // We fallback to default favicon when null
|
||||
}
|
||||
|
||||
return favicon;
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
import type { BoardSize } from "@homarr/old-schema";
|
||||
|
||||
/**
|
||||
* Copied from https://github.com/ajnart/homarr/blob/274eaa92084a8be4d04a69a87f9920860a229128/src/components/Dashboard/Wrappers/gridstack/store.tsx#L21-L30
|
||||
* @param screenSize board size
|
||||
* @returns layout breakpoint for the board
|
||||
*/
|
||||
export const mapBreakpoint = (screenSize: BoardSize) => {
|
||||
switch (screenSize) {
|
||||
case "lg":
|
||||
return 1400;
|
||||
case "md":
|
||||
return 800;
|
||||
case "sm":
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
@@ -1,48 +0,0 @@
|
||||
const oldColors = [
|
||||
"dark",
|
||||
"gray",
|
||||
"red",
|
||||
"pink",
|
||||
"grape",
|
||||
"violet",
|
||||
"indigo",
|
||||
"blue",
|
||||
"cyan",
|
||||
"green",
|
||||
"lime",
|
||||
"yellow",
|
||||
"orange",
|
||||
"teal",
|
||||
] as const;
|
||||
type OldColor = (typeof oldColors)[number];
|
||||
|
||||
export const mapColor = (color: string | undefined, fallback: string) => {
|
||||
if (!color) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
if (!oldColors.some((mantineColor) => color === mantineColor)) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const mantineColor = color as OldColor;
|
||||
|
||||
return mappedColors[mantineColor];
|
||||
};
|
||||
|
||||
const mappedColors: Record<(typeof oldColors)[number], string> = {
|
||||
blue: "#228be6",
|
||||
cyan: "#15aabf",
|
||||
dark: "#2e2e2e",
|
||||
grape: "#be4bdb",
|
||||
gray: "#868e96",
|
||||
green: "#40c057",
|
||||
indigo: "#4c6ef5",
|
||||
lime: "#82c91e",
|
||||
orange: "#fd7e14",
|
||||
pink: "#e64980",
|
||||
red: "#fa5252",
|
||||
teal: "#12b886",
|
||||
violet: "#7950f2",
|
||||
yellow: "#fab005",
|
||||
};
|
||||
@@ -1,17 +0,0 @@
|
||||
import type { BoardSize, OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
export const mapColumnCount = (
|
||||
gridstackSettings: OldmarrConfig["settings"]["customization"]["gridstack"],
|
||||
screenSize: BoardSize,
|
||||
) => {
|
||||
switch (screenSize) {
|
||||
case "lg":
|
||||
return gridstackSettings.columnCountLarge;
|
||||
case "md":
|
||||
return gridstackSettings.columnCountMedium;
|
||||
case "sm":
|
||||
return gridstackSettings.columnCountSmall;
|
||||
default:
|
||||
return 10;
|
||||
}
|
||||
};
|
||||
@@ -1,118 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecretWithKey } from "@homarr/common/server";
|
||||
import type { IntegrationKind } from "@homarr/definitions";
|
||||
import type { OldmarrIntegrationType } from "@homarr/old-schema";
|
||||
|
||||
import type { PreparedIntegration } from "../prepare/prepare-integrations";
|
||||
|
||||
export const mapIntegrationType = (type: OldmarrIntegrationType) => {
|
||||
const kind = mapping[type];
|
||||
if (!kind) {
|
||||
throw new Error(`Integration type ${type} is not supported yet`);
|
||||
}
|
||||
return kind;
|
||||
};
|
||||
|
||||
const mapping: Record<OldmarrIntegrationType, IntegrationKind | null> = {
|
||||
adGuardHome: "adGuardHome",
|
||||
deluge: "deluge",
|
||||
homeAssistant: "homeAssistant",
|
||||
jellyfin: "jellyfin",
|
||||
jellyseerr: "jellyseerr",
|
||||
lidarr: "lidarr",
|
||||
nzbGet: "nzbGet",
|
||||
openmediavault: "openmediavault",
|
||||
overseerr: "overseerr",
|
||||
pihole: "piHole",
|
||||
prowlarr: "prowlarr",
|
||||
proxmox: "proxmox",
|
||||
qBittorrent: "qBittorrent",
|
||||
radarr: "radarr",
|
||||
readarr: "readarr",
|
||||
sabnzbd: "sabNzbd",
|
||||
sonarr: "sonarr",
|
||||
tdarr: "tdarr",
|
||||
transmission: "transmission",
|
||||
plex: "plex",
|
||||
};
|
||||
|
||||
export const mapAndDecryptIntegrations = (
|
||||
preparedIntegrations: PreparedIntegration[],
|
||||
encryptionToken: string | null,
|
||||
) => {
|
||||
if (encryptionToken === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return preparedIntegrations.map(({ type, name, url, properties }) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const kind = mapIntegrationType(type!);
|
||||
|
||||
return {
|
||||
id: createId(),
|
||||
name,
|
||||
url,
|
||||
kind,
|
||||
secrets: mapSecrets(properties, encryptionToken, kind),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const mapSecrets = (properties: PreparedIntegration["properties"], encryptionToken: string, kind: IntegrationKind) => {
|
||||
const key = Buffer.from(encryptionToken, "hex");
|
||||
|
||||
const decryptedProperties = properties.map((property) => ({
|
||||
...property,
|
||||
value: property.value ? decryptSecretWithKey(property.value as `${string}.${string}`, key) : null,
|
||||
}));
|
||||
|
||||
return kind === "proxmox" ? mapProxmoxSecrets(decryptedProperties) : decryptedProperties;
|
||||
};
|
||||
|
||||
/**
|
||||
* Proxmox secrets have bee split up from format `user@realm!tokenId=secret` to separate fields
|
||||
*/
|
||||
const mapProxmoxSecrets = (decryptedProperties: PreparedIntegration["properties"]) => {
|
||||
const apiToken = decryptedProperties.find((property) => property.field === "apiKey");
|
||||
|
||||
if (!apiToken?.value) return [];
|
||||
|
||||
let splitValues = apiToken.value.split("@");
|
||||
|
||||
if (splitValues.length <= 1) return [];
|
||||
|
||||
const [user, ...rest] = splitValues;
|
||||
|
||||
splitValues = rest.join("@").split("!");
|
||||
|
||||
if (splitValues.length <= 1) return [];
|
||||
|
||||
const [realm, ...rest2] = splitValues;
|
||||
|
||||
splitValues = rest2.join("!").split("=");
|
||||
|
||||
if (splitValues.length <= 1) return [];
|
||||
|
||||
const [tokenId, ...rest3] = splitValues;
|
||||
|
||||
const secret = rest3.join("=");
|
||||
|
||||
return [
|
||||
{
|
||||
field: "username" as const,
|
||||
value: user,
|
||||
},
|
||||
{
|
||||
field: "realm" as const,
|
||||
value: realm,
|
||||
},
|
||||
{
|
||||
field: "tokenId" as const,
|
||||
value: tokenId,
|
||||
},
|
||||
{
|
||||
field: "apiKey" as const,
|
||||
value: secret,
|
||||
},
|
||||
];
|
||||
};
|
||||
@@ -1,124 +0,0 @@
|
||||
import SuperJSON from "superjson";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { InferInsertModel } from "@homarr/db";
|
||||
import type { itemLayouts, items } from "@homarr/db/schema";
|
||||
import type { BoardSize, OldmarrApp, OldmarrWidget } from "@homarr/old-schema";
|
||||
import { boardSizes } from "@homarr/old-schema";
|
||||
|
||||
import type { WidgetComponentProps } from "../../../widgets/src/definition";
|
||||
import { mapKind } from "../widgets/definitions";
|
||||
import { mapOptions } from "../widgets/options";
|
||||
|
||||
const logger = createLogger({ module: "mapItem" });
|
||||
|
||||
export const mapApp = (
|
||||
app: OldmarrApp,
|
||||
appsMap: Map<string, { id: string }>,
|
||||
sectionMap: Map<string, { id: string }>,
|
||||
layoutMap: Record<BoardSize, string>,
|
||||
boardId: string,
|
||||
): (InferInsertModel<typeof items> & { layouts: InferInsertModel<typeof itemLayouts>[] }) | null => {
|
||||
if (app.area.type === "sidebar") throw new Error("Mapping app in sidebar is not supported");
|
||||
|
||||
const sectionId = sectionMap.get(app.area.properties.id)?.id;
|
||||
if (!sectionId) {
|
||||
logger.warn("Failed to find section for app. Removing app", {
|
||||
appId: app.id,
|
||||
sectionId: app.area.properties.id,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const itemId = createId();
|
||||
return {
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind: "app",
|
||||
options: SuperJSON.stringify({
|
||||
// it's safe to assume that the app exists in the map
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion, @typescript-eslint/no-non-null-asserted-optional-chain
|
||||
appId: appsMap.get(app.id)?.id!,
|
||||
openInNewTab: app.behaviour.isOpeningNewTab,
|
||||
pingEnabled: app.network.enabledStatusChecker,
|
||||
showTitle: app.appearance.appNameStatus === "normal",
|
||||
layout: app.appearance.positionAppName,
|
||||
descriptionDisplayMode: app.behaviour.tooltipDescription !== "" ? "tooltip" : "hidden",
|
||||
} satisfies WidgetComponentProps<"app">["options"]),
|
||||
layouts: boardSizes.map((size) => {
|
||||
const shapeForSize = app.shape[size];
|
||||
if (!shapeForSize) {
|
||||
throw new Error(`Failed to find a shape for appId='${app.id}' screenSize='${size}'`);
|
||||
}
|
||||
|
||||
return {
|
||||
itemId,
|
||||
height: shapeForSize.size.height,
|
||||
width: shapeForSize.size.width,
|
||||
xOffset: shapeForSize.location.x,
|
||||
yOffset: shapeForSize.location.y,
|
||||
sectionId,
|
||||
layoutId: layoutMap[size],
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
export const mapWidget = (
|
||||
widget: OldmarrWidget,
|
||||
appsMap: Map<string, { id: string }>,
|
||||
sectionMap: Map<string, { id: string }>,
|
||||
layoutMap: Record<BoardSize, string>,
|
||||
boardId: string,
|
||||
): (InferInsertModel<typeof items> & { layouts: InferInsertModel<typeof itemLayouts>[] }) | null => {
|
||||
if (widget.area.type === "sidebar") throw new Error("Mapping widget in sidebar is not supported");
|
||||
|
||||
const kind = mapKind(widget.type);
|
||||
if (!kind) {
|
||||
logger.warn("Failed to map widget type. It's no longer supported", {
|
||||
widgetId: widget.id,
|
||||
widgetType: widget.type,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const sectionId = sectionMap.get(widget.area.properties.id)?.id;
|
||||
if (!sectionId) {
|
||||
logger.warn("Failed to find section for widget. Removing widget", {
|
||||
widgetId: widget.id,
|
||||
sectionId: widget.area.properties.id,
|
||||
});
|
||||
return null;
|
||||
}
|
||||
|
||||
const itemId = createId();
|
||||
return {
|
||||
id: itemId,
|
||||
boardId,
|
||||
kind,
|
||||
options: SuperJSON.stringify(
|
||||
mapOptions(
|
||||
widget.type,
|
||||
widget.properties,
|
||||
new Map([...appsMap.entries()].map(([key, value]) => [key, value.id])),
|
||||
),
|
||||
),
|
||||
layouts: boardSizes.map((size) => {
|
||||
const shapeForSize = widget.shape[size];
|
||||
if (!shapeForSize) {
|
||||
throw new Error(`Failed to find a shape for widgetId='${widget.id}' screenSize='${size}'`);
|
||||
}
|
||||
|
||||
return {
|
||||
itemId,
|
||||
height: shapeForSize.size.height,
|
||||
width: shapeForSize.size.width,
|
||||
xOffset: shapeForSize.location.x,
|
||||
yOffset: shapeForSize.location.y,
|
||||
sectionId,
|
||||
layoutId: layoutMap[size],
|
||||
};
|
||||
}),
|
||||
};
|
||||
};
|
||||
@@ -1,38 +0,0 @@
|
||||
import { stringify } from "superjson";
|
||||
|
||||
import { createId } from "@homarr/common";
|
||||
import type { InferInsertModel } from "@homarr/db";
|
||||
import type { sections } from "@homarr/db/schema";
|
||||
import { emptySuperJSON, rootSectionOffsets } from "@homarr/definitions";
|
||||
import type { OldmarrCategorySection } from "@homarr/old-schema";
|
||||
import { containerSectionOptionsSchema } from "@homarr/validation/shared";
|
||||
|
||||
export const mapLegacyCategoryContainer = (
|
||||
boardId: string,
|
||||
category: OldmarrCategorySection,
|
||||
): InferInsertModel<typeof sections> => ({
|
||||
id: createId(),
|
||||
boardId,
|
||||
kind: "container",
|
||||
xOffset: null,
|
||||
yOffset: null,
|
||||
name: null,
|
||||
options: stringify(
|
||||
containerSectionOptionsSchema.parse({
|
||||
title: category.name.slice(0, 64),
|
||||
showLabel: true,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
}),
|
||||
),
|
||||
});
|
||||
|
||||
export const mapMainRootSection = (boardId: string): InferInsertModel<typeof sections> => ({
|
||||
id: createId(),
|
||||
boardId,
|
||||
kind: "empty",
|
||||
xOffset: rootSectionOffsets.main,
|
||||
yOffset: 0,
|
||||
name: null,
|
||||
options: emptySuperJSON,
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import { decryptSecretWithKey } from "@homarr/common/server";
|
||||
import type { InferInsertModel } from "@homarr/db";
|
||||
import type { users } from "@homarr/db/schema";
|
||||
|
||||
import type { OldmarrImportUser } from "../user-schema";
|
||||
|
||||
export const mapAndDecryptUsers = (importUsers: OldmarrImportUser[], encryptionToken: string | null) => {
|
||||
if (encryptionToken === null) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const key = Buffer.from(encryptionToken, "hex");
|
||||
|
||||
return importUsers.map(
|
||||
({
|
||||
id,
|
||||
password,
|
||||
salt: _saltIsNotNeededAsPartOfPassword,
|
||||
settings,
|
||||
...user
|
||||
}): InferInsertModel<typeof users> & { oldId: string; isAdmin: boolean } => ({
|
||||
...user,
|
||||
oldId: id,
|
||||
id: createId(),
|
||||
name: user.name.toLowerCase(),
|
||||
colorScheme: settings?.colorScheme === "environment" ? "auto" : settings?.colorScheme,
|
||||
firstDayOfWeek: settings?.firstDayOfWeek === "sunday" ? 0 : settings?.firstDayOfWeek === "monday" ? 1 : 6,
|
||||
provider: "credentials",
|
||||
pingIconsEnabled: settings?.replacePingWithIcons,
|
||||
isAdmin: user.isAdmin || user.isOwner,
|
||||
password: decryptSecretWithKey(password, key),
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -1,46 +0,0 @@
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import * as commonServer from "@homarr/common/server";
|
||||
|
||||
import type { PreparedIntegration } from "../../prepare/prepare-integrations";
|
||||
import { mapAndDecryptIntegrations } from "../map-integration";
|
||||
|
||||
describe("Map Integrations", () => {
|
||||
test("should map proxmox integration", () => {
|
||||
vi.spyOn(commonServer, "decryptSecretWithKey").mockReturnValue("user@realm!tokenId=secret");
|
||||
|
||||
const proxmoxIntegration: PreparedIntegration = {
|
||||
type: "proxmox",
|
||||
name: "Proxmox",
|
||||
url: "https://proxmox.com",
|
||||
properties: [
|
||||
{
|
||||
field: "apiKey",
|
||||
value: "any-encrypted-value",
|
||||
type: "private",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const mappedIntegrations = mapAndDecryptIntegrations([proxmoxIntegration], "encryptionToken");
|
||||
|
||||
expect(mappedIntegrations[0]?.secrets).toEqual([
|
||||
{
|
||||
field: "username",
|
||||
value: "user",
|
||||
},
|
||||
{
|
||||
field: "realm",
|
||||
value: "realm",
|
||||
},
|
||||
{
|
||||
field: "tokenId",
|
||||
value: "tokenId",
|
||||
},
|
||||
{
|
||||
field: "apiKey",
|
||||
value: "secret",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,326 +0,0 @@
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { BoardSize, OldmarrApp, OldmarrConfig, OldmarrWidget } from "@homarr/old-schema";
|
||||
import { boardSizes } from "@homarr/old-schema";
|
||||
|
||||
import { mapColumnCount } from "./mappers/map-column-count";
|
||||
import type { OldmarrImportConfiguration } from "./settings";
|
||||
|
||||
const logger = createLogger({ module: "moveWidgetsAndAppsMerge" });
|
||||
|
||||
export const moveWidgetsAndAppsIfMerge = (
|
||||
old: OldmarrConfig,
|
||||
wrapperIdsToMerge: string[],
|
||||
configuration: OldmarrImportConfiguration,
|
||||
) => {
|
||||
const firstId = wrapperIdsToMerge[0];
|
||||
if (!firstId) {
|
||||
return { apps: old.apps, widgets: old.widgets };
|
||||
}
|
||||
|
||||
const affectedMap = new Map<string, { apps: OldmarrApp[]; widgets: OldmarrWidget[] }>(
|
||||
wrapperIdsToMerge.map((id) => [
|
||||
id,
|
||||
{
|
||||
apps: old.apps.filter((app) => app.area.type !== "sidebar" && id === app.area.properties.id),
|
||||
widgets: old.widgets.filter((app) => app.area.type !== "sidebar" && id === app.area.properties.id),
|
||||
},
|
||||
]),
|
||||
);
|
||||
|
||||
logger.debug("Merging wrappers at the end of the board", { count: wrapperIdsToMerge.length });
|
||||
|
||||
const offsets = boardSizes.reduce(
|
||||
(previous, screenSize) => {
|
||||
previous[screenSize] = 0;
|
||||
return previous;
|
||||
},
|
||||
{} as Record<BoardSize, number>,
|
||||
);
|
||||
for (const id of wrapperIdsToMerge) {
|
||||
const requiredHeights = boardSizes.reduce(
|
||||
(previous, screenSize) => {
|
||||
previous[screenSize] = 0;
|
||||
return previous;
|
||||
},
|
||||
{} as Record<BoardSize, number>,
|
||||
);
|
||||
const affected = affectedMap.get(id);
|
||||
if (!affected) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const apps = affected.apps;
|
||||
const widgets = affected.widgets;
|
||||
|
||||
for (const app of apps) {
|
||||
if (app.area.type === "sidebar") continue;
|
||||
// Move item to first wrapper
|
||||
app.area.properties.id = firstId;
|
||||
|
||||
for (const screenSize of boardSizes) {
|
||||
const screenSizeShape = app.shape[screenSize];
|
||||
if (!screenSizeShape) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find the highest widget in the wrapper to increase the offset accordingly
|
||||
if (screenSizeShape.location.y + screenSizeShape.size.height > requiredHeights[screenSize]) {
|
||||
requiredHeights[screenSize] = screenSizeShape.location.y + screenSizeShape.size.height;
|
||||
}
|
||||
|
||||
// Move item down as much as needed to not overlap with other items
|
||||
screenSizeShape.location.y += offsets[screenSize];
|
||||
}
|
||||
}
|
||||
|
||||
for (const widget of widgets) {
|
||||
if (widget.area.type === "sidebar") continue;
|
||||
// Move item to first wrapper
|
||||
widget.area.properties.id = firstId;
|
||||
|
||||
for (const screenSize of boardSizes) {
|
||||
const screenSizeShape = widget.shape[screenSize];
|
||||
if (!screenSizeShape) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Find the highest widget in the wrapper to increase the offset accordingly
|
||||
if (screenSizeShape.location.y + screenSizeShape.size.height > requiredHeights[screenSize]) {
|
||||
requiredHeights[screenSize] = screenSizeShape.location.y + screenSizeShape.size.height;
|
||||
}
|
||||
|
||||
// Move item down as much as needed to not overlap with other items
|
||||
screenSizeShape.location.y += offsets[screenSize];
|
||||
}
|
||||
}
|
||||
|
||||
for (const screenSize of boardSizes) {
|
||||
offsets[screenSize] += requiredHeights[screenSize];
|
||||
}
|
||||
}
|
||||
|
||||
if (configuration.sidebarBehaviour === "last-section") {
|
||||
const areas = [...old.apps.map((app) => app.area), ...old.widgets.map((widget) => widget.area)];
|
||||
if (
|
||||
old.settings.customization.layout.enabledLeftSidebar ||
|
||||
areas.some((area) => area.type === "sidebar" && area.properties.location === "left")
|
||||
) {
|
||||
for (const screenSize of boardSizes) {
|
||||
offsets[screenSize] = moveWidgetsAndAppsInLeftSidebar(old, firstId, offsets[screenSize], screenSize);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
old.settings.customization.layout.enabledRightSidebar ||
|
||||
areas.some((area) => area.type === "sidebar" && area.properties.location === "right")
|
||||
) {
|
||||
for (const screenSize of boardSizes) {
|
||||
moveWidgetsAndAppsInRightSidebar(old, firstId, offsets[screenSize], screenSize);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Remove all widgets and apps in the sidebar
|
||||
return {
|
||||
apps: old.apps.filter((app) => app.area.type !== "sidebar"),
|
||||
widgets: old.widgets.filter((app) => app.area.type !== "sidebar"),
|
||||
};
|
||||
}
|
||||
|
||||
return { apps: old.apps, widgets: old.widgets };
|
||||
};
|
||||
|
||||
const moveWidgetsAndAppsInLeftSidebar = (
|
||||
old: OldmarrConfig,
|
||||
firstId: string,
|
||||
offset: number,
|
||||
screenSize: BoardSize,
|
||||
) => {
|
||||
const columnCount = mapColumnCount(old.settings.customization.gridstack, screenSize);
|
||||
let requiredHeight = updateItems({
|
||||
// This should work as the reference of the items did not change, only the array reference did
|
||||
items: [...old.widgets, ...old.apps],
|
||||
screenSize,
|
||||
filter: (item) =>
|
||||
item.area.type === "sidebar" &&
|
||||
item.area.properties.location === "left" &&
|
||||
(columnCount >= 2 || item.shape[screenSize]?.location.x === 0),
|
||||
update: (item) => {
|
||||
item.area = {
|
||||
type: "wrapper",
|
||||
properties: {
|
||||
id: firstId,
|
||||
},
|
||||
};
|
||||
|
||||
const screenSizeShape = item.shape[screenSize];
|
||||
if (!screenSizeShape) return;
|
||||
|
||||
// Reduce width to one if column count is one
|
||||
if (screenSizeShape.size.width > columnCount) {
|
||||
screenSizeShape.size.width = columnCount;
|
||||
}
|
||||
|
||||
screenSizeShape.location.y += offset;
|
||||
},
|
||||
});
|
||||
|
||||
// Only increase offset if there are less than 3 columns because then the items have to be stacked
|
||||
if (columnCount <= 3) {
|
||||
offset += requiredHeight;
|
||||
}
|
||||
|
||||
// When column count is 0 we need to stack the items of the sidebar on top of each other
|
||||
if (columnCount !== 1) {
|
||||
return offset;
|
||||
}
|
||||
|
||||
requiredHeight = updateItems({
|
||||
// This should work as the reference of the items did not change, only the array reference did
|
||||
items: [...old.widgets, ...old.apps],
|
||||
screenSize,
|
||||
filter: (item) =>
|
||||
item.area.type === "sidebar" &&
|
||||
item.area.properties.location === "left" &&
|
||||
item.shape[screenSize]?.location.x === 1,
|
||||
update: (item) => {
|
||||
item.area = {
|
||||
type: "wrapper",
|
||||
properties: {
|
||||
id: firstId,
|
||||
},
|
||||
};
|
||||
|
||||
const screenSizeShape = item.shape[screenSize];
|
||||
if (!screenSizeShape) return;
|
||||
|
||||
screenSizeShape.location.x = 0;
|
||||
screenSizeShape.location.y += offset;
|
||||
},
|
||||
});
|
||||
|
||||
offset += requiredHeight;
|
||||
return offset;
|
||||
};
|
||||
|
||||
const moveWidgetsAndAppsInRightSidebar = (
|
||||
old: OldmarrConfig,
|
||||
firstId: string,
|
||||
offset: number,
|
||||
screenSize: BoardSize,
|
||||
) => {
|
||||
const columnCount = mapColumnCount(old.settings.customization.gridstack, screenSize);
|
||||
const xOffsetDelta = Math.max(columnCount - 2, 0);
|
||||
const requiredHeight = updateItems({
|
||||
// This should work as the reference of the items did not change, only the array reference did
|
||||
items: [...old.widgets, ...old.apps],
|
||||
screenSize,
|
||||
filter: (item) =>
|
||||
item.area.type === "sidebar" &&
|
||||
item.area.properties.location === "right" &&
|
||||
(columnCount >= 2 || item.shape[screenSize]?.location.x === 0),
|
||||
update: (item) => {
|
||||
item.area = {
|
||||
type: "wrapper",
|
||||
properties: {
|
||||
id: firstId,
|
||||
},
|
||||
};
|
||||
|
||||
const screenSizeShape = item.shape[screenSize];
|
||||
if (!screenSizeShape) return;
|
||||
|
||||
// Reduce width to one if column count is one
|
||||
if (screenSizeShape.size.width > columnCount) {
|
||||
screenSizeShape.size.width = columnCount;
|
||||
}
|
||||
|
||||
screenSizeShape.location.y += offset;
|
||||
screenSizeShape.location.x += xOffsetDelta;
|
||||
},
|
||||
});
|
||||
|
||||
// When column count is 0 we need to stack the items of the sidebar on top of each other
|
||||
if (columnCount !== 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
offset += requiredHeight;
|
||||
|
||||
updateItems({
|
||||
// This should work as the reference of the items did not change, only the array reference did
|
||||
items: [...old.widgets, ...old.apps],
|
||||
screenSize,
|
||||
filter: (item) =>
|
||||
item.area.type === "sidebar" &&
|
||||
item.area.properties.location === "left" &&
|
||||
item.shape[screenSize]?.location.x === 1,
|
||||
update: (item) => {
|
||||
item.area = {
|
||||
type: "wrapper",
|
||||
properties: {
|
||||
id: firstId,
|
||||
},
|
||||
};
|
||||
|
||||
const screenSizeShape = item.shape[screenSize];
|
||||
if (!screenSizeShape) return;
|
||||
|
||||
screenSizeShape.location.x = 0;
|
||||
screenSizeShape.location.y += offset;
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const createItemSnapshot = (item: OldmarrApp | OldmarrWidget, screenSize: BoardSize) => ({
|
||||
x: item.shape[screenSize]?.location.x,
|
||||
y: item.shape[screenSize]?.location.y,
|
||||
height: item.shape[screenSize]?.size.height,
|
||||
width: item.shape[screenSize]?.size.width,
|
||||
section:
|
||||
item.area.type === "sidebar"
|
||||
? {
|
||||
type: "sidebar",
|
||||
location: item.area.properties.location,
|
||||
}
|
||||
: {
|
||||
type: item.area.type,
|
||||
id: item.area.properties.id,
|
||||
},
|
||||
toString(): string {
|
||||
return objectEntries(this)
|
||||
.filter(([key]) => key !== "toString")
|
||||
.map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
|
||||
.join(" ");
|
||||
},
|
||||
});
|
||||
|
||||
const updateItems = (options: {
|
||||
items: (OldmarrApp | OldmarrWidget)[];
|
||||
filter: (item: OldmarrApp | OldmarrWidget) => boolean;
|
||||
update: (item: OldmarrApp | OldmarrWidget) => void;
|
||||
screenSize: BoardSize;
|
||||
}) => {
|
||||
const items = options.items.filter(options.filter);
|
||||
let requiredHeight = 0;
|
||||
for (const item of items) {
|
||||
const before = createItemSnapshot(item, options.screenSize);
|
||||
|
||||
options.update(item);
|
||||
|
||||
const screenSizeShape = item.shape[options.screenSize];
|
||||
if (!screenSizeShape) return requiredHeight;
|
||||
|
||||
if (screenSizeShape.location.y + screenSizeShape.size.height > requiredHeight) {
|
||||
requiredHeight = screenSizeShape.location.y + screenSizeShape.size.height;
|
||||
}
|
||||
|
||||
const after = createItemSnapshot(item, options.screenSize);
|
||||
|
||||
logger.debug(
|
||||
`Moved item ${item.id}\n [snapshot before]: ${before.toString()}\n [snapshot after]: ${after.toString()}`,
|
||||
);
|
||||
}
|
||||
|
||||
return requiredHeight;
|
||||
};
|
||||
@@ -1,59 +0,0 @@
|
||||
import type { InferSelectModel } from "@homarr/db";
|
||||
import type { apps } from "@homarr/db/schema";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import type { ValidAnalyseConfig } from "../analyse/types";
|
||||
import { mapOldmarrApp, mapOldmarrBookmarkApp } from "../mappers/map-app";
|
||||
import type { OldmarrBookmarkDefinition } from "../widgets/definitions/bookmark";
|
||||
|
||||
export type PreparedApp = Omit<InferSelectModel<typeof apps>, "id"> & { ids: string[]; existingId?: string };
|
||||
|
||||
export const prepareApps = (analyseConfigs: ValidAnalyseConfig[]) => {
|
||||
const preparedApps: PreparedApp[] = [];
|
||||
|
||||
analyseConfigs.forEach(({ config }) => {
|
||||
const appsFromConfig = extractAppsFromConfig(config).concat(extractBookmarkAppsFromConfig(config));
|
||||
addAppsToPreparedApps(preparedApps, appsFromConfig);
|
||||
});
|
||||
|
||||
return preparedApps;
|
||||
};
|
||||
|
||||
const extractAppsFromConfig = (config: OldmarrConfig) => {
|
||||
return config.apps.map(mapOldmarrApp);
|
||||
};
|
||||
|
||||
const extractBookmarkAppsFromConfig = (config: OldmarrConfig) => {
|
||||
const bookmarkWidgets = config.widgets.filter((widget) => widget.type === "bookmark");
|
||||
return bookmarkWidgets.flatMap((widget) =>
|
||||
(widget.properties as OldmarrBookmarkDefinition["options"]).items.map(mapOldmarrBookmarkApp),
|
||||
);
|
||||
};
|
||||
|
||||
const addAppsToPreparedApps = (preparedApps: PreparedApp[], configApps: InferSelectModel<typeof apps>[]) => {
|
||||
configApps.forEach(({ id, ...app }) => {
|
||||
const existingApp = preparedApps.find((preparedApp) => doAppsMatch(preparedApp, app));
|
||||
|
||||
if (existingApp) {
|
||||
existingApp.ids.push(id);
|
||||
return;
|
||||
}
|
||||
|
||||
preparedApps.push({
|
||||
...app,
|
||||
ids: [id],
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
export const doAppsMatch = (
|
||||
app1: Omit<InferSelectModel<typeof apps>, "id">,
|
||||
app2: Omit<InferSelectModel<typeof apps>, "id">,
|
||||
) => {
|
||||
return (
|
||||
app1.name === app2.name &&
|
||||
app1.iconUrl === app2.iconUrl &&
|
||||
app1.description === app2.description &&
|
||||
app1.href === app2.href
|
||||
);
|
||||
};
|
||||
@@ -1,6 +0,0 @@
|
||||
import type { ValidAnalyseConfig } from "../analyse/types";
|
||||
import type { BoardSelectionMap } from "../components/initial/board-selection-card";
|
||||
|
||||
export const prepareBoards = (analyseConfigs: ValidAnalyseConfig[], selections: BoardSelectionMap) => {
|
||||
return analyseConfigs.filter(({ name }) => selections.get(name));
|
||||
};
|
||||
@@ -1,19 +0,0 @@
|
||||
import type { ValidAnalyseConfig } from "../analyse/types";
|
||||
|
||||
export type PreparedIntegration = ReturnType<typeof prepareIntegrations>[number];
|
||||
|
||||
export const prepareIntegrations = (analyseConfigs: ValidAnalyseConfig[]) => {
|
||||
return analyseConfigs.flatMap(({ config }) => {
|
||||
return config.apps
|
||||
.map((app) =>
|
||||
app.integration?.type
|
||||
? {
|
||||
...app.integration,
|
||||
name: app.name,
|
||||
url: app.url,
|
||||
}
|
||||
: null,
|
||||
)
|
||||
.filter((integration) => integration !== null);
|
||||
});
|
||||
};
|
||||
@@ -1,105 +0,0 @@
|
||||
import { generateResponsiveGridFor } from "@homarr/common";
|
||||
import type { GridAlgorithmItem } from "@homarr/common";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
import type { BoardSize, OldmarrApp, OldmarrConfig, OldmarrWidget, SizedShape } from "@homarr/old-schema";
|
||||
import { boardSizes } from "@homarr/old-schema";
|
||||
|
||||
import { mapColumnCount } from "../mappers/map-column-count";
|
||||
import { mapApp, mapWidget } from "../mappers/map-item";
|
||||
|
||||
const logger = createLogger({ module: "prepareItems" });
|
||||
|
||||
export const prepareItems = (
|
||||
{ apps, widgets, settings }: Pick<OldmarrConfig, "apps" | "widgets" | "settings">,
|
||||
appsMap: Map<string, { id: string }>,
|
||||
sectionMap: Map<string, { id: string }>,
|
||||
layoutMap: Record<BoardSize, string>,
|
||||
boardId: string,
|
||||
) => {
|
||||
let localApps = apps;
|
||||
let localWidgets = widgets;
|
||||
|
||||
const incompleteSizes = boardSizes.filter((size) =>
|
||||
widgets
|
||||
.map((widget) => widget.shape)
|
||||
.concat(apps.map((app) => app.shape))
|
||||
.some((shape) => !shape[size]),
|
||||
);
|
||||
|
||||
if (incompleteSizes.length > 0) {
|
||||
logger.warn("Found items with incomplete sizes. Generating missing sizes.", {
|
||||
boardId,
|
||||
count: incompleteSizes.length,
|
||||
sizes: incompleteSizes.join(", "),
|
||||
});
|
||||
|
||||
incompleteSizes.forEach((size) => {
|
||||
const columnCount = mapColumnCount(settings.customization.gridstack, size);
|
||||
const previousSize = !incompleteSizes.includes("lg") ? "lg" : incompleteSizes.includes("sm") ? "md" : "sm";
|
||||
const previousWidth = mapColumnCount(settings.customization.gridstack, previousSize);
|
||||
logger.info("Generating missing size", { boardId, from: previousSize, to: size });
|
||||
|
||||
const items = widgets
|
||||
.map((item) => mapItemForGridAlgorithm(item, previousSize))
|
||||
.concat(apps.map((item) => mapItemForGridAlgorithm(item, previousSize)));
|
||||
|
||||
const distinctSectionIds = [...new Set(items.map((item) => item.sectionId))];
|
||||
distinctSectionIds.forEach((sectionId) => {
|
||||
const { items: newItems } = generateResponsiveGridFor({ items, previousWidth, width: columnCount, sectionId });
|
||||
|
||||
localApps = localApps.map((app) => {
|
||||
const item = newItems.find((item) => item.id === app.id);
|
||||
if (!item) return app;
|
||||
|
||||
return {
|
||||
...app,
|
||||
shape: {
|
||||
...app.shape,
|
||||
[size]: mapShapeFromGridAlgorithm(item),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
localWidgets = localWidgets.map((widget) => {
|
||||
const item = newItems.find((item) => item.id === widget.id);
|
||||
if (!item) return widget;
|
||||
|
||||
return {
|
||||
...widget,
|
||||
shape: {
|
||||
...widget.shape,
|
||||
[size]: mapShapeFromGridAlgorithm(item),
|
||||
},
|
||||
};
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
return localWidgets
|
||||
.map((widget) => mapWidget(widget, appsMap, sectionMap, layoutMap, boardId))
|
||||
.concat(localApps.map((app) => mapApp(app, appsMap, sectionMap, layoutMap, boardId)))
|
||||
.filter((widget) => widget !== null);
|
||||
};
|
||||
|
||||
const mapItemForGridAlgorithm = (item: OldmarrApp | OldmarrWidget, size: BoardSize): GridAlgorithmItem => ({
|
||||
width: item.shape[size]?.size.width ?? 1,
|
||||
height: item.shape[size]?.size.height ?? 1,
|
||||
xOffset: item.shape[size]?.location.x ?? 0,
|
||||
yOffset: item.shape[size]?.location.y ?? 0,
|
||||
sectionId: item.area.type === "sidebar" ? item.area.properties.location : item.area.properties.id,
|
||||
id: item.id,
|
||||
type: "item",
|
||||
});
|
||||
|
||||
const mapShapeFromGridAlgorithm = (item: GridAlgorithmItem) =>
|
||||
({
|
||||
location: {
|
||||
x: item.xOffset,
|
||||
y: item.yOffset,
|
||||
},
|
||||
size: {
|
||||
width: item.width,
|
||||
height: item.height,
|
||||
},
|
||||
}) satisfies SizedShape;
|
||||
@@ -1,25 +0,0 @@
|
||||
import type { AnalyseConfig, ValidAnalyseConfig } from "../analyse/types";
|
||||
import type { BoardSelectionMap } from "../components/initial/board-selection-card";
|
||||
import type { InitialOldmarrImportSettings } from "../settings";
|
||||
import { prepareApps } from "./prepare-apps";
|
||||
import { prepareBoards } from "./prepare-boards";
|
||||
import { prepareIntegrations } from "./prepare-integrations";
|
||||
|
||||
export const prepareMultipleImports = (
|
||||
analyseConfigs: AnalyseConfig[],
|
||||
settings: InitialOldmarrImportSettings,
|
||||
selections: BoardSelectionMap,
|
||||
) => {
|
||||
const invalidConfigs = analyseConfigs.filter((item) => item.config === null);
|
||||
invalidConfigs.forEach(({ name }) => {
|
||||
console.warn(`Skipping import of ${name} due to error in configuration. See logs of container for more details.`);
|
||||
});
|
||||
|
||||
const filteredConfigs = analyseConfigs.filter((item): item is ValidAnalyseConfig => item.config !== null);
|
||||
|
||||
return {
|
||||
preparedApps: prepareApps(filteredConfigs),
|
||||
preparedBoards: settings.onlyImportApps ? [] : prepareBoards(filteredConfigs, selections),
|
||||
preparedIntegrations: prepareIntegrations(filteredConfigs),
|
||||
};
|
||||
};
|
||||
@@ -1,87 +0,0 @@
|
||||
import { parse } from "superjson";
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { placePreparedSections, prepareSections } from "./prepare-sections";
|
||||
|
||||
describe("prepareSections", () => {
|
||||
test("maps legacy blocks into one root and durable containers", () => {
|
||||
const prepared = prepareSections("board", {
|
||||
categories: [{ id: "category", name: "Media", position: 1 }],
|
||||
wrappers: [{ id: "wrapper", position: 0 }],
|
||||
});
|
||||
const root = prepared.sections.find((section) => section.kind === "empty");
|
||||
const container = prepared.sections.find((section) => section.kind === "container");
|
||||
if (!root || !container) throw new Error("Expected a root and a container");
|
||||
|
||||
expect(prepared.sections).toHaveLength(2);
|
||||
expect(root).toMatchObject({ boardId: "board", xOffset: 0, yOffset: 0 });
|
||||
expect(container).toMatchObject({ boardId: "board", xOffset: null, yOffset: null, name: null });
|
||||
expect(parse(container.options ?? "{}")).toMatchObject({
|
||||
title: "Media",
|
||||
showLabel: true,
|
||||
collapsible: true,
|
||||
showOpenAll: true,
|
||||
});
|
||||
expect(prepared.byLegacyId.get("category")?.id).toBe(container.id);
|
||||
expect(prepared.byLegacyId.get("wrapper")?.id).not.toBe(root.id);
|
||||
});
|
||||
|
||||
test("places root content and containers in legacy order for every layout", () => {
|
||||
const prepared = prepareSections("board", {
|
||||
categories: [{ id: "category", name: "Media", position: 1 }],
|
||||
wrappers: [{ id: "wrapper", position: 0 }],
|
||||
});
|
||||
const wrapperPlacementId = prepared.byLegacyId.get("wrapper")?.id;
|
||||
const containerId = prepared.byLegacyId.get("category")?.id;
|
||||
if (!wrapperPlacementId || !containerId) throw new Error("Expected mapped section ids");
|
||||
|
||||
const preparedItems = [
|
||||
{
|
||||
layouts: [
|
||||
{
|
||||
itemId: "root-item",
|
||||
layoutId: "layout",
|
||||
sectionId: wrapperPlacementId,
|
||||
xOffset: 1,
|
||||
yOffset: 0,
|
||||
width: 2,
|
||||
height: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
layouts: [
|
||||
{
|
||||
itemId: "container-item",
|
||||
layoutId: "layout",
|
||||
sectionId: containerId,
|
||||
xOffset: 0,
|
||||
yOffset: 1,
|
||||
width: 3,
|
||||
height: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const layouts = placePreparedSections(prepared, preparedItems, [{ id: "layout", columnCount: 12 }]);
|
||||
|
||||
expect(preparedItems[0]?.layouts[0]).toMatchObject({
|
||||
sectionId: prepared.mainRootId,
|
||||
xOffset: 1,
|
||||
yOffset: 0,
|
||||
});
|
||||
expect(preparedItems[1]?.layouts[0]).toMatchObject({ sectionId: containerId, yOffset: 1 });
|
||||
expect(layouts).toEqual([
|
||||
{
|
||||
sectionId: containerId,
|
||||
layoutId: "layout",
|
||||
parentSectionId: prepared.mainRootId,
|
||||
xOffset: 0,
|
||||
yOffset: 2,
|
||||
width: 12,
|
||||
height: 3,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,115 +0,0 @@
|
||||
import { createId } from "@homarr/common";
|
||||
import type { InferInsertModel } from "@homarr/db";
|
||||
import type { itemLayouts, sectionLayouts, sections } from "@homarr/db/schema";
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import { mapLegacyCategoryContainer, mapMainRootSection } from "../mappers/map-section";
|
||||
|
||||
interface PreparedSectionBlock {
|
||||
id: string;
|
||||
legacyId: string;
|
||||
position: number;
|
||||
type: "container" | "root-content";
|
||||
}
|
||||
|
||||
interface PreparedSections {
|
||||
blocks: PreparedSectionBlock[];
|
||||
byLegacyId: Map<string, { id: string }>;
|
||||
mainRootId: string;
|
||||
sections: InferInsertModel<typeof sections>[];
|
||||
}
|
||||
|
||||
interface PreparedItemWithLayouts {
|
||||
layouts: InferInsertModel<typeof itemLayouts>[];
|
||||
}
|
||||
|
||||
export const prepareSections = (
|
||||
boardId: string,
|
||||
{ categories, wrappers }: Pick<OldmarrConfig, "categories" | "wrappers">,
|
||||
): PreparedSections => {
|
||||
const mainRoot = mapMainRootSection(boardId);
|
||||
const containers = categories.map((category) => ({
|
||||
category,
|
||||
section: mapLegacyCategoryContainer(boardId, category),
|
||||
}));
|
||||
const rootContent = wrappers.map((wrapper) => ({ wrapper, id: createId() }));
|
||||
|
||||
return {
|
||||
mainRootId: mainRoot.id,
|
||||
sections: [mainRoot, ...containers.map(({ section }) => section)],
|
||||
byLegacyId: new Map([
|
||||
...containers.map(({ category, section }) => [category.id, { id: section.id }] as const),
|
||||
...rootContent.map(({ wrapper, id }) => [wrapper.id, { id }] as const),
|
||||
]),
|
||||
blocks: [
|
||||
...containers.map(({ category, section }) => ({
|
||||
id: section.id,
|
||||
legacyId: category.id,
|
||||
position: category.position,
|
||||
type: "container" as const,
|
||||
})),
|
||||
...rootContent.map(({ wrapper, id }) => ({
|
||||
id,
|
||||
legacyId: wrapper.id,
|
||||
position: wrapper.position,
|
||||
type: "root-content" as const,
|
||||
})),
|
||||
].toSorted(
|
||||
(first, second) =>
|
||||
first.position - second.position ||
|
||||
(first.type === second.type
|
||||
? first.legacyId.localeCompare(second.legacyId)
|
||||
: first.type === "container"
|
||||
? -1
|
||||
: 1),
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* Old Homarr stored each top-level block in its own coordinate space. The
|
||||
* current model has one main root and places labelled containers inside it.
|
||||
* This compacts those blocks in their legacy order without changing the
|
||||
* coordinates of content inside a container.
|
||||
*/
|
||||
export const placePreparedSections = (
|
||||
preparedSections: PreparedSections,
|
||||
preparedItems: PreparedItemWithLayouts[],
|
||||
preparedLayouts: { id: string; columnCount: number }[],
|
||||
): InferInsertModel<typeof sectionLayouts>[] => {
|
||||
const result: InferInsertModel<typeof sectionLayouts>[] = [];
|
||||
|
||||
for (const layout of preparedLayouts) {
|
||||
let nextRow = 0;
|
||||
|
||||
for (const block of preparedSections.blocks) {
|
||||
const content = preparedItems.flatMap((item) =>
|
||||
item.layouts.filter((itemLayout) => itemLayout.layoutId === layout.id && itemLayout.sectionId === block.id),
|
||||
);
|
||||
const contentHeight = Math.max(0, ...content.map((itemLayout) => itemLayout.yOffset + itemLayout.height));
|
||||
|
||||
if (block.type === "container") {
|
||||
const height = Math.max(1, contentHeight);
|
||||
result.push({
|
||||
sectionId: block.id,
|
||||
layoutId: layout.id,
|
||||
parentSectionId: preparedSections.mainRootId,
|
||||
xOffset: 0,
|
||||
yOffset: nextRow,
|
||||
width: layout.columnCount,
|
||||
height,
|
||||
});
|
||||
nextRow += height;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const itemLayout of content) {
|
||||
itemLayout.sectionId = preparedSections.mainRootId;
|
||||
itemLayout.yOffset += nextRow;
|
||||
}
|
||||
nextRow += contentHeight;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
import type { OldmarrConfig } from "@homarr/old-schema";
|
||||
|
||||
import type { OldmarrImportConfiguration } from "../settings";
|
||||
import { prepareApps } from "./prepare-apps";
|
||||
|
||||
export const prepareSingleImport = (config: OldmarrConfig, settings: OldmarrImportConfiguration) => {
|
||||
const validAnalyseConfigs = [{ name: settings.name, config, isError: false }];
|
||||
|
||||
return {
|
||||
preparedApps: prepareApps(validAnalyseConfigs),
|
||||
preparedBoards: settings.onlyImportApps ? [] : validAnalyseConfigs,
|
||||
};
|
||||
};
|
||||
@@ -1,55 +0,0 @@
|
||||
import { zfd } from "zod-form-data";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { boardNameSchema } from "@homarr/validation/board";
|
||||
import { createCustomErrorParams } from "@homarr/validation/form/i18n";
|
||||
|
||||
export const sidebarBehaviours = ["remove-items", "last-section"] as const;
|
||||
export const defaultSidebarBehaviour = "last-section";
|
||||
export type SidebarBehaviour = (typeof sidebarBehaviours)[number];
|
||||
|
||||
export const oldmarrImportConfigurationSchema = z.object({
|
||||
name: boardNameSchema,
|
||||
onlyImportApps: z.boolean().default(false),
|
||||
sidebarBehaviour: z.enum(sidebarBehaviours).default(defaultSidebarBehaviour),
|
||||
});
|
||||
|
||||
export type OldmarrImportConfiguration = z.infer<typeof oldmarrImportConfigurationSchema>;
|
||||
|
||||
export const initialOldmarrImportSettings = oldmarrImportConfigurationSchema.pick({
|
||||
onlyImportApps: true,
|
||||
sidebarBehaviour: true,
|
||||
});
|
||||
|
||||
export type InitialOldmarrImportSettings = z.infer<typeof initialOldmarrImportSettings>;
|
||||
|
||||
export const checkJsonImportFile: z.core.CheckFn<File> = (context) => {
|
||||
if (context.value.type !== "application/json") {
|
||||
context.issues.push({
|
||||
code: "custom",
|
||||
params: createCustomErrorParams({
|
||||
key: "invalidFileType",
|
||||
params: { expected: "JSON" },
|
||||
}),
|
||||
input: context.value.type,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.value.size > 1024 * 1024) {
|
||||
context.issues.push({
|
||||
code: "custom",
|
||||
params: createCustomErrorParams({
|
||||
key: "fileTooLarge",
|
||||
params: { maxSize: "1 MB" },
|
||||
}),
|
||||
input: context.value.size,
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
export const importJsonFileSchema = zfd.formData({
|
||||
file: zfd.file().check(checkJsonImportFile),
|
||||
configuration: zfd.json(oldmarrImportConfigurationSchema),
|
||||
});
|
||||
@@ -1,2 +0,0 @@
|
||||
export { importJsonFileSchema, checkJsonImportFile, oldmarrImportConfigurationSchema } from "./settings";
|
||||
export type { OldmarrImportConfiguration } from "./settings";
|
||||
@@ -1,29 +0,0 @@
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { requiredNullableEmailSchema } from "@homarr/validation/email";
|
||||
|
||||
const regexEncryptedSchema = z.string().regex(/^[a-f0-9]+\.[a-f0-9]+$/g);
|
||||
|
||||
const encryptedSchema = z.custom<`${string}.${string}`>((value) => regexEncryptedSchema.safeParse(value).success);
|
||||
|
||||
export const oldmarrImportUserSchema = z.object({
|
||||
id: z.string(),
|
||||
name: z.string(),
|
||||
email: requiredNullableEmailSchema,
|
||||
emailVerified: z.date().nullable(),
|
||||
image: z.string().nullable(),
|
||||
isAdmin: z.boolean(),
|
||||
isOwner: z.boolean(),
|
||||
settings: z
|
||||
.object({
|
||||
colorScheme: z.enum(["environment", "light", "dark"]),
|
||||
defaultBoard: z.string(),
|
||||
firstDayOfWeek: z.enum(["monday", "saturday", "sunday"]),
|
||||
replacePingWithIcons: z.boolean(),
|
||||
})
|
||||
.nullable(),
|
||||
password: encryptedSchema,
|
||||
salt: encryptedSchema,
|
||||
});
|
||||
|
||||
export type OldmarrImportUser = z.infer<typeof oldmarrImportUserSchema>;
|
||||
@@ -1,20 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrBookmarkDefinition = CommonOldmarrWidgetDefinition<
|
||||
"bookmark",
|
||||
{
|
||||
name: string;
|
||||
items: {
|
||||
id: string;
|
||||
name: string;
|
||||
href: string;
|
||||
iconUrl: string;
|
||||
openNewTab: boolean;
|
||||
hideHostname: boolean;
|
||||
hideIcon: boolean;
|
||||
}[];
|
||||
layout: "autoGrid" | "horizontal" | "vertical";
|
||||
}
|
||||
>;
|
||||
|
||||
export type BookmarkApp = OldmarrBookmarkDefinition["options"]["items"][number];
|
||||
@@ -1,11 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrCalendarDefinition = CommonOldmarrWidgetDefinition<
|
||||
"calendar",
|
||||
{
|
||||
hideWeekDays: boolean;
|
||||
showUnmonitored: boolean;
|
||||
radarrReleaseType: "inCinemas" | "physicalRelease" | "digitalRelease";
|
||||
fontSize: "xs" | "sm" | "md" | "lg" | "xl";
|
||||
}
|
||||
>;
|
||||
@@ -1,9 +0,0 @@
|
||||
import type { OldmarrWidgetKind } from "@homarr/old-schema";
|
||||
|
||||
export interface CommonOldmarrWidgetDefinition<
|
||||
TId extends OldmarrWidgetKind,
|
||||
TOptions extends Record<string, unknown>,
|
||||
> {
|
||||
id: TId;
|
||||
options: TOptions;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrDashdotDefinition = CommonOldmarrWidgetDefinition<
|
||||
"dashdot",
|
||||
{
|
||||
dashName: string;
|
||||
url: string;
|
||||
usePercentages: boolean;
|
||||
columns: number;
|
||||
graphHeight: number;
|
||||
graphsOrder: (
|
||||
| {
|
||||
key: "storage";
|
||||
subValues: {
|
||||
enabled: boolean;
|
||||
compactView: boolean;
|
||||
span: number;
|
||||
multiView: boolean;
|
||||
};
|
||||
}
|
||||
| {
|
||||
key: "network";
|
||||
subValues: {
|
||||
enabled: boolean;
|
||||
compactView: boolean;
|
||||
span: number;
|
||||
};
|
||||
}
|
||||
| {
|
||||
key: "cpu";
|
||||
subValues: {
|
||||
enabled: boolean;
|
||||
multiView: boolean;
|
||||
span: number;
|
||||
};
|
||||
}
|
||||
| {
|
||||
key: "ram";
|
||||
subValues: {
|
||||
enabled: boolean;
|
||||
span: number;
|
||||
};
|
||||
}
|
||||
| {
|
||||
key: "gpu";
|
||||
subValues: {
|
||||
enabled: boolean;
|
||||
span: number;
|
||||
};
|
||||
}
|
||||
)[];
|
||||
}
|
||||
>;
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrDateDefinition = CommonOldmarrWidgetDefinition<
|
||||
"date",
|
||||
{
|
||||
timezone: string;
|
||||
customTitle: string;
|
||||
display24HourFormat: boolean;
|
||||
dateFormat:
|
||||
| "hide"
|
||||
| "dddd, MMMM D"
|
||||
| "dddd, D MMMM"
|
||||
| "MMM D"
|
||||
| "D MMM"
|
||||
| "DD/MM/YYYY"
|
||||
| "MM/DD/YYYY"
|
||||
| "DD/MM"
|
||||
| "MM/DD";
|
||||
titleState: "none" | "city" | "both";
|
||||
}
|
||||
>;
|
||||
@@ -1,4 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-empty-object-type
|
||||
export type OldmarrDlspeedDefinition = CommonOldmarrWidgetDefinition<"dlspeed", {}>;
|
||||
@@ -1,8 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrDnsHoleControlsDefinition = CommonOldmarrWidgetDefinition<
|
||||
"dns-hole-controls",
|
||||
{
|
||||
showToggleAllButtons: boolean;
|
||||
}
|
||||
>;
|
||||
@@ -1,6 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrDnsHoleSummaryDefinition = CommonOldmarrWidgetDefinition<
|
||||
"dns-hole-summary",
|
||||
{ usePiHoleColors: boolean; layout: "column" | "row" | "grid" }
|
||||
>;
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrHealthMonitoringDefinition = CommonOldmarrWidgetDefinition<
|
||||
"health-monitoring",
|
||||
{
|
||||
fahrenheit: boolean;
|
||||
cpu: boolean;
|
||||
memory: boolean;
|
||||
fileSystem: boolean;
|
||||
defaultTabState: "system" | "cluster";
|
||||
node: string;
|
||||
defaultViewState: "storage" | "none" | "node" | "vm" | "lxc";
|
||||
summary: boolean;
|
||||
showNode: boolean;
|
||||
showVM: boolean;
|
||||
showLXCs: boolean;
|
||||
showStorage: boolean;
|
||||
sectionIndicatorColor: "all" | "any";
|
||||
ignoreCert: boolean;
|
||||
}
|
||||
>;
|
||||
@@ -1,16 +0,0 @@
|
||||
import type { CommonOldmarrWidgetDefinition } from "./common";
|
||||
|
||||
export type OldmarrIframeDefinition = CommonOldmarrWidgetDefinition<
|
||||
"iframe",
|
||||
{
|
||||
embedUrl: string;
|
||||
allowFullScreen: boolean;
|
||||
allowScrolling: boolean;
|
||||
allowTransparency: boolean;
|
||||
allowPayment: boolean;
|
||||
allowAutoPlay: boolean;
|
||||
allowMicrophone: boolean;
|
||||
allowCamera: boolean;
|
||||
allowGeolocation: boolean;
|
||||
}
|
||||
>;
|
||||
@@ -1,81 +0,0 @@
|
||||
import { objectEntries } from "@homarr/common";
|
||||
import type { Inverse } from "@homarr/common/types";
|
||||
import type { WidgetKind } from "@homarr/definitions";
|
||||
|
||||
import type { OldmarrBookmarkDefinition } from "./bookmark";
|
||||
import type { OldmarrCalendarDefinition } from "./calendar";
|
||||
import type { OldmarrDashdotDefinition } from "./dashdot";
|
||||
import type { OldmarrDateDefinition } from "./date";
|
||||
import type { OldmarrDlspeedDefinition } from "./dlspeed";
|
||||
import type { OldmarrDnsHoleControlsDefinition } from "./dns-hole-controls";
|
||||
import type { OldmarrDnsHoleSummaryDefinition } from "./dns-hole-summary";
|
||||
import type { OldmarrHealthMonitoringDefinition } from "./health-monitoring";
|
||||
import type { OldmarrIframeDefinition } from "./iframe";
|
||||
import type { OldmarrIndexerManagerDefinition } from "./indexer-manager";
|
||||
import type { OldmarrMediaRequestListDefinition } from "./media-requests-list";
|
||||
import type { OldmarrMediaRequestStatsDefinition } from "./media-requests-stats";
|
||||
import type { OldmarrMediaServerDefinition } from "./media-server";
|
||||
import type { OldmarrMediaTranscodingDefinition } from "./media-transcoding";
|
||||
import type { OldmarrNotebookDefinition } from "./notebook";
|
||||
import type { OldmarrRssDefinition } from "./rss";
|
||||
import type { OldmarrSmartHomeEntityStateDefinition } from "./smart-home-entity-state";
|
||||
import type { OldmarrSmartHomeTriggerAutomationDefinition } from "./smart-home-trigger-automation";
|
||||
import type { OldmarrTorrentStatusDefinition } from "./torrent-status";
|
||||
import type { OldmarrUsenetDefinition } from "./usenet";
|
||||
import type { OldmarrVideoStreamDefinition } from "./video-stream";
|
||||
import type { OldmarrWeatherDefinition } from "./weather";
|
||||
|
||||
export type OldmarrWidgetDefinitions =
|
||||
| OldmarrWeatherDefinition
|
||||
| OldmarrDateDefinition
|
||||
| OldmarrCalendarDefinition
|
||||
| OldmarrIndexerManagerDefinition
|
||||
| OldmarrDashdotDefinition
|
||||
| OldmarrUsenetDefinition
|
||||
| OldmarrTorrentStatusDefinition
|
||||
| OldmarrDlspeedDefinition
|
||||
| OldmarrRssDefinition
|
||||
| OldmarrVideoStreamDefinition
|
||||
| OldmarrIframeDefinition
|
||||
| OldmarrMediaServerDefinition
|
||||
| OldmarrMediaRequestListDefinition
|
||||
| OldmarrMediaRequestStatsDefinition
|
||||
| OldmarrDnsHoleSummaryDefinition
|
||||
| OldmarrDnsHoleControlsDefinition
|
||||
| OldmarrBookmarkDefinition
|
||||
| OldmarrNotebookDefinition
|
||||
| OldmarrSmartHomeEntityStateDefinition
|
||||
| OldmarrSmartHomeTriggerAutomationDefinition
|
||||
| OldmarrHealthMonitoringDefinition
|
||||
| OldmarrMediaTranscodingDefinition;
|
||||
|
||||
export const widgetKindMapping = {
|
||||
date: "clock",
|
||||
calendar: "calendar",
|
||||
"torrents-status": "downloads",
|
||||
weather: "weather",
|
||||
rss: "rssFeed",
|
||||
"video-stream": "video",
|
||||
iframe: "iframe",
|
||||
"media-server": "mediaServer",
|
||||
"dns-hole-summary": "dnsHoleSummary",
|
||||
"dns-hole-controls": "dnsHoleControls",
|
||||
notebook: "notebook",
|
||||
"smart-home/entity-state": "smartHome-entityState",
|
||||
"smart-home/trigger-automation": "smartHome-executeAutomation",
|
||||
"media-requests-list": "mediaRequests-requestList",
|
||||
"media-requests-stats": "mediaRequests-requestStats",
|
||||
"indexer-manager": "indexerManager",
|
||||
bookmark: "bookmarks",
|
||||
"health-monitoring": "healthMonitoring",
|
||||
dashdot: "healthMonitoring",
|
||||
"media-transcoding": "mediaTranscoding",
|
||||
dlspeed: null,
|
||||
usenet: "downloads",
|
||||
} satisfies Record<OldmarrWidgetDefinitions["id"], WidgetKind | null>;
|
||||
|
||||
export type WidgetMapping = typeof widgetKindMapping;
|
||||
export type InversedWidgetMapping = Inverse<Omit<typeof widgetKindMapping, "dlspeed">>;
|
||||
|
||||
export const mapKind = (kind: OldmarrWidgetDefinitions["id"]): keyof InversedWidgetMapping | null =>
|
||||
objectEntries(widgetKindMapping).find(([key]) => key === kind)?.[1] ?? null;
|
||||
Loaded 100 of 249 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user