Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db64ded3f0 | ||
|
|
fe35a9cf68 | ||
|
|
ad76ce9cdc | ||
|
|
ced96a57b3 | ||
|
|
302a9f4e54 | ||
|
|
69ed608241 | ||
|
|
9da8ea1dec | ||
|
|
2b4a18385d | ||
|
|
c9f003dadd |
No files matched your search
+2
@@ -8,6 +8,7 @@ import {
|
|||||||
IconPasswordUser,
|
IconPasswordUser,
|
||||||
IconPlug,
|
IconPlug,
|
||||||
IconServer,
|
IconServer,
|
||||||
|
IconTag,
|
||||||
IconUser,
|
IconUser,
|
||||||
} from "@tabler/icons-react";
|
} from "@tabler/icons-react";
|
||||||
|
|
||||||
@@ -28,4 +29,5 @@ export const integrationSecretIcons = {
|
|||||||
githubAppId: IconCode,
|
githubAppId: IconCode,
|
||||||
githubInstallationId: IconPlug,
|
githubInstallationId: IconPlug,
|
||||||
privateKey: IconKey,
|
privateKey: IconKey,
|
||||||
|
slug: IconTag,
|
||||||
} satisfies Record<IntegrationSecretKind, TablerIcon>;
|
} satisfies Record<IntegrationSecretKind, TablerIcon>;
|
||||||
@@ -2,6 +2,7 @@ import { getBoardLayouts } from "@homarr/boards/context";
|
|||||||
import { createId } from "@homarr/common";
|
import { createId } from "@homarr/common";
|
||||||
import type { Modify } from "@homarr/common/types";
|
import type { Modify } from "@homarr/common/types";
|
||||||
import type { WidgetKind } from "@homarr/definitions";
|
import type { WidgetKind } from "@homarr/definitions";
|
||||||
|
import { widgetDefaultSizes } from "@homarr/definitions";
|
||||||
|
|
||||||
import type { Board, EmptySection, Item, ItemLayout } from "~/app/[locale]/boards/_types";
|
import type { Board, EmptySection, Item, ItemLayout } from "~/app/[locale]/boards/_types";
|
||||||
import { getFirstEmptyPosition } from "./empty-position";
|
import { getFirstEmptyPosition } from "./empty-position";
|
||||||
@@ -19,7 +20,7 @@ export const createItemCallback =
|
|||||||
(previous: Board): Board => {
|
(previous: Board): Board => {
|
||||||
const firstSection = previous.sections
|
const firstSection = previous.sections
|
||||||
.filter((section): section is EmptySection => section.kind === "empty")
|
.filter((section): section is EmptySection => section.kind === "empty")
|
||||||
.sort((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
|
.toSorted((sectionA, sectionB) => sectionA.yOffset - sectionB.yOffset)
|
||||||
.at(0);
|
.at(0);
|
||||||
|
|
||||||
if (!firstSection) return previous;
|
if (!firstSection) return previous;
|
||||||
@@ -28,7 +29,7 @@ export const createItemCallback =
|
|||||||
id: id ?? createId(),
|
id: id ?? createId(),
|
||||||
kind,
|
kind,
|
||||||
options,
|
options,
|
||||||
layouts: createItemLayouts(previous, firstSection),
|
layouts: createItemLayouts(previous, firstSection, kind),
|
||||||
integrationIds,
|
integrationIds,
|
||||||
advancedOptions: {
|
advancedOptions: {
|
||||||
title: null,
|
title: null,
|
||||||
@@ -48,15 +49,20 @@ export const createItemCallback =
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
const createItemLayouts = (board: Board, currentSection: EmptySection): ItemLayout[] => {
|
const defaultItemSize = { width: 1, height: 1 };
|
||||||
|
|
||||||
|
const getWidgetItemSize = (kind: WidgetKind) => widgetDefaultSizes[kind] ?? defaultItemSize;
|
||||||
|
|
||||||
|
const createItemLayouts = (board: Board, currentSection: EmptySection, kind: WidgetKind): ItemLayout[] => {
|
||||||
const layouts = getBoardLayouts(board);
|
const layouts = getBoardLayouts(board);
|
||||||
|
const itemSize = getWidgetItemSize(kind);
|
||||||
|
|
||||||
return layouts.map((layoutId) => {
|
return layouts.map((layoutId) => {
|
||||||
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
|
const boardLayout = board.layouts.find((layout) => layout.id === layoutId);
|
||||||
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
|
const elements = getSectionElements(board, { sectionId: currentSection.id, layoutId });
|
||||||
|
|
||||||
const emptyPosition = boardLayout
|
const emptyPosition = boardLayout
|
||||||
? getFirstEmptyPosition(elements, boardLayout.columnCount)
|
? getFirstEmptyPosition(elements, boardLayout.columnCount, 9999, itemSize)
|
||||||
: { xOffset: 0, yOffset: 0 };
|
: { xOffset: 0, yOffset: 0 };
|
||||||
|
|
||||||
if (!emptyPosition) {
|
if (!emptyPosition) {
|
||||||
@@ -64,8 +70,8 @@ const createItemLayouts = (board: Board, currentSection: EmptySection): ItemLayo
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
width: 1,
|
width: itemSize.width,
|
||||||
height: 1,
|
height: itemSize.height,
|
||||||
...emptyPosition,
|
...emptyPosition,
|
||||||
sectionId: currentSection.id,
|
sectionId: currentSection.id,
|
||||||
layoutId,
|
layoutId,
|
||||||
|
|||||||
@@ -1,155 +0,0 @@
|
|||||||
import { objectEntries } from "@homarr/common";
|
|
||||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
|
||||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
|
||||||
import type { WidgetOptionDefinition, WidgetOptionType } from "@homarr/widgets";
|
|
||||||
import { reduceWidgetOptionsWithDefaultValues, widgetImports } from "@homarr/widgets";
|
|
||||||
|
|
||||||
import type { SectionItem } from "~/app/[locale]/boards/_types";
|
|
||||||
|
|
||||||
export type Translator = {
|
|
||||||
(key: string): string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export interface HoverMetadataItem {
|
|
||||||
label: string;
|
|
||||||
value: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const maxMetadataItems = 3;
|
|
||||||
|
|
||||||
const skippedOptionTypes: Partial<Record<WidgetOptionType, true>> = {
|
|
||||||
app: true,
|
|
||||||
anchorNote: true,
|
|
||||||
dynamicSelect: true,
|
|
||||||
sortableItemList: true,
|
|
||||||
multiReleasesRepositories: true,
|
|
||||||
umamiEventName: true,
|
|
||||||
umamiEventNames: true,
|
|
||||||
umamiWebsite: true,
|
|
||||||
};
|
|
||||||
|
|
||||||
const isEqualValue = (left: unknown, right: unknown) => JSON.stringify(left) === JSON.stringify(right);
|
|
||||||
|
|
||||||
type OptionDefinitionWithRules = WidgetOptionDefinition & {
|
|
||||||
shouldHide?: (options: never, integrationKinds: IntegrationKind[]) => boolean;
|
|
||||||
options?: readonly { value: unknown; label: unknown }[];
|
|
||||||
};
|
|
||||||
|
|
||||||
type OptionFormatter = (value: unknown, definition: OptionDefinitionWithRules, t: Translator) => string | null;
|
|
||||||
|
|
||||||
const resolveSelectLabel = (value: unknown, definition: OptionDefinitionWithRules, t: Translator) => {
|
|
||||||
const match = definition.options?.find((option) => option.value === value);
|
|
||||||
const label = match?.label;
|
|
||||||
const fallbackLabel = () => String(value);
|
|
||||||
const labelResolvers: Record<string, () => string> = {
|
|
||||||
function: () => (label as (translator: Translator) => string)(t),
|
|
||||||
string: () => label as string,
|
|
||||||
missing: fallbackLabel,
|
|
||||||
};
|
|
||||||
const labelType = typeof label;
|
|
||||||
const resolveLabel: () => string = labelResolvers[labelType] ?? fallbackLabel;
|
|
||||||
return resolveLabel();
|
|
||||||
};
|
|
||||||
|
|
||||||
const optionTypeFormatters: Partial<Record<WidgetOptionType, OptionFormatter>> = {
|
|
||||||
switch: (value, _, t) => {
|
|
||||||
const switchLabels: Record<string, string> = {
|
|
||||||
true: t("common.action.show"),
|
|
||||||
false: t("common.action.hide"),
|
|
||||||
};
|
|
||||||
return switchLabels[String(Boolean(value))] ?? null;
|
|
||||||
},
|
|
||||||
text: (value) => {
|
|
||||||
const text = String(value).trim();
|
|
||||||
return text.length > 0 ? text : null;
|
|
||||||
},
|
|
||||||
number: (value) => String(value),
|
|
||||||
slider: (value) => String(value),
|
|
||||||
select: (value, definition, t) => resolveSelectLabel(value, definition, t),
|
|
||||||
multiSelect: (value) => {
|
|
||||||
const items = value as unknown[];
|
|
||||||
return items.length > 0 ? String(items.length) : null;
|
|
||||||
},
|
|
||||||
multiText: (value) => {
|
|
||||||
const items = (value as string[]).filter((entry) => entry.trim().length > 0);
|
|
||||||
return items.length > 0 ? items.join(", ") : null;
|
|
||||||
},
|
|
||||||
location: (value) => {
|
|
||||||
const location = value as { name?: string };
|
|
||||||
const name = location.name?.trim() ?? "";
|
|
||||||
return name.length > 0 ? name : null;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
|
|
||||||
const formatOptionValue = (
|
|
||||||
type: WidgetOptionType,
|
|
||||||
value: unknown,
|
|
||||||
definition: OptionDefinitionWithRules,
|
|
||||||
t: Translator,
|
|
||||||
) => {
|
|
||||||
const formatter = optionTypeFormatters[type];
|
|
||||||
return formatter?.(value, definition, t) ?? null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const getOptionLabel = (kind: WidgetKind, key: string, t: Translator) => {
|
|
||||||
const labelKey = `widget.${kind}.option.${key}.label`;
|
|
||||||
const translated = t(labelKey);
|
|
||||||
return translated === labelKey ? key : translated;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const collectWidgetHoverMetadata = (
|
|
||||||
item: SectionItem,
|
|
||||||
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
|
|
||||||
integrationKinds: IntegrationKind[],
|
|
||||||
t: Translator,
|
|
||||||
): HoverMetadataItem[] => {
|
|
||||||
const { definition } = widgetImports[item.kind];
|
|
||||||
const optionDefinitions = definition.createOptions(settings) as Record<string, OptionDefinitionWithRules>;
|
|
||||||
const resolvedOptions = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
|
|
||||||
|
|
||||||
return objectEntries(optionDefinitions)
|
|
||||||
.filter(([key, optionDefinition]) => {
|
|
||||||
const skip = skippedOptionTypes[optionDefinition.type];
|
|
||||||
const hidden = optionDefinition.shouldHide?.(resolvedOptions as never, integrationKinds);
|
|
||||||
const unchanged = isEqualValue(resolvedOptions[key], optionDefinition.defaultValue);
|
|
||||||
return !skip && !hidden && !unchanged;
|
|
||||||
})
|
|
||||||
.map(([key, optionDefinition]) => {
|
|
||||||
const formattedValue = formatOptionValue(optionDefinition.type, resolvedOptions[key], optionDefinition, t);
|
|
||||||
return {
|
|
||||||
label: getOptionLabel(item.kind, key, t),
|
|
||||||
value: formattedValue ?? "",
|
|
||||||
};
|
|
||||||
})
|
|
||||||
.filter((entry) => entry.value.length > 0)
|
|
||||||
.slice(0, maxMetadataItems);
|
|
||||||
};
|
|
||||||
|
|
||||||
interface DisplayNameSource {
|
|
||||||
matches: (item: SectionItem, options: Record<string, unknown>) => boolean;
|
|
||||||
resolve: (item: SectionItem, options: Record<string, unknown>) => string;
|
|
||||||
}
|
|
||||||
|
|
||||||
const displayNameSources: DisplayNameSource[] = [
|
|
||||||
{
|
|
||||||
matches: (item) => Boolean(item.advancedOptions.title?.trim()),
|
|
||||||
resolve: (item) => item.advancedOptions.title?.trim() ?? "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
matches: (item, options) =>
|
|
||||||
item.kind === "clock" &&
|
|
||||||
Boolean(options.customTitleToggle) &&
|
|
||||||
String(options.customTitle ?? "").trim().length > 0,
|
|
||||||
resolve: (_, options) => String(options.customTitle).trim(),
|
|
||||||
},
|
|
||||||
];
|
|
||||||
|
|
||||||
export const resolveWidgetDisplayName = (
|
|
||||||
item: SectionItem,
|
|
||||||
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
|
|
||||||
t: Translator,
|
|
||||||
) => {
|
|
||||||
const resolvedOptions = reduceWidgetOptionsWithDefaultValues(item.kind, settings, item.options);
|
|
||||||
const source = displayNameSources.find((entry) => entry.matches(item, resolvedOptions));
|
|
||||||
return source?.resolve(item, resolvedOptions) ?? t(`widget.${item.kind}.name`);
|
|
||||||
};
|
|
||||||
@@ -1,116 +0,0 @@
|
|||||||
.wrapper {
|
|
||||||
position: absolute;
|
|
||||||
left: 10px;
|
|
||||||
right: 10px;
|
|
||||||
bottom: calc(100% - 10px);
|
|
||||||
margin-bottom: 1px;
|
|
||||||
z-index: 200;
|
|
||||||
pointer-events: auto;
|
|
||||||
opacity: 0;
|
|
||||||
transform: translateY(6px);
|
|
||||||
transition:
|
|
||||||
opacity 150ms ease,
|
|
||||||
transform 150ms ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):hover) .wrapper,
|
|
||||||
:global(.grid-stack-item[data-type="item"]:not([data-kind="app"]):focus-within) .wrapper {
|
|
||||||
opacity: 1;
|
|
||||||
transform: translateY(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
.panel {
|
|
||||||
@mixin dark {
|
|
||||||
--background-color: rgb(from var(--mantine-color-dark-7) r g b / 0.96);
|
|
||||||
--border-color: rgb(from var(--mantine-color-dark-4) r g b / 0.9);
|
|
||||||
}
|
|
||||||
@mixin light {
|
|
||||||
--background-color: rgb(from var(--mantine-color-white) r g b / 0.96);
|
|
||||||
--border-color: rgb(from var(--mantine-color-gray-3) r g b / 0.9);
|
|
||||||
}
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 8px;
|
|
||||||
min-height: 28px;
|
|
||||||
padding: 4px 8px;
|
|
||||||
border: 1px solid var(--border-color);
|
|
||||||
border-radius: var(--mantine-radius-md);
|
|
||||||
background-color: var(--background-color);
|
|
||||||
box-shadow: 0 4px 16px rgb(0 0 0 / 0.12);
|
|
||||||
backdrop-filter: blur(8px);
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.nameSection {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 6px;
|
|
||||||
min-width: 0;
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.widgetIcon {
|
|
||||||
flex-shrink: 0;
|
|
||||||
color: var(--mantine-color-dimmed);
|
|
||||||
}
|
|
||||||
|
|
||||||
.name {
|
|
||||||
font-size: 11px;
|
|
||||||
font-weight: 600;
|
|
||||||
line-height: 1.2;
|
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
.integrations {
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.integrationAvatar {
|
|
||||||
border: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.metadata {
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 4px;
|
|
||||||
min-width: 0;
|
|
||||||
margin-left: auto;
|
|
||||||
}
|
|
||||||
|
|
||||||
.metadataItem {
|
|
||||||
@mixin dark {
|
|
||||||
--chip-background: rgb(from var(--mantine-color-dark-5) r g b / 0.9);
|
|
||||||
}
|
|
||||||
@mixin light {
|
|
||||||
--chip-background: rgb(from var(--mantine-color-gray-1) r g b / 0.95);
|
|
||||||
}
|
|
||||||
display: flex;
|
|
||||||
align-items: center;
|
|
||||||
gap: 4px;
|
|
||||||
max-width: 140px;
|
|
||||||
padding: 2px 6px;
|
|
||||||
border-radius: var(--mantine-radius-md);
|
|
||||||
background-color: var(--chip-background);
|
|
||||||
font-size: 10px;
|
|
||||||
line-height: 1.2;
|
|
||||||
white-space: nowrap;
|
|
||||||
overflow: hidden;
|
|
||||||
}
|
|
||||||
|
|
||||||
.metadataLabel {
|
|
||||||
color: var(--mantine-color-dimmed);
|
|
||||||
flex-shrink: 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
.metadataValue {
|
|
||||||
overflow: hidden;
|
|
||||||
text-overflow: ellipsis;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (max-width: 768px) {
|
|
||||||
.wrapper {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,86 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { Avatar, Group, Text, Tooltip } from "@mantine/core";
|
|
||||||
|
|
||||||
import type { RouterOutputs } from "@homarr/api";
|
|
||||||
import { useEditMode } from "@homarr/boards/edit-mode";
|
|
||||||
import { getIconUrl } from "@homarr/definitions";
|
|
||||||
import { useSettings } from "@homarr/settings";
|
|
||||||
import { useI18n } from "@homarr/translation/client";
|
|
||||||
import { widgetImports } from "@homarr/widgets";
|
|
||||||
|
|
||||||
import type { SectionItem } from "~/app/[locale]/boards/_types";
|
|
||||||
import type { Translator } from "./widget-hover-metadata";
|
|
||||||
import { collectWidgetHoverMetadata, resolveWidgetDisplayName } from "./widget-hover-metadata";
|
|
||||||
import classes from "./widget-hover-overlay.module.css";
|
|
||||||
|
|
||||||
interface WidgetHoverOverlayProps {
|
|
||||||
item: SectionItem;
|
|
||||||
integrations: RouterOutputs["integration"]["all"] | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
export const WidgetHoverOverlay = ({ item, integrations }: WidgetHoverOverlayProps) => {
|
|
||||||
const [isEditMode] = useEditMode();
|
|
||||||
const settings = useSettings();
|
|
||||||
const t = useI18n();
|
|
||||||
const { definition } = widgetImports[item.kind];
|
|
||||||
const WidgetIcon = definition.icon;
|
|
||||||
|
|
||||||
const translate = ((key: string) => t(key as never)) as Translator;
|
|
||||||
const displayName = resolveWidgetDisplayName(item, settings, translate);
|
|
||||||
|
|
||||||
const connectedIntegrations = (integrations ?? []).filter((integration) =>
|
|
||||||
item.integrationIds.includes(integration.id),
|
|
||||||
);
|
|
||||||
const metadataItems = collectWidgetHoverMetadata(
|
|
||||||
item,
|
|
||||||
settings,
|
|
||||||
connectedIntegrations.map((integration) => integration.kind),
|
|
||||||
translate,
|
|
||||||
);
|
|
||||||
const hasIntegrations = connectedIntegrations.length > 0;
|
|
||||||
const hasMetadata = metadataItems.length > 0;
|
|
||||||
|
|
||||||
if (isEditMode) {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className={classes.wrapper}>
|
|
||||||
<div className={classes.panel}>
|
|
||||||
<div className={classes.nameSection}>
|
|
||||||
<WidgetIcon size={14} stroke={1.75} className={classes.widgetIcon} />
|
|
||||||
<Text className={classes.name} title={displayName}>
|
|
||||||
{displayName}
|
|
||||||
</Text>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{hasIntegrations && (
|
|
||||||
<Avatar.Group spacing="xs" className={classes.integrations}>
|
|
||||||
{connectedIntegrations.map((integration) => (
|
|
||||||
<Tooltip key={integration.id} label={integration.name} withArrow position="top">
|
|
||||||
<Avatar
|
|
||||||
src={getIconUrl(integration.kind)}
|
|
||||||
size={20}
|
|
||||||
radius="sm"
|
|
||||||
className={classes.integrationAvatar}
|
|
||||||
/>
|
|
||||||
</Tooltip>
|
|
||||||
))}
|
|
||||||
</Avatar.Group>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{hasMetadata && (
|
|
||||||
<Group className={classes.metadata} gap={4}>
|
|
||||||
{metadataItems.map((metadataItem) => (
|
|
||||||
<div key={`${metadataItem.label}-${metadataItem.value}`} className={classes.metadataItem}>
|
|
||||||
<span className={classes.metadataLabel}>{metadataItem.label}</span>
|
|
||||||
<span className={classes.metadataValue}>{metadataItem.value}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</Group>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
};
|
|
||||||
@@ -2,12 +2,8 @@ import { useMemo } from "react";
|
|||||||
|
|
||||||
import type { GridItemHTMLElement } from "@homarr/gridstack";
|
import type { GridItemHTMLElement } from "@homarr/gridstack";
|
||||||
|
|
||||||
import type { RouterOutputs } from "@homarr/api";
|
|
||||||
import { clientApi } from "@homarr/api/client";
|
|
||||||
|
|
||||||
import type { DynamicSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
|
import type { DynamicSectionItem, SectionItem } from "~/app/[locale]/boards/_types";
|
||||||
import { BoardItemContent } from "../items/item-content";
|
import { BoardItemContent } from "../items/item-content";
|
||||||
import { WidgetHoverOverlay } from "../items/widget-hover-overlay";
|
|
||||||
import { BoardDynamicSection } from "./dynamic-section";
|
import { BoardDynamicSection } from "./dynamic-section";
|
||||||
import { GridStackItem } from "./gridstack/gridstack-item";
|
import { GridStackItem } from "./gridstack/gridstack-item";
|
||||||
import { useSectionContext } from "./section-context";
|
import { useSectionContext } from "./section-context";
|
||||||
@@ -15,7 +11,6 @@ import { useSectionItems } from "./use-section-items";
|
|||||||
|
|
||||||
export const SectionContent = () => {
|
export const SectionContent = () => {
|
||||||
const { innerSections, items, refs } = useSectionContext();
|
const { innerSections, items, refs } = useSectionContext();
|
||||||
const { data: integrations } = clientApi.integration.all.useQuery();
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* IMPORTANT: THE ORDER OF THE BELOW ITEMS HAS TO MATCH THE ORDER OF
|
* IMPORTANT: THE ORDER OF THE BELOW ITEMS HAS TO MATCH THE ORDER OF
|
||||||
@@ -23,7 +18,7 @@ export const SectionContent = () => {
|
|||||||
* @see https://github.com/homarr-labs/homarr/pull/1770
|
* @see https://github.com/homarr-labs/homarr/pull/1770
|
||||||
*/
|
*/
|
||||||
const sortedItems = useMemo(() => {
|
const sortedItems = useMemo(() => {
|
||||||
return [...items, ...innerSections].toSorted((itemA, itemB) => {
|
return [...items, ...innerSections].sort((itemA, itemB) => {
|
||||||
if (itemA.yOffset === itemB.yOffset) {
|
if (itemA.yOffset === itemB.yOffset) {
|
||||||
return itemA.xOffset - itemB.xOffset;
|
return itemA.xOffset - itemB.xOffset;
|
||||||
}
|
}
|
||||||
@@ -35,7 +30,7 @@ export const SectionContent = () => {
|
|||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{sortedItems.map((item) => (
|
{sortedItems.map((item) => (
|
||||||
<Item key={item.id} item={item} innerRef={refs.items.current[item.id]} integrations={integrations} />
|
<Item key={item.id} item={item} innerRef={refs.items.current[item.id]} />
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
@@ -44,12 +39,12 @@ export const SectionContent = () => {
|
|||||||
interface ItemProps {
|
interface ItemProps {
|
||||||
item: DynamicSectionItem | SectionItem;
|
item: DynamicSectionItem | SectionItem;
|
||||||
innerRef: React.RefObject<GridItemHTMLElement | null> | undefined;
|
innerRef: React.RefObject<GridItemHTMLElement | null> | undefined;
|
||||||
integrations: RouterOutputs["integration"]["all"] | undefined;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const Item = ({ item, innerRef, integrations }: ItemProps) => {
|
const Item = ({ item, innerRef }: ItemProps) => {
|
||||||
const minWidth = useMinSize(item, "x");
|
const minWidth = useMinSize(item, "x");
|
||||||
const minHeight = useMinSize(item, "y");
|
const minHeight = useMinSize(item, "y");
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GridStackItem
|
<GridStackItem
|
||||||
key={item.id}
|
key={item.id}
|
||||||
@@ -64,7 +59,6 @@ const Item = ({ item, innerRef, integrations }: ItemProps) => {
|
|||||||
minWidth={minWidth}
|
minWidth={minWidth}
|
||||||
minHeight={minHeight}
|
minHeight={minHeight}
|
||||||
>
|
>
|
||||||
{item.type === "item" && item.kind !== "app" && <WidgetHoverOverlay item={item} integrations={integrations} />}
|
|
||||||
{item.type === "item" ? <BoardItemContent item={item} /> : <BoardDynamicSection section={item} />}
|
{item.type === "item" ? <BoardItemContent item={item} /> : <BoardDynamicSection section={item} />}
|
||||||
</GridStackItem>
|
</GridStackItem>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -57,6 +57,9 @@ export const categoryTranslationKeys: Record<string, string> = {
|
|||||||
mediaMonitoring: "integration.category.mediaMonitoring",
|
mediaMonitoring: "integration.category.mediaMonitoring",
|
||||||
speedtest: "integration.category.speedtest",
|
speedtest: "integration.category.speedtest",
|
||||||
analytics: "integration.category.analytics",
|
analytics: "integration.category.analytics",
|
||||||
|
documents: "integration.category.documents",
|
||||||
|
mediaLibrary: "integration.category.mediaLibrary",
|
||||||
|
uptimeMonitoring: "integration.category.uptimeMonitoring",
|
||||||
};
|
};
|
||||||
|
|
||||||
export interface IntegrationGridItem {
|
export interface IntegrationGridItem {
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
import type { ReactNode } from "react";
|
import type { ReactNode } from "react";
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
import { usePathname } from "next/navigation";
|
import { usePathname } from "next/navigation";
|
||||||
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
import { OnboardingTour } from "@gfazioli/mantine-onboarding-tour";
|
||||||
import { NavLink } from "@mantine/core";
|
import { NavLink } from "@mantine/core";
|
||||||
@@ -15,8 +16,21 @@ const TourTarget = ({ id, children }: { id?: string; children: ReactNode }) => {
|
|||||||
return <OnboardingTour.Target id={id}>{children}</OnboardingTour.Target>;
|
return <OnboardingTour.Target id={id}>{children}</OnboardingTour.Target>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const NavLinkHref = (props: NavigationLinkHref) => {
|
const pathMatches = (pathname: string, href: string) => pathname === href || pathname.startsWith(`${href}/`);
|
||||||
|
|
||||||
|
const useClientPathname = () => {
|
||||||
const pathname = usePathname();
|
const pathname = usePathname();
|
||||||
|
const [isClient, setIsClient] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setIsClient(true);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
return { pathname, isClient };
|
||||||
|
};
|
||||||
|
|
||||||
|
const NavLinkHref = (props: NavigationLinkHref) => {
|
||||||
|
const { pathname, isClient } = useClientPathname();
|
||||||
const tourId = props["data-onboarding-tour-id"];
|
const tourId = props["data-onboarding-tour-id"];
|
||||||
const link = props.external ? (
|
const link = props.external ? (
|
||||||
<NavLink component="a" label={props.label} leftSection={props.icon} href={props.href} target="_blank" />
|
<NavLink component="a" label={props.label} leftSection={props.icon} href={props.href} target="_blank" />
|
||||||
@@ -26,15 +40,15 @@ const NavLinkHref = (props: NavigationLinkHref) => {
|
|||||||
label={props.label}
|
label={props.label}
|
||||||
leftSection={props.icon}
|
leftSection={props.icon}
|
||||||
href={props.href}
|
href={props.href}
|
||||||
active={pathname === props.href || pathname.startsWith(`${props.href}/`)}
|
active={isClient && pathMatches(pathname, props.href)}
|
||||||
/>
|
/>
|
||||||
);
|
);
|
||||||
return <TourTarget id={tourId}>{link}</TourTarget>;
|
return <TourTarget id={tourId}>{link}</TourTarget>;
|
||||||
};
|
};
|
||||||
|
|
||||||
const NavLinkWithItems = (props: NavigationLinkWithItems) => {
|
const NavLinkWithItems = (props: NavigationLinkWithItems) => {
|
||||||
const pathname = usePathname();
|
const { pathname, isClient } = useClientPathname();
|
||||||
const isActive = props.items.some((item) => pathname === item.href || pathname.startsWith(`${item.href}/`));
|
const isActive = isClient && props.items.some((item) => pathMatches(pathname, item.href));
|
||||||
const nav = (
|
const nav = (
|
||||||
<NavLink label={props.label} leftSection={props.icon} defaultOpened={isActive}>
|
<NavLink label={props.label} leftSection={props.icon} defaultOpened={isActive}>
|
||||||
{props.items.map((item) => (
|
{props.items.map((item) => (
|
||||||
|
|||||||
@@ -102,10 +102,6 @@
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
.grid-stack > .grid-stack-item[data-type="item"] {
|
|
||||||
overflow: visible;
|
|
||||||
}
|
|
||||||
|
|
||||||
.grid-stack.grid-stack-animate {
|
.grid-stack.grid-stack-animate {
|
||||||
transition: none;
|
transition: none;
|
||||||
}
|
}
|
||||||
|
|||||||
+1
-1
@@ -89,7 +89,7 @@
|
|||||||
"prismjs@<1.30.0": ">=1.30.0",
|
"prismjs@<1.30.0": ">=1.30.0",
|
||||||
"proxmox-api>undici": "7.24.6",
|
"proxmox-api>undici": "7.24.6",
|
||||||
"react-is": "^19.2.7",
|
"react-is": "^19.2.7",
|
||||||
"rollup@>=4.0.0 <4.22.4": ">=4.61.1",
|
"rollup@>=4.0.0 <4.22.4": ">=4.61.0",
|
||||||
"sha.js@<=2.4.11": ">=2.4.12",
|
"sha.js@<=2.4.11": ">=2.4.12",
|
||||||
"tar-fs@>=3.0.0 <3.0.9": ">=3.1.2",
|
"tar-fs@>=3.0.0 <3.0.9": ">=3.1.2",
|
||||||
"tar-fs@>=2.0.0 <2.1.3": ">=3.1.2",
|
"tar-fs@>=2.0.0 <2.1.3": ">=3.1.2",
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
import { audiobookshelfRequestHandler } from "@homarr/request-handler/audiobookshelf";
|
||||||
|
import { navidromeRequestHandler } from "@homarr/request-handler/navidrome";
|
||||||
|
|
||||||
|
import { createOneIntegrationMiddleware } from "../../middlewares/integration";
|
||||||
|
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||||
|
|
||||||
|
export const audioStatsRouter = createTRPCRouter({
|
||||||
|
getStats: publicProcedure
|
||||||
|
.concat(createOneIntegrationMiddleware("query", "navidrome", "audiobookshelf"))
|
||||||
|
.query(async ({ ctx }) => {
|
||||||
|
const { kind } = ctx.integration;
|
||||||
|
|
||||||
|
const fetchByKind = {
|
||||||
|
navidrome: async () => {
|
||||||
|
const handler = navidromeRequestHandler.handler({ ...ctx.integration, kind: "navidrome" as const }, {});
|
||||||
|
return (await handler.getCachedOrUpdatedDataAsync({ forceUpdate: false })).data;
|
||||||
|
},
|
||||||
|
audiobookshelf: async () => {
|
||||||
|
const handler = audiobookshelfRequestHandler.handler(
|
||||||
|
{ ...ctx.integration, kind: "audiobookshelf" as const },
|
||||||
|
{},
|
||||||
|
);
|
||||||
|
return (await handler.getCachedOrUpdatedDataAsync({ forceUpdate: false })).data;
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
return { kind, data: await fetchByKind[kind]() };
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -6,6 +6,7 @@ export const widgetRouter = createTRPCRouter({
|
|||||||
anchorNotes: lazy(() => import("./anchor-notes").then((mod) => mod.anchorNotesRouter)),
|
anchorNotes: lazy(() => import("./anchor-notes").then((mod) => mod.anchorNotesRouter)),
|
||||||
coolify: lazy(() => import("./coolify").then((mod) => mod.coolifyRouter)),
|
coolify: lazy(() => import("./coolify").then((mod) => mod.coolifyRouter)),
|
||||||
immich: lazy(() => import("./immich").then((mod) => mod.immichRouter)),
|
immich: lazy(() => import("./immich").then((mod) => mod.immichRouter)),
|
||||||
|
paperlessNgx: lazy(() => import("./paperless-ngx").then((mod) => mod.paperlessNgxRouter)),
|
||||||
notebook: lazy(() => import("./notebook").then((mod) => mod.notebookRouter)),
|
notebook: lazy(() => import("./notebook").then((mod) => mod.notebookRouter)),
|
||||||
weather: lazy(() => import("./weather").then((mod) => mod.weatherRouter)),
|
weather: lazy(() => import("./weather").then((mod) => mod.weatherRouter)),
|
||||||
app: lazy(() => import("./app").then((mod) => mod.appRouter)),
|
app: lazy(() => import("./app").then((mod) => mod.appRouter)),
|
||||||
@@ -30,6 +31,8 @@ export const widgetRouter = createTRPCRouter({
|
|||||||
timetable: lazy(() => import("./timetable").then((mod) => mod.timetableRouter)),
|
timetable: lazy(() => import("./timetable").then((mod) => mod.timetableRouter)),
|
||||||
tracearr: lazy(() => import("./tracearr").then((mod) => mod.tracearrRouter)),
|
tracearr: lazy(() => import("./tracearr").then((mod) => mod.tracearrRouter)),
|
||||||
speedtestTracker: lazy(() => import("./speedtest-tracker").then((mod) => mod.speedtestTrackerRouter)),
|
speedtestTracker: lazy(() => import("./speedtest-tracker").then((mod) => mod.speedtestTrackerRouter)),
|
||||||
|
uptimeKuma: lazy(() => import("./uptime-kuma").then((mod) => mod.uptimeKumaRouter)),
|
||||||
|
audioStats: lazy(() => import("./audio-stats").then((mod) => mod.audioStatsRouter)),
|
||||||
umami: lazy(() => import("./umami").then((mod) => mod.umamiRouter)),
|
umami: lazy(() => import("./umami").then((mod) => mod.umamiRouter)),
|
||||||
ups: lazy(() => import("./ups").then((mod) => mod.upsRouter)),
|
ups: lazy(() => import("./ups").then((mod) => mod.upsRouter)),
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { paperlessNgxStatsRequestHandler } from "@homarr/request-handler/paperless-ngx";
|
||||||
|
|
||||||
|
import { createOneIntegrationMiddleware } from "../../middlewares/integration";
|
||||||
|
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||||
|
|
||||||
|
export const paperlessNgxRouter = createTRPCRouter({
|
||||||
|
getStats: publicProcedure.concat(createOneIntegrationMiddleware("query", "paperlessNgx")).query(async ({ ctx }) => {
|
||||||
|
const innerHandler = paperlessNgxStatsRequestHandler.handler(ctx.integration, {});
|
||||||
|
const data = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
||||||
|
return data.data;
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { observable } from "@trpc/server/observable";
|
||||||
|
|
||||||
|
import type { UptimeKumaDashboardData } from "@homarr/integrations/types";
|
||||||
|
import { uptimeKumaRequestHandler } from "@homarr/request-handler/uptime-kuma";
|
||||||
|
|
||||||
|
import { createManyIntegrationMiddleware } from "../../middlewares/integration";
|
||||||
|
import { createTRPCRouter, publicProcedure } from "../../trpc";
|
||||||
|
|
||||||
|
export const uptimeKumaRouter = createTRPCRouter({
|
||||||
|
getDashboard: publicProcedure
|
||||||
|
.concat(createManyIntegrationMiddleware("query", "uptimeKuma"))
|
||||||
|
.query(async ({ ctx }) => {
|
||||||
|
const results = await Promise.all(
|
||||||
|
ctx.integrations.map(async (integration) => {
|
||||||
|
const innerHandler = uptimeKumaRequestHandler.handler(integration, {});
|
||||||
|
const { data, timestamp } = await innerHandler.getCachedOrUpdatedDataAsync({ forceUpdate: false });
|
||||||
|
|
||||||
|
return {
|
||||||
|
integrationId: integration.id,
|
||||||
|
integrationName: integration.name,
|
||||||
|
integrationUrl: integration.url,
|
||||||
|
dashboard: data,
|
||||||
|
updatedAt: timestamp,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}),
|
||||||
|
|
||||||
|
subscribeToDashboard: publicProcedure
|
||||||
|
.concat(createManyIntegrationMiddleware("query", "uptimeKuma"))
|
||||||
|
.subscription(({ ctx }) => {
|
||||||
|
return observable<{
|
||||||
|
integrationId: string;
|
||||||
|
dashboard: UptimeKumaDashboardData;
|
||||||
|
timestamp: Date;
|
||||||
|
}>((emit) => {
|
||||||
|
const unsubscribes = ctx.integrations.map((integration) => {
|
||||||
|
const innerHandler = uptimeKumaRequestHandler.handler(integration, {});
|
||||||
|
return innerHandler.subscribe((dashboard) => {
|
||||||
|
emit.next({
|
||||||
|
integrationId: integration.id,
|
||||||
|
dashboard,
|
||||||
|
timestamp: new Date(),
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
});
|
||||||
@@ -27,6 +27,10 @@ const integrationAliases: Partial<Record<IntegrationKind, readonly string[]>> =
|
|||||||
overseerr: ["overseerr"],
|
overseerr: ["overseerr"],
|
||||||
dashDot: ["dashdot", "dash-dot", "dash."],
|
dashDot: ["dashdot", "dash-dot", "dash."],
|
||||||
speedtestTracker: ["speedtest-tracker"],
|
speedtestTracker: ["speedtest-tracker"],
|
||||||
|
uptimeKuma: ["uptime-kuma"],
|
||||||
|
audiobookshelf: ["audiobookshelf"],
|
||||||
|
navidrome: ["navidrome"],
|
||||||
|
paperlessNgx: ["paperless-ngx", "paperless"],
|
||||||
searchCh: ["search-ch"],
|
searchCh: ["search-ch"],
|
||||||
gitHubContainerRegistry: ["ghcr"],
|
gitHubContainerRegistry: ["ghcr"],
|
||||||
linuxServerIO: ["linuxserver"],
|
linuxServerIO: ["linuxserver"],
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ export const integrationSecretKindObject = {
|
|||||||
privateKey: { isPublic: false, multiline: true },
|
privateKey: { isPublic: false, multiline: true },
|
||||||
githubAppId: { isPublic: true, multiline: false },
|
githubAppId: { isPublic: true, multiline: false },
|
||||||
githubInstallationId: { isPublic: true, multiline: false },
|
githubInstallationId: { isPublic: true, multiline: false },
|
||||||
|
slug: { isPublic: true, multiline: false },
|
||||||
} satisfies Record<string, { isPublic: boolean; multiline: boolean }>;
|
} satisfies Record<string, { isPublic: boolean; multiline: boolean }>;
|
||||||
|
|
||||||
export const integrationSecretKinds = objectKeys(integrationSecretKindObject);
|
export const integrationSecretKinds = objectKeys(integrationSecretKindObject);
|
||||||
@@ -364,7 +365,7 @@ export const integrationDefs = {
|
|||||||
},
|
},
|
||||||
truenas: {
|
truenas: {
|
||||||
name: "TrueNAS",
|
name: "TrueNAS",
|
||||||
secretKinds: [["username", "password"], ["apiKey"]],
|
secretKinds: [["username", "password"]],
|
||||||
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/truenas.svg",
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/truenas.svg",
|
||||||
category: ["healthMonitoring"],
|
category: ["healthMonitoring"],
|
||||||
documentationUrl: createDocumentationLink("/docs/integrations/truenas"),
|
documentationUrl: createDocumentationLink("/docs/integrations/truenas"),
|
||||||
@@ -401,6 +402,14 @@ export const integrationDefs = {
|
|||||||
documentationUrl: createDocumentationLink("/docs/integrations/immich"),
|
documentationUrl: createDocumentationLink("/docs/integrations/immich"),
|
||||||
defaultPort: 2283,
|
defaultPort: 2283,
|
||||||
},
|
},
|
||||||
|
paperlessNgx: {
|
||||||
|
name: "Paperless-ngx",
|
||||||
|
secretKinds: [["apiKey"]],
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/paperless-ngx.svg",
|
||||||
|
category: ["documents"],
|
||||||
|
documentationUrl: null,
|
||||||
|
defaultPort: 8000,
|
||||||
|
},
|
||||||
tracearr: {
|
tracearr: {
|
||||||
name: "Tracearr",
|
name: "Tracearr",
|
||||||
secretKinds: [["apiKey"]],
|
secretKinds: [["apiKey"]],
|
||||||
@@ -417,6 +426,31 @@ export const integrationDefs = {
|
|||||||
documentationUrl: createDocumentationLink("/docs/integrations/speedtest-tracker"),
|
documentationUrl: createDocumentationLink("/docs/integrations/speedtest-tracker"),
|
||||||
defaultPort: 80,
|
defaultPort: 80,
|
||||||
},
|
},
|
||||||
|
uptimeKuma: {
|
||||||
|
name: "Uptime Kuma",
|
||||||
|
secretKinds: [[], ["slug"], ["slug", "apiKey"], ["apiKey"]],
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/uptime-kuma.svg",
|
||||||
|
category: ["uptimeMonitoring"],
|
||||||
|
documentationUrl: null,
|
||||||
|
defaultPort: 3001,
|
||||||
|
},
|
||||||
|
audiobookshelf: {
|
||||||
|
name: "Audiobookshelf",
|
||||||
|
secretKinds: [["apiKey"]],
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/audiobookshelf.svg",
|
||||||
|
category: ["mediaLibrary"],
|
||||||
|
documentationUrl: null,
|
||||||
|
defaultPort: 13378,
|
||||||
|
apiKeySettingsPath: "/account",
|
||||||
|
},
|
||||||
|
navidrome: {
|
||||||
|
name: "Navidrome",
|
||||||
|
secretKinds: [["username", "password"]],
|
||||||
|
iconUrl: "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons@master/svg/navidrome.svg",
|
||||||
|
category: ["mediaLibrary"],
|
||||||
|
documentationUrl: null,
|
||||||
|
defaultPort: 4533,
|
||||||
|
},
|
||||||
umami: {
|
umami: {
|
||||||
name: "Umami",
|
name: "Umami",
|
||||||
secretKinds: [["username", "password"], ["apiKey"]],
|
secretKinds: [["username", "password"], ["apiKey"]],
|
||||||
@@ -452,6 +486,7 @@ export const integrationDefs = {
|
|||||||
"notifications",
|
"notifications",
|
||||||
"smartHomeServer",
|
"smartHomeServer",
|
||||||
"ups",
|
"ups",
|
||||||
|
"uptimeMonitoring",
|
||||||
],
|
],
|
||||||
documentationUrl: null,
|
documentationUrl: null,
|
||||||
},
|
},
|
||||||
@@ -540,6 +575,9 @@ export const integrationCategories = [
|
|||||||
"speedtest",
|
"speedtest",
|
||||||
"analytics",
|
"analytics",
|
||||||
"ups",
|
"ups",
|
||||||
|
"documents",
|
||||||
|
"mediaLibrary",
|
||||||
|
"uptimeMonitoring",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type IntegrationCategory = (typeof integrationCategories)[number];
|
export type IntegrationCategory = (typeof integrationCategories)[number];
|
||||||
@@ -33,8 +33,11 @@ export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly Integ
|
|||||||
timetable: ["searchCh"],
|
timetable: ["searchCh"],
|
||||||
"immich-serverStats": ["immich"],
|
"immich-serverStats": ["immich"],
|
||||||
"immich-albumCarousel": ["immich"],
|
"immich-albumCarousel": ["immich"],
|
||||||
|
paperlessNgx: ["paperlessNgx"],
|
||||||
tracearr: ["tracearr"],
|
tracearr: ["tracearr"],
|
||||||
speedtestTracker: ["speedtestTracker"],
|
speedtestTracker: ["speedtestTracker"],
|
||||||
|
uptimeKuma: ["uptimeKuma"],
|
||||||
|
audioStats: ["navidrome", "audiobookshelf"],
|
||||||
anchorNote: ["anchor"],
|
anchorNote: ["anchor"],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -35,9 +35,18 @@ export const widgetKinds = [
|
|||||||
"timetable",
|
"timetable",
|
||||||
"immich-serverStats",
|
"immich-serverStats",
|
||||||
"immich-albumCarousel",
|
"immich-albumCarousel",
|
||||||
|
"paperlessNgx",
|
||||||
"tracearr",
|
"tracearr",
|
||||||
"speedtestTracker",
|
"speedtestTracker",
|
||||||
|
"uptimeKuma",
|
||||||
|
"audioStats",
|
||||||
"umami",
|
"umami",
|
||||||
"ups",
|
"ups",
|
||||||
] as const;
|
] as const;
|
||||||
export type WidgetKind = (typeof widgetKinds)[number];
|
export type WidgetKind = (typeof widgetKinds)[number];
|
||||||
|
|
||||||
|
export const widgetDefaultSizes: Partial<Record<WidgetKind, { width: number; height: number }>> = {
|
||||||
|
uptimeKuma: { width: 2, height: 3 },
|
||||||
|
audioStats: { width: 2, height: 2 },
|
||||||
|
paperlessNgx: { width: 2, height: 2 },
|
||||||
|
};
|
||||||
@@ -47,14 +47,12 @@
|
|||||||
"timezones-ical-library": "catalog:",
|
"timezones-ical-library": "catalog:",
|
||||||
"tsdav": "catalog:",
|
"tsdav": "catalog:",
|
||||||
"undici": "catalog:",
|
"undici": "catalog:",
|
||||||
"ws": "catalog:",
|
|
||||||
"xml2js": "catalog:",
|
"xml2js": "catalog:",
|
||||||
"zod": "catalog:"
|
"zod": "catalog:"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@homarr/tsconfig": "workspace:^0.1.0",
|
"@homarr/tsconfig": "workspace:^0.1.0",
|
||||||
"@types/node-unifi": "catalog:",
|
"@types/node-unifi": "catalog:",
|
||||||
"@types/ws": "catalog:",
|
|
||||||
"@types/xml2js": "catalog:",
|
"@types/xml2js": "catalog:",
|
||||||
"typescript": "catalog:"
|
"typescript": "catalog:"
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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>;
|
||||||
@@ -2,6 +2,7 @@ import type { IntegrationKind } from "@homarr/definitions";
|
|||||||
|
|
||||||
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
|
import { AdGuardHomeIntegration } from "../adguard-home/adguard-home-integration";
|
||||||
import { AnchorIntegration } from "../anchor/anchor-integration";
|
import { AnchorIntegration } from "../anchor/anchor-integration";
|
||||||
|
import { AudiobookshelfIntegration } from "../audiobookshelf/audiobookshelf-integration";
|
||||||
import { CodebergIntegration } from "../codeberg/codeberg-integration";
|
import { CodebergIntegration } from "../codeberg/codeberg-integration";
|
||||||
import { CoolifyIntegration } from "../coolify/coolify-integration";
|
import { CoolifyIntegration } from "../coolify/coolify-integration";
|
||||||
import { DashDotIntegration } from "../dashdot/dashdot-integration";
|
import { DashDotIntegration } from "../dashdot/dashdot-integration";
|
||||||
@@ -30,12 +31,14 @@ import { ReadarrIntegration } from "../media-organizer/readarr/readarr-integrati
|
|||||||
import { SonarrIntegration } from "../media-organizer/sonarr/sonarr-integration";
|
import { SonarrIntegration } from "../media-organizer/sonarr/sonarr-integration";
|
||||||
import { TdarrIntegration } from "../media-transcoding/tdarr-integration";
|
import { TdarrIntegration } from "../media-transcoding/tdarr-integration";
|
||||||
import { MockIntegration } from "../mock/mock-integration";
|
import { MockIntegration } from "../mock/mock-integration";
|
||||||
|
import { NavidromeIntegration } from "../navidrome/navidrome-integration";
|
||||||
import { NextcloudIntegration } from "../nextcloud/nextcloud.integration";
|
import { NextcloudIntegration } from "../nextcloud/nextcloud.integration";
|
||||||
import { NPMIntegration } from "../npm/npm-integration";
|
import { NPMIntegration } from "../npm/npm-integration";
|
||||||
import { NTFYIntegration } from "../ntfy/ntfy-integration";
|
import { NTFYIntegration } from "../ntfy/ntfy-integration";
|
||||||
import { OpenMediaVaultIntegration } from "../openmediavault/openmediavault-integration";
|
import { OpenMediaVaultIntegration } from "../openmediavault/openmediavault-integration";
|
||||||
import { OPNsenseIntegration } from "../opnsense/opnsense-integration";
|
import { OPNsenseIntegration } from "../opnsense/opnsense-integration";
|
||||||
import { OverseerrIntegration } from "../overseerr/overseerr-integration";
|
import { OverseerrIntegration } from "../overseerr/overseerr-integration";
|
||||||
|
import { PaperlessNgxIntegration } from "../paperless-ngx/paperless-ngx-integration";
|
||||||
import { PeaNutIntegration } from "../peanut/peanut-integration";
|
import { PeaNutIntegration } from "../peanut/peanut-integration";
|
||||||
import { createPiHoleIntegrationAsync } from "../pi-hole/pi-hole-integration-factory";
|
import { createPiHoleIntegrationAsync } from "../pi-hole/pi-hole-integration-factory";
|
||||||
import { PlexIntegration } from "../plex/plex-integration";
|
import { PlexIntegration } from "../plex/plex-integration";
|
||||||
@@ -48,6 +51,7 @@ import { SpeedtestTrackerIntegration } from "../speedtest-tracker/speedtest-trac
|
|||||||
import { TracearrIntegration } from "../tracearr/tracearr-integration";
|
import { TracearrIntegration } from "../tracearr/tracearr-integration";
|
||||||
import { TrueNasIntegration } from "../truenas/truenas-integration";
|
import { TrueNasIntegration } from "../truenas/truenas-integration";
|
||||||
import { UmamiIntegration } from "../umami/umami-integration";
|
import { UmamiIntegration } from "../umami/umami-integration";
|
||||||
|
import { UptimeKumaIntegration } from "../uptime-kuma/uptime-kuma-integration";
|
||||||
import { UnifiControllerIntegration } from "../unifi-controller/unifi-controller-integration";
|
import { UnifiControllerIntegration } from "../unifi-controller/unifi-controller-integration";
|
||||||
import { UnraidIntegration } from "../unraid/unraid-integration";
|
import { UnraidIntegration } from "../unraid/unraid-integration";
|
||||||
import type { Integration, IntegrationInput } from "./integration";
|
import type { Integration, IntegrationInput } from "./integration";
|
||||||
@@ -122,8 +126,12 @@ export const integrationCreators = {
|
|||||||
glances: GlancesIntegration,
|
glances: GlancesIntegration,
|
||||||
searchCh: SearchChIntegration,
|
searchCh: SearchChIntegration,
|
||||||
immich: ImmichIntegration,
|
immich: ImmichIntegration,
|
||||||
|
paperlessNgx: PaperlessNgxIntegration,
|
||||||
speedtestTracker: SpeedtestTrackerIntegration,
|
speedtestTracker: SpeedtestTrackerIntegration,
|
||||||
|
audiobookshelf: AudiobookshelfIntegration,
|
||||||
|
navidrome: NavidromeIntegration,
|
||||||
umami: UmamiIntegration,
|
umami: UmamiIntegration,
|
||||||
|
uptimeKuma: UptimeKumaIntegration,
|
||||||
peaNut: PeaNutIntegration,
|
peaNut: PeaNutIntegration,
|
||||||
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
|
} satisfies Record<IntegrationKind, IntegrationInstance | [(input: IntegrationInput) => Promise<Integration>]>;
|
||||||
|
|
||||||
|
|||||||
@@ -85,16 +85,6 @@ export abstract class Integration {
|
|||||||
return this.createUrl(this.integration.externalUrl ?? this.integration.url, path, queryParams);
|
return this.createUrl(this.integration.externalUrl ?? this.integration.url, path, queryParams);
|
||||||
}
|
}
|
||||||
|
|
||||||
protected webSocketUrl(
|
|
||||||
path: `/${string}`,
|
|
||||||
queryParams?: Record<string, string | Date | number | boolean | null | undefined>,
|
|
||||||
) {
|
|
||||||
const url = this.url(path, queryParams);
|
|
||||||
// http -> ws, https -> wss
|
|
||||||
url.protocol = url.protocol.replace("http", "ws");
|
|
||||||
return url;
|
|
||||||
}
|
|
||||||
|
|
||||||
public async testConnectionAsync(): Promise<TestingResult> {
|
public async testConnectionAsync(): Promise<TestingResult> {
|
||||||
try {
|
try {
|
||||||
const url = new URL(this.integration.url);
|
const url = new URL(this.integration.url);
|
||||||
|
|||||||
@@ -33,6 +33,9 @@ export { CoolifyIntegration } from "./coolify/coolify-integration";
|
|||||||
export { ImmichIntegration } from "./immich/immich-integration";
|
export { ImmichIntegration } from "./immich/immich-integration";
|
||||||
export { TracearrIntegration } from "./tracearr/tracearr-integration";
|
export { TracearrIntegration } from "./tracearr/tracearr-integration";
|
||||||
export { SpeedtestTrackerIntegration } from "./speedtest-tracker/speedtest-tracker-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 { UmamiIntegration } from "./umami/umami-integration";
|
||||||
export { PeaNutIntegration } from "./peanut/peanut-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 { ReleasesRepository, ReleaseResponse } from "./interfaces/releases-providers/releases-providers-types";
|
||||||
export type { Notification } from "./interfaces/notifications/notification-types";
|
export type { Notification } from "./interfaces/notifications/notification-types";
|
||||||
export type { ImmichServerStats, ImmichAlbum, ImmichAsset } from "./immich/immich-integration";
|
export type { ImmichServerStats, ImmichAlbum, ImmichAsset } from "./immich/immich-integration";
|
||||||
|
export type { PaperlessNgxStats } from "./paperless-ngx/paperless-ngx-types";
|
||||||
export type {
|
export type {
|
||||||
AnchorNote,
|
AnchorNote,
|
||||||
AnchorNotePermission,
|
AnchorNotePermission,
|
||||||
@@ -70,6 +74,9 @@ export type {
|
|||||||
} from "./anchor/anchor-types";
|
} from "./anchor/anchor-types";
|
||||||
export type { TracearrDashboardData } from "./tracearr/tracearr-types";
|
export type { TracearrDashboardData } from "./tracearr/tracearr-types";
|
||||||
export type { SpeedtestTrackerDashboardData } from "./speedtest-tracker/speedtest-tracker-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";
|
export type { UmamiVisitorStats } from "./umami/umami-types";
|
||||||
|
|
||||||
// Schemas
|
// 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;
|
||||||
|
}
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
import { describe, expect, test } from "vitest";
|
|
||||||
|
|
||||||
import { trueNasApis } from "../truenas-api";
|
|
||||||
|
|
||||||
describe("trueNasApis descriptors", () => {
|
|
||||||
test("expose the expected endpoints and handshake requirements", () => {
|
|
||||||
expect(trueNasApis.jsonRpc).toMatchObject({
|
|
||||||
kind: "jsonRpc",
|
|
||||||
path: "/api/current",
|
|
||||||
requiresSessionHandshake: false,
|
|
||||||
});
|
|
||||||
expect(trueNasApis.legacy).toMatchObject({
|
|
||||||
kind: "legacy",
|
|
||||||
path: "/websocket",
|
|
||||||
requiresSessionHandshake: true,
|
|
||||||
});
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("jsonRpc api", () => {
|
|
||||||
const { buildRequest, matchResponse } = trueNasApis.jsonRpc;
|
|
||||||
|
|
||||||
test("builds a JSON-RPC 2.0 envelope", () => {
|
|
||||||
expect(buildRequest("id-1", "system.info", [])).toStrictEqual({
|
|
||||||
jsonrpc: "2.0",
|
|
||||||
id: "id-1",
|
|
||||||
method: "system.info",
|
|
||||||
params: [],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("matches a result for the requested id", () => {
|
|
||||||
const result = matchResponse({ jsonrpc: "2.0", id: "id-1", result: true }, "id-1");
|
|
||||||
expect(result).toStrictEqual({ result: true });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns the error when the response carries one", () => {
|
|
||||||
const error = { code: -32001, message: "Not authenticated" };
|
|
||||||
expect(matchResponse({ jsonrpc: "2.0", id: "id-1", error }, "id-1")).toStrictEqual({ error });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ignores responses for a different id", () => {
|
|
||||||
expect(matchResponse({ jsonrpc: "2.0", id: "other", result: true }, "id-1")).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ignores non JSON-RPC messages", () => {
|
|
||||||
expect(matchResponse({ msg: "result", id: "id-1", result: true }, "id-1")).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
describe("legacy api", () => {
|
|
||||||
const { buildRequest, matchResponse } = trueNasApis.legacy;
|
|
||||||
|
|
||||||
test("builds a DDP method envelope", () => {
|
|
||||||
expect(buildRequest("id-1", "auth.login", ["user", "pass"])).toStrictEqual({
|
|
||||||
id: "id-1",
|
|
||||||
msg: "method",
|
|
||||||
method: "auth.login",
|
|
||||||
params: ["user", "pass"],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("matches a result message for the requested id", () => {
|
|
||||||
expect(matchResponse({ msg: "result", id: "id-1", result: false }, "id-1")).toStrictEqual({ result: false });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("returns the error when the result message carries one", () => {
|
|
||||||
const error = { error: 13, reason: "boom" };
|
|
||||||
expect(matchResponse({ msg: "result", id: "id-1", error }, "id-1")).toStrictEqual({ error });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ignores responses for a different id", () => {
|
|
||||||
expect(matchResponse({ msg: "result", id: "other", result: true }, "id-1")).toBeUndefined();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("ignores non-result messages such as the session handshake", () => {
|
|
||||||
expect(matchResponse({ msg: "connected", session: "abc" }, "id-1")).toBeUndefined();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,264 +0,0 @@
|
|||||||
import { beforeEach, describe, expect, test, vi } from "vitest";
|
|
||||||
|
|
||||||
import { IntegrationRequestError } from "../../base/errors/http/integration-request-error";
|
|
||||||
import type { IntegrationSecret } from "../../base/types";
|
|
||||||
|
|
||||||
const ws = vi.hoisted(() => {
|
|
||||||
const sentPayloads: Record<string, unknown>[] = [];
|
|
||||||
const constructedUrls: string[] = [];
|
|
||||||
// A failure with a `code` emits a coded TLS-style error; without one it mimics a missing endpoint (HTTP 404).
|
|
||||||
const failures: { path: string; code?: string }[] = [];
|
|
||||||
let responder: (method: string, params: unknown[]) => unknown = () => undefined;
|
|
||||||
|
|
||||||
type Listener = (...args: unknown[]) => void;
|
|
||||||
|
|
||||||
class FakeWebSocket {
|
|
||||||
static readonly OPEN = 1;
|
|
||||||
public readyState = FakeWebSocket.OPEN;
|
|
||||||
private readonly listeners: Record<string, Listener[]> = {};
|
|
||||||
|
|
||||||
constructor(url: URL | string) {
|
|
||||||
constructedUrls.push(url.toString());
|
|
||||||
setTimeout(() => {
|
|
||||||
const failure = failures.find((candidate) => url.toString().includes(candidate.path));
|
|
||||||
if (failure) {
|
|
||||||
const error: Error & { code?: string } = new Error(failure.code ?? "Unexpected server response: 404");
|
|
||||||
if (failure.code) error.code = failure.code;
|
|
||||||
this.dispatch("error", error);
|
|
||||||
} else {
|
|
||||||
this.dispatch("open");
|
|
||||||
}
|
|
||||||
}, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
on(event: string, listener: Listener) {
|
|
||||||
(this.listeners[event] ??= []).push(listener);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
once(event: string, listener: Listener) {
|
|
||||||
const wrapper: Listener = (...args) => {
|
|
||||||
this.off(event, wrapper);
|
|
||||||
listener(...args);
|
|
||||||
};
|
|
||||||
return this.on(event, wrapper);
|
|
||||||
}
|
|
||||||
|
|
||||||
off(event: string, listener: Listener) {
|
|
||||||
this.listeners[event] = (this.listeners[event] ?? []).filter((candidate) => candidate !== listener);
|
|
||||||
return this;
|
|
||||||
}
|
|
||||||
|
|
||||||
send(raw: string) {
|
|
||||||
const payload = JSON.parse(raw) as Record<string, unknown>;
|
|
||||||
sentPayloads.push(payload);
|
|
||||||
|
|
||||||
if (payload.msg === "connect") {
|
|
||||||
this.respond(JSON.stringify({ msg: "connected", session: "test-session" }));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = responder(payload.method as string, (payload.params as unknown[] | undefined) ?? []);
|
|
||||||
const envelope =
|
|
||||||
payload.jsonrpc === "2.0"
|
|
||||||
? { jsonrpc: "2.0", id: payload.id, result }
|
|
||||||
: { msg: "result", id: payload.id, result };
|
|
||||||
this.respond(JSON.stringify(envelope));
|
|
||||||
}
|
|
||||||
|
|
||||||
close() {
|
|
||||||
this.readyState = 3;
|
|
||||||
}
|
|
||||||
|
|
||||||
private respond(message: string) {
|
|
||||||
setTimeout(() => this.dispatch("message", message), 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
private dispatch(event: string, ...args: unknown[]) {
|
|
||||||
// `off` replaces the array rather than mutating it, so iterating it directly is safe.
|
|
||||||
for (const listener of this.listeners[event] ?? []) listener(...args);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
FakeWebSocket,
|
|
||||||
sentPayloads,
|
|
||||||
constructedUrls,
|
|
||||||
failures,
|
|
||||||
setResponder: (fn: (method: string, params: unknown[]) => unknown) => {
|
|
||||||
responder = fn;
|
|
||||||
},
|
|
||||||
};
|
|
||||||
});
|
|
||||||
|
|
||||||
vi.mock("ws", () => ({ WebSocket: ws.FakeWebSocket }));
|
|
||||||
vi.mock("@homarr/core/infrastructure/certificates", () => ({
|
|
||||||
getAllTrustedCertificatesAsync: vi.fn().mockResolvedValue([]),
|
|
||||||
getTrustedCertificateHostnamesAsync: vi.fn().mockResolvedValue([]),
|
|
||||||
}));
|
|
||||||
vi.mock("@homarr/core/infrastructure/http", () => ({
|
|
||||||
createCustomCheckServerIdentity: () => () => undefined,
|
|
||||||
}));
|
|
||||||
|
|
||||||
import { TrueNasIntegration } from "../truenas-integration";
|
|
||||||
|
|
||||||
const happyResponder = (method: string) => {
|
|
||||||
switch (method) {
|
|
||||||
case "auth.login":
|
|
||||||
case "auth.login_with_api_key":
|
|
||||||
return true;
|
|
||||||
case "system.info":
|
|
||||||
return {
|
|
||||||
version: "TrueNAS-SCALE-24.10",
|
|
||||||
hostname: "nas",
|
|
||||||
physmem: 16_000_000_000,
|
|
||||||
model: "Intel Xeon",
|
|
||||||
uptime_seconds: 3600,
|
|
||||||
};
|
|
||||||
case "reporting.get_data":
|
|
||||||
return [
|
|
||||||
{
|
|
||||||
name: "cpu",
|
|
||||||
identifier: "cpu",
|
|
||||||
aggregations: emptyAggregations(),
|
|
||||||
start: 0,
|
|
||||||
end: 1,
|
|
||||||
legend: [],
|
|
||||||
data: [[1000, 12]],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "memory",
|
|
||||||
identifier: "memory",
|
|
||||||
aggregations: emptyAggregations(),
|
|
||||||
start: 0,
|
|
||||||
end: 1,
|
|
||||||
legend: [],
|
|
||||||
data: [[1000, 8_000_000_000]],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "cputemp",
|
|
||||||
identifier: "cputemp",
|
|
||||||
aggregations: emptyAggregations(),
|
|
||||||
start: 0,
|
|
||||||
end: 1,
|
|
||||||
legend: [],
|
|
||||||
data: [[1000, 45]],
|
|
||||||
},
|
|
||||||
];
|
|
||||||
case "pool.query":
|
|
||||||
return [{ name: "tank", status: "ONLINE", healthy: true, free: 500, size: 1000, allocated: 500 }];
|
|
||||||
case "interface.query":
|
|
||||||
return [{ id: "eth0", name: "eth0" }];
|
|
||||||
case "reporting.netdata_get_data":
|
|
||||||
return [{ name: "interface", identifier: "eth0", data: [[1000, 100, 200]] }];
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
const emptyAggregations = () => ({ min: {}, mean: {}, max: {} });
|
|
||||||
|
|
||||||
let integrationCounter = 0;
|
|
||||||
const createIntegration = (decryptedSecrets: IntegrationSecret[]) =>
|
|
||||||
new TrueNasIntegration({
|
|
||||||
id: `truenas-${(integrationCounter += 1)}`,
|
|
||||||
name: "TrueNAS Test",
|
|
||||||
url: "https://truenas.local",
|
|
||||||
externalUrl: null,
|
|
||||||
decryptedSecrets,
|
|
||||||
});
|
|
||||||
|
|
||||||
const credentials: IntegrationSecret[] = [
|
|
||||||
{ kind: "username", value: "root" },
|
|
||||||
{ kind: "password", value: "secret" },
|
|
||||||
];
|
|
||||||
|
|
||||||
describe("TrueNasIntegration", () => {
|
|
||||||
beforeEach(() => {
|
|
||||||
ws.sentPayloads.length = 0;
|
|
||||||
ws.constructedUrls.length = 0;
|
|
||||||
ws.failures.length = 0;
|
|
||||||
ws.setResponder(happyResponder);
|
|
||||||
});
|
|
||||||
|
|
||||||
test("fetches and maps system info over the JSON-RPC API", async () => {
|
|
||||||
const integration = createIntegration(credentials);
|
|
||||||
|
|
||||||
const result = await integration.getSystemInfoAsync();
|
|
||||||
|
|
||||||
expect(ws.constructedUrls).toContain("wss://truenas.local/api/current");
|
|
||||||
// JSON-RPC does not use the legacy "connect" session handshake.
|
|
||||||
expect(ws.sentPayloads.some((payload) => payload.msg === "connect")).toBe(false);
|
|
||||||
|
|
||||||
expect(result).toMatchObject({
|
|
||||||
version: "TrueNAS-SCALE-24.10",
|
|
||||||
cpuModelName: "Intel Xeon",
|
|
||||||
cpuTemp: 45,
|
|
||||||
memAvailableInBytes: 16_000_000_000,
|
|
||||||
memUsedInBytes: 8_000_000_000,
|
|
||||||
uptime: 3600,
|
|
||||||
rebootRequired: false,
|
|
||||||
availablePkgUpdates: 0,
|
|
||||||
loadAverage: null,
|
|
||||||
gpu: [],
|
|
||||||
network: { up: 20_000, down: 10_000 },
|
|
||||||
fileSystem: [{ deviceName: "tank", available: "1000", used: "500", percentage: 50 }],
|
|
||||||
smart: [{ deviceName: "tank", healthy: true, overallStatus: "ONLINE", temperature: null }],
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
test("authenticates with an API key when one is configured", async () => {
|
|
||||||
const integration = createIntegration([{ kind: "apiKey", value: "api-key-123" }]);
|
|
||||||
|
|
||||||
await integration.getSystemInfoAsync();
|
|
||||||
|
|
||||||
const authPayload = ws.sentPayloads.find((payload) => String(payload.method).startsWith("auth."));
|
|
||||||
expect(authPayload).toMatchObject({ method: "auth.login_with_api_key", params: ["api-key-123"] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("authenticates with username and password when no API key is configured", async () => {
|
|
||||||
const integration = createIntegration(credentials);
|
|
||||||
|
|
||||||
await integration.getSystemInfoAsync();
|
|
||||||
|
|
||||||
const authPayload = ws.sentPayloads.find((payload) => String(payload.method).startsWith("auth."));
|
|
||||||
expect(authPayload).toMatchObject({ method: "auth.login", params: ["root", "secret"] });
|
|
||||||
});
|
|
||||||
|
|
||||||
test("falls back to the legacy websocket API when the JSON-RPC endpoint is unavailable", async () => {
|
|
||||||
ws.failures.push({ path: "/api/current" });
|
|
||||||
const integration = createIntegration(credentials);
|
|
||||||
|
|
||||||
const result = await integration.getSystemInfoAsync();
|
|
||||||
|
|
||||||
expect(ws.constructedUrls).toContain("wss://truenas.local/api/current");
|
|
||||||
expect(ws.constructedUrls).toContain("wss://truenas.local/websocket");
|
|
||||||
// The legacy API requires the "connect" session handshake before authenticating.
|
|
||||||
expect(ws.sentPayloads[0]).toMatchObject({ msg: "connect" });
|
|
||||||
expect(ws.sentPayloads.find((payload) => String(payload.method).startsWith("auth."))).toMatchObject({
|
|
||||||
msg: "method",
|
|
||||||
method: "auth.login",
|
|
||||||
});
|
|
||||||
expect(result.version).toBe("TrueNAS-SCALE-24.10");
|
|
||||||
});
|
|
||||||
|
|
||||||
test("rejects when authentication is not successful", async () => {
|
|
||||||
ws.setResponder((method) => (method.startsWith("auth.") ? false : happyResponder(method)));
|
|
||||||
const integration = createIntegration(credentials);
|
|
||||||
|
|
||||||
await expect(integration.getSystemInfoAsync()).rejects.toThrow();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("surfaces a self-signed certificate as a certificate request error without falling back", async () => {
|
|
||||||
ws.failures.push({ path: "/api/current", code: "DEPTH_ZERO_SELF_SIGNED_CERT" });
|
|
||||||
ws.failures.push({ path: "/websocket", code: "DEPTH_ZERO_SELF_SIGNED_CERT" });
|
|
||||||
const integration = createIntegration(credentials);
|
|
||||||
|
|
||||||
const error = await integration.getSystemInfoAsync().catch((caught: unknown) => caught);
|
|
||||||
|
|
||||||
expect(error).toBeInstanceOf(IntegrationRequestError);
|
|
||||||
expect((error as IntegrationRequestError).cause).toMatchObject({ type: "certificate", reason: "untrusted" });
|
|
||||||
// A certificate failure is endpoint-independent, so the legacy API must not be tried.
|
|
||||||
expect(ws.constructedUrls).not.toContain("wss://truenas.local/websocket");
|
|
||||||
});
|
|
||||||
});
|
|
||||||
@@ -1,50 +0,0 @@
|
|||||||
export type TrueNasApiKind = "jsonRpc" | "legacy";
|
|
||||||
|
|
||||||
export type TrueNasResponse = { result: unknown } | { error: unknown };
|
|
||||||
|
|
||||||
export interface TrueNasApi {
|
|
||||||
kind: TrueNasApiKind;
|
|
||||||
/** Websocket path appended to the integration URL. */
|
|
||||||
path: `/${string}`;
|
|
||||||
/** The legacy DDP API requires a "connect" handshake before authentication, the JSON-RPC API does not. */
|
|
||||||
requiresSessionHandshake: boolean;
|
|
||||||
/** Builds the request envelope for a method call. */
|
|
||||||
buildRequest: (id: string, method: string, params: unknown[]) => Record<string, unknown>;
|
|
||||||
/**
|
|
||||||
* Returns the response payload when `message` is the reply to `id`,
|
|
||||||
* otherwise `undefined` so the caller keeps waiting for a later message.
|
|
||||||
*/
|
|
||||||
matchResponse: (message: Record<string, unknown>, id: string) => TrueNasResponse | undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* JSON-RPC 2.0 API introduced in TrueNAS SCALE 24.10 (Electric Eel) and the
|
|
||||||
* legacy DDP-style websocket API used before it. Both expose the same
|
|
||||||
* middleware methods, so only the transport envelope differs.
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_rest_api.html
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#websocket_protocol
|
|
||||||
*/
|
|
||||||
export const trueNasApis = {
|
|
||||||
jsonRpc: {
|
|
||||||
kind: "jsonRpc",
|
|
||||||
path: "/api/current",
|
|
||||||
requiresSessionHandshake: false,
|
|
||||||
buildRequest: (id: string, method: string, params: unknown[]) => ({ jsonrpc: "2.0", id, method, params }),
|
|
||||||
matchResponse: (message: Record<string, unknown>, id: string) => {
|
|
||||||
if (message.id !== id || message.jsonrpc !== "2.0") return undefined;
|
|
||||||
if (message.error != null) return { error: message.error };
|
|
||||||
return { result: message.result };
|
|
||||||
},
|
|
||||||
},
|
|
||||||
legacy: {
|
|
||||||
kind: "legacy",
|
|
||||||
path: "/websocket",
|
|
||||||
requiresSessionHandshake: true,
|
|
||||||
buildRequest: (id: string, method: string, params: unknown[]) => ({ id, msg: "method", method, params }),
|
|
||||||
matchResponse: (message: Record<string, unknown>, id: string) => {
|
|
||||||
if (message.id !== id || message.msg !== "result") return undefined;
|
|
||||||
if (message.error != null) return { error: message.error };
|
|
||||||
return { result: message.result };
|
|
||||||
},
|
|
||||||
},
|
|
||||||
} satisfies Record<TrueNasApiKind, TrueNasApi>;
|
|
||||||
@@ -1,315 +0,0 @@
|
|||||||
import type { RawData } from "ws";
|
|
||||||
import { WebSocket } from "ws";
|
|
||||||
import z from "zod";
|
|
||||||
|
|
||||||
import { createId } from "@homarr/common";
|
|
||||||
import { matchErrorCode, RequestError, ResponseError } from "@homarr/common/server";
|
|
||||||
import {
|
|
||||||
getAllTrustedCertificatesAsync,
|
|
||||||
getTrustedCertificateHostnamesAsync,
|
|
||||||
} from "@homarr/core/infrastructure/certificates";
|
|
||||||
import { createCustomCheckServerIdentity } from "@homarr/core/infrastructure/http";
|
|
||||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
|
||||||
|
|
||||||
import type { IntegrationTestingInput } from "../base/integration";
|
|
||||||
import type { TrueNasApi } from "./truenas-api";
|
|
||||||
import { trueNasApis } from "./truenas-api";
|
|
||||||
|
|
||||||
const logger = createLogger({ module: "trueNasClient" });
|
|
||||||
|
|
||||||
const REQUEST_TIMEOUT_MS = 5000;
|
|
||||||
|
|
||||||
type CertificateOptions = IntegrationTestingInput["options"];
|
|
||||||
|
|
||||||
export type TrueNasCredentials = { apiKey: string } | { username: string; password: string };
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Handles talking to a TrueNAS server: opening a websocket with Homarr's
|
|
||||||
* trusted certificates, negotiating the API variant, authenticating, and
|
|
||||||
* sending method requests. Connections are reused across the per-request
|
|
||||||
* integration instances and reconnected transparently when the server drops
|
|
||||||
* an idle socket.
|
|
||||||
*/
|
|
||||||
export class TrueNasClient {
|
|
||||||
// Keyed by integration id. The value is the in-flight connection promise so concurrent
|
|
||||||
// callers reuse a single socket instead of racing to open duplicates.
|
|
||||||
private static readonly connectionMap = new Map<string, Promise<TrueNasSocket>>();
|
|
||||||
private static readonly apiMap = new Map<string, TrueNasApi>();
|
|
||||||
|
|
||||||
constructor(
|
|
||||||
private readonly id: string,
|
|
||||||
private readonly webSocketUrl: (path: `/${string}`) => URL,
|
|
||||||
private readonly credentials: TrueNasCredentials,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
/** Sends an authenticated request, reusing the cached connection while it is open. */
|
|
||||||
public async requestAsync(method: string, params: unknown[] = []): Promise<unknown> {
|
|
||||||
const socket = await this.getSocketAsync();
|
|
||||||
return socket.requestAsync(method, params);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens a connection with the provided certificate options, authenticates,
|
|
||||||
* and closes it. Used by the connection test, which may run with updated
|
|
||||||
* credentials, so any cached connection is dropped and the API re-detected.
|
|
||||||
*/
|
|
||||||
public async testAsync(certificate: CertificateOptions): Promise<void> {
|
|
||||||
this.evictConnection();
|
|
||||||
TrueNasClient.apiMap.delete(this.id);
|
|
||||||
|
|
||||||
const socket = await this.openSocketAsync(certificate);
|
|
||||||
try {
|
|
||||||
await this.authenticateAsync(socket);
|
|
||||||
} finally {
|
|
||||||
socket.close();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private getSocketAsync(): Promise<TrueNasSocket> {
|
|
||||||
let connection = TrueNasClient.connectionMap.get(this.id);
|
|
||||||
if (!connection) {
|
|
||||||
connection = this.connectAndAuthenticateAsync();
|
|
||||||
TrueNasClient.connectionMap.set(this.id, connection);
|
|
||||||
|
|
||||||
const evict = () => {
|
|
||||||
if (TrueNasClient.connectionMap.get(this.id) === connection) {
|
|
||||||
TrueNasClient.connectionMap.delete(this.id);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
// Reconnect on the next request once this attempt fails or the server drops the socket.
|
|
||||||
connection.then((socket) => socket.onClose(evict), evict);
|
|
||||||
}
|
|
||||||
|
|
||||||
return connection;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async connectAndAuthenticateAsync(): Promise<TrueNasSocket> {
|
|
||||||
const socket = await this.openSocketAsync(await resolveCertificateOptionsAsync());
|
|
||||||
try {
|
|
||||||
await this.authenticateAsync(socket);
|
|
||||||
} catch (error) {
|
|
||||||
// Never keep an unauthenticated socket, it would be reused without re-authenticating.
|
|
||||||
socket.close();
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
return socket;
|
|
||||||
}
|
|
||||||
|
|
||||||
private evictConnection() {
|
|
||||||
const connection = TrueNasClient.connectionMap.get(this.id);
|
|
||||||
if (!connection) return;
|
|
||||||
|
|
||||||
TrueNasClient.connectionMap.delete(this.id);
|
|
||||||
connection.then((socket) => socket.close()).catch(() => undefined);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Connects using the JSON-RPC API (TrueNAS 24.10+) when available and falls
|
|
||||||
* back to the legacy websocket API otherwise. A missing JSON-RPC endpoint
|
|
||||||
* surfaces as a plain protocol error; certificate, connection, DNS and
|
|
||||||
* timeout errors are endpoint-independent and are never retried.
|
|
||||||
*/
|
|
||||||
private async openSocketAsync(certificate: CertificateOptions): Promise<TrueNasSocket> {
|
|
||||||
const cachedApi = TrueNasClient.apiMap.get(this.id);
|
|
||||||
if (cachedApi) {
|
|
||||||
return openTrueNasSocketAsync(this.webSocketUrl(cachedApi.path), cachedApi, certificate);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const socket = await openTrueNasSocketAsync(
|
|
||||||
this.webSocketUrl(trueNasApis.jsonRpc.path),
|
|
||||||
trueNasApis.jsonRpc,
|
|
||||||
certificate,
|
|
||||||
);
|
|
||||||
TrueNasClient.apiMap.set(this.id, trueNasApis.jsonRpc);
|
|
||||||
return socket;
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof RequestError) throw error;
|
|
||||||
|
|
||||||
logger.debug("JSON-RPC API unavailable, falling back to the legacy websocket API", {
|
|
||||||
error: error instanceof Error ? error.message : undefined,
|
|
||||||
});
|
|
||||||
const socket = await openTrueNasSocketAsync(
|
|
||||||
this.webSocketUrl(trueNasApis.legacy.path),
|
|
||||||
trueNasApis.legacy,
|
|
||||||
certificate,
|
|
||||||
);
|
|
||||||
TrueNasClient.apiMap.set(this.id, trueNasApis.legacy);
|
|
||||||
return socket;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Authenticates with an API key when one is configured, otherwise with the
|
|
||||||
* username and password. Both methods work on either API.
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#websocket_protocol
|
|
||||||
*/
|
|
||||||
private async authenticateAsync(socket: TrueNasSocket): Promise<void> {
|
|
||||||
const response =
|
|
||||||
"apiKey" in this.credentials
|
|
||||||
? await socket.requestAsync("auth.login_with_api_key", [this.credentials.apiKey])
|
|
||||||
: await socket.requestAsync("auth.login", [this.credentials.username, this.credentials.password]);
|
|
||||||
|
|
||||||
const success = await z.boolean().parseAsync(response);
|
|
||||||
if (!success) throw new ResponseError({ status: 401 });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Wraps a single websocket connection and speaks whichever TrueNAS API
|
|
||||||
* ({@link trueNasApis}) was negotiated when it was opened.
|
|
||||||
*/
|
|
||||||
class TrueNasSocket {
|
|
||||||
constructor(
|
|
||||||
private readonly webSocket: WebSocket,
|
|
||||||
private readonly api: TrueNasApi,
|
|
||||||
) {}
|
|
||||||
|
|
||||||
public close() {
|
|
||||||
this.webSocket.close();
|
|
||||||
}
|
|
||||||
|
|
||||||
public onClose(listener: () => void) {
|
|
||||||
this.webSocket.once("close", listener);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The legacy DDP API requires a "connect" handshake to obtain a session
|
|
||||||
* before any method can be called.
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#websocket_protocol
|
|
||||||
*/
|
|
||||||
public registerSessionAsync(): Promise<void> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const handler = (raw: RawData) => {
|
|
||||||
const message = parseMessage(raw);
|
|
||||||
if (message?.msg === "connected") {
|
|
||||||
this.webSocket.off("message", handler);
|
|
||||||
resolve();
|
|
||||||
} else if (message?.msg === "failed") {
|
|
||||||
this.webSocket.off("message", handler);
|
|
||||||
reject(new Error("Unable to establish TrueNAS session"));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
this.webSocket.on("message", handler);
|
|
||||||
this.webSocket.send(JSON.stringify({ msg: "connect", version: "1", support: ["1"] }));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sends a method request and resolves with its result. Rejects after
|
|
||||||
* {@link REQUEST_TIMEOUT_MS} when no matching response was received.
|
|
||||||
*/
|
|
||||||
public requestAsync(method: string, params: unknown[] = []): Promise<unknown> {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
const id = createId();
|
|
||||||
|
|
||||||
const cleanup = () => {
|
|
||||||
clearTimeout(timeoutId);
|
|
||||||
this.webSocket.off("message", handler);
|
|
||||||
this.webSocket.off("close", onClose);
|
|
||||||
this.webSocket.off("error", onError);
|
|
||||||
};
|
|
||||||
|
|
||||||
const handler = (raw: RawData) => {
|
|
||||||
const message = parseMessage(raw);
|
|
||||||
if (!message) return;
|
|
||||||
|
|
||||||
const response = this.api.matchResponse(message, id);
|
|
||||||
if (!response) return;
|
|
||||||
|
|
||||||
cleanup();
|
|
||||||
if ("error" in response) {
|
|
||||||
reject(new Error(`TrueNAS method "${method}" failed: ${JSON.stringify(response.error)}`));
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
logger.debug("Received method response", { id, method, api: this.api.kind });
|
|
||||||
resolve(response.result);
|
|
||||||
};
|
|
||||||
|
|
||||||
// A dropped connection would otherwise leave the request hanging until the timeout below.
|
|
||||||
const onClose = () => {
|
|
||||||
cleanup();
|
|
||||||
reject(
|
|
||||||
new RequestError(
|
|
||||||
{ type: "connection", reason: "reset", code: "ECONNRESET" },
|
|
||||||
{ cause: new Error("Connection closed before a response was received") },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
};
|
|
||||||
const onError = (error: Error) => {
|
|
||||||
cleanup();
|
|
||||||
reject(error);
|
|
||||||
};
|
|
||||||
|
|
||||||
const timeoutId = setTimeout(() => {
|
|
||||||
cleanup();
|
|
||||||
reject(
|
|
||||||
new RequestError(
|
|
||||||
{
|
|
||||||
type: "timeout",
|
|
||||||
reason: "aborted",
|
|
||||||
code: "ECONNABORTED",
|
|
||||||
},
|
|
||||||
{ cause: new Error("Canceled request after 5 seconds") },
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}, REQUEST_TIMEOUT_MS);
|
|
||||||
|
|
||||||
this.webSocket.on("message", handler);
|
|
||||||
this.webSocket.once("close", onClose);
|
|
||||||
this.webSocket.once("error", onError);
|
|
||||||
logger.debug("Sending method request", { id, method, api: this.api.kind });
|
|
||||||
this.webSocket.send(JSON.stringify(this.api.buildRequest(id, method, params)));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Opens a websocket using Homarr's trusted certificates and performs the
|
|
||||||
* session handshake when the API requires it. TLS, connection, DNS and timeout
|
|
||||||
* failures are translated into {@link RequestError}s so the connection test can
|
|
||||||
* offer to trust a self-signed certificate, exactly like the HTTP integrations.
|
|
||||||
*/
|
|
||||||
const openTrueNasSocketAsync = async (
|
|
||||||
url: URL,
|
|
||||||
api: TrueNasApi,
|
|
||||||
certificate: CertificateOptions,
|
|
||||||
): Promise<TrueNasSocket> => {
|
|
||||||
logger.debug("Connecting to TrueNAS websocket", { url: url.toString(), api: api.kind });
|
|
||||||
|
|
||||||
const webSocket = await new Promise<WebSocket>((resolve, reject) => {
|
|
||||||
const socket = new WebSocket(url, {
|
|
||||||
ca: certificate.ca,
|
|
||||||
// The @types/ws contract types this as returning a boolean, but ws forwards it to
|
|
||||||
// tls.connect which uses Node's `Error | undefined` contract that our helper follows.
|
|
||||||
checkServerIdentity: certificate.checkServerIdentity as never,
|
|
||||||
});
|
|
||||||
|
|
||||||
socket.once("open", () => resolve(socket));
|
|
||||||
socket.once("error", (error: Error & { code?: string }) => {
|
|
||||||
const matched = error.code ? matchErrorCode(error.code) : undefined;
|
|
||||||
reject(matched ? new RequestError(matched, { cause: error }) : error);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
const socket = new TrueNasSocket(webSocket, api);
|
|
||||||
if (api.requiresSessionHandshake) await socket.registerSessionAsync();
|
|
||||||
return socket;
|
|
||||||
};
|
|
||||||
|
|
||||||
const resolveCertificateOptionsAsync = async (): Promise<CertificateOptions> => ({
|
|
||||||
ca: await getAllTrustedCertificatesAsync(),
|
|
||||||
checkServerIdentity: createCustomCheckServerIdentity(await getTrustedCertificateHostnamesAsync()),
|
|
||||||
});
|
|
||||||
|
|
||||||
const parseMessage = (raw: RawData): Record<string, unknown> | undefined => {
|
|
||||||
try {
|
|
||||||
const parsed: unknown = JSON.parse(raw.toString());
|
|
||||||
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
|
|
||||||
? (parsed as Record<string, unknown>)
|
|
||||||
: undefined;
|
|
||||||
} catch {
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
@@ -1,6 +1,8 @@
|
|||||||
import dayjs from "dayjs";
|
import dayjs from "dayjs";
|
||||||
import z from "zod";
|
import z from "zod";
|
||||||
|
|
||||||
|
import { createId } from "@homarr/common";
|
||||||
|
import { RequestError, ResponseError } from "@homarr/common/server";
|
||||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||||
|
|
||||||
import type { IntegrationTestingInput } from "../base/integration";
|
import type { IntegrationTestingInput } from "../base/integration";
|
||||||
@@ -8,21 +10,252 @@ import { Integration } from "../base/integration";
|
|||||||
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
import type { TestingResult } from "../base/test-connection/test-connection-service";
|
||||||
import type { ISystemHealthMonitoringIntegration } from "../interfaces/health-monitoring/health-monitoring-integration";
|
import type { ISystemHealthMonitoringIntegration } from "../interfaces/health-monitoring/health-monitoring-integration";
|
||||||
import type { SystemHealthMonitoring } from "../interfaces/health-monitoring/health-monitoring-types";
|
import type { SystemHealthMonitoring } from "../interfaces/health-monitoring/health-monitoring-types";
|
||||||
import type { TrueNasCredentials } from "./truenas-client";
|
|
||||||
import { TrueNasClient } from "./truenas-client";
|
|
||||||
|
|
||||||
const logger = createLogger({ module: "trueNasIntegration" });
|
const logger = createLogger({ module: "trueNasIntegration" });
|
||||||
|
|
||||||
const NETWORK_MULTIPLIER = 100;
|
const NETWORK_MULTIPLIER = 100;
|
||||||
|
|
||||||
export class TrueNasIntegration extends Integration implements ISystemHealthMonitoringIntegration {
|
export class TrueNasIntegration extends Integration implements ISystemHealthMonitoringIntegration {
|
||||||
private client?: TrueNasClient;
|
private static webSocketMap = new Map<string, WebSocket>();
|
||||||
|
|
||||||
|
private wsUrl() {
|
||||||
|
const url = super.url("/websocket");
|
||||||
|
url.protocol = url.protocol.replace("http", "ws");
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
private get webSocket() {
|
||||||
|
return TrueNasIntegration.webSocketMap.get(this.integration.id) ?? null;
|
||||||
|
}
|
||||||
|
|
||||||
|
protected async testingAsync(_input: IntegrationTestingInput): Promise<TestingResult> {
|
||||||
|
const webSocket = await this.connectWebSocketAsync();
|
||||||
|
await this.registerSessionAsync(webSocket);
|
||||||
|
await this.authenticateWebSocketAsync(webSocket);
|
||||||
|
|
||||||
|
// Remove current socket connection so we can authenticate with updated credentials
|
||||||
|
TrueNasIntegration.webSocketMap.delete(this.integration.id);
|
||||||
|
|
||||||
protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {
|
|
||||||
await this.getClient().testAsync(input.options);
|
|
||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TrueNAS API uses WebSocket. This function connects to the socket
|
||||||
|
* and resolves the promise if the connection was successful.
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html
|
||||||
|
*/
|
||||||
|
private async connectWebSocketAsync(): Promise<WebSocket> {
|
||||||
|
logger.debug("Connecting to websocket server", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
const webSocket = new WebSocket(this.wsUrl());
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
webSocket.onopen = () => {
|
||||||
|
logger.debug("Connected to websocket server", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
resolve(webSocket);
|
||||||
|
};
|
||||||
|
|
||||||
|
webSocket.onerror = () => {
|
||||||
|
reject(new Error("Failed to connect"));
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Before authentication, a session must be obtained from the server using the "connect" event.
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#websocket_protocol
|
||||||
|
*/
|
||||||
|
private async registerSessionAsync(webSocket: WebSocket): Promise<void> {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const subscribe = (event: MessageEvent<string>) => {
|
||||||
|
const data = JSON.parse(event.data) as { msg: string };
|
||||||
|
if (data.msg === "connected") {
|
||||||
|
webSocket.removeEventListener("message", subscribe);
|
||||||
|
resolve();
|
||||||
|
} else if (data.msg === "failed") {
|
||||||
|
webSocket.removeEventListener("message", subscribe);
|
||||||
|
reject(new Error("Unable to establish connection"));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
webSocket.addEventListener("message", subscribe);
|
||||||
|
webSocket.send(
|
||||||
|
JSON.stringify({
|
||||||
|
msg: "connect",
|
||||||
|
version: "1", // this must be number, not string
|
||||||
|
support: ["1"], // this must be number, not string
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* After a session was obtained, the session can be authenticated.
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#websocket_protocol
|
||||||
|
*/
|
||||||
|
private async authenticateWebSocketAsync(webSocket?: WebSocket): Promise<void> {
|
||||||
|
logger.debug("Authenticating with username and password", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
const response = await this.requestAsync(
|
||||||
|
"auth.login",
|
||||||
|
[this.getSecretValue("username"), this.getSecretValue("password")],
|
||||||
|
webSocket,
|
||||||
|
);
|
||||||
|
const result = await z.boolean().parseAsync(response);
|
||||||
|
if (!result) throw new ResponseError({ status: 401 });
|
||||||
|
logger.debug("Authenticated successfully with username and password", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private async getPoolsAsync() {
|
||||||
|
logger.debug("Retrieving pools", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.requestAsync("pool.query", [
|
||||||
|
[],
|
||||||
|
{
|
||||||
|
extra: {
|
||||||
|
is_upgraded: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const result = await poolSchema.parseAsync(response);
|
||||||
|
// Offline / exported pools have null values for allocated, size and free, so we filter them out
|
||||||
|
// See https://github.com/homarr-labs/homarr/issues/5194
|
||||||
|
const activePools = result
|
||||||
|
.map((pool) => {
|
||||||
|
if (pool.allocated !== null && pool.size !== null && pool.free !== null) {
|
||||||
|
return {
|
||||||
|
...pool,
|
||||||
|
allocated: pool.allocated,
|
||||||
|
size: pool.size,
|
||||||
|
free: pool.free,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
})
|
||||||
|
.filter((pool) => pool !== null);
|
||||||
|
logger.debug("Retrieved pools", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
totalCount: result.length,
|
||||||
|
activeCount: activePools.length,
|
||||||
|
});
|
||||||
|
return activePools;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves data using the reporting method
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#reporting
|
||||||
|
*/
|
||||||
|
private async getReportingAsync(): Promise<ReportingItem[]> {
|
||||||
|
logger.debug("Retrieving reporting data", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.requestAsync("reporting.get_data", [
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: "cpu",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "memory",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "cputemp",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
{
|
||||||
|
aggregate: true,
|
||||||
|
start: dayjs().add(-5, "minutes").unix(),
|
||||||
|
end: dayjs().unix(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const result = await z.array(reportingItemSchema).parseAsync(response);
|
||||||
|
|
||||||
|
logger.debug("Retrieved reporting data", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
count: result.length,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves a list of all available network interfaces
|
||||||
|
* @see https://www.truenas.com/docs/core/13.0/api/core_websocket_api.html#interface
|
||||||
|
*/
|
||||||
|
private async getNetworkInterfacesAsync(): Promise<z.infer<typeof networkInterfaceSchema>> {
|
||||||
|
logger.debug("Retrieving available network-interfaces", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.requestAsync("interface.query", [
|
||||||
|
[], // no filters
|
||||||
|
{},
|
||||||
|
]);
|
||||||
|
const result = await networkInterfaceSchema.parseAsync(response);
|
||||||
|
|
||||||
|
logger.debug("Retrieved available network-interfaces", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
count: result.length,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves reporting network data of the last 5 minutes
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#reporting
|
||||||
|
*/
|
||||||
|
private async getReportingNetdataAsync(): Promise<z.infer<typeof reportingNetDataSchema>> {
|
||||||
|
const networkInterfaces = await this.getNetworkInterfacesAsync();
|
||||||
|
|
||||||
|
logger.debug("Retrieving reporting network data", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.requestAsync("reporting.netdata_get_data", [
|
||||||
|
networkInterfaces.map((networkInterface) => ({
|
||||||
|
name: "interface",
|
||||||
|
identifier: networkInterface.id,
|
||||||
|
})),
|
||||||
|
{
|
||||||
|
start: dayjs().add(-5, "minutes").unix(),
|
||||||
|
end: dayjs().unix(),
|
||||||
|
},
|
||||||
|
]);
|
||||||
|
const result = await reportingNetDataSchema.parseAsync(response);
|
||||||
|
|
||||||
|
logger.debug("Retrieved reporting-network-data", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
count: result.length,
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves information about the system
|
||||||
|
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#system
|
||||||
|
*/
|
||||||
|
private async getSystemInformationAsync(): Promise<z.infer<typeof systemInfoSchema>> {
|
||||||
|
logger.debug("Retrieving system-information", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.requestAsync("system.info");
|
||||||
|
const result = await systemInfoSchema.parseAsync(response);
|
||||||
|
|
||||||
|
logger.debug("Retrieved system-information", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
public async getSystemInfoAsync(): Promise<SystemHealthMonitoring> {
|
public async getSystemInfoAsync(): Promise<SystemHealthMonitoring> {
|
||||||
const systemInformation = await this.getSystemInformationAsync();
|
const systemInformation = await this.getSystemInformationAsync();
|
||||||
const reporting = await this.getReportingAsync();
|
const reporting = await this.getReportingAsync();
|
||||||
@@ -39,7 +272,7 @@ export class TrueNasIntegration extends Integration implements ISystemHealthMoni
|
|||||||
|
|
||||||
return {
|
return {
|
||||||
cpuUtilization: cpuData.reduce((acc, item) => acc + (item > 100 ? 0 : item), 0) / cpuData.length,
|
cpuUtilization: cpuData.reduce((acc, item) => acc + (item > 100 ? 0 : item), 0) / cpuData.length,
|
||||||
cpuTemp: Math.max(...cpuTempData.filter((_item, index) => index > 0)),
|
cpuTemp: Math.max(...cpuTempData.filter((_item, i) => i > 0)),
|
||||||
memAvailableInBytes: systemInformation.physmem,
|
memAvailableInBytes: systemInformation.physmem,
|
||||||
memUsedInBytes: memoryData[1] ?? 0, // Index 0 is UNIX timestamp, Index 1 is free space in bytes
|
memUsedInBytes: memoryData[1] ?? 0, // Index 0 is UNIX timestamp, Index 1 is free space in bytes
|
||||||
fileSystem: datasets.map((dataset) => ({
|
fileSystem: datasets.map((dataset) => ({
|
||||||
@@ -68,164 +301,87 @@ export class TrueNasIntegration extends Integration implements ISystemHealthMoni
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private getClient(): TrueNasClient {
|
|
||||||
return (this.client ??= this.createClient());
|
|
||||||
}
|
|
||||||
|
|
||||||
private createClient(): TrueNasClient {
|
|
||||||
const credentials: TrueNasCredentials = this.hasSecretValue("apiKey")
|
|
||||||
? { apiKey: this.getSecretValue("apiKey") }
|
|
||||||
: { username: this.getSecretValue("username"), password: this.getSecretValue("password") };
|
|
||||||
|
|
||||||
return new TrueNasClient(this.integration.id, (path) => this.webSocketUrl(path), credentials);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async requestAsync(method: string, params: unknown[] = []): Promise<unknown> {
|
|
||||||
return this.getClient().requestAsync(method, params);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async getPoolsAsync() {
|
|
||||||
logger.debug("Retrieving pools", { url: this.integration.url });
|
|
||||||
|
|
||||||
const response = await this.requestAsync("pool.query", [
|
|
||||||
[],
|
|
||||||
{
|
|
||||||
extra: {
|
|
||||||
is_upgraded: true,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const result = await poolSchema.parseAsync(response);
|
|
||||||
// Offline / exported pools have null values for allocated, size and free, so we filter them out
|
|
||||||
// See https://github.com/homarr-labs/homarr/issues/5194
|
|
||||||
const activePools = result
|
|
||||||
.map((pool) => {
|
|
||||||
if (pool.allocated !== null && pool.size !== null && pool.free !== null) {
|
|
||||||
return {
|
|
||||||
...pool,
|
|
||||||
allocated: pool.allocated,
|
|
||||||
size: pool.size,
|
|
||||||
free: pool.free,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
})
|
|
||||||
.filter((pool) => pool !== null);
|
|
||||||
logger.debug("Retrieved pools", {
|
|
||||||
url: this.integration.url,
|
|
||||||
totalCount: result.length,
|
|
||||||
activeCount: activePools.length,
|
|
||||||
});
|
|
||||||
return activePools;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves data using the reporting method
|
* Send a request through websocket and return response
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#reporting
|
* Times out after 5 seconds when no response was received.
|
||||||
|
* @param method json-rpc method to call
|
||||||
|
* @param params array of parameters
|
||||||
|
* @param webSocketOverride override of webSocket, helpful for not storing the connection
|
||||||
|
* @returns result of json-rpc call
|
||||||
*/
|
*/
|
||||||
private async getReportingAsync(): Promise<ReportingItem[]> {
|
private async requestAsync(method: string, params: unknown[] = [], webSocketOverride?: WebSocket) {
|
||||||
logger.debug("Retrieving reporting data", { url: this.integration.url });
|
let webSocket = webSocketOverride ?? this.webSocket;
|
||||||
|
if (webSocket?.readyState !== WebSocket.OPEN) {
|
||||||
|
logger.debug("Connecting to websocket", {
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
// We can only land here with static webSocket
|
||||||
|
webSocket = await this.connectWebSocketAsync();
|
||||||
|
await this.registerSessionAsync(webSocket);
|
||||||
|
|
||||||
const response = await this.requestAsync("reporting.get_data", [
|
TrueNasIntegration.webSocketMap.set(this.integration.id, webSocket);
|
||||||
[
|
await this.authenticateWebSocketAsync();
|
||||||
{
|
}
|
||||||
name: "cpu",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "memory",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "cputemp",
|
|
||||||
},
|
|
||||||
],
|
|
||||||
{
|
|
||||||
aggregate: true,
|
|
||||||
start: dayjs().add(-5, "minutes").unix(),
|
|
||||||
end: dayjs().unix(),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const result = await z.array(reportingItemSchema).parseAsync(response);
|
|
||||||
|
|
||||||
logger.debug("Retrieved reporting data", {
|
return await new Promise((resolve, reject) => {
|
||||||
url: this.integration.url,
|
const id = createId();
|
||||||
count: result.length,
|
const handler = (event: MessageEvent<string>) => {
|
||||||
|
const data = JSON.parse(event.data) as Record<string, unknown>;
|
||||||
|
if (data.msg !== "result") return;
|
||||||
|
if (data.id !== id) return;
|
||||||
|
|
||||||
|
clearTimeout(timeoutId);
|
||||||
|
webSocket.removeEventListener("message", handler);
|
||||||
|
logger.debug("Received method response", {
|
||||||
|
id,
|
||||||
|
method,
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
resolve(data.result);
|
||||||
|
};
|
||||||
|
const timeoutId = setTimeout(() => {
|
||||||
|
webSocket.removeEventListener("message", handler);
|
||||||
|
reject(
|
||||||
|
new RequestError(
|
||||||
|
{
|
||||||
|
type: "timeout",
|
||||||
|
reason: "aborted",
|
||||||
|
code: "ECONNABORTED",
|
||||||
|
},
|
||||||
|
{ cause: new Error("Canceled request after 5 seconds") },
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}, 5000);
|
||||||
|
|
||||||
|
webSocket.addEventListener("message", handler);
|
||||||
|
|
||||||
|
logger.debug("Sending method request", {
|
||||||
|
id,
|
||||||
|
method,
|
||||||
|
url: this.wsUrl(),
|
||||||
|
});
|
||||||
|
|
||||||
|
webSocket.send(
|
||||||
|
JSON.stringify({
|
||||||
|
id,
|
||||||
|
msg: "method",
|
||||||
|
method,
|
||||||
|
params,
|
||||||
|
}),
|
||||||
|
);
|
||||||
});
|
});
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
private extractNetworkTrafficData = (data: z.infer<typeof reportingNetDataSchema>, index = 1 | 2) => {
|
||||||
* Retrieves a list of all available network interfaces
|
|
||||||
* @see https://www.truenas.com/docs/core/13.0/api/core_websocket_api.html#interface
|
|
||||||
*/
|
|
||||||
private async getNetworkInterfacesAsync(): Promise<z.infer<typeof networkInterfaceSchema>> {
|
|
||||||
logger.debug("Retrieving available network-interfaces", { url: this.integration.url });
|
|
||||||
|
|
||||||
const response = await this.requestAsync("interface.query", [
|
|
||||||
[], // no filters
|
|
||||||
{},
|
|
||||||
]);
|
|
||||||
const result = await networkInterfaceSchema.parseAsync(response);
|
|
||||||
|
|
||||||
logger.debug("Retrieved available network-interfaces", {
|
|
||||||
url: this.integration.url,
|
|
||||||
count: result.length,
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves reporting network data of the last 5 minutes
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#reporting
|
|
||||||
*/
|
|
||||||
private async getReportingNetdataAsync(): Promise<z.infer<typeof reportingNetDataSchema>> {
|
|
||||||
const networkInterfaces = await this.getNetworkInterfacesAsync();
|
|
||||||
|
|
||||||
logger.debug("Retrieving reporting network data", { url: this.integration.url });
|
|
||||||
|
|
||||||
const response = await this.requestAsync("reporting.netdata_get_data", [
|
|
||||||
networkInterfaces.map((networkInterface) => ({
|
|
||||||
name: "interface",
|
|
||||||
identifier: networkInterface.id,
|
|
||||||
})),
|
|
||||||
{
|
|
||||||
start: dayjs().add(-5, "minutes").unix(),
|
|
||||||
end: dayjs().unix(),
|
|
||||||
},
|
|
||||||
]);
|
|
||||||
const result = await reportingNetDataSchema.parseAsync(response);
|
|
||||||
|
|
||||||
logger.debug("Retrieved reporting-network-data", {
|
|
||||||
url: this.integration.url,
|
|
||||||
count: result.length,
|
|
||||||
});
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves information about the system
|
|
||||||
* @see https://www.truenas.com/docs/api/scale_websocket_api.html#system
|
|
||||||
*/
|
|
||||||
private async getSystemInformationAsync(): Promise<z.infer<typeof systemInfoSchema>> {
|
|
||||||
logger.debug("Retrieving system-information", { url: this.integration.url });
|
|
||||||
|
|
||||||
const response = await this.requestAsync("system.info");
|
|
||||||
const result = await systemInfoSchema.parseAsync(response);
|
|
||||||
|
|
||||||
logger.debug("Retrieved system-information", { url: this.integration.url });
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
|
|
||||||
private extractNetworkTrafficData = (data: z.infer<typeof reportingNetDataSchema>, index: 1 | 2) => {
|
|
||||||
return data.reduce((acc, current) => acc + (current.data.at(-1)?.at(index) ?? 0), 0);
|
return data.reduce((acc, current) => acc + (current.data.at(-1)?.at(index) ?? 0), 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
private extractLatestReportingData(data: ReportingItem[], identifier: ReportingItem["identifier"]) {
|
private extractLatestReportingData(data: ReportingItem[], key: ReportingItem["identifier"]) {
|
||||||
const item = data.find((reportingItem) => reportingItem.identifier === identifier);
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
// Reporting rows are [timestamp, ...values] in ascending time order, so the last row is the most recent reading.
|
const dataObject = data.find((item) => item.identifier === key)!;
|
||||||
const latest = item?.data.at(-1);
|
// TODO: check why the below sorting is done, because right now it compares number[] with number[]?
|
||||||
if (!latest) throw new Error(`TrueNAS returned no "${identifier}" reporting data`);
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
return latest;
|
return dataObject.data.sort((item1, item2) => (item1 > item2 ? -1 : 1))[0]!;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -17,4 +17,8 @@ export * from "./anchor/anchor-types";
|
|||||||
export * from "./interfaces/timetable/timetable-types";
|
export * from "./interfaces/timetable/timetable-types";
|
||||||
export * from "./tracearr/tracearr-types";
|
export * from "./tracearr/tracearr-types";
|
||||||
export * from "./speedtest-tracker/speedtest-tracker-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 "./umami/umami-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>;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { AudiobookshelfDashboardData } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
|
||||||
|
|
||||||
|
export const audiobookshelfRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
AudiobookshelfDashboardData,
|
||||||
|
"audiobookshelf",
|
||||||
|
Record<string, never>
|
||||||
|
>({
|
||||||
|
async requestAsync(integration) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.getDashboardDataAsync();
|
||||||
|
},
|
||||||
|
cacheDuration: dayjs.duration(10, "minutes"),
|
||||||
|
queryKey: "audiobookshelfDashboard",
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { NavidromeDashboardData } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
|
||||||
|
|
||||||
|
export const navidromeRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
NavidromeDashboardData,
|
||||||
|
"navidrome",
|
||||||
|
Record<string, never>
|
||||||
|
>({
|
||||||
|
async requestAsync(integration) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.getDashboardDataAsync();
|
||||||
|
},
|
||||||
|
cacheDuration: dayjs.duration(10, "minutes"),
|
||||||
|
queryKey: "navidromeDashboard",
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { PaperlessNgxStats } from "@homarr/integrations";
|
||||||
|
|
||||||
|
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
|
||||||
|
|
||||||
|
export const paperlessNgxStatsRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
PaperlessNgxStats,
|
||||||
|
"paperlessNgx",
|
||||||
|
Record<string, never>
|
||||||
|
>({
|
||||||
|
async requestAsync(integration) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.getStatsAsync();
|
||||||
|
},
|
||||||
|
cacheDuration: dayjs.duration(15, "minute"),
|
||||||
|
queryKey: "paperless-ngx-stats",
|
||||||
|
});
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
import dayjs from "dayjs";
|
||||||
|
|
||||||
|
import { createIntegrationAsync } from "@homarr/integrations";
|
||||||
|
import type { UptimeKumaDashboardData } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
import { createCachedIntegrationRequestHandler } from "./lib/cached-integration-request-handler";
|
||||||
|
|
||||||
|
export const uptimeKumaRequestHandler = createCachedIntegrationRequestHandler<
|
||||||
|
UptimeKumaDashboardData,
|
||||||
|
"uptimeKuma",
|
||||||
|
Record<string, never>
|
||||||
|
>({
|
||||||
|
async requestAsync(integration, _input) {
|
||||||
|
const integrationInstance = await createIntegrationAsync(integration);
|
||||||
|
return await integrationInstance.getDashboardDataAsync();
|
||||||
|
},
|
||||||
|
cacheDuration: dayjs.duration(1, "minute"),
|
||||||
|
queryKey: "uptimeKumaDashboard",
|
||||||
|
});
|
||||||
@@ -808,10 +808,13 @@
|
|||||||
"firewall": "Firewall",
|
"firewall": "Firewall",
|
||||||
"timetable": "Timetable",
|
"timetable": "Timetable",
|
||||||
"photoService": "Photos",
|
"photoService": "Photos",
|
||||||
|
"documents": "Documents",
|
||||||
"notes": "Notes",
|
"notes": "Notes",
|
||||||
"mediaMonitoring": "Monitoring",
|
"mediaMonitoring": "Monitoring",
|
||||||
"speedtest": "Speed Test",
|
"speedtest": "Speed Test",
|
||||||
"analytics": "Analytics"
|
"analytics": "Analytics",
|
||||||
|
"mediaLibrary": "Media Library",
|
||||||
|
"uptimeMonitoring": "Uptime Monitoring"
|
||||||
},
|
},
|
||||||
"testConnection": {
|
"testConnection": {
|
||||||
"action": {
|
"action": {
|
||||||
@@ -1084,6 +1087,10 @@
|
|||||||
"privateKey": {
|
"privateKey": {
|
||||||
"label": "Private key",
|
"label": "Private key",
|
||||||
"newLabel": "New private key"
|
"newLabel": "New private key"
|
||||||
|
},
|
||||||
|
"slug": {
|
||||||
|
"label": "Status page slug",
|
||||||
|
"newLabel": "New status page slug"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -1091,6 +1098,30 @@
|
|||||||
"use": "Select integrations in items",
|
"use": "Select integrations in items",
|
||||||
"interact": "Interact with integrations",
|
"interact": "Interact with integrations",
|
||||||
"full": "Full integration access"
|
"full": "Full integration access"
|
||||||
|
},
|
||||||
|
"audiobookshelf": {
|
||||||
|
"name": "Audiobookshelf",
|
||||||
|
"description": "Self-hosted audiobook and podcast server"
|
||||||
|
},
|
||||||
|
"navidrome": {
|
||||||
|
"name": "Navidrome",
|
||||||
|
"description": "Self-hosted music streaming server with Subsonic API compatibility"
|
||||||
|
},
|
||||||
|
"uptimeKuma": {
|
||||||
|
"name": "Uptime Kuma",
|
||||||
|
"description": "Self-hosted uptime monitoring with public status pages",
|
||||||
|
"secret": {
|
||||||
|
"slug": {
|
||||||
|
"description": "The slug of your public status page. Defaults to \"default\" if not set."
|
||||||
|
},
|
||||||
|
"apiKey": {
|
||||||
|
"description": "Optional API key for authenticated /metrics access"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"paperlessNgx": {
|
||||||
|
"name": "Paperless-ngx",
|
||||||
|
"description": "Document management system for archiving and organizing scanned documents"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"media": {
|
"media": {
|
||||||
@@ -2429,6 +2460,51 @@
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"paperlessNgx": {
|
||||||
|
"name": "Paperless-ngx",
|
||||||
|
"description": "Overview of your Paperless-ngx document archive",
|
||||||
|
"documentsTotal": "Total Documents",
|
||||||
|
"documentsInbox": "Inbox",
|
||||||
|
"correspondents": "Correspondents",
|
||||||
|
"tags": "Tags",
|
||||||
|
"documentTypes": "Document Types",
|
||||||
|
"inboxRatio": "Inbox Ratio",
|
||||||
|
"inbox": "inbox",
|
||||||
|
"total": "total",
|
||||||
|
"option": {
|
||||||
|
"showInboxRatio": {
|
||||||
|
"label": "Show inbox ratio",
|
||||||
|
"description": "Display the inbox-to-total document ratio in the hero section"
|
||||||
|
},
|
||||||
|
"showInboxRing": {
|
||||||
|
"label": "Show inbox ring",
|
||||||
|
"description": "Display a progress ring alongside the inbox ratio"
|
||||||
|
},
|
||||||
|
"showDocumentsTotal": {
|
||||||
|
"label": "Show total documents",
|
||||||
|
"description": "Show the total number of documents in your archive"
|
||||||
|
},
|
||||||
|
"showDocumentsInbox": {
|
||||||
|
"label": "Show inbox count",
|
||||||
|
"description": "Show the number of unprocessed documents in the inbox"
|
||||||
|
},
|
||||||
|
"showCorrespondents": {
|
||||||
|
"label": "Show correspondents",
|
||||||
|
"description": "Show the total number of correspondents"
|
||||||
|
},
|
||||||
|
"showTags": {
|
||||||
|
"label": "Show tags",
|
||||||
|
"description": "Show the total number of tags"
|
||||||
|
},
|
||||||
|
"showDocumentTypes": {
|
||||||
|
"label": "Show document types",
|
||||||
|
"description": "Show the total number of document types"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Failed to fetch Paperless-ngx data"
|
||||||
|
}
|
||||||
|
},
|
||||||
"immich-serverStats": {
|
"immich-serverStats": {
|
||||||
"name": "Immich Server Stats",
|
"name": "Immich Server Stats",
|
||||||
"description": "Information about your Immich instance",
|
"description": "Information about your Immich instance",
|
||||||
@@ -3037,6 +3113,113 @@
|
|||||||
"internalServerError": "Failed to fetch speedtest data"
|
"internalServerError": "Failed to fetch speedtest data"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"uptimeKuma": {
|
||||||
|
"name": "Uptime Kuma",
|
||||||
|
"description": "Monitor uptime statistics from your Uptime Kuma status page",
|
||||||
|
"option": {
|
||||||
|
"showAverageUptime": {
|
||||||
|
"label": "Show average uptime",
|
||||||
|
"description": "Display the combined 24-hour average uptime percentage"
|
||||||
|
},
|
||||||
|
"showUptimeRing": {
|
||||||
|
"label": "Show uptime ring",
|
||||||
|
"description": "Display a progress ring alongside the average uptime value"
|
||||||
|
},
|
||||||
|
"showTotalMonitors": {
|
||||||
|
"label": "Show total monitors",
|
||||||
|
"description": "Display the total number of configured monitors"
|
||||||
|
},
|
||||||
|
"showUpCount": {
|
||||||
|
"label": "Show up count",
|
||||||
|
"description": "Display how many monitors are currently up"
|
||||||
|
},
|
||||||
|
"showDownCount": {
|
||||||
|
"label": "Show down count",
|
||||||
|
"description": "Display how many monitors are currently down"
|
||||||
|
},
|
||||||
|
"showPausedCount": {
|
||||||
|
"label": "Show paused count",
|
||||||
|
"description": "Display how many monitors are currently paused"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"averageUptime": "Average uptime (24h)",
|
||||||
|
"stats": {
|
||||||
|
"totalMonitors": "Total monitors",
|
||||||
|
"upCount": "Up",
|
||||||
|
"downCount": "Down",
|
||||||
|
"pausedCount": "Paused"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Failed to fetch uptime data"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"audioStats": {
|
||||||
|
"name": "Audio stats",
|
||||||
|
"description": "Library and playback statistics from Navidrome or Audiobookshelf",
|
||||||
|
"option": {
|
||||||
|
"showArtists": {
|
||||||
|
"label": "Show artists",
|
||||||
|
"description": "Show the total number of artists in your music library (Navidrome)"
|
||||||
|
},
|
||||||
|
"showAlbums": {
|
||||||
|
"label": "Show albums",
|
||||||
|
"description": "Show the total number of albums in your music library (Navidrome)"
|
||||||
|
},
|
||||||
|
"showSongs": {
|
||||||
|
"label": "Show songs",
|
||||||
|
"description": "Show the total number of songs in your music library (Navidrome)"
|
||||||
|
},
|
||||||
|
"showNowPlaying": {
|
||||||
|
"label": "Show now playing",
|
||||||
|
"description": "Show tracks currently being played (Navidrome)"
|
||||||
|
},
|
||||||
|
"showNowPlayingList": {
|
||||||
|
"label": "Show now playing list",
|
||||||
|
"description": "Show individual tracks instead of only the active stream count (Navidrome)"
|
||||||
|
},
|
||||||
|
"maxNowPlayingItems": {
|
||||||
|
"label": "Max now playing items",
|
||||||
|
"description": "Maximum number of tracks to show in the now playing list (Navidrome)"
|
||||||
|
},
|
||||||
|
"showLibraryCount": {
|
||||||
|
"label": "Show library count",
|
||||||
|
"description": "Show the number of libraries on your instance (Audiobookshelf)"
|
||||||
|
},
|
||||||
|
"showAudiobooks": {
|
||||||
|
"label": "Show audiobooks",
|
||||||
|
"description": "Show the total number of audiobooks across all libraries (Audiobookshelf)"
|
||||||
|
},
|
||||||
|
"showPodcasts": {
|
||||||
|
"label": "Show podcasts",
|
||||||
|
"description": "Show the total number of podcasts across all libraries (Audiobookshelf)"
|
||||||
|
},
|
||||||
|
"showListeningTime": {
|
||||||
|
"label": "Show listening time",
|
||||||
|
"description": "Show your total listening time (Audiobookshelf)"
|
||||||
|
},
|
||||||
|
"showActiveSessions": {
|
||||||
|
"label": "Show active sessions",
|
||||||
|
"description": "Show the number of currently active playback sessions (Audiobookshelf)"
|
||||||
|
},
|
||||||
|
"compactMode": {
|
||||||
|
"label": "Compact mode",
|
||||||
|
"description": "Use a denser layout with smaller tiles, ideal for small widget sizes"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"artists": "Artists",
|
||||||
|
"albums": "Albums",
|
||||||
|
"songs": "Songs",
|
||||||
|
"libraryCount": "Libraries",
|
||||||
|
"audiobooks": "Audiobooks",
|
||||||
|
"podcasts": "Podcasts",
|
||||||
|
"listeningTime": "Listening Time",
|
||||||
|
"activeSessions": "Active Sessions",
|
||||||
|
"nowPlaying": "Now Playing",
|
||||||
|
"nowPlayingCount": "{count, plural, one {# stream} other {# streams}}",
|
||||||
|
"error": {
|
||||||
|
"internalServerError": "Failed to fetch audio stats data"
|
||||||
|
}
|
||||||
|
},
|
||||||
"systemResources": {
|
"systemResources": {
|
||||||
"name": "System resources",
|
"name": "System resources",
|
||||||
"description": "CPU, Memory, Disk and other hardware usage of your system",
|
"description": "CPU, Memory, Disk and other hardware usage of your system",
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { CSSProperties } from "react";
|
||||||
|
import { Badge, Text } from "@mantine/core";
|
||||||
|
import { IconHeadphones } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import type { AudiobookshelfDashboardData, NavidromeDashboardData } from "@homarr/integrations/types";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import classes from "./component.module.css";
|
||||||
|
import type { AudioStatsBackend, AudioStatsDisplayOptions } from "./shared";
|
||||||
|
import { AUDIO_STATS_TRANSLATION_SCOPE, getGridCols, getIconSize, getVisibleStats } from "./shared";
|
||||||
|
|
||||||
|
const rootClassByCompact = {
|
||||||
|
true: classes.rootCompact,
|
||||||
|
false: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const gridClassByCompact = {
|
||||||
|
true: classes.gridCompact,
|
||||||
|
false: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statTileClassByCompact = {
|
||||||
|
true: classes.statTileCompact,
|
||||||
|
false: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
interface AudioStatsContentProps {
|
||||||
|
backend: AudioStatsBackend;
|
||||||
|
stats: NavidromeDashboardData | AudiobookshelfDashboardData;
|
||||||
|
options: AudioStatsDisplayOptions;
|
||||||
|
width: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AudioStatsContent({ backend, stats, options, width }: AudioStatsContentProps) {
|
||||||
|
const t = useScopedI18n(AUDIO_STATS_TRANSLATION_SCOPE);
|
||||||
|
const visibleStats = getVisibleStats(backend, options, stats);
|
||||||
|
const compactKey = String(options.compactMode ?? false) as keyof typeof rootClassByCompact;
|
||||||
|
const gridCols = getGridCols(width, visibleStats.length, options.compactMode ?? false);
|
||||||
|
const iconSize = getIconSize(width, options.compactMode ?? false);
|
||||||
|
|
||||||
|
const navidromeStatsByBackend: Record<AudioStatsBackend, NavidromeDashboardData | null> = {
|
||||||
|
navidrome: stats as NavidromeDashboardData,
|
||||||
|
audiobookshelf: null,
|
||||||
|
};
|
||||||
|
const navidromeStats = navidromeStatsByBackend[backend];
|
||||||
|
const showNowPlayingSection =
|
||||||
|
navidromeStats !== null && Boolean(options.showNowPlaying) && navidromeStats.nowPlaying.length > 0;
|
||||||
|
|
||||||
|
const nowPlayingLimitByListVisibility = {
|
||||||
|
true: options.maxNowPlayingItems ?? 3,
|
||||||
|
false: 0,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const nowPlayingTracks =
|
||||||
|
navidromeStats?.nowPlaying.slice(
|
||||||
|
0,
|
||||||
|
nowPlayingLimitByListVisibility[
|
||||||
|
String(options.showNowPlayingList) as keyof typeof nowPlayingLimitByListVisibility
|
||||||
|
],
|
||||||
|
) ?? [];
|
||||||
|
|
||||||
|
const hasContent = visibleStats.length > 0 || showNowPlayingSection;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`${classes.root} ${rootClassByCompact[compactKey]}`}>
|
||||||
|
{visibleStats.length > 0 && (
|
||||||
|
<div
|
||||||
|
className={`${classes.grid} ${gridClassByCompact[compactKey]}`}
|
||||||
|
style={{ "--stat-cols": gridCols } as CSSProperties}
|
||||||
|
>
|
||||||
|
{visibleStats.map(({ optionKey, statKey, value, Icon }) => (
|
||||||
|
<div key={optionKey} className={`${classes.statTile} ${statTileClassByCompact[compactKey]}`}>
|
||||||
|
<Icon className={classes.statIcon} size={iconSize} stroke={1.5} />
|
||||||
|
<span className={classes.statValue}>{value}</span>
|
||||||
|
<span className={classes.statLabel}>{t(statKey as never)}</span>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{showNowPlayingSection && navidromeStats && (
|
||||||
|
<div className={classes.nowPlaying}>
|
||||||
|
<div className={classes.nowPlayingHeader}>
|
||||||
|
<IconHeadphones size={iconSize} stroke={1.5} />
|
||||||
|
<span className={classes.nowPlayingTitle}>{t("nowPlaying" as never)}</span>
|
||||||
|
{!options.showNowPlayingList && (
|
||||||
|
<Badge className={classes.nowPlayingCount} variant="light" size="sm">
|
||||||
|
{(t as unknown as (key: string, params?: { count: number }) => string)("nowPlayingCount", {
|
||||||
|
count: navidromeStats.nowPlaying.length,
|
||||||
|
})}
|
||||||
|
</Badge>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{options.showNowPlayingList && (
|
||||||
|
<div className={classes.nowPlayingList}>
|
||||||
|
{nowPlayingTracks.map((track, index) => (
|
||||||
|
<div key={`${track.username}-${track.title}-${index}`} className={classes.nowPlayingItem}>
|
||||||
|
<div className={classes.trackInfo}>
|
||||||
|
<span className={classes.trackTitle}>{track.title}</span>
|
||||||
|
<span className={classes.trackArtist}>
|
||||||
|
{[track.artist, track.album].filter(Boolean).join(" · ")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<Badge className={classes.trackUser} variant="outline" size="xs">
|
||||||
|
{track.username || track.playerName}
|
||||||
|
</Badge>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!hasContent && (
|
||||||
|
<div className={classes.emptyState}>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
—
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import type { AudiobookshelfDashboardData, NavidromeDashboardData } from "@homarr/integrations/types";
|
||||||
|
|
||||||
|
import { getGridCols, getIconSize, getVisibleStats } from "./shared";
|
||||||
|
|
||||||
|
describe("getGridCols", () => {
|
||||||
|
test("caps columns to visible stat count", () => {
|
||||||
|
expect(getGridCols(500, 2, false)).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns max cols when many stats visible", () => {
|
||||||
|
expect(getGridCols(500, 10, false)).toBe(5);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("compact mode uses smaller breakpoints", () => {
|
||||||
|
expect(getGridCols(290, 5, true)).toBe(5);
|
||||||
|
expect(getGridCols(290, 5, false)).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns at least 1 col even with 0 visible stats", () => {
|
||||||
|
expect(getGridCols(500, 0, false)).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getIconSize", () => {
|
||||||
|
test("returns large size for wide container", () => {
|
||||||
|
expect(getIconSize(400, false)).toBe(22);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns compact size for narrow container in compact mode", () => {
|
||||||
|
expect(getIconSize(100, true)).toBe(14);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns fallback for very narrow non-compact container", () => {
|
||||||
|
expect(getIconSize(50, false)).toBe(16);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("getVisibleStats", () => {
|
||||||
|
const navidromeStats: NavidromeDashboardData = {
|
||||||
|
artistCount: 100,
|
||||||
|
albumCount: 200,
|
||||||
|
songCount: 3000,
|
||||||
|
nowPlaying: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const audiobookshelfStats: AudiobookshelfDashboardData = {
|
||||||
|
libraryCount: 3,
|
||||||
|
totalAudiobooks: 150,
|
||||||
|
totalPodcasts: 20,
|
||||||
|
totalListeningTimeSeconds: 86400,
|
||||||
|
activeSessions: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("returns only enabled navidrome stats", () => {
|
||||||
|
const result = getVisibleStats(
|
||||||
|
"navidrome",
|
||||||
|
{ showArtists: true, showAlbums: false, showSongs: true },
|
||||||
|
navidromeStats,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(2);
|
||||||
|
expect(result.map((s) => s.statKey)).toEqual(["artists", "songs"]);
|
||||||
|
expect(result[0]?.value).toBe(100);
|
||||||
|
expect(result[1]?.value).toBe(3000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns only enabled audiobookshelf stats", () => {
|
||||||
|
const result = getVisibleStats(
|
||||||
|
"audiobookshelf",
|
||||||
|
{
|
||||||
|
showLibraryCount: true,
|
||||||
|
showAudiobooks: true,
|
||||||
|
showPodcasts: false,
|
||||||
|
showListeningTime: false,
|
||||||
|
showActiveSessions: true,
|
||||||
|
},
|
||||||
|
audiobookshelfStats,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(3);
|
||||||
|
expect(result.map((s) => s.statKey)).toEqual(["libraryCount", "audiobooks", "activeSessions"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns empty array when all options disabled", () => {
|
||||||
|
const result = getVisibleStats("navidrome", {}, navidromeStats);
|
||||||
|
expect(result).toEqual([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("formats listening time as duration string", () => {
|
||||||
|
const result = getVisibleStats("audiobookshelf", { showListeningTime: true }, audiobookshelfStats);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(typeof result[0]?.value).toBe("string");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,185 @@
|
|||||||
|
.root {
|
||||||
|
container-type: size;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
padding: clamp(6px, 3cqi, 12px);
|
||||||
|
gap: clamp(4px, 2cqi, 8px);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.rootCompact {
|
||||||
|
padding: clamp(4px, 2cqi, 8px);
|
||||||
|
gap: clamp(2px, 1cqi, 4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
flex: 1;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
gap: clamp(4px, 2cqi, 8px);
|
||||||
|
grid-template-columns: repeat(var(--stat-cols, 2), minmax(0, 1fr));
|
||||||
|
grid-auto-rows: 1fr;
|
||||||
|
align-content: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.gridCompact {
|
||||||
|
gap: clamp(2px, 1cqi, 4px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTile {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
height: 100%;
|
||||||
|
gap: clamp(2px, 1.5cqi, 4px);
|
||||||
|
padding: clamp(4px, 2cqi, 8px);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTileCompact {
|
||||||
|
gap: clamp(1px, 0.8cqi, 2px);
|
||||||
|
padding: clamp(2px, 1.2cqi, 5px);
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
}
|
||||||
|
|
||||||
|
.statIcon {
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
flex-shrink: 0;
|
||||||
|
line-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statLabel {
|
||||||
|
font-size: clamp(8px, 2.5cqi, 11px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
text-align: center;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTileCompact .statLabel {
|
||||||
|
font-size: clamp(7px, 2cqi, 9px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.statValue {
|
||||||
|
font-size: clamp(13px, 5cqi, 20px);
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--mantine-primary-color-filled);
|
||||||
|
line-height: 1.1;
|
||||||
|
text-align: center;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTileCompact .statValue {
|
||||||
|
font-size: clamp(11px, 4cqi, 16px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlaying {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: clamp(3px, 1.2cqi, 5px);
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlayingHeader {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: clamp(4px, 1.5cqi, 6px);
|
||||||
|
font-size: clamp(10px, 2.8cqi, 12px);
|
||||||
|
font-weight: 600;
|
||||||
|
flex-shrink: 0;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlayingTitle {
|
||||||
|
min-width: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlayingCount {
|
||||||
|
flex-shrink: 0;
|
||||||
|
margin-inline-start: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlayingList {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: clamp(2px, 0.8cqi, 4px);
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nowPlayingItem {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: clamp(4px, 1.5cqi, 6px);
|
||||||
|
padding: clamp(3px, 1.2cqi, 6px) clamp(4px, 1.5cqi, 8px);
|
||||||
|
border-radius: var(--mantine-radius-sm);
|
||||||
|
background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));
|
||||||
|
min-width: 0;
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trackInfo {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1px;
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trackTitle {
|
||||||
|
font-size: clamp(9px, 2.6cqi, 12px);
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 1.2;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trackArtist {
|
||||||
|
font-size: clamp(8px, 2.2cqi, 10px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.trackUser {
|
||||||
|
flex-shrink: 0;
|
||||||
|
max-width: clamp(40px, 22cqi, 88px);
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emptyState {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
font-size: clamp(11px, 3cqi, 13px);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
|
||||||
|
import type { WidgetComponentProps } from "../definition";
|
||||||
|
import { AudioStatsContent } from "./audio-stats-content";
|
||||||
|
|
||||||
|
export default function AudioStatsWidget({ integrationIds, options, width }: WidgetComponentProps<"audioStats">) {
|
||||||
|
const [response] = clientApi.widget.audioStats.getStats.useSuspenseQuery({
|
||||||
|
integrationId: integrationIds[0] ?? "",
|
||||||
|
});
|
||||||
|
|
||||||
|
return <AudioStatsContent backend={response.kind} stats={response.data} options={options} width={width} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
import { IconHeadphones, IconServerOff } from "@tabler/icons-react";
|
||||||
|
import { z } from "zod/v4";
|
||||||
|
|
||||||
|
import { createWidgetDefinition } from "../definition";
|
||||||
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
|
const hideUnlessNavidrome = {
|
||||||
|
shouldHide: (_: unknown, integrationKinds: string[]) => !integrationKinds.includes("navidrome"),
|
||||||
|
};
|
||||||
|
|
||||||
|
const hideUnlessAudiobookshelf = {
|
||||||
|
shouldHide: (_: unknown, integrationKinds: string[]) => !integrationKinds.includes("audiobookshelf"),
|
||||||
|
};
|
||||||
|
|
||||||
|
export const { definition, componentLoader } = createWidgetDefinition("audioStats", {
|
||||||
|
icon: IconHeadphones,
|
||||||
|
supportedIntegrations: ["navidrome", "audiobookshelf"],
|
||||||
|
integrationsRequired: true,
|
||||||
|
maxIntegrations: 1,
|
||||||
|
createOptions() {
|
||||||
|
return optionsBuilder.from(
|
||||||
|
(factory) => ({
|
||||||
|
showArtists: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showAlbums: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showSongs: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showNowPlaying: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showNowPlayingList: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
maxNowPlayingItems: factory.number({
|
||||||
|
defaultValue: 3,
|
||||||
|
validate: z.number().min(1).max(5),
|
||||||
|
step: 1,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showLibraryCount: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showAudiobooks: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showPodcasts: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showListeningTime: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
showActiveSessions: factory.switch({ defaultValue: true, withDescription: true }),
|
||||||
|
compactMode: factory.switch({ defaultValue: false, withDescription: true }),
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
showArtists: hideUnlessNavidrome,
|
||||||
|
showAlbums: hideUnlessNavidrome,
|
||||||
|
showSongs: hideUnlessNavidrome,
|
||||||
|
showNowPlaying: hideUnlessNavidrome,
|
||||||
|
showNowPlayingList: hideUnlessNavidrome,
|
||||||
|
maxNowPlayingItems: hideUnlessNavidrome,
|
||||||
|
showLibraryCount: hideUnlessAudiobookshelf,
|
||||||
|
showAudiobooks: hideUnlessAudiobookshelf,
|
||||||
|
showPodcasts: hideUnlessAudiobookshelf,
|
||||||
|
showListeningTime: hideUnlessAudiobookshelf,
|
||||||
|
showActiveSessions: hideUnlessAudiobookshelf,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.audioStats.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
import type { TablerIcon } from "@tabler/icons-react";
|
||||||
|
import {
|
||||||
|
IconAlbum,
|
||||||
|
IconBook,
|
||||||
|
IconBooks,
|
||||||
|
IconDisc,
|
||||||
|
IconHeadphones,
|
||||||
|
IconMicrophone,
|
||||||
|
IconMicrophone2,
|
||||||
|
IconPlayerPlay,
|
||||||
|
} from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import type { AudiobookshelfDashboardData, NavidromeDashboardData } from "@homarr/integrations/types";
|
||||||
|
import { formatDuration } from "@homarr/common";
|
||||||
|
|
||||||
|
export type AudioStatsBackend = "navidrome" | "audiobookshelf";
|
||||||
|
|
||||||
|
export interface NavidromeDisplayOptions {
|
||||||
|
showArtists: boolean;
|
||||||
|
showAlbums: boolean;
|
||||||
|
showSongs: boolean;
|
||||||
|
showNowPlaying: boolean;
|
||||||
|
showNowPlayingList: boolean;
|
||||||
|
maxNowPlayingItems: number;
|
||||||
|
compactMode?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AudiobookshelfDisplayOptions {
|
||||||
|
showLibraryCount: boolean;
|
||||||
|
showAudiobooks: boolean;
|
||||||
|
showPodcasts: boolean;
|
||||||
|
showListeningTime: boolean;
|
||||||
|
showActiveSessions: boolean;
|
||||||
|
compactMode: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AudioStatsDisplayOptions = Partial<NavidromeDisplayOptions & AudiobookshelfDisplayOptions>;
|
||||||
|
|
||||||
|
const navidromeStatVisibilityOptions = {
|
||||||
|
showArtists: "artists",
|
||||||
|
showAlbums: "albums",
|
||||||
|
showSongs: "songs",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const audiobookshelfStatVisibilityOptions = {
|
||||||
|
showLibraryCount: "libraryCount",
|
||||||
|
showAudiobooks: "audiobooks",
|
||||||
|
showPodcasts: "podcasts",
|
||||||
|
showListeningTime: "listeningTime",
|
||||||
|
showActiveSessions: "activeSessions",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statVisibilityOptionsByBackend = {
|
||||||
|
navidrome: navidromeStatVisibilityOptions,
|
||||||
|
audiobookshelf: audiobookshelfStatVisibilityOptions,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const navidromeStatIcons = {
|
||||||
|
artists: IconMicrophone2,
|
||||||
|
albums: IconAlbum,
|
||||||
|
songs: IconDisc,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const audiobookshelfStatIcons = {
|
||||||
|
libraryCount: IconBooks,
|
||||||
|
audiobooks: IconBook,
|
||||||
|
podcasts: IconMicrophone,
|
||||||
|
listeningTime: IconHeadphones,
|
||||||
|
activeSessions: IconPlayerPlay,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statIconsByBackend = {
|
||||||
|
navidrome: navidromeStatIcons,
|
||||||
|
audiobookshelf: audiobookshelfStatIcons,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const gridColsByCompact = {
|
||||||
|
true: [
|
||||||
|
{ minWidth: 280, cols: 5 },
|
||||||
|
{ minWidth: 180, cols: 3 },
|
||||||
|
{ minWidth: 110, cols: 2 },
|
||||||
|
{ minWidth: 0, cols: 1 },
|
||||||
|
],
|
||||||
|
false: [
|
||||||
|
{ minWidth: 420, cols: 5 },
|
||||||
|
{ minWidth: 300, cols: 3 },
|
||||||
|
{ minWidth: 180, cols: 2 },
|
||||||
|
{ minWidth: 0, cols: 1 },
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const iconSizeByCompact = {
|
||||||
|
true: [
|
||||||
|
{ minWidth: 260, size: 18 },
|
||||||
|
{ minWidth: 160, size: 16 },
|
||||||
|
{ minWidth: 0, size: 14 },
|
||||||
|
],
|
||||||
|
false: [
|
||||||
|
{ minWidth: 320, size: 22 },
|
||||||
|
{ minWidth: 200, size: 18 },
|
||||||
|
{ minWidth: 0, size: 16 },
|
||||||
|
],
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export interface VisibleStat {
|
||||||
|
optionKey: string;
|
||||||
|
statKey: string;
|
||||||
|
value: string | number;
|
||||||
|
Icon: TablerIcon;
|
||||||
|
}
|
||||||
|
|
||||||
|
const getNavidromeStatValues = (stats: NavidromeDashboardData) =>
|
||||||
|
({
|
||||||
|
artists: stats.artistCount,
|
||||||
|
albums: stats.albumCount,
|
||||||
|
songs: stats.songCount,
|
||||||
|
}) as const;
|
||||||
|
|
||||||
|
const getAudiobookshelfStatValues = (stats: AudiobookshelfDashboardData) =>
|
||||||
|
({
|
||||||
|
libraryCount: stats.libraryCount,
|
||||||
|
audiobooks: stats.totalAudiobooks,
|
||||||
|
podcasts: stats.totalPodcasts,
|
||||||
|
listeningTime: formatDuration(stats.totalListeningTimeSeconds * 1000),
|
||||||
|
activeSessions: stats.activeSessions,
|
||||||
|
}) as const;
|
||||||
|
|
||||||
|
const statValueGetterByBackend = {
|
||||||
|
navidrome: (stats: NavidromeDashboardData | AudiobookshelfDashboardData) =>
|
||||||
|
getNavidromeStatValues(stats as NavidromeDashboardData),
|
||||||
|
audiobookshelf: (stats: NavidromeDashboardData | AudiobookshelfDashboardData) =>
|
||||||
|
getAudiobookshelfStatValues(stats as AudiobookshelfDashboardData),
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export const getVisibleStats = (
|
||||||
|
backend: AudioStatsBackend,
|
||||||
|
options: AudioStatsDisplayOptions,
|
||||||
|
stats: NavidromeDashboardData | AudiobookshelfDashboardData,
|
||||||
|
): VisibleStat[] => {
|
||||||
|
const visibilityOptions = statVisibilityOptionsByBackend[backend];
|
||||||
|
const statIcons = statIconsByBackend[backend];
|
||||||
|
const statValues = statValueGetterByBackend[backend](stats);
|
||||||
|
|
||||||
|
return Object.entries(visibilityOptions)
|
||||||
|
.filter(([optionKey]) => Boolean(options[optionKey as keyof typeof visibilityOptions]))
|
||||||
|
.map(([optionKey, statKey]) => ({
|
||||||
|
optionKey,
|
||||||
|
statKey,
|
||||||
|
value: statValues[statKey as keyof typeof statValues],
|
||||||
|
Icon: statIcons[statKey as keyof typeof statIcons],
|
||||||
|
}));
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getGridCols = (width: number, visibleCount: number, compact: boolean): number => {
|
||||||
|
const colsTable = gridColsByCompact[String(compact) as keyof typeof gridColsByCompact];
|
||||||
|
const match = colsTable.find(({ minWidth }) => width >= minWidth);
|
||||||
|
const maxCols = match?.cols ?? 1;
|
||||||
|
return Math.min(maxCols, Math.max(visibleCount, 1));
|
||||||
|
};
|
||||||
|
|
||||||
|
const fallbackIconSize = { true: 14, false: 16 } as const;
|
||||||
|
|
||||||
|
export const getIconSize = (width: number, compact: boolean): number => {
|
||||||
|
const sizeTable = iconSizeByCompact[String(compact) as keyof typeof iconSizeByCompact];
|
||||||
|
const match = sizeTable.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.size ?? fallbackIconSize[String(compact) as keyof typeof fallbackIconSize];
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AUDIO_STATS_TRANSLATION_SCOPE = "widget.audioStats" as const;
|
||||||
@@ -42,6 +42,7 @@ export interface WidgetDefinition {
|
|||||||
icon: TablerIcon;
|
icon: TablerIcon;
|
||||||
supportedIntegrations?: IntegrationKind[];
|
supportedIntegrations?: IntegrationKind[];
|
||||||
integrationsRequired?: boolean;
|
integrationsRequired?: boolean;
|
||||||
|
maxIntegrations?: number;
|
||||||
createOptions: (
|
createOptions: (
|
||||||
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
|
settings: Pick<SettingsContextProps, "enableStatusByDefault" | "forceDisableStatus">,
|
||||||
) => WidgetOptionsRecord;
|
) => WidgetOptionsRecord;
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
|||||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||||
|
|
||||||
import * as anchorNote from "./anchor-note";
|
import * as anchorNote from "./anchor-note";
|
||||||
|
import * as audioStats from "./audio-stats";
|
||||||
import * as app from "./app";
|
import * as app from "./app";
|
||||||
import * as bookmarks from "./bookmarks";
|
import * as bookmarks from "./bookmarks";
|
||||||
import * as calendar from "./calendar";
|
import * as calendar from "./calendar";
|
||||||
@@ -34,6 +35,7 @@ import * as minecraftServerStatus from "./minecraft/server-status";
|
|||||||
import * as networkControllerStatus from "./network-controller/network-status";
|
import * as networkControllerStatus from "./network-controller/network-status";
|
||||||
import * as networkControllerSummary from "./network-controller/summary";
|
import * as networkControllerSummary from "./network-controller/summary";
|
||||||
import * as notebook from "./notebook";
|
import * as notebook from "./notebook";
|
||||||
|
import * as paperlessNgx from "./paperless-ngx";
|
||||||
import * as notifications from "./notifications";
|
import * as notifications from "./notifications";
|
||||||
import type { WidgetOptionDefinition } from "./options";
|
import type { WidgetOptionDefinition } from "./options";
|
||||||
import * as releases from "./releases";
|
import * as releases from "./releases";
|
||||||
@@ -41,6 +43,7 @@ import * as rssFeed from "./rssFeed";
|
|||||||
import * as smartHomeEntityState from "./smart-home/entity-state";
|
import * as smartHomeEntityState from "./smart-home/entity-state";
|
||||||
import * as smartHomeExecuteAutomation from "./smart-home/execute-automation";
|
import * as smartHomeExecuteAutomation from "./smart-home/execute-automation";
|
||||||
import * as speedtestTracker from "./speedtest-tracker";
|
import * as speedtestTracker from "./speedtest-tracker";
|
||||||
|
import * as uptimeKuma from "./uptime-kuma";
|
||||||
import * as stockPrice from "./stocks";
|
import * as stockPrice from "./stocks";
|
||||||
import * as systemDisks from "./system-disks";
|
import * as systemDisks from "./system-disks";
|
||||||
import * as systemResources from "./system-resources";
|
import * as systemResources from "./system-resources";
|
||||||
@@ -53,7 +56,6 @@ import * as weather from "./weather";
|
|||||||
|
|
||||||
export type { WidgetDefinition, WidgetOptionsSettings } from "./definition";
|
export type { WidgetDefinition, WidgetOptionsSettings } from "./definition";
|
||||||
export type { WidgetComponentProps };
|
export type { WidgetComponentProps };
|
||||||
export type { WidgetOptionDefinition, WidgetOptionType } from "./options";
|
|
||||||
|
|
||||||
export const widgetImports = {
|
export const widgetImports = {
|
||||||
clock,
|
clock,
|
||||||
@@ -92,8 +94,11 @@ export const widgetImports = {
|
|||||||
timetable,
|
timetable,
|
||||||
"immich-serverStats": immichServerStats,
|
"immich-serverStats": immichServerStats,
|
||||||
"immich-albumCarousel": immichAlbumCarousel,
|
"immich-albumCarousel": immichAlbumCarousel,
|
||||||
|
paperlessNgx,
|
||||||
tracearr,
|
tracearr,
|
||||||
speedtestTracker,
|
speedtestTracker,
|
||||||
|
uptimeKuma,
|
||||||
|
audioStats,
|
||||||
umami,
|
umami,
|
||||||
ups,
|
ups,
|
||||||
} satisfies WidgetImportRecord;
|
} satisfies WidgetImportRecord;
|
||||||
|
|||||||
@@ -117,6 +117,10 @@ export const WidgetEditModal = createModal<ModalProps<WidgetKind>>(({ actions, i
|
|||||||
<WidgetIntegrationSelect
|
<WidgetIntegrationSelect
|
||||||
label={t("item.edit.field.integrations.label")}
|
label={t("item.edit.field.integrations.label")}
|
||||||
data={innerProps.integrationData}
|
data={innerProps.integrationData}
|
||||||
|
canSelectMultiple={
|
||||||
|
((widgetImports[innerProps.kind].definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity) >
|
||||||
|
1
|
||||||
|
}
|
||||||
{...form.getInputProps("integrationIds")}
|
{...form.getInputProps("integrationIds")}
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
.root {
|
||||||
|
container-type: size;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
padding: clamp(6px, 3cqi, 14px);
|
||||||
|
gap: clamp(4px, 2cqi, 10px);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: clamp(8px, 3cqi, 18px);
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding-bottom: clamp(4px, 2cqi, 10px);
|
||||||
|
border-bottom: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroExpanded {
|
||||||
|
flex: 1;
|
||||||
|
border-bottom: none;
|
||||||
|
justify-content: center;
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly .heroText {
|
||||||
|
align-items: center;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly .heroInbox {
|
||||||
|
font-size: clamp(18px, 8cqi, 32px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroText {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: clamp(2px, 1cqi, 4px);
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroLabel {
|
||||||
|
font-size: clamp(9px, 2.8cqi, 13px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroCounts {
|
||||||
|
display: flex;
|
||||||
|
align-items: baseline;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: clamp(4px, 1.5cqi, 6px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroInbox {
|
||||||
|
font-size: clamp(16px, 6cqi, 24px);
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--mantine-color-orange-6);
|
||||||
|
line-height: 1.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTotal {
|
||||||
|
font-size: clamp(11px, 3.5cqi, 15px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ring {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
gap: clamp(4px, 2cqi, 10px);
|
||||||
|
grid-template-columns: repeat(var(--stat-cols, 2), minmax(0, 1fr));
|
||||||
|
grid-auto-rows: 1fr;
|
||||||
|
align-content: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTile {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
gap: clamp(2px, 1.5cqi, 5px);
|
||||||
|
padding: clamp(4px, 2.5cqi, 10px);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statIcon {
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statLabel {
|
||||||
|
font-size: clamp(8px, 2.5cqi, 12px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
text-align: center;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statValue {
|
||||||
|
font-size: clamp(14px, 5.5cqi, 24px);
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--mantine-primary-color-filled);
|
||||||
|
line-height: 1.1;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emptyState {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
font-size: clamp(11px, 3cqi, 14px);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { Fragment } from "react";
|
||||||
|
import type { CSSProperties } from "react";
|
||||||
|
import { RingProgress, Text } from "@mantine/core";
|
||||||
|
import { IconFileDescription, IconFileText, IconInbox, IconTag, IconUsers } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import type { WidgetComponentProps } from "../definition";
|
||||||
|
import classes from "./component.module.css";
|
||||||
|
|
||||||
|
const statVisibilityByOption = {
|
||||||
|
showDocumentsTotal: "documentsTotal",
|
||||||
|
showDocumentsInbox: "documentsInbox",
|
||||||
|
showCorrespondents: "correspondents",
|
||||||
|
showTags: "tags",
|
||||||
|
showDocumentTypes: "documentTypes",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statIcons = {
|
||||||
|
documentsTotal: IconFileText,
|
||||||
|
documentsInbox: IconInbox,
|
||||||
|
correspondents: IconUsers,
|
||||||
|
tags: IconTag,
|
||||||
|
documentTypes: IconFileDescription,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const gridHiddenWhenHeroShown = new Set(["documentsTotal", "documentsInbox"]);
|
||||||
|
|
||||||
|
const gridColsByWidth = [
|
||||||
|
{ minWidth: 380, cols: 3 },
|
||||||
|
{ minWidth: 220, cols: 2 },
|
||||||
|
{ minWidth: 0, cols: 1 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ringSizeByWidth = [
|
||||||
|
{ minWidth: 400, size: 88 },
|
||||||
|
{ minWidth: 320, size: 72 },
|
||||||
|
{ minWidth: 220, size: 56 },
|
||||||
|
{ minWidth: 0, size: 44 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const iconSizeByWidth = [
|
||||||
|
{ minWidth: 320, size: 22 },
|
||||||
|
{ minWidth: 200, size: 18 },
|
||||||
|
{ minWidth: 0, size: 16 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ringLabelSizeByRingSize = [
|
||||||
|
{ minSize: 72, size: "sm" },
|
||||||
|
{ minSize: 56, size: "xs" },
|
||||||
|
{ minSize: 0, size: "xs" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const heroLayoutBySecondaryStats = {
|
||||||
|
false: classes.heroExpanded,
|
||||||
|
true: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const heroVariantByRing = {
|
||||||
|
true: "",
|
||||||
|
false: classes.heroTextOnly,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const heroPartVisibility = {
|
||||||
|
ratio: "showInboxRatio",
|
||||||
|
ring: "showInboxRing",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export default function PaperlessNgxWidget({ integrationIds, options, width }: WidgetComponentProps<"paperlessNgx">) {
|
||||||
|
const t = useScopedI18n("widget.paperlessNgx");
|
||||||
|
const [stats] = clientApi.widget.paperlessNgx.getStats.useSuspenseQuery({
|
||||||
|
integrationId: integrationIds[0] ?? "",
|
||||||
|
});
|
||||||
|
|
||||||
|
const canShowInboxHero = options.showDocumentsInbox && options.showDocumentsTotal;
|
||||||
|
const showHero = options.showInboxRatio && canShowInboxHero;
|
||||||
|
const inboxProgress = computeInboxProgress(stats.documentsTotal, stats.documentsInbox);
|
||||||
|
|
||||||
|
const statValues = {
|
||||||
|
documentsTotal: stats.documentsTotal,
|
||||||
|
documentsInbox: stats.documentsInbox,
|
||||||
|
correspondents: stats.correspondentsCount,
|
||||||
|
tags: stats.tagsCount,
|
||||||
|
documentTypes: stats.documentTypesCount,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const visibleStatKeys = Object.entries(statVisibilityByOption)
|
||||||
|
.filter(([optionKey]) => options[optionKey as keyof typeof options])
|
||||||
|
.map(([, statKey]) => statKey)
|
||||||
|
.filter((statKey) => !(showHero && gridHiddenWhenHeroShown.has(statKey)));
|
||||||
|
|
||||||
|
const gridCols = getGridCols(width);
|
||||||
|
const ringSize = getRingSize(width);
|
||||||
|
const iconSize = getIconSize(width);
|
||||||
|
const ringLabelSize = getRingLabelSize(ringSize);
|
||||||
|
const hasContent = showHero || visibleStatKeys.length > 0;
|
||||||
|
|
||||||
|
const heroLayoutClass =
|
||||||
|
heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats];
|
||||||
|
const heroRingClass = heroVariantByRing[String(options.showInboxRing) as keyof typeof heroVariantByRing];
|
||||||
|
|
||||||
|
const visibleHeroParts = Object.entries(heroPartVisibility).filter(
|
||||||
|
([, optionKey]) => options[optionKey as keyof typeof options],
|
||||||
|
);
|
||||||
|
|
||||||
|
const heroPartRenderers = {
|
||||||
|
ratio: (
|
||||||
|
<div className={classes.heroText}>
|
||||||
|
<span className={classes.heroLabel}>{t("inboxRatio")}</span>
|
||||||
|
<div className={classes.heroCounts}>
|
||||||
|
<span className={classes.heroInbox}>
|
||||||
|
{stats.documentsInbox} {t("inbox")}
|
||||||
|
</span>
|
||||||
|
<span className={classes.heroTotal}>
|
||||||
|
/ {stats.documentsTotal} {t("total")}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
),
|
||||||
|
ring: (
|
||||||
|
<RingProgress
|
||||||
|
className={classes.ring}
|
||||||
|
size={ringSize}
|
||||||
|
thickness={Math.max(4, Math.round(ringSize / 10))}
|
||||||
|
roundCaps
|
||||||
|
sections={[{ value: inboxProgress, color: "orange" }]}
|
||||||
|
label={
|
||||||
|
<Text ta="center" size={ringLabelSize} fw={700}>
|
||||||
|
{inboxProgress}%
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={classes.root}>
|
||||||
|
{showHero && (
|
||||||
|
<div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}>
|
||||||
|
{visibleHeroParts.map(([partKey]) => (
|
||||||
|
<Fragment key={partKey}>{heroPartRenderers[partKey as keyof typeof heroPartRenderers]}</Fragment>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!hasContent && (
|
||||||
|
<div className={classes.emptyState}>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
—
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{visibleStatKeys.length > 0 && (
|
||||||
|
<div className={classes.grid} style={{ "--stat-cols": gridCols } as CSSProperties}>
|
||||||
|
{visibleStatKeys.map((statKey) => {
|
||||||
|
const Icon = statIcons[statKey];
|
||||||
|
return (
|
||||||
|
<div key={statKey} className={classes.statTile}>
|
||||||
|
<Icon className={classes.statIcon} size={iconSize} stroke={1.5} />
|
||||||
|
<span className={classes.statValue}>{statValues[statKey]}</span>
|
||||||
|
<span className={classes.statLabel}>{t(statKey)}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function computeInboxProgress(total: number, inbox: number): number {
|
||||||
|
if (total <= 0) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.round((inbox / total) * 100);
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGridCols(width: number): number {
|
||||||
|
const match = gridColsByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.cols ?? 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRingSize(width: number): number {
|
||||||
|
const match = ringSizeByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.size ?? 44;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getIconSize(width: number): number {
|
||||||
|
const match = iconSizeByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.size ?? 16;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRingLabelSize(ringSize: number): "xs" | "sm" {
|
||||||
|
const match = ringLabelSizeByRingSize.find(({ minSize }) => ringSize >= minSize);
|
||||||
|
return match?.size ?? "xs";
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { IconFileText, IconServerOff } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { createWidgetDefinition } from "../definition";
|
||||||
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
|
export const { definition, componentLoader } = createWidgetDefinition("paperlessNgx", {
|
||||||
|
icon: IconFileText,
|
||||||
|
supportedIntegrations: ["paperlessNgx"],
|
||||||
|
integrationsRequired: true,
|
||||||
|
createOptions() {
|
||||||
|
return optionsBuilder.from((factory) => ({
|
||||||
|
showInboxRatio: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showInboxRing: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showDocumentsTotal: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showDocumentsInbox: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showCorrespondents: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showTags: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showDocumentTypes: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.paperlessNgx.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
.root {
|
||||||
|
container-type: size;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
height: 100%;
|
||||||
|
min-height: 0;
|
||||||
|
padding: clamp(6px, 3cqi, 14px);
|
||||||
|
gap: clamp(4px, 2cqi, 10px);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hero {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: clamp(8px, 3cqi, 18px);
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding-bottom: clamp(4px, 2cqi, 10px);
|
||||||
|
border-bottom: 1px solid light-dark(var(--mantine-color-gray-2), var(--mantine-color-dark-4));
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroExpanded {
|
||||||
|
flex: 1;
|
||||||
|
border-bottom: none;
|
||||||
|
justify-content: center;
|
||||||
|
padding-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly {
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly .heroText {
|
||||||
|
align-items: center;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroTextOnly .heroValue {
|
||||||
|
font-size: clamp(22px, 10cqi, 36px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroText {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: clamp(2px, 1cqi, 4px);
|
||||||
|
min-width: 0;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroLabel {
|
||||||
|
font-size: clamp(9px, 2.8cqi, 13px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.heroValue {
|
||||||
|
font-size: clamp(18px, 8cqi, 32px);
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.ring {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statGrid {
|
||||||
|
display: grid;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
gap: clamp(4px, 2cqi, 10px);
|
||||||
|
grid-template-columns: repeat(var(--stat-cols, 2), minmax(0, 1fr));
|
||||||
|
grid-auto-rows: 1fr;
|
||||||
|
align-content: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statTile {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
min-width: 0;
|
||||||
|
gap: clamp(2px, 1.5cqi, 5px);
|
||||||
|
padding: clamp(4px, 2.5cqi, 10px);
|
||||||
|
border-radius: var(--mantine-radius-md);
|
||||||
|
background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statIcon {
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statValue {
|
||||||
|
font-size: clamp(14px, 5.5cqi, 24px);
|
||||||
|
font-weight: 700;
|
||||||
|
line-height: 1.1;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.statLabel {
|
||||||
|
font-size: clamp(8px, 2.5cqi, 12px);
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
line-height: 1.2;
|
||||||
|
text-align: center;
|
||||||
|
max-width: 100%;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.emptyState {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
min-height: 0;
|
||||||
|
color: var(--mantine-color-dimmed);
|
||||||
|
font-size: clamp(11px, 3cqi, 14px);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
@@ -0,0 +1,245 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import type { CSSProperties } from "react";
|
||||||
|
import { RingProgress, Text } from "@mantine/core";
|
||||||
|
import { IconArrowDown, IconArrowUp, IconClockPause, IconServer } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { clientApi } from "@homarr/api/client";
|
||||||
|
import { formatNumber } from "@homarr/common";
|
||||||
|
import type { UptimeKumaDashboardData } from "@homarr/integrations/types";
|
||||||
|
import { useScopedI18n } from "@homarr/translation/client";
|
||||||
|
|
||||||
|
import type { WidgetComponentProps } from "../definition";
|
||||||
|
import { NoIntegrationDataError } from "../errors/no-data-integration";
|
||||||
|
import classes from "./component.module.css";
|
||||||
|
|
||||||
|
const emptyDashboard: UptimeKumaDashboardData = {
|
||||||
|
totalMonitors: 0,
|
||||||
|
upCount: 0,
|
||||||
|
downCount: 0,
|
||||||
|
pausedCount: 0,
|
||||||
|
averageUptimePercent: 0,
|
||||||
|
monitors: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const statVisibilityByOption = {
|
||||||
|
showTotalMonitors: "totalMonitors",
|
||||||
|
showUpCount: "upCount",
|
||||||
|
showDownCount: "downCount",
|
||||||
|
showPausedCount: "pausedCount",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statIcons = {
|
||||||
|
totalMonitors: IconServer,
|
||||||
|
upCount: IconArrowUp,
|
||||||
|
downCount: IconArrowDown,
|
||||||
|
pausedCount: IconClockPause,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const statColorByKey = {
|
||||||
|
totalMonitors: "gray",
|
||||||
|
upCount: "green",
|
||||||
|
downCount: "red",
|
||||||
|
pausedCount: "yellow",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const uptimeTierByThreshold = [
|
||||||
|
[99, "excellent"],
|
||||||
|
[95, "good"],
|
||||||
|
[0, "poor"],
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const uptimeColorByTier = {
|
||||||
|
excellent: "green",
|
||||||
|
good: "yellow",
|
||||||
|
poor: "red",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const gridColsByWidth = [
|
||||||
|
{ minWidth: 380, cols: 4 },
|
||||||
|
{ minWidth: 260, cols: 2 },
|
||||||
|
{ minWidth: 0, cols: 2 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const ringSizeByWidth = [
|
||||||
|
{ minWidth: 400, size: 88 },
|
||||||
|
{ minWidth: 320, size: 72 },
|
||||||
|
{ minWidth: 220, size: 56 },
|
||||||
|
{ minWidth: 0, size: 44 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const iconSizeByWidth = [
|
||||||
|
{ minWidth: 320, size: 22 },
|
||||||
|
{ minWidth: 200, size: 18 },
|
||||||
|
{ minWidth: 0, size: 16 },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const heroLayoutBySecondaryStats = {
|
||||||
|
false: classes.heroExpanded,
|
||||||
|
true: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const heroVariantByRing = {
|
||||||
|
true: "",
|
||||||
|
false: classes.heroTextOnly,
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
export default function UptimeKumaWidget({
|
||||||
|
integrationIds,
|
||||||
|
isEditMode,
|
||||||
|
options,
|
||||||
|
width,
|
||||||
|
}: WidgetComponentProps<"uptimeKuma">) {
|
||||||
|
if (integrationIds.length === 0) {
|
||||||
|
throw new NoIntegrationDataError();
|
||||||
|
}
|
||||||
|
|
||||||
|
return <UptimeKumaContent integrationIds={integrationIds} isEditMode={isEditMode} options={options} width={width} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface UptimeKumaContentProps {
|
||||||
|
integrationIds: string[];
|
||||||
|
isEditMode: boolean;
|
||||||
|
options: WidgetComponentProps<"uptimeKuma">["options"];
|
||||||
|
width: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
function UptimeKumaContent({ integrationIds, isEditMode, options, width }: UptimeKumaContentProps) {
|
||||||
|
const t = useScopedI18n("widget.uptimeKuma");
|
||||||
|
const [dashboardData] = clientApi.widget.uptimeKuma.getDashboard.useSuspenseQuery({ integrationIds });
|
||||||
|
|
||||||
|
const utils = clientApi.useUtils();
|
||||||
|
clientApi.widget.uptimeKuma.subscribeToDashboard.useSubscription(
|
||||||
|
{ integrationIds },
|
||||||
|
{
|
||||||
|
enabled: !isEditMode,
|
||||||
|
onData(newData) {
|
||||||
|
utils.widget.uptimeKuma.getDashboard.setData({ integrationIds }, (prevData) => {
|
||||||
|
if (!prevData) return prevData;
|
||||||
|
return prevData.map((instance) => {
|
||||||
|
if (instance.integrationId === newData.integrationId) {
|
||||||
|
return { ...instance, dashboard: newData.dashboard, updatedAt: newData.timestamp };
|
||||||
|
}
|
||||||
|
return instance;
|
||||||
|
});
|
||||||
|
});
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const combined = dashboardData.reduce<UptimeKumaDashboardData>(
|
||||||
|
(acc, item) => ({
|
||||||
|
totalMonitors: acc.totalMonitors + item.dashboard.totalMonitors,
|
||||||
|
upCount: acc.upCount + item.dashboard.upCount,
|
||||||
|
downCount: acc.downCount + item.dashboard.downCount,
|
||||||
|
pausedCount: acc.pausedCount + item.dashboard.pausedCount,
|
||||||
|
averageUptimePercent: acc.averageUptimePercent + item.dashboard.averageUptimePercent,
|
||||||
|
monitors: [...acc.monitors, ...item.dashboard.monitors],
|
||||||
|
}),
|
||||||
|
emptyDashboard,
|
||||||
|
);
|
||||||
|
|
||||||
|
const instanceCount = dashboardData.length;
|
||||||
|
const averageUptime = combined.averageUptimePercent / Math.max(instanceCount, 1);
|
||||||
|
const uptimeValue = clampPercent(averageUptime);
|
||||||
|
const uptimeColor = getUptimeColor(uptimeValue);
|
||||||
|
const ringSize = getRingSize(width);
|
||||||
|
const iconSize = getIconSize(width);
|
||||||
|
const gridCols = getGridCols(width);
|
||||||
|
|
||||||
|
const visibleStatKeys = Object.entries(statVisibilityByOption)
|
||||||
|
.filter(([optionKey]) => options[optionKey as keyof typeof options])
|
||||||
|
.map(([, statKey]) => statKey);
|
||||||
|
|
||||||
|
const showHero = options.showAverageUptime;
|
||||||
|
const hasContent = showHero || visibleStatKeys.length > 0;
|
||||||
|
|
||||||
|
const heroLayoutClass =
|
||||||
|
heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats];
|
||||||
|
const heroRingClass = heroVariantByRing[String(options.showUptimeRing) as keyof typeof heroVariantByRing];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={classes.root}>
|
||||||
|
{showHero && (
|
||||||
|
<div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}>
|
||||||
|
<div className={classes.heroText}>
|
||||||
|
<span className={classes.heroLabel}>{t("averageUptime")}</span>
|
||||||
|
<span className={classes.heroValue}>{formatNumber(uptimeValue, 1)}%</span>
|
||||||
|
</div>
|
||||||
|
{options.showUptimeRing && (
|
||||||
|
<RingProgress
|
||||||
|
className={classes.ring}
|
||||||
|
size={ringSize}
|
||||||
|
thickness={Math.max(4, Math.round(ringSize / 10))}
|
||||||
|
roundCaps
|
||||||
|
sections={[{ value: uptimeValue, color: uptimeColor }]}
|
||||||
|
label={
|
||||||
|
<Text ta="center" size="xs" fw={700}>
|
||||||
|
{formatNumber(uptimeValue, 0)}%
|
||||||
|
</Text>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{!hasContent && (
|
||||||
|
<div className={classes.emptyState}>
|
||||||
|
<Text size="sm" c="dimmed">
|
||||||
|
—
|
||||||
|
</Text>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{visibleStatKeys.length > 0 && (
|
||||||
|
<div className={classes.statGrid} style={{ "--stat-cols": gridCols } as CSSProperties}>
|
||||||
|
{visibleStatKeys.map((statKey) => {
|
||||||
|
const Icon = statIcons[statKey];
|
||||||
|
const color = statColorByKey[statKey];
|
||||||
|
return (
|
||||||
|
<div key={statKey} className={classes.statTile}>
|
||||||
|
<Icon
|
||||||
|
className={classes.statIcon}
|
||||||
|
size={iconSize}
|
||||||
|
stroke={1.5}
|
||||||
|
color={`var(--mantine-color-${color}-6)`}
|
||||||
|
/>
|
||||||
|
<span className={classes.statValue}>{formatNumber(combined[statKey], 0)}</span>
|
||||||
|
<span className={classes.statLabel}>{t(`stats.${statKey}`)}</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampPercent(value: number): number {
|
||||||
|
return Math.min(100, Math.max(0, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUptimeTier(uptime: number): keyof typeof uptimeColorByTier {
|
||||||
|
const match = uptimeTierByThreshold.find(([min]) => uptime >= min);
|
||||||
|
const tier = match?.[1] ?? "poor";
|
||||||
|
return tier;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUptimeColor(uptime: number): string {
|
||||||
|
return uptimeColorByTier[getUptimeTier(uptime)];
|
||||||
|
}
|
||||||
|
|
||||||
|
function getGridCols(width: number): number {
|
||||||
|
const match = gridColsByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.cols ?? 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getRingSize(width: number): number {
|
||||||
|
const match = ringSizeByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.size ?? 44;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getIconSize(width: number): number {
|
||||||
|
const match = iconSizeByWidth.find(({ minWidth }) => width >= minWidth);
|
||||||
|
return match?.size ?? 16;
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { IconHeartbeat, IconServerOff } from "@tabler/icons-react";
|
||||||
|
|
||||||
|
import { createWidgetDefinition } from "../definition";
|
||||||
|
import { optionsBuilder } from "../options";
|
||||||
|
|
||||||
|
export const { definition, componentLoader } = createWidgetDefinition("uptimeKuma", {
|
||||||
|
icon: IconHeartbeat,
|
||||||
|
createOptions() {
|
||||||
|
return optionsBuilder.from((factory) => ({
|
||||||
|
showAverageUptime: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showUptimeRing: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showTotalMonitors: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showUpCount: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showDownCount: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
showPausedCount: factory.switch({
|
||||||
|
defaultValue: true,
|
||||||
|
withDescription: true,
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
supportedIntegrations: ["uptimeKuma"],
|
||||||
|
errors: {
|
||||||
|
INTERNAL_SERVER_ERROR: {
|
||||||
|
icon: IconServerOff,
|
||||||
|
message: (t) => t("widget.uptimeKuma.error.internalServerError"),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}).withDynamicImport(() => import("./component"));
|
||||||
@@ -51,11 +51,14 @@ export const WidgetIntegrationSelect = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const handleValueSelect = (selectedValue: string) => {
|
const handleValueSelect = (selectedValue: string) => {
|
||||||
onChange(
|
if (multiSelectValues.includes(selectedValue)) {
|
||||||
multiSelectValues.includes(selectedValue)
|
onChange(multiSelectValues.filter((value) => value !== selectedValue));
|
||||||
? multiSelectValues.filter((value) => value !== selectedValue)
|
} else if (canSelectMultiple) {
|
||||||
: [...multiSelectValues, selectedValue],
|
onChange([...multiSelectValues, selectedValue]);
|
||||||
);
|
} else {
|
||||||
|
onChange([selectedValue]);
|
||||||
|
}
|
||||||
|
|
||||||
if (!canSelectMultiple) {
|
if (!canSelectMultiple) {
|
||||||
combobox.closeDropdown();
|
combobox.closeDropdown();
|
||||||
}
|
}
|
||||||
|
|||||||
Generated
+535
-561
File diff suppressed because it is too large.
Load diff
+32
-32
@@ -21,17 +21,17 @@ catalog:
|
|||||||
"@immich/sdk": ^2.7.5
|
"@immich/sdk": ^2.7.5
|
||||||
"@jellyfin/sdk": ^0.13.0
|
"@jellyfin/sdk": ^0.13.0
|
||||||
"@kubernetes/client-node": ^1.4.0
|
"@kubernetes/client-node": ^1.4.0
|
||||||
"@mantine/charts": ^9.3.0
|
"@mantine/charts": ^9.2.2
|
||||||
"@mantine/colors-generator": ^9.3.0
|
"@mantine/colors-generator": ^9.2.2
|
||||||
"@mantine/core": ^9.3.0
|
"@mantine/core": ^9.2.2
|
||||||
"@mantine/dates": ^9.3.0
|
"@mantine/dates": ^9.2.2
|
||||||
"@mantine/dropzone": ^9.3.0
|
"@mantine/dropzone": ^9.2.2
|
||||||
"@mantine/form": ^9.3.0
|
"@mantine/form": ^9.2.2
|
||||||
"@mantine/hooks": ^9.3.0
|
"@mantine/hooks": ^9.2.2
|
||||||
"@mantine/modals": ^9.3.0
|
"@mantine/modals": ^9.2.2
|
||||||
"@mantine/notifications": ^9.3.0
|
"@mantine/notifications": ^9.2.2
|
||||||
"@mantine/spotlight": ^9.3.0
|
"@mantine/spotlight": ^9.2.2
|
||||||
"@mantine/tiptap": ^9.3.0
|
"@mantine/tiptap": ^9.2.2
|
||||||
"@next/eslint-plugin-next": 16.2.7
|
"@next/eslint-plugin-next": 16.2.7
|
||||||
"@octokit/auth-app": ^8.2.0
|
"@octokit/auth-app": ^8.2.0
|
||||||
"@paralleldrive/cuid2": ^3.3.0
|
"@paralleldrive/cuid2": ^3.3.0
|
||||||
@@ -44,28 +44,28 @@ catalog:
|
|||||||
"@semantic-release/release-notes-generator": ^14.1.1
|
"@semantic-release/release-notes-generator": ^14.1.1
|
||||||
"@t3-oss/env-nextjs": ^0.13.11
|
"@t3-oss/env-nextjs": ^0.13.11
|
||||||
"@tabler/icons-react": ^3.44.0
|
"@tabler/icons-react": ^3.44.0
|
||||||
"@tanstack/react-query": ^5.101.0
|
"@tanstack/react-query": ^5.100.14
|
||||||
"@tanstack/react-query-devtools": ^5.101.0
|
"@tanstack/react-query-devtools": ^5.100.14
|
||||||
"@tanstack/react-query-next-experimental": ^5.101.0
|
"@tanstack/react-query-next-experimental": ^5.100.14
|
||||||
"@testcontainers/mysql": ^12.0.1
|
"@testcontainers/mysql": ^12.0.1
|
||||||
"@testcontainers/postgresql": ^12.0.1
|
"@testcontainers/postgresql": ^12.0.1
|
||||||
"@testcontainers/redis": ^12.0.1
|
"@testcontainers/redis": ^12.0.1
|
||||||
"@tiptap/extension-color": 3.25.0
|
"@tiptap/extension-color": 3.24.0
|
||||||
"@tiptap/extension-highlight": 3.25.0
|
"@tiptap/extension-highlight": 3.24.0
|
||||||
"@tiptap/extension-image": 3.25.0
|
"@tiptap/extension-image": 3.24.0
|
||||||
"@tiptap/extension-link": ^3.25.0
|
"@tiptap/extension-link": ^3.24.0
|
||||||
"@tiptap/extension-placeholder": ^3.25.0
|
"@tiptap/extension-placeholder": ^3.24.0
|
||||||
"@tiptap/extension-table": 3.25.0
|
"@tiptap/extension-table": 3.24.0
|
||||||
"@tiptap/extension-table-cell": 3.25.0
|
"@tiptap/extension-table-cell": 3.24.0
|
||||||
"@tiptap/extension-table-header": 3.25.0
|
"@tiptap/extension-table-header": 3.24.0
|
||||||
"@tiptap/extension-table-row": 3.25.0
|
"@tiptap/extension-table-row": 3.24.0
|
||||||
"@tiptap/extension-task-item": 3.25.0
|
"@tiptap/extension-task-item": 3.24.0
|
||||||
"@tiptap/extension-task-list": 3.25.0
|
"@tiptap/extension-task-list": 3.24.0
|
||||||
"@tiptap/extension-text-align": 3.25.0
|
"@tiptap/extension-text-align": 3.24.0
|
||||||
"@tiptap/extension-text-style": 3.25.0
|
"@tiptap/extension-text-style": 3.24.0
|
||||||
"@tiptap/extension-underline": 3.25.0
|
"@tiptap/extension-underline": 3.24.0
|
||||||
"@tiptap/react": ^3.25.0
|
"@tiptap/react": ^3.24.0
|
||||||
"@tiptap/starter-kit": ^3.25.0
|
"@tiptap/starter-kit": ^3.24.0
|
||||||
"@trpc/client": ^11.17.0
|
"@trpc/client": ^11.17.0
|
||||||
"@trpc/next": ^11.17.0
|
"@trpc/next": ^11.17.0
|
||||||
"@trpc/react-query": ^11.17.0
|
"@trpc/react-query": ^11.17.0
|
||||||
@@ -126,7 +126,7 @@ catalog:
|
|||||||
glob: ^13.0.6
|
glob: ^13.0.6
|
||||||
ical.js: ^2.2.1
|
ical.js: ^2.2.1
|
||||||
ioredis: 5.11.0
|
ioredis: 5.11.0
|
||||||
isomorphic-dompurify: ^3.16.0
|
isomorphic-dompurify: ^3.15.0
|
||||||
jotai: ^2.20.0
|
jotai: ^2.20.0
|
||||||
jsdom: ^29.1.1
|
jsdom: ^29.1.1
|
||||||
json5: ^2.2.3
|
json5: ^2.2.3
|
||||||
@@ -155,7 +155,7 @@ catalog:
|
|||||||
recharts: ^3.8.1
|
recharts: ^3.8.1
|
||||||
sass: ^1.100.0
|
sass: ^1.100.0
|
||||||
semantic-release: ^25.0.3
|
semantic-release: ^25.0.3
|
||||||
semver-parser: ^4.2.1
|
semver-parser: ^4.2.0
|
||||||
superjson: 2.2.6
|
superjson: 2.2.6
|
||||||
svgson: ^5.3.1
|
svgson: ^5.3.1
|
||||||
swagger-ui-react: ^5.32.6
|
swagger-ui-react: ^5.32.6
|
||||||
|
|||||||
Reference in new issue
Block a user