feat: add Uptime Kuma, Audiobookshelf, Paperless-ngx, and Navidrome integrations (#5910)

This commit is contained in:
Thomas authored and GitHub committed 2026-06-10 18:27:24 +02:00
1 parent a4db9cf0dc
commit d77c6f8d4e
46 files changed
+2994 -16

No files matched your search

@@ -0,0 +1,133 @@
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
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 {
audiobookshelfLibrariesResponseSchema,
audiobookshelfLibraryStatsSchema,
audiobookshelfListeningStatsSchema,
audiobookshelfOnlineUsersResponseSchema,
} from "./audiobookshelf-types";
import type {
AudiobookshelfDashboardData,
AudiobookshelfLibrary,
AudiobookshelfLibraryStats,
} from "./audiobookshelf-types";
const mediaTypeCountField = {
book: "totalAudiobooks",
podcast: "totalPodcasts",
} as const satisfies Record<
AudiobookshelfLibrary["mediaType"],
keyof Pick<AudiobookshelfDashboardData, "totalAudiobooks" | "totalPodcasts">
>;
export class AudiobookshelfIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const healthResponse = await input.fetchAsync(this.url("/healthcheck"));
if (!healthResponse.ok) {
return TestConnectionError.StatusResult(healthResponse);
}
const authorizeResponse = await input.fetchAsync(this.url("/api/authorize"), {
method: "POST",
headers: this.getAuthHeaders(),
});
if (!authorizeResponse.ok) {
return TestConnectionError.StatusResult(authorizeResponse);
}
return { success: true };
}
public async getDashboardDataAsync(): Promise<AudiobookshelfDashboardData> {
const [libraries, listeningStats, activeSessions] = await Promise.all([
this.getLibrariesAsync(),
this.getListeningStatsAsync(),
this.getActiveSessionsCountAsync(),
]);
const statsByLibrary = await Promise.all(
libraries.map(async (library) => ({
mediaType: library.mediaType,
stats: await this.getLibraryStatsAsync(library.id),
})),
);
const counts = {
totalAudiobooks: 0,
totalPodcasts: 0,
};
for (const item of statsByLibrary) {
const countField = mediaTypeCountField[item.mediaType];
counts[countField] += item.stats.totalItems;
}
return {
libraryCount: libraries.length,
totalAudiobooks: counts.totalAudiobooks,
totalPodcasts: counts.totalPodcasts,
totalListeningTimeSeconds: listeningStats.totalTime,
activeSessions,
};
}
private async getLibrariesAsync(): Promise<AudiobookshelfLibrary[]> {
const response = await this.getAsync("/api/libraries");
if (!response.ok) {
throw new ResponseError(response);
}
return audiobookshelfLibrariesResponseSchema.parse(await response.json()).libraries;
}
private async getLibraryStatsAsync(libraryId: string): Promise<AudiobookshelfLibraryStats> {
const response = await this.getAsync(`/api/libraries/${libraryId}/stats`);
if (!response.ok) {
throw new ResponseError(response);
}
return audiobookshelfLibraryStatsSchema.parse(await response.json());
}
private async getListeningStatsAsync() {
const response = await this.getAsync("/api/me/listening-stats");
if (!response.ok) {
throw new ResponseError(response);
}
return audiobookshelfListeningStatsSchema.parse(await response.json());
}
private async getActiveSessionsCountAsync(): Promise<number> {
const response = await this.getAsync("/api/users/online");
if (!response.ok) {
throw new ResponseError(response);
}
return audiobookshelfOnlineUsersResponseSchema.parse(await response.json()).openSessions.length;
}
private async getAsync(path: `/api/${string}` | "/healthcheck") {
return await fetchWithTrustedCertificatesAsync(this.url(path), {
headers: this.getAuthHeaders(),
});
}
private getAuthHeaders(): Record<string, string> {
return {
Authorization: `Bearer ${this.getSecretValue("apiKey")}`,
Accept: "application/json",
};
}
}
@@ -0,0 +1,36 @@
import { z } from "zod/v4";
export const audiobookshelfLibrarySchema = z.object({
id: z.string(),
name: z.string(),
mediaType: z.enum(["book", "podcast"]),
});
export const audiobookshelfLibrariesResponseSchema = z.object({
libraries: z.array(audiobookshelfLibrarySchema),
});
export const audiobookshelfLibraryStatsSchema = z.object({
totalItems: z.number(),
totalDuration: z.number().optional(),
totalSize: z.number().optional(),
});
export const audiobookshelfListeningStatsSchema = z.object({
totalTime: z.number(),
});
export const audiobookshelfOnlineUsersResponseSchema = z.object({
openSessions: z.array(z.unknown()),
});
export interface AudiobookshelfDashboardData {
libraryCount: number;
totalAudiobooks: number;
totalPodcasts: number;
totalListeningTimeSeconds: number;
activeSessions: number;
}
export type AudiobookshelfLibrary = z.infer<typeof audiobookshelfLibrarySchema>;
export type AudiobookshelfLibraryStats = z.infer<typeof audiobookshelfLibraryStatsSchema>;
@@ -3,6 +3,7 @@ import type { IntegrationKind } from "@homarr/definitions";
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
import { BeszelIntegration } from "../beszel/beszel-integration";
import { AnchorIntegration } from "../anchor/anchor-integration";
import { AudiobookshelfIntegration } from "../audiobookshelf/audiobookshelf-integration";
import { CodebergIntegration } from "../codeberg/codeberg-integration";
import { CoolifyIntegration } from "../coolify/coolify-integration";
import { DashDotIntegration } from "../dashdot/dashdot-integration";
@@ -31,12 +32,14 @@ import { ReadarrIntegration } from "../media-organizer/readarr/readarr-integrati
import { SonarrIntegration } from "../media-organizer/sonarr/sonarr-integration";
import { TdarrIntegration } from "../media-transcoding/tdarr-integration";
import { MockIntegration } from "../mock/mock-integration";
import { NavidromeIntegration } from "../navidrome/navidrome-integration";
import { NextcloudIntegration } from "../nextcloud/nextcloud.integration";
import { NPMIntegration } from "../npm/npm-integration";
import { NTFYIntegration } from "../ntfy/ntfy-integration";
import { OpenMediaVaultIntegration } from "../openmediavault/openmediavault-integration";
import { OPNsenseIntegration } from "../opnsense/opnsense-integration";
import { OverseerrIntegration } from "../overseerr/overseerr-integration";
import { PaperlessNgxIntegration } from "../paperless-ngx/paperless-ngx-integration";
import { PeaNutIntegration } from "../peanut/peanut-integration";
import { createPiHoleIntegrationAsync } from "../pi-hole/pi-hole-integration-factory";
import { PlexIntegration } from "../plex/plex-integration";
@@ -49,6 +52,7 @@ import { SpeedtestTrackerIntegration } from "../speedtest-tracker/speedtest-trac
import { TracearrIntegration } from "../tracearr/tracearr-integration";
import { TrueNasIntegration } from "../truenas/truenas-integration";
import { UmamiIntegration } from "../umami/umami-integration";
import { UptimeKumaIntegration } from "../uptime-kuma/uptime-kuma-integration";
import { UnifiControllerIntegration } from "../unifi-controller/unifi-controller-integration";
import { UnraidIntegration } from "../unraid/unraid-integration";
import type { Integration, IntegrationInput } from "./integration";
@@ -123,8 +127,12 @@ export const integrationCreators = {
glances: GlancesIntegration,
searchCh: SearchChIntegration,
immich: ImmichIntegration,
paperlessNgx: PaperlessNgxIntegration,
speedtestTracker: SpeedtestTrackerIntegration,
audiobookshelf: AudiobookshelfIntegration,
navidrome: NavidromeIntegration,
umami: UmamiIntegration,
uptimeKuma: UptimeKumaIntegration,
peaNut: PeaNutIntegration,
beszel: BeszelIntegration,
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
+7
View File
@@ -33,6 +33,9 @@ export { CoolifyIntegration } from "./coolify/coolify-integration";
export { ImmichIntegration } from "./immich/immich-integration";
export { TracearrIntegration } from "./tracearr/tracearr-integration";
export { SpeedtestTrackerIntegration } from "./speedtest-tracker/speedtest-tracker-integration";
export { AudiobookshelfIntegration } from "./audiobookshelf/audiobookshelf-integration";
export { NavidromeIntegration } from "./navidrome/navidrome-integration";
export { UptimeKumaIntegration } from "./uptime-kuma/uptime-kuma-integration";
export { UmamiIntegration } from "./umami/umami-integration";
export { PeaNutIntegration } from "./peanut/peanut-integration";
@@ -61,6 +64,7 @@ export type {
export type { ReleasesRepository, ReleaseResponse } from "./interfaces/releases-providers/releases-providers-types";
export type { Notification } from "./interfaces/notifications/notification-types";
export type { ImmichServerStats, ImmichAlbum, ImmichAsset } from "./immich/immich-integration";
export type { PaperlessNgxStats } from "./paperless-ngx/paperless-ngx-types";
export type {
AnchorNote,
AnchorNotePermission,
@@ -70,6 +74,9 @@ export type {
} from "./anchor/anchor-types";
export type { TracearrDashboardData } from "./tracearr/tracearr-types";
export type { SpeedtestTrackerDashboardData } from "./speedtest-tracker/speedtest-tracker-types";
export type { AudiobookshelfDashboardData } from "./audiobookshelf/audiobookshelf-types";
export type { NavidromeDashboardData } from "./navidrome/navidrome-types";
export type { UptimeKumaDashboardData } from "./uptime-kuma/uptime-kuma-types";
export type { UmamiVisitorStats } from "./umami/umami-types";
// Schemas
@@ -0,0 +1,171 @@
import { ParseError, ResponseError } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
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 { NavidromeDashboardData, NavidromeNowPlayingEntry, SubsonicResponseBody } from "./navidrome-types";
import { subsonicResponseSchema } from "./navidrome-types";
const logger = createLogger({ module: "navidromeIntegration" });
const subsonicVersion = "1.16.1";
const subsonicClient = "homarr";
const albumListPageSize = 500;
const maxAlbumListPages = 20;
const emptyLibraryMessage = "Library not found or empty";
const subsonicAuthErrorCodes = new Set([40, 41]);
const asArray = <TValue>(value: TValue | TValue[] | undefined): TValue[] =>
[value].flat().filter((item): item is TValue => item !== undefined);
export class NavidromeIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const url = this.url("/rest/ping.view", this.getAuthParams());
const response = await input.fetchAsync(url);
if (!response.ok) {
return TestConnectionError.StatusResult(response);
}
const parsed = subsonicResponseSchema.safeParse(await response.json());
if (!parsed.success) {
return TestConnectionError.ParseResult(new ParseError("Invalid Subsonic response", { cause: parsed.error }));
}
const subsonicResponse = parsed.data["subsonic-response"];
if (subsonicResponse.status === "failed") {
const errorCode = subsonicResponse.error?.code;
if (errorCode !== undefined && subsonicAuthErrorCodes.has(errorCode)) {
return TestConnectionError.UnauthorizedResult(401);
}
return TestConnectionError.UnknownResult(new Error(subsonicResponse.error?.message ?? "Subsonic request failed"));
}
return { success: true };
}
public async getDashboardDataAsync(): Promise<NavidromeDashboardData> {
const [artistCount, libraryCounts, nowPlaying] = await Promise.all([
this.getArtistCountAsync(),
this.getAlbumAndSongCountsAsync(),
this.getNowPlayingAsync(),
]);
return {
artistCount,
albumCount: libraryCounts.albumCount,
songCount: libraryCounts.songCount,
nowPlaying,
};
}
private async getArtistCountAsync(): Promise<number> {
const response = await this.subsonicRequestAsync("/rest/getArtists.view", {}, { tolerateEmptyLibrary: true });
return asArray(response.artists?.index).reduce((count, index) => count + asArray(index.artist).length, 0);
}
private async getAlbumAndSongCountsAsync(): Promise<{ albumCount: number; songCount: number }> {
let offset = 0;
let albumCount = 0;
let songCount = 0;
let page = 0;
while (page < maxAlbumListPages) {
const response = await this.subsonicRequestAsync(
"/rest/getAlbumList2.view",
{
type: "alphabeticalByName",
size: albumListPageSize,
offset,
},
{ tolerateEmptyLibrary: true },
);
const albums = asArray(response.albumList2?.album);
if (albums.length === 0) {
break;
}
albumCount += albums.length;
for (const album of albums) {
songCount += album.songCount ?? 0;
}
if (albums.length < albumListPageSize) {
break;
}
offset += albumListPageSize;
page += 1;
}
if (page >= maxAlbumListPages) {
logger.warn("Reached Navidrome album list page limit", {
integrationId: this.integration.id,
maxPages: maxAlbumListPages,
albumCount,
});
}
return { albumCount, songCount };
}
private async getNowPlayingAsync(): Promise<NavidromeNowPlayingEntry[]> {
const response = await this.subsonicRequestAsync("/rest/getNowPlaying.view", {}, { tolerateEmptyLibrary: true });
return asArray(response.nowPlaying?.entry).map((entry) => ({
title: entry.title ?? "",
artist: entry.artist ?? "",
album: entry.album ?? "",
username: entry.username ?? "",
playerName: entry.playerName ?? "",
}));
}
private async subsonicRequestAsync(
path: `/rest/${string}`,
params: Record<string, string | number> = {},
options: { tolerateEmptyLibrary?: boolean } = {},
): Promise<SubsonicResponseBody> {
const url = this.url(path, { ...this.getAuthParams(), ...params });
const response = await fetchWithTrustedCertificatesAsync(url);
if (!response.ok) {
throw new ResponseError(response);
}
const parsed = subsonicResponseSchema.parse(await response.json());
const subsonicResponse = parsed["subsonic-response"];
if (subsonicResponse.status === "failed") {
const message = subsonicResponse.error?.message ?? "Subsonic request failed";
if (options.tolerateEmptyLibrary && message === emptyLibraryMessage) {
return subsonicResponse;
}
throw new Error(message);
}
return subsonicResponse;
}
private getAuthParams(): Record<string, string> {
return {
u: this.getSecretValue("username"),
p: this.getSecretValue("password"),
v: subsonicVersion,
c: subsonicClient,
f: "json",
};
}
}
@@ -0,0 +1,71 @@
import { z } from "zod/v4";
const subsonicArtistSchema = z.object({
id: z.string(),
name: z.string(),
albumCount: z.number().optional(),
});
const subsonicIndexSchema = z.object({
name: z.string(),
artist: z.union([subsonicArtistSchema, z.array(subsonicArtistSchema)]).optional(),
});
const subsonicAlbumSchema = z.object({
id: z.string(),
name: z.string(),
songCount: z.number().optional(),
});
const subsonicNowPlayingEntrySchema = z.object({
title: z.string().optional(),
artist: z.string().optional(),
album: z.string().optional(),
username: z.string().optional(),
playerName: z.string().optional(),
});
export const subsonicResponseSchema = z.object({
"subsonic-response": z.object({
status: z.enum(["ok", "failed"]),
version: z.string().optional(),
error: z
.object({
code: z.number(),
message: z.string(),
})
.optional(),
artists: z
.object({
index: z.union([subsonicIndexSchema, z.array(subsonicIndexSchema)]).optional(),
})
.optional(),
albumList2: z
.object({
album: z.union([subsonicAlbumSchema, z.array(subsonicAlbumSchema)]).optional(),
})
.optional(),
nowPlaying: z
.object({
entry: z.union([subsonicNowPlayingEntrySchema, z.array(subsonicNowPlayingEntrySchema)]).optional(),
})
.optional(),
}),
});
export type SubsonicResponseBody = z.infer<typeof subsonicResponseSchema>["subsonic-response"];
export interface NavidromeNowPlayingEntry {
title: string;
artist: string;
album: string;
username: string;
playerName: string;
}
export interface NavidromeDashboardData {
artistCount: number;
albumCount: number;
songCount: number;
nowPlaying: NavidromeNowPlayingEntry[];
}
@@ -0,0 +1,201 @@
import { Response } from "undici";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationSecret } from "../../base/types";
import { NavidromeIntegration } from "../navidrome-integration";
vi.mock("@homarr/core/infrastructure/http", () => ({
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
const TEST_URL = "https://navidrome.example.com";
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
const secrets: IntegrationSecret[] = [
{ kind: "username", value: "admin" },
{ kind: "password", value: "secret" },
];
const toUrlString = (url: unknown): string => String(url);
const createIntegration = () =>
new NavidromeIntegration({
id: "test-navidrome",
name: "Test Navidrome",
url: TEST_URL,
externalUrl: null,
decryptedSecrets: secrets,
});
const subsonicOk = <T extends Record<string, unknown>>(data: T) =>
JSON.stringify({
"subsonic-response": { status: "ok", version: "1.16.1", ...data },
});
const subsonicFailed = (message: string) =>
JSON.stringify({
"subsonic-response": { status: "failed", error: { code: 70, message } },
});
beforeEach(() => {
mockFetch.mockReset();
});
describe("NavidromeIntegration.getDashboardDataAsync", () => {
test("paginates album list and counts songs", async () => {
const makeAlbums = (count: number, songCount: number) =>
Array.from({ length: count }, (_, i) => ({
id: `album-${i}`,
name: `Album ${i}`,
songCount,
}));
mockFetch.mockImplementation((url) => {
const urlStr = toUrlString(url);
if (urlStr.includes("getArtists")) {
return Promise.resolve(
new Response(subsonicOk({ artists: { index: [{ name: "A", artist: [{ id: "1", name: "Artist" }] }] } }), {
status: 200,
}),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
if (urlStr.includes("getAlbumList2")) {
const offsetMatch = urlStr.match(/offset=(\d+)/);
const offset = Number(offsetMatch?.[1] ?? 0);
if (offset === 0) {
return Promise.resolve(
new Response(subsonicOk({ albumList2: { album: makeAlbums(500, 10) } }), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
if (offset === 500) {
return Promise.resolve(
new Response(subsonicOk({ albumList2: { album: makeAlbums(200, 5) } }), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
return Promise.resolve(new Response(subsonicOk({ albumList2: {} }), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
}
if (urlStr.includes("getNowPlaying")) {
return Promise.resolve(new Response(subsonicOk({ nowPlaying: {} }), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
}
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
});
const integration = createIntegration();
const result = await integration.getDashboardDataAsync();
expect(result.albumCount).toBe(700);
expect(result.songCount).toBe(500 * 10 + 200 * 5);
expect(result.artistCount).toBe(1);
expect(result.nowPlaying).toEqual([]);
});
test("handles empty library gracefully", async () => {
mockFetch.mockImplementation((url) => {
const urlStr = toUrlString(url);
if (urlStr.includes("getArtists")) {
return Promise.resolve(
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
if (urlStr.includes("getAlbumList2")) {
return Promise.resolve(
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
if (urlStr.includes("getNowPlaying")) {
return Promise.resolve(
new Response(subsonicFailed("Library not found or empty"), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
});
const integration = createIntegration();
const result = await integration.getDashboardDataAsync();
expect(result.artistCount).toBe(0);
expect(result.albumCount).toBe(0);
expect(result.songCount).toBe(0);
expect(result.nowPlaying).toEqual([]);
});
test("throws on non-empty-library subsonic error", async () => {
mockFetch.mockImplementation(
() =>
Promise.resolve(new Response(subsonicFailed("Permission denied"), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>,
);
const integration = createIntegration();
await expect(integration.getDashboardDataAsync()).rejects.toThrow();
});
test("now playing maps entries correctly", async () => {
mockFetch.mockImplementation((url) => {
const urlStr = toUrlString(url);
if (urlStr.includes("getNowPlaying")) {
return Promise.resolve(
new Response(
subsonicOk({
nowPlaying: {
entry: { title: "Song", artist: "Band", album: "LP", username: "user1", playerName: "Chrome" },
},
}),
{ status: 200 },
),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
if (urlStr.includes("getArtists")) {
return Promise.resolve(new Response(subsonicOk({ artists: {} }), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
}
if (urlStr.includes("getAlbumList2")) {
return Promise.resolve(new Response(subsonicOk({ albumList2: {} }), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
}
return Promise.resolve(new Response(subsonicOk({}), { status: 200 })) as unknown as ReturnType<
typeof fetchWithTrustedCertificatesAsync
>;
});
const integration = createIntegration();
const result = await integration.getDashboardDataAsync();
expect(result.nowPlaying).toHaveLength(1);
expect(result.nowPlaying[0]).toEqual({
title: "Song",
artist: "Band",
album: "LP",
username: "user1",
playerName: "Chrome",
});
});
});
@@ -0,0 +1,67 @@
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
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 { PaperlessNgxStats } from "./paperless-ngx-types";
import { paperlessNgxPaginatedCountSchema, paperlessNgxStatisticsSchema } from "./paperless-ngx-types";
export class PaperlessNgxIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const statisticsUrl = this.url("/api/statistics/");
const statisticsResponse = await input.fetchAsync(statisticsUrl, {
headers: this.getAuthHeaders(),
});
if (!statisticsResponse.ok) {
return TestConnectionError.StatusResult(statisticsResponse);
}
return { success: true };
}
public async getStatsAsync(): Promise<PaperlessNgxStats> {
const [statistics, tags, correspondents, documentTypes] = await Promise.all([
this.fetchStatisticsAsync(),
this.fetchCountAsync("/api/tags/"),
this.fetchCountAsync("/api/correspondents/"),
this.fetchCountAsync("/api/document_types/"),
]);
return {
documentsTotal: statistics.documents_total,
documentsInbox: statistics.documents_inbox,
correspondentsCount: correspondents,
tagsCount: tags,
documentTypesCount: documentTypes,
};
}
private async fetchAuthenticatedAsync(path: `/${string}`) {
const response = await fetchWithTrustedCertificatesAsync(this.url(path), {
headers: this.getAuthHeaders(),
});
if (!response.ok) {
throw new ResponseError(response);
}
return response;
}
private async fetchStatisticsAsync() {
const response = await this.fetchAuthenticatedAsync("/api/statistics/");
return paperlessNgxStatisticsSchema.parse(await response.json());
}
private async fetchCountAsync(path: `/${string}`) {
const response = await this.fetchAuthenticatedAsync(path);
return paperlessNgxPaginatedCountSchema.parse(await response.json()).count;
}
private getAuthHeaders(): Record<string, string> {
return {
Authorization: `Token ${this.getSecretValue("apiKey")}`,
};
}
}
@@ -0,0 +1,21 @@
import { z } from "zod/v4";
export const paperlessNgxStatisticsSchema = z.object({
documents_total: z.number(),
documents_inbox: z
.number()
.nullable()
.transform((value) => value ?? 0),
});
export const paperlessNgxPaginatedCountSchema = z.object({
count: z.number(),
});
export interface PaperlessNgxStats {
documentsTotal: number;
documentsInbox: number;
correspondentsCount: number;
tagsCount: number;
documentTypesCount: number;
}
+4
View File
@@ -17,5 +17,9 @@ export * from "./anchor/anchor-types";
export * from "./interfaces/timetable/timetable-types";
export * from "./tracearr/tracearr-types";
export * from "./speedtest-tracker/speedtest-tracker-types";
export * from "./uptime-kuma/uptime-kuma-types";
export * from "./audiobookshelf/audiobookshelf-types";
export * from "./navidrome/navidrome-types";
export * from "./paperless-ngx/paperless-ngx-types";
export * from "./umami/umami-types";
export * from "./beszel/beszel-types";
@@ -0,0 +1,162 @@
import { Response } from "undici";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import type { IntegrationSecret } from "../../base/types";
import { UptimeKumaIntegration } from "../uptime-kuma-integration";
import { uptimeKumaHeartbeatCategoryMap } from "../uptime-kuma-types";
vi.mock("@homarr/core/infrastructure/http", () => ({
fetchWithTrustedCertificatesAsync: vi.fn(),
}));
const TEST_URL = "https://uptime.example.com";
const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);
const toUrlString = (url: unknown): string => String(url);
const createIntegration = (secrets: IntegrationSecret[] = []) =>
new UptimeKumaIntegration({
id: "test-uptime-kuma",
name: "Test Uptime Kuma",
url: TEST_URL,
externalUrl: null,
decryptedSecrets: secrets,
});
beforeEach(() => {
mockFetch.mockReset();
});
describe("uptimeKumaHeartbeatCategoryMap", () => {
test("maps status 0 (down) to 'down'", () => {
expect(uptimeKumaHeartbeatCategoryMap[0]).toBe("down");
});
test("maps status 1 (up) to 'up'", () => {
expect(uptimeKumaHeartbeatCategoryMap[1]).toBe("up");
});
test("maps status 2 (pending) to 'paused'", () => {
expect(uptimeKumaHeartbeatCategoryMap[2]).toBe("paused");
});
test("maps status 3 (maintenance) to 'paused'", () => {
expect(uptimeKumaHeartbeatCategoryMap[3]).toBe("paused");
});
test("returns undefined for unknown status codes", () => {
expect(uptimeKumaHeartbeatCategoryMap[99]).toBeUndefined();
});
});
describe("UptimeKumaIntegration.getDashboardDataAsync", () => {
const statusPageResponse = {
publicGroupList: [
{
id: 1,
name: "Services",
monitorList: [
{ id: 10, name: "Web" },
{ id: 20, name: "API" },
{ id: 30, name: "DB" },
],
},
],
};
const heartbeatResponse = {
heartbeatList: {
"10": [{ status: 1, time: "2025-01-01" }],
"20": [{ status: 0, time: "2025-01-01" }],
"30": [{ status: 2, time: "2025-01-01" }],
},
uptimeList: {
"10_24": 0.995,
"20_24": 0.5,
"30_24": 0.8,
},
};
const mockResponses = () => {
mockFetch.mockImplementation((url) => {
const urlStr = toUrlString(url);
if (urlStr.includes("/heartbeat/")) {
return Promise.resolve(
new Response(JSON.stringify(heartbeatResponse), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
return Promise.resolve(
new Response(JSON.stringify(statusPageResponse), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
});
};
test("aggregates monitor counts correctly", async () => {
mockResponses();
const integration = createIntegration([{ kind: "slug", value: "default" }]);
const result = await integration.getDashboardDataAsync();
expect(result.totalMonitors).toBe(3);
expect(result.upCount).toBe(1);
expect(result.downCount).toBe(1);
expect(result.pausedCount).toBe(1);
});
test("computes average uptime from uptimeList", async () => {
mockResponses();
const integration = createIntegration([{ kind: "slug", value: "default" }]);
const result = await integration.getDashboardDataAsync();
const expectedAverage = ((0.995 + 0.5 + 0.8) * 100) / 3;
expect(result.averageUptimePercent).toBeCloseTo(expectedAverage, 5);
});
test("defaults unknown heartbeat status to 'down'", async () => {
const unknownHeartbeat = {
heartbeatList: { "10": [{ status: 99, time: "2025-01-01" }] },
uptimeList: { "10_24": 1 },
};
mockFetch.mockImplementation((url) => {
const urlStr = toUrlString(url);
if (urlStr.includes("/heartbeat/")) {
return Promise.resolve(
new Response(JSON.stringify(unknownHeartbeat), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
}
return Promise.resolve(
new Response(
JSON.stringify({
publicGroupList: [{ id: 1, name: "G", monitorList: [{ id: 10, name: "Svc" }] }],
}),
{ status: 200 },
),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;
});
const integration = createIntegration([{ kind: "slug", value: "default" }]);
const result = await integration.getDashboardDataAsync();
expect(result.monitors[0]?.status).toBe("down");
expect(result.downCount).toBe(1);
});
test("handles empty monitor list gracefully", async () => {
mockFetch.mockImplementation(
() =>
Promise.resolve(
new Response(JSON.stringify({ publicGroupList: [], heartbeatList: {}, uptimeList: {} }), { status: 200 }),
) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>,
);
const integration = createIntegration([{ kind: "slug", value: "default" }]);
const result = await integration.getDashboardDataAsync();
expect(result.totalMonitors).toBe(0);
expect(result.averageUptimePercent).toBe(0);
});
});
@@ -0,0 +1,140 @@
import { ParseError, ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
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 {
uptimeKumaHeartbeatCategoryMap,
uptimeKumaHeartbeatResponseSchema,
uptimeKumaStatusPageResponseSchema,
} from "./uptime-kuma-types";
import type { UptimeKumaDashboardData, UptimeKumaMonitor, UptimeKumaMonitorCategory } from "./uptime-kuma-types";
export class UptimeKumaIntegration extends Integration {
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
const statusPageResponse = await input.fetchAsync(this.statusPageUrl());
if (!statusPageResponse.ok) {
return TestConnectionError.StatusResult(statusPageResponse);
}
const statusPageParsed = uptimeKumaStatusPageResponseSchema.safeParse(await statusPageResponse.json());
if (!statusPageParsed.success) {
return TestConnectionError.ParseResult(
new ParseError("Invalid Uptime Kuma status page response", { cause: statusPageParsed.error }),
);
}
const heartbeatResponse = await input.fetchAsync(this.heartbeatUrl());
if (!heartbeatResponse.ok) {
return TestConnectionError.StatusResult(heartbeatResponse);
}
const heartbeatParsed = uptimeKumaHeartbeatResponseSchema.safeParse(await heartbeatResponse.json());
if (!heartbeatParsed.success) {
return TestConnectionError.ParseResult(
new ParseError("Invalid Uptime Kuma heartbeat response", { cause: heartbeatParsed.error }),
);
}
return { success: true };
}
public async getDashboardDataAsync(): Promise<UptimeKumaDashboardData> {
const [statusPageResponse, heartbeatResponse] = await Promise.all([
this.getStatusPageAsync(),
this.getHeartbeatAsync(),
]);
const statusPage = uptimeKumaStatusPageResponseSchema.parse(await statusPageResponse.json());
const heartbeat = uptimeKumaHeartbeatResponseSchema.parse(await heartbeatResponse.json());
const monitors = statusPage.publicGroupList.flatMap((group) =>
group.monitorList.map((monitor) => this.mapMonitor(monitor, heartbeat)),
);
return this.buildDashboardData(monitors);
}
private mapMonitor(
monitor: { id: number; name: string },
heartbeat: { heartbeatList: Record<string, { status: number }[]>; uptimeList: Record<string, number> },
): UptimeKumaMonitor {
const heartbeats = heartbeat.heartbeatList[String(monitor.id)] ?? [];
const latestHeartbeat = heartbeats.at(-1);
const uptimeKey = `${monitor.id}_24`;
const uptimeRaw = heartbeat.uptimeList[uptimeKey];
const uptimePercent24h = typeof uptimeRaw === "number" ? uptimeRaw * 100 : null;
const status: UptimeKumaMonitorCategory =
(latestHeartbeat && (uptimeKumaHeartbeatCategoryMap[latestHeartbeat.status] ?? "down")) || "paused";
return {
id: monitor.id,
name: monitor.name,
status,
uptimePercent24h,
};
}
private buildDashboardData(monitors: UptimeKumaMonitor[]): UptimeKumaDashboardData {
const counts = monitors.reduce(
(acc, monitor) => {
acc[monitor.status] += 1;
return acc;
},
{ up: 0, down: 0, paused: 0 },
);
const uptimeValues = monitors
.map((monitor) => monitor.uptimePercent24h)
.filter((value): value is number => value !== null);
const averageUptimePercent = uptimeValues.reduce((sum, value) => sum + value, 0) / Math.max(uptimeValues.length, 1);
return {
totalMonitors: monitors.length,
upCount: counts.up,
downCount: counts.down,
pausedCount: counts.paused,
averageUptimePercent,
monitors,
};
}
private async fetchOkAsync(url: string | URL) {
const response = await fetchWithTrustedCertificatesAsync(url);
if (!response.ok) {
throw new ResponseError(response);
}
return response;
}
private getStatusPageAsync() {
return this.fetchOkAsync(this.statusPageUrl());
}
private getHeartbeatAsync() {
return this.fetchOkAsync(this.heartbeatUrl());
}
private statusPageUrl() {
return this.url(`/api/status-page/${this.getSlug()}`);
}
private heartbeatUrl() {
return this.url(`/api/status-page/heartbeat/${this.getSlug()}`);
}
private getSlug() {
if (this.hasSecretValue("slug")) {
return this.getSecretValue("slug").toLowerCase();
}
return "default";
}
}
@@ -0,0 +1,62 @@
import { z } from "zod";
export const uptimeKumaHeartbeatStatus = {
down: 0,
up: 1,
pending: 2,
maintenance: 3,
} as const;
export type UptimeKumaMonitorCategory = "up" | "down" | "paused";
export const uptimeKumaHeartbeatCategoryMap: Record<number, UptimeKumaMonitorCategory> = {
[uptimeKumaHeartbeatStatus.down]: "down",
[uptimeKumaHeartbeatStatus.up]: "up",
[uptimeKumaHeartbeatStatus.pending]: "paused",
[uptimeKumaHeartbeatStatus.maintenance]: "paused",
};
export const uptimeKumaStatusPageMonitorSchema = z.object({
id: z.number().int(),
name: z.string(),
});
export const uptimeKumaStatusPageGroupSchema = z.object({
id: z.number().int(),
name: z.string(),
monitorList: z.array(uptimeKumaStatusPageMonitorSchema),
});
export const uptimeKumaStatusPageResponseSchema = z.object({
publicGroupList: z.array(uptimeKumaStatusPageGroupSchema),
});
export const uptimeKumaHeartbeatEntrySchema = z.object({
status: z.number().int(),
time: z.string(),
ping: z.number().nullable().optional(),
});
export const uptimeKumaHeartbeatResponseSchema = z.object({
heartbeatList: z.record(z.string(), z.array(uptimeKumaHeartbeatEntrySchema)),
uptimeList: z.record(z.string(), z.number()),
});
export interface UptimeKumaMonitor {
id: number;
name: string;
status: UptimeKumaMonitorCategory;
uptimePercent24h: number | null;
}
export interface UptimeKumaDashboardData {
totalMonitors: number;
upCount: number;
downCount: number;
pausedCount: number;
averageUptimePercent: number;
monitors: UptimeKumaMonitor[];
}
export type UptimeKumaStatusPageResponse = z.infer<typeof uptimeKumaStatusPageResponseSchema>;
export type UptimeKumaHeartbeatResponse = z.infer<typeof uptimeKumaHeartbeatResponseSchema>;