Merge branch 'dev' into add-more-openapi

This commit is contained in:
Meier Lukas committed 2025-12-10 15:58:04 +01:00
commit df5704019b
309 files changed
+23031 -8513

No files matched your search

+3 -3
View File
@@ -26,13 +26,13 @@
"@homarr/log": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0",
"@umami/node": "^0.4.0",
"superjson": "2.2.2"
"superjson": "2.2.6"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+16 -15
View File
@@ -40,27 +40,28 @@
"@homarr/redis": "workspace:^0.1.0",
"@homarr/request-handler": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@kubernetes/client-node": "^1.3.0",
"@tanstack/react-query": "^5.87.1",
"@trpc/client": "^11.5.1",
"@trpc/react-query": "^11.5.1",
"@trpc/server": "^11.5.1",
"@trpc/tanstack-react-query": "^11.5.1",
"@kubernetes/client-node": "^1.4.0",
"@tanstack/react-query": "^5.90.12",
"@trpc/client": "^11.7.2",
"@trpc/react-query": "^11.7.2",
"@trpc/server": "^11.7.2",
"@trpc/tanstack-react-query": "^11.7.2",
"lodash.clonedeep": "^4.5.0",
"next": "15.5.2",
"react": "19.1.1",
"react-dom": "19.1.1",
"superjson": "2.2.2",
"trpc-to-openapi": "^3.0.1",
"zod": "^4.1.5"
"next": "16.0.7",
"react": "19.2.1",
"react-dom": "19.2.1",
"superjson": "2.2.6",
"trpc-to-openapi": "^3.1.0",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"prettier": "^3.6.2",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"prettier": "^3.7.4",
"typescript": "^5.9.3"
}
}
@@ -32,6 +32,7 @@ export const createOneIntegrationMiddleware = <TKind extends IntegrationKind>(
const integration = await ctx.db.query.integrations.findFirst({
where: and(eq(integrations.id, input.integrationId), inArray(integrations.kind, kinds)),
with: {
app: true,
secrets: true,
groupPermissions: true,
userPermissions: true,
@@ -65,6 +66,7 @@ export const createOneIntegrationMiddleware = <TKind extends IntegrationKind>(
ctx: {
integration: {
...rest,
externalUrl: rest.app?.href ?? null,
kind: kind as TKind,
decryptedSecrets: secrets.map((secret) => ({
...secret,
@@ -96,6 +98,7 @@ export const createManyIntegrationMiddleware = <TKind extends IntegrationKind>(
? await ctx.db.query.integrations.findMany({
where: and(inArray(integrations.id, input.integrationIds), inArray(integrations.kind, kinds)),
with: {
app: true,
secrets: true,
items: {
with: {
@@ -125,6 +128,7 @@ export const createManyIntegrationMiddleware = <TKind extends IntegrationKind>(
integrations: dbIntegrations.map(
({ secrets, kind, items: _ignore1, groupPermissions: _ignore2, userPermissions: _ignore3, ...rest }) => ({
...rest,
externalUrl: rest.app?.href ?? null,
kind: kind as TKind,
decryptedSecrets: secrets.map((secret) => ({
...secret,
+6 -4
View File
@@ -118,20 +118,22 @@ export const appRouter = createTRPCRouter({
create: permissionRequiredProcedure
.requiresPermission("app-create")
.input(appManageSchema)
.output(z.object({ appId: z.string() }))
.output(z.object({ appId: z.string() }).and(selectAppSchema))
.meta({ openapi: { method: "POST", path: "/api/apps", tags: ["apps"], protect: true } })
.mutation(async ({ ctx, input }) => {
const id = createId();
await ctx.db.insert(apps).values({
const insertValues = {
id,
name: input.name,
description: input.description,
iconUrl: input.iconUrl,
href: input.href,
pingUrl: input.pingUrl === "" ? null : input.pingUrl,
});
};
await ctx.db.insert(apps).values(insertValues);
return { appId: id };
// TODO: breaking change necessary for removing appId property
return { appId: id, ...insertValues };
}),
createMany: permissionRequiredProcedure
.requiresPermission("app-create")
+136 -20
View File
@@ -1,31 +1,147 @@
import type { AnySQLiteTable } from "drizzle-orm/sqlite-core";
import { isProviderEnabled } from "@homarr/auth/server";
import type { Database } from "@homarr/db";
import { apps, boards, groups, integrations, invites, users } from "@homarr/db/schema";
import { db, eq, inArray, or } from "@homarr/db";
import {
apps,
boards,
boardUserPermissions,
groupMembers,
groups,
integrations,
invites,
medias,
searchEngines,
users,
} from "@homarr/db/schema";
import type { TranslationObject } from "@homarr/translation";
import { createTRPCRouter, publicProcedure } from "../trpc";
interface HomeStatistic {
titleKey: keyof TranslationObject["management"]["page"]["home"]["statistic"];
subtitleKey: keyof TranslationObject["management"]["page"]["home"]["statisticLabel"];
count: number;
path: string;
}
export const homeRouter = createTRPCRouter({
getStats: publicProcedure.query(async ({ ctx }) => {
const isAdmin = ctx.session?.user.permissions.includes("admin") ?? false;
const isCredentialsEnabled = isProviderEnabled("credentials");
return {
countBoards: await getCountForTableAsync(ctx.db, boards, true),
countUsers: await getCountForTableAsync(ctx.db, users, isAdmin),
countGroups: await getCountForTableAsync(ctx.db, groups, true),
countInvites: await getCountForTableAsync(ctx.db, invites, isAdmin),
countIntegrations: await getCountForTableAsync(ctx.db, integrations, isCredentialsEnabled && isAdmin),
countApps: await getCountForTableAsync(ctx.db, apps, true),
};
const statistics: HomeStatistic[] = [];
const boardIds: string[] = [];
if (ctx.session?.user && !ctx.session.user.permissions.includes("board-view-all")) {
const permissionsOfCurrentUserWhenPresent = await ctx.db.query.boardUserPermissions.findMany({
where: eq(boardUserPermissions.userId, ctx.session.user.id),
});
const permissionsOfCurrentUserGroupsWhenPresent = await ctx.db.query.groupMembers.findMany({
where: eq(groupMembers.userId, ctx.session.user.id),
with: {
group: {
with: {
boardPermissions: {},
},
},
},
});
boardIds.push(
...permissionsOfCurrentUserWhenPresent
.map((permission) => permission.boardId)
.concat(
permissionsOfCurrentUserGroupsWhenPresent
.map((groupMember) => groupMember.group.boardPermissions.map((permission) => permission.boardId))
.flat(),
),
);
}
statistics.push({
titleKey: "board",
subtitleKey: "boards",
count: await db.$count(
boards,
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,
),
),
path: "/manage/boards",
});
if (isAdmin) {
statistics.push({
titleKey: "user",
subtitleKey: "authentication",
count: await db.$count(users),
path: "/manage/users",
});
}
if (isAdmin && isCredentialsEnabled) {
statistics.push({
titleKey: "invite",
subtitleKey: "authentication",
count: await db.$count(invites),
path: "/manage/users/invites",
});
}
if (ctx.session?.user.permissions.includes("integration-create")) {
statistics.push({
titleKey: "integration",
subtitleKey: "resources",
count: await db.$count(integrations),
path: "/manage/integrations",
});
}
if (ctx.session?.user) {
statistics.push({
titleKey: "app",
subtitleKey: "resources",
count: await db.$count(apps),
path: "/manage/apps",
});
}
if (isAdmin) {
statistics.push({
titleKey: "group",
subtitleKey: "authorization",
count: await db.$count(groups),
path: "/manage/users/groups",
});
}
if (ctx.session?.user.permissions.includes("search-engine-create")) {
statistics.push({
titleKey: "searchEngine",
subtitleKey: "resources",
count: await db.$count(searchEngines),
path: "/manage/search-engines",
});
}
if (ctx.session?.user.permissions.includes("media-upload")) {
statistics.push({
titleKey: "media",
subtitleKey: "resources",
count: await db.$count(
medias,
ctx.session.user.permissions.includes("media-view-all")
? undefined
: eq(medias.creatorId, ctx.session.user.id),
),
path: "/manage/medias",
});
}
return statistics;
}),
});
const getCountForTableAsync = async (db: Database, table: AnySQLiteTable, canView: boolean) => {
if (!canView) {
return 0;
}
return await db.$count(table);
};
@@ -4,8 +4,9 @@ import { z } from "zod/v4";
import { createId, objectEntries } from "@homarr/common";
import { decryptSecret, encryptSecret } from "@homarr/common/server";
import type { Database } from "@homarr/db";
import { and, asc, eq, handleTransactionsAsync, inArray, like } from "@homarr/db";
import { and, asc, eq, handleTransactionsAsync, inArray, like, or } from "@homarr/db";
import {
apps,
groupMembers,
groupPermissions,
integrationGroupPermissions,
@@ -212,6 +213,14 @@ export const integrationRouter = createTRPCRouter({
updatedAt: true,
},
},
app: {
columns: {
id: true,
name: true,
iconUrl: true,
href: true,
},
},
},
});
@@ -233,6 +242,7 @@ export const integrationRouter = createTRPCRouter({
value: integrationSecretKindObject[secret.kind].isPublic ? decryptSecret(secret.value) : null,
updatedAt: secret.updatedAt,
})),
app: integration.app,
};
}),
create: permissionRequiredProcedure
@@ -245,6 +255,13 @@ export const integrationRouter = createTRPCRouter({
url: input.url,
});
if (input.app && "name" in input.app && !ctx.session.user.permissions.includes("app-create")) {
throw new TRPCError({
code: "FORBIDDEN",
message: "Permission denied",
});
}
const result = await testConnectionAsync({
id: "new",
name: input.name,
@@ -267,12 +284,15 @@ export const integrationRouter = createTRPCRouter({
};
}
const appId = await createAppIfNecessaryAsync(ctx.db, input.app);
const integrationId = createId();
await ctx.db.insert(integrations).values({
id: integrationId,
name: input.name,
url: input.url,
kind: input.kind,
appId,
});
if (input.secrets.length >= 1) {
@@ -358,6 +378,7 @@ export const integrationRouter = createTRPCRouter({
.set({
name: input.name,
url: input.url,
appId: input.appId,
})
.where(eq(integrations.id, input.id));
@@ -386,6 +407,21 @@ export const integrationRouter = createTRPCRouter({
}
}
const removedSecrets = integration.secrets.filter(
(dbSecret) => !input.secrets.some((secret) => dbSecret.kind === secret.kind),
);
if (removedSecrets.length >= 1) {
await ctx.db
.delete(integrationSecrets)
.where(
or(
...removedSecrets.map((secret) =>
and(eq(integrationSecrets.integrationId, input.id), eq(integrationSecrets.kind, secret.kind)),
),
),
);
}
logger.info("Updated integration", {
id: input.id,
name: input.name,
@@ -637,3 +673,30 @@ const addSecretAsync = async (db: Database, input: AddSecretInput) => {
integrationId: input.integrationId,
});
};
const createAppIfNecessaryAsync = async (db: Database, app: z.infer<typeof integrationCreateSchema>["app"]) => {
if (!app) return null;
if ("id" in app) return app.id;
logger.info("Creating app", {
name: app.name,
url: app.href,
});
const appId = createId();
await db.insert(apps).values({
id: appId,
name: app.name,
description: app.description,
iconUrl: app.iconUrl,
href: app.href,
pingUrl: app.pingUrl,
});
logger.info("Created app", {
id: appId,
name: app.name,
url: app.href,
});
return appId;
};
@@ -5,7 +5,7 @@ import { getAllSecretKindOptions } from "@homarr/definitions";
import { createIntegrationAsync } from "@homarr/integrations";
import { logger } from "@homarr/log";
type FormIntegration = Integration & {
type FormIntegration = Omit<Integration, "appId"> & {
secrets: {
kind: IntegrationSecretKind;
value: string | null;
@@ -75,6 +75,7 @@ export const testConnectionAsync = async (
const integrationInstance = await createIntegrationAsync({
...baseIntegration,
decryptedSecrets,
externalUrl: null,
});
const result = await integrationInstance.testConnectionAsync();
+34 -21
View File
@@ -55,34 +55,47 @@ export const mediaRouter = createTRPCRouter({
.requiresPermission("media-upload")
.input(mediaUploadSchema)
.mutation(async ({ ctx, input }) => {
const content = Buffer.from(await input.file.arrayBuffer());
const id = createId();
const media = {
id,
creatorId: ctx.session.user.id,
content,
size: input.file.size,
contentType: input.file.type,
name: input.file.name,
} satisfies InferInsertModel<typeof medias>;
await ctx.db.insert(medias).values(media);
const files = await Promise.all(
input.files.map(async (file) => ({
id: createId(),
meta: file,
content: Buffer.from(await file.arrayBuffer()),
})),
);
const insertMedias = files.map(
(file): InferInsertModel<typeof medias> => ({
id: file.id,
creatorId: ctx.session.user.id,
content: file.content,
size: file.meta.size,
contentType: file.meta.type,
name: file.meta.name,
}),
);
await ctx.db.insert(medias).values(insertMedias);
const localIconRepository = await ctx.db.query.iconRepositories.findFirst({
where: eq(iconRepositories.slug, LOCAL_ICON_REPOSITORY_SLUG),
});
if (!localIconRepository) return id;
const ids = files.map((file) => file.id);
if (!localIconRepository) return ids;
const icon = mapMediaToIcon(media);
await ctx.db.insert(icons).values({
id: createId(),
checksum: icon.checksum,
name: icon.fileNameWithExtension,
url: icon.imageUrl,
iconRepositoryId: localIconRepository.id,
});
await ctx.db.insert(icons).values(
insertMedias.map((media) => {
const icon = mapMediaToIcon(media);
return id;
return {
id: createId(),
checksum: icon.checksum,
name: icon.fileNameWithExtension,
url: icon.imageUrl,
iconRepositoryId: localIconRepository.id,
};
}),
);
return ids;
}),
deleteMedia: protectedProcedure.input(byIdSchema).mutation(async ({ ctx, input }) => {
const dbMedia = await ctx.db.query.medias.findFirst({
@@ -4,7 +4,7 @@ import { describe, expect, test, vi } from "vitest";
import type { Session } from "@homarr/auth";
import { createId } from "@homarr/common";
import { encryptSecret } from "@homarr/common/server";
import { integrations, integrationSecrets } from "@homarr/db/schema";
import { apps, integrations, integrationSecrets } from "@homarr/db/schema";
import { createDb } from "@homarr/db/test";
import type { GroupPermissionKey } from "@homarr/definitions";
@@ -251,6 +251,102 @@ describe("create should create a new integration", () => {
);
});
test("with create integration access should create a new integration with new linked app", async () => {
const db = createDb();
const caller = integrationRouter.createCaller({
db,
deviceType: undefined,
session: defaultSessionWithPermissions(["integration-create", "app-create"]),
});
const input = {
name: "Jellyfin",
kind: "jellyfin" as const,
url: "http://jellyfin.local",
secrets: [{ kind: "apiKey" as const, value: "1234567890" }],
attemptSearchEngineCreation: false,
app: {
name: "Jellyfin",
description: null,
pingUrl: "http://jellyfin.local",
href: "https://jellyfin.home",
iconUrl: "logo.png",
},
};
const fakeNow = new Date("2023-07-01T00:00:00Z");
vi.useFakeTimers();
vi.setSystemTime(fakeNow);
await caller.create(input);
vi.useRealTimers();
const dbIntegration = await db.query.integrations.findFirst({
with: {
app: true,
},
});
const dbSecret = await db.query.integrationSecrets.findFirst();
expect(dbIntegration).toBeDefined();
expect(dbIntegration!.name).toBe(input.name);
expect(dbIntegration!.kind).toBe(input.kind);
expect(dbIntegration!.url).toBe(input.url);
expect(dbIntegration!.app!.name).toBe(input.app.name);
expect(dbIntegration!.app!.pingUrl).toBe(input.app.pingUrl);
expect(dbIntegration!.app!.href).toBe(input.app.href);
expect(dbIntegration!.app!.iconUrl).toBe(input.app.iconUrl);
expect(dbSecret!.integrationId).toBe(dbIntegration!.id);
expect(dbSecret).toBeDefined();
expect(dbSecret!.kind).toBe(input.secrets[0]!.kind);
expect(dbSecret!.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(dbSecret!.updatedAt).toEqual(fakeNow);
});
test("with create integration access should create a new integration with existing linked app", async () => {
const db = createDb();
const appId = createId();
await db.insert(apps).values({
id: appId,
name: "Existing Jellyfin",
iconUrl: "logo.png",
});
const caller = integrationRouter.createCaller({
db,
deviceType: undefined,
session: defaultSessionWithPermissions(["integration-create"]),
});
const input = {
name: "Jellyfin",
kind: "jellyfin" as const,
url: "http://jellyfin.local",
secrets: [{ kind: "apiKey" as const, value: "1234567890" }],
attemptSearchEngineCreation: false,
app: {
id: appId,
},
};
const fakeNow = new Date("2023-07-01T00:00:00Z");
vi.useFakeTimers();
vi.setSystemTime(fakeNow);
await caller.create(input);
vi.useRealTimers();
const dbIntegration = await db.query.integrations.findFirst();
const dbSecret = await db.query.integrationSecrets.findFirst();
expect(dbIntegration).toBeDefined();
expect(dbIntegration!.name).toBe(input.name);
expect(dbIntegration!.kind).toBe(input.kind);
expect(dbIntegration!.url).toBe(input.url);
expect(dbIntegration!.appId).toBe(appId);
expect(dbSecret!.integrationId).toBe(dbIntegration!.id);
expect(dbSecret).toBeDefined();
expect(dbSecret!.kind).toBe(input.secrets[0]!.kind);
expect(dbSecret!.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(dbSecret!.updatedAt).toEqual(fakeNow);
});
test("without create integration access should throw permission error", async () => {
// Arrange
const db = createDb();
@@ -273,6 +369,36 @@ describe("create should create a new integration", () => {
// Assert
await expect(actAsync()).rejects.toThrow("Permission denied");
});
test("without create app access should throw permission error with new linked app", async () => {
// Arrange
const db = createDb();
const caller = integrationRouter.createCaller({
db,
deviceType: undefined,
session: defaultSessionWithPermissions(["integration-create"]),
});
const input = {
name: "Jellyfin",
kind: "jellyfin" as const,
url: "http://jellyfin.local",
secrets: [{ kind: "apiKey" as const, value: "1234567890" }],
attemptSearchEngineCreation: false,
app: {
name: "Jellyfin",
description: null,
href: "https://jellyfin.home",
iconUrl: "logo.png",
pingUrl: null,
},
};
// Act
const actAsync = async () => await caller.create(input);
// Assert
await expect(actAsync()).rejects.toThrow("Permission denied");
});
});
describe("update should update an integration", () => {
@@ -285,6 +411,7 @@ describe("update should update an integration", () => {
});
const lastWeek = new Date("2023-06-24T00:00:00Z");
const appId = createId();
const integrationId = createId();
const toInsert = {
id: integrationId,
@@ -293,6 +420,11 @@ describe("update should update an integration", () => {
url: "http://hole.local",
};
await db.insert(apps).values({
id: appId,
name: "Previous",
iconUrl: "logo.png",
});
await db.insert(integrations).values(toInsert);
const usernameToInsert = {
@@ -320,6 +452,7 @@ describe("update should update an integration", () => {
{ kind: "password" as const, value: null },
{ kind: "apiKey" as const, value: "1234567890" },
],
appId,
};
const fakeNow = new Date("2023-07-01T00:00:00Z");
@@ -335,6 +468,7 @@ describe("update should update an integration", () => {
expect(dbIntegration!.name).toBe(input.name);
expect(dbIntegration!.kind).toBe(input.kind);
expect(dbIntegration!.url).toBe(input.url);
expect(dbIntegration!.appId).toBe(appId);
expect(dbSecrets.length).toBe(3);
const username = expectToBeDefined(dbSecrets.find((secret) => secret.kind === "username"));
@@ -365,6 +499,7 @@ describe("update should update an integration", () => {
name: "Pi Hole",
url: "http://hole.local",
secrets: [],
appId: null,
});
await expect(actAsync()).rejects.toThrow("Integration not found");
});
@@ -385,6 +520,7 @@ describe("update should update an integration", () => {
name: "Pi Hole",
url: "http://hole.local",
secrets: [],
appId: null,
});
// Assert
@@ -55,6 +55,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "secret",
}),
],
externalUrl: null,
});
});
@@ -104,6 +105,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "dbSecret",
}),
],
externalUrl: null,
});
});
@@ -153,6 +155,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "secret",
}),
],
externalUrl: null,
});
});
@@ -206,6 +209,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "secret",
}),
],
externalUrl: null,
});
});
@@ -263,6 +267,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "dbPassword",
}),
],
externalUrl: null,
});
});
@@ -336,6 +341,7 @@ describe("testConnectionAsync should run test connection of integration", () =>
value: "privateKey",
}),
],
externalUrl: null,
});
});
});
+1 -9
View File
@@ -114,11 +114,10 @@ export const userRouter = createTRPCRouter({
.input(
z.object({
userId: z.string(),
// Max image size of 256KB, only png and jpeg are allowed
image: z
.string()
.regex(/^data:image\/(png|jpeg|gif|webp);base64,[A-Za-z0-9/+]+=*$/g)
.max(262144)
.max(350000) // approximately 256KB in base64 (256 * 1024 * 4 / 3 + prefixes)
.nullable(),
}),
)
@@ -147,13 +146,6 @@ export const userRouter = createTRPCRouter({
});
}
if (user.provider !== "credentials") {
throw new TRPCError({
code: "FORBIDDEN",
message: "Profile image can not be changed for users with external providers",
});
}
await ctx.db
.update(users)
.set({
+51 -4
View File
@@ -1,6 +1,11 @@
import { observable } from "@trpc/server/observable";
import { z } from "zod/v4";
import type { Modify } from "@homarr/common/types";
import type { Integration } from "@homarr/db/schema";
import type { IntegrationKindByCategory } from "@homarr/definitions";
import { getIntegrationKindsByCategory } from "@homarr/definitions";
import type { CalendarEvent } from "@homarr/integrations/types";
import { radarrReleaseTypes } from "@homarr/integrations/types";
import { calendarMonthRequestHandler } from "@homarr/request-handler/calendar";
@@ -19,14 +24,56 @@ export const calendarRouter = createTRPCRouter({
)
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("calendar")))
.query(async ({ ctx, input }) => {
const results = await Promise.all(
return await Promise.all(
ctx.integrations.map(async (integration) => {
const innerHandler = calendarMonthRequestHandler.handler(integration, input);
const { integrationIds: _integrationIds, ...handlerInput } = input;
const innerHandler = calendarMonthRequestHandler.handler(integration, handlerInput);
const { data } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
return data;
return {
events: data,
integration: {
id: integration.id,
name: integration.name,
kind: integration.kind,
},
};
}),
);
return results.flat();
}),
subscribeToEvents: publicProcedure
.input(
z.object({
year: z.number(),
month: z.number(),
releaseType: z.array(z.enum(radarrReleaseTypes)),
showUnmonitored: z.boolean(),
}),
)
.concat(createManyIntegrationMiddleware("query", ...getIntegrationKindsByCategory("calendar")))
.subscription(({ ctx, input }) => {
return observable<{
integration: Modify<Integration, { kind: IntegrationKindByCategory<"calendar"> }>;
events: CalendarEvent[];
}>((emit) => {
const unsubscribes: (() => void)[] = [];
for (const integrationWithSecrets of ctx.integrations) {
const { decryptedSecrets: _, ...integration } = integrationWithSecrets;
const { integrationIds: _integrationIds, ...handlerInput } = input;
const innerHandler = calendarMonthRequestHandler.handler(integrationWithSecrets, handlerInput);
const unsubscribe = innerHandler.subscribe((events) => {
emit.next({
integration,
events,
});
});
unsubscribes.push(unsubscribe);
}
return () => {
unsubscribes.forEach((unsubscribe) => {
unsubscribe();
});
};
});
}),
});
@@ -3,6 +3,7 @@ import { z } from "zod/v4";
import { getIntegrationKindsByCategory } from "@homarr/definitions";
import { createIntegrationAsync } from "@homarr/integrations";
import { mediaRequestStatusConfiguration } from "@homarr/integrations/types";
import type { MediaRequest } from "@homarr/integrations/types";
import { mediaRequestListRequestHandler } from "@homarr/request-handler/media-request-list";
import { mediaRequestStatsRequestHandler } from "@homarr/request-handler/media-request-stats";
@@ -35,7 +36,10 @@ export const mediaRequestsRouter = createTRPCRouter({
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
}
return dataA.status - dataB.status;
return (
mediaRequestStatusConfiguration[dataA.status].position -
mediaRequestStatusConfiguration[dataB.status].position
);
});
}),
subscribeToLatestRequests: publicProcedure
@@ -1,4 +1,7 @@
import { observable } from "@trpc/server/observable";
import { getIntegrationKindsByCategory } from "@homarr/definitions";
import type { MediaTranscoding } from "@homarr/request-handler/media-transcoding";
import { mediaTranscodingRequestHandler } from "@homarr/request-handler/media-transcoding";
import { paginatedSchema } from "@homarr/validation/common";
@@ -15,7 +18,7 @@ export const mediaTranscodingRouter = createTRPCRouter({
.input(paginatedSchema.pick({ page: true, pageSize: true }))
.query(async ({ ctx, input }) => {
const innerHandler = mediaTranscodingRequestHandler.handler(ctx.integration, {
pageOffset: input.page,
pageOffset: (input.page - 1) * input.pageSize,
pageSize: input.pageSize,
});
const { data } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
@@ -25,4 +28,19 @@ export const mediaTranscodingRouter = createTRPCRouter({
data,
};
}),
subscribeData: publicProcedure
.concat(createIndexerManagerIntegrationMiddleware("query"))
.input(paginatedSchema.pick({ page: true, pageSize: true }))
.subscription(({ ctx, input }) => {
return observable<{ integrationId: string; data: MediaTranscoding }>((emit) => {
const innerHandler = mediaTranscodingRequestHandler.handler(ctx.integration, {
pageOffset: (input.page - 1) * input.pageSize,
pageSize: input.pageSize,
});
const unsubscribe = innerHandler.subscribe((data) => {
emit.next({ integrationId: input.integrationId, data });
});
return unsubscribe;
});
}),
});
+15 -8
View File
@@ -40,15 +40,22 @@ export const releasesRouter = createTRPCRouter({
.query(async ({ ctx, input }) => {
return await Promise.all(
input.repositories.map(async (repository) => {
const innerHandler = releasesRequestHandler.handler(ctx.integration, {
id: repository.id,
identifier: repository.identifier,
versionRegex: formatVersionFilterRegex(repository.versionFilter),
});
const response = await releasesRequestHandler
.handler(ctx.integration, {
id: repository.id,
identifier: repository.identifier,
versionRegex: formatVersionFilterRegex(repository.versionFilter),
})
.getCachedOrUpdatedDataAsync({
forceUpdate: false,
});
return await innerHandler.getCachedOrUpdatedDataAsync({
forceUpdate: false,
});
return {
id: repository.id,
integration: { name: ctx.integration.name, kind: ctx.integration.kind },
timestamp: response.timestamp,
...response.data,
};
}),
);
}),
+15 -39
View File
@@ -1,6 +1,8 @@
import { observable } from "@trpc/server/observable";
import { z } from "zod/v4";
import { fetchWithTimeout } from "@homarr/common";
import type { Weather } from "@homarr/request-handler/weather";
import { weatherRequestHandler } from "@homarr/request-handler/weather";
import { createTRPCRouter, publicProcedure } from "../../trpc";
@@ -9,45 +11,19 @@ const atLocationInput = z.object({
latitude: z.number(),
});
const atLocationOutput = z.object({
current_weather: z.object({
weathercode: z.number(),
temperature: z.number(),
windspeed: z.number(),
}),
daily: z.object({
time: z.array(z.string()),
weathercode: z.array(z.number()),
temperature_2m_max: z.array(z.number()),
temperature_2m_min: z.array(z.number()),
sunrise: z.array(z.string()),
sunset: z.array(z.string()),
wind_speed_10m_max: z.array(z.number()),
wind_gusts_10m_max: z.array(z.number()),
}),
});
export const weatherRouter = createTRPCRouter({
atLocation: publicProcedure.input(atLocationInput).query(async ({ input }) => {
const res = await fetchWithTimeout(
`https://api.open-meteo.com/v1/forecast?latitude=${input.latitude}&longitude=${input.longitude}&daily=weathercode,temperature_2m_max,temperature_2m_min,sunrise,sunset,wind_speed_10m_max,wind_gusts_10m_max&current_weather=true&timezone=auto`,
);
const json: unknown = await res.json();
const weather = await atLocationOutput.parseAsync(json);
return {
current: weather.current_weather,
daily: weather.daily.time.map((value, index) => {
return {
time: value,
weatherCode: weather.daily.weathercode[index] ?? 404,
maxTemp: weather.daily.temperature_2m_max[index],
minTemp: weather.daily.temperature_2m_min[index],
sunrise: weather.daily.sunrise[index],
sunset: weather.daily.sunset[index],
maxWindSpeed: weather.daily.wind_speed_10m_max[index],
maxWindGusts: weather.daily.wind_gusts_10m_max[index],
};
}),
};
const handler = weatherRequestHandler.handler(input);
return await handler.getCachedOrUpdatedDataAsync({ forceUpdate: false }).then((result) => result.data);
}),
subscribeAtLocation: publicProcedure.input(atLocationInput).subscription(({ input }) => {
return observable<Weather>((emit) => {
const handler = weatherRequestHandler.handler(input);
const unsubscribe = handler.subscribe((data) => {
emit.next(data);
});
return unsubscribe;
});
}),
});
+10
View File
@@ -20,6 +20,7 @@ export const createSignInEventHandler = (db: Database): Exclude<NextAuthConfig["
where: eq(users.id, user.id),
columns: {
name: true,
image: true,
colorScheme: true,
},
});
@@ -59,6 +60,15 @@ export const createSignInEventHandler = (db: Database): Exclude<NextAuthConfig["
`Username for user of oidc provider has changed. user=${user.id} old='${dbUser.name}' new='${profileUsername}'`,
);
}
if (
typeof profile.picture === "string" &&
dbUser.image !== profile.picture &&
!dbUser.image?.startsWith("data:")
) {
await db.update(users).set({ image: profile.picture }).where(eq(users.id, user.id));
logger.info(`Profile picture for user of oidc provider has changed. user=${user.id}'`);
}
}
logger.info(`User '${dbUser.name}' logged in at ${dayjs().format()}`);
+12 -12
View File
@@ -23,8 +23,8 @@
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@auth/core": "^0.40.0",
"@auth/drizzle-adapter": "^1.10.0",
"@auth/core": "^0.41.1",
"@auth/drizzle-adapter": "^1.11.1",
"@homarr/certificates": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
@@ -34,21 +34,21 @@
"@homarr/validation": "workspace:^0.1.0",
"bcrypt": "^6.0.0",
"cookies": "^0.9.1",
"ldapts": "8.0.9",
"next": "15.5.2",
"next-auth": "5.0.0-beta.29",
"react": "19.1.1",
"react-dom": "19.1.1",
"zod": "^4.1.5"
"ldapts": "8.0.12",
"next": "16.0.7",
"next-auth": "5.0.0-beta.30",
"react": "19.2.1",
"react-dom": "19.2.1",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/bcrypt": "6.0.0",
"@types/cookies": "0.9.1",
"eslint": "^9.35.0",
"prettier": "^3.6.2",
"typescript": "^5.9.2"
"@types/cookies": "0.9.2",
"eslint": "^9.39.1",
"prettier": "^3.7.4",
"typescript": "^5.9.3"
}
}
@@ -6,14 +6,14 @@ import type { Database, InferInsertModel } from "@homarr/db";
import { and, eq } from "@homarr/db";
import { users } from "@homarr/db/schema";
import { logger } from "@homarr/log";
import type { userSignInSchema } from "@homarr/validation/user";
import type { ldapSignInSchema } from "@homarr/validation/user";
import { env } from "../../../env";
import { LdapClient } from "../ldap-client";
export const authorizeWithLdapCredentialsAsync = async (
db: Database,
credentials: z.infer<typeof userSignInSchema>,
credentials: z.infer<typeof ldapSignInSchema>,
) => {
logger.info(`user ${credentials.name} is trying to log in using LDAP. Connecting to LDAP server...`);
const client = new LdapClient();
@@ -38,7 +38,14 @@ export const authorizeWithLdapCredentialsAsync = async (
attributes: [env.AUTH_LDAP_USERNAME_ATTRIBUTE, env.AUTH_LDAP_USER_MAIL_ATTRIBUTE],
},
})
.then((entries) => entries.at(0));
.then((entries) => {
if (entries.length > 1) {
logger.warn(`Multiple LDAP users found for ${credentials.name}, expected only one.`);
throw new CredentialsSignin();
}
return entries.at(0);
});
if (!ldapUser) {
logger.warn(`User ${credentials.name} not found in LDAP`);
@@ -1,7 +1,7 @@
import type Credentials from "@auth/core/providers/credentials";
import type { Database } from "@homarr/db";
import { userSignInSchema } from "@homarr/validation/user";
import { ldapSignInSchema, userSignInSchema } from "@homarr/validation/user";
import { authorizeWithBasicCredentialsAsync } from "./authorization/basic-authorization";
import { authorizeWithLdapCredentialsAsync } from "./authorization/ldap-authorization";
@@ -28,7 +28,7 @@ export const createLdapConfiguration = (db: Database) =>
name: "Ldap",
// eslint-disable-next-line no-restricted-syntax
async authorize(credentials) {
const data = await userSignInSchema.parseAsync(credentials);
const data = await ldapSignInSchema.parseAsync(credentials);
return await authorizeWithLdapCredentialsAsync(db, data).catch(() => null);
},
}) satisfies CredentialsConfiguration;
@@ -61,6 +61,7 @@ export const OidcProvider = (headers: ReadonlyHeaders | null): OIDCConfig<Profil
id: profile.sub,
name,
email: profile.email,
image: typeof profile.picture === "string" ? profile.picture : null,
provider: "oidc",
};
},
@@ -23,12 +23,11 @@ describe("authorizeWithLdapCredentials", () => {
test("should fail when wrong ldap base credentials", async () => {
// Arrange
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.reject(new Error("bindAsync"))),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.reject(new Error("bindAsync"))),
} as unknown as ldapClient.LdapClient;
});
// Act
const act = () =>
@@ -44,13 +43,12 @@ describe("authorizeWithLdapCredentials", () => {
test("should fail when user not found", async () => {
// Arrange
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() => Promise.resolve([])),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() => Promise.resolve([])),
} as unknown as ldapClient.LdapClient;
});
// Act
const act = () =>
@@ -66,20 +64,19 @@ describe("authorizeWithLdapCredentials", () => {
test("should fail when user has invalid email", async () => {
// Arrange
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test",
},
]),
),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test",
},
]),
),
} as unknown as ldapClient.LdapClient;
});
// Act
const act = () =>
@@ -103,15 +100,14 @@ describe("authorizeWithLdapCredentials", () => {
]),
);
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn((props: ldapClient.BindOptions) =>
props.distinguishedName === "test" ? Promise.reject(new Error("bindAsync")) : Promise.resolve(),
),
searchAsync: searchSpy,
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn((props: ldapClient.BindOptions) =>
props.distinguishedName === "test" ? Promise.reject(new Error("bindAsync")) : Promise.resolve(),
),
searchAsync: searchSpy,
} as unknown as ldapClient.LdapClient;
});
// Act
const act = () =>
@@ -129,21 +125,20 @@ describe("authorizeWithLdapCredentials", () => {
// Arrange
const db = createDb();
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
} as unknown as ldapClient.LdapClient;
});
// Act
const result = await authorizeWithLdapCredentialsAsync(db, {
@@ -168,21 +163,20 @@ describe("authorizeWithLdapCredentials", () => {
// Arrange
const db = createDb();
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
} as unknown as ldapClient.LdapClient;
});
await db.insert(users).values({
id: createId(),
name: "test",
@@ -220,21 +214,20 @@ describe("authorizeWithLdapCredentials", () => {
test("should authorize user with correct credentials and return updated name", async () => {
// Arrange
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test55",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn(() =>
Promise.resolve([
{
dn: "test55",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
} as unknown as ldapClient.LdapClient;
});
const userId = createId();
const db = createDb();
@@ -268,27 +261,26 @@ describe("authorizeWithLdapCredentials", () => {
test("should authorize user with correct credentials and return his groups", async () => {
// Arrange
const spy = vi.spyOn(ldapClient, "LdapClient");
spy.mockImplementation(
() =>
({
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn((argument: { options: { filter: string } }) =>
argument.options.filter.includes("group")
? Promise.resolve([
{
cn: "homarr_example",
},
])
: Promise.resolve([
{
dn: "test55",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
}) as unknown as ldapClient.LdapClient,
);
spy.mockImplementation(function () {
return {
bindAsync: vi.fn(() => Promise.resolve()),
searchAsync: vi.fn((argument: { options: { filter: string } }) =>
argument.options.filter.includes("group")
? Promise.resolve([
{
cn: "homarr_example",
},
])
: Promise.resolve([
{
dn: "test55",
mail: "test@gmail.com",
},
]),
),
disconnectAsync: vi.fn(),
} as unknown as ldapClient.LdapClient;
});
const db = createDb();
const userId = createId();
await db.insert(users).values({
+4 -4
View File
@@ -25,14 +25,14 @@
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/api": "workspace:^0.1.0",
"react": "19.1.1",
"react-dom": "19.1.1"
"react": "19.2.1",
"react-dom": "19.2.1"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+3 -3
View File
@@ -24,13 +24,13 @@
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"undici": "7.15.0"
"undici": "7.16.0"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+4 -4
View File
@@ -28,14 +28,14 @@
"@homarr/common": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"dotenv": "^17.2.2"
"dotenv": "^17.2.3"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"esbuild": "^0.25.9",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"esbuild": "^0.27.1",
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+12 -12
View File
@@ -29,22 +29,22 @@
"dependencies": {
"@homarr/core": "workspace:^0.1.0",
"@homarr/log": "workspace:^0.1.0",
"@paralleldrive/cuid2": "^2.2.2",
"dayjs": "^1.11.18",
"dns-caching": "^0.2.5",
"next": "15.5.2",
"octokit": "^5.0.3",
"react": "19.1.1",
"react-dom": "19.1.1",
"undici": "7.15.0",
"zod": "^4.1.5",
"zod-validation-error": "^4.0.1"
"@paralleldrive/cuid2": "^3.1.0",
"dayjs": "^1.11.19",
"dns-caching": "^0.2.7",
"next": "16.0.7",
"octokit": "^5.0.5",
"react": "19.2.1",
"react-dom": "19.2.1",
"undici": "7.16.0",
"zod": "^4.1.13",
"zod-validation-error": "^5.0.0"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+5 -1
View File
@@ -12,7 +12,11 @@ export class LoggingAgent extends Agent {
}
dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandler): boolean {
const url = new URL(`${options.origin as string}${options.path}`);
const path = options.path
.split("/")
.map((segment) => (segment.length >= 32 && !segment.startsWith("?") ? "REDACTED" : segment))
.join("/");
const url = new URL(`${options.origin as string}${path}`);
// The below code should prevent sensitive data from being logged as
// some integrations use query parameters for auth
+6 -2
View File
@@ -11,13 +11,17 @@ const calculateTimeAgo = (timestamp: Date) => {
};
export const useTimeAgo = (timestamp: Date, updateFrequency = 1000) => {
const [timeAgo, setTimeAgo] = useState(calculateTimeAgo(timestamp));
const [timeAgo, setTimeAgo] = useState(() => calculateTimeAgo(timestamp));
useEffect(() => {
setTimeAgo(calculateTimeAgo(timestamp));
}, [timestamp]);
useEffect(() => {
const intervalId = setInterval(() => setTimeAgo(calculateTimeAgo(timestamp)), updateFrequency);
return () => clearInterval(intervalId); // clear interval on hook unmount
}, [timestamp]);
}, [timestamp, updateFrequency]);
return timeAgo;
};
+5
View File
@@ -47,3 +47,8 @@ export const humanFileSize = (size: number, concat = ""): string => {
}
return "∞";
};
const IMPERIAL_MULTIPLIER = 1.609344;
export const metricToImperial = (metricValue: number) => metricValue / IMPERIAL_MULTIPLIER;
export const imperialToMetric = (imperialValue: number) => imperialValue * IMPERIAL_MULTIPLIER;
@@ -66,6 +66,7 @@ describe("LoggingAgent should log all requests", () => {
["/?one=a1&two=b2&three=c3", `/?one=${REDACTED}&two=${REDACTED}&three=${REDACTED}`],
["/?numberWith13Chars=1234567890123", `/?numberWith13Chars=${REDACTED}`],
[`/?stringWith13Chars=${"a".repeat(13)}`, `/?stringWith13Chars=${REDACTED}`],
[`/${"a".repeat(32)}/?param=123`, `/${REDACTED}/?param=123`],
])("should redact sensitive data in url https://homarr.dev%s", (path, expected) => {
// Arrange
const infoLogSpy = vi.spyOn(logger, "debug");
+4 -4
View File
@@ -25,14 +25,14 @@
"prettier": "@homarr/prettier-config",
"dependencies": {
"@t3-oss/env-nextjs": "^0.13.8",
"ioredis": "5.7.0",
"zod": "^4.1.5"
"ioredis": "5.8.2",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
@@ -15,6 +15,7 @@ export const createRedisClient = () =>
...defaultRedisOptions,
host: redisEnv.HOST,
port: redisEnv.PORT,
db: redisEnv.DATABASE_INDEX,
tls: redisEnv.TLS_CA
? {
ca: redisEnv.TLS_CA,
@@ -12,6 +12,7 @@ export const redisEnv = createEnv({
TLS_CA: z.string().optional(),
USERNAME: z.string().optional(),
PASSWORD: z.string().optional(),
DATABASE_INDEX: z.coerce.number().optional(),
},
runtimeEnv: runtimeEnvWithPrefix("REDIS_"),
});
+9 -9
View File
@@ -29,21 +29,21 @@
"@homarr/core": "workspace:^0.1.0",
"@homarr/cron-jobs": "workspace:^0.1.0",
"@homarr/log": "workspace:^0.1.0",
"@tanstack/react-query": "^5.87.1",
"@trpc/client": "^11.5.1",
"@trpc/server": "^11.5.1",
"@trpc/tanstack-react-query": "^11.5.1",
"@tanstack/react-query": "^5.90.12",
"@trpc/client": "^11.7.2",
"@trpc/server": "^11.7.2",
"@trpc/tanstack-react-query": "^11.7.2",
"node-cron": "^4.2.1",
"react": "19.1.1",
"zod": "^4.1.5"
"react": "19.2.1",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/node-cron": "^3.0.11",
"@types/react": "19.1.12",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"@types/react": "19.2.7",
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+2 -2
View File
@@ -29,7 +29,7 @@
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+2 -2
View File
@@ -33,7 +33,7 @@
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/node-cron": "^3.0.11",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+2 -2
View File
@@ -44,7 +44,7 @@
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+2
View File
@@ -22,6 +22,7 @@ import { minecraftServerStatusJob } from "./jobs/minecraft-server-status";
import { pingJob } from "./jobs/ping";
import { rssFeedsJob } from "./jobs/rss-feeds";
import { updateCheckerJob } from "./jobs/update-checker";
import { weatherJob } from "./jobs/weather";
import { createCronJobGroup } from "./lib";
export const jobGroup = createCronJobGroup({
@@ -48,6 +49,7 @@ export const jobGroup = createCronJobGroup({
firewallVersion: firewallVersionJob,
firewallInterfaces: firewallInterfacesJob,
refreshNotifications: refreshNotificationsJob,
weather: weatherJob,
});
export type JobGroupKeys = ReturnType<(typeof jobGroup)["getKeys"]>[number];
+33
View File
@@ -0,0 +1,33 @@
import SuperJSON from "superjson";
import { EVERY_10_MINUTES } from "@homarr/cron-jobs-core/expressions";
import { db, eq } from "@homarr/db";
import { items } from "@homarr/db/schema";
import { logger } from "@homarr/log";
import { weatherRequestHandler } from "@homarr/request-handler/weather";
import type { WidgetComponentProps } from "../../../widgets";
import { createCronJob } from "../lib";
export const weatherJob = createCronJob("weather", EVERY_10_MINUTES).withCallback(async () => {
const weatherItems = await db.query.items.findMany({
where: eq(items.kind, "weather"),
});
const parsedItems = weatherItems.map((item) => ({
id: item.id,
options: SuperJSON.parse<WidgetComponentProps<"weather">["options"]>(item.options),
}));
for (const item of parsedItems) {
try {
const innerHandler = weatherRequestHandler.handler({
longitude: item.options.location.longitude,
latitude: item.options.location.latitude,
});
await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: true });
} catch (error) {
logger.error("Failed to update weather", { id: item.id, error });
}
}
});
@@ -0,0 +1,2 @@
ALTER TABLE `integration` ADD `app_id` varchar(128);--> statement-breakpoint
ALTER TABLE `integration` ADD CONSTRAINT `integration_app_id_app_id_fk` FOREIGN KEY (`app_id`) REFERENCES `app`(`id`) ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large. Load diff
@@ -253,6 +253,13 @@
"when": 1756701556908,
"tag": "0035_increase-secret-kind-length",
"breakpoints": true
},
{
"idx": 36,
"version": "5",
"when": 1760968518445,
"tag": "0036_add_app_reference_to_integration",
"breakpoints": true
}
]
}
@@ -0,0 +1,2 @@
ALTER TABLE "integration" ADD COLUMN "app_id" varchar(128);--> statement-breakpoint
ALTER TABLE "integration" ADD CONSTRAINT "integration_app_id_app_id_fk" FOREIGN KEY ("app_id") REFERENCES "public"."app"("id") ON DELETE set null ON UPDATE no action;
File diff suppressed because it is too large. Load diff
@@ -15,6 +15,13 @@
"when": 1756701573101,
"tag": "0001_increase-secret-kind-length",
"breakpoints": true
},
{
"idx": 2,
"version": "7",
"when": 1760968530084,
"tag": "0002_add_app_reference_to_integration",
"breakpoints": true
}
]
}
+1
View File
@@ -150,6 +150,7 @@ const seedDefaultIntegrationsAsync = async (db: Database) => {
name: `${name} Default`,
url: defaultUrl,
kind,
appId: null,
});
}
@@ -0,0 +1 @@
ALTER TABLE `integration` ADD `app_id` text REFERENCES app(id);
File diff suppressed because it is too large. Load diff
@@ -239,6 +239,13 @@
"when": 1750014001941,
"tag": "0033_add_cron_job_configuration",
"breakpoints": true
},
{
"idx": 34,
"version": "6",
"when": 1760968503571,
"tag": "0034_add_app_reference_to_integration",
"breakpoints": true
}
]
}
+17 -17
View File
@@ -43,36 +43,36 @@
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@auth/core": "^0.40.0",
"@auth/core": "^0.41.1",
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/log": "workspace:^0.1.0",
"@homarr/server-settings": "workspace:^0.1.0",
"@mantine/core": "^8.3.1",
"@paralleldrive/cuid2": "^2.2.2",
"@testcontainers/mysql": "^11.5.1",
"@testcontainers/postgresql": "^11.5.1",
"better-sqlite3": "^12.2.0",
"dotenv": "^17.2.2",
"drizzle-kit": "^0.31.4",
"drizzle-orm": "^0.44.5",
"@mantine/core": "^8.3.9",
"@paralleldrive/cuid2": "^3.1.0",
"@testcontainers/mysql": "^11.9.0",
"@testcontainers/postgresql": "^11.9.0",
"better-sqlite3": "^12.5.0",
"dotenv": "^17.2.3",
"drizzle-kit": "^0.31.8",
"drizzle-orm": "^0.45.0",
"drizzle-zod": "^0.8.3",
"mysql2": "3.14.5",
"mysql2": "3.15.3",
"pg": "^8.16.3",
"superjson": "2.2.2"
"superjson": "2.2.6"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/better-sqlite3": "7.6.13",
"@types/pg": "^8.15.5",
"dotenv-cli": "^10.0.0",
"esbuild": "^0.25.9",
"eslint": "^9.35.0",
"prettier": "^3.6.2",
"@types/pg": "^8.15.6",
"dotenv-cli": "^11.0.0",
"esbuild": "^0.27.1",
"eslint": "^9.39.1",
"prettier": "^3.7.4",
"tsx": "4.20.4",
"typescript": "^5.9.2"
"typescript": "^5.9.3"
}
}
+1
View File
@@ -16,6 +16,7 @@ export const getItemsWithIntegrationsAsync = async <TKind extends WidgetKind>(
with: {
integration: {
with: {
app: true,
secrets: {
columns: {
kind: true,
+6 -1
View File
@@ -199,6 +199,7 @@ export const integrations = mysqlTable(
name: text().notNull(),
url: text().notNull(),
kind: varchar({ length: 128 }).$type<IntegrationKind>().notNull(),
appId: varchar({ length: 128 }).references(() => apps.id, { onDelete: "set null" }),
},
(integrations) => ({
kindIdx: index("integration__kind_idx").on(integrations.kind),
@@ -627,11 +628,15 @@ export const boardGroupPermissionRelations = relations(boardGroupPermissions, ({
}),
}));
export const integrationRelations = relations(integrations, ({ many }) => ({
export const integrationRelations = relations(integrations, ({ one, many }) => ({
secrets: many(integrationSecrets),
items: many(integrationItems),
userPermissions: many(integrationUserPermissions),
groupPermissions: many(integrationGroupPermissions),
app: one(apps, {
fields: [integrations.appId],
references: [apps.id],
}),
}));
export const integrationUserPermissionRelations = relations(integrationUserPermissions, ({ one }) => ({
+6 -1
View File
@@ -198,6 +198,7 @@ export const integrations = pgTable(
name: text().notNull(),
url: text().notNull(),
kind: varchar({ length: 128 }).$type<IntegrationKind>().notNull(),
appId: varchar({ length: 128 }).references(() => apps.id, { onDelete: "set null" }),
},
(integrations) => ({
kindIdx: index("integration__kind_idx").on(integrations.kind),
@@ -626,11 +627,15 @@ export const boardGroupPermissionRelations = relations(boardGroupPermissions, ({
}),
}));
export const integrationRelations = relations(integrations, ({ many }) => ({
export const integrationRelations = relations(integrations, ({ one, many }) => ({
secrets: many(integrationSecrets),
items: many(integrationItems),
userPermissions: many(integrationUserPermissions),
groupPermissions: many(integrationGroupPermissions),
app: one(apps, {
fields: [integrations.appId],
references: [apps.id],
}),
}));
export const integrationUserPermissionRelations = relations(integrationUserPermissions, ({ one }) => ({
+6 -1
View File
@@ -185,6 +185,7 @@ export const integrations = sqliteTable(
name: text().notNull(),
url: text().notNull(),
kind: text().$type<IntegrationKind>().notNull(),
appId: text().references(() => apps.id, { onDelete: "set null" }),
},
(integrations) => ({
kindIdx: index("integration__kind_idx").on(integrations.kind),
@@ -612,11 +613,15 @@ export const boardGroupPermissionRelations = relations(boardGroupPermissions, ({
}),
}));
export const integrationRelations = relations(integrations, ({ many }) => ({
export const integrationRelations = relations(integrations, ({ one, many }) => ({
secrets: many(integrationSecrets),
items: many(integrationItems),
userPermissions: many(integrationUserPermissions),
groupPermissions: many(integrationGroupPermissions),
app: one(apps, {
fields: [integrations.appId],
references: [apps.id],
}),
}));
export const integrationUserPermissionRelations = relations(integrationUserPermissions, ({ one }) => ({
+4 -4
View File
@@ -24,15 +24,15 @@
"prettier": "@homarr/prettier-config",
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"fast-xml-parser": "^5.2.5",
"zod": "^4.1.5"
"fast-xml-parser": "^5.3.2",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"eslint": "^9.39.1",
"tsx": "4.20.4",
"typescript": "^5.9.2"
"typescript": "^5.9.3"
}
}
@@ -87,6 +87,7 @@ export type HomarrDocumentationPath =
| "/docs/tags/programming"
| "/docs/tags/proxy"
| "/docs/tags/puid"
| "/docs/tags/redis"
| "/docs/tags/responsive"
| "/docs/tags/roles"
| "/docs/tags/search"
@@ -143,6 +144,7 @@ export type HomarrDocumentationPath =
| "/docs/getting-started/installation/proxmox"
| "/docs/getting-started/installation/qnap"
| "/docs/getting-started/installation/railway"
| "/docs/getting-started/installation/runtipi"
| "/docs/getting-started/installation/saltbox"
| "/docs/getting-started/installation/source"
| "/docs/getting-started/installation/synology"
@@ -159,6 +161,7 @@ export type HomarrDocumentationPath =
| "/docs/integrations/github"
| "/docs/integrations/gitlab"
| "/docs/integrations/home-assistant"
| "/docs/integrations/ical"
| "/docs/integrations/jellyfin"
| "/docs/integrations/jellyseerr"
| "/docs/integrations/kubernetes"
+6
View File
@@ -0,0 +1,6 @@
export const hotkeys = {
toggleBoardEdit: "mod+e",
toggleColorScheme: "mod+j",
saveNotebook: "mod+s",
openSpotlight: "mod+k",
};
+1
View File
@@ -13,3 +13,4 @@ export * from "./cookie";
export * from "./search-engine";
export * from "./onboarding";
export * from "./emptysuperjson";
export * from "./hotkeys";
+10 -2
View File
@@ -13,6 +13,7 @@ export const integrationSecretKindObject = {
topic: { isPublic: true, multiline: false },
opnsenseApiKey: { isPublic: false, multiline: false },
opnsenseApiSecret: { isPublic: false, multiline: false },
url: { isPublic: false, multiline: false },
privateKey: { isPublic: false, multiline: true },
githubAppId: { isPublic: true, multiline: false },
githubInstallationId: { isPublic: true, multiline: false },
@@ -144,7 +145,7 @@ export const integrationDefs = {
},
piHole: {
name: "Pi-hole",
secretKinds: [["apiKey"]],
secretKinds: [["apiKey"], []],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/pi-hole.svg",
category: ["dnsHole"],
documentationUrl: createDocumentationLink("/docs/integrations/pi-hole"),
@@ -160,7 +161,7 @@ export const integrationDefs = {
name: "Home Assistant",
secretKinds: [["apiKey"]],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/home-assistant.svg",
category: ["smartHomeServer"],
category: ["smartHomeServer", "calendar"],
documentationUrl: createDocumentationLink("/docs/integrations/home-assistant"),
},
openmediavault: {
@@ -283,6 +284,13 @@ export const integrationDefs = {
category: ["notifications"],
documentationUrl: createDocumentationLink("/docs/integrations/ntfy"),
},
ical: {
name: "iCal",
secretKinds: [["url"]],
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/ical.svg",
category: ["calendar"],
documentationUrl: createDocumentationLink("/docs/integrations/ical"),
},
truenas: {
name: "TrueNAS",
secretKinds: [["username", "password"]],
+4 -4
View File
@@ -26,14 +26,14 @@
"dependencies": {
"@homarr/common": "workspace:^0.1.0",
"@homarr/core": "workspace:^0.1.0",
"dockerode": "^4.0.8"
"dockerode": "^4.0.9"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/dockerode": "^3.3.43",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"@types/dockerode": "^3.3.47",
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+1
View File
@@ -8,3 +8,4 @@ export type { Docker };
export const containerStates = ["created", "running", "paused", "restarting", "exited", "removing", "dead"] as const;
export type ContainerState = (typeof containerStates)[number];
export * from "./labels";
+4
View File
@@ -0,0 +1,4 @@
export const dockerLabels = {
// Label to hide a container from Homarrs docker integration
hide: "homarr.hide",
} as const;
+4 -4
View File
@@ -26,15 +26,15 @@
"@homarr/common": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@mantine/form": "^8.3.1",
"@mantine/form": "^8.3.9",
"mantine-form-zod-resolver": "^1.3.0",
"zod": "^4.1.5"
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+4 -2
View File
@@ -1,7 +1,9 @@
import type { ChangeEvent, FocusEvent } from "react";
export interface InputPropsFor<T, TOnChangeArg, TComponent extends HTMLElement = HTMLInputElement>
extends BasePropsFor<TOnChangeArg, TComponent> {
export interface InputPropsFor<T, TOnChangeArg, TComponent extends HTMLElement = HTMLInputElement> extends BasePropsFor<
TOnChangeArg,
TComponent
> {
value?: T;
defaultValue?: T;
}
+6 -5
View File
@@ -28,16 +28,17 @@
"@homarr/form": "workspace:^0.1.0",
"@homarr/notifications": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/ui": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@mantine/core": "^8.3.1",
"react": "19.1.1",
"zod": "^4.1.5"
"@mantine/core": "^8.3.9",
"react": "19.2.1",
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
@@ -165,11 +165,14 @@ export const IconPicker = ({
/>
{session?.user.permissions.includes("media-upload") && (
<UploadMedia
onSuccess={({ url }) => {
onSuccess={(medias) => {
const first = medias.at(0);
if (!first) return;
startTransition(() => {
setValue(url);
setPreviewUrl(url);
setSearch(url);
setValue(first.url);
setPreviewUrl(first.url);
setSearch(first.url);
});
}}
>
@@ -2,7 +2,6 @@
import type { ChangeEventHandler } from "react";
import { useEffect, useRef } from "react";
import Link from "next/link";
import { Button, Checkbox, Collapse, Group, Stack, Textarea, TextInput } from "@mantine/core";
import { useDebouncedValue, useDisclosure } from "@mantine/hooks";
import type { z } from "zod/v4";
@@ -10,6 +9,7 @@ import type { z } from "zod/v4";
import { clientApi } from "@homarr/api/client";
import { useZodForm } from "@homarr/form";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import { appManageSchema } from "@homarr/validation/app";
import { IconPicker } from "../icon-picker/icon-picker";
@@ -9,41 +9,48 @@ import { supportedMediaUploadFormats } from "@homarr/validation/media";
interface UploadMediaProps {
children: (props: { onClick: () => void; loading: boolean }) => JSX.Element;
multiple?: boolean;
onSettled?: () => MaybePromise<void>;
onSuccess?: (media: { id: string; url: string }) => MaybePromise<void>;
onSuccess?: (media: { id: string; url: string }[]) => MaybePromise<void>;
}
export const UploadMedia = ({ children, onSettled, onSuccess }: UploadMediaProps) => {
export const UploadMedia = ({ children, onSettled, onSuccess, multiple = false }: UploadMediaProps) => {
const t = useI18n();
const { mutateAsync, isPending } = clientApi.media.uploadMedia.useMutation();
const { mutateAsync, isPending } = clientApi.media.uploadMedia.useMutation({
async onSuccess(mediaIds) {
await onSuccess?.(
mediaIds.map((id) => ({
id,
url: `/api/user-medias/${id}`,
})),
);
},
async onSettled() {
await onSettled?.();
},
});
const handleFileUploadAsync = async (file: File | null) => {
if (!file) return;
const handleFileUploadAsync = async (files: File[] | File | null) => {
if (!files || (Array.isArray(files) && files.length === 0)) return;
const filesArray: File[] = Array.isArray(files) ? files : [files];
const formData = new FormData();
formData.append("file", file);
filesArray.forEach((file) => formData.append("files", file));
await mutateAsync(formData, {
async onSuccess(mediaId) {
onSuccess() {
showSuccessNotification({
message: t("media.action.upload.notification.success.message"),
});
await onSuccess?.({
id: mediaId,
url: `/api/user-medias/${mediaId}`,
});
},
onError() {
showErrorNotification({
message: t("media.action.upload.notification.error.message"),
});
},
async onSettled() {
await onSettled?.();
},
});
};
return (
<FileButton onChange={handleFileUploadAsync} accept={supportedMediaUploadFormats.join(",")}>
<FileButton onChange={handleFileUploadAsync} accept={supportedMediaUploadFormats.join(",")} multiple={multiple}>
{({ onClick }) => children({ onClick, loading: isPending })}
</FileButton>
);
+2 -2
View File
@@ -31,7 +31,7 @@
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+2 -2
View File
@@ -33,7 +33,7 @@
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/bcrypt": "6.0.0",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+14 -13
View File
@@ -25,10 +25,10 @@
},
"prettier": "@homarr/prettier-config",
"dependencies": {
"@ctrl/deluge": "^7.2.0",
"@ctrl/qbittorrent": "^9.7.0",
"@ctrl/transmission": "^7.3.0",
"@gitbeaker/rest": "^43.5.0",
"@ctrl/deluge": "^7.5.0",
"@ctrl/qbittorrent": "^9.11.0",
"@ctrl/transmission": "^7.4.0",
"@gitbeaker/rest": "^43.8.0",
"@homarr/certificates": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/db": "workspace:^0.1.0",
@@ -39,16 +39,17 @@
"@homarr/redis": "workspace:^0.1.0",
"@homarr/translation": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@jellyfin/sdk": "^0.11.0",
"@octokit/auth-app": "^8.1.0",
"@jellyfin/sdk": "^0.13.0",
"@octokit/auth-app": "^8.1.2",
"ical.js": "^2.2.1",
"maria2": "^0.4.1",
"node-ical": "^0.20.1",
"octokit": "^5.0.3",
"node-ical": "^0.22.1",
"octokit": "^5.0.5",
"proxmox-api": "1.1.1",
"tsdav": "^2.1.5",
"undici": "7.15.0",
"tsdav": "^2.1.6",
"undici": "7.16.0",
"xml2js": "^0.6.2",
"zod": "^4.1.5"
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
@@ -56,7 +57,7 @@
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/node-unifi": "^2.5.1",
"@types/xml2js": "^0.4.14",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
+3 -18
View File
@@ -1,7 +1,4 @@
import { decryptSecret } from "@homarr/common/server";
import type { Modify } from "@homarr/common/types";
import type { Integration as DbIntegration } from "@homarr/db/schema";
import type { IntegrationKind, IntegrationSecretKind } from "@homarr/definitions";
import type { IntegrationKind } from "@homarr/definitions";
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
import { CodebergIntegration } from "../codeberg/codeberg-integration";
@@ -18,6 +15,7 @@ import { GitHubContainerRegistryIntegration } from "../github-container-registry
import { GithubIntegration } from "../github/github-integration";
import { GitlabIntegration } from "../gitlab/gitlab-integration";
import { HomeAssistantIntegration } from "../homeassistant/homeassistant-integration";
import { ICalIntegration } from "../ical/ical-integration";
import { JellyfinIntegration } from "../jellyfin/jellyfin-integration";
import { JellyseerrIntegration } from "../jellyseerr/jellyseerr-integration";
import { LinuxServerIOIntegration } from "../linuxserverio/linuxserverio-integration";
@@ -61,20 +59,6 @@ export const createIntegrationAsync = async <TKind extends keyof typeof integrat
return new creator(integration) as IntegrationInstanceOfKind<TKind>;
};
export const createIntegrationAsyncFromSecrets = <TKind extends keyof typeof integrationCreators>(
integration: Modify<DbIntegration, { kind: TKind }> & {
secrets: { kind: IntegrationSecretKind; value: `${string}.${string}` }[];
},
) => {
return createIntegrationAsync({
...integration,
decryptedSecrets: integration.secrets.map((secret) => ({
...secret,
value: decryptSecret(secret.value),
})),
});
};
type IntegrationInstance = new (integration: IntegrationInput) => Integration;
// factories are an array, to differentiate in js between class constructors and functions
@@ -112,6 +96,7 @@ export const integrationCreators = {
codeberg: CodebergIntegration,
linuxServerIO: LinuxServerIOIntegration,
gitHubContainerRegistry: GitHubContainerRegistryIntegration,
ical: ICalIntegration,
quay: QuayIntegration,
ntfy: NTFYIntegration,
mock: MockIntegration,
+14 -2
View File
@@ -17,6 +17,7 @@ export interface IntegrationInput {
id: string;
name: string;
url: string;
externalUrl: string | null;
decryptedSecrets: IntegrationSecret[];
}
@@ -54,8 +55,12 @@ export abstract class Integration {
return this.integration.decryptedSecrets.some((secret) => secret.kind === kind);
}
protected url(path: `/${string}`, queryParams?: Record<string, string | Date | number | boolean>) {
const baseUrl = removeTrailingSlash(this.integration.url);
private createUrl(
inputUrl: string,
path: `/${string}`,
queryParams?: Record<string, string | Date | number | boolean>,
) {
const baseUrl = removeTrailingSlash(inputUrl);
const url = new URL(`${baseUrl}${path}`);
if (queryParams) {
@@ -66,6 +71,13 @@ export abstract class Integration {
return url;
}
protected url(path: `/${string}`, queryParams?: Record<string, string | Date | number | boolean>) {
return this.createUrl(this.integration.url, path, queryParams);
}
protected externalUrl(path: `/${string}`, queryParams?: Record<string, string | Date | number | boolean>) {
return this.createUrl(this.integration.externalUrl ?? this.integration.url, path, queryParams);
}
public async testConnectionAsync(): Promise<TestingResult> {
try {
@@ -11,8 +11,7 @@ import type { ReleasesProviderIntegration } from "../interfaces/releases-provide
import { getLatestRelease } from "../interfaces/releases-providers/releases-providers-integration";
import type {
DetailsProviderResponse,
ReleasesRepository,
ReleasesResponse,
ReleaseResponse,
} from "../interfaces/releases-providers/releases-providers-types";
import { detailsResponseSchema, releasesResponseSchema } from "./codeberg-schemas";
@@ -43,22 +42,23 @@ export class CodebergIntegration extends Integration implements ReleasesProvider
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const [owner, name] = repository.identifier.split("/");
private parseIdentifier(identifier: string) {
const [owner, name] = identifier.split("/");
if (!owner || !name) {
localLogger.warn(
`Invalid identifier format. Expected 'owner/name', for ${repository.identifier} with Codeberg integration`,
{
identifier: repository.identifier,
},
`Invalid identifier format. Expected 'owner/name', for ${identifier} with Codeberg integration`,
{ identifier },
);
return {
id: repository.id,
error: { code: "invalidIdentifier" },
};
return null;
}
return { owner, name };
}
const details = await this.getDetailsAsync(owner, name);
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
const parsedIdentifier = this.parseIdentifier(identifier);
if (!parsedIdentifier) return { success: false, error: { code: "invalidIdentifier" } };
const { owner, name } = parsedIdentifier;
const releasesResponse = await this.withHeadersAsync(async (headers) => {
return await fetchWithTrustedCertificatesAsync(
@@ -66,34 +66,36 @@ export class CodebergIntegration extends Integration implements ReleasesProvider
{ headers },
);
});
if (!releasesResponse.ok) {
return {
id: repository.id,
error: { message: releasesResponse.statusText },
};
return { success: false, error: { code: "unexpected", message: releasesResponse.statusText } };
}
const releasesResponseJson: unknown = await releasesResponse.json();
const { data, success, error } = releasesResponseSchema.safeParse(releasesResponseJson);
if (!success) {
return {
id: repository.id,
success: false,
error: {
code: "unexpected",
message: releasesResponseJson ? JSON.stringify(releasesResponseJson, null, 2) : error.message,
},
};
} else {
const formattedReleases = data.map((tag) => ({
latestRelease: tag.tag_name,
latestReleaseAt: tag.published_at,
releaseUrl: tag.url,
releaseDescription: tag.body,
isPreRelease: tag.prerelease,
}));
return getLatestRelease(formattedReleases, repository, details);
}
const formattedReleases = data.map((tag) => ({
latestRelease: tag.tag_name,
latestReleaseAt: tag.published_at,
releaseUrl: tag.url,
releaseDescription: tag.body,
isPreRelease: tag.prerelease,
}));
const latestRelease = getLatestRelease(formattedReleases, versionRegex);
if (!latestRelease) return { success: false, error: { code: "noMatchingVersion" } };
const details = await this.getDetailsAsync(owner, name);
return { success: true, data: { ...details, ...latestRelease } };
}
protected async getDetailsAsync(owner: string, name: string): Promise<DetailsProviderResponse | undefined> {
@@ -14,8 +14,7 @@ import type { ReleasesProviderIntegration } from "../interfaces/releases-provide
import { getLatestRelease } from "../interfaces/releases-providers/releases-providers-integration";
import type {
DetailsProviderResponse,
ReleasesRepository,
ReleasesResponse,
ReleaseResponse,
} from "../interfaces/releases-providers/releases-providers-types";
import { accessTokenResponseSchema, detailsResponseSchema, releasesResponseSchema } from "./docker-hub-schemas";
@@ -73,49 +72,61 @@ export class DockerHubIntegration extends Integration implements ReleasesProvide
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const relativeUrl = this.getRelativeUrl(repository.identifier);
if (relativeUrl === "/") {
localLogger.warn(
`Invalid identifier format. Expected 'owner/name' or 'name', for ${repository.identifier} on DockerHub`,
{
identifier: repository.identifier,
},
);
return {
id: repository.id,
error: { code: "invalidIdentifier" },
};
}
const details = await this.getDetailsAsync(relativeUrl);
const releasesResponse = await this.withHeadersAsync(async (headers) => {
return await fetchWithTrustedCertificatesAsync(this.url(`${relativeUrl}/tags?page_size=100`), {
headers,
private parseIdentifier(identifier: string) {
if (!identifier.includes("/")) return { owner: "", name: identifier };
const [owner, name] = identifier.split("/");
if (!owner || !name) {
localLogger.warn(`Invalid identifier format. Expected 'owner/name' or 'name', for ${identifier} on DockerHub`, {
identifier,
});
});
return null;
}
return { owner, name };
}
if (!releasesResponse.ok) {
return {
id: repository.id,
error: { message: releasesResponse.statusText },
};
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
const parsedIdentifier = this.parseIdentifier(identifier);
if (!parsedIdentifier) return { success: false, error: { code: "invalidIdentifier" } };
const { owner, name } = parsedIdentifier;
const relativeUrl: `/${string}` = owner
? `/v2/namespaces/${encodeURIComponent(owner)}/repositories/${encodeURIComponent(name)}`
: `/v2/repositories/library/${encodeURIComponent(name)}`;
for (let page = 0; page <= 5; page++) {
const releasesResponse = await this.withHeadersAsync(async (headers) => {
return await fetchWithTrustedCertificatesAsync(this.url(`${relativeUrl}/tags?page_size=100&page=${page}`), {
headers,
});
});
if (!releasesResponse.ok) {
return { success: false, error: { code: "unexpected", message: releasesResponse.statusText } };
}
const releasesResponseJson: unknown = await releasesResponse.json();
const releasesResult = releasesResponseSchema.safeParse(releasesResponseJson);
if (!releasesResult.success) {
return {
success: false,
error: {
code: "unexpected",
message: releasesResponseJson
? JSON.stringify(releasesResponseJson, null, 2)
: releasesResult.error.message,
},
};
}
const latestRelease = getLatestRelease(releasesResult.data.results, versionRegex);
if (!latestRelease) continue;
const details = await this.getDetailsAsync(relativeUrl);
return { success: true, data: { ...details, ...latestRelease } };
}
const releasesResponseJson: unknown = await releasesResponse.json();
const releasesResult = releasesResponseSchema.safeParse(releasesResponseJson);
if (!releasesResult.success) {
return {
id: repository.id,
error: {
message: releasesResponseJson ? JSON.stringify(releasesResponseJson, null, 2) : releasesResult.error.message,
},
};
} else {
return getLatestRelease(releasesResult.data.results, repository, details);
}
return { success: false, error: { code: "noMatchingVersion" } };
}
private async getDetailsAsync(relativeUrl: `/${string}`): Promise<DetailsProviderResponse | undefined> {
@@ -154,18 +165,6 @@ export class DockerHubIntegration extends Integration implements ReleasesProvide
};
}
private getRelativeUrl(identifier: string): `/${string}` {
if (identifier.indexOf("/") > 0) {
const [owner, name] = identifier.split("/");
if (!owner || !name) {
return "/";
}
return `/v2/namespaces/${encodeURIComponent(owner)}/repositories/${encodeURIComponent(name)}`;
} else {
return `/v2/repositories/library/${encodeURIComponent(identifier)}`;
}
}
private async getSessionAsync(fetchAsync: typeof fetch = fetchWithTrustedCertificatesAsync): Promise<string> {
const response = await fetchAsync(this.url("/v2/auth/token"), {
method: "POST",
@@ -11,7 +11,7 @@ import type { TestingResult } from "../base/test-connection/test-connection-serv
import type { IMediaServerIntegration } from "../interfaces/media-server/media-server-integration";
import type { CurrentSessionsInput, StreamSession } from "../interfaces/media-server/media-server-types";
import { convertJellyfinType } from "../jellyfin/jellyfin-integration";
import type { IMediaReleasesIntegration, MediaRelease } from "../types";
import type { IMediaReleasesIntegration, MediaRelease, MediaType } from "../types";
const sessionSchema = z.object({
NowPlayingItem: z
@@ -117,6 +117,7 @@ export class EmbyIntegration extends Integration implements IMediaServerIntegrat
episodeName: sessionInfo.NowPlayingItem.EpisodeTitle,
albumName: sessionInfo.NowPlayingItem.Album ?? "",
episodeCount: sessionInfo.NowPlayingItem.EpisodeCount,
metadata: null,
};
}
@@ -124,7 +125,7 @@ export class EmbyIntegration extends Integration implements IMediaServerIntegrat
sessionId: `${sessionInfo.Id}`,
sessionName: `${sessionInfo.Client} (${sessionInfo.DeviceName})`,
user: {
profilePictureUrl: super.url(`/Users/${sessionInfo.UserId}/Images/Primary`).toString(),
profilePictureUrl: super.externalUrl(`/Users/${sessionInfo.UserId}/Images/Primary`).toString(),
userId: sessionInfo.UserId ?? "",
username: sessionInfo.UserName ?? "",
},
@@ -162,22 +163,43 @@ export class EmbyIntegration extends Integration implements IMediaServerIntegrat
return items.map((item) => ({
id: item.Id,
type: item.Type === "Movie" ? "movie" : item.Type === "Series" ? "tv" : "unknown",
type: this.mapMediaReleaseType(item.Type),
title: item.Name,
subtitle: item.Taglines.at(0),
description: item.Overview,
releaseDate: item.PremiereDate ?? item.DateCreated,
imageUrls: {
poster: super.url(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
backdrop: super.url(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
poster: super.externalUrl(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
backdrop: super.externalUrl(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
},
producer: item.Studios.at(0)?.Name,
rating: item.CommunityRating?.toFixed(1),
tags: item.Genres,
href: super.url(`/web/index.html#!/item?id=${item.Id}&serverId=${item.ServerId}`).toString(),
href: super.externalUrl(`/web/index.html#!/item?id=${item.Id}&serverId=${item.ServerId}`).toString(),
}));
}
private mapMediaReleaseType(type: string | undefined): MediaType {
switch (type) {
case "Audio":
case "AudioBook":
case "MusicAlbum":
return "music";
case "Book":
return "book";
case "Episode":
case "Series":
case "Season":
return "tv";
case "Movie":
return "movie";
case "Video":
return "video";
default:
return "unknown";
}
}
// https://dev.emby.media/reference/RestAPI/UserService/getUsersPublic.html
private async fetchUsersPublicAsync(): Promise<{ id: string; name: string }[]> {
const apiKey = super.getSecretValue("apiKey");
@@ -15,8 +15,7 @@ import { getLatestRelease } from "../interfaces/releases-providers/releases-prov
import type {
DetailsProviderResponse,
ReleaseProviderResponse,
ReleasesRepository,
ReleasesResponse,
ReleaseResponse,
} from "../interfaces/releases-providers/releases-providers-types";
const localLogger = logger.child({ module: "GitHubContainerRegistryIntegration" });
@@ -43,23 +42,24 @@ export class GitHubContainerRegistryIntegration extends Integration implements R
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const [owner, name] = repository.identifier.split("/");
private parseIdentifier(identifier: string) {
const [owner, name] = identifier.split("/");
if (!owner || !name) {
localLogger.warn(
`Invalid identifier format. Expected 'owner/name', for ${repository.identifier} with GitHub Container Registry integration`,
{
identifier: repository.identifier,
},
`Invalid identifier format. Expected 'owner/name', for ${identifier} with GitHub Container Registry integration`,
{ identifier },
);
return {
id: repository.id,
error: { code: "invalidIdentifier" },
};
return null;
}
return { owner, name };
}
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
const parsedIdentifier = this.parseIdentifier(identifier);
if (!parsedIdentifier) return { success: false, error: { code: "invalidIdentifier" } };
const { owner, name } = parsedIdentifier;
const api = this.getApi();
const details = await this.getDetailsAsync(api, owner, name);
try {
const releasesResponse = await api.rest.packages.getAllPackageVersionsForPackageOwnedByUser({
@@ -83,20 +83,20 @@ export class GitHubContainerRegistryIntegration extends Integration implements R
return acc;
}, []);
return getLatestRelease(releasesProviderResponse, repository, details);
const latestRelease = getLatestRelease(releasesProviderResponse, versionRegex);
if (!latestRelease) return { success: false, error: { code: "noMatchingVersion" } };
const details = await this.getDetailsAsync(api, owner, name);
return { success: true, data: { ...details, ...latestRelease } };
} catch (error) {
const errorMessage = error instanceof RequestError ? error.message : String(error);
localLogger.warn(`Failed to get releases for ${owner}\\${name} with GitHub Container Registry integration`, {
owner,
name,
error: errorMessage,
});
return {
id: repository.id,
error: { message: errorMessage },
};
return { success: false, error: { code: "unexpected", message: errorMessage } };
}
}
@@ -15,8 +15,7 @@ import { getLatestRelease } from "../interfaces/releases-providers/releases-prov
import type {
DetailsProviderResponse,
ReleaseProviderResponse,
ReleasesRepository,
ReleasesResponse,
ReleaseResponse,
} from "../interfaces/releases-providers/releases-providers-types";
const localLogger = logger.child({ module: "GithubIntegration" });
@@ -43,38 +42,32 @@ export class GithubIntegration extends Integration implements ReleasesProviderIn
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const [owner, name] = repository.identifier.split("/");
private parseIdentifier(identifier: string) {
const [owner, name] = identifier.split("/");
if (!owner || !name) {
localLogger.warn(
`Invalid identifier format. Expected 'owner/name', for ${repository.identifier} with Github integration`,
{
identifier: repository.identifier,
},
);
return {
id: repository.id,
error: { code: "invalidIdentifier" },
};
localLogger.warn(`Invalid identifier format. Expected 'owner/name', for ${identifier} with Github integration`, {
identifier,
});
return null;
}
return { owner, name };
}
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
const parsedIdentifier = this.parseIdentifier(identifier);
if (!parsedIdentifier) return { success: false, error: { code: "invalidIdentifier" } };
const { owner, name } = parsedIdentifier;
const api = this.getApi();
const details = await this.getDetailsAsync(api, owner, name);
try {
const releasesResponse = await api.rest.repos.listReleases({
owner,
repo: name,
});
const releasesResponse = await api.rest.repos.listReleases({ owner, repo: name });
if (releasesResponse.data.length === 0) {
localLogger.warn(`No releases found, for ${repository.identifier} with Github integration`, {
identifier: repository.identifier,
localLogger.warn(`No releases found, for ${owner}/${name} with Github integration`, {
identifier: `${owner}/${name}`,
});
return {
id: repository.id,
error: { code: "noReleasesFound" },
};
return { success: false, error: { code: "noMatchingVersion" } };
}
const releasesProviderResponse = releasesResponse.data.reduce<ReleaseProviderResponse[]>((acc, release) => {
@@ -90,20 +83,20 @@ export class GithubIntegration extends Integration implements ReleasesProviderIn
return acc;
}, []);
return getLatestRelease(releasesProviderResponse, repository, details);
const latestRelease = getLatestRelease(releasesProviderResponse, versionRegex);
if (!latestRelease) return { success: false, error: { code: "noMatchingVersion" } };
const details = await this.getDetailsAsync(api, owner, name);
return { success: true, data: { ...details, ...latestRelease } };
} catch (error) {
const errorMessage = error instanceof OctokitRequestError ? error.message : String(error);
localLogger.warn(`Failed to get releases for ${owner}\\${name} with Github integration`, {
owner,
name,
error: errorMessage,
});
return {
id: repository.id,
error: { message: errorMessage },
};
return { success: false, error: { code: "unexpected", message: errorMessage } };
}
}
@@ -15,8 +15,7 @@ import { getLatestRelease } from "../interfaces/releases-providers/releases-prov
import type {
DetailsProviderResponse,
ReleaseProviderResponse,
ReleasesRepository,
ReleasesResponse,
ReleaseResponse,
} from "../interfaces/releases-providers/releases-providers-types";
const localLogger = logger.child({ module: "GitlabIntegration" });
@@ -40,25 +39,20 @@ export class GitlabIntegration extends Integration implements ReleasesProviderIn
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
const api = this.getApi();
const details = await this.getDetailsAsync(api, repository.identifier);
try {
const releasesResponse = await api.ProjectReleases.all(repository.identifier, {
const releasesResponse = await api.ProjectReleases.all(identifier, {
perPage: 100,
});
if (releasesResponse instanceof Error) {
localLogger.warn(`Failed to get releases for ${repository.identifier} with Gitlab integration`, {
identifier: repository.identifier,
localLogger.warn(`Failed to get releases for ${identifier} with Gitlab integration`, {
identifier,
error: releasesResponse.message,
});
return {
id: repository.id,
error: { code: "noReleasesFound" },
};
return { success: false, error: { code: "noReleasesFound" } };
}
const releasesProviderResponse = releasesResponse.reduce<ReleaseProviderResponse[]>((acc, release) => {
@@ -76,17 +70,19 @@ export class GitlabIntegration extends Integration implements ReleasesProviderIn
return acc;
}, []);
return getLatestRelease(releasesProviderResponse, repository, details);
} catch (error) {
localLogger.warn(`Failed to get releases for ${repository.identifier} with Gitlab integration`, {
identifier: repository.identifier,
error: error instanceof Error ? error.message : String(error),
});
const latestRelease = getLatestRelease(releasesProviderResponse, versionRegex);
if (!latestRelease) return { success: false, error: { code: "noMatchingVersion" } };
return {
id: repository.id,
error: { code: "noReleasesFound" },
};
const details = await this.getDetailsAsync(api, identifier);
return { success: true, data: { ...details, ...latestRelease } };
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
localLogger.warn(`Failed to get releases for ${identifier} with Gitlab integration`, {
identifier,
error: errorMessage,
});
return { success: false, error: { code: "unexpected", message: errorMessage } };
}
}
@@ -112,7 +108,7 @@ export class GitlabIntegration extends Integration implements ReleasesProviderIn
return {
projectUrl: response.web_url,
projectDescription: response.description,
projectDescription: response.description ?? undefined,
isFork: response.forked_from_project !== null,
isArchived: response.archived,
createdAt: new Date(response.created_at),
@@ -1,14 +1,19 @@
import z from "zod";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import { ResponseError } from "@homarr/common/server";
import { logger } from "@homarr/log";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import { TestConnectionError } from "../base/test-connection/test-connection-error";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../interfaces/calendar/calendar-integration";
import type { ISmartHomeIntegration } from "../interfaces/smart-home/smart-home-integration";
import { entityStateSchema } from "./homeassistant-types";
import type { CalendarEvent } from "../types";
import { calendarEventSchema, calendarsSchema, entityStateSchema } from "./homeassistant-types";
export class HomeAssistantIntegration extends Integration implements ISmartHomeIntegration {
export class HomeAssistantIntegration extends Integration implements ISmartHomeIntegration, ICalendarIntegration {
public async getEntityStateAsync(entityId: string) {
try {
const response = await this.getAsync(`/api/states/${entityId}`);
@@ -62,6 +67,35 @@ export class HomeAssistantIntegration extends Integration implements ISmartHomeI
}
}
public async getCalendarEventsAsync(start: Date, end: Date): Promise<CalendarEvent[]> {
const calendarsResponse = await this.getAsync("/api/calendars");
if (!calendarsResponse.ok) throw new ResponseError(calendarsResponse);
const calendars = await calendarsSchema.parseAsync(await calendarsResponse.json());
return await Promise.all(
calendars.map(async (calendar) => {
const response = await this.getAsync(`/api/calendars/${calendar.entity_id}`, { start, end });
if (!response.ok) throw new ResponseError(response);
return await z.array(calendarEventSchema).parseAsync(await response.json());
}),
).then((events) =>
events.flat().map(
(event): CalendarEvent => ({
title: event.summary,
subTitle: null,
description: event.description,
// If not reseting it to 0 o'clock it uses utc time and therefore shows as 2 o'clock
startDate: "date" in event.start ? new Date(`${event.start.date}T00:00:00`) : new Date(event.start.dateTime),
endDate: "date" in event.end ? new Date(`${event.end.date}T00:00:00`) : new Date(event.end.dateTime),
image: null,
indicatorColor: "#18bcf2",
links: [],
location: event.location,
}),
),
);
}
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const response = await input.fetchAsync(this.url("/api/config"), {
headers: this.getAuthHeaders(),
@@ -82,8 +116,8 @@ export class HomeAssistantIntegration extends Integration implements ISmartHomeI
* @param path full path to the API endpoint
* @returns the response from the API
*/
private async getAsync(path: `/api/${string}`) {
return await fetchWithTrustedCertificatesAsync(this.url(path), {
private async getAsync(path: `/api/${string}`, queryParams?: Record<string, string | Date | number | boolean>) {
return await fetchWithTrustedCertificatesAsync(this.url(path, queryParams), {
headers: this.getAuthHeaders(),
});
}
@@ -12,3 +12,27 @@ export const entityStateSchema = z.object({
});
export type EntityState = z.infer<typeof entityStateSchema>;
export const calendarsSchema = z.array(
z.object({
name: z.string(),
entity_id: z.string(),
}),
);
const calendarMomentSchema = z
.object({
date: z.string(),
})
.or(
z.object({
dateTime: z.string(),
}),
);
export const calendarEventSchema = z.object({
start: calendarMomentSchema,
end: calendarMomentSchema,
summary: z.string(),
description: z.string().nullable(),
location: z.string().nullable(),
});
@@ -0,0 +1,67 @@
import ICAL from "ical.js";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import type { IntegrationTestingInput } from "../base/integration";
import { Integration } from "../base/integration";
import { TestConnectionError } from "../base/test-connection/test-connection-error";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../interfaces/calendar/calendar-types";
export class ICalIntegration extends Integration implements ICalendarIntegration {
async getCalendarEventsAsync(start: Date, end: Date): Promise<CalendarEvent[]> {
const response = await fetchWithTrustedCertificatesAsync(super.getSecretValue("url"));
const result = await response.text();
const jcal = ICAL.parse(result) as unknown[];
const comp = new ICAL.Component(jcal);
return comp.getAllSubcomponents("vevent").reduce((prev, vevent) => {
const event = new ICAL.Event(vevent);
const startDate = event.startDate.toJSDate();
const endDate = event.endDate.toJSDate();
if (startDate > end) return prev;
if (endDate < start) return prev;
return prev.concat({
title: event.summary,
subTitle: null,
description: event.description,
startDate,
endDate,
image: null,
location: event.location,
indicatorColor: "red",
links: [],
});
}, [] as CalendarEvent[]);
}
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const response = await input.fetchAsync(super.getSecretValue("url"));
if (!response.ok) return TestConnectionError.StatusResult(response);
const result = await response.text();
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const jcal = ICAL.parse(result);
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
const comp = new ICAL.Component(jcal);
return comp.getAllSubcomponents("vevent").length > 0
? { success: true }
: TestConnectionError.ParseResult({
name: "Calendar parse error",
message: "No events found",
cause: new Error("No events found"),
});
} catch (error) {
return TestConnectionError.ParseResult({
name: "Calendar parse error",
message: "Failed to parse calendar",
cause: error as Error,
});
}
}
}
+4 -3
View File
@@ -23,6 +23,7 @@ export { PlexIntegration } from "./plex/plex-integration";
export { ProwlarrIntegration } from "./prowlarr/prowlarr-integration";
export { TrueNasIntegration } from "./truenas/truenas-integration";
export { OPNsenseIntegration } from "./opnsense/opnsense-integration";
export { ICalIntegration } from "./ical/ical-integration";
// Types
export type { IntegrationInput } from "./base/integration";
@@ -37,7 +38,7 @@ export type {
FirewallMemorySummary,
} from "./interfaces/firewall-summary/firewall-summary-types";
export type { SystemHealthMonitoring } from "./interfaces/health-monitoring/health-monitoring-types";
export { MediaRequestStatus } from "./interfaces/media-requests/media-request-types";
export { UpstreamMediaRequestStatus } from "./interfaces/media-requests/media-request-types";
export type { MediaRequestList, MediaRequestStats } from "./interfaces/media-requests/media-request-types";
export type { StreamSession } from "./interfaces/media-server/media-server-types";
export type {
@@ -46,11 +47,11 @@ export type {
TdarrStatistics,
TdarrWorker,
} from "./interfaces/media-transcoding/media-transcoding-types";
export type { ReleasesResponse } from "./interfaces/releases-providers/releases-providers-types";
export type { ReleasesRepository, ReleaseResponse } from "./interfaces/releases-providers/releases-providers-types";
export type { Notification } from "./interfaces/notifications/notification-types";
// Schemas
export { downloadClientItemSchema } from "./interfaces/downloads/download-client-items";
// Helpers
export { createIntegrationAsync, createIntegrationAsyncFromSecrets } from "./base/creator";
export { createIntegrationAsync } from "./base/creator";
@@ -1,24 +1,41 @@
export const radarrReleaseTypes = ["inCinemas", "digitalRelease", "physicalRelease"] as const;
export type RadarrReleaseType = (typeof radarrReleaseTypes)[number];
export interface CalendarEvent {
name: string;
subName: string;
date: Date;
dates?: { type: RadarrReleaseType; date: Date }[];
description?: string;
thumbnail?: string;
mediaInformation?: {
type: "audio" | "video" | "tv" | "movie";
seasonNumber?: number;
episodeNumber?: number;
};
links: {
href: string;
name: string;
color: string | undefined;
notificationColor?: string | undefined;
isDark: boolean | undefined;
logo: string;
}[];
export interface RadarrMetadata {
type: "radarr";
releaseType: RadarrReleaseType;
}
export type CalendarMetadata = RadarrMetadata;
export interface CalendarLink {
name: string;
isDark: boolean;
href: string;
color?: string;
logo?: string;
}
export interface CalendarImageBadge {
content: string;
color: string;
}
export interface CalendarImage {
src: string;
badge?: CalendarImageBadge;
aspectRatio?: { width: number; height: number };
}
export interface CalendarEvent {
title: string;
subTitle: string | null;
description: string | null;
startDate: Date;
endDate: Date | null;
image: CalendarImage | null;
location: string | null;
metadata?: CalendarMetadata;
indicatorColor: string;
links: CalendarLink[];
}
@@ -1,3 +1,5 @@
import { objectKeys } from "@homarr/common";
interface SerieSeason {
id: number;
seasonNumber: number;
@@ -34,6 +36,64 @@ export interface MediaRequest {
requestedBy?: Omit<RequestUser, "requestCount">;
}
export const mediaAvailabilityConfiguration = {
available: {
color: "green",
},
partiallyAvailable: {
color: "yellow",
},
processing: {
color: "blue",
},
requested: {
color: "violet",
},
pending: {
color: "violet",
},
unknown: {
color: "orange",
},
deleted: {
color: "red",
},
blacklisted: {
color: "gray",
},
} satisfies Record<string, { color: string }>;
export const mediaAvailabilities = objectKeys(mediaAvailabilityConfiguration);
export type MediaAvailability = (typeof mediaAvailabilities)[number];
export const mediaRequestStatusConfiguration = {
pending: {
color: "blue",
position: 1,
},
approved: {
color: "green",
position: 2,
},
declined: {
color: "red",
position: 3,
},
failed: {
color: "red",
position: 4,
},
completed: {
color: "green",
position: 5,
},
} satisfies Record<string, { color: string; position: number }>;
export const mediaRequestStatuses = objectKeys(mediaRequestStatusConfiguration);
export type MediaRequestStatus = (typeof mediaRequestStatuses)[number];
export interface MediaRequestList {
integration: {
id: string;
@@ -66,7 +126,7 @@ export interface MediaRequestStats {
}
// https://github.com/fallenbagel/jellyseerr/blob/0fd03f38480f853e7015ad9229ed98160e37602e/server/constants/media.ts#L1
export enum MediaRequestStatus {
export enum UpstreamMediaRequestStatus {
PendingApproval = 1,
Approved = 2,
Declined = 3,
@@ -75,12 +135,12 @@ export enum MediaRequestStatus {
}
// https://github.com/fallenbagel/jellyseerr/blob/0fd03f38480f853e7015ad9229ed98160e37602e/server/constants/media.ts#L14
export enum MediaAvailability {
export enum UpstreamMediaAvailability {
Unknown = 1,
Pending = 2,
Processing = 3,
PartiallyAvailable = 4,
Available = 5,
Blacklisted = 6,
Deleted = 7,
JellyseerrBlacklistedOrOverseerrDeleted = 6,
JellyseerrDeleted = 7,
}
@@ -13,6 +13,30 @@ export interface StreamSession {
episodeName?: string | null;
albumName?: string | null;
episodeCount?: number | null;
metadata: {
video: {
resolution: {
width: number;
height: number;
} | null;
frameRate: number | null;
};
audio: {
channelCount: number | null;
codec: string | null;
};
transcoding: {
container: string | null;
resolution: {
width: number;
height: number;
} | null;
target: {
audioCodec: string | null;
videoCodec: string | null;
};
};
} | null;
} | null;
}
@@ -1,47 +1,21 @@
import type {
DetailsProviderResponse,
ReleaseProviderResponse,
ReleasesRepository,
ReleasesResponse,
} from "./releases-providers-types";
import type { ReleaseProviderResponse, ReleaseResponse } from "./releases-providers-types";
export const getLatestRelease = (
releases: ReleaseProviderResponse[],
repository: ReleasesRepository,
details?: DetailsProviderResponse,
): ReleasesResponse => {
versionRegex?: string,
): ReleaseProviderResponse | null => {
const validReleases = releases.filter((result) => {
if (result.latestRelease) {
return repository.versionRegex ? new RegExp(repository.versionRegex).test(result.latestRelease) : true;
return versionRegex ? new RegExp(versionRegex).test(result.latestRelease) : true;
}
return true;
});
const latest =
validReleases.length === 0
? ({
id: repository.id,
error: { code: "noMatchingVersion" },
} as ReleasesResponse)
: validReleases.reduce(
(latest, result) => {
return {
...details,
...(result.latestReleaseAt > latest.latestReleaseAt ? result : latest),
id: repository.id,
};
},
{
id: "",
latestRelease: "",
latestReleaseAt: new Date(0),
},
);
return latest;
return validReleases.length === 0
? null
: validReleases.reduce((latest, current) => (current.latestReleaseAt > latest.latestReleaseAt ? current : latest));
};
export interface ReleasesProviderIntegration {
getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse>;
getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse>;
}
@@ -1,5 +1,11 @@
import type { TranslationObject } from "@homarr/translation";
export interface ReleasesRepository extends Record<string, unknown> {
id: string;
identifier: string;
versionRegex?: string;
}
export interface DetailsProviderResponse {
projectUrl?: string;
projectDescription?: string;
@@ -19,35 +25,10 @@ export interface ReleaseProviderResponse {
isPreRelease?: boolean;
}
export interface ReleasesRepository {
id: string;
identifier: string;
versionRegex?: string;
}
type ReleasesErrorKeys = keyof TranslationObject["widget"]["releases"]["error"]["messages"];
export interface ReleasesResponse {
id: string;
latestRelease?: string;
latestReleaseAt?: Date;
releaseUrl?: string;
releaseDescription?: string;
isPreRelease?: boolean;
projectUrl?: string;
projectDescription?: string;
isFork?: boolean;
isArchived?: boolean;
createdAt?: Date;
starsCount?: number;
openIssues?: number;
forksCount?: number;
export type ReleaseData = DetailsProviderResponse & ReleaseProviderResponse;
error?:
| {
code: ReleasesErrorKeys;
}
| {
message: string;
};
}
export type ReleaseError = { code: ReleasesErrorKeys } | { code: "unexpected"; message: string };
export type ReleaseResponse = { success: true; data: ReleaseData } | { success: false; error: ReleaseError };
@@ -15,7 +15,7 @@ import { Integration } from "../base/integration";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { IMediaServerIntegration } from "../interfaces/media-server/media-server-integration";
import type { CurrentSessionsInput, StreamSession } from "../interfaces/media-server/media-server-types";
import type { IMediaReleasesIntegration, MediaRelease } from "../types";
import type { IMediaReleasesIntegration, MediaRelease, MediaType } from "../types";
@HandleIntegrationErrors([integrationAxiosHttpErrorHandler])
export class JellyfinIntegration extends Integration implements IMediaServerIntegration, IMediaReleasesIntegration {
@@ -57,6 +57,36 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
episodeName: sessionInfo.NowPlayingItem.EpisodeTitle,
albumName: sessionInfo.NowPlayingItem.Album ?? "",
episodeCount: sessionInfo.NowPlayingItem.EpisodeCount,
metadata: {
video: {
resolution:
sessionInfo.NowPlayingItem.Width && sessionInfo.NowPlayingItem.Height
? {
width: sessionInfo.NowPlayingItem.Width,
height: sessionInfo.NowPlayingItem.Height,
}
: null,
frameRate: sessionInfo.TranscodingInfo?.Framerate ?? null,
},
audio: {
channelCount: sessionInfo.TranscodingInfo?.AudioChannels ?? null,
codec: sessionInfo.TranscodingInfo?.AudioCodec ?? null,
},
transcoding: {
resolution:
sessionInfo.TranscodingInfo?.Width && sessionInfo.TranscodingInfo.Height
? {
width: sessionInfo.TranscodingInfo.Width,
height: sessionInfo.TranscodingInfo.Height,
}
: null,
target: {
audioCodec: sessionInfo.TranscodingInfo?.AudioCodec ?? null,
videoCodec: sessionInfo.TranscodingInfo?.VideoCodec ?? null,
},
container: sessionInfo.TranscodingInfo?.Container ?? null,
},
},
};
}
@@ -64,7 +94,7 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
sessionId: `${sessionInfo.Id}`,
sessionName: `${sessionInfo.Client} (${sessionInfo.DeviceName})`,
user: {
profilePictureUrl: this.url(`/Users/${sessionInfo.UserId}/Images/Primary`).toString(),
profilePictureUrl: this.externalUrl(`/Users/${sessionInfo.UserId}/Images/Primary`).toString(),
userId: sessionInfo.UserId ?? "",
username: sessionInfo.UserName ?? "",
},
@@ -92,7 +122,7 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
return result.data.map((item) => ({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
id: item.Id!,
type: item.Type === "Movie" ? "movie" : item.Type === "Series" ? "tv" : "unknown",
type: this.mapMediaReleaseType(item.Type),
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
title: item.Name!,
subtitle: item.Taglines?.at(0),
@@ -100,16 +130,37 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
releaseDate: new Date(item.PremiereDate ?? item.DateCreated!),
imageUrls: {
poster: super.url(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
backdrop: super.url(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
poster: super.externalUrl(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
backdrop: super.externalUrl(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
},
producer: item.Studios?.at(0)?.Name ?? undefined,
rating: item.CommunityRating?.toFixed(1),
tags: item.Genres ?? [],
href: super.url(`/web/index.html#!/details?id=${item.Id}&serverId=${item.ServerId}`).toString(),
href: super.externalUrl(`/web/index.html#!/details?id=${item.Id}&serverId=${item.ServerId}`).toString(),
}));
}
private mapMediaReleaseType(type: BaseItemKind | undefined): MediaType {
switch (type) {
case "Audio":
case "AudioBook":
case "MusicAlbum":
return "music";
case "Book":
return "book";
case "Episode":
case "Series":
case "Season":
return "tv";
case "Movie":
return "movie";
case "Video":
return "video";
default:
return "unknown";
}
}
/**
* Constructs an ApiClient synchronously with an ApiKey or asynchronously
* with a username and password.
@@ -1,3 +1,12 @@
import type { MediaAvailability } from "../interfaces/media-requests/media-request-types";
import { UpstreamMediaAvailability } from "../interfaces/media-requests/media-request-types";
import { OverseerrIntegration } from "../overseerr/overseerr-integration";
export class JellyseerrIntegration extends OverseerrIntegration {}
export class JellyseerrIntegration extends OverseerrIntegration {
protected override mapAvailability(availability: UpstreamMediaAvailability, inProgress: boolean): MediaAvailability {
// Availability statuses are not exactly the same between Jellyseerr and Overseerr (Jellyseerr has "blacklisted" additionally (deleted is the same value in overseerr))
if (availability === UpstreamMediaAvailability.JellyseerrBlacklistedOrOverseerrDeleted) return "blacklisted";
if (availability === UpstreamMediaAvailability.JellyseerrDeleted) return "deleted";
return super.mapAvailability(availability, inProgress);
}
}
@@ -6,7 +6,7 @@ import { Integration } from "../base/integration";
import { TestConnectionError } from "../base/test-connection/test-connection-error";
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ReleasesProviderIntegration } from "../interfaces/releases-providers/releases-providers-integration";
import type { ReleasesRepository, ReleasesResponse } from "../interfaces/releases-providers/releases-providers-types";
import type { ReleaseResponse } from "../interfaces/releases-providers/releases-providers-types";
import { releasesResponseSchema } from "./linuxserverio-schemas";
const localLogger = logger.child({ module: "LinuxServerIOsIntegration" });
@@ -24,56 +24,44 @@ export class LinuxServerIOIntegration extends Integration implements ReleasesPro
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const [owner, name] = repository.identifier.split("/");
private parseIdentifier(identifier: string) {
const [owner, name] = identifier.split("/");
if (!owner || !name) {
localLogger.warn(
`Invalid identifier format. Expected 'owner/name', for ${repository.identifier} with LinuxServerIO integration`,
{
identifier: repository.identifier,
},
`Invalid identifier format. Expected 'owner/name', for ${identifier} with LinuxServerIO integration`,
{ identifier },
);
return {
id: repository.id,
error: { code: "invalidIdentifier" },
};
return null;
}
return { owner, name };
}
public async getLatestMatchingReleaseAsync(identifier: string): Promise<ReleaseResponse> {
const { name } = this.parseIdentifier(identifier) ?? {};
if (!name) return { success: false, error: { code: "invalidIdentifier" } };
const releasesResponse = await fetchWithTrustedCertificatesAsync(this.url("/api/v1/images"));
if (!releasesResponse.ok) {
return {
id: repository.id,
error: { message: releasesResponse.statusText },
};
return { success: false, error: { code: "unexpected", message: releasesResponse.statusText } };
}
const releasesResponseJson: unknown = await releasesResponse.json();
const { data, success, error } = releasesResponseSchema.safeParse(releasesResponseJson);
if (!success) {
return {
id: repository.id,
error: {
message: error.message,
},
};
} else {
const release = data.data.repositories.linuxserver.find((repo) => repo.name === name);
if (!release) {
localLogger.warn(`Repository ${name} not found on provider, with LinuxServerIO integration`, {
owner,
name,
});
return { success: false, error: { code: "unexpected", message: error.message } };
}
return {
id: repository.id,
error: { code: "noReleasesFound" },
};
}
const release = data.data.repositories.linuxserver.find((repo) => repo.name === name);
if (!release) {
localLogger.warn(`Repository ${name} not found on provider, with LinuxServerIO integration`, {
name,
});
return { success: false, error: { code: "noMatchingVersion" } };
}
return {
id: repository.id,
return {
success: true,
data: {
latestRelease: release.version,
latestReleaseAt: release.version_timestamp,
releaseDescription: release.changelog?.shift()?.desc,
@@ -82,7 +70,7 @@ export class LinuxServerIOIntegration extends Integration implements ReleasesPro
isArchived: release.deprecated,
createdAt: release.initial_date ? new Date(release.initial_date) : undefined,
starsCount: release.stars,
};
}
},
};
}
}
@@ -8,7 +8,7 @@ import type { IntegrationTestingInput } from "../../base/integration";
import { TestConnectionError } from "../../base/test-connection/test-connection-error";
import type { TestingResult } from "../../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../../interfaces/calendar/calendar-types";
import type { CalendarEvent, CalendarLink } from "../../interfaces/calendar/calendar-types";
import { mediaOrganizerPriorities } from "../media-organizer";
export class LidarrIntegration extends Integration implements ICalendarIntegration {
@@ -44,22 +44,28 @@ export class LidarrIntegration extends Integration implements ICalendarIntegrati
const lidarrCalendarEvents = await z.array(lidarrCalendarEventSchema).parseAsync(await response.json());
return lidarrCalendarEvents.map((lidarrCalendarEvent): CalendarEvent => {
const imageSrc = this.chooseBestImage(lidarrCalendarEvent);
return {
name: lidarrCalendarEvent.title,
subName: lidarrCalendarEvent.artist.artistName,
description: lidarrCalendarEvent.overview,
thumbnail: this.chooseBestImageAsURL(lidarrCalendarEvent),
date: lidarrCalendarEvent.releaseDate,
mediaInformation: {
type: "audio",
},
title: lidarrCalendarEvent.title,
subTitle: lidarrCalendarEvent.artist.artistName,
description: lidarrCalendarEvent.overview ?? null,
startDate: lidarrCalendarEvent.releaseDate,
endDate: null,
image: imageSrc
? {
src: imageSrc.remoteUrl,
aspectRatio: { width: 7, height: 12 },
}
: null,
location: null,
indicatorColor: "cyan",
links: this.getLinksForLidarrCalendarEvent(lidarrCalendarEvent),
};
});
}
private getLinksForLidarrCalendarEvent = (event: z.infer<typeof lidarrCalendarEventSchema>) => {
const links: CalendarEvent["links"] = [];
const links: CalendarLink[] = [];
for (const link of event.artist.links) {
switch (link.name) {
@@ -70,7 +76,6 @@ export class LidarrIntegration extends Integration implements ICalendarIntegrati
color: "#f5c518",
isDark: false,
logo: "/images/apps/vgmdb.svg",
notificationColor: "cyan",
});
break;
case "imdb":
@@ -80,7 +85,6 @@ export class LidarrIntegration extends Integration implements ICalendarIntegrati
color: "#f5c518",
isDark: false,
logo: "/images/apps/imdb.png",
notificationColor: "cyan",
});
break;
case "last":
@@ -90,7 +94,6 @@ export class LidarrIntegration extends Integration implements ICalendarIntegrati
color: "#cf222a",
isDark: false,
logo: "/images/apps/lastfm.svg",
notificationColor: "cyan",
});
break;
}
@@ -1,15 +1,14 @@
import { z } from "zod/v4";
import { fetchWithTrustedCertificatesAsync } from "@homarr/certificates/server";
import type { AtLeastOneOf } from "@homarr/common/types";
import { logger } from "@homarr/log";
import { Integration } from "../../base/integration";
import type { IntegrationTestingInput } from "../../base/integration";
import { Integration } from "../../base/integration";
import { TestConnectionError } from "../../base/test-connection/test-connection-error";
import type { TestingResult } from "../../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../../interfaces/calendar/calendar-types";
import type { CalendarEvent, CalendarLink } from "../../interfaces/calendar/calendar-types";
import { radarrReleaseTypes } from "../../interfaces/calendar/calendar-types";
import { mediaOrganizerPriorities } from "../media-organizer";
@@ -34,33 +33,44 @@ export class RadarrIntegration extends Integration implements ICalendarIntegrati
});
const radarrCalendarEvents = await z.array(radarrCalendarEventSchema).parseAsync(await response.json());
return radarrCalendarEvents.map((radarrCalendarEvent): CalendarEvent => {
const dates = radarrReleaseTypes
.map((type) => (radarrCalendarEvent[type] ? { type, date: radarrCalendarEvent[type] } : undefined))
.filter((date) => date) as AtLeastOneOf<Exclude<CalendarEvent["dates"], undefined>[number]>;
return {
name: radarrCalendarEvent.title,
subName: radarrCalendarEvent.originalTitle,
description: radarrCalendarEvent.overview,
thumbnail: this.chooseBestImageAsURL(radarrCalendarEvent),
date: dates[0].date,
dates,
mediaInformation: {
type: "movie",
},
links: this.getLinksForRadarrCalendarEvent(radarrCalendarEvent),
};
return radarrCalendarEvents.flatMap((radarrCalendarEvent): CalendarEvent[] => {
const imageSrc = this.chooseBestImageAsURL(radarrCalendarEvent);
return radarrReleaseTypes
.map((releaseType) => ({ type: releaseType, date: radarrCalendarEvent[releaseType] }))
.filter((item) => item.date !== undefined)
.map((item) => ({
title: radarrCalendarEvent.title,
subTitle: radarrCalendarEvent.originalTitle,
description: radarrCalendarEvent.overview ?? null,
// Check is done above in the filter
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
startDate: item.date!,
endDate: null,
image: imageSrc
? {
src: imageSrc,
aspectRatio: { width: 7, height: 12 },
}
: null,
location: null,
metadata: {
type: "radarr",
releaseType: item.type,
},
indicatorColor: "yellow",
links: this.getLinksForRadarrCalendarEvent(radarrCalendarEvent),
}));
});
}
private getLinksForRadarrCalendarEvent = (event: z.infer<typeof radarrCalendarEventSchema>) => {
const links: CalendarEvent["links"] = [
const links: CalendarLink[] = [
{
href: this.url(`/movie/${event.titleSlug}`).toString(),
href: this.externalUrl(`/movie/${event.titleSlug}`).toString(),
name: "Radarr",
logo: "/images/apps/radarr.svg",
color: undefined,
notificationColor: "yellow",
isDark: true,
},
];
@@ -8,7 +8,7 @@ import type { IntegrationTestingInput } from "../../base/integration";
import { TestConnectionError } from "../../base/test-connection/test-connection-error";
import type { TestingResult } from "../../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../../interfaces/calendar/calendar-types";
import type { CalendarEvent, CalendarLink } from "../../interfaces/calendar/calendar-types";
import { mediaOrganizerPriorities } from "../media-organizer";
export class ReadarrIntegration extends Integration implements ICalendarIntegration {
@@ -50,15 +50,22 @@ export class ReadarrIntegration extends Integration implements ICalendarIntegrat
const readarrCalendarEvents = await z.array(readarrCalendarEventSchema).parseAsync(await response.json());
return readarrCalendarEvents.map((readarrCalendarEvent): CalendarEvent => {
const imageSrc = this.chooseBestImageAsURL(readarrCalendarEvent);
return {
name: readarrCalendarEvent.title,
subName: readarrCalendarEvent.author.authorName,
description: readarrCalendarEvent.overview,
thumbnail: this.chooseBestImageAsURL(readarrCalendarEvent),
date: readarrCalendarEvent.releaseDate,
mediaInformation: {
type: "audio",
},
title: readarrCalendarEvent.title,
subTitle: readarrCalendarEvent.author.authorName,
description: readarrCalendarEvent.overview ?? null,
startDate: readarrCalendarEvent.releaseDate,
endDate: null,
image: imageSrc
? {
src: imageSrc,
aspectRatio: { width: 7, height: 12 },
}
: null,
location: null,
indicatorColor: "#f5c518",
links: this.getLinksForReadarrCalendarEvent(readarrCalendarEvent),
};
});
@@ -67,14 +74,13 @@ export class ReadarrIntegration extends Integration implements ICalendarIntegrat
private getLinksForReadarrCalendarEvent = (event: z.infer<typeof readarrCalendarEventSchema>) => {
return [
{
href: this.url(`/author/${event.author.foreignAuthorId}`).toString(),
href: this.externalUrl(`/author/${event.author.foreignAuthorId}`).toString(),
color: "#f5c518",
isDark: false,
logo: "/images/apps/readarr.svg",
name: "Readarr",
notificationColor: "#f5c518",
},
] satisfies CalendarEvent["links"];
] satisfies CalendarLink[];
};
private chooseBestImage = (
@@ -95,7 +101,7 @@ export class ReadarrIntegration extends Integration implements ICalendarIntegrat
if (!bestImage) {
return undefined;
}
return this.url(bestImage.url as `/${string}`).toString();
return this.externalUrl(bestImage.url as `/${string}`).toString();
};
}
@@ -8,7 +8,7 @@ import type { IntegrationTestingInput } from "../../base/integration";
import { TestConnectionError } from "../../base/test-connection/test-connection-error";
import type { TestingResult } from "../../base/test-connection/test-connection-service";
import type { ICalendarIntegration } from "../../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../../interfaces/calendar/calendar-types";
import type { CalendarEvent, CalendarLink } from "../../interfaces/calendar/calendar-types";
import { mediaOrganizerPriorities } from "../media-organizer";
export class SonarrIntegration extends Integration implements ICalendarIntegration {
@@ -33,33 +33,40 @@ export class SonarrIntegration extends Integration implements ICalendarIntegrati
"X-Api-Key": super.getSecretValue("apiKey"),
},
});
const sonarCalendarEvents = await z.array(sonarrCalendarEventSchema).parseAsync(await response.json());
const sonarrCalendarEvents = await z.array(sonarrCalendarEventSchema).parseAsync(await response.json());
return sonarCalendarEvents.map(
(sonarCalendarEvent): CalendarEvent => ({
name: sonarCalendarEvent.title,
subName: sonarCalendarEvent.series.title,
description: sonarCalendarEvent.series.overview,
thumbnail: this.chooseBestImageAsURL(sonarCalendarEvent),
date: sonarCalendarEvent.airDateUtc,
mediaInformation: {
type: "tv",
episodeNumber: sonarCalendarEvent.episodeNumber,
seasonNumber: sonarCalendarEvent.seasonNumber,
},
links: this.getLinksForSonarCalendarEvent(sonarCalendarEvent),
}),
);
return sonarrCalendarEvents.map((event): CalendarEvent => {
const imageSrc = this.chooseBestImageAsURL(event);
return {
title: event.title,
subTitle: event.series.title,
description: event.series.overview ?? null,
startDate: event.airDateUtc,
endDate: null,
image: imageSrc
? {
src: imageSrc,
aspectRatio: { width: 7, height: 12 },
badge: {
color: "red",
content: `S${event.seasonNumber}/E${event.episodeNumber}`,
},
}
: null,
location: null,
indicatorColor: "blue",
links: this.getLinksForSonarrCalendarEvent(event),
};
});
}
private getLinksForSonarCalendarEvent = (event: z.infer<typeof sonarrCalendarEventSchema>) => {
const links: CalendarEvent["links"] = [
private getLinksForSonarrCalendarEvent = (event: z.infer<typeof sonarrCalendarEventSchema>) => {
const links: CalendarLink[] = [
{
href: this.url(`/series/${event.series.titleSlug}`).toString(),
href: this.externalUrl(`/series/${event.series.titleSlug}`).toString(),
name: "Sonarr",
logo: "/images/apps/sonarr.svg",
color: undefined,
notificationColor: "blue",
isDark: true,
},
];
+49 -32
View File
@@ -8,32 +8,46 @@ export class CalendarMockService implements ICalendarIntegration {
}
}
const homarrMeetup = (start: Date, end: Date): CalendarEvent => ({
name: "Homarr Meetup",
subName: "",
description: "Yearly meetup of the Homarr community",
date: randomDateBetween(start, end),
links: [
{
href: "https://homarr.dev",
name: "Homarr",
logo: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/homarr.svg",
color: "#000000",
notificationColor: "#fa5252",
isDark: true,
},
],
});
const homarrMeetup = (start: Date, end: Date): CalendarEvent => {
const startDate = randomDateBetween(start, end);
const endDate = new Date(startDate.getTime() + 2 * 60 * 60 * 1000); // 2 hours later
return {
title: "Homarr Meetup",
subTitle: "",
description: "Yearly meetup of the Homarr community",
startDate,
endDate,
image: null,
location: "Mountains",
indicatorColor: "#fa5252",
links: [
{
href: "https://homarr.dev",
name: "Homarr",
logo: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/homarr.svg",
color: "#000000",
isDark: true,
},
],
};
};
const titanicRelease = (start: Date, end: Date): CalendarEvent => ({
name: "Titanic",
subName: "A classic movie",
title: "Titanic",
subTitle: "A classic movie",
description: "A tragic love story set on the ill-fated RMS Titanic.",
date: randomDateBetween(start, end),
thumbnail: "https://image.tmdb.org/t/p/original/5bTWA20cL9LCIGNpde4Epc2Ijzn.jpg",
mediaInformation: {
type: "movie",
startDate: randomDateBetween(start, end),
endDate: null,
image: {
src: "https://image.tmdb.org/t/p/original/5bTWA20cL9LCIGNpde4Epc2Ijzn.jpg",
aspectRatio: { width: 7, height: 12 },
},
location: null,
metadata: {
type: "radarr",
releaseType: "inCinemas",
},
indicatorColor: "cyan",
links: [
{
href: "https://www.imdb.com/title/tt0120338/",
@@ -41,22 +55,26 @@ const titanicRelease = (start: Date, end: Date): CalendarEvent => ({
color: "#f5c518",
isDark: false,
logo: "/images/apps/imdb.svg",
notificationColor: "cyan",
},
],
});
const seriesRelease = (start: Date, end: Date): CalendarEvent => ({
name: "The Mandalorian",
subName: "A Star Wars Series",
title: "The Mandalorian",
subTitle: "A Star Wars Series",
description: "A lone bounty hunter in the outer reaches of the galaxy.",
date: randomDateBetween(start, end),
thumbnail: "https://image.tmdb.org/t/p/original/ztvm7C7hiUpS3CZRXFmJxljICzK.jpg",
mediaInformation: {
type: "tv",
seasonNumber: 1,
episodeNumber: 1,
startDate: randomDateBetween(start, end),
endDate: null,
image: {
src: "https://image.tmdb.org/t/p/original/sWgBv7LV2PRoQgkxwlibdGXKz1S.jpg",
aspectRatio: { width: 7, height: 12 },
badge: {
content: "S1/E1",
color: "red",
},
},
location: null,
indicatorColor: "blue",
links: [
{
href: "https://www.imdb.com/title/tt8111088/",
@@ -64,7 +82,6 @@ const seriesRelease = (start: Date, end: Date): CalendarEvent => ({
color: "#f5c518",
isDark: false,
logo: "/images/apps/imdb.svg",
notificationColor: "blue",
},
],
});
@@ -1,8 +1,13 @@
import { objectEntries } from "@homarr/common";
import type { IMediaRequestIntegration } from "../../interfaces/media-requests/media-request-integration";
import type { MediaInformation, MediaRequest, RequestStats, RequestUser } from "../../types";
import { MediaAvailability, MediaRequestStatus } from "../../types";
import type {
MediaAvailability,
MediaInformation,
MediaRequest,
MediaRequestStatus,
RequestStats,
RequestUser,
} from "../../types";
import { mediaAvailabilities, mediaRequestStatuses } from "../../types";
export class MediaRequestMockService implements IMediaRequestIntegration {
public async getSeriesInformationAsync(mediaType: "movie" | "tv", id: number): Promise<MediaInformation> {
@@ -86,12 +91,10 @@ export class MediaRequestMockService implements IMediaRequestIntegration {
}
private static randomAvailability(): MediaAvailability {
const values = objectEntries(MediaAvailability).filter(([key]) => typeof key === "number");
return values[Math.floor(Math.random() * values.length)]?.[1] ?? MediaAvailability.Available;
return mediaAvailabilities.at(Math.floor(Math.random() * mediaAvailabilities.length)) ?? "unknown";
}
private static randomStatus(): MediaRequestStatus {
const values = objectEntries(MediaRequestStatus).filter(([key]) => typeof key === "number");
return values[Math.floor(Math.random() * values.length)]?.[1] ?? MediaRequestStatus.PendingApproval;
return mediaRequestStatuses.at(Math.floor(Math.random() * mediaRequestStatuses.length)) ?? "pending";
}
}
@@ -28,6 +28,7 @@ export class MediaServerMockService implements IMediaServerIntegration {
episodeName: null,
albumName: null,
episodeCount: null,
metadata: null,
}
: null,
};
@@ -1,4 +1,7 @@
import type { Agent } from "https";
import dayjs from "dayjs";
import timezone from "dayjs/plugin/timezone";
import utc from "dayjs/plugin/utc";
import type { RequestInit as NodeFetchRequestInit } from "node-fetch";
import * as ical from "node-ical";
import { DAVClient } from "tsdav";
@@ -14,6 +17,9 @@ import type { TestingResult } from "../base/test-connection/test-connection-serv
import type { ICalendarIntegration } from "../interfaces/calendar/calendar-integration";
import type { CalendarEvent } from "../interfaces/calendar/calendar-types";
dayjs.extend(utc);
dayjs.extend(timezone);
@HandleIntegrationErrors([integrationTsdavHttpErrorHandler])
export class NextcloudIntegration extends Integration implements ICalendarIntegration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
@@ -41,44 +47,59 @@ export class NextcloudIntegration extends Integration implements ICalendarIntegr
)
).flat();
return calendarEvents.map((event): CalendarEvent => {
// @ts-expect-error the typescript definitions for this package are wrong
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
const icalData = ical.default.parseICS(event.data) as ical.CalendarResponse;
const veventObject = Object.values(icalData).find((data) => data.type === "VEVENT");
return calendarEvents
.map((event) => {
// @ts-expect-error the typescript definitions for this package are wrong
// eslint-disable-next-line @typescript-eslint/no-unsafe-call,@typescript-eslint/no-unsafe-member-access
const icalData = ical.default.parseICS(event.data) as ical.CalendarResponse;
const veventObject = Object.values(icalData).find((data) => data.type === "VEVENT");
if (!veventObject) {
throw new Error(`Invalid event data object: ${JSON.stringify(event.data)}. Unable to process the calendar.`);
}
if (!veventObject) {
throw new Error(`Invalid event data object: ${JSON.stringify(event.data)}. Unable to process the calendar.`);
}
logger.debug(`Converting VEVENT event to ${event.etag} from Nextcloud: ${JSON.stringify(veventObject)}`);
logger.debug(`Converting VEVENT event to ${event.etag} from Nextcloud: ${JSON.stringify(veventObject)}`);
const date = veventObject.start;
const eventUrlWithoutHost = new URL(event.url).pathname;
const eventSlug = Buffer.from(eventUrlWithoutHost).toString("base64url");
const eventUrlWithoutHost = new URL(event.url).pathname;
const dateInMillis = veventObject.start.valueOf();
const startDates = veventObject.rrule ? veventObject.rrule.between(start, end) : [veventObject.start];
const url = this.url(
`/apps/calendar/timeGridWeek/now/edit/sidebar/${Buffer.from(eventUrlWithoutHost).toString("base64url")}/${dateInMillis / 1000}`,
);
const durationMs = veventObject.end.getTime() - veventObject.start.getTime();
return {
name: veventObject.summary,
date,
subName: "",
description: veventObject.description,
links: [
{
href: url.toString(),
name: "Nextcloud",
logo: "/images/apps/nextcloud.svg",
color: undefined,
notificationColor: "#ff8600",
isDark: true,
},
],
};
});
return startDates.map((startDate) => {
const timezoneOffsetMinutes = veventObject.rrule?.origOptions.tzid
? dayjs(startDate).tz(veventObject.rrule.origOptions.tzid).utcOffset()
: 0;
const utcStartDate = new Date(startDate.getTime() - timezoneOffsetMinutes * 60 * 1000);
const endDate = new Date(utcStartDate.getTime() + durationMs);
const dateInMillis = utcStartDate.valueOf();
return {
title: veventObject.summary,
subTitle: null,
description: veventObject.description,
startDate: utcStartDate,
endDate,
image: null,
location: veventObject.location || null,
indicatorColor:
"color" in veventObject && typeof veventObject.color === "string" ? veventObject.color : "#ff8600",
links: [
{
href: this.externalUrl(
`/apps/calendar/timeGridWeek/now/edit/sidebar/${eventSlug}/${dateInMillis / 1000}`,
).toString(),
name: "Nextcloud",
logo: "/images/apps/nextcloud.svg",
color: undefined,
isDark: true,
},
],
};
});
})
.flat();
}
private async createCalendarClientAsync(agent?: Agent) {
@@ -6,7 +6,7 @@ import { TestConnectionError } from "../base/test-connection/test-connection-err
import type { TestingResult } from "../base/test-connection/test-connection-service";
import type { ReleasesProviderIntegration } from "../interfaces/releases-providers/releases-providers-integration";
import { getLatestRelease } from "../interfaces/releases-providers/releases-providers-integration";
import type { ReleasesRepository, ReleasesResponse } from "../interfaces/releases-providers/releases-providers-types";
import type { ReleaseResponse } from "../interfaces/releases-providers/releases-providers-types";
import { releasesResponseSchema } from "./npm-schemas";
export class NPMIntegration extends Integration implements ReleasesProviderIntegration {
@@ -22,35 +22,35 @@ export class NPMIntegration extends Integration implements ReleasesProviderInteg
};
}
public async getLatestMatchingReleaseAsync(repository: ReleasesRepository): Promise<ReleasesResponse> {
const releasesResponse = await fetchWithTrustedCertificatesAsync(
this.url(`/${encodeURIComponent(repository.identifier)}`),
);
public async getLatestMatchingReleaseAsync(identifier: string, versionRegex?: string): Promise<ReleaseResponse> {
if (!identifier) return { success: false, error: { code: "invalidIdentifier" } };
const releasesResponse = await fetchWithTrustedCertificatesAsync(this.url(`/${encodeURIComponent(identifier)}`));
if (!releasesResponse.ok) {
return {
id: repository.id,
error: { message: releasesResponse.statusText },
};
return { success: false, error: { code: "unexpected", message: releasesResponse.statusText } };
}
const releasesResponseJson: unknown = await releasesResponse.json();
const { data, success, error } = releasesResponseSchema.safeParse(releasesResponseJson);
if (!success) {
return {
id: repository.id,
success: false,
error: {
code: "unexpected",
message: releasesResponseJson ? JSON.stringify(releasesResponseJson, null, 2) : error.message,
},
};
} else {
const formattedReleases = data.time.map((tag) => ({
...tag,
releaseUrl: `https://www.npmjs.com/package/${encodeURIComponent(data.name)}/v/${encodeURIComponent(tag.latestRelease)}`,
releaseDescription: data.versions[tag.latestRelease]?.description ?? "",
}));
return getLatestRelease(formattedReleases, repository);
}
const formattedReleases = data.time.map((tag) => ({
...tag,
releaseUrl: `https://www.npmjs.com/package/${encodeURIComponent(data.name)}/v/${encodeURIComponent(tag.latestRelease)}`,
releaseDescription: data.versions[tag.latestRelease]?.description ?? "",
}));
const latestRelease = getLatestRelease(formattedReleases, versionRegex);
if (!latestRelease) return { success: false, error: { code: "noMatchingVersion" } };
return { success: true, data: latestRelease };
}
}
Loaded 100 of 309 files, more files were not shown because too many files have changed in this diff. Show more